text
stringlengths 54
60.6k
|
---|
<commit_before>/*
* Copyright (c) 2011, The University of Oxford
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* 1. Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
* 3. Neither the name of the University of Oxford nor the names of its
* contributors may be used to endorse or promote products derived from this
* software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*/
#include "apps/lib/oskar_settings_load_image.h"
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <QtCore/QSettings>
#include <QtCore/QByteArray>
#include <QtCore/QVariant>
#include <QtCore/QFile>
extern "C"
int oskar_settings_load_image(oskar_SettingsImage* im,
const char* filename)
{
QString temp;
QByteArray t;
QSettings s(QString(filename), QSettings::IniFormat);
s.beginGroup("image");
im->fov_deg = s.value("fov_deg", 2).toDouble();
im->size = s.value("size", 256).toInt();
im->channel_snapshots = s.value("channel_snapshots", true).toBool();
im->channel_range[0] = s.value("channel_start", 0).toInt();
temp = s.value("channel_end", "max").toString();
if (temp.compare("max", Qt::CaseInsensitive) == 0)
im->channel_range[1] = -1;
else
im->channel_range[1] = temp.toInt();
im->time_snapshots = s.value("time_snapshots", true).toBool();
im->time_range[0] = s.value("time_start", 0).toInt();
temp = s.value("time_end", "max").toString();
if (temp.compare("max", Qt::CaseInsensitive) == 0)
im->time_range[1] = -1;
else
im->time_range[1] = temp.toInt();
temp = s.value("image_type", "I").toString().toUpper();
QString type(temp);
if (temp.startsWith("STOKES"))
{
im->image_type = OSKAR_IMAGE_TYPE_STOKES;
type = "STOKES";
}
else if (temp == "I")
im->image_type = OSKAR_IMAGE_TYPE_STOKES_I;
else if (temp == "Q")
im->image_type = OSKAR_IMAGE_TYPE_STOKES_Q;
else if (temp == "U")
im->image_type = OSKAR_IMAGE_TYPE_STOKES_U;
else if (temp == "V")
im->image_type = OSKAR_IMAGE_TYPE_STOKES_V;
else if (temp.startsWith("LINEAR"))
{
im->image_type = OSKAR_IMAGE_TYPE_POL_LINEAR;
type = "LINEAR";
}
else if (temp == "XX")
im->image_type = OSKAR_IMAGE_TYPE_POL_XX;
else if (temp == "XY")
im->image_type = OSKAR_IMAGE_TYPE_POL_XY;
else if (temp == "YX")
im->image_type = OSKAR_IMAGE_TYPE_POL_YX;
else if (temp == "YY")
im->image_type = OSKAR_IMAGE_TYPE_POL_YY;
else if (temp == "PSF")
im->image_type = OSKAR_IMAGE_TYPE_PSF;
else
return OSKAR_ERR_SETTINGS_IMAGE;
temp = s.value("transform_type", "DFT 2D").toString().toUpper();
if (temp == "DFT 2D")
im->transform_type = OSKAR_IMAGE_DFT_2D;
else if (temp == "DFT 3D")
im->transform_type = OSKAR_IMAGE_DFT_3D;
else if (temp == "FFT")
im->transform_type = OSKAR_IMAGE_FFT;
else
return OSKAR_ERR_SETTINGS_IMAGE;
temp = s.value("direction", "Observation pointing direction").toString();
if (temp.startsWith("O", Qt::CaseInsensitive))
im->direction_type = OSKAR_IMAGE_DIRECTION_OBSERVATION;
else if (temp.startsWith("R", Qt::CaseInsensitive))
im->direction_type = OSKAR_IMAGE_DIRECTION_RA_DEC;
else
return OSKAR_ERR_SETTINGS_IMAGE;
im->ra_deg = s.value("direction/ra_deg", 0.0).toDouble();
im->dec_deg = s.value("direction/dec_deg", 0.0).toDouble();
t = s.value("input_vis_data").toByteArray();
if (t.size() > 0)
{
im->input_vis_data = (char*)malloc(t.size() + 1);
strcpy(im->input_vis_data, t.constData());
}
bool overwrite = s.value("overwrite", true).toBool();
t = s.value("root").toByteArray();
if (t.size() > 0)
{
t += "_" + type;
// Construct FITS filename
if (s.value("fits_image", true).toBool())
{
if (!overwrite)
{
if (QFile::exists(QString(t) + ".fits"))
{
int i = 1;
while (true)
{
QString test = QString(t) + "-" + QString::number(i);
test += ".fits";
if (!QFile::exists(QString(test)))
{
t = test.toAscii();
break;
}
++i;
}
}
}
else
{
t += ".fits";
}
im->fits_image = (char*)malloc(t.size() + 1);
strcpy(im->fits_image, t.constData());
}
// Construct OSKAR filename
if (s.value("oskar_image", false).toBool())
{
if (!overwrite)
{
if (QFile::exists(QString(t) + ".img"))
{
int i = 1;
while (true)
{
QString test = QString(t) + "-" + QString::number(i);
test += ".fits";
if (!QFile::exists(QString(test)))
{
t = test.toAscii();
break;
}
++i;
}
}
}
else
{
t += ".img";
}
im->oskar_image = (char*)malloc(t.size() + 1);
strcpy(im->oskar_image, t.constData());
}
}
#if 0
t = s.value("oskar_image_root").toByteArray();
if (t.size() > 0)
{
// Construct filename from root.
t += "_" + type + ".img";
im->oskar_image = (char*)malloc(t.size() + 1);
strcpy(im->oskar_image, t.constData());
}
t = s.value("fits_image_root").toByteArray();
if (t.size() > 0)
{
t += "_" + type + ".fits";
im->fits_image = (char*)malloc(t.size() + 1);
strcpy(im->fits_image, t.constData());
}
#endif
return OSKAR_SUCCESS;
}
<commit_msg>fixed bug in output image name creation<commit_after>/*
* Copyright (c) 2011, The University of Oxford
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* 1. Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
* 3. Neither the name of the University of Oxford nor the names of its
* contributors may be used to endorse or promote products derived from this
* software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*/
#include "apps/lib/oskar_settings_load_image.h"
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <QtCore/QSettings>
#include <QtCore/QByteArray>
#include <QtCore/QVariant>
#include <QtCore/QFile>
extern "C"
int oskar_settings_load_image(oskar_SettingsImage* im,
const char* filename)
{
QString temp;
QByteArray t;
QSettings s(QString(filename), QSettings::IniFormat);
s.beginGroup("image");
im->fov_deg = s.value("fov_deg", 2).toDouble();
im->size = s.value("size", 256).toInt();
im->channel_snapshots = s.value("channel_snapshots", true).toBool();
im->channel_range[0] = s.value("channel_start", 0).toInt();
temp = s.value("channel_end", "max").toString();
if (temp.compare("max", Qt::CaseInsensitive) == 0)
im->channel_range[1] = -1;
else
im->channel_range[1] = temp.toInt();
im->time_snapshots = s.value("time_snapshots", true).toBool();
im->time_range[0] = s.value("time_start", 0).toInt();
temp = s.value("time_end", "max").toString();
if (temp.compare("max", Qt::CaseInsensitive) == 0)
im->time_range[1] = -1;
else
im->time_range[1] = temp.toInt();
temp = s.value("image_type", "I").toString().toUpper();
QString type(temp);
if (temp.startsWith("STOKES"))
{
im->image_type = OSKAR_IMAGE_TYPE_STOKES;
type = "STOKES";
}
else if (temp == "I")
im->image_type = OSKAR_IMAGE_TYPE_STOKES_I;
else if (temp == "Q")
im->image_type = OSKAR_IMAGE_TYPE_STOKES_Q;
else if (temp == "U")
im->image_type = OSKAR_IMAGE_TYPE_STOKES_U;
else if (temp == "V")
im->image_type = OSKAR_IMAGE_TYPE_STOKES_V;
else if (temp.startsWith("LINEAR"))
{
im->image_type = OSKAR_IMAGE_TYPE_POL_LINEAR;
type = "LINEAR";
}
else if (temp == "XX")
im->image_type = OSKAR_IMAGE_TYPE_POL_XX;
else if (temp == "XY")
im->image_type = OSKAR_IMAGE_TYPE_POL_XY;
else if (temp == "YX")
im->image_type = OSKAR_IMAGE_TYPE_POL_YX;
else if (temp == "YY")
im->image_type = OSKAR_IMAGE_TYPE_POL_YY;
else if (temp == "PSF")
im->image_type = OSKAR_IMAGE_TYPE_PSF;
else
return OSKAR_ERR_SETTINGS_IMAGE;
temp = s.value("transform_type", "DFT 2D").toString().toUpper();
if (temp == "DFT 2D")
im->transform_type = OSKAR_IMAGE_DFT_2D;
else if (temp == "DFT 3D")
im->transform_type = OSKAR_IMAGE_DFT_3D;
else if (temp == "FFT")
im->transform_type = OSKAR_IMAGE_FFT;
else
return OSKAR_ERR_SETTINGS_IMAGE;
temp = s.value("direction", "Observation pointing direction").toString();
if (temp.startsWith("O", Qt::CaseInsensitive))
im->direction_type = OSKAR_IMAGE_DIRECTION_OBSERVATION;
else if (temp.startsWith("R", Qt::CaseInsensitive))
im->direction_type = OSKAR_IMAGE_DIRECTION_RA_DEC;
else
return OSKAR_ERR_SETTINGS_IMAGE;
im->ra_deg = s.value("direction/ra_deg", 0.0).toDouble();
im->dec_deg = s.value("direction/dec_deg", 0.0).toDouble();
t = s.value("input_vis_data").toByteArray();
if (t.size() > 0)
{
im->input_vis_data = (char*)malloc(t.size() + 1);
strcpy(im->input_vis_data, t.constData());
}
bool overwrite = s.value("overwrite", true).toBool();
t = s.value("root").toByteArray();
if (t.size() > 0)
{
t += "_" + type;
// Construct FITS filename
if (s.value("fits_image", true).toBool())
{
if (!overwrite && QFile::exists(QString(t) + ".fits"))
{
int i = 1;
while (true)
{
QString test = QString(t) + "-" + QString::number(i);
test += ".fits";
if (!QFile::exists(QString(test)))
{
t = test.toAscii();
break;
}
++i;
}
}
else
{
t += ".fits";
}
im->fits_image = (char*)malloc(t.size() + 1);
strcpy(im->fits_image, t.constData());
}
// Construct OSKAR filename
if (s.value("oskar_image", false).toBool())
{
if (!overwrite && QFile::exists(QString(t) + ".img"))
{
int i = 1;
while (true)
{
QString test = QString(t) + "-" + QString::number(i);
test += ".fits";
if (!QFile::exists(QString(test)))
{
t = test.toAscii();
break;
}
++i;
}
}
else
{
t += ".img";
}
im->oskar_image = (char*)malloc(t.size() + 1);
strcpy(im->oskar_image, t.constData());
}
}
#if 0
t = s.value("oskar_image_root").toByteArray();
if (t.size() > 0)
{
// Construct filename from root.
t += "_" + type + ".img";
im->oskar_image = (char*)malloc(t.size() + 1);
strcpy(im->oskar_image, t.constData());
}
t = s.value("fits_image_root").toByteArray();
if (t.size() > 0)
{
t += "_" + type + ".fits";
im->fits_image = (char*)malloc(t.size() + 1);
strcpy(im->fits_image, t.constData());
}
#endif
return OSKAR_SUCCESS;
}
<|endoftext|> |
<commit_before>#include "ShotSegmentation.hpp"
ShotSegmentation::ShotSegmentation(vector<Mat> histograms) {
this->histograms = histograms;
}
void ShotSegmentation::setGradualThreshold(int value) {
this->gradualHeuristicThreshold = value;
}
void ShotSegmentation::setSlidingWindowsIntersect(float value) {
this->swIntersectThreshold = value;
}
void ShotSegmentation::setSlidingWindowsEuclidean(float value) {
this->swEuclideanThreshold = value;
}
void ShotSegmentation::setLocalSlidingWindowIntersect(float value) {
this->localSlidingWindowIntersectThreshold = value;
}
void ShotSegmentation::setLocalSlidingWindowEuclidean(float value) {
this->localSlidingWindowEuclideanThreshold = value;
}
double ShotSegmentation::histogramEuclideanDistance(Mat histogram1, Mat histogram2) {
double distance = 0.0;
for(int h = 0; h < 8; h++) {
for(int s = 0; s < 4; s++) {
for(int v = 0; v < 4; v++) {
float val1 = histogram1.at<float>(h,s,v);
float val2 = histogram2.at<float>(h,s,v);
distance = distance + sqrt(pow(val1-val2,2.0));
}
}
}
return distance;
}
double ShotSegmentation::histogramIntersectionDistance(Mat histogram1, Mat histogram2) {
return compareHist(histogram1, histogram2, CV_COMP_INTERSECT);
}
double ShotSegmentation::calcThresholdIntersection(vector<double> distances, pair<int,int> window) {
double avg = 0.0;
for(int i = window.first; i < window.second; i++) {
avg = avg + distances[i];
}
avg = avg / (double) (window.second - window.first);
return avg * this->localSlidingWindowIntersectThreshold;
}
double ShotSegmentation::calcThresholdEuclidean(vector<double> distances, pair<int,int> window) {
double avg = 0.0;
for(int i = window.first; i < window.second; i++) {
avg = avg + distances[i];
}
avg = avg / (double) (window.second - window.first);
return avg * this->localSlidingWindowEuclideanThreshold;
}
bool ShotSegmentation::heuristicIntersec(vector<double> distances, int pos, double threshold) {
for(int i = pos; i < pos+this->gradualHeuristicThreshold && i < distances.size(); i++) {
if(distances[i] < threshold) {
return true;
}
}
return false;
}
bool ShotSegmentation::heuristicEuclidean(vector<double> distances, int pos, double threshold) {
for(int i = pos; i < pos+this->gradualHeuristicThreshold && i < distances.size(); i++) {
if(distances[i] > threshold) {
return true;
}
}
return false;
}
vector< pair<int,int> > ShotSegmentation::segmentSlidingWindows(vector<double> distEuclidean, vector<double> distIntersec, double thresholdIntersec, double thresholdEuclidean, pair<int,int> window) {
int i, j, ant;
vector< pair<int,int> > shots;
for(ant = window.first, i = window.first, j = 0; i < window.second; i++) {
if(distIntersec[i] <= thresholdIntersec || distEuclidean[i] >= thresholdEuclidean) {
j++;
} else {
if (j > 0) {
if(heuristicIntersec(distIntersec, i, thresholdIntersec) || heuristicEuclidean(distEuclidean, i, thresholdEuclidean)) {
j++;
} else {
if (j >= 1) {
shots.push_back(make_pair(ant,i - j));
ant = i - j + 1;
}
j = 0;
}
}
}
}
shots.push_back(make_pair(ant,window.second));
return shots;
}
vector< pair<int,int> > ShotSegmentation::segment() {
vector<double> distEuclidean, distIntersec, thresholdIntersec, thresholdEuclidean;
vector<double>::iterator maxVal, minVal;
int previousPos = 0;
vector<pair<int,int> > slidingWindow;
pair<int,int> window;
/* Calculate the distances between consecutive histograms*/
for(int i = 1; i < this->histograms.size(); i++) {
distEuclidean.push_back(this->histogramEuclideanDistance(this->histograms[i-1],this->histograms[i]));
distIntersec.push_back(this->histogramIntersectionDistance(this->histograms[i-1],this->histograms[i]));
}
/* Find the max and min distances among the histograms */
maxVal = max_element(distEuclidean.begin(), distEuclidean.end());
minVal = min_element(distIntersec.begin(), distIntersec.end());
/* Generate the sliding windows and its threholds */
int i;
for(i = 0; i < distIntersec.size(); i++) {
if(distIntersec[i] <= this->swIntersectThreshold || (distIntersec[i] <= (*minVal * 1.5) && distIntersec[i] <= 0.4) ||
(distEuclidean[i] >= (*maxVal * 0.85) && distEuclidean[i] >= 0.9) || distEuclidean[i] >= this->swEuclideanThreshold ) {
window = make_pair(previousPos,i);
thresholdIntersec.push_back(this->calcThresholdIntersection(distIntersec, window));
thresholdEuclidean.push_back(this->calcThresholdEuclidean(distEuclidean, window));
slidingWindow.push_back(window);
previousPos = i+1;
}
}
if(previousPos < distIntersec.size() && i <= distIntersec.size() && slidingWindow.size() > 0) {
window = make_pair(previousPos,i);
thresholdIntersec.push_back(this->calcThresholdIntersection(distIntersec, window));
thresholdEuclidean.push_back(this->calcThresholdEuclidean(distEuclidean, window));
slidingWindow.push_back(window);
} else if (slidingWindow.size() == 0) {
window = make_pair(0,distIntersec.size()-1);
thresholdIntersec.push_back(this->calcThresholdIntersection(distIntersec, window));
thresholdEuclidean.push_back(this->calcThresholdEuclidean(distEuclidean, window));
slidingWindow.push_back(window);
}
/* Do the shot segmentation for each sliding window */
vector< pair<int,int> > shots;
for(int i = 0; i < slidingWindow.size(); i++) {
vector< pair<int,int> > temp = this->segmentSlidingWindows(distEuclidean, distIntersec, thresholdIntersec[i], thresholdEuclidean[i], slidingWindow[i]);
shots.insert(shots.end(), temp.begin(), temp.end());
}
/* Remove all shots with a duration of 1 frame or less */
for(int i = 0; i < shots.size(); i++) {
if(shots[i].second - shots[i].first <= 1) {
shots.erase(shots.begin() + i);
i--;
}
}
/* Increase all values by 1. The first frame should begin with 1 :) */
for(int i = 0; i < shots.size(); i++) {
shots[i] = make_pair(shots[i].first+1, shots[i].second+1);
}
return shots;
}<commit_msg>Fixes #2. Also fixed intersection and euclidean distances heuristic thresholds which were not being properly used<commit_after>#include "ShotSegmentation.hpp"
ShotSegmentation::ShotSegmentation(vector<Mat> histograms) {
this->histograms = histograms;
}
void ShotSegmentation::setGradualThreshold(int value) {
this->gradualHeuristicThreshold = value;
}
void ShotSegmentation::setSlidingWindowsIntersect(float value) {
this->swIntersectThreshold = value;
}
void ShotSegmentation::setSlidingWindowsEuclidean(float value) {
this->swEuclideanThreshold = value;
}
void ShotSegmentation::setLocalSlidingWindowIntersect(float value) {
this->localSlidingWindowIntersectThreshold = value;
}
void ShotSegmentation::setLocalSlidingWindowEuclidean(float value) {
this->localSlidingWindowEuclideanThreshold = value;
}
double ShotSegmentation::histogramEuclideanDistance(Mat histogram1, Mat histogram2) {
double distance = 0.0;
for(int h = 0; h < 8; h++) {
for(int s = 0; s < 4; s++) {
for(int v = 0; v < 4; v++) {
float val1 = histogram1.at<float>(h,s,v);
float val2 = histogram2.at<float>(h,s,v);
distance = distance + sqrt(pow(val1-val2,2.0));
}
}
}
return distance;
}
double ShotSegmentation::histogramIntersectionDistance(Mat histogram1, Mat histogram2) {
return compareHist(histogram1, histogram2, CV_COMP_INTERSECT);
}
double ShotSegmentation::calcThresholdIntersection(vector<double> distances, pair<int,int> window) {
double avg = 0.0;
for(int i = window.first; i < window.second; i++) {
avg = avg + distances[i];
}
avg = avg / (double) (window.second - window.first);
return avg * this->swIntersectThreshold;
}
double ShotSegmentation::calcThresholdEuclidean(vector<double> distances, pair<int,int> window) {
double avg = 0.0;
for(int i = window.first; i < window.second; i++) {
avg = avg + distances[i];
}
avg = avg / (double) (window.second - window.first);
return avg * this->swEuclideanThreshold;
}
bool ShotSegmentation::heuristicIntersec(vector<double> distances, int pos, double threshold) {
for(int i = pos; i <= pos+this->gradualHeuristicThreshold && i < distances.size(); i++) {
if(distances[i] < threshold) {
return true;
}
}
return false;
}
bool ShotSegmentation::heuristicEuclidean(vector<double> distances, int pos, double threshold) {
for(int i = pos; i <= pos+this->gradualHeuristicThreshold && i < distances.size(); i++) {
if(distances[i] > threshold) {
return true;
}
}
return false;
}
vector< pair<int,int> > ShotSegmentation::segmentSlidingWindows(vector<double> distEuclidean, vector<double> distIntersec, double thresholdIntersec, double thresholdEuclidean, pair<int,int> window) {
int actual, gradual, ant;
vector< pair<int,int> > shots;
for(ant = window.first, actual = window.first, gradual = 0; actual < window.second; actual++) {
/* The frame is a transition */
if(distIntersec[actual] <= thresholdIntersec || distEuclidean[actual] >= thresholdEuclidean) {
gradual++;
} else {
/* The frame is not a transition, but there was a transition before it */
if (gradual > 0) {
/* There is a very close frame transition after it*/
if(heuristicIntersec(distIntersec, actual, thresholdIntersec) || heuristicEuclidean(distEuclidean, actual, thresholdEuclidean)) {
gradual++;
} else {
shots.push_back(make_pair(ant, actual - gradual));
/* As this frame is not a transition, it is the begining of a new shot. So reset the relevant values */
ant = actual;
gradual = 0;
}
}
}
}
/* The very last shot of the local is also a shot so add it. But only if its not a part of a gradual transition... */
if(shots.size() > 0 && shots[shots.size()-1].second != window.second && gradual == 0) {
shots.push_back(make_pair(shots[shots.size()-1].second+1,window.second));
}
return shots;
}
vector< pair<int,int> > ShotSegmentation::segment() {
vector<double> distEuclidean, distIntersec, thresholdIntersec, thresholdEuclidean;
vector<double>::iterator maxVal, minVal;
int previousPos = 0;
vector<pair<int,int> > slidingWindow;
pair<int,int> window;
/* Calculate the distances between consecutive histograms*/
for(int i = 1; i < this->histograms.size(); i++) {
distEuclidean.push_back(this->histogramEuclideanDistance(this->histograms[i-1],this->histograms[i]));
distIntersec.push_back(this->histogramIntersectionDistance(this->histograms[i-1],this->histograms[i]));
}
/* Find the max and min distances among the histograms */
maxVal = max_element(distEuclidean.begin(), distEuclidean.end());
minVal = min_element(distIntersec.begin(), distIntersec.end());
/* Generate the sliding windows and its threholds */
int i;
for(i = 0; i < distIntersec.size(); i++) {
if(distIntersec[i] <= this->swIntersectThreshold || (distIntersec[i] <= (*minVal * 1.5) && distIntersec[i] <= 0.4) ||
(distEuclidean[i] >= (*maxVal * 0.85) && distEuclidean[i] >= 0.9) || distEuclidean[i] >= this->swEuclideanThreshold ) {
window = make_pair(previousPos,i);
thresholdIntersec.push_back(this->calcThresholdIntersection(distIntersec, window));
thresholdEuclidean.push_back(this->calcThresholdEuclidean(distEuclidean, window));
slidingWindow.push_back(window);
previousPos = i+1;
}
}
if(previousPos < distIntersec.size() && i <= distIntersec.size() && slidingWindow.size() > 0) {
window = make_pair(previousPos,i);
thresholdIntersec.push_back(this->calcThresholdIntersection(distIntersec, window));
thresholdEuclidean.push_back(this->calcThresholdEuclidean(distEuclidean, window));
slidingWindow.push_back(window);
} else if (slidingWindow.size() == 0) {
window = make_pair(0,distIntersec.size()-1);
thresholdIntersec.push_back(this->calcThresholdIntersection(distIntersec, window));
thresholdEuclidean.push_back(this->calcThresholdEuclidean(distEuclidean, window));
slidingWindow.push_back(window);
}
/* Do the shot segmentation for each sliding window */
vector< pair<int,int> > shots;
for(int i = 0; i < slidingWindow.size(); i++) {
vector< pair<int,int> > temp = this->segmentSlidingWindows(distEuclidean, distIntersec, thresholdIntersec[i], thresholdEuclidean[i], slidingWindow[i]);
shots.insert(shots.end(), temp.begin(), temp.end());
}
/* Remove all shots with a duration of 1 frame or less */
for(int i = 0; i < shots.size(); i++) {
if(shots[i].second - shots[i].first <= 1) {
shots.erase(shots.begin() + i);
i--;
}
}
/* Increase all values by 1. The first frame should begin with 1 :) */
for(int i = 0; i < shots.size(); i++) {
shots[i] = make_pair(shots[i].first+1, shots[i].second+1);
}
return shots;
}<|endoftext|> |
<commit_before>//2D implementation of the Ramer-Douglas-Peucker algorithm
//https://en.wikipedia.org/wiki/Ramer%E2%80%93Douglas%E2%80%93Peucker_algorithm
#include <iostream>
#include <cmath>
#include <utility>
#include <vector>
#include <stdexcept>
#include "RdpSimplify.h"
using namespace std;
double PerpendicularDistance(const Point &pt, const Point &lineStart, const Point &lineEnd)
{
double dx = lineEnd.first - lineStart.first;
double dy = lineEnd.second - lineStart.second;
//Normalise
double mag = pow(pow(dx,2.0)+pow(dy,2.0),0.5);
if(mag > 0.0)
{
dx /= mag; dy /= mag;
}
double pvx = pt.first - lineStart.first;
double pvy = pt.second - lineStart.second;
//Get dot product (project pv onto normalized direction)
double pvdot = dx * pvx + dy * pvy;
//Scale line direction vector
double dsx = pvdot * dx;
double dsy = pvdot * dy;
//Subtract this from pv
double ax = pvx - dsx;
double ay = pvy - dsy;
return pow(pow(ax,2.0)+pow(ay,2.0),0.5);
}
void RamerDouglasPeucker(const Contour &pointList, double epsilon, Contour &out)
{
if(pointList.size()<2)
throw invalid_argument("Not enough points to simplify");
// Find the point with the maximum distance from line between start and end
double dmax = 0.0;
size_t index = 0;
size_t end = pointList.size()-1;
for(size_t i = 1; i < end; i++)
{
double d = PerpendicularDistance(pointList[i], pointList[0], pointList[end]);
if (d > dmax)
{
index = i;
dmax = d;
}
}
// If max distance is greater than epsilon, recursively simplify
if(dmax > epsilon)
{
// Recursive call
vector<Point> recResults1;
vector<Point> recResults2;
vector<Point> firstLine(pointList.begin(), pointList.begin()+index+1);
vector<Point> lastLine(pointList.begin()+index, pointList.end());
RamerDouglasPeucker(firstLine, epsilon, recResults1);
RamerDouglasPeucker(lastLine, epsilon, recResults2);
// Build the result list
out.assign(recResults1.begin(), recResults1.end()-1);
out.insert(out.end(), recResults2.begin(), recResults2.end());
if(out.size()<2)
throw runtime_error("Problem assembling output");
}
else
{
//Just return start and end points
out.clear();
out.push_back(pointList[0]);
out.push_back(pointList[end]);
}
}
int main()
{
vector<Point> pointList;
vector<Point> pointListOut;
pointList.push_back(Point(0.0, 0.0));
pointList.push_back(Point(1.0, 0.1));
pointList.push_back(Point(2.0, -0.1));
pointList.push_back(Point(3.0, 5.0));
pointList.push_back(Point(4.0, 6.0));
pointList.push_back(Point(5.0, 7.0));
pointList.push_back(Point(6.0, 8.1));
pointList.push_back(Point(7.0, 9.0));
pointList.push_back(Point(8.0, 9.0));
pointList.push_back(Point(9.0, 9.0));
RamerDouglasPeucker(pointList, 1.0, pointListOut);
cout << "result" << endl;
for(size_t i=0;i< pointListOut.size();i++)
{
cout << pointListOut[i].first << "," << pointListOut[i].second << endl;
}
return 0;
}
<commit_msg>Remove test code<commit_after>//2D implementation of the Ramer-Douglas-Peucker algorithm
//https://en.wikipedia.org/wiki/Ramer%E2%80%93Douglas%E2%80%93Peucker_algorithm
#include <iostream>
#include <cmath>
#include <utility>
#include <vector>
#include <stdexcept>
#include "RdpSimplify.h"
using namespace std;
double PerpendicularDistance(const Point &pt, const Point &lineStart, const Point &lineEnd)
{
double dx = lineEnd.first - lineStart.first;
double dy = lineEnd.second - lineStart.second;
//Normalise
double mag = pow(pow(dx,2.0)+pow(dy,2.0),0.5);
if(mag > 0.0)
{
dx /= mag; dy /= mag;
}
double pvx = pt.first - lineStart.first;
double pvy = pt.second - lineStart.second;
//Get dot product (project pv onto normalized direction)
double pvdot = dx * pvx + dy * pvy;
//Scale line direction vector
double dsx = pvdot * dx;
double dsy = pvdot * dy;
//Subtract this from pv
double ax = pvx - dsx;
double ay = pvy - dsy;
return pow(pow(ax,2.0)+pow(ay,2.0),0.5);
}
void RamerDouglasPeucker(const Contour &pointList, double epsilon, Contour &out)
{
if(pointList.size()<2)
throw invalid_argument("Not enough points to simplify");
// Find the point with the maximum distance from line between start and end
double dmax = 0.0;
size_t index = 0;
size_t end = pointList.size()-1;
for(size_t i = 1; i < end; i++)
{
double d = PerpendicularDistance(pointList[i], pointList[0], pointList[end]);
if (d > dmax)
{
index = i;
dmax = d;
}
}
// If max distance is greater than epsilon, recursively simplify
if(dmax > epsilon)
{
// Recursive call
vector<Point> recResults1;
vector<Point> recResults2;
vector<Point> firstLine(pointList.begin(), pointList.begin()+index+1);
vector<Point> lastLine(pointList.begin()+index, pointList.end());
RamerDouglasPeucker(firstLine, epsilon, recResults1);
RamerDouglasPeucker(lastLine, epsilon, recResults2);
// Build the result list
out.assign(recResults1.begin(), recResults1.end()-1);
out.insert(out.end(), recResults2.begin(), recResults2.end());
if(out.size()<2)
throw runtime_error("Problem assembling output");
}
else
{
//Just return start and end points
out.clear();
out.push_back(pointList[0]);
out.push_back(pointList[end]);
}
}
<|endoftext|> |
<commit_before>
// Author: Greg "fugue" Santucci, 2011
// Email: [email protected]
// Web: http://createuniverses.blogspot.com/
#include "luaCB.h"
int luaCBLuaCall(lua_State * L)
{
std::string sText = luaL_checkstring(L, 1);
luaCall(sText);
return 0;
}
void cbLuaBreakHook(lua_State *L, lua_Debug *ar);
int luaCBTurnOnDebugHook(lua_State * L)
{
int nLines = 1000;
int n = lua_gettop(L);
if(n == 1)
nLines = luaL_checknumber(L, 1);
lua_sethook(L, cbLuaBreakHook, LUA_MASKCOUNT, nLines);
return 0;
}
int luaCBTurnOffDebugHook(lua_State * L)
{
lua_sethook(L, 0, LUA_MASKCOUNT, 1000);
return 0;
}
int luaCBGetFPS(lua_State * L)
{
extern float g_fFPS;
lua_pushnumber(L, g_fFPS);
return 1;
}
int luaCBGetCurrentDir(lua_State * L)
{
return 0;
}
#ifdef __PRAXIS_LINUX__
#include <unistd.h>
int luaCBSetCurrentDir(lua_State * L)
{
std::string sDir = luaL_checkstring(L, 1);
chdir(sDir.c_str());
return 0;
}
#endif
#ifdef __PRAXIS_WINDOWS__
int luaCBSetCurrentDir(lua_State * L)
{
std::string sDir = luaL_checkstring(L, 1);
::SetCurrentDirectory(sDir.c_str());
return 0;
}
#endif
int luaCBPrintf(lua_State * L)
{
std::string s = luaL_checkstring(L, 1);
printf("%s", s.c_str());
fflush(stdout);
return 0;
}
int luaCBPlatform(lua_State * L)
{
std::string s = "undefined";
#ifdef __PRAXIS_WINDOWS__
s = "windows";
#endif
#ifdef __PRAXIS_LINUX__
s = "linux";
#endif
lua_pushstring(L, s.c_str());
return 1;
}
void luaInitCallbacksSystem()
{
lua_register(g_pLuaState, "luaCall", luaCBLuaCall);
lua_register(g_pLuaState, "turnOnDebugHook", luaCBTurnOnDebugHook);
lua_register(g_pLuaState, "turnOffDebugHook", luaCBTurnOffDebugHook);
lua_register(g_pLuaState, "getFPS", luaCBGetFPS);
lua_register(g_pLuaState, "getCurrentDir", luaCBGetCurrentDir);
lua_register(g_pLuaState, "setCurrentDir", luaCBSetCurrentDir);
lua_register(g_pLuaState, "printf", luaCBPrintf);
lua_register(g_pLuaState, "platform", luaCBPlatform);
}
<commit_msg>getchar added, because why not!<commit_after>
// Author: Greg "fugue" Santucci, 2011
// Email: [email protected]
// Web: http://createuniverses.blogspot.com/
#include "luaCB.h"
int luaCBLuaCall(lua_State * L)
{
std::string sText = luaL_checkstring(L, 1);
luaCall(sText);
return 0;
}
void cbLuaBreakHook(lua_State *L, lua_Debug *ar);
int luaCBTurnOnDebugHook(lua_State * L)
{
int nLines = 1000;
int n = lua_gettop(L);
if(n == 1)
nLines = luaL_checknumber(L, 1);
lua_sethook(L, cbLuaBreakHook, LUA_MASKCOUNT, nLines);
return 0;
}
int luaCBTurnOffDebugHook(lua_State * L)
{
lua_sethook(L, 0, LUA_MASKCOUNT, 1000);
return 0;
}
int luaCBGetFPS(lua_State * L)
{
extern float g_fFPS;
lua_pushnumber(L, g_fFPS);
return 1;
}
int luaCBGetCurrentDir(lua_State * L)
{
return 0;
}
#ifdef __PRAXIS_LINUX__
#include <unistd.h>
int luaCBSetCurrentDir(lua_State * L)
{
std::string sDir = luaL_checkstring(L, 1);
chdir(sDir.c_str());
return 0;
}
#endif
#ifdef __PRAXIS_WINDOWS__
int luaCBSetCurrentDir(lua_State * L)
{
std::string sDir = luaL_checkstring(L, 1);
::SetCurrentDirectory(sDir.c_str());
return 0;
}
#endif
int luaCBPrintf(lua_State * L)
{
std::string s = luaL_checkstring(L, 1);
printf("%s", s.c_str());
fflush(stdout);
return 0;
}
//#include <conio.h>
int luaCBGetChar(lua_State * L)
{
int c = getchar();
//int c = getch();
lua_pushnumber(L, c);
return 1;
}
int luaCBPlatform(lua_State * L)
{
std::string s = "undefined";
#ifdef __PRAXIS_WINDOWS__
s = "windows";
#endif
#ifdef __PRAXIS_LINUX__
s = "linux";
#endif
lua_pushstring(L, s.c_str());
return 1;
}
void luaInitCallbacksSystem()
{
lua_register(g_pLuaState, "luaCall", luaCBLuaCall);
lua_register(g_pLuaState, "turnOnDebugHook", luaCBTurnOnDebugHook);
lua_register(g_pLuaState, "turnOffDebugHook", luaCBTurnOffDebugHook);
lua_register(g_pLuaState, "getFPS", luaCBGetFPS);
lua_register(g_pLuaState, "getCurrentDir", luaCBGetCurrentDir);
lua_register(g_pLuaState, "setCurrentDir", luaCBSetCurrentDir);
lua_register(g_pLuaState, "printf", luaCBPrintf);
lua_register(g_pLuaState, "getchar", luaCBGetChar);
lua_register(g_pLuaState, "platform", luaCBPlatform);
}
<|endoftext|> |
<commit_before>// Copyright © 2016 The Things Network
// Use of this source code is governed by the MIT license that can be found in the LICENSE file.
#include <Arduino.h>
#include <TheThingsNetwork.h>
#define debugPrintLn(...) { if (debugStream) debugStream->println(__VA_ARGS__); }
#define debugPrint(...) { if (debugStream) debugStream->print(__VA_ARGS__); }
String TheThingsNetwork::readLine(int waitTime) {
unsigned long start = millis();
while (millis() < start + waitTime) {
String line = modemStream->readStringUntil('\n');
if (line.length() > 0) {
return line.substring(0, line.length() - 1);
}
}
return "";
}
bool TheThingsNetwork::waitForOK(int waitTime, String okMessage) {
String line = readLine(waitTime);
if (line == "") {
debugPrintLn(F("Wait for OK time-out expired"));
return false;
}
if (line != okMessage) {
debugPrint(F("Response is not OK: "));
debugPrintLn(line);
return false;
}
return true;
}
String TheThingsNetwork::readValue(String cmd) {
modemStream->println(cmd);
return readLine();
}
bool TheThingsNetwork::sendCommand(String cmd, int waitTime) {
debugPrint(F("Sending: "));
debugPrintLn(cmd);
modemStream->println(cmd);
return waitForOK(waitTime);
}
bool TheThingsNetwork::sendCommand(String cmd, String value, int waitTime) {
int l = value.length();
byte buf[l];
value.getBytes(buf, l);
return sendCommand(cmd, buf, l, waitTime);
}
char btohexa_high(unsigned char b) {
b >>= 4;
return (b > 0x9u) ? b + 'A' - 10 : b + '0';
}
char btohexa_low(unsigned char b) {
b &= 0x0F;
return (b > 0x9u) ? b + 'A' - 10 : b + '0';
}
bool TheThingsNetwork::sendCommand(String cmd, const byte *buf, int length, int waitTime) {
debugPrint(F("Sending: "));
debugPrint(cmd);
debugPrint(F(" with "));
debugPrint(length);
debugPrintLn(F(" bytes"));
modemStream->print(cmd + " ");
for (int i = 0; i < length; i++) {
modemStream->print(btohexa_high(buf[i]));
modemStream->print(btohexa_low(buf[i]));
}
modemStream->println();
return waitForOK(waitTime);
}
void TheThingsNetwork::reset(bool adr) {
#if !TTN_ADR_SUPPORTED
adr = false;
#endif
modemStream->println(F("sys reset"));
String version = readLine(3000);
if (version == "") {
debugPrintLn(F("Invalid version"));
return;
}
model = version.substring(0, version.indexOf(' '));
debugPrint(F("Version is "));
debugPrint(version);
debugPrint(F(", model is "));
debugPrintLn(model);
String devEui = readValue(F("sys get hweui"));
String str = "";
str.concat(F("mac set deveui "));
str.concat(devEui);
sendCommand(str);
String devEui = readValue(F("sys get hweui"));
String str = "";
str.concat(F("mac set deveui "));
str.concat(devEui);
sendCommand(str);
str = "";
str.concat(F("mac set adr "));
if(adr){
str.concat(F("on"));
} else {
str.concat(F("off"));
}
sendCommand(str);
}
void TheThingsNetwork::onMessage(void (*cb)(const byte* payload, int length, int port)) {
this->messageCallback = cb;
}
bool TheThingsNetwork::personalize(const byte devAddr[4], const byte nwkSKey[16], const byte appSKey[16]) {
reset();
sendCommand(F("mac set devaddr"), devAddr, 4);
sendCommand(F("mac set nwkskey"), nwkSKey, 16);
sendCommand(F("mac set appskey"), appSKey, 16);
return personalize();
}
bool TheThingsNetwork::personalize() {
configureChannels(this->sf, this->fsb);
sendCommand(F("mac join abp"));
String response = readLine();
if (response != F("accepted")) {
debugPrint(F("Personalize not accepted: "));
debugPrintLn(response);
return false;
}
debugPrint(F("Personalize accepted. Status: "));
debugPrintLn(readValue(F("mac get status")));
return true;
}
bool TheThingsNetwork::provision(const byte appEui[8], const byte appKey[16]) {
sendCommand(F("mac set appeui"), appEui, 8);
sendCommand(F("mac set appkey"), appKey, 16);
return sendCommand(F("mac save"), 50000);
}
bool TheThingsNetwork::join(int retries, long int retryDelay) {
configureChannels(this->sf, this->fsb);
String devEui = readValue(F("sys get hweui"));
String str = "";
str.concat(F("mac set deveui "));
str.concat(devEui);
sendCommand(str);
while (retries != 0) {
if (retries > 0) {
retries--;
}
if (!sendCommand(F("mac join otaa"))) {
debugPrintLn(F("Send join command failed"));
delay(retryDelay);
continue;
}
String response = readLine(10000);
if (response != F("accepted")) {
debugPrint(F("Join not accepted: "));
debugPrintLn(response);
delay(retryDelay);
continue;
}
debugPrint(F("Join accepted. Status: "));
debugPrintLn(readValue(F("mac get status")));
debugPrint(F("DevAddr: "));
debugPrintLn(readValue(F("mac get devaddr")));
return true;
}
return false;
}
bool TheThingsNetwork::join(const byte appEui[8], const byte appKey[16], int retries, long int retryDelay) {
reset();
provision(appEui, appKey);
return join(retries, retryDelay);
}
int TheThingsNetwork::sendBytes(const byte* payload, int length, int port, bool confirm) {
String str = "";
str.concat(F("mac tx "));
str.concat(confirm ? F("cnf ") : F("uncnf "));
str.concat(port);
if (!sendCommand(str, payload, length)) {
debugPrintLn(F("Send command failed"));
return -1;
}
String response = readLine(10000);
if (response == "") {
debugPrintLn(F("Time-out"));
return -2;
}
if (response == F("mac_tx_ok")) {
debugPrintLn(F("Successful transmission"));
return 1;
}
if (response.startsWith(F("mac_rx"))) {
int portEnds = response.indexOf(" ", 7);
int downlinkPort = response.substring(7, portEnds).toInt();
String data = response.substring(portEnds + 1);
int downlinkLength = data.length() / 2;
byte downlink[64];
for (int i = 0, d = 0; i < downlinkLength; i++, d += 2)
downlink[i] = TTN_HEX_PAIR_TO_BYTE(data[d], data[d+1]);
debugPrint(F("Successful transmission. Received "));
debugPrint(downlinkLength);
debugPrintLn(F(" bytes"));
if (this->messageCallback)
this->messageCallback(downlink, downlinkLength, downlinkPort);
return 2;
}
debugPrint(F("Unexpected response: "));
debugPrintLn(response);
return -10;
}
int TheThingsNetwork::poll(int port, bool confirm) {
byte payload[] = { 0x00 };
return sendBytes(payload, 1, port, confirm);
}
void TheThingsNetwork::showStatus() {
debugPrint(F("EUI: "));
debugPrintLn(readValue(F("sys get hweui")));
debugPrint(F("Battery: "));
debugPrintLn(readValue(F("sys get vdd")));
debugPrint(F("AppEUI: "));
debugPrintLn(readValue(F("mac get appeui")));
debugPrint(F("DevEUI: "));
debugPrintLn(readValue(F("mac get deveui")));
if (this->model == F("RN2483")) {
debugPrint(F("Band: "));
debugPrintLn(readValue(F("mac get band")));
}
debugPrint(F("Data Rate: "));
debugPrintLn(readValue(F("mac get dr")));
debugPrint(F("RX Delay 1: "));
debugPrintLn(readValue(F("mac get rxdelay1")));
debugPrint(F("RX Delay 2: "));
debugPrintLn(readValue(F("mac get rxdelay2")));
}
void TheThingsNetwork::configureEU868(int sf) {
int ch;
int dr = -1;
long int freq = 867100000;
String str = "";
str.concat(F("mac set rx2 3 869525000"));
sendCommand(str);
str = "";
for (ch = 0; ch <= 7; ch++) {
if (ch >= 3) {
str.concat(F("mac set ch freq "));
str.concat(ch);
str.concat(F(" "));
str.concat(freq);
sendCommand(str);
str = "";
str.concat(F("mac set ch drrange "));
str.concat(ch);
str.concat(F(" 0 5"));
sendCommand(str);
str = "";
str.concat(F("mac set ch status "));
str.concat(ch);
str.concat(F(" on"));
sendCommand(str);
str = "";
freq = freq + 200000;
}
str.concat(F("mac set ch dcycle "));
str.concat(ch);
str.concat(F(" 799"));
sendCommand(str);
str = "";
}
str.concat(F("mac set ch drrange 1 0 6"));
sendCommand(str);
str = "";
str.concat(F("mac set pwridx "));
str.concat(TTN_PWRIDX_868);
sendCommand(str);
switch (sf) {
case 7:
dr = 5;
break;
case 8:
dr = 4;
break;
case 9:
dr = 3;
break;
case 10:
dr = 2;
break;
case 11:
dr = 1;
break;
case 12:
dr = 0;
break;
default:
debugPrintLn(F("Invalid SF"))
break;
}
if (dr > -1){
str = "";
str.concat(F("mac set dr "));
str.concat(dr);
sendCommand(str);
}
}
void TheThingsNetwork::configureUS915(int sf, int fsb) {
int ch;
int dr = -1;
String str = "";
int chLow = fsb > 0 ? (fsb - 1) * 8 : 0;
int chHigh = fsb > 0 ? chLow + 7 : 71;
int ch500 = fsb + 63;
sendCommand(F("radio set freq 904200000"));
str = "";
str.concat(F("mac set pwridx "));
str.concat(TTN_PWRIDX_915);
sendCommand(str);
for (ch = 0; ch < 72; ch++) {
str = "";
str.concat(F("mac set ch status "));
str.concat(ch);
if (ch == ch500 || ch <= chHigh && ch >= chLow) {
str.concat(F(" on"));
sendCommand(str);
if (ch < 63) {
str = "";
str.concat(F("mac set ch drrange "));
str.concat(ch);
str.concat(F(" 0 3"));
sendCommand(str);
str = "";
}
}
else {
str.concat(F(" off"));
sendCommand(str);
}
}
switch (sf) {
case 7:
dr = 3;
break;
case 8:
dr = 2;
break;
case 9:
dr = 1;
break;
case 10:
dr = 0;
break;
default:
debugPrintLn(F("Invalid SF"))
break;
}
if (dr > -1){
str = "";
str.concat(F("mac set dr "));
str.concat(dr);
sendCommand(str);
}
}
void TheThingsNetwork::configureChannels(int sf, int fsb) {
switch (this->fp) {
case TTN_FP_EU868:
configureEU868(sf);
break;
case TTN_FP_US915:
configureUS915(sf, fsb);
break;
default:
debugPrintLn("Invalid frequency plan");
break;
}
}
TheThingsNetwork::TheThingsNetwork(Stream& modemStream, Stream& debugStream, fp_ttn_t fp, int sf, int fsb) {
this->debugStream = &debugStream;
this->modemStream = &modemStream;
this->fp = fp;
this->sf = sf;
this->fsb = fsb;
}
<commit_msg>remove dupe code<commit_after>// Copyright © 2016 The Things Network
// Use of this source code is governed by the MIT license that can be found in the LICENSE file.
#include <Arduino.h>
#include <TheThingsNetwork.h>
#define debugPrintLn(...) { if (debugStream) debugStream->println(__VA_ARGS__); }
#define debugPrint(...) { if (debugStream) debugStream->print(__VA_ARGS__); }
String TheThingsNetwork::readLine(int waitTime) {
unsigned long start = millis();
while (millis() < start + waitTime) {
String line = modemStream->readStringUntil('\n');
if (line.length() > 0) {
return line.substring(0, line.length() - 1);
}
}
return "";
}
bool TheThingsNetwork::waitForOK(int waitTime, String okMessage) {
String line = readLine(waitTime);
if (line == "") {
debugPrintLn(F("Wait for OK time-out expired"));
return false;
}
if (line != okMessage) {
debugPrint(F("Response is not OK: "));
debugPrintLn(line);
return false;
}
return true;
}
String TheThingsNetwork::readValue(String cmd) {
modemStream->println(cmd);
return readLine();
}
bool TheThingsNetwork::sendCommand(String cmd, int waitTime) {
debugPrint(F("Sending: "));
debugPrintLn(cmd);
modemStream->println(cmd);
return waitForOK(waitTime);
}
bool TheThingsNetwork::sendCommand(String cmd, String value, int waitTime) {
int l = value.length();
byte buf[l];
value.getBytes(buf, l);
return sendCommand(cmd, buf, l, waitTime);
}
char btohexa_high(unsigned char b) {
b >>= 4;
return (b > 0x9u) ? b + 'A' - 10 : b + '0';
}
char btohexa_low(unsigned char b) {
b &= 0x0F;
return (b > 0x9u) ? b + 'A' - 10 : b + '0';
}
bool TheThingsNetwork::sendCommand(String cmd, const byte *buf, int length, int waitTime) {
debugPrint(F("Sending: "));
debugPrint(cmd);
debugPrint(F(" with "));
debugPrint(length);
debugPrintLn(F(" bytes"));
modemStream->print(cmd + " ");
for (int i = 0; i < length; i++) {
modemStream->print(btohexa_high(buf[i]));
modemStream->print(btohexa_low(buf[i]));
}
modemStream->println();
return waitForOK(waitTime);
}
void TheThingsNetwork::reset(bool adr) {
#if !TTN_ADR_SUPPORTED
adr = false;
#endif
modemStream->println(F("sys reset"));
String version = readLine(3000);
if (version == "") {
debugPrintLn(F("Invalid version"));
return;
}
model = version.substring(0, version.indexOf(' '));
debugPrint(F("Version is "));
debugPrint(version);
debugPrint(F(", model is "));
debugPrintLn(model);
String devEui = readValue(F("sys get hweui"));
String str = "";
str.concat(F("mac set deveui "));
str.concat(devEui);
sendCommand(str);
str = "";
str.concat(F("mac set adr "));
if(adr){
str.concat(F("on"));
} else {
str.concat(F("off"));
}
sendCommand(str);
}
void TheThingsNetwork::onMessage(void (*cb)(const byte* payload, int length, int port)) {
this->messageCallback = cb;
}
bool TheThingsNetwork::personalize(const byte devAddr[4], const byte nwkSKey[16], const byte appSKey[16]) {
reset();
sendCommand(F("mac set devaddr"), devAddr, 4);
sendCommand(F("mac set nwkskey"), nwkSKey, 16);
sendCommand(F("mac set appskey"), appSKey, 16);
return personalize();
}
bool TheThingsNetwork::personalize() {
configureChannels(this->sf, this->fsb);
sendCommand(F("mac join abp"));
String response = readLine();
if (response != F("accepted")) {
debugPrint(F("Personalize not accepted: "));
debugPrintLn(response);
return false;
}
debugPrint(F("Personalize accepted. Status: "));
debugPrintLn(readValue(F("mac get status")));
return true;
}
bool TheThingsNetwork::provision(const byte appEui[8], const byte appKey[16]) {
sendCommand(F("mac set appeui"), appEui, 8);
sendCommand(F("mac set appkey"), appKey, 16);
return sendCommand(F("mac save"), 50000);
}
bool TheThingsNetwork::join(int retries, long int retryDelay) {
configureChannels(this->sf, this->fsb);
String devEui = readValue(F("sys get hweui"));
String str = "";
str.concat(F("mac set deveui "));
str.concat(devEui);
sendCommand(str);
while (retries != 0) {
if (retries > 0) {
retries--;
}
if (!sendCommand(F("mac join otaa"))) {
debugPrintLn(F("Send join command failed"));
delay(retryDelay);
continue;
}
String response = readLine(10000);
if (response != F("accepted")) {
debugPrint(F("Join not accepted: "));
debugPrintLn(response);
delay(retryDelay);
continue;
}
debugPrint(F("Join accepted. Status: "));
debugPrintLn(readValue(F("mac get status")));
debugPrint(F("DevAddr: "));
debugPrintLn(readValue(F("mac get devaddr")));
return true;
}
return false;
}
bool TheThingsNetwork::join(const byte appEui[8], const byte appKey[16], int retries, long int retryDelay) {
reset();
provision(appEui, appKey);
return join(retries, retryDelay);
}
int TheThingsNetwork::sendBytes(const byte* payload, int length, int port, bool confirm) {
String str = "";
str.concat(F("mac tx "));
str.concat(confirm ? F("cnf ") : F("uncnf "));
str.concat(port);
if (!sendCommand(str, payload, length)) {
debugPrintLn(F("Send command failed"));
return -1;
}
String response = readLine(10000);
if (response == "") {
debugPrintLn(F("Time-out"));
return -2;
}
if (response == F("mac_tx_ok")) {
debugPrintLn(F("Successful transmission"));
return 1;
}
if (response.startsWith(F("mac_rx"))) {
int portEnds = response.indexOf(" ", 7);
int downlinkPort = response.substring(7, portEnds).toInt();
String data = response.substring(portEnds + 1);
int downlinkLength = data.length() / 2;
byte downlink[64];
for (int i = 0, d = 0; i < downlinkLength; i++, d += 2)
downlink[i] = TTN_HEX_PAIR_TO_BYTE(data[d], data[d+1]);
debugPrint(F("Successful transmission. Received "));
debugPrint(downlinkLength);
debugPrintLn(F(" bytes"));
if (this->messageCallback)
this->messageCallback(downlink, downlinkLength, downlinkPort);
return 2;
}
debugPrint(F("Unexpected response: "));
debugPrintLn(response);
return -10;
}
int TheThingsNetwork::poll(int port, bool confirm) {
byte payload[] = { 0x00 };
return sendBytes(payload, 1, port, confirm);
}
void TheThingsNetwork::showStatus() {
debugPrint(F("EUI: "));
debugPrintLn(readValue(F("sys get hweui")));
debugPrint(F("Battery: "));
debugPrintLn(readValue(F("sys get vdd")));
debugPrint(F("AppEUI: "));
debugPrintLn(readValue(F("mac get appeui")));
debugPrint(F("DevEUI: "));
debugPrintLn(readValue(F("mac get deveui")));
if (this->model == F("RN2483")) {
debugPrint(F("Band: "));
debugPrintLn(readValue(F("mac get band")));
}
debugPrint(F("Data Rate: "));
debugPrintLn(readValue(F("mac get dr")));
debugPrint(F("RX Delay 1: "));
debugPrintLn(readValue(F("mac get rxdelay1")));
debugPrint(F("RX Delay 2: "));
debugPrintLn(readValue(F("mac get rxdelay2")));
}
void TheThingsNetwork::configureEU868(int sf) {
int ch;
int dr = -1;
long int freq = 867100000;
String str = "";
str.concat(F("mac set rx2 3 869525000"));
sendCommand(str);
str = "";
for (ch = 0; ch <= 7; ch++) {
if (ch >= 3) {
str.concat(F("mac set ch freq "));
str.concat(ch);
str.concat(F(" "));
str.concat(freq);
sendCommand(str);
str = "";
str.concat(F("mac set ch drrange "));
str.concat(ch);
str.concat(F(" 0 5"));
sendCommand(str);
str = "";
str.concat(F("mac set ch status "));
str.concat(ch);
str.concat(F(" on"));
sendCommand(str);
str = "";
freq = freq + 200000;
}
str.concat(F("mac set ch dcycle "));
str.concat(ch);
str.concat(F(" 799"));
sendCommand(str);
str = "";
}
str.concat(F("mac set ch drrange 1 0 6"));
sendCommand(str);
str = "";
str.concat(F("mac set pwridx "));
str.concat(TTN_PWRIDX_868);
sendCommand(str);
switch (sf) {
case 7:
dr = 5;
break;
case 8:
dr = 4;
break;
case 9:
dr = 3;
break;
case 10:
dr = 2;
break;
case 11:
dr = 1;
break;
case 12:
dr = 0;
break;
default:
debugPrintLn(F("Invalid SF"))
break;
}
if (dr > -1){
str = "";
str.concat(F("mac set dr "));
str.concat(dr);
sendCommand(str);
}
}
void TheThingsNetwork::configureUS915(int sf, int fsb) {
int ch;
int dr = -1;
String str = "";
int chLow = fsb > 0 ? (fsb - 1) * 8 : 0;
int chHigh = fsb > 0 ? chLow + 7 : 71;
int ch500 = fsb + 63;
sendCommand(F("radio set freq 904200000"));
str = "";
str.concat(F("mac set pwridx "));
str.concat(TTN_PWRIDX_915);
sendCommand(str);
for (ch = 0; ch < 72; ch++) {
str = "";
str.concat(F("mac set ch status "));
str.concat(ch);
if (ch == ch500 || ch <= chHigh && ch >= chLow) {
str.concat(F(" on"));
sendCommand(str);
if (ch < 63) {
str = "";
str.concat(F("mac set ch drrange "));
str.concat(ch);
str.concat(F(" 0 3"));
sendCommand(str);
str = "";
}
}
else {
str.concat(F(" off"));
sendCommand(str);
}
}
switch (sf) {
case 7:
dr = 3;
break;
case 8:
dr = 2;
break;
case 9:
dr = 1;
break;
case 10:
dr = 0;
break;
default:
debugPrintLn(F("Invalid SF"))
break;
}
if (dr > -1){
str = "";
str.concat(F("mac set dr "));
str.concat(dr);
sendCommand(str);
}
}
void TheThingsNetwork::configureChannels(int sf, int fsb) {
switch (this->fp) {
case TTN_FP_EU868:
configureEU868(sf);
break;
case TTN_FP_US915:
configureUS915(sf, fsb);
break;
default:
debugPrintLn("Invalid frequency plan");
break;
}
}
TheThingsNetwork::TheThingsNetwork(Stream& modemStream, Stream& debugStream, fp_ttn_t fp, int sf, int fsb) {
this->debugStream = &debugStream;
this->modemStream = &modemStream;
this->fp = fp;
this->sf = sf;
this->fsb = fsb;
}
<|endoftext|> |
<commit_before>/*
* Copyright(c) Sophist Solutions, Inc. 1990-2014. All rights reserved
*/
#include "../StroikaPreComp.h"
#if qHas_Syslog
#include <syslog.h>
#endif
#include "../Characters/CString/Utilities.h"
#include "../Characters/Format.h"
#include "../Debug/Trace.h"
#include "BlockingQueue.h"
#include "Process.h"
#include "Thread.h"
#include "TimeOutException.h"
#include "Logger.h"
using namespace Stroika::Foundation;
using namespace Stroika::Foundation::Execution;
using Memory::Optional;
using Time::DurationSecondsType;
/*
********************************************************************************
******************************** Execution::Logger *****************************
********************************************************************************
*/
Logger Logger::sThe_;
namespace {
BlockingQueue<pair<Logger::Priority, String>> sOutMsgQ_;
Execution::Thread sBookkeepingThread_;
bool sOutQMaybeNeedsFlush_ = true; // sligt optimziation of not using buffering
// @TODO - not threadsafe - til we add a threadsafe Optional to Stroika - but SB OK
Optional<DurationSecondsType> sSupressDuplicatesThreshold_;
struct LastMsg_ {
mutex fMutex_; // mutex so we can update related variables together
pair<Logger::Priority, String> fLastMsgSent_;
Time::DurationSecondsType fLastSentAt = 0.0;
unsigned int fRepeatCount_ = 0;
};
LastMsg_ sLastMsg_;
}
Logger::Logger ()
: fAppender_ ()
, fMinLogLevel_ (Priority::eInfo)
, fBufferingEnabled_ (false)
{
}
void Logger::SetAppender (const shared_ptr<IAppenderRep>& rep)
{
fAppender_ = rep;
}
void Logger::Log_ (Priority logLevel, const String& format, va_list argList)
{
shared_ptr<IAppenderRep> tmp = sThe_.fAppender_; // avoid races and critical sections
if (tmp.get () != nullptr) {
auto p = pair<Logger::Priority, String> (logLevel, Characters::FormatV (format.c_str (), argList));
if (sSupressDuplicatesThreshold_.IsPresent ()) {
lock_guard<mutex> critSec (sLastMsg_.fMutex_);
if (p == sLastMsg_.fLastMsgSent_) {
sLastMsg_.fRepeatCount_++;
return; // so will be handled later
}
else {
if (sLastMsg_.fRepeatCount_ > 0) {
FlushDupsWarning_ ();
}
sLastMsg_.fLastMsgSent_ = p;
sLastMsg_.fRepeatCount_ = 0;
}
sLastMsg_.fLastSentAt = Time::GetTickCount ();
}
if (GetBufferingEnabled ()) {
sOutQMaybeNeedsFlush_ = true;
sOutMsgQ_.AddTail (p);
}
else {
if (sOutQMaybeNeedsFlush_) {
FlushBuffer (); // in case recently disabled
}
tmp->Log (p.first, p.second);
}
}
}
void Logger::SetBufferingEnabled (bool logBufferingEnabled)
{
sThe_.fBufferingEnabled_ = logBufferingEnabled;
UpdateBookkeepingThread_ ();
}
void Logger::FlushBuffer ()
{
shared_ptr<IAppenderRep> tmp = sThe_.fAppender_; // avoid races and critical sections
if (tmp != nullptr) {
while (true) {
auto p = sOutMsgQ_.RemoveHeadIfPossible ();
if (p.IsPresent ()) {
tmp->Log (p->first, p->second);
}
else {
return; // no more entries
}
}
}
sOutQMaybeNeedsFlush_ = false;
}
Memory::Optional<Time::DurationSecondsType> Logger::GetSuppressDuplicates ()
{
return sSupressDuplicatesThreshold_;
}
void Logger::SetSuppressDuplicates (const Optional<DurationSecondsType>& suppressDuplicatesThreshold)
{
Require (suppressDuplicatesThreshold.IsMissing () or * suppressDuplicatesThreshold > 0.0);
if (sSupressDuplicatesThreshold_ != suppressDuplicatesThreshold) {
sSupressDuplicatesThreshold_ = suppressDuplicatesThreshold;
UpdateBookkeepingThread_ ();
}
}
void Logger::FlushDupsWarning_ ()
{
if (sLastMsg_.fRepeatCount_ > 0) {
shared_ptr<IAppenderRep> tmp = sThe_.fAppender_; // avoid races and critical sections
if (tmp != nullptr) {
if (sLastMsg_.fRepeatCount_ == 1) {
tmp->Log (sLastMsg_.fLastMsgSent_.first, sLastMsg_.fLastMsgSent_.second);
}
else {
tmp->Log (sLastMsg_.fLastMsgSent_.first, Characters::Format (L"[%d duplicates supressed]: %s", sLastMsg_.fRepeatCount_ - 1, sLastMsg_.fLastMsgSent_.second.c_str ()));
}
}
sLastMsg_.fRepeatCount_ = 0;
sLastMsg_.fLastMsgSent_.second.clear ();
}
}
void Logger::UpdateBookkeepingThread_ ()
{
sBookkeepingThread_.AbortAndWaitForDone ();
sBookkeepingThread_ = Thread (); // so null
Time::DurationSecondsType suppressDuplicatesThreshold = sSupressDuplicatesThreshold_.Value (0);
bool suppressDuplicates = suppressDuplicatesThreshold > 0;
if (suppressDuplicates or GetBufferingEnabled ()) {
if (suppressDuplicates) {
sBookkeepingThread_ = Thread ([suppressDuplicatesThreshold] () {
while (true) {
DurationSecondsType time2Wait = max (static_cast<DurationSecondsType> (2), suppressDuplicatesThreshold); // never wait less than this
try {
auto p = sOutMsgQ_.RemoveHead (time2Wait);
shared_ptr<IAppenderRep> tmp = sThe_.fAppender_; // avoid races and critical sections
if (tmp != nullptr) {
tmp->Log (p.first, p.second);
}
}
catch (const TimeOutException&) {
}
{
lock_guard<mutex> critSec (sLastMsg_.fMutex_);
if (sLastMsg_.fRepeatCount_ > 0 and sLastMsg_.fLastSentAt + suppressDuplicatesThreshold < Time::GetTickCount ()) {
FlushDupsWarning_ ();
}
}
}
});
}
else {
sBookkeepingThread_ = Thread ([] () {
while (true) {
auto p = sOutMsgQ_.RemoveHead ();
shared_ptr<IAppenderRep> tmp = sThe_.fAppender_; // avoid races and critical sections
if (tmp != nullptr) {
tmp->Log (p.first, p.second);
}
}
});
}
sBookkeepingThread_.SetThreadName (L"Logger Bookkeeping");
sBookkeepingThread_.SetThreadPriority (Thread::Priority::eBelowNormal);
sBookkeepingThread_.Start ();
}
// manually push out pending messages
FlushBuffer ();
}
/*
********************************************************************************
************************** Execution::IAppenderRep *****************************
********************************************************************************
*/
Logger::IAppenderRep::~IAppenderRep ()
{
}
#if qHas_Syslog
/*
********************************************************************************
************************ Execution::SysLogAppender *****************************
********************************************************************************
*/
namespace {
string mkMsg_ (const String& applicationName)
{
return Characters::CString::Format ("%s[%d]", applicationName.AsNarrowSDKString ().c_str (), GetCurrentProcessID ());
}
}
Logger::SysLogAppender::SysLogAppender (const String& applicationName)
: fApplicationName_ (mkMsg_ (applicationName))
{
openlog (fApplicationName_.c_str (), 0, LOG_DAEMON); // not sure what facility to pass?
}
Logger::SysLogAppender::SysLogAppender (const String& applicationName, int facility)
: fApplicationName_ (mkMsg_ (applicationName))
{
openlog (fApplicationName_.c_str (), 0, facility);
}
Logger::SysLogAppender::~SysLogAppender ()
{
closelog ();
}
void Logger::SysLogAppender::Log (Priority logLevel, const String& message)
{
DbgTrace (L"SYSLOG: %d: %s", logLevel, message.c_str ());
int sysLogLevel = LOG_NOTICE; // doesnt matter cuz assert error if hit
switch (logLevel) {
case Priority::eDebug:
sysLogLevel = LOG_DEBUG;
break;
case Priority::eInfo:
sysLogLevel = LOG_INFO;
break;
case Priority::eNotice:
sysLogLevel = LOG_NOTICE;
break;
case Priority::eWarning:
sysLogLevel = LOG_WARNING;
break;
case Priority::eError:
sysLogLevel = LOG_DEBUG;
break;
case Priority::eCriticalError:
sysLogLevel = LOG_CRIT;
break;
case Priority::eAlertError:
sysLogLevel = LOG_ALERT;
break;
case Priority::eEmergency:
sysLogLevel = LOG_EMERG;
break;
default:
RequireNotReached ();
}
syslog (sysLogLevel, "%s", message.AsNarrowSDKString ().c_str ());
}
#endif
/*
********************************************************************************
************************** Execution::FileAppender *****************************
********************************************************************************
*/
Logger::FileAppender::FileAppender (const String& fileName)
{
AssertNotImplemented ();
}
void Logger::FileAppender::Log (Priority logLevel, const String& message)
{
AssertNotImplemented ();
}
#if qPlatform_Windows
/*
********************************************************************************
************************ Execution::SysLogAppender *****************************
********************************************************************************
*/
Logger::WindowsEventLogAppender::WindowsEventLogAppender ()
{
}
void Logger::WindowsEventLogAppender::Log (Priority logLevel, const String& message)
{
/*
* VERY QUICK HACK - AT LEAST DUMPS SOME INFO TO EVENTLOG - BUT MUCH TWEAKING LEFT TODO
*/
const TCHAR kEventSourceName[] = _T ("xxxtest");
WORD eventType = EVENTLOG_ERROR_TYPE;
switch (logLevel) {
case Priority::eDebug:
eventType = EVENTLOG_INFORMATION_TYPE;
break;
case Priority::eInfo:
eventType = EVENTLOG_INFORMATION_TYPE;
break;
case Priority::eNotice:
eventType = EVENTLOG_INFORMATION_TYPE;
break;
case Priority::eWarning:
eventType = EVENTLOG_WARNING_TYPE;
break;
case Priority::eError:
eventType = EVENTLOG_ERROR_TYPE;
break;
case Priority::eAlertError:
eventType = EVENTLOG_ERROR_TYPE;
break;
case Priority::eEmergency:
eventType = EVENTLOG_ERROR_TYPE;
break;
}
#define CATEGORY_Normal 0x00000001L
WORD eventCategoryID = CATEGORY_Normal;
// See SPR#565 for wierdness - where I cannot really get these paid attention to
// by the Windows EventLog. So had to use the .Net eventlogger. It SEEMS
#define EVENT_Message 0x00000064L
const DWORD kEventID = EVENT_Message;
HANDLE hEventSource = RegisterEventSource (NULL, kEventSourceName);
Verify (hEventSource != NULL);
SDKString tmp = message.AsSDKString ();
const Characters::SDKChar* msg = tmp.c_str ();
Verify (::ReportEvent (
hEventSource,
eventType,
eventCategoryID,
kEventID,
NULL,
(WORD)1,
0,
&msg,
NULL
)
);
Verify (::DeregisterEventSource (hEventSource));
}
#endif<commit_msg>use new Containers::Optional<> in logger code<commit_after>/*
* Copyright(c) Sophist Solutions, Inc. 1990-2014. All rights reserved
*/
#include "../StroikaPreComp.h"
#if qHas_Syslog
#include <syslog.h>
#endif
#include "../Characters/CString/Utilities.h"
#include "../Characters/Format.h"
#include "../Containers/Optional.h"
#include "../Debug/Trace.h"
#include "BlockingQueue.h"
#include "Process.h"
#include "Thread.h"
#include "TimeOutException.h"
#include "Logger.h"
using namespace Stroika::Foundation;
using namespace Stroika::Foundation::Execution;
using Time::DurationSecondsType;
/*
********************************************************************************
******************************** Execution::Logger *****************************
********************************************************************************
*/
Logger Logger::sThe_;
namespace {
BlockingQueue<pair<Logger::Priority, String>> sOutMsgQ_;
Execution::Thread sBookkeepingThread_;
bool sOutQMaybeNeedsFlush_ = true; // sligt optimziation of not using buffering
Containers::Optional<DurationSecondsType> sSupressDuplicatesThreshold_;
struct LastMsg_ {
mutex fMutex_; // mutex so we can update related variables together
pair<Logger::Priority, String> fLastMsgSent_;
Time::DurationSecondsType fLastSentAt = 0.0;
unsigned int fRepeatCount_ = 0;
};
LastMsg_ sLastMsg_;
}
Logger::Logger ()
: fAppender_ ()
, fMinLogLevel_ (Priority::eInfo)
, fBufferingEnabled_ (false)
{
}
void Logger::SetAppender (const shared_ptr<IAppenderRep>& rep)
{
fAppender_ = rep;
}
void Logger::Log_ (Priority logLevel, const String& format, va_list argList)
{
shared_ptr<IAppenderRep> tmp = sThe_.fAppender_; // avoid races and critical sections
if (tmp.get () != nullptr) {
auto p = pair<Logger::Priority, String> (logLevel, Characters::FormatV (format.c_str (), argList));
if (sSupressDuplicatesThreshold_.IsPresent ()) {
lock_guard<mutex> critSec (sLastMsg_.fMutex_);
if (p == sLastMsg_.fLastMsgSent_) {
sLastMsg_.fRepeatCount_++;
return; // so will be handled later
}
else {
if (sLastMsg_.fRepeatCount_ > 0) {
FlushDupsWarning_ ();
}
sLastMsg_.fLastMsgSent_ = p;
sLastMsg_.fRepeatCount_ = 0;
}
sLastMsg_.fLastSentAt = Time::GetTickCount ();
}
if (GetBufferingEnabled ()) {
sOutQMaybeNeedsFlush_ = true;
sOutMsgQ_.AddTail (p);
}
else {
if (sOutQMaybeNeedsFlush_) {
FlushBuffer (); // in case recently disabled
}
tmp->Log (p.first, p.second);
}
}
}
void Logger::SetBufferingEnabled (bool logBufferingEnabled)
{
sThe_.fBufferingEnabled_ = logBufferingEnabled;
UpdateBookkeepingThread_ ();
}
void Logger::FlushBuffer ()
{
shared_ptr<IAppenderRep> tmp = sThe_.fAppender_; // avoid races and critical sections
if (tmp != nullptr) {
while (true) {
auto p = sOutMsgQ_.RemoveHeadIfPossible ();
if (p.IsPresent ()) {
tmp->Log (p->first, p->second);
}
else {
return; // no more entries
}
}
}
sOutQMaybeNeedsFlush_ = false;
}
Memory::Optional<Time::DurationSecondsType> Logger::GetSuppressDuplicates ()
{
return Memory::Optional<Time::DurationSecondsType> (sSupressDuplicatesThreshold_);
}
void Logger::SetSuppressDuplicates (const Memory::Optional<DurationSecondsType>& suppressDuplicatesThreshold)
{
Require (suppressDuplicatesThreshold.IsMissing () or * suppressDuplicatesThreshold > 0.0);
if (sSupressDuplicatesThreshold_ != suppressDuplicatesThreshold) {
sSupressDuplicatesThreshold_ = suppressDuplicatesThreshold;
UpdateBookkeepingThread_ ();
}
}
void Logger::FlushDupsWarning_ ()
{
if (sLastMsg_.fRepeatCount_ > 0) {
shared_ptr<IAppenderRep> tmp = sThe_.fAppender_; // avoid races and critical sections
if (tmp != nullptr) {
if (sLastMsg_.fRepeatCount_ == 1) {
tmp->Log (sLastMsg_.fLastMsgSent_.first, sLastMsg_.fLastMsgSent_.second);
}
else {
tmp->Log (sLastMsg_.fLastMsgSent_.first, Characters::Format (L"[%d duplicates supressed]: %s", sLastMsg_.fRepeatCount_ - 1, sLastMsg_.fLastMsgSent_.second.c_str ()));
}
}
sLastMsg_.fRepeatCount_ = 0;
sLastMsg_.fLastMsgSent_.second.clear ();
}
}
void Logger::UpdateBookkeepingThread_ ()
{
sBookkeepingThread_.AbortAndWaitForDone ();
sBookkeepingThread_ = Thread (); // so null
Time::DurationSecondsType suppressDuplicatesThreshold = sSupressDuplicatesThreshold_.Value (0);
bool suppressDuplicates = suppressDuplicatesThreshold > 0;
if (suppressDuplicates or GetBufferingEnabled ()) {
if (suppressDuplicates) {
sBookkeepingThread_ = Thread ([suppressDuplicatesThreshold] () {
while (true) {
DurationSecondsType time2Wait = max (static_cast<DurationSecondsType> (2), suppressDuplicatesThreshold); // never wait less than this
try {
auto p = sOutMsgQ_.RemoveHead (time2Wait);
shared_ptr<IAppenderRep> tmp = sThe_.fAppender_; // avoid races and critical sections
if (tmp != nullptr) {
tmp->Log (p.first, p.second);
}
}
catch (const TimeOutException&) {
}
{
lock_guard<mutex> critSec (sLastMsg_.fMutex_);
if (sLastMsg_.fRepeatCount_ > 0 and sLastMsg_.fLastSentAt + suppressDuplicatesThreshold < Time::GetTickCount ()) {
FlushDupsWarning_ ();
}
}
}
});
}
else {
sBookkeepingThread_ = Thread ([] () {
while (true) {
auto p = sOutMsgQ_.RemoveHead ();
shared_ptr<IAppenderRep> tmp = sThe_.fAppender_; // avoid races and critical sections
if (tmp != nullptr) {
tmp->Log (p.first, p.second);
}
}
});
}
sBookkeepingThread_.SetThreadName (L"Logger Bookkeeping");
sBookkeepingThread_.SetThreadPriority (Thread::Priority::eBelowNormal);
sBookkeepingThread_.Start ();
}
// manually push out pending messages
FlushBuffer ();
}
/*
********************************************************************************
************************** Execution::IAppenderRep *****************************
********************************************************************************
*/
Logger::IAppenderRep::~IAppenderRep ()
{
}
#if qHas_Syslog
/*
********************************************************************************
************************ Execution::SysLogAppender *****************************
********************************************************************************
*/
namespace {
string mkMsg_ (const String& applicationName)
{
return Characters::CString::Format ("%s[%d]", applicationName.AsNarrowSDKString ().c_str (), GetCurrentProcessID ());
}
}
Logger::SysLogAppender::SysLogAppender (const String& applicationName)
: fApplicationName_ (mkMsg_ (applicationName))
{
openlog (fApplicationName_.c_str (), 0, LOG_DAEMON); // not sure what facility to pass?
}
Logger::SysLogAppender::SysLogAppender (const String& applicationName, int facility)
: fApplicationName_ (mkMsg_ (applicationName))
{
openlog (fApplicationName_.c_str (), 0, facility);
}
Logger::SysLogAppender::~SysLogAppender ()
{
closelog ();
}
void Logger::SysLogAppender::Log (Priority logLevel, const String& message)
{
DbgTrace (L"SYSLOG: %d: %s", logLevel, message.c_str ());
int sysLogLevel = LOG_NOTICE; // doesnt matter cuz assert error if hit
switch (logLevel) {
case Priority::eDebug:
sysLogLevel = LOG_DEBUG;
break;
case Priority::eInfo:
sysLogLevel = LOG_INFO;
break;
case Priority::eNotice:
sysLogLevel = LOG_NOTICE;
break;
case Priority::eWarning:
sysLogLevel = LOG_WARNING;
break;
case Priority::eError:
sysLogLevel = LOG_DEBUG;
break;
case Priority::eCriticalError:
sysLogLevel = LOG_CRIT;
break;
case Priority::eAlertError:
sysLogLevel = LOG_ALERT;
break;
case Priority::eEmergency:
sysLogLevel = LOG_EMERG;
break;
default:
RequireNotReached ();
}
syslog (sysLogLevel, "%s", message.AsNarrowSDKString ().c_str ());
}
#endif
/*
********************************************************************************
************************** Execution::FileAppender *****************************
********************************************************************************
*/
Logger::FileAppender::FileAppender (const String& fileName)
{
AssertNotImplemented ();
}
void Logger::FileAppender::Log (Priority logLevel, const String& message)
{
AssertNotImplemented ();
}
#if qPlatform_Windows
/*
********************************************************************************
************************ Execution::SysLogAppender *****************************
********************************************************************************
*/
Logger::WindowsEventLogAppender::WindowsEventLogAppender ()
{
}
void Logger::WindowsEventLogAppender::Log (Priority logLevel, const String& message)
{
/*
* VERY QUICK HACK - AT LEAST DUMPS SOME INFO TO EVENTLOG - BUT MUCH TWEAKING LEFT TODO
*/
const TCHAR kEventSourceName[] = _T ("xxxtest");
WORD eventType = EVENTLOG_ERROR_TYPE;
switch (logLevel) {
case Priority::eDebug:
eventType = EVENTLOG_INFORMATION_TYPE;
break;
case Priority::eInfo:
eventType = EVENTLOG_INFORMATION_TYPE;
break;
case Priority::eNotice:
eventType = EVENTLOG_INFORMATION_TYPE;
break;
case Priority::eWarning:
eventType = EVENTLOG_WARNING_TYPE;
break;
case Priority::eError:
eventType = EVENTLOG_ERROR_TYPE;
break;
case Priority::eAlertError:
eventType = EVENTLOG_ERROR_TYPE;
break;
case Priority::eEmergency:
eventType = EVENTLOG_ERROR_TYPE;
break;
}
#define CATEGORY_Normal 0x00000001L
WORD eventCategoryID = CATEGORY_Normal;
// See SPR#565 for wierdness - where I cannot really get these paid attention to
// by the Windows EventLog. So had to use the .Net eventlogger. It SEEMS
#define EVENT_Message 0x00000064L
const DWORD kEventID = EVENT_Message;
HANDLE hEventSource = RegisterEventSource (NULL, kEventSourceName);
Verify (hEventSource != NULL);
SDKString tmp = message.AsSDKString ();
const Characters::SDKChar* msg = tmp.c_str ();
Verify (::ReportEvent (
hEventSource,
eventType,
eventCategoryID,
kEventID,
NULL,
(WORD)1,
0,
&msg,
NULL
)
);
Verify (::DeregisterEventSource (hEventSource));
}
#endif<|endoftext|> |
<commit_before>/*=========================================================================
Library: CTK
Copyright (c) Kitware 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.txt
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.
=========================================================================*/
// Qt includes
#include <QApplication>
#include <QDir>
#include <QTimer>
// ctk includes
#include "ctkUtils.h"
// ctkDICOMCore includes
#include "ctkDICOMDatabase.h"
// ctkDICOMWidget includes
#include "ctkDICOMBrowser.h"
// STD includes
#include <iostream>
int ctkDICOMBrowserTest1( int argc, char * argv [] )
{
QApplication app(argc, argv);
qDebug() << "argc = " << argc;
for (int i = 0; i < argc; ++i)
{
qDebug() << "\t" << argv[i];
}
QFileInfo tempFileInfo(QDir::tempPath() + QString("/ctkDICOMBrowserTest1-db"));
QString dbDir = tempFileInfo.absoluteFilePath();
qDebug() << "\n\nUsing directory: " << dbDir;
if (tempFileInfo.exists())
{
qDebug() << "\n\nRemoving directory: " << dbDir;
ctk::removeDirRecursively(dbDir);
}
qDebug() << "\n\nMaking directory: " << dbDir;
QDir dir(dbDir);
dir.mkdir(dbDir);
ctkDICOMBrowser browser;
browser.setDatabaseDirectory(dbDir);
browser.show();
browser.setDisplayImportSummary(false);
qDebug() << "Importing directory " << argv[1];
// make sure copy/link dialog doesn't pop up, always copy on import
QSettings settings;
QString settingsString = settings.value("MainWindow/DontConfirmCopyOnImport").toString();
settings.setValue("MainWindow/DontConfirmCopyOnImport", QString("0"));
browser.onImportDirectory(argv[1]);
// reset to the original copy/import setting
settings.setValue("MainWindow/DontConfirmCopyOnImport", settingsString);
if (browser.patientsAddedDuringImport() != 1
|| browser.studiesAddedDuringImport() != 1
|| browser.seriesAddedDuringImport() != 1
|| browser.instancesAddedDuringImport() != 100)
{
qDebug() << "\n\nDirectory did not import as expected!\n\n";
return EXIT_FAILURE;
}
qDebug() << "\n\nAdded to database directory: " << dbDir;
if (argc <= 2 || QString(argv[argc - 1]) != "-I")
{
QTimer::singleShot(200, &app, SLOT(quit()));
}
return app.exec();
}
<commit_msg>STYLE: Refactor ctkDICOMBrowserTest1 to use testing macros<commit_after>/*=========================================================================
Library: CTK
Copyright (c) Kitware 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.txt
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.
=========================================================================*/
// Qt includes
#include <QApplication>
#include <QDir>
#include <QTimer>
// ctk includes
#include "ctkCoreTestingMacros.h"
#include "ctkUtils.h"
// ctkDICOMCore includes
#include "ctkDICOMDatabase.h"
// ctkDICOMWidget includes
#include "ctkDICOMBrowser.h"
// STD includes
#include <iostream>
int ctkDICOMBrowserTest1( int argc, char * argv [] )
{
QApplication app(argc, argv);
qDebug() << "argc = " << argc;
for (int i = 0; i < argc; ++i)
{
qDebug() << "\t" << argv[i];
}
QFileInfo tempFileInfo(QDir::tempPath() + QString("/ctkDICOMBrowserTest1-db"));
QString dbDir = tempFileInfo.absoluteFilePath();
qDebug() << "\n\nUsing directory: " << dbDir;
if (tempFileInfo.exists())
{
qDebug() << "\n\nRemoving directory: " << dbDir;
ctk::removeDirRecursively(dbDir);
}
qDebug() << "\n\nMaking directory: " << dbDir;
QDir dir(dbDir);
dir.mkdir(dbDir);
ctkDICOMBrowser browser;
browser.setDatabaseDirectory(dbDir);
browser.show();
browser.setDisplayImportSummary(false);
qDebug() << "Importing directory " << argv[1];
// make sure copy/link dialog doesn't pop up, always copy on import
QSettings settings;
QString settingsString = settings.value("MainWindow/DontConfirmCopyOnImport").toString();
settings.setValue("MainWindow/DontConfirmCopyOnImport", QString("0"));
browser.onImportDirectory(argv[1]);
// reset to the original copy/import setting
settings.setValue("MainWindow/DontConfirmCopyOnImport", settingsString);
CHECK_INT(browser.patientsAddedDuringImport(), 1);
CHECK_INT(browser.studiesAddedDuringImport(), 1);
CHECK_INT(browser.seriesAddedDuringImport(), 1);
CHECK_INT(browser.instancesAddedDuringImport(), 100);
qDebug() << "\n\nAdded to database directory: " << dbDir;
if (argc <= 2 || QString(argv[argc - 1]) != "-I")
{
QTimer::singleShot(200, &app, SLOT(quit()));
}
return app.exec();
}
<|endoftext|> |
<commit_before>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: hfi_typedef.cxx,v $
*
* $Revision: 1.5 $
*
* last change: $Author: vg $ $Date: 2007-09-18 13:59:47 $
*
* 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
*
************************************************************************/
#include <precomp.h>
#include "hfi_typedef.hxx"
// NOT FULLY DEFINED SERVICES
#include <ary/idl/i_ce.hxx>
#include <ary/idl/ik_typedef.hxx>
#include <toolkit/hf_docentry.hxx>
#include <toolkit/hf_linachain.hxx>
#include <toolkit/hf_title.hxx>
#include "hfi_navibar.hxx"
#include "hfi_typetext.hxx"
#include "hi_linkhelper.hxx"
HF_IdlTypedef::HF_IdlTypedef( Environment & io_rEnv,
Xml::Element & o_rOut )
: HtmlFactory_Idl(io_rEnv, &o_rOut)
{
}
HF_IdlTypedef::~HF_IdlTypedef()
{
}
typedef ary::idl::ifc_typedef::attr TypedefAttr;
void
HF_IdlTypedef::Produce_byData( const client & i_ce ) const
{
make_Navibar(i_ce);
HF_TitleTable
aTitle(CurOut());
HF_LinkedNameChain
aNameChain(aTitle.Add_Row());
aNameChain.Produce_CompleteChain(Env().CurPosition(), nameChainLinker);
produce_Title(aTitle, C_sCePrefix_Typedef, i_ce);
HF_DocEntryList
aTopList( aTitle.Add_Row() );
aTopList.Produce_Term("Defining Type");
HF_IdlTypeText
aDefinition( Env(), aTopList.Produce_Definition(), true );
aDefinition.Produce_byData( TypedefAttr::DefiningType(i_ce) );
CurOut() << new Html::HorizontalLine;
write_Docu(aTitle.Add_Row(), i_ce);
CurOut() << new Html::HorizontalLine();
}
void
HF_IdlTypedef::make_Navibar( const client & i_ce ) const
{
HF_IdlNavigationBar
aNaviBar(Env(), CurOut());
aNaviBar.Produce_CeMainRow(i_ce);
CurOut() << new Html::HorizontalLine();
}
<commit_msg>INTEGRATION: CWS changefileheader (1.5.26); FILE MERGED 2008/03/28 16:02:06 rt 1.5.26.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: hfi_typedef.cxx,v $
* $Revision: 1.6 $
*
* 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.
*
************************************************************************/
#include <precomp.h>
#include "hfi_typedef.hxx"
// NOT FULLY DEFINED SERVICES
#include <ary/idl/i_ce.hxx>
#include <ary/idl/ik_typedef.hxx>
#include <toolkit/hf_docentry.hxx>
#include <toolkit/hf_linachain.hxx>
#include <toolkit/hf_title.hxx>
#include "hfi_navibar.hxx"
#include "hfi_typetext.hxx"
#include "hi_linkhelper.hxx"
HF_IdlTypedef::HF_IdlTypedef( Environment & io_rEnv,
Xml::Element & o_rOut )
: HtmlFactory_Idl(io_rEnv, &o_rOut)
{
}
HF_IdlTypedef::~HF_IdlTypedef()
{
}
typedef ary::idl::ifc_typedef::attr TypedefAttr;
void
HF_IdlTypedef::Produce_byData( const client & i_ce ) const
{
make_Navibar(i_ce);
HF_TitleTable
aTitle(CurOut());
HF_LinkedNameChain
aNameChain(aTitle.Add_Row());
aNameChain.Produce_CompleteChain(Env().CurPosition(), nameChainLinker);
produce_Title(aTitle, C_sCePrefix_Typedef, i_ce);
HF_DocEntryList
aTopList( aTitle.Add_Row() );
aTopList.Produce_Term("Defining Type");
HF_IdlTypeText
aDefinition( Env(), aTopList.Produce_Definition(), true );
aDefinition.Produce_byData( TypedefAttr::DefiningType(i_ce) );
CurOut() << new Html::HorizontalLine;
write_Docu(aTitle.Add_Row(), i_ce);
CurOut() << new Html::HorizontalLine();
}
void
HF_IdlTypedef::make_Navibar( const client & i_ce ) const
{
HF_IdlNavigationBar
aNaviBar(Env(), CurOut());
aNaviBar.Produce_CeMainRow(i_ce);
CurOut() << new Html::HorizontalLine();
}
<|endoftext|> |
<commit_before>/**
* @file
* @copyright defined in eos/LICENSE.txt
*/
#pragma once
#include <eosio/chain/types.hpp>
#include <numeric>
namespace eosio { namespace chain {
struct permission_level {
account_name actor;
permission_name permission;
};
/**
* An action is performed by an actor, aka an account. It may
* be created explicitly and authorized by signatures or might be
* generated implicitly by executing application code.
*
* This follows the design pattern of React Flux where actions are
* named and then dispatched to one or more action handlers (aka stores).
* In the context of eosio, every action is dispatched to the handler defined
* by account 'scope' and function 'name', but the default handler may also
* forward the action to any number of additional handlers. Any application
* can write a handler for "scope::name" that will get executed if and only if
* this action is forwarded to that application.
*
* Each action may require the permission of specific actors. Actors can define
* any number of permission levels. The actors and their respective permission
* levels are declared on the action and validated independently of the executing
* application code. An application code will check to see if the required authorization
* were properly declared when it executes.
*/
struct action {
account_name account;
action_name name;
vector<permission_level> authorization;
bytes data;
action(){}
template<typename T, std::enable_if_t<std::is_base_of<bytes, T>::value, int> = 1>
action( vector<permission_level> auth, const T& value ) {
account = T::get_account();
name = T::get_name();
authorization = move(auth);
data.assign(value.data(), value.data() + value.size());
}
template<typename T, std::enable_if_t<!std::is_base_of<bytes, T>::value, int> = 1>
action( vector<permission_level> auth, const T& value ) {
account = T::get_account();
name = T::get_name();
authorization = move(auth);
data = fc::raw::pack(value);
}
action( vector<permission_level> auth, account_name account, action_name name, const bytes& data )
: account(account), name(name), authorization(move(auth)), data(data) {
}
template<typename T>
T data_as()const {
FC_ASSERT( account == T::get_account() );
FC_ASSERT( name == T::get_name() );
return fc::raw::unpack<T>(data);
}
};
struct action_notice : public action {
account_name receiver;
};
/**
* When a transaction is referenced by a block it could imply one of several outcomes which
* describe the state-transition undertaken by the block producer.
*/
struct transaction_receipt {
enum status_enum {
executed = 0, ///< succeed, no error handler executed
soft_fail = 1, ///< objectively failed (not executed), error handler executed
hard_fail = 2, ///< objectively failed and error handler objectively failed thus no state change
delayed = 3 ///< transaction delayed
};
transaction_receipt() : status(hard_fail) {}
transaction_receipt( transaction_id_type tid ):status(executed),id(tid){}
fc::enum_type<uint8_t,status_enum> status;
transaction_id_type id;
};
/**
* The transaction header contains the fixed-sized data
* associated with each transaction. It is separated from
* the transaction body to facilitate partial parsing of
* transactions without requiring dynamic memory allocation.
*
* All transactions have an expiration time after which they
* may no longer be included in the blockchain. Once a block
* with a block_header::timestamp greater than expiration is
* deemed irreversible, then a user can safely trust the transaction
* will never be included.
*
* Each region is an independent blockchain, it is included as routing
* information for inter-blockchain communication. A contract in this
* region might generate or authorize a transaction intended for a foreign
* region.
*/
struct transaction_header {
time_point_sec expiration; ///< the time at which a transaction expires
uint16_t region = 0; ///< the computational memory region this transaction applies to.
uint16_t ref_block_num = 0; ///< specifies a block num in the last 2^16 blocks.
uint32_t ref_block_prefix = 0; ///< specifies the lower 32 bits of the blockid at get_ref_blocknum
uint16_t packed_bandwidth_words = 0; /// number of 8 byte words this transaction can compress into
uint16_t context_free_cpu_bandwidth = 0; /// number of CPU usage units to bill transaction for
/**
* @return the absolute block number given the relative ref_block_num
*/
block_num_type get_ref_blocknum( block_num_type head_blocknum )const {
return ((head_blocknum/0xffff)*0xffff) + head_blocknum%0xffff;
}
void set_reference_block( const block_id_type& reference_block );
bool verify_reference_block( const block_id_type& reference_block )const;
};
/**
* A transaction consits of a set of messages which must all be applied or
* all are rejected. These messages have access to data within the given
* read and write scopes.
*/
struct transaction : public transaction_header {
vector<action> context_free_actions;
vector<action> actions;
transaction_id_type id()const;
digest_type sig_digest( const chain_id_type& chain_id, const vector<bytes>& cfd = vector<bytes>() )const;
flat_set<public_key_type> get_signature_keys( const vector<signature_type>& signatures, const chain_id_type& chain_id, const vector<bytes>& cfd = vector<bytes>() )const;
};
struct signed_transaction : public transaction
{
signed_transaction() = default;
// signed_transaction( const signed_transaction& ) = default;
// signed_transaction( signed_transaction&& ) = default;
signed_transaction( transaction&& trx, const vector<signature_type>& signatures, const vector<bytes>& context_free_data)
: transaction(std::forward<transaction>(trx))
, signatures(signatures)
, context_free_data(context_free_data)
{
}
vector<signature_type> signatures;
vector<bytes> context_free_data; ///< for each context-free action, there is an entry here
const signature_type& sign(const private_key_type& key, const chain_id_type& chain_id);
signature_type sign(const private_key_type& key, const chain_id_type& chain_id)const;
flat_set<public_key_type> get_signature_keys( const chain_id_type& chain_id )const;
};
struct packed_transaction {
enum compression_type {
none,
zlib,
};
packed_transaction() = default;
explicit packed_transaction(const transaction& t, compression_type _compression = none)
{
set_transaction(t, _compression);
}
explicit packed_transaction(const signed_transaction& t, compression_type _compression = none)
:signatures(t.signatures)
,context_free_data(t.context_free_data)
{
set_transaction(t, _compression);
}
explicit packed_transaction(signed_transaction&& t, compression_type _compression = none)
:signatures(std::move(t.signatures))
,context_free_data(std::move(t.context_free_data))
{
set_transaction(t, _compression);
}
vector<signature_type> signatures;
vector<bytes> context_free_data;
compression_type compression;
bytes data;
bytes get_raw_transaction()const;
transaction get_transaction()const;
signed_transaction get_signed_transaction()const;
void set_transaction(const transaction& t, compression_type _compression = none);
};
/**
* When a transaction is generated it can be scheduled to occur
* in the future. It may also fail to execute for some reason in
* which case the sender needs to be notified. When the sender
* sends a transaction they will assign it an ID which will be
* passed back to the sender if the transaction fails for some
* reason.
*/
struct deferred_transaction : public transaction
{
uint64_t sender_id; /// ID assigned by sender of generated, accessible via WASM api when executing normal or error
account_name sender; /// receives error handler callback
time_point_sec execute_after; /// delayed exeuction
deferred_transaction() = default;
deferred_transaction(uint32_t sender_id, account_name sender, time_point_sec execute_after, const transaction& txn)
: transaction(txn),
sender_id(sender_id),
sender(sender),
execute_after(execute_after)
{}
};
struct deferred_reference {
deferred_reference( const account_name& sender, uint64_t sender_id)
:sender(sender),sender_id(sender_id)
{}
account_name sender;
uint64_t sender_id;
};
struct data_access_info {
enum access_type {
read = 0, ///< scope was read by this action
write = 1, ///< scope was (potentially) written to by this action
};
access_type type;
account_name code;
scope_name scope;
uint64_t sequence;
};
struct action_trace {
account_name receiver;
action act;
string console;
uint32_t region_id;
uint32_t cycle_index;
vector<data_access_info> data_access;
};
struct transaction_trace : transaction_receipt {
using transaction_receipt::transaction_receipt;
vector<action_trace> action_traces;
vector<fc::static_variant<deferred_transaction, deferred_reference>> deferred_transaction_requests;
};
} } // eosio::chain
FC_REFLECT( eosio::chain::permission_level, (actor)(permission) )
FC_REFLECT( eosio::chain::action, (account)(name)(authorization)(data) )
FC_REFLECT( eosio::chain::transaction_header, (expiration)(region)(ref_block_num)(ref_block_prefix)(packed_bandwidth_words)(context_free_cpu_bandwidth) )
FC_REFLECT_DERIVED( eosio::chain::transaction, (eosio::chain::transaction_header), (context_free_actions)(actions) )
FC_REFLECT_DERIVED( eosio::chain::signed_transaction, (eosio::chain::transaction), (signatures)(context_free_data) )
FC_REFLECT_ENUM( eosio::chain::packed_transaction::compression_type, (none)(zlib))
FC_REFLECT( eosio::chain::packed_transaction, (signatures)(compression)(data) )
FC_REFLECT_DERIVED( eosio::chain::deferred_transaction, (eosio::chain::transaction), (sender_id)(sender)(execute_after) )
FC_REFLECT( eosio::chain::deferred_reference, (sender_id)(sender) )
FC_REFLECT_ENUM( eosio::chain::data_access_info::access_type, (read)(write))
FC_REFLECT( eosio::chain::data_access_info, (type)(code)(scope)(sequence))
FC_REFLECT( eosio::chain::action_trace, (receiver)(act)(console)(region_id)(cycle_index)(data_access) )
FC_REFLECT( eosio::chain::transaction_receipt, (status)(id))
FC_REFLECT_ENUM( eosio::chain::transaction_receipt::status_enum, (executed)(soft_fail)(hard_fail)(delayed) )
FC_REFLECT_DERIVED( eosio::chain::transaction_trace, (eosio::chain::transaction_receipt), (action_traces)(deferred_transaction_requests) )
<commit_msg>Fix unpack packed_transaction struct error<commit_after>/**
* @file
* @copyright defined in eos/LICENSE.txt
*/
#pragma once
#include <eosio/chain/types.hpp>
#include <numeric>
namespace eosio { namespace chain {
struct permission_level {
account_name actor;
permission_name permission;
};
/**
* An action is performed by an actor, aka an account. It may
* be created explicitly and authorized by signatures or might be
* generated implicitly by executing application code.
*
* This follows the design pattern of React Flux where actions are
* named and then dispatched to one or more action handlers (aka stores).
* In the context of eosio, every action is dispatched to the handler defined
* by account 'scope' and function 'name', but the default handler may also
* forward the action to any number of additional handlers. Any application
* can write a handler for "scope::name" that will get executed if and only if
* this action is forwarded to that application.
*
* Each action may require the permission of specific actors. Actors can define
* any number of permission levels. The actors and their respective permission
* levels are declared on the action and validated independently of the executing
* application code. An application code will check to see if the required authorization
* were properly declared when it executes.
*/
struct action {
account_name account;
action_name name;
vector<permission_level> authorization;
bytes data;
action(){}
template<typename T, std::enable_if_t<std::is_base_of<bytes, T>::value, int> = 1>
action( vector<permission_level> auth, const T& value ) {
account = T::get_account();
name = T::get_name();
authorization = move(auth);
data.assign(value.data(), value.data() + value.size());
}
template<typename T, std::enable_if_t<!std::is_base_of<bytes, T>::value, int> = 1>
action( vector<permission_level> auth, const T& value ) {
account = T::get_account();
name = T::get_name();
authorization = move(auth);
data = fc::raw::pack(value);
}
action( vector<permission_level> auth, account_name account, action_name name, const bytes& data )
: account(account), name(name), authorization(move(auth)), data(data) {
}
template<typename T>
T data_as()const {
FC_ASSERT( account == T::get_account() );
FC_ASSERT( name == T::get_name() );
return fc::raw::unpack<T>(data);
}
};
struct action_notice : public action {
account_name receiver;
};
/**
* When a transaction is referenced by a block it could imply one of several outcomes which
* describe the state-transition undertaken by the block producer.
*/
struct transaction_receipt {
enum status_enum {
executed = 0, ///< succeed, no error handler executed
soft_fail = 1, ///< objectively failed (not executed), error handler executed
hard_fail = 2, ///< objectively failed and error handler objectively failed thus no state change
delayed = 3 ///< transaction delayed
};
transaction_receipt() : status(hard_fail) {}
transaction_receipt( transaction_id_type tid ):status(executed),id(tid){}
fc::enum_type<uint8_t,status_enum> status;
transaction_id_type id;
};
/**
* The transaction header contains the fixed-sized data
* associated with each transaction. It is separated from
* the transaction body to facilitate partial parsing of
* transactions without requiring dynamic memory allocation.
*
* All transactions have an expiration time after which they
* may no longer be included in the blockchain. Once a block
* with a block_header::timestamp greater than expiration is
* deemed irreversible, then a user can safely trust the transaction
* will never be included.
*
* Each region is an independent blockchain, it is included as routing
* information for inter-blockchain communication. A contract in this
* region might generate or authorize a transaction intended for a foreign
* region.
*/
struct transaction_header {
time_point_sec expiration; ///< the time at which a transaction expires
uint16_t region = 0; ///< the computational memory region this transaction applies to.
uint16_t ref_block_num = 0; ///< specifies a block num in the last 2^16 blocks.
uint32_t ref_block_prefix = 0; ///< specifies the lower 32 bits of the blockid at get_ref_blocknum
uint16_t packed_bandwidth_words = 0; /// number of 8 byte words this transaction can compress into
uint16_t context_free_cpu_bandwidth = 0; /// number of CPU usage units to bill transaction for
/**
* @return the absolute block number given the relative ref_block_num
*/
block_num_type get_ref_blocknum( block_num_type head_blocknum )const {
return ((head_blocknum/0xffff)*0xffff) + head_blocknum%0xffff;
}
void set_reference_block( const block_id_type& reference_block );
bool verify_reference_block( const block_id_type& reference_block )const;
};
/**
* A transaction consits of a set of messages which must all be applied or
* all are rejected. These messages have access to data within the given
* read and write scopes.
*/
struct transaction : public transaction_header {
vector<action> context_free_actions;
vector<action> actions;
transaction_id_type id()const;
digest_type sig_digest( const chain_id_type& chain_id, const vector<bytes>& cfd = vector<bytes>() )const;
flat_set<public_key_type> get_signature_keys( const vector<signature_type>& signatures, const chain_id_type& chain_id, const vector<bytes>& cfd = vector<bytes>() )const;
};
struct signed_transaction : public transaction
{
signed_transaction() = default;
// signed_transaction( const signed_transaction& ) = default;
// signed_transaction( signed_transaction&& ) = default;
signed_transaction( transaction&& trx, const vector<signature_type>& signatures, const vector<bytes>& context_free_data)
: transaction(std::forward<transaction>(trx))
, signatures(signatures)
, context_free_data(context_free_data)
{
}
vector<signature_type> signatures;
vector<bytes> context_free_data; ///< for each context-free action, there is an entry here
const signature_type& sign(const private_key_type& key, const chain_id_type& chain_id);
signature_type sign(const private_key_type& key, const chain_id_type& chain_id)const;
flat_set<public_key_type> get_signature_keys( const chain_id_type& chain_id )const;
};
struct packed_transaction {
enum compression_type {
none,
zlib,
};
packed_transaction() = default;
explicit packed_transaction(const transaction& t, compression_type _compression = none)
{
set_transaction(t, _compression);
}
explicit packed_transaction(const signed_transaction& t, compression_type _compression = none)
:signatures(t.signatures)
,context_free_data(t.context_free_data)
{
set_transaction(t, _compression);
}
explicit packed_transaction(signed_transaction&& t, compression_type _compression = none)
:signatures(std::move(t.signatures))
,context_free_data(std::move(t.context_free_data))
{
set_transaction(t, _compression);
}
vector<signature_type> signatures;
vector<bytes> context_free_data;
compression_type compression;
bytes data;
bytes get_raw_transaction()const;
transaction get_transaction()const;
signed_transaction get_signed_transaction()const;
void set_transaction(const transaction& t, compression_type _compression = none);
};
/**
* When a transaction is generated it can be scheduled to occur
* in the future. It may also fail to execute for some reason in
* which case the sender needs to be notified. When the sender
* sends a transaction they will assign it an ID which will be
* passed back to the sender if the transaction fails for some
* reason.
*/
struct deferred_transaction : public transaction
{
uint64_t sender_id; /// ID assigned by sender of generated, accessible via WASM api when executing normal or error
account_name sender; /// receives error handler callback
time_point_sec execute_after; /// delayed exeuction
deferred_transaction() = default;
deferred_transaction(uint32_t sender_id, account_name sender, time_point_sec execute_after, const transaction& txn)
: transaction(txn),
sender_id(sender_id),
sender(sender),
execute_after(execute_after)
{}
};
struct deferred_reference {
deferred_reference( const account_name& sender, uint64_t sender_id)
:sender(sender),sender_id(sender_id)
{}
account_name sender;
uint64_t sender_id;
};
struct data_access_info {
enum access_type {
read = 0, ///< scope was read by this action
write = 1, ///< scope was (potentially) written to by this action
};
access_type type;
account_name code;
scope_name scope;
uint64_t sequence;
};
struct action_trace {
account_name receiver;
action act;
string console;
uint32_t region_id;
uint32_t cycle_index;
vector<data_access_info> data_access;
};
struct transaction_trace : transaction_receipt {
using transaction_receipt::transaction_receipt;
vector<action_trace> action_traces;
vector<fc::static_variant<deferred_transaction, deferred_reference>> deferred_transaction_requests;
};
} } // eosio::chain
FC_REFLECT( eosio::chain::permission_level, (actor)(permission) )
FC_REFLECT( eosio::chain::action, (account)(name)(authorization)(data) )
FC_REFLECT( eosio::chain::transaction_header, (expiration)(region)(ref_block_num)(ref_block_prefix)(packed_bandwidth_words)(context_free_cpu_bandwidth) )
FC_REFLECT_DERIVED( eosio::chain::transaction, (eosio::chain::transaction_header), (context_free_actions)(actions) )
FC_REFLECT_DERIVED( eosio::chain::signed_transaction, (eosio::chain::transaction), (signatures)(context_free_data) )
FC_REFLECT_ENUM( eosio::chain::packed_transaction::compression_type, (none)(zlib))
FC_REFLECT( eosio::chain::packed_transaction, (signatures)(context_free_data)(compression)(data) )
FC_REFLECT_DERIVED( eosio::chain::deferred_transaction, (eosio::chain::transaction), (sender_id)(sender)(execute_after) )
FC_REFLECT( eosio::chain::deferred_reference, (sender_id)(sender) )
FC_REFLECT_ENUM( eosio::chain::data_access_info::access_type, (read)(write))
FC_REFLECT( eosio::chain::data_access_info, (type)(code)(scope)(sequence))
FC_REFLECT( eosio::chain::action_trace, (receiver)(act)(console)(region_id)(cycle_index)(data_access) )
FC_REFLECT( eosio::chain::transaction_receipt, (status)(id))
FC_REFLECT_ENUM( eosio::chain::transaction_receipt::status_enum, (executed)(soft_fail)(hard_fail)(delayed) )
FC_REFLECT_DERIVED( eosio::chain::transaction_trace, (eosio::chain::transaction_receipt), (action_traces)(deferred_transaction_requests) )
<|endoftext|> |
<commit_before>#ifndef CPIMPL
#define CPIMPL
#include<memory> //make_unique, unique_ptr
#include<utility> //forward, move
namespace nTool
{
template<class T>
class CPimpl //a class to help you use pimpl easily
{
std::unique_ptr<T> p_;
public:
CPimpl()
:p_{std::make_unique<T>()}{}
CPimpl(const CPimpl &val)
:p_{std::make_unique<T>(val.get())}{}
CPimpl(CPimpl &&rVal) noexcept
:p_{std::move(rVal.p_)}{}
//as smart pointer, use () instead of {}
template<class ... Args>
CPimpl(Args &&...args)
:p_(std::make_unique<T>(std::forward<Args>(args)...)){}
inline T& get() const noexcept
{
return *p_.get();
}
CPimpl& operator=(const CPimpl &val)
{
get()=val.get();
return *this;
}
CPimpl& operator=(CPimpl &&rVal) noexcept
{
p_=std::move(rVal.p_);
return *this;
}
explicit operator bool() const noexcept
{
return p_.operator bool();
}
~CPimpl(){}
};
}
#endif<commit_msg>fix CPimpl::get<commit_after>#ifndef CPIMPL
#define CPIMPL
#include<memory> //make_unique, unique_ptr
#include<utility> //forward, move
namespace nTool
{
template<class T>
class CPimpl //a class to help you use pimpl easily
{
std::unique_ptr<T> p_;
public:
CPimpl()
:p_{std::make_unique<T>()}{}
CPimpl(const CPimpl &val)
:p_{std::make_unique<T>(val.get())}{}
CPimpl(CPimpl &&rVal) noexcept
:p_{std::move(rVal.p_)}{}
//as smart pointer, use () instead of {}
template<class ... Args>
CPimpl(Args &&...args)
:p_(std::make_unique<T>(std::forward<Args>(args)...)){}
inline T& get() const noexcept
{
return *p_;
}
CPimpl& operator=(const CPimpl &val)
{
get()=val.get();
return *this;
}
CPimpl& operator=(CPimpl &&rVal) noexcept
{
p_=std::move(rVal.p_);
return *this;
}
explicit operator bool() const noexcept
{
return p_.operator bool();
}
~CPimpl(){}
};
}
#endif<|endoftext|> |
<commit_before>#include "qtdcmDataSourceSerieToolBox.h"
#include <QtDcmPreviewWidget.h>
#include <QtDcmSerieInfoWidget.h>
#include <QtDcmImportWidget.h>
#include <medPluginManager.h>
class qtdcmDataSourceSerieToolBoxPrivate
{
public:
QWidget *parent;
QtDcmPreviewWidget * preview;
QtDcmSerieInfoWidget * serieInfoWidget;
QtDcmImportWidget * importWidget;
};
qtdcmDataSourceSerieToolBox::qtdcmDataSourceSerieToolBox ( QWidget* parent ) : medToolBox ( parent ), d ( new qtdcmDataSourceSerieToolBoxPrivate )
{
d->parent = parent;
d->preview = new QtDcmPreviewWidget(this);
//d->preview->previewGroupBox->setTitle("");
d->serieInfoWidget = new QtDcmSerieInfoWidget(this);
//d->serieInfoWidget->infosGroupBox->setTitle("");
d->importWidget = new QtDcmImportWidget(this);
this->addWidget(d->preview);
this->addWidget(d->serieInfoWidget);
this->addWidget(d->importWidget);
this->setTitle("Series preview and import");
// Add about plugin
medPluginManager* pm = medPluginManager::instance();
dtkPlugin* plugin = pm->plugin ( "qtdcmDataSourcePlugin" );
setAboutPluginButton ( plugin );
setAboutPluginVisibility( true );
}
qtdcmDataSourceSerieToolBox::~qtdcmDataSourceSerieToolBox()
{
if (d)
delete d;
d = NULL;
}
QtDcmPreviewWidget* qtdcmDataSourceSerieToolBox::getPreviewWidget()
{
return d->preview;
}
QtDcmSerieInfoWidget* qtdcmDataSourceSerieToolBox::getSerieInfoWidget()
{
return d->serieInfoWidget;
}
QtDcmImportWidget* qtdcmDataSourceSerieToolBox::getImportWidget()
{
return d->importWidget;
}
<commit_msg>Remove comments<commit_after>#include "qtdcmDataSourceSerieToolBox.h"
#include <QtDcmPreviewWidget.h>
#include <QtDcmSerieInfoWidget.h>
#include <QtDcmImportWidget.h>
#include <medPluginManager.h>
class qtdcmDataSourceSerieToolBoxPrivate
{
public:
QWidget *parent;
QtDcmPreviewWidget * preview;
QtDcmSerieInfoWidget * serieInfoWidget;
QtDcmImportWidget * importWidget;
};
qtdcmDataSourceSerieToolBox::qtdcmDataSourceSerieToolBox ( QWidget* parent ) : medToolBox ( parent ), d ( new qtdcmDataSourceSerieToolBoxPrivate )
{
d->parent = parent;
d->preview = new QtDcmPreviewWidget(this);
d->serieInfoWidget = new QtDcmSerieInfoWidget(this);
d->importWidget = new QtDcmImportWidget(this);
this->addWidget(d->preview);
this->addWidget(d->serieInfoWidget);
this->addWidget(d->importWidget);
this->setTitle("Series preview and import");
// Add about plugin
medPluginManager* pm = medPluginManager::instance();
dtkPlugin* plugin = pm->plugin ( "qtdcmDataSourcePlugin" );
setAboutPluginButton ( plugin );
setAboutPluginVisibility( true );
}
qtdcmDataSourceSerieToolBox::~qtdcmDataSourceSerieToolBox()
{
if (d)
delete d;
d = NULL;
}
QtDcmPreviewWidget* qtdcmDataSourceSerieToolBox::getPreviewWidget()
{
return d->preview;
}
QtDcmSerieInfoWidget* qtdcmDataSourceSerieToolBox::getSerieInfoWidget()
{
return d->serieInfoWidget;
}
QtDcmImportWidget* qtdcmDataSourceSerieToolBox::getImportWidget()
{
return d->importWidget;
}
<|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 "remoting/host/capturer_mac.h"
#include <stddef.h>
#include <OpenGL/CGLMacro.h>
namespace remoting {
CapturerMac::CapturerMac(MessageLoop* message_loop)
: Capturer(message_loop),
cgl_context_(NULL),
width_(0),
height_(0),
bytes_per_row_(0) {
// TODO(dmaclach): move this initialization out into session_manager,
// or at least have session_manager call into here to initialize it.
CGError err =
CGRegisterScreenRefreshCallback(CapturerMac::ScreenRefreshCallback,
this);
DCHECK_EQ(err, kCGErrorSuccess);
err = CGScreenRegisterMoveCallback(CapturerMac::ScreenUpdateMoveCallback,
this);
DCHECK_EQ(err, kCGErrorSuccess);
err = CGDisplayRegisterReconfigurationCallback(
CapturerMac::DisplaysReconfiguredCallback, this);
DCHECK_EQ(err, kCGErrorSuccess);
ScreenConfigurationChanged();
}
CapturerMac::~CapturerMac() {
ReleaseBuffers();
CGUnregisterScreenRefreshCallback(CapturerMac::ScreenRefreshCallback, this);
CGScreenUnregisterMoveCallback(CapturerMac::ScreenUpdateMoveCallback, this);
CGDisplayRemoveReconfigurationCallback(
CapturerMac::DisplaysReconfiguredCallback, this);
}
void CapturerMac::ReleaseBuffers() {
if (cgl_context_) {
CGLDestroyContext(cgl_context_);
cgl_context_ = NULL;
}
}
void CapturerMac::ScreenConfigurationChanged() {
ReleaseBuffers();
CGDirectDisplayID mainDevice = CGMainDisplayID();
width_ = CGDisplayPixelsWide(mainDevice);
height_ = CGDisplayPixelsHigh(mainDevice);
pixel_format_ = media::VideoFrame::RGB32;
bytes_per_row_ = width_ * sizeof(uint32_t);
size_t buffer_size = height_ * bytes_per_row_;
for (int i = 0; i < kNumBuffers; ++i) {
buffers_[i].reset(new uint8[buffer_size]);
}
flip_buffer_.reset(new uint8[buffer_size]);
CGLPixelFormatAttribute attributes[] = {
kCGLPFAFullScreen,
kCGLPFADisplayMask,
(CGLPixelFormatAttribute)CGDisplayIDToOpenGLDisplayMask(mainDevice),
(CGLPixelFormatAttribute)0
};
CGLPixelFormatObj pixel_format = NULL;
GLint matching_pixel_format_count = 0;
CGLError err = CGLChoosePixelFormat(attributes,
&pixel_format,
&matching_pixel_format_count);
DCHECK_EQ(err, kCGLNoError);
err = CGLCreateContext(pixel_format, NULL, &cgl_context_);
DCHECK_EQ(err, kCGLNoError);
CGLDestroyPixelFormat(pixel_format);
CGLSetFullScreen(cgl_context_);
CGLSetCurrentContext(cgl_context_);
}
void CapturerMac::CalculateInvalidRects() {
// Since the Mac gets its list of invalid rects via calls to InvalidateRect(),
// this step only needs to perform post-processing optimizations on the rect
// list (if needed).
}
void CapturerMac::CaptureRects(const InvalidRects& rects,
CaptureCompletedCallback* callback) {
CGLContextObj CGL_MACRO_CONTEXT = cgl_context_;
glReadBuffer(GL_FRONT);
glPushClientAttrib(GL_CLIENT_PIXEL_STORE_BIT);
glPixelStorei(GL_PACK_ALIGNMENT, 4); // Force 4-byte alignment.
glPixelStorei(GL_PACK_ROW_LENGTH, 0);
glPixelStorei(GL_PACK_SKIP_ROWS, 0);
glPixelStorei(GL_PACK_SKIP_PIXELS, 0);
// Read a block of pixels from the frame buffer.
uint8* flip_buffer = flip_buffer_.get();
uint8* current_buffer = buffers_[current_buffer_].get();
glReadPixels(0, 0, width_, height_, GL_BGRA, GL_UNSIGNED_BYTE, flip_buffer);
glPopClientAttrib();
// OpenGL reads with a vertical flip, and sadly there is no optimized
// way to get it flipped automatically.
for (int y = 0; y < height_; ++y) {
uint8* flip_row = &(flip_buffer[y * bytes_per_row_]);
uint8* current_row =
&(current_buffer[(height_ - (y + 1)) * bytes_per_row_]);
memcpy(current_row, flip_row, bytes_per_row_);
}
DataPlanes planes;
planes.data[0] = buffers_[current_buffer_].get();
planes.strides[0] = bytes_per_row_;
scoped_refptr<CaptureData> data(
new CaptureData(planes, width_, height_, pixel_format()));
data->mutable_dirty_rects() = rects;
FinishCapture(data, callback);
}
void CapturerMac::ScreenRefresh(CGRectCount count, const CGRect *rect_array) {
InvalidRects rects;
for (CGRectCount i = 0; i < count; ++i) {
CGRect rect = rect_array[i];
rect.origin.y = height_ - rect.size.height;
rects.insert(gfx::Rect(rect));
}
InvalidateRects(rects);
}
void CapturerMac::ScreenUpdateMove(CGScreenUpdateMoveDelta delta,
size_t count,
const CGRect *rect_array) {
InvalidRects rects;
for (CGRectCount i = 0; i < count; ++i) {
CGRect rect = rect_array[i];
rect.origin.y = height_ - rect.size.height;
rects.insert(gfx::Rect(rect));
rect = CGRectOffset(rect, delta.dX, delta.dY);
rects.insert(gfx::Rect(rect));
}
InvalidateRects(rects);
}
void CapturerMac::ScreenRefreshCallback(CGRectCount count,
const CGRect *rect_array,
void *user_parameter) {
CapturerMac *capturer = reinterpret_cast<CapturerMac *>(user_parameter);
capturer->ScreenRefresh(count, rect_array);
}
void CapturerMac::ScreenUpdateMoveCallback(CGScreenUpdateMoveDelta delta,
size_t count,
const CGRect *rect_array,
void *user_parameter) {
CapturerMac *capturer = reinterpret_cast<CapturerMac *>(user_parameter);
capturer->ScreenUpdateMove(delta, count, rect_array);
}
void CapturerMac::DisplaysReconfiguredCallback(
CGDirectDisplayID display,
CGDisplayChangeSummaryFlags flags,
void *user_parameter) {
if ((display == CGMainDisplayID()) &&
!(flags & kCGDisplayBeginConfigurationFlag)) {
CapturerMac *capturer = reinterpret_cast<CapturerMac *>(user_parameter);
capturer->ScreenConfigurationChanged();
}
}
// static
Capturer* Capturer::Create(MessageLoop* message_loop) {
return new CapturerMac(message_loop);
}
} // namespace remoting
<commit_msg>Don't translate dirty rectangles in Mac capturer.<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 "remoting/host/capturer_mac.h"
#include <stddef.h>
#include <OpenGL/CGLMacro.h>
namespace remoting {
CapturerMac::CapturerMac(MessageLoop* message_loop)
: Capturer(message_loop),
cgl_context_(NULL),
width_(0),
height_(0),
bytes_per_row_(0) {
// TODO(dmaclach): move this initialization out into session_manager,
// or at least have session_manager call into here to initialize it.
CGError err =
CGRegisterScreenRefreshCallback(CapturerMac::ScreenRefreshCallback,
this);
DCHECK_EQ(err, kCGErrorSuccess);
err = CGScreenRegisterMoveCallback(CapturerMac::ScreenUpdateMoveCallback,
this);
DCHECK_EQ(err, kCGErrorSuccess);
err = CGDisplayRegisterReconfigurationCallback(
CapturerMac::DisplaysReconfiguredCallback, this);
DCHECK_EQ(err, kCGErrorSuccess);
ScreenConfigurationChanged();
}
CapturerMac::~CapturerMac() {
ReleaseBuffers();
CGUnregisterScreenRefreshCallback(CapturerMac::ScreenRefreshCallback, this);
CGScreenUnregisterMoveCallback(CapturerMac::ScreenUpdateMoveCallback, this);
CGDisplayRemoveReconfigurationCallback(
CapturerMac::DisplaysReconfiguredCallback, this);
}
void CapturerMac::ReleaseBuffers() {
if (cgl_context_) {
CGLDestroyContext(cgl_context_);
cgl_context_ = NULL;
}
}
void CapturerMac::ScreenConfigurationChanged() {
ReleaseBuffers();
CGDirectDisplayID mainDevice = CGMainDisplayID();
width_ = CGDisplayPixelsWide(mainDevice);
height_ = CGDisplayPixelsHigh(mainDevice);
pixel_format_ = media::VideoFrame::RGB32;
bytes_per_row_ = width_ * sizeof(uint32_t);
size_t buffer_size = height_ * bytes_per_row_;
for (int i = 0; i < kNumBuffers; ++i) {
buffers_[i].reset(new uint8[buffer_size]);
}
flip_buffer_.reset(new uint8[buffer_size]);
CGLPixelFormatAttribute attributes[] = {
kCGLPFAFullScreen,
kCGLPFADisplayMask,
(CGLPixelFormatAttribute)CGDisplayIDToOpenGLDisplayMask(mainDevice),
(CGLPixelFormatAttribute)0
};
CGLPixelFormatObj pixel_format = NULL;
GLint matching_pixel_format_count = 0;
CGLError err = CGLChoosePixelFormat(attributes,
&pixel_format,
&matching_pixel_format_count);
DCHECK_EQ(err, kCGLNoError);
err = CGLCreateContext(pixel_format, NULL, &cgl_context_);
DCHECK_EQ(err, kCGLNoError);
CGLDestroyPixelFormat(pixel_format);
CGLSetFullScreen(cgl_context_);
CGLSetCurrentContext(cgl_context_);
}
void CapturerMac::CalculateInvalidRects() {
// Since the Mac gets its list of invalid rects via calls to InvalidateRect(),
// this step only needs to perform post-processing optimizations on the rect
// list (if needed).
}
void CapturerMac::CaptureRects(const InvalidRects& rects,
CaptureCompletedCallback* callback) {
CGLContextObj CGL_MACRO_CONTEXT = cgl_context_;
glReadBuffer(GL_FRONT);
glPushClientAttrib(GL_CLIENT_PIXEL_STORE_BIT);
glPixelStorei(GL_PACK_ALIGNMENT, 4); // Force 4-byte alignment.
glPixelStorei(GL_PACK_ROW_LENGTH, 0);
glPixelStorei(GL_PACK_SKIP_ROWS, 0);
glPixelStorei(GL_PACK_SKIP_PIXELS, 0);
// Read a block of pixels from the frame buffer.
uint8* flip_buffer = flip_buffer_.get();
uint8* current_buffer = buffers_[current_buffer_].get();
glReadPixels(0, 0, width_, height_, GL_BGRA, GL_UNSIGNED_BYTE, flip_buffer);
glPopClientAttrib();
// OpenGL reads with a vertical flip, and sadly there is no optimized
// way to get it flipped automatically.
for (int y = 0; y < height_; ++y) {
uint8* flip_row = &(flip_buffer[y * bytes_per_row_]);
uint8* current_row =
&(current_buffer[(height_ - (y + 1)) * bytes_per_row_]);
memcpy(current_row, flip_row, bytes_per_row_);
}
DataPlanes planes;
planes.data[0] = buffers_[current_buffer_].get();
planes.strides[0] = bytes_per_row_;
scoped_refptr<CaptureData> data(
new CaptureData(planes, width_, height_, pixel_format()));
data->mutable_dirty_rects() = rects;
FinishCapture(data, callback);
}
void CapturerMac::ScreenRefresh(CGRectCount count, const CGRect *rect_array) {
InvalidRects rects;
for (CGRectCount i = 0; i < count; ++i) {
rects.insert(gfx::Rect(rect_array[i]));
}
InvalidateRects(rects);
}
void CapturerMac::ScreenUpdateMove(CGScreenUpdateMoveDelta delta,
size_t count,
const CGRect *rect_array) {
InvalidRects rects;
for (CGRectCount i = 0; i < count; ++i) {
CGRect rect = rect_array[i];
rects.insert(gfx::Rect(rect));
rect = CGRectOffset(rect, delta.dX, delta.dY);
rects.insert(gfx::Rect(rect));
}
InvalidateRects(rects);
}
void CapturerMac::ScreenRefreshCallback(CGRectCount count,
const CGRect *rect_array,
void *user_parameter) {
CapturerMac *capturer = reinterpret_cast<CapturerMac *>(user_parameter);
capturer->ScreenRefresh(count, rect_array);
}
void CapturerMac::ScreenUpdateMoveCallback(CGScreenUpdateMoveDelta delta,
size_t count,
const CGRect *rect_array,
void *user_parameter) {
CapturerMac *capturer = reinterpret_cast<CapturerMac *>(user_parameter);
capturer->ScreenUpdateMove(delta, count, rect_array);
}
void CapturerMac::DisplaysReconfiguredCallback(
CGDirectDisplayID display,
CGDisplayChangeSummaryFlags flags,
void *user_parameter) {
if ((display == CGMainDisplayID()) &&
!(flags & kCGDisplayBeginConfigurationFlag)) {
CapturerMac *capturer = reinterpret_cast<CapturerMac *>(user_parameter);
capturer->ScreenConfigurationChanged();
}
}
// static
Capturer* Capturer::Create(MessageLoop* message_loop) {
return new CapturerMac(message_loop);
}
} // namespace remoting
<|endoftext|> |
<commit_before>/*
* Copyright (c) 2013 Opposite Renderer
* For the full copyright and license information, please view the LICENSE.txt
* file that was distributed with this source code.
*/
/*
* This is the render server main entry. The render server accepts connections from clients
* and will perform rendering per request
*/
#include <iostream>
#include <exception>
#include <QObject>
#include "gui/ServerWindow.hxx"
#include <QApplication>
#include <QMessageBox>
#include "server/RenderServer.hxx"
//#include <vld.h>
int main( int argc, char** argv )
{
QApplication app(argc, argv);
app.setOrganizationName("Opposite Renderer");
app.setApplicationName("Opposite Renderer");
try {
RenderServer renderServer;
ServerWindow serverWindow(NULL, renderServer);
serverWindow.show();
int appCode = app.exec();
renderServer.wait();
return appCode;
} catch(std::exception ex){
QString error = QString("An unexpected error ocurred during execution:\n\t%1\nApplication will now quit.").arg(ex.what());
QMessageBox::critical(nullptr, "Critical", error);
return 1;
}
}
<commit_msg>Adds Optix error handling.<commit_after>/*
* Copyright (c) 2013 Opposite Renderer
* For the full copyright and license information, please view the LICENSE.txt
* file that was distributed with this source code.
*/
/*
* This is the render server main entry. The render server accepts connections from clients
* and will perform rendering per request
*/
#include <iostream>
#include <exception>
#include <QObject>
#include "gui/ServerWindow.hxx"
#include <QApplication>
#include <QMessageBox>
#include "server/RenderServer.hxx"
#include <optix.h>
//#include <vld.h>
int main( int argc, char** argv )
{
QApplication app(argc, argv);
app.setOrganizationName("Opposite Renderer");
app.setApplicationName("Opposite Renderer");
try {
RenderServer renderServer;
ServerWindow serverWindow(NULL, renderServer);
serverWindow.show();
int appCode = app.exec();
renderServer.wait();
return appCode;
} catch(optix::Exception ex){
QString error = QString("An OptiX unexpected error ocurred during execution:\n\t%2(cod: %1)\nApplication will now quit.").arg(QString(ex.getErrorCode()), QString(ex.getErrorString().c_str()));
QMessageBox::critical(nullptr, "Critical", error);
return 1;
} catch(std::exception ex){
QString error = QString("An unexpected error ocurred during execution:\n\t%1\nApplication will now quit.").arg(ex.what());
QMessageBox::critical(nullptr, "Critical", error);
return 1;
}
}
<|endoftext|> |
<commit_before>/******************************************************************************
* Copyright 2018 The Apollo Authors. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*****************************************************************************/
/**
* @file
**/
#include "modules/planning/scenarios/side_pass/side_pass_stop_on_wait_point.h"
#include <algorithm>
#include <vector>
#include "modules/common/configs/vehicle_config_helper.h"
#include "modules/common/proto/pnc_point.pb.h"
#include "modules/planning/common/frame.h"
#include "modules/planning/common/speed_profile_generator.h"
namespace apollo {
namespace planning {
namespace scenario {
namespace side_pass {
using apollo::common::TrajectoryPoint;
using apollo::common::PathPoint;
using apollo::common::math::Vec2d;
constexpr double kExtraMarginforStopOnWaitPointStage = 3.0;
Stage::StageStatus SidePassStopOnWaitPoint::Process(
const TrajectoryPoint& planning_start_point, Frame* frame) {
const ReferenceLineInfo& reference_line_info =
frame->reference_line_info().front();
const ReferenceLine& reference_line = reference_line_info.reference_line();
const PathDecision& path_decision = reference_line_info.path_decision();
if (GetContext()->path_data_.discretized_path().path_points().empty()) {
AERROR << "path data is empty.";
return Stage::ERROR;
}
if (!GetContext()->path_data_.UpdateFrenetFramePath(&reference_line)) {
return Stage::ERROR;
}
const auto adc_frenet_frame_point_ =
reference_line.GetFrenetPoint(frame->PlanningStartPoint());
if (!GetContext()->path_data_.LeftTrimWithRefS(adc_frenet_frame_point_.s(),
adc_frenet_frame_point_.l())) {
return Stage::ERROR;
}
PathPoint first_path_point =
GetContext()->path_data_.discretized_path().path_points().front();
PathPoint last_path_point;
if (!GetMoveForwardLastPathPoint(reference_line, &last_path_point)) {
AERROR << "Fail to get move forward last path point.";
return Stage::ERROR;
}
ADEBUG << "first_path_point: " << first_path_point.ShortDebugString();
ADEBUG << "last_path_point : " << first_path_point.ShortDebugString();
double move_forward_distance = last_path_point.s() - first_path_point.s();
ADEBUG << "move_forward_distance: " << move_forward_distance;
if (!IsFarAwayFromObstacles(reference_line, path_decision.obstacles(),
first_path_point, last_path_point)) {
// wait here, do nothing this cycle.
AINFO << "waiting until obstacles are far away.";
return Stage::RUNNING;
}
// (1) call proceed with cautious
constexpr double kSidePassCreepSpeed = 2.33; // m/s
auto& rfl_info = frame->mutable_reference_line_info()->front();
*(rfl_info.mutable_speed_data()) =
SpeedProfileGenerator::GenerateFixedDistanceCreepProfile(
move_forward_distance, kSidePassCreepSpeed);
// (2) combine path and speed.
*(rfl_info.mutable_path_data()) = GetContext()->path_data_;
rfl_info.set_trajectory_type(ADCTrajectory::NORMAL);
DiscretizedTrajectory trajectory;
if (!rfl_info.CombinePathAndSpeedProfile(
frame->PlanningStartPoint().relative_time(),
frame->PlanningStartPoint().path_point().s(), &trajectory)) {
AERROR << "Fail to aggregate planning trajectory.";
return Stage::RUNNING;
}
rfl_info.SetTrajectory(trajectory);
rfl_info.SetDrivable(true);
constexpr double kBuffer = 0.3;
if (move_forward_distance < kBuffer) {
next_stage_ = ScenarioConfig::SIDE_PASS_DETECT_SAFETY;
}
return Stage::FINISHED;
}
bool SidePassStopOnWaitPoint::IsFarAwayFromObstacles(
const ReferenceLine& reference_line,
const IndexedList<std::string, Obstacle>& indexed_obstacle_list,
const PathPoint& first_path_point, const PathPoint& last_path_point) {
common::SLPoint first_sl_point;
if (!reference_line.XYToSL(Vec2d(first_path_point.x(), first_path_point.y()),
&first_sl_point)) {
AERROR << "Failed to get the projection from TrajectoryPoint onto "
"reference_line";
return false;
}
common::SLPoint last_sl_point;
if (!reference_line.XYToSL(Vec2d(last_path_point.x(), last_path_point.y()),
&last_sl_point)) {
AERROR << "Failed to get the projection from TrajectoryPoint onto "
"reference_line";
return false;
}
// Go through every obstacle, check if there is any in the no_obs_zone,
// which will used by the proceed_with_caution movement.
for (const auto* obstacle : indexed_obstacle_list.Items()) {
if (obstacle->IsVirtual()) {
continue;
}
// Check the s-direction.
double obs_start_s = obstacle->PerceptionSLBoundary().start_s();
double obs_end_s = obstacle->PerceptionSLBoundary().end_s();
if (obs_end_s < first_sl_point.s() ||
obs_start_s > last_sl_point.s() + kExtraMarginforStopOnWaitPointStage) {
continue;
}
// Check the l-direction.
double lane_left_width_at_start_s = 0.0;
double lane_left_width_at_end_s = 0.0;
double lane_right_width_at_start_s = 0.0;
double lane_right_width_at_end_s = 0.0;
reference_line.GetLaneWidth(obs_start_s, &lane_left_width_at_start_s,
&lane_right_width_at_start_s);
reference_line.GetLaneWidth(obs_end_s, &lane_left_width_at_end_s,
&lane_right_width_at_end_s);
double lane_left_width = std::min(std::abs(lane_left_width_at_start_s),
std::abs(lane_left_width_at_end_s));
double lane_right_width = std::min(std::abs(lane_right_width_at_start_s),
std::abs(lane_right_width_at_end_s));
double obs_start_l = obstacle->PerceptionSLBoundary().start_l();
double obs_end_l = obstacle->PerceptionSLBoundary().end_l();
if (obs_start_l < lane_left_width && -obs_end_l < lane_right_width) {
return false;
}
}
return true;
}
bool SidePassStopOnWaitPoint::GetMoveForwardLastPathPoint(
const ReferenceLine& reference_line,
common::PathPoint* const last_path_point) {
int count = 0;
for (const auto& path_point :
GetContext()->path_data_.discretized_path().path_points()) {
// Get the four corner points ABCD of ADC at every path point,
// and check if that's within the current lane until it reaches
// out of current lane.
const auto& vehicle_box =
common::VehicleConfigHelper::Instance()->GetBoundingBox(path_point);
std::vector<Vec2d> ABCDpoints = vehicle_box.GetAllCorners();
bool is_out_of_curr_lane = false;
for (size_t i = 0; i < ABCDpoints.size(); i++) {
// For each corner point, project it onto reference_line
common::SLPoint curr_point_sl;
if (!reference_line.XYToSL(ABCDpoints[i], &curr_point_sl)) {
AERROR << "Failed to get the projection from point onto "
"reference_line";
return false;
}
// Get the lane width at the current s indicated by path_point
double curr_point_left_width = 0.0;
double curr_point_right_width = 0.0;
reference_line.GetLaneWidth(curr_point_sl.s(), &curr_point_left_width,
&curr_point_right_width);
// Check if this corner point is within the lane:
if (curr_point_sl.l() > std::abs(curr_point_left_width) ||
curr_point_sl.l() < -std::abs(curr_point_right_width)) {
is_out_of_curr_lane = true;
break;
}
}
if (is_out_of_curr_lane) {
if (count == 0) {
// The current ADC, without moving at all, is already at least
// partially out of the current lane.
return Stage::FINISHED;
}
break;
} else {
*last_path_point = path_point;
}
// check if the ego car on path_point will partially go into the
// neighbor lane, and retain only those within-lane path-points.
CHECK_GE(path_point.s(), 0.0);
++count;
}
return true;
}
} // namespace side_pass
} // namespace scenario
} // namespace planning
} // namespace apollo
<commit_msg>planning: side pass added traj output for stop on wait point.<commit_after>/******************************************************************************
* Copyright 2018 The Apollo Authors. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*****************************************************************************/
/**
* @file
**/
#include "modules/planning/scenarios/side_pass/side_pass_stop_on_wait_point.h"
#include <algorithm>
#include <vector>
#include "modules/common/configs/vehicle_config_helper.h"
#include "modules/common/proto/pnc_point.pb.h"
#include "modules/planning/common/frame.h"
#include "modules/planning/common/speed_profile_generator.h"
namespace apollo {
namespace planning {
namespace scenario {
namespace side_pass {
using apollo::common::TrajectoryPoint;
using apollo::common::PathPoint;
using apollo::common::math::Vec2d;
constexpr double kExtraMarginforStopOnWaitPointStage = 3.0;
Stage::StageStatus SidePassStopOnWaitPoint::Process(
const TrajectoryPoint& planning_start_point, Frame* frame) {
const ReferenceLineInfo& reference_line_info =
frame->reference_line_info().front();
const ReferenceLine& reference_line = reference_line_info.reference_line();
const PathDecision& path_decision = reference_line_info.path_decision();
if (GetContext()->path_data_.discretized_path().path_points().empty()) {
AERROR << "path data is empty.";
return Stage::ERROR;
}
if (!GetContext()->path_data_.UpdateFrenetFramePath(&reference_line)) {
return Stage::ERROR;
}
const auto adc_frenet_frame_point_ =
reference_line.GetFrenetPoint(frame->PlanningStartPoint());
if (!GetContext()->path_data_.LeftTrimWithRefS(adc_frenet_frame_point_.s(),
adc_frenet_frame_point_.l())) {
return Stage::ERROR;
}
PathPoint first_path_point =
GetContext()->path_data_.discretized_path().path_points().front();
PathPoint last_path_point;
if (!GetMoveForwardLastPathPoint(reference_line, &last_path_point)) {
AERROR << "Fail to get move forward last path point.";
return Stage::ERROR;
}
ADEBUG << "first_path_point: " << first_path_point.ShortDebugString();
ADEBUG << "last_path_point : " << first_path_point.ShortDebugString();
double move_forward_distance = last_path_point.s() - first_path_point.s();
ADEBUG << "move_forward_distance: " << move_forward_distance;
if (!IsFarAwayFromObstacles(reference_line, path_decision.obstacles(),
first_path_point, last_path_point)) {
// wait here, do nothing this cycle.
auto& rfl_info = frame->mutable_reference_line_info()->front();
*(rfl_info.mutable_speed_data()) =
SpeedProfileGenerator::GenerateFallbackSpeedProfile();
rfl_info.set_trajectory_type(ADCTrajectory::NORMAL);
DiscretizedTrajectory trajectory;
if (!rfl_info.CombinePathAndSpeedProfile(
frame->PlanningStartPoint().relative_time(),
frame->PlanningStartPoint().path_point().s(), &trajectory)) {
AERROR << "Fail to aggregate planning trajectory.";
return Stage::RUNNING;
}
rfl_info.SetTrajectory(trajectory);
rfl_info.SetDrivable(true);
AINFO << "waiting until obstacles are far away.";
return Stage::RUNNING;
}
// (1) call proceed with cautious
constexpr double kSidePassCreepSpeed = 2.33; // m/s
auto& rfl_info = frame->mutable_reference_line_info()->front();
*(rfl_info.mutable_speed_data()) =
SpeedProfileGenerator::GenerateFixedDistanceCreepProfile(
move_forward_distance, kSidePassCreepSpeed);
// (2) combine path and speed.
*(rfl_info.mutable_path_data()) = GetContext()->path_data_;
rfl_info.set_trajectory_type(ADCTrajectory::NORMAL);
DiscretizedTrajectory trajectory;
if (!rfl_info.CombinePathAndSpeedProfile(
frame->PlanningStartPoint().relative_time(),
frame->PlanningStartPoint().path_point().s(), &trajectory)) {
AERROR << "Fail to aggregate planning trajectory.";
return Stage::RUNNING;
}
rfl_info.SetTrajectory(trajectory);
rfl_info.SetDrivable(true);
constexpr double kBuffer = 0.3;
if (move_forward_distance < kBuffer) {
next_stage_ = ScenarioConfig::SIDE_PASS_DETECT_SAFETY;
}
return Stage::FINISHED;
}
bool SidePassStopOnWaitPoint::IsFarAwayFromObstacles(
const ReferenceLine& reference_line,
const IndexedList<std::string, Obstacle>& indexed_obstacle_list,
const PathPoint& first_path_point, const PathPoint& last_path_point) {
common::SLPoint first_sl_point;
if (!reference_line.XYToSL(Vec2d(first_path_point.x(), first_path_point.y()),
&first_sl_point)) {
AERROR << "Failed to get the projection from TrajectoryPoint onto "
"reference_line";
return false;
}
common::SLPoint last_sl_point;
if (!reference_line.XYToSL(Vec2d(last_path_point.x(), last_path_point.y()),
&last_sl_point)) {
AERROR << "Failed to get the projection from TrajectoryPoint onto "
"reference_line";
return false;
}
// Go through every obstacle, check if there is any in the no_obs_zone,
// which will used by the proceed_with_caution movement.
for (const auto* obstacle : indexed_obstacle_list.Items()) {
if (obstacle->IsVirtual()) {
continue;
}
// Check the s-direction.
double obs_start_s = obstacle->PerceptionSLBoundary().start_s();
double obs_end_s = obstacle->PerceptionSLBoundary().end_s();
if (obs_end_s < first_sl_point.s() ||
obs_start_s > last_sl_point.s() + kExtraMarginforStopOnWaitPointStage) {
continue;
}
// Check the l-direction.
double lane_left_width_at_start_s = 0.0;
double lane_left_width_at_end_s = 0.0;
double lane_right_width_at_start_s = 0.0;
double lane_right_width_at_end_s = 0.0;
reference_line.GetLaneWidth(obs_start_s, &lane_left_width_at_start_s,
&lane_right_width_at_start_s);
reference_line.GetLaneWidth(obs_end_s, &lane_left_width_at_end_s,
&lane_right_width_at_end_s);
double lane_left_width = std::min(std::abs(lane_left_width_at_start_s),
std::abs(lane_left_width_at_end_s));
double lane_right_width = std::min(std::abs(lane_right_width_at_start_s),
std::abs(lane_right_width_at_end_s));
double obs_start_l = obstacle->PerceptionSLBoundary().start_l();
double obs_end_l = obstacle->PerceptionSLBoundary().end_l();
if (obs_start_l < lane_left_width && -obs_end_l < lane_right_width) {
return false;
}
}
return true;
}
bool SidePassStopOnWaitPoint::GetMoveForwardLastPathPoint(
const ReferenceLine& reference_line,
common::PathPoint* const last_path_point) {
int count = 0;
for (const auto& path_point :
GetContext()->path_data_.discretized_path().path_points()) {
// Get the four corner points ABCD of ADC at every path point,
// and check if that's within the current lane until it reaches
// out of current lane.
const auto& vehicle_box =
common::VehicleConfigHelper::Instance()->GetBoundingBox(path_point);
std::vector<Vec2d> ABCDpoints = vehicle_box.GetAllCorners();
bool is_out_of_curr_lane = false;
for (size_t i = 0; i < ABCDpoints.size(); i++) {
// For each corner point, project it onto reference_line
common::SLPoint curr_point_sl;
if (!reference_line.XYToSL(ABCDpoints[i], &curr_point_sl)) {
AERROR << "Failed to get the projection from point onto "
"reference_line";
return false;
}
// Get the lane width at the current s indicated by path_point
double curr_point_left_width = 0.0;
double curr_point_right_width = 0.0;
reference_line.GetLaneWidth(curr_point_sl.s(), &curr_point_left_width,
&curr_point_right_width);
// Check if this corner point is within the lane:
if (curr_point_sl.l() > std::abs(curr_point_left_width) ||
curr_point_sl.l() < -std::abs(curr_point_right_width)) {
is_out_of_curr_lane = true;
break;
}
}
if (is_out_of_curr_lane) {
if (count == 0) {
// The current ADC, without moving at all, is already at least
// partially out of the current lane.
return Stage::FINISHED;
}
break;
} else {
*last_path_point = path_point;
}
// check if the ego car on path_point will partially go into the
// neighbor lane, and retain only those within-lane path-points.
CHECK_GE(path_point.s(), 0.0);
++count;
}
return true;
}
} // namespace side_pass
} // namespace scenario
} // namespace planning
} // namespace apollo
<|endoftext|> |
<commit_before>// Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "ash/system/ime/tray_ime.h"
#include <vector>
#include "ash/metrics/user_metrics_recorder.h"
#include "ash/root_window_controller.h"
#include "ash/shelf/shelf_widget.h"
#include "ash/shell.h"
#include "ash/system/system_notifier.h"
#include "ash/system/tray/hover_highlight_view.h"
#include "ash/system/tray/system_tray.h"
#include "ash/system/tray/system_tray_delegate.h"
#include "ash/system/tray/system_tray_notifier.h"
#include "ash/system/tray/tray_constants.h"
#include "ash/system/tray/tray_details_view.h"
#include "ash/system/tray/tray_item_more.h"
#include "ash/system/tray/tray_item_view.h"
#include "ash/system/tray/tray_utils.h"
#include "base/logging.h"
#include "base/strings/utf_string_conversions.h"
#include "grit/ash_resources.h"
#include "grit/ash_strings.h"
#include "ui/base/l10n/l10n_util.h"
#include "ui/base/resource/resource_bundle.h"
#include "ui/gfx/font.h"
#include "ui/gfx/image/image.h"
#include "ui/message_center/message_center.h"
#include "ui/message_center/notification.h"
#include "ui/message_center/notification_delegate.h"
#include "ui/views/controls/label.h"
#include "ui/views/layout/box_layout.h"
#include "ui/views/widget/widget.h"
using message_center::Notification;
namespace {
const char kIMENotificationId[] = "chrome://settings/ime";
} // namespace
namespace ash {
namespace internal {
namespace tray {
class IMEDefaultView : public TrayItemMore {
public:
explicit IMEDefaultView(SystemTrayItem* owner)
: TrayItemMore(owner, true) {
ui::ResourceBundle& bundle = ui::ResourceBundle::GetSharedInstance();
SetImage(bundle.GetImageNamed(
IDR_AURA_UBER_TRAY_IME).ToImageSkia());
IMEInfo info;
Shell::GetInstance()->system_tray_delegate()->GetCurrentIME(&info);
UpdateLabel(info);
}
virtual ~IMEDefaultView() {}
void UpdateLabel(const IMEInfo& info) {
SetLabel(info.name);
SetAccessibleName(info.name);
}
private:
DISALLOW_COPY_AND_ASSIGN(IMEDefaultView);
};
class IMEDetailedView : public TrayDetailsView,
public ViewClickListener {
public:
IMEDetailedView(SystemTrayItem* owner, user::LoginStatus login)
: TrayDetailsView(owner),
login_(login) {
SystemTrayDelegate* delegate = Shell::GetInstance()->system_tray_delegate();
IMEInfoList list;
delegate->GetAvailableIMEList(&list);
IMEPropertyInfoList property_list;
delegate->GetCurrentIMEProperties(&property_list);
Update(list, property_list);
}
virtual ~IMEDetailedView() {}
void Update(const IMEInfoList& list,
const IMEPropertyInfoList& property_list) {
Reset();
AppendIMEList(list);
if (!property_list.empty())
AppendIMEProperties(property_list);
if (login_ != user::LOGGED_IN_NONE && login_ != user::LOGGED_IN_LOCKED)
AppendSettings();
AppendHeaderEntry();
Layout();
SchedulePaint();
}
private:
void AppendHeaderEntry() {
CreateSpecialRow(IDS_ASH_STATUS_TRAY_IME, this);
}
void AppendIMEList(const IMEInfoList& list) {
ime_map_.clear();
CreateScrollableList();
for (size_t i = 0; i < list.size(); i++) {
HoverHighlightView* container = new HoverHighlightView(this);
container->AddLabel(list[i].name,
list[i].selected ? gfx::Font::BOLD : gfx::Font::NORMAL);
scroll_content()->AddChildView(container);
ime_map_[container] = list[i].id;
}
}
void AppendIMEProperties(const IMEPropertyInfoList& property_list) {
property_map_.clear();
for (size_t i = 0; i < property_list.size(); i++) {
HoverHighlightView* container = new HoverHighlightView(this);
container->AddLabel(
property_list[i].name,
property_list[i].selected ? gfx::Font::BOLD : gfx::Font::NORMAL);
if (i == 0)
container->SetBorder(views::Border::CreateSolidSidedBorder(
1, 0, 0, 0, kBorderLightColor));
scroll_content()->AddChildView(container);
property_map_[container] = property_list[i].key;
}
}
void AppendSettings() {
HoverHighlightView* container = new HoverHighlightView(this);
container->AddLabel(ui::ResourceBundle::GetSharedInstance().
GetLocalizedString(IDS_ASH_STATUS_TRAY_IME_SETTINGS),
gfx::Font::NORMAL);
AddChildView(container);
settings_ = container;
}
// Overridden from ViewClickListener.
virtual void OnViewClicked(views::View* sender) OVERRIDE {
SystemTrayDelegate* delegate = Shell::GetInstance()->system_tray_delegate();
if (sender == footer()->content()) {
TransitionToDefaultView();
} else if (sender == settings_) {
Shell::GetInstance()->metrics()->RecordUserMetricsAction(
ash::UMA_STATUS_AREA_IME_SHOW_DETAILED);
delegate->ShowIMESettings();
} else {
std::map<views::View*, std::string>::const_iterator ime_find;
ime_find = ime_map_.find(sender);
if (ime_find != ime_map_.end()) {
Shell::GetInstance()->metrics()->RecordUserMetricsAction(
ash::UMA_STATUS_AREA_IME_SWITCH_MODE);
std::string ime_id = ime_find->second;
delegate->SwitchIME(ime_id);
GetWidget()->Close();
} else {
std::map<views::View*, std::string>::const_iterator prop_find;
prop_find = property_map_.find(sender);
if (prop_find != property_map_.end()) {
const std::string key = prop_find->second;
delegate->ActivateIMEProperty(key);
GetWidget()->Close();
}
}
}
}
user::LoginStatus login_;
std::map<views::View*, std::string> ime_map_;
std::map<views::View*, std::string> property_map_;
views::View* settings_;
DISALLOW_COPY_AND_ASSIGN(IMEDetailedView);
};
} // namespace tray
TrayIME::TrayIME(SystemTray* system_tray)
: SystemTrayItem(system_tray),
tray_label_(NULL),
default_(NULL),
detailed_(NULL),
message_shown_(false),
weak_factory_(this) {
Shell::GetInstance()->system_tray_notifier()->AddIMEObserver(this);
}
TrayIME::~TrayIME() {
Shell::GetInstance()->system_tray_notifier()->RemoveIMEObserver(this);
message_center::MessageCenter::Get()->RemoveNotification(
kIMENotificationId, false /* by_user */);
}
void TrayIME::UpdateTrayLabel(const IMEInfo& current, size_t count) {
if (tray_label_) {
if (current.third_party) {
tray_label_->label()->SetText(
current.short_name + base::UTF8ToUTF16("*"));
} else {
tray_label_->label()->SetText(current.short_name);
}
tray_label_->SetVisible(count > 1);
SetTrayLabelItemBorder(tray_label_, system_tray()->shelf_alignment());
tray_label_->Layout();
}
}
void TrayIME::UpdateOrCreateNotification() {
message_center::MessageCenter* message_center =
message_center::MessageCenter::Get();
if (!message_center->HasNotification(kIMENotificationId) && message_shown_)
return;
SystemTrayDelegate* delegate = Shell::GetInstance()->system_tray_delegate();
IMEInfo current;
delegate->GetCurrentIME(¤t);
ResourceBundle& bundle = ui::ResourceBundle::GetSharedInstance();
scoped_ptr<Notification> notification(new Notification(
message_center::NOTIFICATION_TYPE_SIMPLE,
kIMENotificationId,
// TODO(zork): Use IDS_ASH_STATUS_TRAY_THIRD_PARTY_IME_TURNED_ON_BUBBLE
// for third party IMEs
l10n_util::GetStringFUTF16(
IDS_ASH_STATUS_TRAY_IME_TURNED_ON_BUBBLE,
current.medium_name),
base::string16(), // message
bundle.GetImageNamed(IDR_AURA_UBER_TRAY_IME),
base::string16(), // display_source
message_center::NotifierId(
message_center::NotifierId::SYSTEM_COMPONENT,
system_notifier::kNotifierInputMethod),
message_center::RichNotificationData(),
new message_center::HandleNotificationClickedDelegate(
base::Bind(&TrayIME::PopupDetailedView,
weak_factory_.GetWeakPtr(), 0, true))));
message_center->AddNotification(notification.Pass());
message_shown_ = true;
}
views::View* TrayIME::CreateTrayView(user::LoginStatus status) {
CHECK(tray_label_ == NULL);
tray_label_ = new TrayItemView(this);
tray_label_->CreateLabel();
SetupLabelForTray(tray_label_->label());
// Hide IME tray when it is created, it will be updated when it is notified
// for IME refresh event.
tray_label_->SetVisible(false);
return tray_label_;
}
views::View* TrayIME::CreateDefaultView(user::LoginStatus status) {
SystemTrayDelegate* delegate = Shell::GetInstance()->system_tray_delegate();
IMEInfoList list;
IMEPropertyInfoList property_list;
delegate->GetAvailableIMEList(&list);
delegate->GetCurrentIMEProperties(&property_list);
if (list.size() <= 1 && property_list.size() <= 1)
return NULL;
CHECK(default_ == NULL);
default_ = new tray::IMEDefaultView(this);
return default_;
}
views::View* TrayIME::CreateDetailedView(user::LoginStatus status) {
CHECK(detailed_ == NULL);
detailed_ = new tray::IMEDetailedView(this, status);
return detailed_;
}
void TrayIME::DestroyTrayView() {
tray_label_ = NULL;
}
void TrayIME::DestroyDefaultView() {
default_ = NULL;
}
void TrayIME::DestroyDetailedView() {
detailed_ = NULL;
}
void TrayIME::UpdateAfterLoginStatusChange(user::LoginStatus status) {
}
void TrayIME::UpdateAfterShelfAlignmentChange(ShelfAlignment alignment) {
SetTrayLabelItemBorder(tray_label_, alignment);
tray_label_->Layout();
}
void TrayIME::OnIMERefresh(bool show_message) {
SystemTrayDelegate* delegate = Shell::GetInstance()->system_tray_delegate();
IMEInfoList list;
IMEInfo current;
IMEPropertyInfoList property_list;
delegate->GetCurrentIME(¤t);
delegate->GetAvailableIMEList(&list);
delegate->GetCurrentIMEProperties(&property_list);
UpdateTrayLabel(current, list.size());
if (default_)
default_->UpdateLabel(current);
if (detailed_)
detailed_->Update(list, property_list);
if (list.size() > 1 && show_message)
UpdateOrCreateNotification();
}
} // namespace internal
} // namespace ash
<commit_msg>Do not change IME label in tray before hiding it.<commit_after>// Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "ash/system/ime/tray_ime.h"
#include <vector>
#include "ash/metrics/user_metrics_recorder.h"
#include "ash/root_window_controller.h"
#include "ash/shelf/shelf_widget.h"
#include "ash/shell.h"
#include "ash/system/system_notifier.h"
#include "ash/system/tray/hover_highlight_view.h"
#include "ash/system/tray/system_tray.h"
#include "ash/system/tray/system_tray_delegate.h"
#include "ash/system/tray/system_tray_notifier.h"
#include "ash/system/tray/tray_constants.h"
#include "ash/system/tray/tray_details_view.h"
#include "ash/system/tray/tray_item_more.h"
#include "ash/system/tray/tray_item_view.h"
#include "ash/system/tray/tray_utils.h"
#include "base/logging.h"
#include "base/strings/utf_string_conversions.h"
#include "grit/ash_resources.h"
#include "grit/ash_strings.h"
#include "ui/base/l10n/l10n_util.h"
#include "ui/base/resource/resource_bundle.h"
#include "ui/gfx/font.h"
#include "ui/gfx/image/image.h"
#include "ui/message_center/message_center.h"
#include "ui/message_center/notification.h"
#include "ui/message_center/notification_delegate.h"
#include "ui/views/controls/label.h"
#include "ui/views/layout/box_layout.h"
#include "ui/views/widget/widget.h"
using message_center::Notification;
namespace {
const char kIMENotificationId[] = "chrome://settings/ime";
} // namespace
namespace ash {
namespace internal {
namespace tray {
class IMEDefaultView : public TrayItemMore {
public:
explicit IMEDefaultView(SystemTrayItem* owner)
: TrayItemMore(owner, true) {
ui::ResourceBundle& bundle = ui::ResourceBundle::GetSharedInstance();
SetImage(bundle.GetImageNamed(
IDR_AURA_UBER_TRAY_IME).ToImageSkia());
IMEInfo info;
Shell::GetInstance()->system_tray_delegate()->GetCurrentIME(&info);
UpdateLabel(info);
}
virtual ~IMEDefaultView() {}
void UpdateLabel(const IMEInfo& info) {
SetLabel(info.name);
SetAccessibleName(info.name);
}
private:
DISALLOW_COPY_AND_ASSIGN(IMEDefaultView);
};
class IMEDetailedView : public TrayDetailsView,
public ViewClickListener {
public:
IMEDetailedView(SystemTrayItem* owner, user::LoginStatus login)
: TrayDetailsView(owner),
login_(login) {
SystemTrayDelegate* delegate = Shell::GetInstance()->system_tray_delegate();
IMEInfoList list;
delegate->GetAvailableIMEList(&list);
IMEPropertyInfoList property_list;
delegate->GetCurrentIMEProperties(&property_list);
Update(list, property_list);
}
virtual ~IMEDetailedView() {}
void Update(const IMEInfoList& list,
const IMEPropertyInfoList& property_list) {
Reset();
AppendIMEList(list);
if (!property_list.empty())
AppendIMEProperties(property_list);
if (login_ != user::LOGGED_IN_NONE && login_ != user::LOGGED_IN_LOCKED)
AppendSettings();
AppendHeaderEntry();
Layout();
SchedulePaint();
}
private:
void AppendHeaderEntry() {
CreateSpecialRow(IDS_ASH_STATUS_TRAY_IME, this);
}
void AppendIMEList(const IMEInfoList& list) {
ime_map_.clear();
CreateScrollableList();
for (size_t i = 0; i < list.size(); i++) {
HoverHighlightView* container = new HoverHighlightView(this);
container->AddLabel(list[i].name,
list[i].selected ? gfx::Font::BOLD : gfx::Font::NORMAL);
scroll_content()->AddChildView(container);
ime_map_[container] = list[i].id;
}
}
void AppendIMEProperties(const IMEPropertyInfoList& property_list) {
property_map_.clear();
for (size_t i = 0; i < property_list.size(); i++) {
HoverHighlightView* container = new HoverHighlightView(this);
container->AddLabel(
property_list[i].name,
property_list[i].selected ? gfx::Font::BOLD : gfx::Font::NORMAL);
if (i == 0)
container->SetBorder(views::Border::CreateSolidSidedBorder(
1, 0, 0, 0, kBorderLightColor));
scroll_content()->AddChildView(container);
property_map_[container] = property_list[i].key;
}
}
void AppendSettings() {
HoverHighlightView* container = new HoverHighlightView(this);
container->AddLabel(ui::ResourceBundle::GetSharedInstance().
GetLocalizedString(IDS_ASH_STATUS_TRAY_IME_SETTINGS),
gfx::Font::NORMAL);
AddChildView(container);
settings_ = container;
}
// Overridden from ViewClickListener.
virtual void OnViewClicked(views::View* sender) OVERRIDE {
SystemTrayDelegate* delegate = Shell::GetInstance()->system_tray_delegate();
if (sender == footer()->content()) {
TransitionToDefaultView();
} else if (sender == settings_) {
Shell::GetInstance()->metrics()->RecordUserMetricsAction(
ash::UMA_STATUS_AREA_IME_SHOW_DETAILED);
delegate->ShowIMESettings();
} else {
std::map<views::View*, std::string>::const_iterator ime_find;
ime_find = ime_map_.find(sender);
if (ime_find != ime_map_.end()) {
Shell::GetInstance()->metrics()->RecordUserMetricsAction(
ash::UMA_STATUS_AREA_IME_SWITCH_MODE);
std::string ime_id = ime_find->second;
delegate->SwitchIME(ime_id);
GetWidget()->Close();
} else {
std::map<views::View*, std::string>::const_iterator prop_find;
prop_find = property_map_.find(sender);
if (prop_find != property_map_.end()) {
const std::string key = prop_find->second;
delegate->ActivateIMEProperty(key);
GetWidget()->Close();
}
}
}
}
user::LoginStatus login_;
std::map<views::View*, std::string> ime_map_;
std::map<views::View*, std::string> property_map_;
views::View* settings_;
DISALLOW_COPY_AND_ASSIGN(IMEDetailedView);
};
} // namespace tray
TrayIME::TrayIME(SystemTray* system_tray)
: SystemTrayItem(system_tray),
tray_label_(NULL),
default_(NULL),
detailed_(NULL),
message_shown_(false),
weak_factory_(this) {
Shell::GetInstance()->system_tray_notifier()->AddIMEObserver(this);
}
TrayIME::~TrayIME() {
Shell::GetInstance()->system_tray_notifier()->RemoveIMEObserver(this);
message_center::MessageCenter::Get()->RemoveNotification(
kIMENotificationId, false /* by_user */);
}
void TrayIME::UpdateTrayLabel(const IMEInfo& current, size_t count) {
if (tray_label_) {
bool visible = count > 1;
tray_label_->SetVisible(visible);
// Do not change label before hiding because this change is noticeable.
if (!visible)
return;
if (current.third_party) {
tray_label_->label()->SetText(
current.short_name + base::UTF8ToUTF16("*"));
} else {
tray_label_->label()->SetText(current.short_name);
}
SetTrayLabelItemBorder(tray_label_, system_tray()->shelf_alignment());
tray_label_->Layout();
}
}
void TrayIME::UpdateOrCreateNotification() {
message_center::MessageCenter* message_center =
message_center::MessageCenter::Get();
if (!message_center->HasNotification(kIMENotificationId) && message_shown_)
return;
SystemTrayDelegate* delegate = Shell::GetInstance()->system_tray_delegate();
IMEInfo current;
delegate->GetCurrentIME(¤t);
ResourceBundle& bundle = ui::ResourceBundle::GetSharedInstance();
scoped_ptr<Notification> notification(new Notification(
message_center::NOTIFICATION_TYPE_SIMPLE,
kIMENotificationId,
// TODO(zork): Use IDS_ASH_STATUS_TRAY_THIRD_PARTY_IME_TURNED_ON_BUBBLE
// for third party IMEs
l10n_util::GetStringFUTF16(
IDS_ASH_STATUS_TRAY_IME_TURNED_ON_BUBBLE,
current.medium_name),
base::string16(), // message
bundle.GetImageNamed(IDR_AURA_UBER_TRAY_IME),
base::string16(), // display_source
message_center::NotifierId(
message_center::NotifierId::SYSTEM_COMPONENT,
system_notifier::kNotifierInputMethod),
message_center::RichNotificationData(),
new message_center::HandleNotificationClickedDelegate(
base::Bind(&TrayIME::PopupDetailedView,
weak_factory_.GetWeakPtr(), 0, true))));
message_center->AddNotification(notification.Pass());
message_shown_ = true;
}
views::View* TrayIME::CreateTrayView(user::LoginStatus status) {
CHECK(tray_label_ == NULL);
tray_label_ = new TrayItemView(this);
tray_label_->CreateLabel();
SetupLabelForTray(tray_label_->label());
// Hide IME tray when it is created, it will be updated when it is notified
// for IME refresh event.
tray_label_->SetVisible(false);
return tray_label_;
}
views::View* TrayIME::CreateDefaultView(user::LoginStatus status) {
SystemTrayDelegate* delegate = Shell::GetInstance()->system_tray_delegate();
IMEInfoList list;
IMEPropertyInfoList property_list;
delegate->GetAvailableIMEList(&list);
delegate->GetCurrentIMEProperties(&property_list);
if (list.size() <= 1 && property_list.size() <= 1)
return NULL;
CHECK(default_ == NULL);
default_ = new tray::IMEDefaultView(this);
return default_;
}
views::View* TrayIME::CreateDetailedView(user::LoginStatus status) {
CHECK(detailed_ == NULL);
detailed_ = new tray::IMEDetailedView(this, status);
return detailed_;
}
void TrayIME::DestroyTrayView() {
tray_label_ = NULL;
}
void TrayIME::DestroyDefaultView() {
default_ = NULL;
}
void TrayIME::DestroyDetailedView() {
detailed_ = NULL;
}
void TrayIME::UpdateAfterLoginStatusChange(user::LoginStatus status) {
}
void TrayIME::UpdateAfterShelfAlignmentChange(ShelfAlignment alignment) {
SetTrayLabelItemBorder(tray_label_, alignment);
tray_label_->Layout();
}
void TrayIME::OnIMERefresh(bool show_message) {
SystemTrayDelegate* delegate = Shell::GetInstance()->system_tray_delegate();
IMEInfoList list;
IMEInfo current;
IMEPropertyInfoList property_list;
delegate->GetCurrentIME(¤t);
delegate->GetAvailableIMEList(&list);
delegate->GetCurrentIMEProperties(&property_list);
UpdateTrayLabel(current, list.size());
if (default_)
default_->UpdateLabel(current);
if (detailed_)
detailed_->Update(list, property_list);
if (list.size() > 1 && show_message)
UpdateOrCreateNotification();
}
} // namespace internal
} // namespace ash
<|endoftext|> |
<commit_before>// $Id$
//
// Root macro that opens a mini GUI for running aliroot with Geant4.
//
// To run aliroot with Geant4 using the g4menu.C:
// aliroot
// root [0] .x g4menu.C
// --> First select "Geometry" to build geometry.root file
// --> Then re-run aliroot and select "Run" button
//
// The Init button is kept for debugging purposes,
// it itializes MonteCarlo but it does not itialize
// completely ALICE framework. That's why to run simulation,
// you have to re-run aliroot and select Run button.
//
// The menu enables to start Geant4 interactive session:
// --> Select "Geant4UI" button and use Geant4 interactive commands;
// To go back to Root UI, type exit.
//
// By I. Hrivnacova, IPN Orsay
#include <iostream>
void g4menu()
{
// Load Geant4 libraries
if (!gInterpreter->IsLoaded("$ALICE/geant4_vmc/examples/macro/g4libs.C"))
gROOT->LoadMacro("$ALICE/geant4_vmc/examples/macro/g4libs.C");
gInterpreter->ProcessLine("g4libs()");
// Menu
TControlBar* menu = new TControlBar("vertical","Alice Geant4 menu");
menu->AddButton("Geometry", "MakeGeometry()", "Generate Root geometry file");
menu->AddButton("Run", "RunSimulation()", "Process Alice run");
menu->AddButton("Init", "Init()", "Initialize Alice for simulation");
menu->AddButton("Geant4UI", "StartGeant4UI()","Go to Geant4 Interactive session");
menu->AddButton("AGDD", "GenerateAGDD()","Generate XML (AGDD) file with geometry description");
//menu->AddButton("GDML", "GenerateGDML()","Generate XML (GDML) file with geometry description");
menu->AddButton("Quit", "Quit()", "Quit aliroot");
gROOT->SaveContext();
cout << endl
<< "**************************************************************" << endl
<< " To run simulation:" << endl
<< " First select <Geometry> to build geometry.root file." << endl
<< " Then re-run aliroot and select <Run> button" << endl
<< endl
<< " The <Init> button is kept for debugging purposes," << endl
<< " it itializes MonteCarlo but it does not itialize" << endl
<< " completely ALICE framework. That's why to run simulation," << endl
<< " you have to re-run aliroot and select Run button." << endl
<< endl
<< " The menu enables to start Geant4 interactive session:" << endl
<< " Select <Geant4UI> button and use Geant4 interactive commands" << endl
<< " To go back to Root UI, type exit." << endl
<< "**************************************************************" << endl
<< endl;
menu->Show();
}
void MakeGeometry()
{
AliCDBManager* man = AliCDBManager::Instance();
man->SetDefaultStorage("local://$ALICE_ROOT/OCDB");
man->SetRun(1);
gAlice->Init("$ALICE_ROOT/macros/g4ConfigGeometry.C");
// Generate geometry file
//
gGeoManager->Export("geometry.root");
cout << endl
<< "Geometry file geometry.root has been generated." << endl
<< "You have to re-run aliroot and choose Run in g4menu." << endl;
exit(0);
}
void Init()
{
AliCDBManager* man = AliCDBManager::Instance();
man->SetDefaultStorage("local://$ALICE_ROOT/OCDB");
man->SetRun(0);
gAlice->Init("$ALICE_ROOT/macros/g4Config.C");
cout << endl
<< "Only MonteCarlo initialization has been performed. " << endl
<< "To run simulation you have to re-run aliroot and choose Run in g4menu." << endl;
}
void RunSimulation()
{
AliSimulation sim("$ALICE_ROOT/macros/g4Config.C");
sim.SetMakeDigits("");
sim.SetMakeSDigits("");
sim.SetRunHLT("");
sim.SetNumberOfEvents(1);
TStopwatch timer;
timer.Start();
sim.Run(1);
timer.Stop();
timer.Print();
}
void StartGeant4UI()
{
if (gMC) {
// release Root terminal control
// go into non-raw term mode
Getlinem(kCleanUp, 0);
// add test if gMC is TGeant4
TGeant4* g4 = (TGeant4*)gMC;
g4->StartGeantUI();
// new Root prompt
Getlinem(kInit, ((TRint*)gROOT->GetApplication())->GetPrompt());
}
else {
cout << "Monte Carlo has not been yet created." << endl;
}
}
void GenerateAGDD()
{
if (gMC) {
// release Root terminal control
// go into non-raw term mode
//Getlinem(kCleanUp, 0);
// add test if gMC is TGeant4
TGeant4* g4 = (TGeant4*)gMC;
g4->ProcessGeantCommand("/vgm/generateAGDD");
// new Root prompt
//Getlinem(kInit, ((TRint*)gROOT->GetApplication())->GetPrompt());
}
else {
cout << "Monte Carlo has not been yet created." << endl;
}
}
/*
void GenerateGDML()
{
if (gMC) {
// release Root terminal control
// go into non-raw term mode
//Getlinem(kCleanUp, 0);
// add test if gMC is TGeant4
TGeant4* g4 = (TGeant4*)gMC;
g4->ProcessGeantCommand("/vgm/generateGDML");
// new Root prompt
//Getlinem(kInit, ((TRint*)gROOT->GetApplication())->GetPrompt());
}
else {
cout << "Monte Carlo has not been yet created." << endl;
}
}
*/
void Quit()
{
delete AliRunLoader::Instance();
delete gAlice;
exit(0);
}
<commit_msg>Updating g4menu.C macro for changes in STEER; calling gAlice->GetMCApp()->Init(); instead of gAlice->Init(), which is no more available. (I. Hrivnacova)<commit_after>// $Id$
//
// Root macro that opens a mini GUI for running aliroot with Geant4.
//
// To run aliroot with Geant4 using the g4menu.C:
// aliroot
// root [0] .x g4menu.C
// --> First select "Geometry" to build geometry.root file
// --> Then re-run aliroot and select "Run" button
//
// The Init button is kept for debugging purposes,
// it itializes MonteCarlo but it does not itialize
// completely ALICE framework. That's why to run simulation,
// you have to re-run aliroot and select Run button.
//
// The menu enables to start Geant4 interactive session:
// --> Select "Geant4UI" button and use Geant4 interactive commands;
// To go back to Root UI, type exit.
//
// By I. Hrivnacova, IPN Orsay
#include <iostream>
void g4menu()
{
// Load Geant4 libraries
if (!gInterpreter->IsLoaded("$ALICE/geant4_vmc/examples/macro/g4libs.C"))
gROOT->LoadMacro("$ALICE/geant4_vmc/examples/macro/g4libs.C");
gInterpreter->ProcessLine("g4libs()");
// Menu
TControlBar* menu = new TControlBar("vertical","Alice Geant4 menu");
menu->AddButton("Geometry", "MakeGeometry()", "Generate Root geometry file");
menu->AddButton("Run", "RunSimulation()", "Process Alice run");
menu->AddButton("Init", "Init()", "Initialize Alice for simulation");
menu->AddButton("Geant4UI", "StartGeant4UI()","Go to Geant4 Interactive session");
menu->AddButton("AGDD", "GenerateAGDD()","Generate XML (AGDD) file with geometry description");
//menu->AddButton("GDML", "GenerateGDML()","Generate XML (GDML) file with geometry description");
menu->AddButton("Quit", "Quit()", "Quit aliroot");
gROOT->SaveContext();
cout << endl
<< "**************************************************************" << endl
<< " To run simulation:" << endl
<< " First select <Geometry> to build geometry.root file." << endl
<< " Then re-run aliroot and select <Run> button" << endl
<< endl
<< " The <Init> button is kept for debugging purposes," << endl
<< " it itializes MonteCarlo but it does not itialize" << endl
<< " completely ALICE framework. That's why to run simulation," << endl
<< " you have to re-run aliroot and select Run button." << endl
<< endl
<< " The menu enables to start Geant4 interactive session:" << endl
<< " Select <Geant4UI> button and use Geant4 interactive commands" << endl
<< " To go back to Root UI, type exit." << endl
<< "**************************************************************" << endl
<< endl;
menu->Show();
}
void MakeGeometry()
{
AliCDBManager* man = AliCDBManager::Instance();
man->SetDefaultStorage("local://$ALICE_ROOT/OCDB");
man->SetRun(1);
// MC application initialization
TString configFileName = "$ALICE_ROOT/macros/g4ConfigGeometry.C";
gROOT->LoadMacro(configFileName.Data());
gInterpreter->ProcessLine(gAlice->GetConfigFunction());
gAlice->GetMCApp()->Init();
// Generate geometry file
//
gGeoManager->Export("geometry.root");
cout << endl
<< "Geometry file geometry.root has been generated." << endl
<< "You have to re-run aliroot and choose Run in g4menu." << endl;
exit(0);
}
void Init()
{
AliCDBManager* man = AliCDBManager::Instance();
man->SetDefaultStorage("local://$ALICE_ROOT/OCDB");
man->SetRun(0);
// MC application initialization
TString configFileName = "$ALICE_ROOT/macros/g4Config.C";
gROOT->LoadMacro(configFileName.Data());
gInterpreter->ProcessLine(gAlice->GetConfigFunction());
gAlice->GetMCApp()->Init();
cout << endl
<< "Only MonteCarlo initialization has been performed. " << endl
<< "To run simulation you have to re-run aliroot and choose Run in g4menu." << endl;
}
void RunSimulation()
{
AliSimulation sim("$ALICE_ROOT/macros/g4Config.C");
sim.SetMakeDigits("");
sim.SetMakeSDigits("");
sim.SetRunHLT("");
sim.SetNumberOfEvents(1);
TStopwatch timer;
timer.Start();
sim.Run(1);
timer.Stop();
timer.Print();
}
void StartGeant4UI()
{
if (gMC) {
// release Root terminal control
// go into non-raw term mode
Getlinem(kCleanUp, 0);
// add test if gMC is TGeant4
TGeant4* g4 = (TGeant4*)gMC;
g4->StartGeantUI();
// new Root prompt
Getlinem(kInit, ((TRint*)gROOT->GetApplication())->GetPrompt());
}
else {
cout << "Monte Carlo has not been yet created." << endl;
}
}
void GenerateAGDD()
{
if (gMC) {
// release Root terminal control
// go into non-raw term mode
//Getlinem(kCleanUp, 0);
// add test if gMC is TGeant4
TGeant4* g4 = (TGeant4*)gMC;
g4->ProcessGeantCommand("/vgm/generateAGDD");
// new Root prompt
//Getlinem(kInit, ((TRint*)gROOT->GetApplication())->GetPrompt());
}
else {
cout << "Monte Carlo has not been yet created." << endl;
}
}
/*
void GenerateGDML()
{
if (gMC) {
// release Root terminal control
// go into non-raw term mode
//Getlinem(kCleanUp, 0);
// add test if gMC is TGeant4
TGeant4* g4 = (TGeant4*)gMC;
g4->ProcessGeantCommand("/vgm/generateGDML");
// new Root prompt
//Getlinem(kInit, ((TRint*)gROOT->GetApplication())->GetPrompt());
}
else {
cout << "Monte Carlo has not been yet created." << endl;
}
}
*/
void Quit()
{
delete AliRunLoader::Instance();
delete gAlice;
exit(0);
}
<|endoftext|> |
<commit_before>#include "nw_screen_api.h"
#if defined(OS_WIN)
#include "windows.h"
#endif
#include "base/lazy_instance.h"
#include "base/values.h"
#include "content/nw/src/api/nw_screen.h"
#include "extensions/browser/extensions_browser_client.h"
#include "ui/display/display_observer.h"
#include "ui/display/display.h"
#include "ui/display/screen.h"
// For desktop capture APIs
#include "base/base64.h"
#include "base/strings/utf_string_conversions.h"
#include "chrome/browser/media/webrtc/desktop_media_list_observer.h"
#include "chrome/browser/media/webrtc/media_capture_devices_dispatcher.h"
#include "chrome/browser/media/webrtc/native_desktop_media_list.h"
#include "content/public/browser/render_frame_host.h"
#include "content/public/browser/desktop_streams_registry.h"
#include "content/public/browser/render_process_host.h"
#include "content/public/browser/web_contents.h"
#include "third_party/webrtc/modules/desktop_capture/desktop_capture_options.h"
#include "third_party/webrtc/modules/desktop_capture/desktop_capturer.h"
#include "ui/gfx/codec/png_codec.h"
#include "ui/gfx/image/image.h"
#include "ui/gfx/image/image_skia.h"
using namespace extensions::nwapi::nw__screen;
using namespace content;
namespace extensions {
class NwDesktopCaptureMonitor : public DesktopMediaListObserver {
public:
static NwDesktopCaptureMonitor* GetInstance();
NwDesktopCaptureMonitor();
void Start(bool screens, bool windows);
void Stop();
bool IsStarted();
private:
int GetPrimaryMonitorIndex();
// DesktopMediaListObserver implementation.
void OnSourceAdded(int index) override;
void OnSourceRemoved(int index) override;
void OnSourceMoved(int old_index, int new_index) override;
void OnSourceNameChanged(int index) override;
void OnSourceThumbnailChanged(int index) override;
void OnSourcePreviewChanged(size_t index) override;
bool started_;
std::vector<std::unique_ptr<DesktopMediaList>> media_list_;
DISALLOW_COPY_AND_ASSIGN(NwDesktopCaptureMonitor);
};
class NwScreenDisplayObserver: public display::DisplayObserver {
public:
static NwScreenDisplayObserver* GetInstance();
NwScreenDisplayObserver();
private:
~NwScreenDisplayObserver() override;
// gfx::DisplayObserver implementation.
void OnDisplayMetricsChanged(const display::Display& display, uint32_t changed_metrics) override;
void OnDisplayAdded(const display::Display& new_display) override;
void OnDisplayRemoved(const display::Display& old_display) override;
DISALLOW_COPY_AND_ASSIGN(NwScreenDisplayObserver);
};
namespace {
// Helper function to convert display::Display to nwapi::nw__screen::Display
std::unique_ptr<nwapi::nw__screen::Display> ConvertGfxDisplay(const display::Display& gfx_display) {
std::unique_ptr<nwapi::nw__screen::Display> displayResult(new nwapi::nw__screen::Display);
displayResult->id = gfx_display.id();
displayResult->scale_factor = gfx_display.device_scale_factor();
displayResult->is_built_in = gfx_display.IsInternal();
displayResult->rotation = gfx_display.RotationAsDegree();
displayResult->touch_support = (int)gfx_display.touch_support();
gfx::Rect rect = gfx_display.bounds();
DisplayGeometry& bounds = displayResult->bounds;
bounds.x = rect.x();
bounds.y = rect.y();
bounds.width = rect.width();
bounds.height = rect.height();
rect = gfx_display.work_area();
DisplayGeometry& work_area = displayResult->work_area;
work_area.x = rect.x();
work_area.y = rect.y();
work_area.width = rect.width();
work_area.height = rect.height();
return displayResult;
}
void DispatchEvent(
events::HistogramValue histogram_value,
const std::string& event_name,
std::vector<base::Value> args) {
DCHECK_CURRENTLY_ON(BrowserThread::UI);
//std::unique_ptr<base::ListValue> arg_list(std::move(args));
ExtensionsBrowserClient::Get()->
BroadcastEventToRenderers(
histogram_value, event_name,
std::make_unique<base::ListValue>(std::move(args)),
false);
}
// Lazy initialize screen event listeners until first call
base::LazyInstance<NwScreenDisplayObserver>::Leaky
g_display_observer = LAZY_INSTANCE_INITIALIZER;
base::LazyInstance<NwDesktopCaptureMonitor>::Leaky
g_desktop_capture_monitor = LAZY_INSTANCE_INITIALIZER;
}
// static
NwScreenDisplayObserver* NwScreenDisplayObserver::GetInstance() {
return g_display_observer.Pointer();
}
NwScreenDisplayObserver::NwScreenDisplayObserver() {
display::Screen* screen = display::Screen::GetScreen();
if (screen) {
screen->AddObserver(this);
}
}
NwScreenDisplayObserver::~NwScreenDisplayObserver() {
display::Screen* screen = display::Screen::GetScreen();
if (screen) {
screen->RemoveObserver(this);
}
}
// Called when the |display|'s bound has changed.
void NwScreenDisplayObserver::OnDisplayMetricsChanged(const display::Display& display,
uint32_t changed_metrics) {
std::vector<base::Value> args =
nwapi::nw__screen::OnDisplayBoundsChanged::Create(*ConvertGfxDisplay(display),
changed_metrics);
DispatchEvent(
events::HistogramValue::UNKNOWN,
nwapi::nw__screen::OnDisplayBoundsChanged::kEventName,
std::move(args));
}
// Called when |new_display| has been added.
void NwScreenDisplayObserver::OnDisplayAdded(const display::Display& new_display) {
std::vector<base::Value> args =
nwapi::nw__screen::OnDisplayAdded::Create(*ConvertGfxDisplay(new_display));
DispatchEvent(
events::HistogramValue::UNKNOWN,
nwapi::nw__screen::OnDisplayAdded::kEventName,
std::move(args));
}
// Called when |old_display| has been removed.
void NwScreenDisplayObserver::OnDisplayRemoved(const display::Display& old_display) {
std::vector<base::Value> args =
nwapi::nw__screen::OnDisplayRemoved::Create(*ConvertGfxDisplay(old_display));
DispatchEvent(
events::HistogramValue::UNKNOWN,
nwapi::nw__screen::OnDisplayRemoved::kEventName,
std::move(args));
}
NwScreenGetScreensFunction::NwScreenGetScreensFunction() {}
bool NwScreenGetScreensFunction::RunNWSync(base::ListValue* response, std::string* error) {
const std::vector<display::Display>& displays = display::Screen::GetScreen()->GetAllDisplays();
for (size_t i=0; i<displays.size(); i++) {
response->Append(ConvertGfxDisplay(displays[i])->ToValue());
}
return true;
}
NwScreenInitEventListenersFunction::NwScreenInitEventListenersFunction() {}
bool NwScreenInitEventListenersFunction::RunNWSync(base::ListValue* response, std::string* error) {
NwScreenDisplayObserver::GetInstance();
return true;
}
NwDesktopCaptureMonitor* NwDesktopCaptureMonitor::GetInstance() {
return g_desktop_capture_monitor.Pointer();
}
NwDesktopCaptureMonitor::NwDesktopCaptureMonitor()
: started_(false) {
}
void NwDesktopCaptureMonitor::Start(bool screens, bool windows) {
if (started_) {
return;
}
started_ = true;
webrtc::DesktopCaptureOptions options = webrtc::DesktopCaptureOptions::CreateDefault();
options.set_disable_effects(false);
if (screens) {
std::unique_ptr<DesktopMediaList> screen_media_list =
std::make_unique<NativeDesktopMediaList>(
DesktopMediaList::Type::kScreen,
webrtc::DesktopCapturer::CreateScreenCapturer(options));
media_list_.push_back(std::move(screen_media_list));
}
if (windows) {
std::unique_ptr<DesktopMediaList> window_media_list =
std::make_unique<NativeDesktopMediaList>(
DesktopMediaList::Type::kWindow,
webrtc::DesktopCapturer::CreateWindowCapturer(options));
media_list_.push_back(std::move(window_media_list));
}
for (auto& media_list : media_list_) {
media_list->StartUpdating(this);
}
}
void NwDesktopCaptureMonitor::Stop() {
started_ = false;
media_list_.clear();
}
bool NwDesktopCaptureMonitor::IsStarted() {
return started_;
}
int NwDesktopCaptureMonitor::GetPrimaryMonitorIndex() {
#ifdef _WIN32
int count=0;
for (int i = 0;; ++i) {
DISPLAY_DEVICE device;
device.cb = sizeof(device);
BOOL ret = EnumDisplayDevices(NULL, i, &device, 0);
if(!ret)
break;
if (device.StateFlags & DISPLAY_DEVICE_ACTIVE){
if (device.StateFlags & DISPLAY_DEVICE_PRIMARY_DEVICE){
return count;
}
count++;
}
}
#endif
return -1;
}
void NwDesktopCaptureMonitor::OnSourceAdded(int index) {
DesktopMediaList::Source src = media_list_[0]->GetSource(index);
std::string type;
switch(src.id.type) {
case content::DesktopMediaID::TYPE_WINDOW:
type = "window";
break;
case content::DesktopMediaID::TYPE_SCREEN:
type = "screen";
break;
case content::DesktopMediaID::TYPE_NONE:
type = "none";
break;
default:
type = "unknown";
break;
}
std::vector<base::Value> args = nwapi::nw__screen::OnSourceAdded::Create(
src.id.ToString(),
base::UTF16ToUTF8(src.name),
index,
type,
src.id.type == content::DesktopMediaID::TYPE_SCREEN && GetPrimaryMonitorIndex() == index);
DispatchEvent(
events::HistogramValue::UNKNOWN,
nwapi::nw__screen::OnSourceAdded::kEventName,
std::move(args));
}
void NwDesktopCaptureMonitor::OnSourceRemoved(int index) {
std::vector<base::Value> args = nwapi::nw__screen::OnSourceRemoved::Create(index);
DispatchEvent(
events::HistogramValue::UNKNOWN,
nwapi::nw__screen::OnSourceRemoved::kEventName,
std::move(args));
}
void NwDesktopCaptureMonitor::OnSourceMoved(int old_index, int new_index) {
DesktopMediaList::Source src = media_list_[0]->GetSource(new_index);
std::vector<base::Value> args = nwapi::nw__screen::OnSourceOrderChanged::Create(
src.id.ToString(),
new_index,
old_index);
DispatchEvent(
events::HistogramValue::UNKNOWN,
nwapi::nw__screen::OnSourceOrderChanged::kEventName,
std::move(args));
}
void NwDesktopCaptureMonitor::OnSourceNameChanged(int index) {
DesktopMediaList::Source src = media_list_[0]->GetSource(index);
std::vector<base::Value> args = nwapi::nw__screen::OnSourceNameChanged::Create(
src.id.ToString(),
base::UTF16ToUTF8(src.name));
DispatchEvent(
events::HistogramValue::UNKNOWN,
nwapi::nw__screen::OnSourceNameChanged::kEventName,
std::move(args));
}
void NwDesktopCaptureMonitor::OnSourcePreviewChanged(size_t index) {
}
void NwDesktopCaptureMonitor::OnSourceThumbnailChanged(int index) {
std::string base64;
DesktopMediaList::Source src = media_list_[0]->GetSource(index);
SkBitmap bitmap = src.thumbnail.GetRepresentation(1).GetBitmap();
std::vector<unsigned char> data;
bool success = gfx::PNGCodec::EncodeBGRASkBitmap(bitmap, false, &data);
if (success){
base::StringPiece raw_str(reinterpret_cast<const char*>(&data[0]), data.size());
base::Base64Encode(raw_str, &base64);
}
std::vector<base::Value> args = nwapi::nw__screen::OnSourceThumbnailChanged::Create(
src.id.ToString(),
base64);
DispatchEvent(
events::HistogramValue::UNKNOWN,
nwapi::nw__screen::OnSourceThumbnailChanged::kEventName,
std::move(args));
}
NwScreenStartMonitorFunction::NwScreenStartMonitorFunction() {}
bool NwScreenStartMonitorFunction::RunNWSync(base::ListValue* response, std::string* error) {
bool screens, windows;
EXTENSION_FUNCTION_VALIDATE(args().size() >= 2);
EXTENSION_FUNCTION_VALIDATE(args()[0].is_bool() && args()[1].is_bool());
screens = args()[0].GetBool();
windows = args()[1].GetBool();
NwDesktopCaptureMonitor::GetInstance()->Start(screens, windows);
return true;
}
NwScreenStopMonitorFunction::NwScreenStopMonitorFunction() {}
bool NwScreenStopMonitorFunction::RunNWSync(base::ListValue* response, std::string* error) {
NwDesktopCaptureMonitor::GetInstance()->Stop();
return true;
}
NwScreenIsMonitorStartedFunction::NwScreenIsMonitorStartedFunction() {}
bool NwScreenIsMonitorStartedFunction::RunNWSync(base::ListValue* response, std::string* error) {
response->Append(NwDesktopCaptureMonitor::GetInstance()->IsStarted());
return true;
}
NwScreenRegisterStreamFunction::NwScreenRegisterStreamFunction() {}
bool NwScreenRegisterStreamFunction::RunNWSync(base::ListValue* response, std::string* error) {
std::string id;
EXTENSION_FUNCTION_VALIDATE(args().size() >= 1);
EXTENSION_FUNCTION_VALIDATE(args()[0].is_string());
id = args()[0].GetString();
// following code is modified from `DesktopCaptureChooseDesktopMediaFunctionBase::OnPickerDialogResults`
// in chrome/browser/extensions/api/desktop_capture/desktop_capture_base.cc
content::DesktopMediaID source = content::DesktopMediaID::Parse(id);
content::WebContents* web_contents = GetSenderWebContents();
if (!source.is_null() && web_contents) {
std::string result;
source.audio_share = true;
content::DesktopStreamsRegistry* registry = content::DesktopStreamsRegistry::GetInstance();
// TODO(miu): Once render_frame_host() is being set, we should register the
// exact RenderFrame requesting the stream, not the main RenderFrame. With
// that change, also update
// MediaCaptureDevicesDispatcher::ProcessDesktopCaptureAccessRequest().
// http://crbug.com/304341
content::RenderFrameHost* const main_frame = web_contents->GetMainFrame();
result = registry->RegisterStream(main_frame->GetProcess()->GetID(),
main_frame->GetRoutingID(),
url::Origin::Create(web_contents->GetURL().GetOrigin()),
source,
extension()->name(), content::kRegistryStreamTypeDesktop);
response->Append(result);
}
return true;
}
} // extensions
<commit_msg>migrate from GetOrigin()<commit_after>#include "nw_screen_api.h"
#if defined(OS_WIN)
#include "windows.h"
#endif
#include "base/lazy_instance.h"
#include "base/values.h"
#include "content/nw/src/api/nw_screen.h"
#include "extensions/browser/extensions_browser_client.h"
#include "ui/display/display_observer.h"
#include "ui/display/display.h"
#include "ui/display/screen.h"
// For desktop capture APIs
#include "base/base64.h"
#include "base/strings/utf_string_conversions.h"
#include "chrome/browser/media/webrtc/desktop_media_list_observer.h"
#include "chrome/browser/media/webrtc/media_capture_devices_dispatcher.h"
#include "chrome/browser/media/webrtc/native_desktop_media_list.h"
#include "content/public/browser/render_frame_host.h"
#include "content/public/browser/desktop_streams_registry.h"
#include "content/public/browser/render_process_host.h"
#include "content/public/browser/web_contents.h"
#include "third_party/webrtc/modules/desktop_capture/desktop_capture_options.h"
#include "third_party/webrtc/modules/desktop_capture/desktop_capturer.h"
#include "ui/gfx/codec/png_codec.h"
#include "ui/gfx/image/image.h"
#include "ui/gfx/image/image_skia.h"
using namespace extensions::nwapi::nw__screen;
using namespace content;
namespace extensions {
class NwDesktopCaptureMonitor : public DesktopMediaListObserver {
public:
static NwDesktopCaptureMonitor* GetInstance();
NwDesktopCaptureMonitor();
void Start(bool screens, bool windows);
void Stop();
bool IsStarted();
private:
int GetPrimaryMonitorIndex();
// DesktopMediaListObserver implementation.
void OnSourceAdded(int index) override;
void OnSourceRemoved(int index) override;
void OnSourceMoved(int old_index, int new_index) override;
void OnSourceNameChanged(int index) override;
void OnSourceThumbnailChanged(int index) override;
void OnSourcePreviewChanged(size_t index) override;
bool started_;
std::vector<std::unique_ptr<DesktopMediaList>> media_list_;
DISALLOW_COPY_AND_ASSIGN(NwDesktopCaptureMonitor);
};
class NwScreenDisplayObserver: public display::DisplayObserver {
public:
static NwScreenDisplayObserver* GetInstance();
NwScreenDisplayObserver();
private:
~NwScreenDisplayObserver() override;
// gfx::DisplayObserver implementation.
void OnDisplayMetricsChanged(const display::Display& display, uint32_t changed_metrics) override;
void OnDisplayAdded(const display::Display& new_display) override;
void OnDisplayRemoved(const display::Display& old_display) override;
DISALLOW_COPY_AND_ASSIGN(NwScreenDisplayObserver);
};
namespace {
// Helper function to convert display::Display to nwapi::nw__screen::Display
std::unique_ptr<nwapi::nw__screen::Display> ConvertGfxDisplay(const display::Display& gfx_display) {
std::unique_ptr<nwapi::nw__screen::Display> displayResult(new nwapi::nw__screen::Display);
displayResult->id = gfx_display.id();
displayResult->scale_factor = gfx_display.device_scale_factor();
displayResult->is_built_in = gfx_display.IsInternal();
displayResult->rotation = gfx_display.RotationAsDegree();
displayResult->touch_support = (int)gfx_display.touch_support();
gfx::Rect rect = gfx_display.bounds();
DisplayGeometry& bounds = displayResult->bounds;
bounds.x = rect.x();
bounds.y = rect.y();
bounds.width = rect.width();
bounds.height = rect.height();
rect = gfx_display.work_area();
DisplayGeometry& work_area = displayResult->work_area;
work_area.x = rect.x();
work_area.y = rect.y();
work_area.width = rect.width();
work_area.height = rect.height();
return displayResult;
}
void DispatchEvent(
events::HistogramValue histogram_value,
const std::string& event_name,
std::vector<base::Value> args) {
DCHECK_CURRENTLY_ON(BrowserThread::UI);
//std::unique_ptr<base::ListValue> arg_list(std::move(args));
ExtensionsBrowserClient::Get()->
BroadcastEventToRenderers(
histogram_value, event_name,
std::make_unique<base::ListValue>(std::move(args)),
false);
}
// Lazy initialize screen event listeners until first call
base::LazyInstance<NwScreenDisplayObserver>::Leaky
g_display_observer = LAZY_INSTANCE_INITIALIZER;
base::LazyInstance<NwDesktopCaptureMonitor>::Leaky
g_desktop_capture_monitor = LAZY_INSTANCE_INITIALIZER;
}
// static
NwScreenDisplayObserver* NwScreenDisplayObserver::GetInstance() {
return g_display_observer.Pointer();
}
NwScreenDisplayObserver::NwScreenDisplayObserver() {
display::Screen* screen = display::Screen::GetScreen();
if (screen) {
screen->AddObserver(this);
}
}
NwScreenDisplayObserver::~NwScreenDisplayObserver() {
display::Screen* screen = display::Screen::GetScreen();
if (screen) {
screen->RemoveObserver(this);
}
}
// Called when the |display|'s bound has changed.
void NwScreenDisplayObserver::OnDisplayMetricsChanged(const display::Display& display,
uint32_t changed_metrics) {
std::vector<base::Value> args =
nwapi::nw__screen::OnDisplayBoundsChanged::Create(*ConvertGfxDisplay(display),
changed_metrics);
DispatchEvent(
events::HistogramValue::UNKNOWN,
nwapi::nw__screen::OnDisplayBoundsChanged::kEventName,
std::move(args));
}
// Called when |new_display| has been added.
void NwScreenDisplayObserver::OnDisplayAdded(const display::Display& new_display) {
std::vector<base::Value> args =
nwapi::nw__screen::OnDisplayAdded::Create(*ConvertGfxDisplay(new_display));
DispatchEvent(
events::HistogramValue::UNKNOWN,
nwapi::nw__screen::OnDisplayAdded::kEventName,
std::move(args));
}
// Called when |old_display| has been removed.
void NwScreenDisplayObserver::OnDisplayRemoved(const display::Display& old_display) {
std::vector<base::Value> args =
nwapi::nw__screen::OnDisplayRemoved::Create(*ConvertGfxDisplay(old_display));
DispatchEvent(
events::HistogramValue::UNKNOWN,
nwapi::nw__screen::OnDisplayRemoved::kEventName,
std::move(args));
}
NwScreenGetScreensFunction::NwScreenGetScreensFunction() {}
bool NwScreenGetScreensFunction::RunNWSync(base::ListValue* response, std::string* error) {
const std::vector<display::Display>& displays = display::Screen::GetScreen()->GetAllDisplays();
for (size_t i=0; i<displays.size(); i++) {
response->Append(ConvertGfxDisplay(displays[i])->ToValue());
}
return true;
}
NwScreenInitEventListenersFunction::NwScreenInitEventListenersFunction() {}
bool NwScreenInitEventListenersFunction::RunNWSync(base::ListValue* response, std::string* error) {
NwScreenDisplayObserver::GetInstance();
return true;
}
NwDesktopCaptureMonitor* NwDesktopCaptureMonitor::GetInstance() {
return g_desktop_capture_monitor.Pointer();
}
NwDesktopCaptureMonitor::NwDesktopCaptureMonitor()
: started_(false) {
}
void NwDesktopCaptureMonitor::Start(bool screens, bool windows) {
if (started_) {
return;
}
started_ = true;
webrtc::DesktopCaptureOptions options = webrtc::DesktopCaptureOptions::CreateDefault();
options.set_disable_effects(false);
if (screens) {
std::unique_ptr<DesktopMediaList> screen_media_list =
std::make_unique<NativeDesktopMediaList>(
DesktopMediaList::Type::kScreen,
webrtc::DesktopCapturer::CreateScreenCapturer(options));
media_list_.push_back(std::move(screen_media_list));
}
if (windows) {
std::unique_ptr<DesktopMediaList> window_media_list =
std::make_unique<NativeDesktopMediaList>(
DesktopMediaList::Type::kWindow,
webrtc::DesktopCapturer::CreateWindowCapturer(options));
media_list_.push_back(std::move(window_media_list));
}
for (auto& media_list : media_list_) {
media_list->StartUpdating(this);
}
}
void NwDesktopCaptureMonitor::Stop() {
started_ = false;
media_list_.clear();
}
bool NwDesktopCaptureMonitor::IsStarted() {
return started_;
}
int NwDesktopCaptureMonitor::GetPrimaryMonitorIndex() {
#ifdef _WIN32
int count=0;
for (int i = 0;; ++i) {
DISPLAY_DEVICE device;
device.cb = sizeof(device);
BOOL ret = EnumDisplayDevices(NULL, i, &device, 0);
if(!ret)
break;
if (device.StateFlags & DISPLAY_DEVICE_ACTIVE){
if (device.StateFlags & DISPLAY_DEVICE_PRIMARY_DEVICE){
return count;
}
count++;
}
}
#endif
return -1;
}
void NwDesktopCaptureMonitor::OnSourceAdded(int index) {
DesktopMediaList::Source src = media_list_[0]->GetSource(index);
std::string type;
switch(src.id.type) {
case content::DesktopMediaID::TYPE_WINDOW:
type = "window";
break;
case content::DesktopMediaID::TYPE_SCREEN:
type = "screen";
break;
case content::DesktopMediaID::TYPE_NONE:
type = "none";
break;
default:
type = "unknown";
break;
}
std::vector<base::Value> args = nwapi::nw__screen::OnSourceAdded::Create(
src.id.ToString(),
base::UTF16ToUTF8(src.name),
index,
type,
src.id.type == content::DesktopMediaID::TYPE_SCREEN && GetPrimaryMonitorIndex() == index);
DispatchEvent(
events::HistogramValue::UNKNOWN,
nwapi::nw__screen::OnSourceAdded::kEventName,
std::move(args));
}
void NwDesktopCaptureMonitor::OnSourceRemoved(int index) {
std::vector<base::Value> args = nwapi::nw__screen::OnSourceRemoved::Create(index);
DispatchEvent(
events::HistogramValue::UNKNOWN,
nwapi::nw__screen::OnSourceRemoved::kEventName,
std::move(args));
}
void NwDesktopCaptureMonitor::OnSourceMoved(int old_index, int new_index) {
DesktopMediaList::Source src = media_list_[0]->GetSource(new_index);
std::vector<base::Value> args = nwapi::nw__screen::OnSourceOrderChanged::Create(
src.id.ToString(),
new_index,
old_index);
DispatchEvent(
events::HistogramValue::UNKNOWN,
nwapi::nw__screen::OnSourceOrderChanged::kEventName,
std::move(args));
}
void NwDesktopCaptureMonitor::OnSourceNameChanged(int index) {
DesktopMediaList::Source src = media_list_[0]->GetSource(index);
std::vector<base::Value> args = nwapi::nw__screen::OnSourceNameChanged::Create(
src.id.ToString(),
base::UTF16ToUTF8(src.name));
DispatchEvent(
events::HistogramValue::UNKNOWN,
nwapi::nw__screen::OnSourceNameChanged::kEventName,
std::move(args));
}
void NwDesktopCaptureMonitor::OnSourcePreviewChanged(size_t index) {
}
void NwDesktopCaptureMonitor::OnSourceThumbnailChanged(int index) {
std::string base64;
DesktopMediaList::Source src = media_list_[0]->GetSource(index);
SkBitmap bitmap = src.thumbnail.GetRepresentation(1).GetBitmap();
std::vector<unsigned char> data;
bool success = gfx::PNGCodec::EncodeBGRASkBitmap(bitmap, false, &data);
if (success){
base::StringPiece raw_str(reinterpret_cast<const char*>(&data[0]), data.size());
base::Base64Encode(raw_str, &base64);
}
std::vector<base::Value> args = nwapi::nw__screen::OnSourceThumbnailChanged::Create(
src.id.ToString(),
base64);
DispatchEvent(
events::HistogramValue::UNKNOWN,
nwapi::nw__screen::OnSourceThumbnailChanged::kEventName,
std::move(args));
}
NwScreenStartMonitorFunction::NwScreenStartMonitorFunction() {}
bool NwScreenStartMonitorFunction::RunNWSync(base::ListValue* response, std::string* error) {
bool screens, windows;
EXTENSION_FUNCTION_VALIDATE(args().size() >= 2);
EXTENSION_FUNCTION_VALIDATE(args()[0].is_bool() && args()[1].is_bool());
screens = args()[0].GetBool();
windows = args()[1].GetBool();
NwDesktopCaptureMonitor::GetInstance()->Start(screens, windows);
return true;
}
NwScreenStopMonitorFunction::NwScreenStopMonitorFunction() {}
bool NwScreenStopMonitorFunction::RunNWSync(base::ListValue* response, std::string* error) {
NwDesktopCaptureMonitor::GetInstance()->Stop();
return true;
}
NwScreenIsMonitorStartedFunction::NwScreenIsMonitorStartedFunction() {}
bool NwScreenIsMonitorStartedFunction::RunNWSync(base::ListValue* response, std::string* error) {
response->Append(NwDesktopCaptureMonitor::GetInstance()->IsStarted());
return true;
}
NwScreenRegisterStreamFunction::NwScreenRegisterStreamFunction() {}
bool NwScreenRegisterStreamFunction::RunNWSync(base::ListValue* response, std::string* error) {
std::string id;
EXTENSION_FUNCTION_VALIDATE(args().size() >= 1);
EXTENSION_FUNCTION_VALIDATE(args()[0].is_string());
id = args()[0].GetString();
// following code is modified from `DesktopCaptureChooseDesktopMediaFunctionBase::OnPickerDialogResults`
// in chrome/browser/extensions/api/desktop_capture/desktop_capture_base.cc
content::DesktopMediaID source = content::DesktopMediaID::Parse(id);
content::WebContents* web_contents = GetSenderWebContents();
if (!source.is_null() && web_contents) {
std::string result;
source.audio_share = true;
content::DesktopStreamsRegistry* registry = content::DesktopStreamsRegistry::GetInstance();
// TODO(miu): Once render_frame_host() is being set, we should register the
// exact RenderFrame requesting the stream, not the main RenderFrame. With
// that change, also update
// MediaCaptureDevicesDispatcher::ProcessDesktopCaptureAccessRequest().
// http://crbug.com/304341
content::RenderFrameHost* const main_frame = web_contents->GetMainFrame();
result = registry->RegisterStream(main_frame->GetProcess()->GetID(),
main_frame->GetRoutingID(),
url::Origin::Create(web_contents->GetURL().DeprecatedGetOriginAsURL()),
source,
extension()->name(), content::kRegistryStreamTypeDesktop);
response->Append(result);
}
return true;
}
} // extensions
<|endoftext|> |
<commit_before>// Copied from public information at: http://www.evl.uic.edu/pape/CAVE/prog/
//
// Thanks Dave.
//
#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <drivers/Open/Trackd/trackdmem.h>
#if !defined(VPR_OS_Windows)
#include <sys/ipc.h>
#include <sys/shm.h>
#endif
// ===========================================================================
// trackd tracker API
struct TrackerConnection
{
#if defined(VPR_OS_Windows)
HANDLE file_mapping;
CAVE_TRACKDTRACKER_HEADER* tracker;
#else
int
CAVE_TRACKDTRACKER_HEADER* tracker;
#endif
};
TrackerConnection*
trackd_tracker_attach(int shmKey)
{
TrackerConnection* t = new TrackerConnection();
#if defined(VPR_OS_Windows)
char shmfile[256];
sprintf(shmfile, "%d", shmKey);
t->file_mapping = OpenFileMapping(FILE_MAP_READ, FALSE, shmfile);
if(!t->file_mapping)
{
fprintf(stderr, "ERROR: cannot get tracker shared memory\n");
perror("OpenFileMapping");
return NULL;
}
t->tracker =
reinterpret_cast<CAVE_TRACKDTRACKER_HEADER*>(
MapViewOfFile(t->file_mapping, FILE_MAP_READ, 0, 0, 0));
if(!t->tracker)
{
fprintf(stderr, "ERROR: cannot attach tracker shared memory\n");
perror("MapViewOfFile");
return NULL;
}
#else
t->shmid = shmget(shmKey, sizeof(CAVE_TRACKDTRACKER_HEADER), 0);
if(t->shmid < 0)
{
fprintf(stderr,"ERROR: can't get tracker shared memory\n");
perror("shmget");
return NULL;
}
t->tracker =
reinterpret_cast<CAVE_TRACKDTRACKER_HEADER*>(
shmat(t->shmid, (void *) 0, 0));
if(t->tracker == reinterpret_cast<CAVE_TRACKDTRACKER_HEADER*>(-1))
{
fprintf(stderr,"ERROR: can't attach tracker shared memory\n");
perror("shmat");
return NULL;
}
#endif
return t;
}
void
trackd_tracker_release(TrackerConnection* t)
{
#if defined(VPR_OS_Windows)
if(t && t->tracker)
{
UnmapViewOfFile(t->tracker);
CloseHandle(t->file_mapping);
}
#else
if(t && t->tracker)
{
# ifdef __sun__
# if defined(_XOPEN_SOURCE) && (_XOPEN_VERSION - 0 >= 4)
shmdt(t->tracker);
# else
shmdt((char*) t->tracker);
# endif
# else
shmdt(t->tracker);
# endif
}
#endif
delete t;
}
int
trackd_tracker_num_sensors(TrackerConnection* t)
{
return t->tracker->numSensors;
}
CAVE_SENSOR_ST*
trackd_tracker_sensor(TrackerConnection* t, int sensorNum)
{
unsigned char* pointer =
reinterpret_cast<unsigned char*>(t->tracker);
pointer += t->tracker->sensorOffset + sensorNum * t->tracker->sensorSize;
return reinterpret_cast<CAVE_SENSOR_ST*>(pointer);
}
// ===========================================================================
// trackd controller API
struct ControllerConnection
{
#if defined(VPR_OS_Windows)
HANDLE file_mapping;
CAVE_TRACKDCONTROLLER_HEADER* controller;
#else
int shmid;
CAVE_TRACKDCONTROLLER_HEADER* controller;
#endif
};
ControllerConnection*
trackd_controller_attach(int shmKey)
{
ControllerConnection* c = new ControllerConnection();
#if defined(VPR_OS_Windows)
char shmfile[256];
sprintf(shmfile, "%d", shmKey);
c->file_mapping = OpenFileMapping(FILE_MAP_READ, FALSE, shmfile);
if(!c->file_mapping)
{
fprintf(stderr, "ERROR: cannot get controller shared memory\n");
perror("OpenFileMapping");
return NULL;
}
c->controller =
reinterpret_cast<CAVE_TRACKDCONTROLLER_HEADER*>(
MapViewOfFile(c->file_mapping, FILE_MAP_READ, 0, 0, 0));
if(!c->controller)
{
fprintf(stderr, "ERROR: cannot attach controller shared memory\n");
perror("MapViewOfFile");
return NULL;
}
#else
c->shmid = shmget(shmKey, sizeof(CAVE_TRACKDCONTROLLER_HEADER), 0);
if(c->shmid < 0)
{
fprintf(stderr,"ERROR: can't get controller shared memory\n");
perror("shmget");
return NULL;
}
c->controller =
reinterpret_cast<CAVE_TRACKDCONTROLLER_HEADER*>(
shmat(controller_shmid, (void *) 0, 0));
if(c->controller == (CAVE_TRACKDCONTROLLER_HEADER *) -1)
{
fprintf(stderr,"ERROR: can't attach controller shared memory\n");
perror("shmat");
return NULL;
}
#endif
return c;
}
void
trackd_controller_release(ControllerConnection* c)
{
#if defined(VPR_OS_Windows)
if(c && c->controller)
{
UnmapViewOfFile(c->controller);
CloseHandle(c->file_mapping);
}
#else
if(c && c->controller)
{
# ifdef __sun__
# if defined(_XOPEN_SOURCE) && (_XOPEN_VERSION - 0 >= 4)
shmdt(c->controller);
# else
shmdt((char*) c->controller);
# endif
# else
shmdt(c->controller);
# endif
}
#endif
delete c;
}
int
trackd_controller_num_buttons(ControllerConnection* c)
{
return c->controller->numButtons;
}
int
trackd_controller_num_valuators(ControllerConnection* c)
{
return c->controller->numValuators;
}
int
trackd_controller_button(ControllerConnection* c, int buttonNum)
{
unsigned char* pointer =
reinterpret_cast<unsigned char*>(c->controller)
+ c->controller->buttonOffset;
int* buttons = reinterpret_cast<int*>(pointer);
return buttons[buttonNum];
}
float
trackd_controller_valuator(ControllerConnection* c, int valuatorNum)
{
unsigned char* pointer =
reinterpret_cast<unsigned char*>(c->controller)
+ c->controller->valuatorOffset;
float* valuators = reinterpret_cast<float*>(pointer);
return valuators[valuatorNum];
}
<commit_msg>fix unix compile errors<commit_after>// Copied from public information at: http://www.evl.uic.edu/pape/CAVE/prog/
//
// Thanks Dave.
//
#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <drivers/Open/Trackd/trackdmem.h>
#if !defined(VPR_OS_Windows)
#include <sys/ipc.h>
#include <sys/shm.h>
#endif
// ===========================================================================
// trackd tracker API
struct TrackerConnection
{
#if defined(VPR_OS_Windows)
HANDLE file_mapping;
CAVE_TRACKDTRACKER_HEADER* tracker;
#else
int shmid;
CAVE_TRACKDTRACKER_HEADER* tracker;
#endif
};
TrackerConnection*
trackd_tracker_attach(int shmKey)
{
TrackerConnection* t = new TrackerConnection();
#if defined(VPR_OS_Windows)
char shmfile[256];
sprintf(shmfile, "%d", shmKey);
t->file_mapping = OpenFileMapping(FILE_MAP_READ, FALSE, shmfile);
if(!t->file_mapping)
{
fprintf(stderr, "ERROR: cannot get tracker shared memory\n");
perror("OpenFileMapping");
return NULL;
}
t->tracker =
reinterpret_cast<CAVE_TRACKDTRACKER_HEADER*>(
MapViewOfFile(t->file_mapping, FILE_MAP_READ, 0, 0, 0));
if(!t->tracker)
{
fprintf(stderr, "ERROR: cannot attach tracker shared memory\n");
perror("MapViewOfFile");
return NULL;
}
#else
t->shmid = shmget(shmKey, sizeof(CAVE_TRACKDTRACKER_HEADER), 0);
if(t->shmid < 0)
{
fprintf(stderr,"ERROR: can't get tracker shared memory\n");
perror("shmget");
return NULL;
}
t->tracker =
reinterpret_cast<CAVE_TRACKDTRACKER_HEADER*>(
shmat(t->shmid, (void *) 0, 0));
if(t->tracker == reinterpret_cast<CAVE_TRACKDTRACKER_HEADER*>(-1))
{
fprintf(stderr,"ERROR: can't attach tracker shared memory\n");
perror("shmat");
return NULL;
}
#endif
return t;
}
void
trackd_tracker_release(TrackerConnection* t)
{
#if defined(VPR_OS_Windows)
if(t && t->tracker)
{
UnmapViewOfFile(t->tracker);
CloseHandle(t->file_mapping);
}
#else
if(t && t->tracker)
{
# ifdef __sun__
# if defined(_XOPEN_SOURCE) && (_XOPEN_VERSION - 0 >= 4)
shmdt(t->tracker);
# else
shmdt((char*) t->tracker);
# endif
# else
shmdt(t->tracker);
# endif
}
#endif
delete t;
}
int
trackd_tracker_num_sensors(TrackerConnection* t)
{
return t->tracker->numSensors;
}
CAVE_SENSOR_ST*
trackd_tracker_sensor(TrackerConnection* t, int sensorNum)
{
unsigned char* pointer =
reinterpret_cast<unsigned char*>(t->tracker);
pointer += t->tracker->sensorOffset + sensorNum * t->tracker->sensorSize;
return reinterpret_cast<CAVE_SENSOR_ST*>(pointer);
}
// ===========================================================================
// trackd controller API
struct ControllerConnection
{
#if defined(VPR_OS_Windows)
HANDLE file_mapping;
CAVE_TRACKDCONTROLLER_HEADER* controller;
#else
int shmid;
CAVE_TRACKDCONTROLLER_HEADER* controller;
#endif
};
ControllerConnection*
trackd_controller_attach(int shmKey)
{
ControllerConnection* c = new ControllerConnection();
#if defined(VPR_OS_Windows)
char shmfile[256];
sprintf(shmfile, "%d", shmKey);
c->file_mapping = OpenFileMapping(FILE_MAP_READ, FALSE, shmfile);
if(!c->file_mapping)
{
fprintf(stderr, "ERROR: cannot get controller shared memory\n");
perror("OpenFileMapping");
return NULL;
}
c->controller =
reinterpret_cast<CAVE_TRACKDCONTROLLER_HEADER*>(
MapViewOfFile(c->file_mapping, FILE_MAP_READ, 0, 0, 0));
if(!c->controller)
{
fprintf(stderr, "ERROR: cannot attach controller shared memory\n");
perror("MapViewOfFile");
return NULL;
}
#else
c->shmid = shmget(shmKey, sizeof(CAVE_TRACKDCONTROLLER_HEADER), 0);
if(c->shmid < 0)
{
fprintf(stderr,"ERROR: can't get controller shared memory\n");
perror("shmget");
return NULL;
}
c->controller =
reinterpret_cast<CAVE_TRACKDCONTROLLER_HEADER*>(
shmat(c->shmid, (void *) 0, 0));
if(c->controller == (CAVE_TRACKDCONTROLLER_HEADER *) -1)
{
fprintf(stderr,"ERROR: can't attach controller shared memory\n");
perror("shmat");
return NULL;
}
#endif
return c;
}
void
trackd_controller_release(ControllerConnection* c)
{
#if defined(VPR_OS_Windows)
if(c && c->controller)
{
UnmapViewOfFile(c->controller);
CloseHandle(c->file_mapping);
}
#else
if(c && c->controller)
{
# ifdef __sun__
# if defined(_XOPEN_SOURCE) && (_XOPEN_VERSION - 0 >= 4)
shmdt(c->controller);
# else
shmdt((char*) c->controller);
# endif
# else
shmdt(c->controller);
# endif
}
#endif
delete c;
}
int
trackd_controller_num_buttons(ControllerConnection* c)
{
return c->controller->numButtons;
}
int
trackd_controller_num_valuators(ControllerConnection* c)
{
return c->controller->numValuators;
}
int
trackd_controller_button(ControllerConnection* c, int buttonNum)
{
unsigned char* pointer =
reinterpret_cast<unsigned char*>(c->controller)
+ c->controller->buttonOffset;
int* buttons = reinterpret_cast<int*>(pointer);
return buttons[buttonNum];
}
float
trackd_controller_valuator(ControllerConnection* c, int valuatorNum)
{
unsigned char* pointer =
reinterpret_cast<unsigned char*>(c->controller)
+ c->controller->valuatorOffset;
float* valuators = reinterpret_cast<float*>(pointer);
return valuators[valuatorNum];
}
<|endoftext|> |
<commit_before>/*
* Copyright (c) 2010 ARM Limited
* All rights reserved
*
* The license below extends only to copyright in the software and shall
* not be construed as granting a license to any other intellectual
* property including but not limited to intellectual property relating
* to a hardware implementation of the functionality of the software
* licensed hereunder. You may use the software subject to the license
* terms below provided that you ensure that this notice is replicated
* unmodified and in its entirety in all distributions of the software,
* modified or unmodified, in source code or in binary form.
*
* Copyright (c) 2009 The Regents of The University of Michigan
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are
* met: redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer;
* redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution;
* neither the name of the copyright holders nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* 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.
*
* Authors: Gabe Black
*/
#ifndef __ARCH_ARM_MISCREGS_HH__
#define __ARCH_ARM_MISCREGS_HH__
#include "base/bitunion.hh"
namespace ArmISA
{
enum ConditionCode {
COND_EQ = 0,
COND_NE, // 1
COND_CS, // 2
COND_CC, // 3
COND_MI, // 4
COND_PL, // 5
COND_VS, // 6
COND_VC, // 7
COND_HI, // 8
COND_LS, // 9
COND_GE, // 10
COND_LT, // 11
COND_GT, // 12
COND_LE, // 13
COND_AL, // 14
COND_UC // 15
};
enum MiscRegIndex {
MISCREG_CPSR = 0,
MISCREG_SPSR,
MISCREG_SPSR_FIQ,
MISCREG_SPSR_IRQ,
MISCREG_SPSR_SVC,
MISCREG_SPSR_MON,
MISCREG_SPSR_UND,
MISCREG_SPSR_ABT,
MISCREG_FPSR,
MISCREG_FPSID,
MISCREG_FPSCR,
MISCREG_FPEXC,
MISCREG_MVFR0,
MISCREG_MVFR1,
MISCREG_SEV_MAILBOX,
// CP15 registers
MISCREG_CP15_START,
MISCREG_SCTLR = MISCREG_CP15_START,
MISCREG_DCCISW,
MISCREG_DCCIMVAC,
MISCREG_DCCMVAC,
MISCREG_CONTEXTIDR,
MISCREG_TPIDRURW,
MISCREG_TPIDRURO,
MISCREG_TPIDRPRW,
MISCREG_CP15ISB,
MISCREG_CP15DSB,
MISCREG_CP15DMB,
MISCREG_CPACR,
MISCREG_CLIDR,
MISCREG_CCSIDR,
MISCREG_CSSELR,
MISCREG_ICIALLUIS,
MISCREG_ICIALLU,
MISCREG_ICIMVAU,
MISCREG_BPIMVA,
MISCREG_BPIALLIS,
MISCREG_BPIALL,
MISCREG_MIDR,
MISCREG_TTBR0,
MISCREG_TTBR1,
MISCREG_CP15_UNIMP_START,
MISCREG_CTR = MISCREG_CP15_UNIMP_START,
MISCREG_TLBTR,
MISCREG_TCMTR,
MISCREG_MPIDR,
MISCREG_ID_PFR0,
MISCREG_ID_PFR1,
MISCREG_ID_DFR0,
MISCREG_ID_AFR0,
MISCREG_ID_MMFR0,
MISCREG_ID_MMFR1,
MISCREG_ID_MMFR2,
MISCREG_ID_MMFR3,
MISCREG_ID_ISAR0,
MISCREG_ID_ISAR1,
MISCREG_ID_ISAR2,
MISCREG_ID_ISAR3,
MISCREG_ID_ISAR4,
MISCREG_ID_ISAR5,
MISCREG_PAR,
MISCREG_AIDR,
MISCREG_ACTLR,
MISCREG_DACR,
MISCREG_DFSR,
MISCREG_IFSR,
MISCREG_ADFSR,
MISCREG_AIFSR,
MISCREG_DFAR,
MISCREG_IFAR,
MISCREG_DCIMVAC,
MISCREG_DCISW,
MISCREG_MCCSW,
MISCREG_DCCMVAU,
MISCREG_SCR,
MISCREG_SDER,
MISCREG_NSACR,
MISCREG_TTBCR,
MISCREG_V2PCWPR,
MISCREG_V2PCWPW,
MISCREG_V2PCWUR,
MISCREG_V2PCWUW,
MISCREG_V2POWPR,
MISCREG_V2POWPW,
MISCREG_V2POWUR,
MISCREG_V2POWUW,
MISCREG_TLBIALLIS,
MISCREG_TLBIMVAIS,
MISCREG_TLBIASIDIS,
MISCREG_TLBIMVAAIS,
MISCREG_ITLBIALL,
MISCREG_ITLBIMVA,
MISCREG_ITLBIASID,
MISCREG_DTLBIALL,
MISCREG_DTLBIMVA,
MISCREG_DTLBIASID,
MISCREG_TLBIALL,
MISCREG_TLBIMVA,
MISCREG_TLBIASID,
MISCREG_TLBIMVAA,
MISCREG_PRRR,
MISCREG_NMRR,
MISCREG_VBAR,
MISCREG_MVBAR,
MISCREG_ISR,
MISCREG_FCEIDR,
MISCREG_CP15_END,
// Dummy indices
MISCREG_NOP = MISCREG_CP15_END,
MISCREG_RAZ,
NUM_MISCREGS
};
MiscRegIndex decodeCP15Reg(unsigned crn, unsigned opc1,
unsigned crm, unsigned opc2);
const char * const miscRegName[NUM_MISCREGS] = {
"cpsr", "spsr", "spsr_fiq", "spsr_irq", "spsr_svc",
"spsr_mon", "spsr_und", "spsr_abt",
"fpsr", "fpsid", "fpscr", "fpexc", "mvfr0", "mvfr1",
"sev_mailbox",
"sctlr", "dccisw", "dccimvac", "dccmvac",
"contextidr", "tpidrurw", "tpidruro", "tpidrprw",
"cp15isb", "cp15dsb", "cp15dmb", "cpacr",
"clidr", "ccsidr", "csselr",
"icialluis", "iciallu", "icimvau",
"bpimva", "bpiallis", "bpiall",
"midr", "ttbr0", "ttbr1", "ctr", "tlbtr", "tcmtr", "mpidr",
"id_pfr0", "id_pfr1", "id_dfr0", "id_afr0",
"id_mmfr0", "id_mmfr1", "id_mmfr2", "id_mmfr3",
"id_isar0", "id_isar1", "id_isar2", "id_isar3", "id_isar4", "id_isar5",
"par", "aidr", "actlr", "dacr",
"dfsr", "ifsr", "adfsr", "aifsr", "dfar", "ifar",
"dcimvac", "dcisw", "mccsw",
"dccmvau",
"scr", "sder", "nsacr", "ttbcr",
"v2pcwpr", "v2pcwpw", "v2pcwur", "v2pcwuw",
"v2powpr", "v2powpw", "v2powur", "v2powuw",
"tlbiallis", "tlbimvais", "tlbiasidis", "tlbimvaais",
"itlbiall", "itlbimva", "itlbiasid",
"dtlbiall", "dtlbimva", "dtlbiasid",
"tlbiall", "tlbimva", "tlbiasid", "tlbimvaa",
"prrr", "nmrr", "vbar", "mvbar", "isr", "fceidr",
"nop", "raz"
};
BitUnion32(CPSR)
Bitfield<31> n;
Bitfield<30> z;
Bitfield<29> c;
Bitfield<28> v;
Bitfield<27> q;
Bitfield<26,25> it1;
Bitfield<24> j;
Bitfield<19, 16> ge;
Bitfield<15,10> it2;
Bitfield<9> e;
Bitfield<8> a;
Bitfield<7> i;
Bitfield<6> f;
Bitfield<5> t;
Bitfield<4, 0> mode;
EndBitUnion(CPSR)
// This mask selects bits of the CPSR that actually go in the CondCodes
// integer register to allow renaming.
static const uint32_t CondCodesMask = 0xF80F0000;
BitUnion32(SCTLR)
Bitfield<30> te; // Thumb Exception Enable
Bitfield<29> afe; // Access flag enable
Bitfield<28> tre; // TEX Remap bit
Bitfield<27> nmfi;// Non-maskable fast interrupts enable
Bitfield<25> ee; // Exception Endianness bit
Bitfield<24> ve; // Interrupt vectors enable
Bitfield<23> rao1;// Read as one
Bitfield<22> u; // Alignment (now unused)
Bitfield<21> fi; // Fast interrupts configuration enable
Bitfield<18> rao2;// Read as one
Bitfield<17> ha; // Hardware access flag enable
Bitfield<16> rao3;// Read as one
Bitfield<14> rr; // Round robin cache replacement
Bitfield<13> v; // Base address for exception vectors
Bitfield<12> i; // instruction cache enable
Bitfield<11> z; // branch prediction enable bit
Bitfield<10> sw; // Enable swp/swpb
Bitfield<6,3> rao4;// Read as one
Bitfield<7> b; // Endianness support (unused)
Bitfield<2> c; // Cache enable bit
Bitfield<1> a; // Alignment fault checking
Bitfield<0> m; // MMU enable bit
EndBitUnion(SCTLR)
BitUnion32(CPACR)
Bitfield<1, 0> cp0;
Bitfield<3, 2> cp1;
Bitfield<5, 4> cp2;
Bitfield<7, 6> cp3;
Bitfield<9, 8> cp4;
Bitfield<11, 10> cp5;
Bitfield<13, 12> cp6;
Bitfield<15, 14> cp7;
Bitfield<17, 16> cp8;
Bitfield<19, 18> cp9;
Bitfield<21, 20> cp10;
Bitfield<23, 22> cp11;
Bitfield<25, 24> cp12;
Bitfield<27, 26> cp13;
Bitfield<30> d32dis;
Bitfield<31> asedis;
EndBitUnion(CPACR)
};
#endif // __ARCH_ARM_MISCREGS_HH__
<commit_msg>ARM: Handle accesses to the DACR.<commit_after>/*
* Copyright (c) 2010 ARM Limited
* All rights reserved
*
* The license below extends only to copyright in the software and shall
* not be construed as granting a license to any other intellectual
* property including but not limited to intellectual property relating
* to a hardware implementation of the functionality of the software
* licensed hereunder. You may use the software subject to the license
* terms below provided that you ensure that this notice is replicated
* unmodified and in its entirety in all distributions of the software,
* modified or unmodified, in source code or in binary form.
*
* Copyright (c) 2009 The Regents of The University of Michigan
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are
* met: redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer;
* redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution;
* neither the name of the copyright holders nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* 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.
*
* Authors: Gabe Black
*/
#ifndef __ARCH_ARM_MISCREGS_HH__
#define __ARCH_ARM_MISCREGS_HH__
#include "base/bitunion.hh"
namespace ArmISA
{
enum ConditionCode {
COND_EQ = 0,
COND_NE, // 1
COND_CS, // 2
COND_CC, // 3
COND_MI, // 4
COND_PL, // 5
COND_VS, // 6
COND_VC, // 7
COND_HI, // 8
COND_LS, // 9
COND_GE, // 10
COND_LT, // 11
COND_GT, // 12
COND_LE, // 13
COND_AL, // 14
COND_UC // 15
};
enum MiscRegIndex {
MISCREG_CPSR = 0,
MISCREG_SPSR,
MISCREG_SPSR_FIQ,
MISCREG_SPSR_IRQ,
MISCREG_SPSR_SVC,
MISCREG_SPSR_MON,
MISCREG_SPSR_UND,
MISCREG_SPSR_ABT,
MISCREG_FPSR,
MISCREG_FPSID,
MISCREG_FPSCR,
MISCREG_FPEXC,
MISCREG_MVFR0,
MISCREG_MVFR1,
MISCREG_SEV_MAILBOX,
// CP15 registers
MISCREG_CP15_START,
MISCREG_SCTLR = MISCREG_CP15_START,
MISCREG_DCCISW,
MISCREG_DCCIMVAC,
MISCREG_DCCMVAC,
MISCREG_CONTEXTIDR,
MISCREG_TPIDRURW,
MISCREG_TPIDRURO,
MISCREG_TPIDRPRW,
MISCREG_CP15ISB,
MISCREG_CP15DSB,
MISCREG_CP15DMB,
MISCREG_CPACR,
MISCREG_CLIDR,
MISCREG_CCSIDR,
MISCREG_CSSELR,
MISCREG_ICIALLUIS,
MISCREG_ICIALLU,
MISCREG_ICIMVAU,
MISCREG_BPIMVA,
MISCREG_BPIALLIS,
MISCREG_BPIALL,
MISCREG_MIDR,
MISCREG_TTBR0,
MISCREG_TTBR1,
MISCREG_DACR,
MISCREG_CP15_UNIMP_START,
MISCREG_CTR = MISCREG_CP15_UNIMP_START,
MISCREG_TLBTR,
MISCREG_TCMTR,
MISCREG_MPIDR,
MISCREG_ID_PFR0,
MISCREG_ID_PFR1,
MISCREG_ID_DFR0,
MISCREG_ID_AFR0,
MISCREG_ID_MMFR0,
MISCREG_ID_MMFR1,
MISCREG_ID_MMFR2,
MISCREG_ID_MMFR3,
MISCREG_ID_ISAR0,
MISCREG_ID_ISAR1,
MISCREG_ID_ISAR2,
MISCREG_ID_ISAR3,
MISCREG_ID_ISAR4,
MISCREG_ID_ISAR5,
MISCREG_PAR,
MISCREG_AIDR,
MISCREG_ACTLR,
MISCREG_DFSR,
MISCREG_IFSR,
MISCREG_ADFSR,
MISCREG_AIFSR,
MISCREG_DFAR,
MISCREG_IFAR,
MISCREG_DCIMVAC,
MISCREG_DCISW,
MISCREG_MCCSW,
MISCREG_DCCMVAU,
MISCREG_SCR,
MISCREG_SDER,
MISCREG_NSACR,
MISCREG_TTBCR,
MISCREG_V2PCWPR,
MISCREG_V2PCWPW,
MISCREG_V2PCWUR,
MISCREG_V2PCWUW,
MISCREG_V2POWPR,
MISCREG_V2POWPW,
MISCREG_V2POWUR,
MISCREG_V2POWUW,
MISCREG_TLBIALLIS,
MISCREG_TLBIMVAIS,
MISCREG_TLBIASIDIS,
MISCREG_TLBIMVAAIS,
MISCREG_ITLBIALL,
MISCREG_ITLBIMVA,
MISCREG_ITLBIASID,
MISCREG_DTLBIALL,
MISCREG_DTLBIMVA,
MISCREG_DTLBIASID,
MISCREG_TLBIALL,
MISCREG_TLBIMVA,
MISCREG_TLBIASID,
MISCREG_TLBIMVAA,
MISCREG_PRRR,
MISCREG_NMRR,
MISCREG_VBAR,
MISCREG_MVBAR,
MISCREG_ISR,
MISCREG_FCEIDR,
MISCREG_CP15_END,
// Dummy indices
MISCREG_NOP = MISCREG_CP15_END,
MISCREG_RAZ,
NUM_MISCREGS
};
MiscRegIndex decodeCP15Reg(unsigned crn, unsigned opc1,
unsigned crm, unsigned opc2);
const char * const miscRegName[NUM_MISCREGS] = {
"cpsr", "spsr", "spsr_fiq", "spsr_irq", "spsr_svc",
"spsr_mon", "spsr_und", "spsr_abt",
"fpsr", "fpsid", "fpscr", "fpexc", "mvfr0", "mvfr1",
"sev_mailbox",
"sctlr", "dccisw", "dccimvac", "dccmvac",
"contextidr", "tpidrurw", "tpidruro", "tpidrprw",
"cp15isb", "cp15dsb", "cp15dmb", "cpacr",
"clidr", "ccsidr", "csselr",
"icialluis", "iciallu", "icimvau",
"bpimva", "bpiallis", "bpiall",
"midr", "ttbr0", "ttbr1", "dacr", "ctr", "tlbtr", "tcmtr", "mpidr",
"id_pfr0", "id_pfr1", "id_dfr0", "id_afr0",
"id_mmfr0", "id_mmfr1", "id_mmfr2", "id_mmfr3",
"id_isar0", "id_isar1", "id_isar2", "id_isar3", "id_isar4", "id_isar5",
"par", "aidr", "actlr",
"dfsr", "ifsr", "adfsr", "aifsr", "dfar", "ifar",
"dcimvac", "dcisw", "mccsw",
"dccmvau",
"scr", "sder", "nsacr", "ttbcr",
"v2pcwpr", "v2pcwpw", "v2pcwur", "v2pcwuw",
"v2powpr", "v2powpw", "v2powur", "v2powuw",
"tlbiallis", "tlbimvais", "tlbiasidis", "tlbimvaais",
"itlbiall", "itlbimva", "itlbiasid",
"dtlbiall", "dtlbimva", "dtlbiasid",
"tlbiall", "tlbimva", "tlbiasid", "tlbimvaa",
"prrr", "nmrr", "vbar", "mvbar", "isr", "fceidr",
"nop", "raz"
};
BitUnion32(CPSR)
Bitfield<31> n;
Bitfield<30> z;
Bitfield<29> c;
Bitfield<28> v;
Bitfield<27> q;
Bitfield<26,25> it1;
Bitfield<24> j;
Bitfield<19, 16> ge;
Bitfield<15,10> it2;
Bitfield<9> e;
Bitfield<8> a;
Bitfield<7> i;
Bitfield<6> f;
Bitfield<5> t;
Bitfield<4, 0> mode;
EndBitUnion(CPSR)
// This mask selects bits of the CPSR that actually go in the CondCodes
// integer register to allow renaming.
static const uint32_t CondCodesMask = 0xF80F0000;
BitUnion32(SCTLR)
Bitfield<30> te; // Thumb Exception Enable
Bitfield<29> afe; // Access flag enable
Bitfield<28> tre; // TEX Remap bit
Bitfield<27> nmfi;// Non-maskable fast interrupts enable
Bitfield<25> ee; // Exception Endianness bit
Bitfield<24> ve; // Interrupt vectors enable
Bitfield<23> rao1;// Read as one
Bitfield<22> u; // Alignment (now unused)
Bitfield<21> fi; // Fast interrupts configuration enable
Bitfield<18> rao2;// Read as one
Bitfield<17> ha; // Hardware access flag enable
Bitfield<16> rao3;// Read as one
Bitfield<14> rr; // Round robin cache replacement
Bitfield<13> v; // Base address for exception vectors
Bitfield<12> i; // instruction cache enable
Bitfield<11> z; // branch prediction enable bit
Bitfield<10> sw; // Enable swp/swpb
Bitfield<6,3> rao4;// Read as one
Bitfield<7> b; // Endianness support (unused)
Bitfield<2> c; // Cache enable bit
Bitfield<1> a; // Alignment fault checking
Bitfield<0> m; // MMU enable bit
EndBitUnion(SCTLR)
BitUnion32(CPACR)
Bitfield<1, 0> cp0;
Bitfield<3, 2> cp1;
Bitfield<5, 4> cp2;
Bitfield<7, 6> cp3;
Bitfield<9, 8> cp4;
Bitfield<11, 10> cp5;
Bitfield<13, 12> cp6;
Bitfield<15, 14> cp7;
Bitfield<17, 16> cp8;
Bitfield<19, 18> cp9;
Bitfield<21, 20> cp10;
Bitfield<23, 22> cp11;
Bitfield<25, 24> cp12;
Bitfield<27, 26> cp13;
Bitfield<30> d32dis;
Bitfield<31> asedis;
EndBitUnion(CPACR)
};
#endif // __ARCH_ARM_MISCREGS_HH__
<|endoftext|> |
<commit_before>//===--- Linker.cpp -------------------------------------------------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
///
/// \file
///
/// The SIL linker walks the call graph beginning at a starting function,
/// deserializing functions, vtables and witness tables.
///
/// The behavior of the linker is controlled by a LinkMode value. The LinkMode
/// has three possible values:
///
/// - LinkNone: The linker does not deserialize anything. This is only used for
/// debugging and testing purposes, and never during normal operation.
///
/// - LinkNormal: The linker deserializes bodies for declarations that must be
/// emitted into the client because they do not have definitions available
/// externally. This includes:
///
/// - witness tables for imported conformances
///
/// - functions with shared linkage
///
/// - LinkAll: All reachable functions (including public functions) are
/// deserialized, including public functions.
///
/// The primary entry point into the linker is the SILModule::linkFunction()
/// function, which recursively walks the call graph starting from the given
/// function.
///
/// In the mandatory pipeline (-Onone), the linker is invoked from the mandatory
/// SIL linker pass, which pulls in just enough to allow us to emit code, using
/// LinkNormal mode.
///
/// In the performance pipeline, after guaranteed optimizations but before
/// performance optimizations, the 'performance SILLinker' pass links
/// transitively all reachable functions, to uncover optimization opportunities
/// that might be missed from deserializing late. The performance pipeline uses
/// LinkAll mode.
///
/// *NOTE*: In LinkAll mode, we deserialize all vtables and witness tables,
/// even those with public linkage. This is not strictly necessary, since the
/// devirtualizer deserializes vtables and witness tables as needed. However,
/// doing so early creates more opportunities for optimization.
///
//===----------------------------------------------------------------------===//
#define DEBUG_TYPE "sil-linker"
#include "Linker.h"
#include "llvm/ADT/Statistic.h"
#include "llvm/ADT/FoldingSet.h"
#include "llvm/ADT/SmallString.h"
#include "llvm/ADT/StringSwitch.h"
#include "llvm/Support/Debug.h"
#include "swift/AST/ProtocolConformance.h"
#include "swift/AST/SubstitutionMap.h"
#include "swift/ClangImporter/ClangModule.h"
#include "swift/SIL/FormalLinkage.h"
#include <functional>
using namespace swift;
using namespace Lowering;
STATISTIC(NumFuncLinked, "Number of SIL functions linked");
//===----------------------------------------------------------------------===//
// Linker Helpers
//===----------------------------------------------------------------------===//
void SILLinkerVisitor::addFunctionToWorklist(SILFunction *F) {
assert(F->isExternalDeclaration());
LLVM_DEBUG(llvm::dbgs() << "Imported function: "
<< F->getName() << "\n");
if (Mod.loadFunction(F)) {
if (F->isExternalDeclaration())
return;
F->setBare(IsBare);
F->verify();
Worklist.push_back(F);
Changed = true;
++NumFuncLinked;
}
}
/// Deserialize a function and add it to the worklist for processing.
void SILLinkerVisitor::maybeAddFunctionToWorklist(SILFunction *F) {
// Don't need to do anything if the function already has a body.
if (!F->isExternalDeclaration())
return;
// In the performance pipeline, we deserialize all reachable functions.
if (isLinkAll())
return addFunctionToWorklist(F);
// Otherwise, make sure to deserialize shared functions; we need to
// emit them into the client binary since they're not available
// externally.
if (hasSharedVisibility(F->getLinkage()))
return addFunctionToWorklist(F);
// Functions with PublicNonABI linkage are deserialized as having
// HiddenExternal linkage when they are declarations, then they
// become SharedExternal after the body has been deserialized.
// So try deserializing HiddenExternal functions too.
if (F->getLinkage() == SILLinkage::HiddenExternal)
return addFunctionToWorklist(F);
}
/// Process F, recursively deserializing any thing F may reference.
bool SILLinkerVisitor::processFunction(SILFunction *F) {
// If F is a declaration, first deserialize it.
if (F->isExternalDeclaration()) {
maybeAddFunctionToWorklist(F);
} else {
Worklist.push_back(F);
}
process();
return Changed;
}
/// Deserialize the given VTable all SIL the VTable transitively references.
void SILLinkerVisitor::linkInVTable(ClassDecl *D) {
// Devirtualization already deserializes vtables as needed in both the
// mandatory and performance pipelines, and we don't support specialized
// vtables that might have shared linkage yet, so this is only needed in
// the performance pipeline to deserialize more functions early, and expose
// optimization opportunities.
assert(isLinkAll());
// Attempt to lookup the Vtbl from the SILModule.
SILVTable *Vtbl = Mod.lookUpVTable(D);
if (!Vtbl)
return;
// Ok we found our VTable. Visit each function referenced by the VTable. If
// any of the functions are external declarations, add them to the worklist
// for processing.
for (auto P : Vtbl->getEntries()) {
// Deserialize and recursively walk any vtable entries that do not have
// bodies yet.
maybeAddFunctionToWorklist(P.Implementation);
}
}
//===----------------------------------------------------------------------===//
// Visitors
//===----------------------------------------------------------------------===//
void SILLinkerVisitor::visitApplyInst(ApplyInst *AI) {
visitApplySubstitutions(AI->getSubstitutionMap());
}
void SILLinkerVisitor::visitTryApplyInst(TryApplyInst *TAI) {
visitApplySubstitutions(TAI->getSubstitutionMap());
}
void SILLinkerVisitor::visitPartialApplyInst(PartialApplyInst *PAI) {
visitApplySubstitutions(PAI->getSubstitutionMap());
}
void SILLinkerVisitor::visitFunctionRefInst(FunctionRefInst *FRI) {
maybeAddFunctionToWorklist(FRI->getReferencedFunction());
}
void SILLinkerVisitor::visitDynamicFunctionRefInst(
DynamicFunctionRefInst *FRI) {
maybeAddFunctionToWorklist(FRI->getReferencedFunction());
}
void SILLinkerVisitor::visitPreviousDynamicFunctionRefInst(
PreviousDynamicFunctionRefInst *FRI) {
maybeAddFunctionToWorklist(FRI->getReferencedFunction());
}
// Eagerly visiting all used conformances leads to a large blowup
// in the amount of SIL we read in. For optimization purposes we can defer
// reading in most conformances until we need them for devirtualization.
// However, we *must* pull in shared clang-importer-derived conformances
// we potentially use, since we may not otherwise have a local definition.
static bool mustDeserializeProtocolConformance(SILModule &M,
ProtocolConformanceRef c) {
if (!c.isConcrete())
return false;
auto conformance = c.getConcrete()->getRootNormalConformance();
return M.Types.protocolRequiresWitnessTable(conformance->getProtocol())
&& isa<ClangModuleUnit>(conformance->getDeclContext()
->getModuleScopeContext());
}
void SILLinkerVisitor::visitProtocolConformance(
ProtocolConformanceRef ref, const Optional<SILDeclRef> &Member) {
// If an abstract protocol conformance was passed in, just return false.
if (ref.isAbstract())
return;
bool mustDeserialize = mustDeserializeProtocolConformance(Mod, ref);
// Otherwise try and lookup a witness table for C.
auto C = ref.getConcrete();
if (!VisitedConformances.insert(C).second)
return;
SILWitnessTable *WT = Mod.lookUpWitnessTable(C, /*deserializeLazily=*/false);
// If we don't find any witness table for the conformance, bail and return
// false.
if (!WT) {
Mod.createWitnessTableDeclaration(C);
// Adding the declaration may allow us to now deserialize the body.
// Force the body if we must deserialize this witness table.
if (mustDeserialize) {
WT = Mod.lookUpWitnessTable(C, /*deserializeLazily=*/true);
assert(WT && WT->isDefinition()
&& "unable to deserialize witness table when we must?!");
} else {
return;
}
}
// If the looked up witness table is a declaration, there is nothing we can
// do here. Just bail and return false.
if (WT->isDeclaration())
return;
auto maybeVisitRelatedConformance = [&](ProtocolConformanceRef c) {
// Formally all conformances referenced by a used conformance are used.
// However, eagerly visiting them all at this point leads to a large blowup
// in the amount of SIL we read in. For optimization purposes we can defer
// reading in most conformances until we need them for devirtualization.
// However, we *must* pull in shared clang-importer-derived conformances
// we potentially use, since we may not otherwise have a local definition.
if (mustDeserializeProtocolConformance(Mod, c))
visitProtocolConformance(c, None);
};
// For each entry in the witness table...
for (auto &E : WT->getEntries()) {
switch (E.getKind()) {
// If the entry is a witness method...
case SILWitnessTable::WitnessKind::Method: {
// And we are only interested in deserializing a specific requirement
// and don't have that requirement, don't deserialize this method.
if (Member.hasValue() && E.getMethodWitness().Requirement != *Member)
continue;
// The witness could be removed by dead function elimination.
if (!E.getMethodWitness().Witness)
continue;
// Otherwise, deserialize the witness if it has shared linkage, or if
// we were asked to deserialize everything.
maybeAddFunctionToWorklist(E.getMethodWitness().Witness);
break;
}
// If the entry is a related witness table, see whether we need to
// eagerly deserialize it.
case SILWitnessTable::WitnessKind::BaseProtocol: {
auto baseConformance = E.getBaseProtocolWitness().Witness;
maybeVisitRelatedConformance(ProtocolConformanceRef(baseConformance));
break;
}
case SILWitnessTable::WitnessKind::AssociatedTypeProtocol: {
auto assocConformance = E.getAssociatedTypeProtocolWitness().Witness;
maybeVisitRelatedConformance(assocConformance);
break;
}
case SILWitnessTable::WitnessKind::AssociatedType:
case SILWitnessTable::WitnessKind::Invalid:
break;
}
}
}
void SILLinkerVisitor::visitApplySubstitutions(SubstitutionMap subs) {
for (auto conformance : subs.getConformances()) {
// Formally all conformances referenced in a function application are
// used. However, eagerly visiting them all at this point leads to a
// large blowup in the amount of SIL we read in, and we aren't very
// systematic about laziness. For optimization purposes we can defer
// reading in most conformances until we need them for devirtualization.
// However, we *must* pull in shared clang-importer-derived conformances
// we potentially use, since we may not otherwise have a local definition.
if (mustDeserializeProtocolConformance(Mod, conformance)) {
visitProtocolConformance(conformance, None);
}
}
}
void SILLinkerVisitor::visitInitExistentialAddrInst(
InitExistentialAddrInst *IEI) {
// Link in all protocol conformances that this touches.
//
// TODO: There might be a two step solution where the init_existential_inst
// causes the witness table to be brought in as a declaration and then the
// protocol method inst causes the actual deserialization. For now we are
// not going to be smart about this to enable avoiding any issues with
// visiting the open_existential_addr/witness_method before the
// init_existential_inst.
for (ProtocolConformanceRef C : IEI->getConformances()) {
visitProtocolConformance(C, Optional<SILDeclRef>());
}
}
void SILLinkerVisitor::visitInitExistentialRefInst(
InitExistentialRefInst *IERI) {
// Link in all protocol conformances that this touches.
//
// TODO: There might be a two step solution where the init_existential_inst
// causes the witness table to be brought in as a declaration and then the
// protocol method inst causes the actual deserialization. For now we are
// not going to be smart about this to enable avoiding any issues with
// visiting the protocol_method before the init_existential_inst.
for (ProtocolConformanceRef C : IERI->getConformances()) {
visitProtocolConformance(C, Optional<SILDeclRef>());
}
}
void SILLinkerVisitor::visitAllocRefInst(AllocRefInst *ARI) {
if (!isLinkAll())
return;
// Grab the class decl from the alloc ref inst.
ClassDecl *D = ARI->getType().getClassOrBoundGenericClass();
if (!D)
return;
linkInVTable(D);
}
void SILLinkerVisitor::visitMetatypeInst(MetatypeInst *MI) {
if (!isLinkAll())
return;
CanType instTy = MI->getType().castTo<MetatypeType>().getInstanceType();
ClassDecl *C = instTy.getClassOrBoundGenericClass();
if (!C)
return;
linkInVTable(C);
}
//===----------------------------------------------------------------------===//
// Top Level Routine
//===----------------------------------------------------------------------===//
// Main loop of the visitor. Called by one of the other *visit* methods.
void SILLinkerVisitor::process() {
// Process everything transitively referenced by one of the functions in the
// worklist.
while (!Worklist.empty()) {
auto *Fn = Worklist.pop_back_val();
if (Fn->getModule().isSerialized()) {
// If the containing module has been serialized,
// Remove The Serialized state (if any)
// This allows for more optimizations
Fn->setSerialized(IsSerialized_t::IsNotSerialized);
}
LLVM_DEBUG(llvm::dbgs() << "Process imports in function: "
<< Fn->getName() << "\n");
for (auto &BB : *Fn) {
for (auto &I : BB) {
visit(&I);
}
}
}
}
<commit_msg>SIL: Simplify SILLinkerVisitor::visitProtocolConformance()<commit_after>//===--- Linker.cpp -------------------------------------------------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
///
/// \file
///
/// The SIL linker walks the call graph beginning at a starting function,
/// deserializing functions, vtables and witness tables.
///
/// The behavior of the linker is controlled by a LinkMode value. The LinkMode
/// has three possible values:
///
/// - LinkNone: The linker does not deserialize anything. This is only used for
/// debugging and testing purposes, and never during normal operation.
///
/// - LinkNormal: The linker deserializes bodies for declarations that must be
/// emitted into the client because they do not have definitions available
/// externally. This includes:
///
/// - witness tables for imported conformances
///
/// - functions with shared linkage
///
/// - LinkAll: All reachable functions (including public functions) are
/// deserialized, including public functions.
///
/// The primary entry point into the linker is the SILModule::linkFunction()
/// function, which recursively walks the call graph starting from the given
/// function.
///
/// In the mandatory pipeline (-Onone), the linker is invoked from the mandatory
/// SIL linker pass, which pulls in just enough to allow us to emit code, using
/// LinkNormal mode.
///
/// In the performance pipeline, after guaranteed optimizations but before
/// performance optimizations, the 'performance SILLinker' pass links
/// transitively all reachable functions, to uncover optimization opportunities
/// that might be missed from deserializing late. The performance pipeline uses
/// LinkAll mode.
///
/// *NOTE*: In LinkAll mode, we deserialize all vtables and witness tables,
/// even those with public linkage. This is not strictly necessary, since the
/// devirtualizer deserializes vtables and witness tables as needed. However,
/// doing so early creates more opportunities for optimization.
///
//===----------------------------------------------------------------------===//
#define DEBUG_TYPE "sil-linker"
#include "Linker.h"
#include "llvm/ADT/Statistic.h"
#include "llvm/ADT/FoldingSet.h"
#include "llvm/ADT/SmallString.h"
#include "llvm/ADT/StringSwitch.h"
#include "llvm/Support/Debug.h"
#include "swift/AST/ProtocolConformance.h"
#include "swift/AST/SubstitutionMap.h"
#include "swift/ClangImporter/ClangModule.h"
#include "swift/SIL/FormalLinkage.h"
#include <functional>
using namespace swift;
using namespace Lowering;
STATISTIC(NumFuncLinked, "Number of SIL functions linked");
//===----------------------------------------------------------------------===//
// Linker Helpers
//===----------------------------------------------------------------------===//
void SILLinkerVisitor::addFunctionToWorklist(SILFunction *F) {
assert(F->isExternalDeclaration());
LLVM_DEBUG(llvm::dbgs() << "Imported function: "
<< F->getName() << "\n");
if (Mod.loadFunction(F)) {
if (F->isExternalDeclaration())
return;
F->setBare(IsBare);
F->verify();
Worklist.push_back(F);
Changed = true;
++NumFuncLinked;
}
}
/// Deserialize a function and add it to the worklist for processing.
void SILLinkerVisitor::maybeAddFunctionToWorklist(SILFunction *F) {
// Don't need to do anything if the function already has a body.
if (!F->isExternalDeclaration())
return;
// In the performance pipeline, we deserialize all reachable functions.
if (isLinkAll())
return addFunctionToWorklist(F);
// Otherwise, make sure to deserialize shared functions; we need to
// emit them into the client binary since they're not available
// externally.
if (hasSharedVisibility(F->getLinkage()))
return addFunctionToWorklist(F);
// Functions with PublicNonABI linkage are deserialized as having
// HiddenExternal linkage when they are declarations, then they
// become SharedExternal after the body has been deserialized.
// So try deserializing HiddenExternal functions too.
if (F->getLinkage() == SILLinkage::HiddenExternal)
return addFunctionToWorklist(F);
}
/// Process F, recursively deserializing any thing F may reference.
bool SILLinkerVisitor::processFunction(SILFunction *F) {
// If F is a declaration, first deserialize it.
if (F->isExternalDeclaration()) {
maybeAddFunctionToWorklist(F);
} else {
Worklist.push_back(F);
}
process();
return Changed;
}
/// Deserialize the given VTable all SIL the VTable transitively references.
void SILLinkerVisitor::linkInVTable(ClassDecl *D) {
// Devirtualization already deserializes vtables as needed in both the
// mandatory and performance pipelines, and we don't support specialized
// vtables that might have shared linkage yet, so this is only needed in
// the performance pipeline to deserialize more functions early, and expose
// optimization opportunities.
assert(isLinkAll());
// Attempt to lookup the Vtbl from the SILModule.
SILVTable *Vtbl = Mod.lookUpVTable(D);
if (!Vtbl)
return;
// Ok we found our VTable. Visit each function referenced by the VTable. If
// any of the functions are external declarations, add them to the worklist
// for processing.
for (auto P : Vtbl->getEntries()) {
// Deserialize and recursively walk any vtable entries that do not have
// bodies yet.
maybeAddFunctionToWorklist(P.Implementation);
}
}
//===----------------------------------------------------------------------===//
// Visitors
//===----------------------------------------------------------------------===//
void SILLinkerVisitor::visitApplyInst(ApplyInst *AI) {
visitApplySubstitutions(AI->getSubstitutionMap());
}
void SILLinkerVisitor::visitTryApplyInst(TryApplyInst *TAI) {
visitApplySubstitutions(TAI->getSubstitutionMap());
}
void SILLinkerVisitor::visitPartialApplyInst(PartialApplyInst *PAI) {
visitApplySubstitutions(PAI->getSubstitutionMap());
}
void SILLinkerVisitor::visitFunctionRefInst(FunctionRefInst *FRI) {
maybeAddFunctionToWorklist(FRI->getReferencedFunction());
}
void SILLinkerVisitor::visitDynamicFunctionRefInst(
DynamicFunctionRefInst *FRI) {
maybeAddFunctionToWorklist(FRI->getReferencedFunction());
}
void SILLinkerVisitor::visitPreviousDynamicFunctionRefInst(
PreviousDynamicFunctionRefInst *FRI) {
maybeAddFunctionToWorklist(FRI->getReferencedFunction());
}
// Eagerly visiting all used conformances leads to a large blowup
// in the amount of SIL we read in. For optimization purposes we can defer
// reading in most conformances until we need them for devirtualization.
// However, we *must* pull in shared clang-importer-derived conformances
// we potentially use, since we may not otherwise have a local definition.
static bool mustDeserializeProtocolConformance(SILModule &M,
ProtocolConformanceRef c) {
if (!c.isConcrete())
return false;
auto conformance = c.getConcrete()->getRootNormalConformance();
return M.Types.protocolRequiresWitnessTable(conformance->getProtocol())
&& isa<ClangModuleUnit>(conformance->getDeclContext()
->getModuleScopeContext());
}
void SILLinkerVisitor::visitProtocolConformance(
ProtocolConformanceRef ref, const Optional<SILDeclRef> &Member) {
// If an abstract protocol conformance was passed in, do nothing.
if (ref.isAbstract())
return;
bool mustDeserialize = mustDeserializeProtocolConformance(Mod, ref);
// Otherwise try and lookup a witness table for C.
auto C = ref.getConcrete();
if (!VisitedConformances.insert(C).second)
return;
auto *WT = Mod.lookUpWitnessTable(C, mustDeserialize);
// If the looked up witness table is a declaration, there is nothing we can
// do here.
if (WT == nullptr || WT->isDeclaration()) {
assert(!mustDeserialize &&
"unable to deserialize witness table when we must?!");
return;
}
auto maybeVisitRelatedConformance = [&](ProtocolConformanceRef c) {
// Formally all conformances referenced by a used conformance are used.
// However, eagerly visiting them all at this point leads to a large blowup
// in the amount of SIL we read in. For optimization purposes we can defer
// reading in most conformances until we need them for devirtualization.
// However, we *must* pull in shared clang-importer-derived conformances
// we potentially use, since we may not otherwise have a local definition.
if (mustDeserializeProtocolConformance(Mod, c))
visitProtocolConformance(c, None);
};
// For each entry in the witness table...
for (auto &E : WT->getEntries()) {
switch (E.getKind()) {
// If the entry is a witness method...
case SILWitnessTable::WitnessKind::Method: {
// And we are only interested in deserializing a specific requirement
// and don't have that requirement, don't deserialize this method.
if (Member.hasValue() && E.getMethodWitness().Requirement != *Member)
continue;
// The witness could be removed by dead function elimination.
if (!E.getMethodWitness().Witness)
continue;
// Otherwise, deserialize the witness if it has shared linkage, or if
// we were asked to deserialize everything.
maybeAddFunctionToWorklist(E.getMethodWitness().Witness);
break;
}
// If the entry is a related witness table, see whether we need to
// eagerly deserialize it.
case SILWitnessTable::WitnessKind::BaseProtocol: {
auto baseConformance = E.getBaseProtocolWitness().Witness;
maybeVisitRelatedConformance(ProtocolConformanceRef(baseConformance));
break;
}
case SILWitnessTable::WitnessKind::AssociatedTypeProtocol: {
auto assocConformance = E.getAssociatedTypeProtocolWitness().Witness;
maybeVisitRelatedConformance(assocConformance);
break;
}
case SILWitnessTable::WitnessKind::AssociatedType:
case SILWitnessTable::WitnessKind::Invalid:
break;
}
}
}
void SILLinkerVisitor::visitApplySubstitutions(SubstitutionMap subs) {
for (auto conformance : subs.getConformances()) {
// Formally all conformances referenced in a function application are
// used. However, eagerly visiting them all at this point leads to a
// large blowup in the amount of SIL we read in, and we aren't very
// systematic about laziness. For optimization purposes we can defer
// reading in most conformances until we need them for devirtualization.
// However, we *must* pull in shared clang-importer-derived conformances
// we potentially use, since we may not otherwise have a local definition.
if (mustDeserializeProtocolConformance(Mod, conformance)) {
visitProtocolConformance(conformance, None);
}
}
}
void SILLinkerVisitor::visitInitExistentialAddrInst(
InitExistentialAddrInst *IEI) {
// Link in all protocol conformances that this touches.
//
// TODO: There might be a two step solution where the init_existential_inst
// causes the witness table to be brought in as a declaration and then the
// protocol method inst causes the actual deserialization. For now we are
// not going to be smart about this to enable avoiding any issues with
// visiting the open_existential_addr/witness_method before the
// init_existential_inst.
for (ProtocolConformanceRef C : IEI->getConformances()) {
visitProtocolConformance(C, Optional<SILDeclRef>());
}
}
void SILLinkerVisitor::visitInitExistentialRefInst(
InitExistentialRefInst *IERI) {
// Link in all protocol conformances that this touches.
//
// TODO: There might be a two step solution where the init_existential_inst
// causes the witness table to be brought in as a declaration and then the
// protocol method inst causes the actual deserialization. For now we are
// not going to be smart about this to enable avoiding any issues with
// visiting the protocol_method before the init_existential_inst.
for (ProtocolConformanceRef C : IERI->getConformances()) {
visitProtocolConformance(C, Optional<SILDeclRef>());
}
}
void SILLinkerVisitor::visitAllocRefInst(AllocRefInst *ARI) {
if (!isLinkAll())
return;
// Grab the class decl from the alloc ref inst.
ClassDecl *D = ARI->getType().getClassOrBoundGenericClass();
if (!D)
return;
linkInVTable(D);
}
void SILLinkerVisitor::visitMetatypeInst(MetatypeInst *MI) {
if (!isLinkAll())
return;
CanType instTy = MI->getType().castTo<MetatypeType>().getInstanceType();
ClassDecl *C = instTy.getClassOrBoundGenericClass();
if (!C)
return;
linkInVTable(C);
}
//===----------------------------------------------------------------------===//
// Top Level Routine
//===----------------------------------------------------------------------===//
// Main loop of the visitor. Called by one of the other *visit* methods.
void SILLinkerVisitor::process() {
// Process everything transitively referenced by one of the functions in the
// worklist.
while (!Worklist.empty()) {
auto *Fn = Worklist.pop_back_val();
if (Fn->getModule().isSerialized()) {
// If the containing module has been serialized,
// Remove The Serialized state (if any)
// This allows for more optimizations
Fn->setSerialized(IsSerialized_t::IsNotSerialized);
}
LLVM_DEBUG(llvm::dbgs() << "Process imports in function: "
<< Fn->getName() << "\n");
for (auto &BB : *Fn) {
for (auto &I : BB) {
visit(&I);
}
}
}
}
<|endoftext|> |
<commit_before>/*
* Copyright (c) 2010 ARM Limited
* All rights reserved
*
* The license below extends only to copyright in the software and shall
* not be construed as granting a license to any other intellectual
* property including but not limited to intellectual property relating
* to a hardware implementation of the functionality of the software
* licensed hereunder. You may use the software subject to the license
* terms below provided that you ensure that this notice is replicated
* unmodified and in its entirety in all distributions of the software,
* modified or unmodified, in source code or in binary form.
*
* Copyright (c) 2009 The Regents of The University of Michigan
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are
* met: redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer;
* redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution;
* neither the name of the copyright holders nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* 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.
*
* Authors: Gabe Black
*/
#ifndef __ARCH_ARM_MISCREGS_HH__
#define __ARCH_ARM_MISCREGS_HH__
#include "base/bitunion.hh"
namespace ArmISA
{
enum ConditionCode {
COND_EQ = 0,
COND_NE, // 1
COND_CS, // 2
COND_CC, // 3
COND_MI, // 4
COND_PL, // 5
COND_VS, // 6
COND_VC, // 7
COND_HI, // 8
COND_LS, // 9
COND_GE, // 10
COND_LT, // 11
COND_GT, // 12
COND_LE, // 13
COND_AL, // 14
COND_UC // 15
};
enum MiscRegIndex {
MISCREG_CPSR = 0,
MISCREG_SPSR,
MISCREG_SPSR_FIQ,
MISCREG_SPSR_IRQ,
MISCREG_SPSR_SVC,
MISCREG_SPSR_MON,
MISCREG_SPSR_UND,
MISCREG_SPSR_ABT,
MISCREG_FPSR,
MISCREG_FPSID,
MISCREG_FPSCR,
MISCREG_FPEXC,
// CP15 registers
MISCREG_CP15_START,
MISCREG_SCTLR = MISCREG_CP15_START,
MISCREG_DCCISW,
MISCREG_DCCIMVAC,
MISCREG_DCCMVAC,
MISCREG_CONTEXTIDR,
MISCREG_TPIDRURW,
MISCREG_TPIDRURO,
MISCREG_TPIDRPRW,
MISCREG_CP15ISB,
MISCREG_CP15DSB,
MISCREG_CP15DMB,
MISCREG_CPACR,
MISCREG_CLIDR,
MISCREG_CCSIDR,
MISCREG_CSSELR,
MISCREG_ICIALLUIS,
MISCREG_ICIALLU,
MISCREG_ICIMVAU,
MISCREG_BPIMVA,
MISCREG_BPIALLIS,
MISCREG_BPIALL,
MISCREG_MPUIR,
MISCREG_MIDR,
MISCREG_CP15_UNIMP_START,
MISCREG_CTR = MISCREG_CP15_UNIMP_START,
MISCREG_TCMTR,
MISCREG_MPIDR,
MISCREG_ID_PFR0,
MISCREG_ID_PFR1,
MISCREG_ID_DFR0,
MISCREG_ID_AFR0,
MISCREG_ID_MMFR0,
MISCREG_ID_MMFR1,
MISCREG_ID_MMFR2,
MISCREG_ID_MMFR3,
MISCREG_ID_ISAR0,
MISCREG_ID_ISAR1,
MISCREG_ID_ISAR2,
MISCREG_ID_ISAR3,
MISCREG_ID_ISAR4,
MISCREG_ID_ISAR5,
MISCREG_AIDR,
MISCREG_ACTLR,
MISCREG_DFSR,
MISCREG_IFSR,
MISCREG_ADFSR,
MISCREG_AIFSR,
MISCREG_DFAR,
MISCREG_IFAR,
MISCREG_DRBAR,
MISCREG_IRBAR,
MISCREG_DRSR,
MISCREG_IRSR,
MISCREG_DRACR,
MISCREG_IRACR,
MISCREG_RGNR,
MISCREG_DCIMVAC,
MISCREG_DCISW,
MISCREG_MCCSW,
MISCREG_DCCMVAU,
MISCREG_CP15_END,
// Dummy indices
MISCREG_NOP = MISCREG_CP15_END,
MISCREG_RAZ,
NUM_MISCREGS
};
MiscRegIndex decodeCP15Reg(unsigned crn, unsigned opc1,
unsigned crm, unsigned opc2);
const char * const miscRegName[NUM_MISCREGS] = {
"cpsr", "spsr", "spsr_fiq", "spsr_irq", "spsr_svc",
"spsr_mon", "spsr_und", "spsr_abt",
"fpsr", "fpsid", "fpscr", "fpexc",
"sctlr", "dccisw", "dccimvac", "dccmvac",
"contextidr", "tpidrurw", "tpidruro", "tpidrprw",
"cp15isb", "cp15dsb", "cp15dmb", "cpacr",
"clidr", "ccsidr", "csselr",
"icialluis", "iciallu", "icimvau",
"bpimva", "bpiallis", "bpiall",
"mpuir", "midr", "ctr", "tcmtr", "mpidr",
"id_pfr0", "id_pfr1", "id_dfr0", "id_afr0",
"id_mmfr0", "id_mmfr1", "id_mmfr2", "id_mmfr3",
"id_isar0", "id_isar1", "id_isar2", "id_isar3", "id_isar4", "id_isar5",
"aidr", "actlr",
"dfsr", "ifsr", "adfsr", "aifsr", "dfar", "ifar",
"drbar", "irbar", "drsr", "irsr", "dracr", "iracr",
"rgnr",
"dcimvac", "dcisw", "mccsw",
"dccmvau",
"nop", "raz"
};
BitUnion32(CPSR)
Bitfield<31> n;
Bitfield<30> z;
Bitfield<29> c;
Bitfield<28> v;
Bitfield<27> q;
Bitfield<26,25> it1;
Bitfield<24> j;
Bitfield<19, 16> ge;
Bitfield<15,10> it2;
Bitfield<9> e;
Bitfield<8> a;
Bitfield<7> i;
Bitfield<6> f;
Bitfield<5> t;
Bitfield<4, 0> mode;
EndBitUnion(CPSR)
// This mask selects bits of the CPSR that actually go in the CondCodes
// integer register to allow renaming.
static const uint32_t CondCodesMask = 0xF80F0000;
// These otherwise unused bits of the PC are used to select a mode
// like the J and T bits of the CPSR.
static const Addr PcJBitShift = 33;
static const Addr PcTBitShift = 34;
static const Addr PcModeMask = (ULL(1) << PcJBitShift) |
(ULL(1) << PcTBitShift);
BitUnion32(SCTLR)
Bitfield<30> te; // Thumb Exception Enable
Bitfield<29> afe; // Access flag enable
Bitfield<28> tre; // TEX Remap bit
Bitfield<27> nmfi;// Non-maskable fast interrupts enable
Bitfield<25> ee; // Exception Endianness bit
Bitfield<24> ve; // Interrupt vectors enable
Bitfield<23> rao1;// Read as one
Bitfield<22> u; // Alignment (now unused)
Bitfield<21> fi; // Fast interrupts configuration enable
Bitfield<18> rao2;// Read as one
Bitfield<17> ha; // Hardware access flag enable
Bitfield<16> rao3;// Read as one
Bitfield<14> rr; // Round robin cache replacement
Bitfield<13> v; // Base address for exception vectors
Bitfield<12> i; // instruction cache enable
Bitfield<11> z; // branch prediction enable bit
Bitfield<10> sw; // Enable swp/swpb
Bitfield<6,3> rao4;// Read as one
Bitfield<7> b; // Endianness support (unused)
Bitfield<2> c; // Cache enable bit
Bitfield<1> a; // Alignment fault checking
Bitfield<0> m; // MMU enable bit
EndBitUnion(SCTLR)
};
#endif // __ARCH_ARM_MISCREGS_HH__
<commit_msg>ARM: Allow access to the RGNR register.<commit_after>/*
* Copyright (c) 2010 ARM Limited
* All rights reserved
*
* The license below extends only to copyright in the software and shall
* not be construed as granting a license to any other intellectual
* property including but not limited to intellectual property relating
* to a hardware implementation of the functionality of the software
* licensed hereunder. You may use the software subject to the license
* terms below provided that you ensure that this notice is replicated
* unmodified and in its entirety in all distributions of the software,
* modified or unmodified, in source code or in binary form.
*
* Copyright (c) 2009 The Regents of The University of Michigan
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are
* met: redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer;
* redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution;
* neither the name of the copyright holders nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* 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.
*
* Authors: Gabe Black
*/
#ifndef __ARCH_ARM_MISCREGS_HH__
#define __ARCH_ARM_MISCREGS_HH__
#include "base/bitunion.hh"
namespace ArmISA
{
enum ConditionCode {
COND_EQ = 0,
COND_NE, // 1
COND_CS, // 2
COND_CC, // 3
COND_MI, // 4
COND_PL, // 5
COND_VS, // 6
COND_VC, // 7
COND_HI, // 8
COND_LS, // 9
COND_GE, // 10
COND_LT, // 11
COND_GT, // 12
COND_LE, // 13
COND_AL, // 14
COND_UC // 15
};
enum MiscRegIndex {
MISCREG_CPSR = 0,
MISCREG_SPSR,
MISCREG_SPSR_FIQ,
MISCREG_SPSR_IRQ,
MISCREG_SPSR_SVC,
MISCREG_SPSR_MON,
MISCREG_SPSR_UND,
MISCREG_SPSR_ABT,
MISCREG_FPSR,
MISCREG_FPSID,
MISCREG_FPSCR,
MISCREG_FPEXC,
// CP15 registers
MISCREG_CP15_START,
MISCREG_SCTLR = MISCREG_CP15_START,
MISCREG_DCCISW,
MISCREG_DCCIMVAC,
MISCREG_DCCMVAC,
MISCREG_CONTEXTIDR,
MISCREG_TPIDRURW,
MISCREG_TPIDRURO,
MISCREG_TPIDRPRW,
MISCREG_CP15ISB,
MISCREG_CP15DSB,
MISCREG_CP15DMB,
MISCREG_CPACR,
MISCREG_CLIDR,
MISCREG_CCSIDR,
MISCREG_CSSELR,
MISCREG_ICIALLUIS,
MISCREG_ICIALLU,
MISCREG_ICIMVAU,
MISCREG_BPIMVA,
MISCREG_BPIALLIS,
MISCREG_BPIALL,
MISCREG_MPUIR,
MISCREG_MIDR,
MISCREG_RGNR,
MISCREG_CP15_UNIMP_START,
MISCREG_CTR = MISCREG_CP15_UNIMP_START,
MISCREG_TCMTR,
MISCREG_MPIDR,
MISCREG_ID_PFR0,
MISCREG_ID_PFR1,
MISCREG_ID_DFR0,
MISCREG_ID_AFR0,
MISCREG_ID_MMFR0,
MISCREG_ID_MMFR1,
MISCREG_ID_MMFR2,
MISCREG_ID_MMFR3,
MISCREG_ID_ISAR0,
MISCREG_ID_ISAR1,
MISCREG_ID_ISAR2,
MISCREG_ID_ISAR3,
MISCREG_ID_ISAR4,
MISCREG_ID_ISAR5,
MISCREG_AIDR,
MISCREG_ACTLR,
MISCREG_DFSR,
MISCREG_IFSR,
MISCREG_ADFSR,
MISCREG_AIFSR,
MISCREG_DFAR,
MISCREG_IFAR,
MISCREG_DRBAR,
MISCREG_IRBAR,
MISCREG_DRSR,
MISCREG_IRSR,
MISCREG_DRACR,
MISCREG_IRACR,
MISCREG_DCIMVAC,
MISCREG_DCISW,
MISCREG_MCCSW,
MISCREG_DCCMVAU,
MISCREG_CP15_END,
// Dummy indices
MISCREG_NOP = MISCREG_CP15_END,
MISCREG_RAZ,
NUM_MISCREGS
};
MiscRegIndex decodeCP15Reg(unsigned crn, unsigned opc1,
unsigned crm, unsigned opc2);
const char * const miscRegName[NUM_MISCREGS] = {
"cpsr", "spsr", "spsr_fiq", "spsr_irq", "spsr_svc",
"spsr_mon", "spsr_und", "spsr_abt",
"fpsr", "fpsid", "fpscr", "fpexc",
"sctlr", "dccisw", "dccimvac", "dccmvac",
"contextidr", "tpidrurw", "tpidruro", "tpidrprw",
"cp15isb", "cp15dsb", "cp15dmb", "cpacr",
"clidr", "ccsidr", "csselr",
"icialluis", "iciallu", "icimvau",
"bpimva", "bpiallis", "bpiall",
"mpuir", "midr", "rgnr", "ctr", "tcmtr", "mpidr",
"id_pfr0", "id_pfr1", "id_dfr0", "id_afr0",
"id_mmfr0", "id_mmfr1", "id_mmfr2", "id_mmfr3",
"id_isar0", "id_isar1", "id_isar2", "id_isar3", "id_isar4", "id_isar5",
"aidr", "actlr",
"dfsr", "ifsr", "adfsr", "aifsr", "dfar", "ifar",
"drbar", "irbar", "drsr", "irsr", "dracr", "iracr",
"dcimvac", "dcisw", "mccsw",
"dccmvau",
"nop", "raz"
};
BitUnion32(CPSR)
Bitfield<31> n;
Bitfield<30> z;
Bitfield<29> c;
Bitfield<28> v;
Bitfield<27> q;
Bitfield<26,25> it1;
Bitfield<24> j;
Bitfield<19, 16> ge;
Bitfield<15,10> it2;
Bitfield<9> e;
Bitfield<8> a;
Bitfield<7> i;
Bitfield<6> f;
Bitfield<5> t;
Bitfield<4, 0> mode;
EndBitUnion(CPSR)
// This mask selects bits of the CPSR that actually go in the CondCodes
// integer register to allow renaming.
static const uint32_t CondCodesMask = 0xF80F0000;
// These otherwise unused bits of the PC are used to select a mode
// like the J and T bits of the CPSR.
static const Addr PcJBitShift = 33;
static const Addr PcTBitShift = 34;
static const Addr PcModeMask = (ULL(1) << PcJBitShift) |
(ULL(1) << PcTBitShift);
BitUnion32(SCTLR)
Bitfield<30> te; // Thumb Exception Enable
Bitfield<29> afe; // Access flag enable
Bitfield<28> tre; // TEX Remap bit
Bitfield<27> nmfi;// Non-maskable fast interrupts enable
Bitfield<25> ee; // Exception Endianness bit
Bitfield<24> ve; // Interrupt vectors enable
Bitfield<23> rao1;// Read as one
Bitfield<22> u; // Alignment (now unused)
Bitfield<21> fi; // Fast interrupts configuration enable
Bitfield<18> rao2;// Read as one
Bitfield<17> ha; // Hardware access flag enable
Bitfield<16> rao3;// Read as one
Bitfield<14> rr; // Round robin cache replacement
Bitfield<13> v; // Base address for exception vectors
Bitfield<12> i; // instruction cache enable
Bitfield<11> z; // branch prediction enable bit
Bitfield<10> sw; // Enable swp/swpb
Bitfield<6,3> rao4;// Read as one
Bitfield<7> b; // Endianness support (unused)
Bitfield<2> c; // Cache enable bit
Bitfield<1> a; // Alignment fault checking
Bitfield<0> m; // MMU enable bit
EndBitUnion(SCTLR)
};
#endif // __ARCH_ARM_MISCREGS_HH__
<|endoftext|> |
<commit_before>/*
* Copyright (c) 2010 ARM Limited
* All rights reserved
*
* The license below extends only to copyright in the software and shall
* not be construed as granting a license to any other intellectual
* property including but not limited to intellectual property relating
* to a hardware implementation of the functionality of the software
* licensed hereunder. You may use the software subject to the license
* terms below provided that you ensure that this notice is replicated
* unmodified and in its entirety in all distributions of the software,
* modified or unmodified, in source code or in binary form.
*
* Copyright (c) 2009 The Regents of The University of Michigan
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are
* met: redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer;
* redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution;
* neither the name of the copyright holders nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* 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.
*
* Authors: Gabe Black
*/
#ifndef __ARCH_ARM_MISCREGS_HH__
#define __ARCH_ARM_MISCREGS_HH__
#include "base/bitunion.hh"
namespace ArmISA
{
enum ConditionCode {
COND_EQ = 0,
COND_NE, // 1
COND_CS, // 2
COND_CC, // 3
COND_MI, // 4
COND_PL, // 5
COND_VS, // 6
COND_VC, // 7
COND_HI, // 8
COND_LS, // 9
COND_GE, // 10
COND_LT, // 11
COND_GT, // 12
COND_LE, // 13
COND_AL, // 14
COND_UC // 15
};
enum MiscRegIndex {
MISCREG_CPSR = 0,
MISCREG_SPSR,
MISCREG_SPSR_FIQ,
MISCREG_SPSR_IRQ,
MISCREG_SPSR_SVC,
MISCREG_SPSR_MON,
MISCREG_SPSR_UND,
MISCREG_SPSR_ABT,
MISCREG_FPSR,
MISCREG_FPSID,
MISCREG_FPSCR,
MISCREG_FPEXC,
// CP15 registers
MISCREG_CP15_START,
MISCREG_SCTLR = MISCREG_CP15_START,
MISCREG_DCCISW,
MISCREG_DCCIMVAC,
MISCREG_DCCMVAC,
MISCREG_CONTEXTIDR,
MISCREG_TPIDRURW,
MISCREG_TPIDRURO,
MISCREG_TPIDRPRW,
MISCREG_CP15ISB,
MISCREG_CP15DSB,
MISCREG_CP15DMB,
MISCREG_CPACR,
MISCREG_CLIDR,
MISCREG_CCSIDR,
MISCREG_CSSELR,
MISCREG_ICIALLUIS,
MISCREG_ICIALLU,
MISCREG_ICIMVAU,
MISCREG_BPIMVA,
MISCREG_BPIALLIS,
MISCREG_BPIALL,
MISCREG_MPUIR,
MISCREG_MIDR,
MISCREG_RGNR,
MISCREG_DRBAR,
MISCREG_DRACR,
MISCREG_DRSR,
MISCREG_CP15_UNIMP_START,
MISCREG_CTR = MISCREG_CP15_UNIMP_START,
MISCREG_TCMTR,
MISCREG_MPIDR,
MISCREG_ID_PFR0,
MISCREG_ID_PFR1,
MISCREG_ID_DFR0,
MISCREG_ID_AFR0,
MISCREG_ID_MMFR0,
MISCREG_ID_MMFR1,
MISCREG_ID_MMFR2,
MISCREG_ID_MMFR3,
MISCREG_ID_ISAR0,
MISCREG_ID_ISAR1,
MISCREG_ID_ISAR2,
MISCREG_ID_ISAR3,
MISCREG_ID_ISAR4,
MISCREG_ID_ISAR5,
MISCREG_AIDR,
MISCREG_ACTLR,
MISCREG_DFSR,
MISCREG_IFSR,
MISCREG_ADFSR,
MISCREG_AIFSR,
MISCREG_DFAR,
MISCREG_IFAR,
MISCREG_IRBAR,
MISCREG_IRSR,
MISCREG_IRACR,
MISCREG_DCIMVAC,
MISCREG_DCISW,
MISCREG_MCCSW,
MISCREG_DCCMVAU,
MISCREG_CP15_END,
// Dummy indices
MISCREG_NOP = MISCREG_CP15_END,
MISCREG_RAZ,
NUM_MISCREGS
};
MiscRegIndex decodeCP15Reg(unsigned crn, unsigned opc1,
unsigned crm, unsigned opc2);
const char * const miscRegName[NUM_MISCREGS] = {
"cpsr", "spsr", "spsr_fiq", "spsr_irq", "spsr_svc",
"spsr_mon", "spsr_und", "spsr_abt",
"fpsr", "fpsid", "fpscr", "fpexc",
"sctlr", "dccisw", "dccimvac", "dccmvac",
"contextidr", "tpidrurw", "tpidruro", "tpidrprw",
"cp15isb", "cp15dsb", "cp15dmb", "cpacr",
"clidr", "ccsidr", "csselr",
"icialluis", "iciallu", "icimvau",
"bpimva", "bpiallis", "bpiall",
"mpuir", "midr", "rgnr", "drbar", "dracr", "drsr",
"ctr", "tcmtr", "mpidr",
"id_pfr0", "id_pfr1", "id_dfr0", "id_afr0",
"id_mmfr0", "id_mmfr1", "id_mmfr2", "id_mmfr3",
"id_isar0", "id_isar1", "id_isar2", "id_isar3", "id_isar4", "id_isar5",
"aidr", "actlr",
"dfsr", "ifsr", "adfsr", "aifsr", "dfar", "ifar",
"irbar", "irsr", "iracr",
"dcimvac", "dcisw", "mccsw",
"dccmvau",
"nop", "raz"
};
BitUnion32(CPSR)
Bitfield<31> n;
Bitfield<30> z;
Bitfield<29> c;
Bitfield<28> v;
Bitfield<27> q;
Bitfield<26,25> it1;
Bitfield<24> j;
Bitfield<19, 16> ge;
Bitfield<15,10> it2;
Bitfield<9> e;
Bitfield<8> a;
Bitfield<7> i;
Bitfield<6> f;
Bitfield<5> t;
Bitfield<4, 0> mode;
EndBitUnion(CPSR)
// This mask selects bits of the CPSR that actually go in the CondCodes
// integer register to allow renaming.
static const uint32_t CondCodesMask = 0xF80F0000;
// These otherwise unused bits of the PC are used to select a mode
// like the J and T bits of the CPSR.
static const Addr PcJBitShift = 33;
static const Addr PcTBitShift = 34;
static const Addr PcModeMask = (ULL(1) << PcJBitShift) |
(ULL(1) << PcTBitShift);
BitUnion32(SCTLR)
Bitfield<30> te; // Thumb Exception Enable
Bitfield<29> afe; // Access flag enable
Bitfield<28> tre; // TEX Remap bit
Bitfield<27> nmfi;// Non-maskable fast interrupts enable
Bitfield<25> ee; // Exception Endianness bit
Bitfield<24> ve; // Interrupt vectors enable
Bitfield<23> rao1;// Read as one
Bitfield<22> u; // Alignment (now unused)
Bitfield<21> fi; // Fast interrupts configuration enable
Bitfield<18> rao2;// Read as one
Bitfield<17> ha; // Hardware access flag enable
Bitfield<16> rao3;// Read as one
Bitfield<14> rr; // Round robin cache replacement
Bitfield<13> v; // Base address for exception vectors
Bitfield<12> i; // instruction cache enable
Bitfield<11> z; // branch prediction enable bit
Bitfield<10> sw; // Enable swp/swpb
Bitfield<6,3> rao4;// Read as one
Bitfield<7> b; // Endianness support (unused)
Bitfield<2> c; // Cache enable bit
Bitfield<1> a; // Alignment fault checking
Bitfield<0> m; // MMU enable bit
EndBitUnion(SCTLR)
BitUnion32(CPACR)
Bitfield<1, 0> cp0;
Bitfield<3, 2> cp1;
Bitfield<5, 4> cp2;
Bitfield<7, 6> cp3;
Bitfield<9, 8> cp4;
Bitfield<11, 10> cp5;
Bitfield<13, 12> cp6;
Bitfield<15, 14> cp7;
Bitfield<17, 16> cp8;
Bitfield<19, 18> cp9;
Bitfield<21, 20> cp10;
Bitfield<23, 22> cp11;
Bitfield<25, 24> cp12;
Bitfield<27, 26> cp13;
Bitfield<30> d32dis;
Bitfield<31> asedis;
EndBitUnion(CPACR)
};
#endif // __ARCH_ARM_MISCREGS_HH__
<commit_msg>ARM: Update the set of FP related miscregs.<commit_after>/*
* Copyright (c) 2010 ARM Limited
* All rights reserved
*
* The license below extends only to copyright in the software and shall
* not be construed as granting a license to any other intellectual
* property including but not limited to intellectual property relating
* to a hardware implementation of the functionality of the software
* licensed hereunder. You may use the software subject to the license
* terms below provided that you ensure that this notice is replicated
* unmodified and in its entirety in all distributions of the software,
* modified or unmodified, in source code or in binary form.
*
* Copyright (c) 2009 The Regents of The University of Michigan
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are
* met: redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer;
* redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution;
* neither the name of the copyright holders nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* 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.
*
* Authors: Gabe Black
*/
#ifndef __ARCH_ARM_MISCREGS_HH__
#define __ARCH_ARM_MISCREGS_HH__
#include "base/bitunion.hh"
namespace ArmISA
{
enum ConditionCode {
COND_EQ = 0,
COND_NE, // 1
COND_CS, // 2
COND_CC, // 3
COND_MI, // 4
COND_PL, // 5
COND_VS, // 6
COND_VC, // 7
COND_HI, // 8
COND_LS, // 9
COND_GE, // 10
COND_LT, // 11
COND_GT, // 12
COND_LE, // 13
COND_AL, // 14
COND_UC // 15
};
enum MiscRegIndex {
MISCREG_CPSR = 0,
MISCREG_SPSR,
MISCREG_SPSR_FIQ,
MISCREG_SPSR_IRQ,
MISCREG_SPSR_SVC,
MISCREG_SPSR_MON,
MISCREG_SPSR_UND,
MISCREG_SPSR_ABT,
MISCREG_FPSR,
MISCREG_FPSID,
MISCREG_FPSCR,
MISCREG_FPEXC,
MISCREG_MVFR0,
MISCREG_MVFR1,
// CP15 registers
MISCREG_CP15_START,
MISCREG_SCTLR = MISCREG_CP15_START,
MISCREG_DCCISW,
MISCREG_DCCIMVAC,
MISCREG_DCCMVAC,
MISCREG_CONTEXTIDR,
MISCREG_TPIDRURW,
MISCREG_TPIDRURO,
MISCREG_TPIDRPRW,
MISCREG_CP15ISB,
MISCREG_CP15DSB,
MISCREG_CP15DMB,
MISCREG_CPACR,
MISCREG_CLIDR,
MISCREG_CCSIDR,
MISCREG_CSSELR,
MISCREG_ICIALLUIS,
MISCREG_ICIALLU,
MISCREG_ICIMVAU,
MISCREG_BPIMVA,
MISCREG_BPIALLIS,
MISCREG_BPIALL,
MISCREG_MPUIR,
MISCREG_MIDR,
MISCREG_RGNR,
MISCREG_DRBAR,
MISCREG_DRACR,
MISCREG_DRSR,
MISCREG_CP15_UNIMP_START,
MISCREG_CTR = MISCREG_CP15_UNIMP_START,
MISCREG_TCMTR,
MISCREG_MPIDR,
MISCREG_ID_PFR0,
MISCREG_ID_PFR1,
MISCREG_ID_DFR0,
MISCREG_ID_AFR0,
MISCREG_ID_MMFR0,
MISCREG_ID_MMFR1,
MISCREG_ID_MMFR2,
MISCREG_ID_MMFR3,
MISCREG_ID_ISAR0,
MISCREG_ID_ISAR1,
MISCREG_ID_ISAR2,
MISCREG_ID_ISAR3,
MISCREG_ID_ISAR4,
MISCREG_ID_ISAR5,
MISCREG_AIDR,
MISCREG_ACTLR,
MISCREG_DFSR,
MISCREG_IFSR,
MISCREG_ADFSR,
MISCREG_AIFSR,
MISCREG_DFAR,
MISCREG_IFAR,
MISCREG_IRBAR,
MISCREG_IRSR,
MISCREG_IRACR,
MISCREG_DCIMVAC,
MISCREG_DCISW,
MISCREG_MCCSW,
MISCREG_DCCMVAU,
MISCREG_CP15_END,
// Dummy indices
MISCREG_NOP = MISCREG_CP15_END,
MISCREG_RAZ,
NUM_MISCREGS
};
MiscRegIndex decodeCP15Reg(unsigned crn, unsigned opc1,
unsigned crm, unsigned opc2);
const char * const miscRegName[NUM_MISCREGS] = {
"cpsr", "spsr", "spsr_fiq", "spsr_irq", "spsr_svc",
"spsr_mon", "spsr_und", "spsr_abt",
"fpsr", "fpsid", "fpscr", "fpexc",
"sctlr", "dccisw", "dccimvac", "dccmvac",
"contextidr", "tpidrurw", "tpidruro", "tpidrprw",
"cp15isb", "cp15dsb", "cp15dmb", "cpacr",
"clidr", "ccsidr", "csselr",
"icialluis", "iciallu", "icimvau",
"bpimva", "bpiallis", "bpiall",
"mpuir", "midr", "rgnr", "drbar", "dracr", "drsr",
"ctr", "tcmtr", "mpidr",
"id_pfr0", "id_pfr1", "id_dfr0", "id_afr0",
"id_mmfr0", "id_mmfr1", "id_mmfr2", "id_mmfr3",
"id_isar0", "id_isar1", "id_isar2", "id_isar3", "id_isar4", "id_isar5",
"aidr", "actlr",
"dfsr", "ifsr", "adfsr", "aifsr", "dfar", "ifar",
"irbar", "irsr", "iracr",
"dcimvac", "dcisw", "mccsw",
"dccmvau",
"nop", "raz"
};
BitUnion32(CPSR)
Bitfield<31> n;
Bitfield<30> z;
Bitfield<29> c;
Bitfield<28> v;
Bitfield<27> q;
Bitfield<26,25> it1;
Bitfield<24> j;
Bitfield<19, 16> ge;
Bitfield<15,10> it2;
Bitfield<9> e;
Bitfield<8> a;
Bitfield<7> i;
Bitfield<6> f;
Bitfield<5> t;
Bitfield<4, 0> mode;
EndBitUnion(CPSR)
// This mask selects bits of the CPSR that actually go in the CondCodes
// integer register to allow renaming.
static const uint32_t CondCodesMask = 0xF80F0000;
// These otherwise unused bits of the PC are used to select a mode
// like the J and T bits of the CPSR.
static const Addr PcJBitShift = 33;
static const Addr PcTBitShift = 34;
static const Addr PcModeMask = (ULL(1) << PcJBitShift) |
(ULL(1) << PcTBitShift);
BitUnion32(SCTLR)
Bitfield<30> te; // Thumb Exception Enable
Bitfield<29> afe; // Access flag enable
Bitfield<28> tre; // TEX Remap bit
Bitfield<27> nmfi;// Non-maskable fast interrupts enable
Bitfield<25> ee; // Exception Endianness bit
Bitfield<24> ve; // Interrupt vectors enable
Bitfield<23> rao1;// Read as one
Bitfield<22> u; // Alignment (now unused)
Bitfield<21> fi; // Fast interrupts configuration enable
Bitfield<18> rao2;// Read as one
Bitfield<17> ha; // Hardware access flag enable
Bitfield<16> rao3;// Read as one
Bitfield<14> rr; // Round robin cache replacement
Bitfield<13> v; // Base address for exception vectors
Bitfield<12> i; // instruction cache enable
Bitfield<11> z; // branch prediction enable bit
Bitfield<10> sw; // Enable swp/swpb
Bitfield<6,3> rao4;// Read as one
Bitfield<7> b; // Endianness support (unused)
Bitfield<2> c; // Cache enable bit
Bitfield<1> a; // Alignment fault checking
Bitfield<0> m; // MMU enable bit
EndBitUnion(SCTLR)
BitUnion32(CPACR)
Bitfield<1, 0> cp0;
Bitfield<3, 2> cp1;
Bitfield<5, 4> cp2;
Bitfield<7, 6> cp3;
Bitfield<9, 8> cp4;
Bitfield<11, 10> cp5;
Bitfield<13, 12> cp6;
Bitfield<15, 14> cp7;
Bitfield<17, 16> cp8;
Bitfield<19, 18> cp9;
Bitfield<21, 20> cp10;
Bitfield<23, 22> cp11;
Bitfield<25, 24> cp12;
Bitfield<27, 26> cp13;
Bitfield<30> d32dis;
Bitfield<31> asedis;
EndBitUnion(CPACR)
};
#endif // __ARCH_ARM_MISCREGS_HH__
<|endoftext|> |
<commit_before>//===- Scope.cpp - Lexical scope information --------------------*- 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 the Scope class, which is used for recording
// information about a lexical scope.
//
//===----------------------------------------------------------------------===//
#include "clang/Sema/Scope.h"
#include "clang/AST/Decl.h"
#include "llvm/Support/raw_ostream.h"
using namespace clang;
void Scope::setFlags(Scope *parent, unsigned flags) {
AnyParent = parent;
Flags = flags;
if (parent && !(flags & FnScope)) {
BreakParent = parent->BreakParent;
ContinueParent = parent->ContinueParent;
} else {
// Control scopes do not contain the contents of nested function scopes for
// control flow purposes.
BreakParent = ContinueParent = nullptr;
}
if (parent) {
Depth = parent->Depth + 1;
PrototypeDepth = parent->PrototypeDepth;
PrototypeIndex = 0;
FnParent = parent->FnParent;
BlockParent = parent->BlockParent;
TemplateParamParent = parent->TemplateParamParent;
MSLastManglingParent = parent->MSLastManglingParent;
MSCurManglingNumber = getMSLastManglingNumber();
if ((Flags & (FnScope | ClassScope | BlockScope | TemplateParamScope |
FunctionPrototypeScope | AtCatchScope | ObjCMethodScope)) ==
0)
Flags |= parent->getFlags() & OpenMPSimdDirectiveScope;
} else {
Depth = 0;
PrototypeDepth = 0;
PrototypeIndex = 0;
MSLastManglingParent = FnParent = BlockParent = nullptr;
TemplateParamParent = nullptr;
MSLastManglingNumber = 1;
MSCurManglingNumber = 1;
}
// If this scope is a function or contains breaks/continues, remember it.
if (flags & FnScope) FnParent = this;
// The MS mangler uses the number of scopes that can hold declarations as
// part of an external name.
if (Flags & (ClassScope | FnScope)) {
MSLastManglingNumber = getMSLastManglingNumber();
MSLastManglingParent = this;
MSCurManglingNumber = 1;
}
if (flags & BreakScope) BreakParent = this;
if (flags & ContinueScope) ContinueParent = this;
if (flags & BlockScope) BlockParent = this;
if (flags & TemplateParamScope) TemplateParamParent = this;
// If this is a prototype scope, record that.
if (flags & FunctionPrototypeScope) PrototypeDepth++;
if (flags & DeclScope) {
if (flags & FunctionPrototypeScope)
; // Prototype scopes are uninteresting.
else if ((flags & ClassScope) && getParent()->isClassScope())
; // Nested class scopes aren't ambiguous.
else if ((flags & ClassScope) && getParent()->getFlags() == DeclScope)
; // Classes inside of namespaces aren't ambiguous.
else if ((flags & EnumScope))
; // Don't increment for enum scopes.
else
incrementMSManglingNumber();
}
}
void Scope::Init(Scope *parent, unsigned flags) {
setFlags(parent, flags);
DeclsInScope.clear();
UsingDirectives.clear();
Entity = nullptr;
ErrorTrap.reset();
NRVO.setPointerAndInt(nullptr, 0);
}
bool Scope::containedInPrototypeScope() const {
const Scope *S = this;
while (S) {
if (S->isFunctionPrototypeScope())
return true;
S = S->getParent();
}
return false;
}
void Scope::AddFlags(unsigned FlagsToSet) {
assert((FlagsToSet & ~(BreakScope | ContinueScope)) == 0 &&
"Unsupported scope flags");
if (FlagsToSet & BreakScope) {
assert((Flags & BreakScope) == 0 && "Already set");
BreakParent = this;
}
if (FlagsToSet & ContinueScope) {
assert((Flags & ContinueScope) == 0 && "Already set");
ContinueParent = this;
}
Flags |= FlagsToSet;
}
void Scope::mergeNRVOIntoParent() {
if (VarDecl *Candidate = NRVO.getPointer()) {
if (isDeclScope(Candidate))
Candidate->setNRVOVariable(true);
}
if (getEntity())
return;
if (NRVO.getInt())
getParent()->setNoNRVO();
else if (NRVO.getPointer())
getParent()->addNRVOCandidate(NRVO.getPointer());
}
LLVM_DUMP_METHOD void Scope::dump() const { dumpImpl(llvm::errs()); }
void Scope::dumpImpl(raw_ostream &OS) const {
unsigned Flags = getFlags();
bool HasFlags = Flags != 0;
if (HasFlags)
OS << "Flags: ";
while (Flags) {
if (Flags & FnScope) {
OS << "FnScope";
Flags &= ~FnScope;
} else if (Flags & BreakScope) {
OS << "BreakScope";
Flags &= ~BreakScope;
} else if (Flags & ContinueScope) {
OS << "ContinueScope";
Flags &= ~ContinueScope;
} else if (Flags & DeclScope) {
OS << "DeclScope";
Flags &= ~DeclScope;
} else if (Flags & ControlScope) {
OS << "ControlScope";
Flags &= ~ControlScope;
} else if (Flags & ClassScope) {
OS << "ClassScope";
Flags &= ~ClassScope;
} else if (Flags & BlockScope) {
OS << "BlockScope";
Flags &= ~BlockScope;
} else if (Flags & TemplateParamScope) {
OS << "TemplateParamScope";
Flags &= ~TemplateParamScope;
} else if (Flags & FunctionPrototypeScope) {
OS << "FunctionPrototypeScope";
Flags &= ~FunctionPrototypeScope;
} else if (Flags & FunctionDeclarationScope) {
OS << "FunctionDeclarationScope";
Flags &= ~FunctionDeclarationScope;
} else if (Flags & AtCatchScope) {
OS << "AtCatchScope";
Flags &= ~AtCatchScope;
} else if (Flags & ObjCMethodScope) {
OS << "ObjCMethodScope";
Flags &= ~ObjCMethodScope;
} else if (Flags & SwitchScope) {
OS << "SwitchScope";
Flags &= ~SwitchScope;
} else if (Flags & TryScope) {
OS << "TryScope";
Flags &= ~TryScope;
} else if (Flags & FnTryCatchScope) {
OS << "FnTryCatchScope";
Flags &= ~FnTryCatchScope;
} else if (Flags & SEHTryScope) {
OS << "SEHTryScope";
Flags &= ~SEHTryScope;
} else if (Flags & SEHExceptScope) {
OS << "SEHExceptScope";
Flags &= ~SEHExceptScope;
} else if (Flags & OpenMPDirectiveScope) {
OS << "OpenMPDirectiveScope";
Flags &= ~OpenMPDirectiveScope;
} else if (Flags & OpenMPLoopDirectiveScope) {
OS << "OpenMPLoopDirectiveScope";
Flags &= ~OpenMPLoopDirectiveScope;
} else if (Flags & OpenMPSimdDirectiveScope) {
OS << "OpenMPSimdDirectiveScope";
Flags &= ~OpenMPSimdDirectiveScope;
}
if (Flags)
OS << " | ";
}
if (HasFlags)
OS << '\n';
if (const Scope *Parent = getParent())
OS << "Parent: (clang::Scope*)" << Parent << '\n';
OS << "Depth: " << Depth << '\n';
OS << "MSLastManglingNumber: " << getMSLastManglingNumber() << '\n';
OS << "MSCurManglingNumber: " << getMSCurManglingNumber() << '\n';
if (const DeclContext *DC = getEntity())
OS << "Entity : (clang::DeclContext*)" << DC << '\n';
if (NRVO.getInt())
OS << "NRVO not allowed\n";
else if (NRVO.getPointer())
OS << "NRVO candidate : (clang::VarDecl*)" << NRVO.getPointer() << '\n';
}
<commit_msg>Fix Scope::dump()<commit_after>//===- Scope.cpp - Lexical scope information --------------------*- 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 the Scope class, which is used for recording
// information about a lexical scope.
//
//===----------------------------------------------------------------------===//
#include "clang/Sema/Scope.h"
#include "clang/AST/Decl.h"
#include "llvm/Support/raw_ostream.h"
using namespace clang;
void Scope::setFlags(Scope *parent, unsigned flags) {
AnyParent = parent;
Flags = flags;
if (parent && !(flags & FnScope)) {
BreakParent = parent->BreakParent;
ContinueParent = parent->ContinueParent;
} else {
// Control scopes do not contain the contents of nested function scopes for
// control flow purposes.
BreakParent = ContinueParent = nullptr;
}
if (parent) {
Depth = parent->Depth + 1;
PrototypeDepth = parent->PrototypeDepth;
PrototypeIndex = 0;
FnParent = parent->FnParent;
BlockParent = parent->BlockParent;
TemplateParamParent = parent->TemplateParamParent;
MSLastManglingParent = parent->MSLastManglingParent;
MSCurManglingNumber = getMSLastManglingNumber();
if ((Flags & (FnScope | ClassScope | BlockScope | TemplateParamScope |
FunctionPrototypeScope | AtCatchScope | ObjCMethodScope)) ==
0)
Flags |= parent->getFlags() & OpenMPSimdDirectiveScope;
} else {
Depth = 0;
PrototypeDepth = 0;
PrototypeIndex = 0;
MSLastManglingParent = FnParent = BlockParent = nullptr;
TemplateParamParent = nullptr;
MSLastManglingNumber = 1;
MSCurManglingNumber = 1;
}
// If this scope is a function or contains breaks/continues, remember it.
if (flags & FnScope) FnParent = this;
// The MS mangler uses the number of scopes that can hold declarations as
// part of an external name.
if (Flags & (ClassScope | FnScope)) {
MSLastManglingNumber = getMSLastManglingNumber();
MSLastManglingParent = this;
MSCurManglingNumber = 1;
}
if (flags & BreakScope) BreakParent = this;
if (flags & ContinueScope) ContinueParent = this;
if (flags & BlockScope) BlockParent = this;
if (flags & TemplateParamScope) TemplateParamParent = this;
// If this is a prototype scope, record that.
if (flags & FunctionPrototypeScope) PrototypeDepth++;
if (flags & DeclScope) {
if (flags & FunctionPrototypeScope)
; // Prototype scopes are uninteresting.
else if ((flags & ClassScope) && getParent()->isClassScope())
; // Nested class scopes aren't ambiguous.
else if ((flags & ClassScope) && getParent()->getFlags() == DeclScope)
; // Classes inside of namespaces aren't ambiguous.
else if ((flags & EnumScope))
; // Don't increment for enum scopes.
else
incrementMSManglingNumber();
}
}
void Scope::Init(Scope *parent, unsigned flags) {
setFlags(parent, flags);
DeclsInScope.clear();
UsingDirectives.clear();
Entity = nullptr;
ErrorTrap.reset();
NRVO.setPointerAndInt(nullptr, 0);
}
bool Scope::containedInPrototypeScope() const {
const Scope *S = this;
while (S) {
if (S->isFunctionPrototypeScope())
return true;
S = S->getParent();
}
return false;
}
void Scope::AddFlags(unsigned FlagsToSet) {
assert((FlagsToSet & ~(BreakScope | ContinueScope)) == 0 &&
"Unsupported scope flags");
if (FlagsToSet & BreakScope) {
assert((Flags & BreakScope) == 0 && "Already set");
BreakParent = this;
}
if (FlagsToSet & ContinueScope) {
assert((Flags & ContinueScope) == 0 && "Already set");
ContinueParent = this;
}
Flags |= FlagsToSet;
}
void Scope::mergeNRVOIntoParent() {
if (VarDecl *Candidate = NRVO.getPointer()) {
if (isDeclScope(Candidate))
Candidate->setNRVOVariable(true);
}
if (getEntity())
return;
if (NRVO.getInt())
getParent()->setNoNRVO();
else if (NRVO.getPointer())
getParent()->addNRVOCandidate(NRVO.getPointer());
}
LLVM_DUMP_METHOD void Scope::dump() const { dumpImpl(llvm::errs()); }
void Scope::dumpImpl(raw_ostream &OS) const {
unsigned Flags = getFlags();
bool HasFlags = Flags != 0;
if (HasFlags)
OS << "Flags: ";
std::pair<unsigned, const char *> FlagInfo[] = {
{FnScope, "FnScope"},
{BreakScope, "BreakScope"},
{ContinueScope, "ContinueScope"},
{DeclScope, "DeclScope"},
{ControlScope, "ControlScope"},
{ClassScope, "ClassScope"},
{BlockScope, "BlockScope"},
{TemplateParamScope, "TemplateParamScope"},
{FunctionPrototypeScope, "FunctionPrototypeScope"},
{FunctionDeclarationScope, "FunctionDeclarationScope"},
{AtCatchScope, "AtCatchScope"},
{ObjCMethodScope, "ObjCMethodScope"},
{SwitchScope, "SwitchScope"},
{TryScope, "TryScope"},
{FnTryCatchScope, "FnTryCatchScope"},
{OpenMPDirectiveScope, "OpenMPDirectiveScope"},
{OpenMPLoopDirectiveScope, "OpenMPLoopDirectiveScope"},
{OpenMPSimdDirectiveScope, "OpenMPSimdDirectiveScope"},
{EnumScope, "EnumScope"},
{SEHTryScope, "SEHTryScope"},
{SEHExceptScope, "SEHExceptScope"},
{SEHFilterScope, "SEHFilterScope"},
{CompoundStmtScope, "CompoundStmtScope"},
{ClassInheritanceScope, "ClassInheritanceScope"}};
for (auto Info : FlagInfo) {
if (Flags & Info.first) {
OS << Info.second;
Flags &= ~Info.first;
if (Flags)
OS << " | ";
}
}
assert(Flags == 0 && "Unknown scope flags");
if (HasFlags)
OS << '\n';
if (const Scope *Parent = getParent())
OS << "Parent: (clang::Scope*)" << Parent << '\n';
OS << "Depth: " << Depth << '\n';
OS << "MSLastManglingNumber: " << getMSLastManglingNumber() << '\n';
OS << "MSCurManglingNumber: " << getMSCurManglingNumber() << '\n';
if (const DeclContext *DC = getEntity())
OS << "Entity : (clang::DeclContext*)" << DC << '\n';
if (NRVO.getInt())
OS << "NRVO not allowed\n";
else if (NRVO.getPointer())
OS << "NRVO candidate : (clang::VarDecl*)" << NRVO.getPointer() << '\n';
}
<|endoftext|> |
<commit_before>// This file is part of playd.
// playd is licensed under the MIT licence: see LICENSE.txt.
/**
* @file
* Implementation of the AudioSink class.
* @see audio/audio_sink.hpp
*/
#include <algorithm>
#include <cassert>
#include <climits>
#include <cstring>
#include <memory>
#include <string>
#include "SDL.h"
#include "../errors.hpp"
#include "../messages.h"
#include "audio_sink.hpp"
#include "audio_source.hpp"
#include "ringbuffer.hpp"
#include "sample_formats.hpp"
const size_t SdlAudioSink::RINGBUF_POWER = 16;
/**
* The callback used by SDL_Audio.
* Trampolines back into vsink, which must point to an SdlAudioSink.
*/
static void SDLCallback(void *vsink, std::uint8_t *data, int len)
{
assert(vsink != nullptr);
auto sink = static_cast<SdlAudioSink *>(vsink);
sink->Callback(data, len);
}
/* static */ std::unique_ptr<AudioSink> SdlAudioSink::Build(
const AudioSource &source, int device_id)
{
return std::unique_ptr<AudioSink>(new SdlAudioSink(source, device_id));
}
SdlAudioSink::SdlAudioSink(const AudioSource &source, int device_id)
: bytes_per_sample(source.BytesPerSample()),
ring_buf(RINGBUF_POWER, source.BytesPerSample()),
position_sample_count(0),
just_started(false),
source_out(false),
state(Audio::State::STOPPED)
{
const char *name = SDL_GetAudioDeviceName(device_id, 0);
if (name == nullptr) {
throw ConfigError(std::string("invalid device id: ") +
std::to_string(device_id));
}
SDL_AudioSpec want;
SDL_zero(want);
want.freq = source.SampleRate();
want.format = SDLFormat(source.OutputSampleFormat());
want.channels = source.ChannelCount();
want.callback = &SDLCallback;
want.userdata = (void *)this;
SDL_AudioSpec have;
SDL_zero(have);
this->device = SDL_OpenAudioDevice(name, 0, &want, &have, 0);
if (this->device == 0) {
throw ConfigError(std::string("couldn't open device: ") +
SDL_GetError());
}
}
SdlAudioSink::~SdlAudioSink()
{
if (this->device == 0) return;
SDL_CloseAudioDevice(this->device);
SdlAudioSink::CleanupLibrary();
}
/* static */ void SdlAudioSink::InitLibrary()
{
if (SDL_Init(SDL_INIT_AUDIO) != 0) {
throw ConfigError(std::string("could not initialise SDL: ") +
SDL_GetError());
}
}
/* static */ void SdlAudioSink::CleanupLibrary()
{
SDL_Quit();
}
void SdlAudioSink::Start()
{
if (this->state != Audio::State::STOPPED) return;
this->just_started = true;
SDL_PauseAudioDevice(this->device, 0);
this->state = Audio::State::PLAYING;
}
void SdlAudioSink::Stop()
{
if (this->state == Audio::State::STOPPED) return;
SDL_PauseAudioDevice(this->device, 1);
this->state = Audio::State::STOPPED;
}
Audio::State SdlAudioSink::State()
{
return this->state;
}
void SdlAudioSink::SourceOut()
{
// The sink should only be out if the source is.
assert(this->source_out || this->state != Audio::State::AT_END);
this->source_out = true;
}
std::uint64_t SdlAudioSink::Position()
{
return this->position_sample_count;
}
void SdlAudioSink::SetPosition(std::uint64_t samples)
{
this->position_sample_count = samples;
// We might have been at the end of the file previously.
// If so, we might not be now, so clear the out flags.
this->source_out = false;
if (this->state == Audio::State::AT_END) {
this->state = Audio::State::STOPPED;
this->Stop();
}
// The ringbuf will have been full of samples from the old
// position, so we need to get rid of them.
this->ring_buf.Flush();
}
void SdlAudioSink::Transfer(AudioSink::TransferIterator &start,
const AudioSink::TransferIterator &end)
{
assert(start <= end);
// No point transferring 0 bytes.
if (start == end) return;
unsigned long bytes = std::distance(start, end);
// There should be a whole number of samples being transferred.
assert(bytes % bytes_per_sample == 0);
assert(0 < bytes);
auto samples = bytes / this->bytes_per_sample;
// Only transfer as many samples as the ring buffer can take.
// Don't bother trying to write 0 samples!
auto count = std::min(samples, this->ring_buf.WriteCapacity());
if (count == 0) return;
auto start_ptr = reinterpret_cast<char *>(&*start);
unsigned long written_count = this->ring_buf.Write(start_ptr, count);
// Since we never write more than the ring buffer can take, the written
// count should equal the requested written count.
assert(written_count == count);
start += (written_count * this->bytes_per_sample);
assert(start <= end);
}
void SdlAudioSink::Callback(std::uint8_t *out, int nbytes)
{
assert(out != nullptr);
assert(0 <= nbytes);
unsigned long lnbytes = static_cast<unsigned long>(nbytes);
// First of all, let's find out how many samples are available in total
// to give SDL.
auto avail_samples = this->ring_buf.ReadCapacity();
// Have we run out of things to feed?
if (this->source_out && avail_samples == 0) {
// Then we're out too.
this->state = Audio::State::AT_END;
memset(out, 0, lnbytes);
return;
}
// How many samples do we want to pull out of the ring buffer?
auto req_samples = lnbytes / this->bytes_per_sample;
// How many can we pull out? Send this amount to SDL.
auto samples = std::min(req_samples, avail_samples);
auto read_samples = this->ring_buf.Read(reinterpret_cast<char *>(out),
samples);
this->position_sample_count += read_samples;
// Now, we need to fill any gaps with silence.
auto read_bytes = read_samples * this->bytes_per_sample;
assert(read_bytes <= lnbytes);
// I have too little confidence in my own mathematics sometimes.
auto silence_bytes = lnbytes - read_bytes;
assert(read_bytes + silence_bytes == lnbytes);
// SILENCE WILL FALL
memset(out + read_bytes, 0, silence_bytes);
}
/// Mappings from SampleFormats to their equivalent SDL_AudioFormats.
static const std::map<SampleFormat, SDL_AudioFormat> sdl_from_sf = {
{ SampleFormat::PACKED_UNSIGNED_INT_8, AUDIO_U8 },
{ SampleFormat::PACKED_SIGNED_INT_8, AUDIO_S8 },
{ SampleFormat::PACKED_SIGNED_INT_16, AUDIO_S16 },
{ SampleFormat::PACKED_SIGNED_INT_32, AUDIO_S32 },
{ SampleFormat::PACKED_FLOAT_32, AUDIO_F32 }
};
/* static */ SDL_AudioFormat SdlAudioSink::SDLFormat(SampleFormat fmt)
{
try {
return sdl_from_sf.at(fmt);
} catch (std::out_of_range) {
throw FileError(MSG_DECODE_BADRATE);
}
}
/* static */ std::vector<std::pair<int, std::string>> SdlAudioSink::GetDevicesInfo()
{
decltype(SdlAudioSink::GetDevicesInfo()) list;
// The 0 in SDL_GetNumAudioDevices tells SDL we want playback devices.
int is = SDL_GetNumAudioDevices(0);
for (int i = 0; i < is; i++) {
const char *n = SDL_GetAudioDeviceName(i, 0);
if (n == nullptr) continue;
list.emplace_back(i, std::string(n));
}
return list;
}
/* static */ bool SdlAudioSink::IsOutputDevice(int id)
{
int ids = SDL_GetNumAudioDevices(0);
// See above comment for why this is sufficient.
return (0 <= id && id < ids);
}
<commit_msg>Remove unnecessary decltype.<commit_after>// This file is part of playd.
// playd is licensed under the MIT licence: see LICENSE.txt.
/**
* @file
* Implementation of the AudioSink class.
* @see audio/audio_sink.hpp
*/
#include <algorithm>
#include <cassert>
#include <climits>
#include <cstring>
#include <memory>
#include <string>
#include "SDL.h"
#include "../errors.hpp"
#include "../messages.h"
#include "audio_sink.hpp"
#include "audio_source.hpp"
#include "ringbuffer.hpp"
#include "sample_formats.hpp"
const size_t SdlAudioSink::RINGBUF_POWER = 16;
/**
* The callback used by SDL_Audio.
* Trampolines back into vsink, which must point to an SdlAudioSink.
*/
static void SDLCallback(void *vsink, std::uint8_t *data, int len)
{
assert(vsink != nullptr);
auto sink = static_cast<SdlAudioSink *>(vsink);
sink->Callback(data, len);
}
/* static */ std::unique_ptr<AudioSink> SdlAudioSink::Build(
const AudioSource &source, int device_id)
{
return std::unique_ptr<AudioSink>(new SdlAudioSink(source, device_id));
}
SdlAudioSink::SdlAudioSink(const AudioSource &source, int device_id)
: bytes_per_sample(source.BytesPerSample()),
ring_buf(RINGBUF_POWER, source.BytesPerSample()),
position_sample_count(0),
just_started(false),
source_out(false),
state(Audio::State::STOPPED)
{
const char *name = SDL_GetAudioDeviceName(device_id, 0);
if (name == nullptr) {
throw ConfigError(std::string("invalid device id: ") +
std::to_string(device_id));
}
SDL_AudioSpec want;
SDL_zero(want);
want.freq = source.SampleRate();
want.format = SDLFormat(source.OutputSampleFormat());
want.channels = source.ChannelCount();
want.callback = &SDLCallback;
want.userdata = (void *)this;
SDL_AudioSpec have;
SDL_zero(have);
this->device = SDL_OpenAudioDevice(name, 0, &want, &have, 0);
if (this->device == 0) {
throw ConfigError(std::string("couldn't open device: ") +
SDL_GetError());
}
}
SdlAudioSink::~SdlAudioSink()
{
if (this->device == 0) return;
SDL_CloseAudioDevice(this->device);
SdlAudioSink::CleanupLibrary();
}
/* static */ void SdlAudioSink::InitLibrary()
{
if (SDL_Init(SDL_INIT_AUDIO) != 0) {
throw ConfigError(std::string("could not initialise SDL: ") +
SDL_GetError());
}
}
/* static */ void SdlAudioSink::CleanupLibrary()
{
SDL_Quit();
}
void SdlAudioSink::Start()
{
if (this->state != Audio::State::STOPPED) return;
this->just_started = true;
SDL_PauseAudioDevice(this->device, 0);
this->state = Audio::State::PLAYING;
}
void SdlAudioSink::Stop()
{
if (this->state == Audio::State::STOPPED) return;
SDL_PauseAudioDevice(this->device, 1);
this->state = Audio::State::STOPPED;
}
Audio::State SdlAudioSink::State()
{
return this->state;
}
void SdlAudioSink::SourceOut()
{
// The sink should only be out if the source is.
assert(this->source_out || this->state != Audio::State::AT_END);
this->source_out = true;
}
std::uint64_t SdlAudioSink::Position()
{
return this->position_sample_count;
}
void SdlAudioSink::SetPosition(std::uint64_t samples)
{
this->position_sample_count = samples;
// We might have been at the end of the file previously.
// If so, we might not be now, so clear the out flags.
this->source_out = false;
if (this->state == Audio::State::AT_END) {
this->state = Audio::State::STOPPED;
this->Stop();
}
// The ringbuf will have been full of samples from the old
// position, so we need to get rid of them.
this->ring_buf.Flush();
}
void SdlAudioSink::Transfer(AudioSink::TransferIterator &start,
const AudioSink::TransferIterator &end)
{
assert(start <= end);
// No point transferring 0 bytes.
if (start == end) return;
unsigned long bytes = std::distance(start, end);
// There should be a whole number of samples being transferred.
assert(bytes % bytes_per_sample == 0);
assert(0 < bytes);
auto samples = bytes / this->bytes_per_sample;
// Only transfer as many samples as the ring buffer can take.
// Don't bother trying to write 0 samples!
auto count = std::min(samples, this->ring_buf.WriteCapacity());
if (count == 0) return;
auto start_ptr = reinterpret_cast<char *>(&*start);
unsigned long written_count = this->ring_buf.Write(start_ptr, count);
// Since we never write more than the ring buffer can take, the written
// count should equal the requested written count.
assert(written_count == count);
start += (written_count * this->bytes_per_sample);
assert(start <= end);
}
void SdlAudioSink::Callback(std::uint8_t *out, int nbytes)
{
assert(out != nullptr);
assert(0 <= nbytes);
unsigned long lnbytes = static_cast<unsigned long>(nbytes);
// First of all, let's find out how many samples are available in total
// to give SDL.
auto avail_samples = this->ring_buf.ReadCapacity();
// Have we run out of things to feed?
if (this->source_out && avail_samples == 0) {
// Then we're out too.
this->state = Audio::State::AT_END;
memset(out, 0, lnbytes);
return;
}
// How many samples do we want to pull out of the ring buffer?
auto req_samples = lnbytes / this->bytes_per_sample;
// How many can we pull out? Send this amount to SDL.
auto samples = std::min(req_samples, avail_samples);
auto read_samples = this->ring_buf.Read(reinterpret_cast<char *>(out),
samples);
this->position_sample_count += read_samples;
// Now, we need to fill any gaps with silence.
auto read_bytes = read_samples * this->bytes_per_sample;
assert(read_bytes <= lnbytes);
// I have too little confidence in my own mathematics sometimes.
auto silence_bytes = lnbytes - read_bytes;
assert(read_bytes + silence_bytes == lnbytes);
// SILENCE WILL FALL
memset(out + read_bytes, 0, silence_bytes);
}
/// Mappings from SampleFormats to their equivalent SDL_AudioFormats.
static const std::map<SampleFormat, SDL_AudioFormat> sdl_from_sf = {
{ SampleFormat::PACKED_UNSIGNED_INT_8, AUDIO_U8 },
{ SampleFormat::PACKED_SIGNED_INT_8, AUDIO_S8 },
{ SampleFormat::PACKED_SIGNED_INT_16, AUDIO_S16 },
{ SampleFormat::PACKED_SIGNED_INT_32, AUDIO_S32 },
{ SampleFormat::PACKED_FLOAT_32, AUDIO_F32 }
};
/* static */ SDL_AudioFormat SdlAudioSink::SDLFormat(SampleFormat fmt)
{
try {
return sdl_from_sf.at(fmt);
} catch (std::out_of_range) {
throw FileError(MSG_DECODE_BADRATE);
}
}
/* static */ std::vector<std::pair<int, std::string>> SdlAudioSink::GetDevicesInfo()
{
std::vector<std::pair<int, std::string>> list;
// The 0 in SDL_GetNumAudioDevices tells SDL we want playback devices.
int is = SDL_GetNumAudioDevices(0);
for (int i = 0; i < is; i++) {
const char *n = SDL_GetAudioDeviceName(i, 0);
if (n == nullptr) continue;
list.emplace_back(i, std::string(n));
}
return list;
}
/* static */ bool SdlAudioSink::IsOutputDevice(int id)
{
int ids = SDL_GetNumAudioDevices(0);
// See above comment for why this is sufficient.
return (0 <= id && id < ids);
}
<|endoftext|> |
<commit_before><commit_msg>fixes #0003993: Memory leak with Python3<commit_after><|endoftext|> |
<commit_before>#include "IntakeBall.h"
using IntakeBall = commands::IntakeBall;
// Constructor:
IntakeBall::IntakeBall(Intake * intake) : Command("IntakeBall")
{
intake_ = intake;
}
void IntakeBall::Initialize()
{
intake_->TakeBall(true);
}
bool IntakeBall::IsFinished()
{
return intake_->CheckSwitch();
}
void IntakeBall::End()
{
intake_->Stop();
}
void IntakeBall::Interrupted()
{
End();
}
<commit_msg>Changes existing functions to take Intake states into account, and updates documentation.<commit_after>#include "IntakeBall.h"
/**
* Namespace commands with implementation
* of IntakeBall command functions.
*/
namespace commands
{
// Constructor:
IntakeBall::IntakeBall(Intake * intake) : Command("IntakeBall")
{
intake_ = intake;
SetInterruptible(true);
}
// Main functions:
void IntakeBall::Initialize()
{
if (intake_->GetState() == State_t::OFF)
{
intake_->SetState(State_t::TAKING);
intake_->TakeBall(true);
}
else
{
std::cout << "ERROR: Invalid starting state (Should be \"OFF\")";
}
}
bool IntakeBall::IsFinished()
{
return intake_->CheckSwitch();
}
void IntakeBall::End()
{
intake_->Stop();
intake_->SetState(State_t::HOLDING);
}
void IntakeBall::Interrupted()
{
intake_->Stop();
intake_->SetState(State_t::OFF);
}
} // end namespace commands
<|endoftext|> |
<commit_before>// LICENSE/*{{{*/
/*
sxc - Simple Xmpp Client
Copyright (C) 2008 Dennis Felsing, Andreas Waidler
Permission to use, copy, modify, and/or distribute this software for any
purpose with or without fee is hereby granted, provided that the above
copyright notice and this permission notice appear in all copies.
THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
*/
/*}}}*/
#ifndef ACCOUNT_FILE_OUTPUT_HXX
#define ACCOUNT_FILE_OUTPUT_HXX
// INCLUDES/*{{{*/
#include <string>
#include <File/AbcOutput.hxx>
/*}}}*/
namespace Contact
{
namespace File
{
/**
* @brief Output class for contacts.
*
* Creates the file $JID/$CONTACT/out which contains messages from and
* to that contact.
*
*/
class Output : public ::File::AbcOutput
{
public:
// Output(const string &accountJid, const string &contactJid);/*{{{*/
/**
* @brief Initializes the object.
*
* @param accountJid Our local jid.
* @param contactJid The remote contact's jid.
*/
Output(const std::string &accountJid, const std::string &contactJid);
/*}}}*/
private:
const std::string _accountJid;
const std::string _contactJid;
// std::string _createPath() const;/*{{{*/
/**
* @brief Creates a string containing the path of this file.
*
* @see File::AbcOutput::_createPath()
*
* @return $accountName/out
*/
std::string _createPath() const;
/*}}}*/
// std::string _format(const std::string &output) const;/*{{{*/
/**
* @brief Formats the output.
*
* @param output String to be formatted.
* @return A formatted string.
*/
std::string _format(const std::string &output) const;
/*}}}*/
};
}
}
#endif // ACCOUNT_FILE_OUTPUT_HXX
// Use no tabs at all; two spaces indentation; max. eighty chars per line.
// vim: et ts=2 sw=2 sts=2 tw=80 fdm=marker
<commit_msg>Fix: Use correct define<commit_after>// LICENSE/*{{{*/
/*
sxc - Simple Xmpp Client
Copyright (C) 2008 Dennis Felsing, Andreas Waidler
Permission to use, copy, modify, and/or distribute this software for any
purpose with or without fee is hereby granted, provided that the above
copyright notice and this permission notice appear in all copies.
THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
*/
/*}}}*/
#ifndef CONTACT_FILE_OUTPUT_HXX
#define CONTACT_FILE_OUTPUT_HXX
// INCLUDES/*{{{*/
#include <string>
#include <File/AbcOutput.hxx>
/*}}}*/
namespace Contact
{
namespace File
{
/**
* @brief Output class for contacts.
*
* Creates the file $JID/$CONTACT/out which contains messages from and
* to that contact.
*
*/
class Output : public ::File::AbcOutput
{
public:
// Output(const string &accountJid, const string &contactJid);/*{{{*/
/**
* @brief Initializes the object.
*
* @param accountJid Our local jid.
* @param contactJid The remote contact's jid.
*/
Output(const std::string &accountJid, const std::string &contactJid);
/*}}}*/
private:
const std::string _accountJid;
const std::string _contactJid;
// std::string _createPath() const;/*{{{*/
/**
* @brief Creates a string containing the path of this file.
*
* @see File::AbcOutput::_createPath()
*
* @return $accountName/out
*/
std::string _createPath() const;
/*}}}*/
// std::string _format(const std::string &output) const;/*{{{*/
/**
* @brief Formats the output.
*
* @param output String to be formatted.
* @return A formatted string.
*/
std::string _format(const std::string &output) const;
/*}}}*/
};
}
}
#endif // CONTACT_FILE_OUTPUT_HXX
// Use no tabs at all; two spaces indentation; max. eighty chars per line.
// vim: et ts=2 sw=2 sts=2 tw=80 fdm=marker
<|endoftext|> |
<commit_before>#include "wxSFMLCanvas.hpp"
BEGIN_EVENT_TABLE(wxSFMLCanvas, wxControl)
EVT_IDLE(wxSFMLCanvas::onIdle)
EVT_PAINT(wxSFMLCanvas::onPaint)
END_EVENT_TABLE()
wxSFMLCanvas::wxSFMLCanvas(
wxWindow* parent,
wxWindowID id,
const wxPoint& pos,
const wxSize& size,
long style,
const wxValidator& validator,
const wxString& name)
:
wxControl(parent, id, pos, size, style, validator, name)
{
#ifdef __WXGTK__
gtk_widget_realize(m_wxwindow);
gtk_widget_set_double_buffered(m_wxwindow, false);
GdkWindow* Win = GTK_PIZZA(m_wxwindow)->bin_window;
XFlush(GDK_WINDOW_XDISPLAY(Win));
sf::RenderWindow::create(GDK_WINDOW_XWINDOW(Win));
#else
sf::RenderWindow::create(GetHandle());
#endif
}
void wxSFMLCanvas::onIdle(wxIdleEvent&)
{
Refresh(false);
}
void wxSFMLCanvas::onPaint(wxPaintEvent&)
{
wxPaintDC Dc(this);
update();
display();
}
<commit_msg>solves a compilation issue on windows<commit_after>#include "wxSFMLCanvas.hpp"
BEGIN_EVENT_TABLE(wxSFMLCanvas, wxControl)
EVT_IDLE(wxSFMLCanvas::onIdle)
EVT_PAINT(wxSFMLCanvas::onPaint)
END_EVENT_TABLE()
wxSFMLCanvas::wxSFMLCanvas(
wxWindow* parent,
wxWindowID id,
const wxPoint& pos,
const wxSize& size,
long style,
const wxValidator& validator,
const wxString& name)
:
wxControl(parent, id, pos, size, style, validator, name)
{
#ifdef __WXGTK__
gtk_widget_realize(m_wxwindow);
gtk_widget_set_double_buffered(m_wxwindow, false);
GdkWindow* Win = GTK_PIZZA(m_wxwindow)->bin_window;
XFlush(GDK_WINDOW_XDISPLAY(Win));
sf::RenderWindow::create(GDK_WINDOW_XWINDOW(Win));
#else
sf::RenderWindow::create( static_cast<sf::WindowHandle>(GetHandle()) );
#endif
}
void wxSFMLCanvas::onIdle(wxIdleEvent&)
{
Refresh(false);
}
void wxSFMLCanvas::onPaint(wxPaintEvent&)
{
wxPaintDC Dc(this);
update();
clear(sf::Color::Red);
display();
}
<|endoftext|> |
<commit_before>/****************************************************************************
**
** Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies).
** All rights reserved.
** Contact: Nokia Corporation ([email protected])
**
** This file is part of the test suite of the QtSparql module (not yet part of the Qt Toolkit).
**
** $QT_BEGIN_LICENSE:LGPL$
** No Commercial Usage
** This file contains pre-release code and may not be distributed.
** You may use this file in accordance with the terms and conditions
** contained in the Technology Preview License Agreement accompanying
** this package.
**
** GNU Lesser General Public License Usage
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 as published by the Free Software
** Foundation and appearing in the file LICENSE.LGPL included in the
** packaging of this file. Please review the following information to
** ensure the GNU Lesser General Public License version 2.1 requirements
** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, Nokia gives you certain additional
** rights. These rights are described in the Nokia Qt LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
** If you have questions regarding the use of this file, please contact
** Nokia at [email protected].
**
**
**
**
**
**
**
**
** $QT_END_LICENSE$
**
****************************************************************************/
#include <QtTest/QtTest>
#include <QtSparql/QtSparql>
#include "private/qsparqlconnection_p.h"
#include "private/qsparqldriver_p.h"
//const QString qtest(qTableName( "qtest", __FILE__ )); // FIXME: what's this
//TESTED_FILES=
class MockDriver;
class MockResult : public QSparqlResult
{
Q_OBJECT
public:
MockResult(const MockDriver* d);
int size() const
{
return 0;
}
QSparqlResultRow current() const
{
return QSparqlResultRow();
}
QSparqlBinding binding(int) const
{
return QSparqlBinding();
}
QVariant value(int) const
{
return QVariant();
}
};
class MockDriver : public QSparqlDriver
{
Q_OBJECT
public:
MockDriver()
{
}
~MockDriver()
{
}
bool open(const QSparqlConnectionOptions&)
{
++openCount;
return openRetVal;
}
void close()
{
++closeCount;
}
bool hasFeature(QSparqlConnection::Feature) const
{
return false;
}
MockResult* exec(const QString&, QSparqlQuery::StatementType)
{
return new MockResult(this);
}
static int openCount;
static int closeCount;
static bool openRetVal;
};
int MockDriver::openCount = 0;
int MockDriver::closeCount = 0;
bool MockDriver::openRetVal = true;
MockResult::MockResult(const MockDriver*)
: QSparqlResult()
{
}
class MockDriverCreator : public QSparqlDriverCreatorBase
{
QSparqlDriver* createObject() const
{
return new MockDriver();
}
};
class tst_QSparql : public QObject
{
Q_OBJECT
public:
tst_QSparql();
virtual ~tst_QSparql();
public slots:
void initTestCase();
void cleanupTestCase();
void init();
void cleanup();
private slots:
void mock_creation();
void wrong_creation();
void open_fails();
void connection_scope();
};
tst_QSparql::tst_QSparql()
{
}
tst_QSparql::~tst_QSparql()
{
}
void tst_QSparql::initTestCase()
{
qSparqlRegisterConnectionCreator("MOCK", new MockDriverCreator());
}
void tst_QSparql::cleanupTestCase()
{
}
void tst_QSparql::init()
{
MockDriver::openCount = 0;
MockDriver::closeCount = 0;
MockDriver::openRetVal = true;
}
void tst_QSparql::cleanup()
{
}
void tst_QSparql::mock_creation()
{
QSparqlConnection conn("MOCK");
QCOMPARE(MockDriver::openCount, 1);
}
void tst_QSparql::wrong_creation()
{
QSparqlConnection conn("TOTALLYNOTTHERE");
QSparqlResult* res = conn.exec(QSparqlQuery("foo"));
QVERIFY(res->hasError());
QCOMPARE(res->lastError().type(), QSparqlError::ConnectionError);
}
void tst_QSparql::open_fails()
{
MockDriver::openRetVal = false;
QSparqlConnection conn("MOCK");
QSparqlResult* res = conn.exec(QSparqlQuery("foo"));
QVERIFY(res->hasError());
QCOMPARE(res->lastError().type(), QSparqlError::ConnectionError);
}
void tst_QSparql::connection_scope()
{
{
QSparqlConnection conn("MOCK");
}
QCOMPARE(MockDriver::openCount, 1);
QCOMPARE(MockDriver::closeCount, 1);
}
QTEST_MAIN(tst_QSparql)
#include "tst_qsparql.moc"
<commit_msg>* Add a test for QSparqlConnection::drivers(). If the not all the drivers are present on a particular platform the test will fail though<commit_after>/****************************************************************************
**
** Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies).
** All rights reserved.
** Contact: Nokia Corporation ([email protected])
**
** This file is part of the test suite of the QtSparql module (not yet part of the Qt Toolkit).
**
** $QT_BEGIN_LICENSE:LGPL$
** No Commercial Usage
** This file contains pre-release code and may not be distributed.
** You may use this file in accordance with the terms and conditions
** contained in the Technology Preview License Agreement accompanying
** this package.
**
** GNU Lesser General Public License Usage
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 as published by the Free Software
** Foundation and appearing in the file LICENSE.LGPL included in the
** packaging of this file. Please review the following information to
** ensure the GNU Lesser General Public License version 2.1 requirements
** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, Nokia gives you certain additional
** rights. These rights are described in the Nokia Qt LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
** If you have questions regarding the use of this file, please contact
** Nokia at [email protected].
**
**
**
**
**
**
**
**
** $QT_END_LICENSE$
**
****************************************************************************/
#include <QtTest/QtTest>
#include <QtSparql/QtSparql>
#include "private/qsparqlconnection_p.h"
#include "private/qsparqldriver_p.h"
//const QString qtest(qTableName( "qtest", __FILE__ )); // FIXME: what's this
//TESTED_FILES=
class MockDriver;
class MockResult : public QSparqlResult
{
Q_OBJECT
public:
MockResult(const MockDriver* d);
int size() const
{
return 0;
}
QSparqlResultRow current() const
{
return QSparqlResultRow();
}
QSparqlBinding binding(int) const
{
return QSparqlBinding();
}
QVariant value(int) const
{
return QVariant();
}
};
class MockDriver : public QSparqlDriver
{
Q_OBJECT
public:
MockDriver()
{
}
~MockDriver()
{
}
bool open(const QSparqlConnectionOptions&)
{
++openCount;
return openRetVal;
}
void close()
{
++closeCount;
}
bool hasFeature(QSparqlConnection::Feature) const
{
return false;
}
MockResult* exec(const QString&, QSparqlQuery::StatementType)
{
return new MockResult(this);
}
static int openCount;
static int closeCount;
static bool openRetVal;
};
int MockDriver::openCount = 0;
int MockDriver::closeCount = 0;
bool MockDriver::openRetVal = true;
MockResult::MockResult(const MockDriver*)
: QSparqlResult()
{
}
class MockDriverCreator : public QSparqlDriverCreatorBase
{
QSparqlDriver* createObject() const
{
return new MockDriver();
}
};
class tst_QSparql : public QObject
{
Q_OBJECT
public:
tst_QSparql();
virtual ~tst_QSparql();
public slots:
void initTestCase();
void cleanupTestCase();
void init();
void cleanup();
private slots:
void mock_creation();
void wrong_creation();
void open_fails();
void connection_scope();
void drivers_list();
};
tst_QSparql::tst_QSparql()
{
}
tst_QSparql::~tst_QSparql()
{
}
void tst_QSparql::initTestCase()
{
qSparqlRegisterConnectionCreator("MOCK", new MockDriverCreator());
// For running the test without installing the plugins. Should work in
// normal and vpath builds.
QCoreApplication::addLibraryPath("../../../plugins");
}
void tst_QSparql::cleanupTestCase()
{
}
void tst_QSparql::init()
{
MockDriver::openCount = 0;
MockDriver::closeCount = 0;
MockDriver::openRetVal = true;
}
void tst_QSparql::cleanup()
{
}
void tst_QSparql::mock_creation()
{
QSparqlConnection conn("MOCK");
QCOMPARE(MockDriver::openCount, 1);
}
void tst_QSparql::wrong_creation()
{
QSparqlConnection conn("TOTALLYNOTTHERE");
QSparqlResult* res = conn.exec(QSparqlQuery("foo"));
QVERIFY(res->hasError());
QCOMPARE(res->lastError().type(), QSparqlError::ConnectionError);
}
void tst_QSparql::open_fails()
{
MockDriver::openRetVal = false;
QSparqlConnection conn("MOCK");
QSparqlResult* res = conn.exec(QSparqlQuery("foo"));
QVERIFY(res->hasError());
QCOMPARE(res->lastError().type(), QSparqlError::ConnectionError);
}
void tst_QSparql::connection_scope()
{
{
QSparqlConnection conn("MOCK");
}
QCOMPARE(MockDriver::openCount, 1);
QCOMPARE(MockDriver::closeCount, 1);
}
void tst_QSparql::drivers_list()
{
QStringList expectedDrivers;
expectedDrivers << "QSPARQL_ENDPOINT" << "QTRACKER" << "QTRACKER_DIRECT" << "QVIRTUOSO" << "MOCK";
QStringList drivers = QSparqlConnection::drivers();
foreach (QString driver, drivers) {
QCOMPARE(expectedDrivers.indexOf(driver) != -1, true);
// qDebug() << driver;
}
}
QTEST_MAIN(tst_QSparql)
#include "tst_qsparql.moc"
<|endoftext|> |
<commit_before>// Copyright (c) 2010-2020, Lawrence Livermore National Security, LLC. Produced
// at the Lawrence Livermore National Laboratory. All Rights reserved. See files
// LICENSE and NOTICE for details. LLNL-CODE-443271.
//
// This file is part of the GLVis visualization tool and library. For more
// information and source code availability see https://glvis.org.
//
// GLVis is free software; you can redistribute it and/or modify it under the
// terms of the BSD-3 license. We welcome feedback and contributions, see file
// CONTRIBUTING.md for details.
#include "visual.hpp"
#include "palettes.hpp"
#include "stream_reader.hpp"
#include <SDL2/SDL_hints.h>
#include <emscripten/bind.h>
#include <emscripten/html5.h>
std::string plot_caption;
std::string extra_caption; // used in extern context
mfem::GeometryRefiner GLVisGeometryRefiner; // used in extern context
static VisualizationSceneScalarData * vs{nullptr};
namespace js
{
using namespace mfem;
// Replace a given VectorFiniteElement-based grid function (e.g. from a Nedelec
// or Raviart-Thomas space) with a discontinuous piece-wise polynomial Cartesian
// product vector grid function of the same order.
GridFunction *ProjectVectorFEGridFunction(GridFunction *gf)
{
if ((gf->VectorDim() == 3) && (gf->FESpace()->GetVDim() == 1))
{
int p = gf->FESpace()->GetOrder(0);
cout << "Switching to order " << p
<< " discontinuous vector grid function..." << endl;
int dim = gf->FESpace()->GetMesh()->Dimension();
FiniteElementCollection *d_fec = new L2_FECollection(p, dim, 1);
FiniteElementSpace *d_fespace =
new FiniteElementSpace(gf->FESpace()->GetMesh(), d_fec, 3);
GridFunction *d_gf = new GridFunction(d_fespace);
d_gf->MakeOwner(d_fec);
gf->ProjectVectorFieldOn(*d_gf);
delete gf;
return d_gf;
}
return gf;
}
bool startVisualization(const std::string input, const std::string data_type,
int w, int h)
{
std::stringstream ss(input);
const int field_type = ReadStream(ss, data_type);
// reset antialiasing
GetAppWindow()->getRenderer().setAntialiasing(0);
std::string line;
while (ss >> line)
{
if (line == "keys")
{
std::cout << "parsing 'keys'" << std::endl;
ss >> stream_state.keys;
}
else
{
std::cout << "unknown line '" << line << "'" << std::endl;
}
}
if (field_type < 0 || field_type > 2)
{
return false;
}
if (InitVisualization("glvis", 0, 0, w, h))
{
return false;
}
delete vs;
vs = nullptr;
double mesh_range = -1.0;
if (field_type == 0 || field_type == 2)
{
if (stream_state.grid_f)
{
stream_state.grid_f->GetNodalValues(stream_state.sol);
}
if (stream_state.mesh->SpaceDimension() == 2)
{
VisualizationSceneSolution * vss;
if (field_type == 2)
{
// Use the 'bone' palette when visualizing a 2D mesh only
paletteSet(4);
}
// Otherwise, the 'jet-like' palette is used in 2D see vssolution.cpp
if (stream_state.normals.Size() > 0)
{
vs = vss = new VisualizationSceneSolution(*stream_state.mesh, stream_state.sol,
&stream_state.normals);
}
else
{
vs = vss = new VisualizationSceneSolution(*stream_state.mesh, stream_state.sol);
}
if (stream_state.grid_f)
{
vss->SetGridFunction(*stream_state.grid_f);
}
if (field_type == 2)
{
vs->OrthogonalProjection = 1;
vs->SetLight(0);
vs->Zoom(1.8);
}
}
else if (stream_state.mesh->SpaceDimension() == 3)
{
VisualizationSceneSolution3d * vss;
vs = vss = new VisualizationSceneSolution3d(*stream_state.mesh,
stream_state.sol);
if (stream_state.grid_f)
{
vss->SetGridFunction(stream_state.grid_f);
}
if (field_type == 2)
{
if (stream_state.mesh->Dimension() == 3)
{
// Use the 'white' palette when visualizing a 3D volume mesh only
// paletteSet(4);
paletteSet(11);
vss->SetLightMatIdx(4);
}
else
{
// Use the 'bone' palette when visualizing a surface mesh only
// (the same as when visualizing a 2D mesh only)
paletteSet(4);
}
// Otherwise, the 'vivid' palette is used in 3D see vssolution3d.cpp
vss->ToggleDrawAxes();
vss->ToggleDrawMesh();
}
}
if (field_type == 2)
{
if (stream_state.grid_f)
{
mesh_range = stream_state.grid_f->Max() + 1.0;
}
else
{
mesh_range = stream_state.sol.Max() + 1.0;
}
}
}
else if (field_type == 1)
{
if (stream_state.mesh->SpaceDimension() == 2)
{
if (stream_state.grid_f)
{
vs = new VisualizationSceneVector(*stream_state.grid_f);
}
else
{
vs = new VisualizationSceneVector(*stream_state.mesh, stream_state.solu,
stream_state.solv);
}
}
else if (stream_state.mesh->SpaceDimension() == 3)
{
if (stream_state.grid_f)
{
stream_state.grid_f = ProjectVectorFEGridFunction(stream_state.grid_f);
vs = new VisualizationSceneVector3d(*stream_state.grid_f);
}
else
{
vs = new VisualizationSceneVector3d(*stream_state.mesh, stream_state.solu,
stream_state.solv, stream_state.solw);
}
}
}
if (vs)
{
// increase the refinement factors if visualizing a GridFunction
if (stream_state.grid_f)
{
vs->AutoRefine();
vs->SetShading(2, true);
}
if (mesh_range > 0.0)
{
vs->SetValueRange(-mesh_range, mesh_range);
vs->SetAutoscale(0);
}
if (stream_state.mesh->SpaceDimension() == 2 && field_type == 2)
{
SetVisualizationScene(vs, 2);
}
else
{
SetVisualizationScene(vs, 3);
}
}
CallKeySequence(stream_state.keys.c_str());
SendExposeEvent();
return true;
}
int updateVisualization(std::string data_type, std::string stream)
{
std::stringstream ss(stream);
if (data_type != "solution")
{
std::cerr << "unsupported data type '" << data_type << "' for stream update" <<
std::endl;
return 1;
}
auto * new_m = new Mesh(ss, 1, 0, stream_state.fix_elem_orient);
auto * new_g = new GridFunction(new_m, ss);
double mesh_range = -1.0;
if (new_m->SpaceDimension() == stream_state.mesh->SpaceDimension() &&
new_g->VectorDim() == stream_state.grid_f->VectorDim())
{
if (new_m->SpaceDimension() == 2)
{
if (new_g->VectorDim() == 1)
{
VisualizationSceneSolution *vss =
dynamic_cast<VisualizationSceneSolution *>(vs);
new_g->GetNodalValues(stream_state.sol);
vss->NewMeshAndSolution(new_m, &stream_state.sol, new_g);
}
else
{
VisualizationSceneVector *vsv =
dynamic_cast<VisualizationSceneVector *>(vs);
vsv->NewMeshAndSolution(*new_g);
}
}
else
{
if (new_g->VectorDim() == 1)
{
VisualizationSceneSolution3d *vss =
dynamic_cast<VisualizationSceneSolution3d *>(vs);
new_g->GetNodalValues(stream_state.sol);
vss->NewMeshAndSolution(new_m, &stream_state.sol, new_g);
}
else
{
new_g = ProjectVectorFEGridFunction(new_g);
VisualizationSceneVector3d *vss =
dynamic_cast<VisualizationSceneVector3d *>(vs);
vss->NewMeshAndSolution(new_m, new_g);
}
}
if (mesh_range > 0.0)
{
vs->SetValueRange(-mesh_range, mesh_range);
}
delete stream_state.grid_f;
stream_state.grid_f = new_g;
delete stream_state.mesh;
stream_state.mesh = new_m;
SendExposeEvent();
return 0;
}
else
{
cout << "Stream: field type does not match!" << endl;
delete new_g;
delete new_m;
return 1;
}
}
void iterVisualization()
{
GetAppWindow()->mainIter();
}
void setCanvasId(const std::string & id)
{
std::cout << "glvis: setting canvas id to " << id << std::endl;
GetAppWindow()->setCanvasId(id);
}
void disableKeyHandling()
{
SDL_EventState(SDL_KEYDOWN, SDL_DISABLE);
SDL_EventState(SDL_KEYUP, SDL_DISABLE);
}
void enableKeyHandling()
{
SDL_EventState(SDL_KEYDOWN, SDL_ENABLE);
SDL_EventState(SDL_KEYUP, SDL_ENABLE);
}
void setKeyboardListeningElementId(const std::string & id)
{
SDL_SetHint(SDL_HINT_EMSCRIPTEN_KEYBOARD_ELEMENT, id.c_str());
}
void setupResizeEventCallback(const std::string & id)
{
// typedef EM_BOOL (*em_ui_callback_func)(int eventType, const EmscriptenUiEvent *uiEvent, void *userData);
std::cout << "glvis: adding resize callback for " << id << std::endl;
auto err = emscripten_set_resize_callback(id.c_str(), nullptr,
true, [](int eventType, const EmscriptenUiEvent *uiEvent,
void *userData) -> EM_BOOL
{
std::cout << "got resize event" << std::endl;
return true;
});
// TODO: macro to wrap this
if (err != EMSCRIPTEN_RESULT_SUCCESS)
{
std::cerr << "error (emscripten_set_resize_callback): " << err << std::endl;
}
}
std::string getHelpString()
{
VisualizationSceneScalarData* vss
= dynamic_cast<VisualizationSceneScalarData*>(GetVisualizationScene());
return vss->GetHelpString();
}
} // namespace js
namespace em = emscripten;
EMSCRIPTEN_BINDINGS(js_funcs)
{
em::function("startVisualization", &js::startVisualization);
em::function("updateVisualization", &js::updateVisualization);
em::function("iterVisualization", &js::iterVisualization);
em::function("sendExposeEvent", &SendExposeEvent);
em::function("disableKeyHanding", &js::disableKeyHandling);
em::function("enableKeyHandling", &js::enableKeyHandling);
em::function("setKeyboardListeningElementId",
js::setKeyboardListeningElementId);
em::function("getTextureMode", &GetUseTexture);
em::function("setTextureMode", &SetUseTexture);
em::function("resizeWindow", &ResizeWindow);
em::function("setCanvasId", &js::setCanvasId);
em::function("setupResizeEventCallback", &js::setupResizeEventCallback);
em::function("getHelpString", &js::getHelpString);
}
<commit_msg>use uniform assignment<commit_after>// Copyright (c) 2010-2020, Lawrence Livermore National Security, LLC. Produced
// at the Lawrence Livermore National Laboratory. All Rights reserved. See files
// LICENSE and NOTICE for details. LLNL-CODE-443271.
//
// This file is part of the GLVis visualization tool and library. For more
// information and source code availability see https://glvis.org.
//
// GLVis is free software; you can redistribute it and/or modify it under the
// terms of the BSD-3 license. We welcome feedback and contributions, see file
// CONTRIBUTING.md for details.
#include "visual.hpp"
#include "palettes.hpp"
#include "stream_reader.hpp"
#include <SDL2/SDL_hints.h>
#include <emscripten/bind.h>
#include <emscripten/html5.h>
std::string plot_caption;
std::string extra_caption; // used in extern context
mfem::GeometryRefiner GLVisGeometryRefiner; // used in extern context
static VisualizationSceneScalarData * vs = nullptr;
namespace js
{
using namespace mfem;
// Replace a given VectorFiniteElement-based grid function (e.g. from a Nedelec
// or Raviart-Thomas space) with a discontinuous piece-wise polynomial Cartesian
// product vector grid function of the same order.
GridFunction *ProjectVectorFEGridFunction(GridFunction *gf)
{
if ((gf->VectorDim() == 3) && (gf->FESpace()->GetVDim() == 1))
{
int p = gf->FESpace()->GetOrder(0);
cout << "Switching to order " << p
<< " discontinuous vector grid function..." << endl;
int dim = gf->FESpace()->GetMesh()->Dimension();
FiniteElementCollection *d_fec = new L2_FECollection(p, dim, 1);
FiniteElementSpace *d_fespace =
new FiniteElementSpace(gf->FESpace()->GetMesh(), d_fec, 3);
GridFunction *d_gf = new GridFunction(d_fespace);
d_gf->MakeOwner(d_fec);
gf->ProjectVectorFieldOn(*d_gf);
delete gf;
return d_gf;
}
return gf;
}
bool startVisualization(const std::string input, const std::string data_type,
int w, int h)
{
std::stringstream ss(input);
const int field_type = ReadStream(ss, data_type);
// reset antialiasing
GetAppWindow()->getRenderer().setAntialiasing(0);
std::string line;
while (ss >> line)
{
if (line == "keys")
{
std::cout << "parsing 'keys'" << std::endl;
ss >> stream_state.keys;
}
else
{
std::cout << "unknown line '" << line << "'" << std::endl;
}
}
if (field_type < 0 || field_type > 2)
{
return false;
}
if (InitVisualization("glvis", 0, 0, w, h))
{
return false;
}
delete vs;
vs = nullptr;
double mesh_range = -1.0;
if (field_type == 0 || field_type == 2)
{
if (stream_state.grid_f)
{
stream_state.grid_f->GetNodalValues(stream_state.sol);
}
if (stream_state.mesh->SpaceDimension() == 2)
{
VisualizationSceneSolution * vss;
if (field_type == 2)
{
// Use the 'bone' palette when visualizing a 2D mesh only
paletteSet(4);
}
// Otherwise, the 'jet-like' palette is used in 2D see vssolution.cpp
if (stream_state.normals.Size() > 0)
{
vs = vss = new VisualizationSceneSolution(*stream_state.mesh, stream_state.sol,
&stream_state.normals);
}
else
{
vs = vss = new VisualizationSceneSolution(*stream_state.mesh, stream_state.sol);
}
if (stream_state.grid_f)
{
vss->SetGridFunction(*stream_state.grid_f);
}
if (field_type == 2)
{
vs->OrthogonalProjection = 1;
vs->SetLight(0);
vs->Zoom(1.8);
}
}
else if (stream_state.mesh->SpaceDimension() == 3)
{
VisualizationSceneSolution3d * vss;
vs = vss = new VisualizationSceneSolution3d(*stream_state.mesh,
stream_state.sol);
if (stream_state.grid_f)
{
vss->SetGridFunction(stream_state.grid_f);
}
if (field_type == 2)
{
if (stream_state.mesh->Dimension() == 3)
{
// Use the 'white' palette when visualizing a 3D volume mesh only
// paletteSet(4);
paletteSet(11);
vss->SetLightMatIdx(4);
}
else
{
// Use the 'bone' palette when visualizing a surface mesh only
// (the same as when visualizing a 2D mesh only)
paletteSet(4);
}
// Otherwise, the 'vivid' palette is used in 3D see vssolution3d.cpp
vss->ToggleDrawAxes();
vss->ToggleDrawMesh();
}
}
if (field_type == 2)
{
if (stream_state.grid_f)
{
mesh_range = stream_state.grid_f->Max() + 1.0;
}
else
{
mesh_range = stream_state.sol.Max() + 1.0;
}
}
}
else if (field_type == 1)
{
if (stream_state.mesh->SpaceDimension() == 2)
{
if (stream_state.grid_f)
{
vs = new VisualizationSceneVector(*stream_state.grid_f);
}
else
{
vs = new VisualizationSceneVector(*stream_state.mesh, stream_state.solu,
stream_state.solv);
}
}
else if (stream_state.mesh->SpaceDimension() == 3)
{
if (stream_state.grid_f)
{
stream_state.grid_f = ProjectVectorFEGridFunction(stream_state.grid_f);
vs = new VisualizationSceneVector3d(*stream_state.grid_f);
}
else
{
vs = new VisualizationSceneVector3d(*stream_state.mesh, stream_state.solu,
stream_state.solv, stream_state.solw);
}
}
}
if (vs)
{
// increase the refinement factors if visualizing a GridFunction
if (stream_state.grid_f)
{
vs->AutoRefine();
vs->SetShading(2, true);
}
if (mesh_range > 0.0)
{
vs->SetValueRange(-mesh_range, mesh_range);
vs->SetAutoscale(0);
}
if (stream_state.mesh->SpaceDimension() == 2 && field_type == 2)
{
SetVisualizationScene(vs, 2);
}
else
{
SetVisualizationScene(vs, 3);
}
}
CallKeySequence(stream_state.keys.c_str());
SendExposeEvent();
return true;
}
int updateVisualization(std::string data_type, std::string stream)
{
std::stringstream ss(stream);
if (data_type != "solution")
{
std::cerr << "unsupported data type '" << data_type << "' for stream update" <<
std::endl;
return 1;
}
auto * new_m = new Mesh(ss, 1, 0, stream_state.fix_elem_orient);
auto * new_g = new GridFunction(new_m, ss);
double mesh_range = -1.0;
if (new_m->SpaceDimension() == stream_state.mesh->SpaceDimension() &&
new_g->VectorDim() == stream_state.grid_f->VectorDim())
{
if (new_m->SpaceDimension() == 2)
{
if (new_g->VectorDim() == 1)
{
VisualizationSceneSolution *vss =
dynamic_cast<VisualizationSceneSolution *>(vs);
new_g->GetNodalValues(stream_state.sol);
vss->NewMeshAndSolution(new_m, &stream_state.sol, new_g);
}
else
{
VisualizationSceneVector *vsv =
dynamic_cast<VisualizationSceneVector *>(vs);
vsv->NewMeshAndSolution(*new_g);
}
}
else
{
if (new_g->VectorDim() == 1)
{
VisualizationSceneSolution3d *vss =
dynamic_cast<VisualizationSceneSolution3d *>(vs);
new_g->GetNodalValues(stream_state.sol);
vss->NewMeshAndSolution(new_m, &stream_state.sol, new_g);
}
else
{
new_g = ProjectVectorFEGridFunction(new_g);
VisualizationSceneVector3d *vss =
dynamic_cast<VisualizationSceneVector3d *>(vs);
vss->NewMeshAndSolution(new_m, new_g);
}
}
if (mesh_range > 0.0)
{
vs->SetValueRange(-mesh_range, mesh_range);
}
delete stream_state.grid_f;
stream_state.grid_f = new_g;
delete stream_state.mesh;
stream_state.mesh = new_m;
SendExposeEvent();
return 0;
}
else
{
cout << "Stream: field type does not match!" << endl;
delete new_g;
delete new_m;
return 1;
}
}
void iterVisualization()
{
GetAppWindow()->mainIter();
}
void setCanvasId(const std::string & id)
{
std::cout << "glvis: setting canvas id to " << id << std::endl;
GetAppWindow()->setCanvasId(id);
}
void disableKeyHandling()
{
SDL_EventState(SDL_KEYDOWN, SDL_DISABLE);
SDL_EventState(SDL_KEYUP, SDL_DISABLE);
}
void enableKeyHandling()
{
SDL_EventState(SDL_KEYDOWN, SDL_ENABLE);
SDL_EventState(SDL_KEYUP, SDL_ENABLE);
}
void setKeyboardListeningElementId(const std::string & id)
{
SDL_SetHint(SDL_HINT_EMSCRIPTEN_KEYBOARD_ELEMENT, id.c_str());
}
void setupResizeEventCallback(const std::string & id)
{
// typedef EM_BOOL (*em_ui_callback_func)(int eventType, const EmscriptenUiEvent *uiEvent, void *userData);
std::cout << "glvis: adding resize callback for " << id << std::endl;
auto err = emscripten_set_resize_callback(id.c_str(), nullptr,
true, [](int eventType, const EmscriptenUiEvent *uiEvent,
void *userData) -> EM_BOOL
{
std::cout << "got resize event" << std::endl;
return true;
});
// TODO: macro to wrap this
if (err != EMSCRIPTEN_RESULT_SUCCESS)
{
std::cerr << "error (emscripten_set_resize_callback): " << err << std::endl;
}
}
std::string getHelpString()
{
VisualizationSceneScalarData* vss
= dynamic_cast<VisualizationSceneScalarData*>(GetVisualizationScene());
return vss->GetHelpString();
}
} // namespace js
namespace em = emscripten;
EMSCRIPTEN_BINDINGS(js_funcs)
{
em::function("startVisualization", &js::startVisualization);
em::function("updateVisualization", &js::updateVisualization);
em::function("iterVisualization", &js::iterVisualization);
em::function("sendExposeEvent", &SendExposeEvent);
em::function("disableKeyHanding", &js::disableKeyHandling);
em::function("enableKeyHandling", &js::enableKeyHandling);
em::function("setKeyboardListeningElementId",
js::setKeyboardListeningElementId);
em::function("getTextureMode", &GetUseTexture);
em::function("setTextureMode", &SetUseTexture);
em::function("resizeWindow", &ResizeWindow);
em::function("setCanvasId", &js::setCanvasId);
em::function("setupResizeEventCallback", &js::setupResizeEventCallback);
em::function("getHelpString", &js::getHelpString);
}
<|endoftext|> |
<commit_before>#include <utility>
/******************************************************************************
* Copyright (C) 2017 Kitsune Ral <[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 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
*/
#include "avatar.h"
#include "jobs/mediathumbnailjob.h"
#include "events/eventcontent.h"
#include "connection.h"
#include <QtGui/QPainter>
#include <QtCore/QPointer>
using namespace QMatrixClient;
using std::move;
class Avatar::Private
{
public:
explicit Private(QIcon di, QUrl url = {})
: _defaultIcon(move(di)), _url(move(url))
{ }
QImage get(Connection* connection, QSize size,
get_callback_t callback) const;
bool upload(UploadContentJob* job, upload_callback_t callback);
bool checkUrl(QUrl url) const;
const QIcon _defaultIcon;
QUrl _url;
// The below are related to image caching, hence mutable
mutable QImage _originalImage;
mutable std::vector<QPair<QSize, QImage>> _scaledImages;
mutable QSize _requestedSize;
mutable bool _bannedUrl = false;
mutable bool _fetched = false;
mutable QPointer<MediaThumbnailJob> _thumbnailRequest = nullptr;
mutable QPointer<BaseJob> _uploadRequest = nullptr;
mutable std::vector<get_callback_t> callbacks;
};
Avatar::Avatar(QIcon defaultIcon)
: d(std::make_unique<Private>(std::move(defaultIcon)))
{ }
Avatar::Avatar(QUrl url, QIcon defaultIcon)
: d(std::make_unique<Private>(std::move(defaultIcon), std::move(url)))
{ }
Avatar::Avatar(Avatar&&) = default;
Avatar::~Avatar() = default;
Avatar& Avatar::operator=(Avatar&&) = default;
QImage Avatar::get(Connection* connection, int dimension,
get_callback_t callback) const
{
return d->get(connection, {dimension, dimension}, move(callback));
}
QImage Avatar::get(Connection* connection, int width, int height,
get_callback_t callback) const
{
return d->get(connection, {width, height}, move(callback));
}
bool Avatar::upload(Connection* connection, const QString& fileName,
upload_callback_t callback) const
{
if (isJobRunning(d->_uploadRequest))
return false;
return d->upload(connection->uploadFile(fileName), move(callback));
}
bool Avatar::upload(Connection* connection, QIODevice* source,
upload_callback_t callback) const
{
if (isJobRunning(d->_uploadRequest) || !source->isReadable())
return false;
return d->upload(connection->uploadContent(source), move(callback));
}
QString Avatar::mediaId() const
{
return d->_url.authority() + d->_url.path();
}
QImage Avatar::Private::get(Connection* connection, QSize size,
get_callback_t callback) const
{
// FIXME: Alternating between longer-width and longer-height requests
// is a sure way to trick the below code into constantly getting another
// image from the server because the existing one is alleged unsatisfactory.
// This is plain abuse by the client, though; so not critical for now.
if( ( !(_fetched || _thumbnailRequest)
|| size.width() > _requestedSize.width()
|| size.height() > _requestedSize.height() ) && checkUrl(_url) )
{
qCDebug(MAIN) << "Getting avatar from" << _url.toString();
_requestedSize = size;
if (isJobRunning(_thumbnailRequest))
_thumbnailRequest->abandon();
callbacks.emplace_back(move(callback));
_thumbnailRequest = connection->getThumbnail(_url, size);
QObject::connect( _thumbnailRequest, &MediaThumbnailJob::success,
_thumbnailRequest, [this] {
_fetched = true;
_originalImage =
_thumbnailRequest->scaledThumbnail(_requestedSize);
_scaledImages.clear();
for (const auto& n: callbacks)
n();
callbacks.clear();
});
}
if( _originalImage.isNull() )
{
if (_defaultIcon.isNull())
return _originalImage;
QPainter p { &_originalImage };
_defaultIcon.paint(&p, { QPoint(), _defaultIcon.actualSize(size) });
}
for (const auto& p: _scaledImages)
if (p.first == size)
return p.second;
auto result = _originalImage.scaled(size,
Qt::KeepAspectRatio, Qt::SmoothTransformation);
_scaledImages.emplace_back(size, result);
return result;
}
bool Avatar::Private::upload(UploadContentJob* job, upload_callback_t callback)
{
_uploadRequest = job;
if (!isJobRunning(_uploadRequest))
return false;
_uploadRequest->connect(_uploadRequest, &BaseJob::success, _uploadRequest,
[job,callback] { callback(job->contentUri()); });
return true;
}
bool Avatar::Private::checkUrl(QUrl url) const
{
if (_bannedUrl || url.isEmpty())
return false;
// FIXME: Make "mxc" a library-wide constant and maybe even make
// the URL checker a Connection(?) method.
_bannedUrl = !(url.isValid() &&
url.scheme() == "mxc" && url.path().count('/') == 1);
if (_bannedUrl)
qCWarning(MAIN) << "Avatar URL is invalid or not mxc-based:"
<< url.toDisplayString();
return !_bannedUrl;
}
QUrl Avatar::url() const { return d->_url; }
bool Avatar::updateUrl(const QUrl& newUrl)
{
if (newUrl == d->_url)
return false;
d->_url = newUrl;
d->_fetched = false;
if (isJobRunning(d->_thumbnailRequest))
d->_thumbnailRequest->abandon();
return true;
}
<commit_msg>Avatar: don't allow null callbacks to be registered<commit_after>#include <utility>
/******************************************************************************
* Copyright (C) 2017 Kitsune Ral <[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 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
*/
#include "avatar.h"
#include "jobs/mediathumbnailjob.h"
#include "events/eventcontent.h"
#include "connection.h"
#include <QtGui/QPainter>
#include <QtCore/QPointer>
using namespace QMatrixClient;
using std::move;
class Avatar::Private
{
public:
explicit Private(QIcon di, QUrl url = {})
: _defaultIcon(move(di)), _url(move(url))
{ }
QImage get(Connection* connection, QSize size,
get_callback_t callback) const;
bool upload(UploadContentJob* job, upload_callback_t callback);
bool checkUrl(QUrl url) const;
const QIcon _defaultIcon;
QUrl _url;
// The below are related to image caching, hence mutable
mutable QImage _originalImage;
mutable std::vector<QPair<QSize, QImage>> _scaledImages;
mutable QSize _requestedSize;
mutable bool _bannedUrl = false;
mutable bool _fetched = false;
mutable QPointer<MediaThumbnailJob> _thumbnailRequest = nullptr;
mutable QPointer<BaseJob> _uploadRequest = nullptr;
mutable std::vector<get_callback_t> callbacks;
};
Avatar::Avatar(QIcon defaultIcon)
: d(std::make_unique<Private>(std::move(defaultIcon)))
{ }
Avatar::Avatar(QUrl url, QIcon defaultIcon)
: d(std::make_unique<Private>(std::move(defaultIcon), std::move(url)))
{ }
Avatar::Avatar(Avatar&&) = default;
Avatar::~Avatar() = default;
Avatar& Avatar::operator=(Avatar&&) = default;
QImage Avatar::get(Connection* connection, int dimension,
get_callback_t callback) const
{
return d->get(connection, {dimension, dimension}, move(callback));
}
QImage Avatar::get(Connection* connection, int width, int height,
get_callback_t callback) const
{
return d->get(connection, {width, height}, move(callback));
}
bool Avatar::upload(Connection* connection, const QString& fileName,
upload_callback_t callback) const
{
if (isJobRunning(d->_uploadRequest))
return false;
return d->upload(connection->uploadFile(fileName), move(callback));
}
bool Avatar::upload(Connection* connection, QIODevice* source,
upload_callback_t callback) const
{
if (isJobRunning(d->_uploadRequest) || !source->isReadable())
return false;
return d->upload(connection->uploadContent(source), move(callback));
}
QString Avatar::mediaId() const
{
return d->_url.authority() + d->_url.path();
}
QImage Avatar::Private::get(Connection* connection, QSize size,
get_callback_t callback) const
{
if (!callback)
{
qCCritical(MAIN) << "Null callbacks are not allowed in Avatar::get";
Q_ASSERT(false);
}
// FIXME: Alternating between longer-width and longer-height requests
// is a sure way to trick the below code into constantly getting another
// image from the server because the existing one is alleged unsatisfactory.
// This is plain abuse by the client, though; so not critical for now.
if( ( !(_fetched || _thumbnailRequest)
|| size.width() > _requestedSize.width()
|| size.height() > _requestedSize.height() ) && checkUrl(_url) )
{
qCDebug(MAIN) << "Getting avatar from" << _url.toString();
_requestedSize = size;
if (isJobRunning(_thumbnailRequest))
_thumbnailRequest->abandon();
if (callback)
callbacks.emplace_back(move(callback));
_thumbnailRequest = connection->getThumbnail(_url, size);
QObject::connect( _thumbnailRequest, &MediaThumbnailJob::success,
_thumbnailRequest, [this] {
_fetched = true;
_originalImage =
_thumbnailRequest->scaledThumbnail(_requestedSize);
_scaledImages.clear();
for (const auto& n: callbacks)
n();
callbacks.clear();
});
}
if( _originalImage.isNull() )
{
if (_defaultIcon.isNull())
return _originalImage;
QPainter p { &_originalImage };
_defaultIcon.paint(&p, { QPoint(), _defaultIcon.actualSize(size) });
}
for (const auto& p: _scaledImages)
if (p.first == size)
return p.second;
auto result = _originalImage.scaled(size,
Qt::KeepAspectRatio, Qt::SmoothTransformation);
_scaledImages.emplace_back(size, result);
return result;
}
bool Avatar::Private::upload(UploadContentJob* job, upload_callback_t callback)
{
_uploadRequest = job;
if (!isJobRunning(_uploadRequest))
return false;
_uploadRequest->connect(_uploadRequest, &BaseJob::success, _uploadRequest,
[job,callback] { callback(job->contentUri()); });
return true;
}
bool Avatar::Private::checkUrl(QUrl url) const
{
if (_bannedUrl || url.isEmpty())
return false;
// FIXME: Make "mxc" a library-wide constant and maybe even make
// the URL checker a Connection(?) method.
_bannedUrl = !(url.isValid() &&
url.scheme() == "mxc" && url.path().count('/') == 1);
if (_bannedUrl)
qCWarning(MAIN) << "Avatar URL is invalid or not mxc-based:"
<< url.toDisplayString();
return !_bannedUrl;
}
QUrl Avatar::url() const { return d->_url; }
bool Avatar::updateUrl(const QUrl& newUrl)
{
if (newUrl == d->_url)
return false;
d->_url = newUrl;
d->_fetched = false;
if (isJobRunning(d->_thumbnailRequest))
d->_thumbnailRequest->abandon();
return true;
}
<|endoftext|> |
<commit_before>#include <boost/test/unit_test.hpp>
#include "ports/events/event_sinks.hpp"
#include "ports/events/event_sources.hpp"
#include "event_sink_with_queue.hpp"
#include "core/connection.hpp"
using namespace fc;
namespace fc
{
namespace pure
{
template<class T>
struct event_sink_value
{
void operator()(T in) { *storage = in; }
std::shared_ptr<T> storage = std::make_shared<T>();
};
template<class T>
struct event_sink_vector
{
void operator()(T in) { storage->push_back(in); }
std::shared_ptr<std::vector<T>> storage = std::make_shared<std::vector<T>>();
};
} // namespace pure
template<class T> struct is_passive_sink<pure::event_sink_value<T>> : std::true_type {};
template<class T> struct is_passive_sink<pure::event_sink_vector<T>> : std::true_type {};
} // namespace fc
namespace
{
/**
* \brief Node for calculating the number of elements in a range
*/
struct range_size
{
public:
range_size()
: out()
{}
pure::event_source<int> out;
auto in()
{
return ::fc::pure::make_event_sink_tmpl( [this](auto event)
{
size_t elems = std::distance(std::begin(event), std::end(event));
this->out.fire(static_cast<int>(elems));
} );
}
};
/**
* Helper class for testing event_in_port_tmpl
*/
class generic_input_node
{
public:
generic_input_node() : value() {}
/*
* Define a getter for the port named "in" and
* Declare a member function to be called from the port.
* The token type is available as "event_t" and the token as "event".
*/
auto in()
{
return ::fc::pure::make_event_sink_tmpl( [this](auto event)
{
value = event;
} );
}
int value;
};
} // unnamed namespace
BOOST_AUTO_TEST_SUITE(test_events)
BOOST_AUTO_TEST_CASE( test_event_in_port_tmpl )
{
pure::event_source<int> src_int;
pure::event_source<double> src_double;
generic_input_node to;
src_int >> to.in();
src_double >> to.in();
src_int.fire(2);
BOOST_CHECK_EQUAL(to.value, 2);
src_int.fire(4.1);
BOOST_CHECK_EQUAL(to.value, 4);
}
BOOST_AUTO_TEST_CASE( connections )
{
static_assert(is_active<pure::event_source<int>>{},
"event_out_port is active by definition");
static_assert(is_passive<pure::event_sink<int>>{},
"event_in_port is passive by definition");
static_assert(!is_active<pure::event_sink<int>>{},
"event_in_port is not active by definition");
static_assert(!is_passive<pure::event_source<int>>{},
"event_out_port is not passive by definition");
pure::event_source<int> test_event;
pure::event_sink_value<int> test_handler;
connect(test_event, test_handler);
test_event.fire(1);
BOOST_CHECK_EQUAL(*(test_handler.storage), 1);
auto tmp_connection = test_event >> [](int i){return ++i;};
static_assert(is_instantiation_of<
detail::active_connection_proxy, decltype(tmp_connection)>{},
"active port connected with standard connectable gets proxy");
std::move(tmp_connection) >> test_handler;
test_event.fire(1);
BOOST_CHECK_EQUAL(*(test_handler.storage), 2);
auto incr = [](int i){return ++i;};
test_event >> incr >> incr >> incr >> test_handler;
test_event.fire(1);
BOOST_CHECK_EQUAL(*(test_handler.storage), 4);
}
BOOST_AUTO_TEST_CASE( queue_sink )
{
auto inc = [](int i) { return i + 1; };
pure::event_source<int> source;
pure::event_sink_queue<int> sink;
source >> inc >> sink;
source.fire(4);
BOOST_CHECK_EQUAL(sink.empty(), false);
int received = sink.get();
BOOST_CHECK_EQUAL(received, 5);
BOOST_CHECK_EQUAL(sink.empty(), true);
}
BOOST_AUTO_TEST_CASE( merge_events )
{
pure::event_source<int> test_event;
pure::event_source<int> test_event_2;
pure::event_sink_vector<int> test_handler;
test_event >> test_handler;
test_event_2 >> test_handler;
test_event.fire(0);
BOOST_CHECK_EQUAL(test_handler.storage->size(), 1);
BOOST_CHECK_EQUAL(test_handler.storage->back(), 0);
test_event_2.fire(1);
BOOST_CHECK_EQUAL(test_handler.storage->size(), 2);
BOOST_CHECK_EQUAL(test_handler.storage->front(), 0);
BOOST_CHECK_EQUAL(test_handler.storage->back(), 1);
}
BOOST_AUTO_TEST_CASE( split_events )
{
pure::event_source<int> test_event;
pure::event_sink_value<int> test_handler_1;
pure::event_sink_value<int> test_handler_2;
test_event >> test_handler_1;
test_event >> test_handler_2;
test_event.fire(2);
BOOST_CHECK_EQUAL(*(test_handler_1.storage), 2);
BOOST_CHECK_EQUAL(*(test_handler_2.storage), 2);
}
BOOST_AUTO_TEST_CASE( in_port )
{
int test_value = 0;
auto test_writer = [&](int i) {test_value = i;};
pure::event_sink<int> in_port(test_writer);
pure::event_source<int> test_event;
test_event >> in_port;
test_event.fire(1);
BOOST_CHECK_EQUAL(test_value, 1);
//test void event
auto write_999 = [&]() {test_value = 999;};
pure::event_sink<void> void_in(write_999);
pure::event_source<void> void_out;
void_out >> void_in;
void_out.fire();
BOOST_CHECK_EQUAL(test_value, 999);
}
BOOST_AUTO_TEST_CASE( test_event_out_port )
{
range_size get_size;
int storage = 0;
get_size.out >> [&](int i) { storage = i; };
get_size.in()(std::list<float>{1., 2., .3});
BOOST_CHECK_EQUAL(storage, 3);
get_size.in()(std::vector<int>{0, 1});
BOOST_CHECK_EQUAL(storage, 2);
}
BOOST_AUTO_TEST_CASE( lambda )
{
int test_value = 0;
auto write_666 = [&]() {test_value = 666;};
pure::event_source<void> void_out_2;
void_out_2 >> write_666;
void_out_2.fire();
BOOST_CHECK_EQUAL(test_value, 666);
}
namespace
{
template<class T>
void test_connection(const T& connection)
{
int storage = 0;
pure::event_source<int> a;
pure::event_sink_queue<int> d;
auto c = [&](int i) { storage = i; return i; };
auto b = [](int i) { return i + 1; };
connection(a,b,c,d);
a.fire(2);
BOOST_CHECK_EQUAL(storage, 3);
BOOST_CHECK_EQUAL(d.get(), 3);
}
}
/**
* Confirm that connecting ports and connectables
* does not depend on any particular order.
*/
BOOST_AUTO_TEST_CASE( associativity )
{
test_connection([](auto& a, auto& b, auto& c, auto& d)
{
a >> b >> c >> d;
});
test_connection([](auto& a, auto& b, auto& c, auto& d)
{
(a >> b) >> (c >> d);
});
test_connection([](auto& a, auto& b, auto& c, auto& d)
{
a >> ((b >> c) >> d);
});
test_connection([](auto& a, auto& b, auto& c, auto& d)
{
(a >> (b >> c)) >> d;
});
}
namespace
{
template<class operation>
struct sink_t
{
typedef void result_t;
template <class T>
void operator()(T&& in) { op(std::forward<T>(in)); }
operation op;
};
template<class operation>
auto sink(const operation& op )
{
return sink_t<operation>{op};
}
}
BOOST_AUTO_TEST_CASE( test_polymorphic_lambda )
{
int test_value = 0;
pure::event_source<int> p;
auto write = sink([&](auto in) {test_value = in;});
static_assert(is_passive_sink<decltype(write)>{}, "");
p >> write;
BOOST_CHECK_EQUAL(test_value, 0);
p.fire(4);
BOOST_CHECK_EQUAL(test_value, 4);
}
BOOST_AUTO_TEST_CASE(test_sink_has_callback)
{
static_assert(has_register_function<pure::event_sink<void>>(0),
"type is defined with ability to register a callback");
}
template <class T>
struct disconnecting_event_sink : public pure::event_sink<T>
{
disconnecting_event_sink() :
pure::event_sink<T>(
[&](T in){
*storage = in;
}
)
{
}
std::shared_ptr<T> storage = std::make_shared<T>();
};
BOOST_AUTO_TEST_CASE(test_sink_deleted_callback)
{
disconnecting_event_sink<int> test_sink1;
{
pure::event_source<int> test_source;
disconnecting_event_sink<int> test_sink4;
test_source >> test_sink1;
test_source.fire(5);
BOOST_CHECK_EQUAL(*(test_sink1.storage), 5);
{
disconnecting_event_sink<int> test_sink2;
disconnecting_event_sink<int> test_sink3;
test_source >> test_sink2;
test_source >> test_sink3;
test_source.fire(6);
BOOST_CHECK_EQUAL(*(test_sink2.storage), 6);
BOOST_CHECK_EQUAL(*(test_sink3.storage), 6);
test_source >> test_sink4;
test_source.fire(7);
BOOST_CHECK_EQUAL(*(test_sink4.storage), 7);
}
// this primarily checks, that no exception is thrown
// since the connections from test_source to sink1-3 are deleted.
test_source.fire(8);
BOOST_CHECK_EQUAL(*(test_sink4.storage), 8);
}
}
BOOST_AUTO_TEST_CASE(test_delete_with_lambda_in_connection)
{
disconnecting_event_sink<int> test_sink;
pure::event_source<int> test_source;
(test_source >> [](int i){ return i+1; }) >> test_sink;
{
disconnecting_event_sink<int> test_sink_2;
test_source >> ([](int i){ return i+1; }
>> [](int i){ return i+1; })
>> test_sink_2;
test_source.fire(10);
BOOST_CHECK_EQUAL(*(test_sink_2.storage), 12);
}
test_source.fire(11);
BOOST_CHECK_EQUAL(*(test_sink.storage), 12);
}
BOOST_AUTO_TEST_SUITE_END()
<commit_msg>Added test to check for correct deletion of handlers in event_source<commit_after>#include <boost/test/unit_test.hpp>
#include "ports/events/event_sinks.hpp"
#include "ports/events/event_sources.hpp"
#include "event_sink_with_queue.hpp"
#include "core/connection.hpp"
using namespace fc;
namespace fc
{
namespace pure
{
template<class T>
struct event_sink_value
{
void operator()(T in) { *storage = in; }
std::shared_ptr<T> storage = std::make_shared<T>();
};
template<class T>
struct event_sink_vector
{
void operator()(T in) { storage->push_back(in); }
std::shared_ptr<std::vector<T>> storage = std::make_shared<std::vector<T>>();
};
} // namespace pure
template<class T> struct is_passive_sink<pure::event_sink_value<T>> : std::true_type {};
template<class T> struct is_passive_sink<pure::event_sink_vector<T>> : std::true_type {};
} // namespace fc
namespace
{
/**
* \brief Node for calculating the number of elements in a range
*/
struct range_size
{
public:
range_size()
: out()
{}
pure::event_source<int> out;
auto in()
{
return ::fc::pure::make_event_sink_tmpl( [this](auto event)
{
size_t elems = std::distance(std::begin(event), std::end(event));
this->out.fire(static_cast<int>(elems));
} );
}
};
/**
* Helper class for testing event_in_port_tmpl
*/
class generic_input_node
{
public:
generic_input_node() : value() {}
/*
* Define a getter for the port named "in" and
* Declare a member function to be called from the port.
* The token type is available as "event_t" and the token as "event".
*/
auto in()
{
return ::fc::pure::make_event_sink_tmpl( [this](auto event)
{
value = event;
} );
}
int value;
};
} // unnamed namespace
BOOST_AUTO_TEST_SUITE(test_events)
BOOST_AUTO_TEST_CASE( test_event_in_port_tmpl )
{
pure::event_source<int> src_int;
pure::event_source<double> src_double;
generic_input_node to;
src_int >> to.in();
src_double >> to.in();
src_int.fire(2);
BOOST_CHECK_EQUAL(to.value, 2);
src_int.fire(4.1);
BOOST_CHECK_EQUAL(to.value, 4);
}
BOOST_AUTO_TEST_CASE( connections )
{
static_assert(is_active<pure::event_source<int>>{},
"event_out_port is active by definition");
static_assert(is_passive<pure::event_sink<int>>{},
"event_in_port is passive by definition");
static_assert(!is_active<pure::event_sink<int>>{},
"event_in_port is not active by definition");
static_assert(!is_passive<pure::event_source<int>>{},
"event_out_port is not passive by definition");
pure::event_source<int> test_event;
pure::event_sink_value<int> test_handler;
connect(test_event, test_handler);
test_event.fire(1);
BOOST_CHECK_EQUAL(*(test_handler.storage), 1);
auto tmp_connection = test_event >> [](int i){return ++i;};
static_assert(is_instantiation_of<
detail::active_connection_proxy, decltype(tmp_connection)>{},
"active port connected with standard connectable gets proxy");
std::move(tmp_connection) >> test_handler;
test_event.fire(1);
BOOST_CHECK_EQUAL(*(test_handler.storage), 2);
auto incr = [](int i){return ++i;};
test_event >> incr >> incr >> incr >> test_handler;
test_event.fire(1);
BOOST_CHECK_EQUAL(*(test_handler.storage), 4);
}
BOOST_AUTO_TEST_CASE( queue_sink )
{
auto inc = [](int i) { return i + 1; };
pure::event_source<int> source;
pure::event_sink_queue<int> sink;
source >> inc >> sink;
source.fire(4);
BOOST_CHECK_EQUAL(sink.empty(), false);
int received = sink.get();
BOOST_CHECK_EQUAL(received, 5);
BOOST_CHECK_EQUAL(sink.empty(), true);
}
BOOST_AUTO_TEST_CASE( merge_events )
{
pure::event_source<int> test_event;
pure::event_source<int> test_event_2;
pure::event_sink_vector<int> test_handler;
test_event >> test_handler;
test_event_2 >> test_handler;
test_event.fire(0);
BOOST_CHECK_EQUAL(test_handler.storage->size(), 1);
BOOST_CHECK_EQUAL(test_handler.storage->back(), 0);
test_event_2.fire(1);
BOOST_CHECK_EQUAL(test_handler.storage->size(), 2);
BOOST_CHECK_EQUAL(test_handler.storage->front(), 0);
BOOST_CHECK_EQUAL(test_handler.storage->back(), 1);
}
BOOST_AUTO_TEST_CASE( split_events )
{
pure::event_source<int> test_event;
pure::event_sink_value<int> test_handler_1;
pure::event_sink_value<int> test_handler_2;
test_event >> test_handler_1;
test_event >> test_handler_2;
test_event.fire(2);
BOOST_CHECK_EQUAL(*(test_handler_1.storage), 2);
BOOST_CHECK_EQUAL(*(test_handler_2.storage), 2);
}
BOOST_AUTO_TEST_CASE( in_port )
{
int test_value = 0;
auto test_writer = [&](int i) {test_value = i;};
pure::event_sink<int> in_port(test_writer);
pure::event_source<int> test_event;
test_event >> in_port;
test_event.fire(1);
BOOST_CHECK_EQUAL(test_value, 1);
//test void event
auto write_999 = [&]() {test_value = 999;};
pure::event_sink<void> void_in(write_999);
pure::event_source<void> void_out;
void_out >> void_in;
void_out.fire();
BOOST_CHECK_EQUAL(test_value, 999);
}
BOOST_AUTO_TEST_CASE( test_event_out_port )
{
range_size get_size;
int storage = 0;
get_size.out >> [&](int i) { storage = i; };
get_size.in()(std::list<float>{1., 2., .3});
BOOST_CHECK_EQUAL(storage, 3);
get_size.in()(std::vector<int>{0, 1});
BOOST_CHECK_EQUAL(storage, 2);
}
BOOST_AUTO_TEST_CASE( lambda )
{
int test_value = 0;
auto write_666 = [&]() {test_value = 666;};
pure::event_source<void> void_out_2;
void_out_2 >> write_666;
void_out_2.fire();
BOOST_CHECK_EQUAL(test_value, 666);
}
namespace
{
template<class T>
void test_connection(const T& connection)
{
int storage = 0;
pure::event_source<int> a;
pure::event_sink_queue<int> d;
auto c = [&](int i) { storage = i; return i; };
auto b = [](int i) { return i + 1; };
connection(a,b,c,d);
a.fire(2);
BOOST_CHECK_EQUAL(storage, 3);
BOOST_CHECK_EQUAL(d.get(), 3);
}
}
/**
* Confirm that connecting ports and connectables
* does not depend on any particular order.
*/
BOOST_AUTO_TEST_CASE( associativity )
{
test_connection([](auto& a, auto& b, auto& c, auto& d)
{
a >> b >> c >> d;
});
test_connection([](auto& a, auto& b, auto& c, auto& d)
{
(a >> b) >> (c >> d);
});
test_connection([](auto& a, auto& b, auto& c, auto& d)
{
a >> ((b >> c) >> d);
});
test_connection([](auto& a, auto& b, auto& c, auto& d)
{
(a >> (b >> c)) >> d;
});
}
namespace
{
template<class operation>
struct sink_t
{
typedef void result_t;
template <class T>
void operator()(T&& in) { op(std::forward<T>(in)); }
operation op;
};
template<class operation>
auto sink(const operation& op )
{
return sink_t<operation>{op};
}
}
BOOST_AUTO_TEST_CASE( test_polymorphic_lambda )
{
int test_value = 0;
pure::event_source<int> p;
auto write = sink([&](auto in) {test_value = in;});
static_assert(is_passive_sink<decltype(write)>{}, "");
p >> write;
BOOST_CHECK_EQUAL(test_value, 0);
p.fire(4);
BOOST_CHECK_EQUAL(test_value, 4);
}
BOOST_AUTO_TEST_CASE(test_sink_has_callback)
{
static_assert(has_register_function<pure::event_sink<void>>(0),
"type is defined with ability to register a callback");
}
template <class T>
struct disconnecting_event_sink : public pure::event_sink<T>
{
disconnecting_event_sink() :
pure::event_sink<T>(
[&](T in){
*storage = in;
}
)
{
}
std::shared_ptr<T> storage = std::make_shared<T>();
};
BOOST_AUTO_TEST_CASE(test_sink_deleted_callback)
{
disconnecting_event_sink<int> test_sink1;
{
pure::event_source<int> test_source;
disconnecting_event_sink<int> test_sink4;
test_source >> test_sink1;
test_source.fire(5);
BOOST_CHECK_EQUAL(*(test_sink1.storage), 5);
{
disconnecting_event_sink<int> test_sink2;
disconnecting_event_sink<int> test_sink3;
test_source >> test_sink2;
test_source >> test_sink3;
test_source.fire(6);
BOOST_CHECK_EQUAL(*(test_sink2.storage), 6);
BOOST_CHECK_EQUAL(*(test_sink3.storage), 6);
test_source >> test_sink4;
test_source.fire(7);
BOOST_CHECK_EQUAL(*(test_sink4.storage), 7);
BOOST_CHECK_EQUAL(test_source.nr_connected_handlers(), 4);
}
BOOST_CHECK_EQUAL(test_source.nr_connected_handlers(), 2);
// this primarily checks, that no exception is thrown
// since the connections from test_source to sink1-3 are deleted.
test_source.fire(8);
BOOST_CHECK_EQUAL(*(test_sink4.storage), 8);
}
}
BOOST_AUTO_TEST_CASE(test_delete_with_lambda_in_connection)
{
disconnecting_event_sink<int> test_sink;
pure::event_source<int> test_source;
(test_source >> [](int i){ return i+1; }) >> test_sink;
{
disconnecting_event_sink<int> test_sink_2;
test_source >> ([](int i){ return i+1; }
>> [](int i){ return i+1; })
>> test_sink_2;
test_source.fire(10);
BOOST_CHECK_EQUAL(*(test_sink_2.storage), 12);
BOOST_CHECK_EQUAL(test_source.nr_connected_handlers(), 2);
}
BOOST_CHECK_EQUAL(test_source.nr_connected_handlers(), 1);
test_source.fire(11);
BOOST_CHECK_EQUAL(*(test_sink.storage), 12);
}
BOOST_AUTO_TEST_SUITE_END()
<|endoftext|> |
<commit_before>//===-------- cfi.cc ------------------------------------------------------===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This file implements the runtime support for the cross-DSO CFI.
//
//===----------------------------------------------------------------------===//
// FIXME: Intercept dlopen/dlclose.
// FIXME: Support diagnostic mode.
// FIXME: Harden:
// * mprotect shadow, use mremap for updates
// * something else equally important
#include <assert.h>
#include <elf.h>
#include <link.h>
#include <string.h>
typedef ElfW(Phdr) Elf_Phdr;
typedef ElfW(Ehdr) Elf_Ehdr;
#include "interception/interception.h"
#include "sanitizer_common/sanitizer_common.h"
#include "sanitizer_common/sanitizer_flag_parser.h"
#include "ubsan/ubsan_init.h"
#include "ubsan/ubsan_flags.h"
static uptr __cfi_shadow;
static constexpr uptr kShadowGranularity = 12;
static constexpr uptr kShadowAlign = 1UL << kShadowGranularity; // 4096
static constexpr uint16_t kInvalidShadow = 0;
static constexpr uint16_t kUncheckedShadow = 0xFFFFU;
static uint16_t *mem_to_shadow(uptr x) {
return (uint16_t *)(__cfi_shadow + ((x >> kShadowGranularity) << 1));
}
typedef int (*CFICheckFn)(uptr, void *);
class ShadowValue {
uptr addr;
uint16_t v;
explicit ShadowValue(uptr addr, uint16_t v) : addr(addr), v(v) {}
public:
bool is_invalid() const { return v == kInvalidShadow; }
bool is_unchecked() const { return v == kUncheckedShadow; }
CFICheckFn get_cfi_check() const {
assert(!is_invalid() && !is_unchecked());
uptr aligned_addr = addr & ~(kShadowAlign - 1);
uptr p = aligned_addr - (((uptr)v - 1) << kShadowGranularity);
return reinterpret_cast<CFICheckFn>(p);
}
// Load a shadow valud for the given application memory address.
static const ShadowValue load(uptr addr) {
return ShadowValue(addr, *mem_to_shadow(addr));
}
};
static void fill_shadow_constant(uptr begin, uptr end, uint16_t v) {
assert(v == kInvalidShadow || v == kUncheckedShadow);
uint16_t *shadow_begin = mem_to_shadow(begin);
uint16_t *shadow_end = mem_to_shadow(end - 1) + 1;
memset(shadow_begin, v, (shadow_end - shadow_begin) * sizeof(*shadow_begin));
}
static void fill_shadow(uptr begin, uptr end, uptr cfi_check) {
assert((cfi_check & (kShadowAlign - 1)) == 0);
// Don't fill anything below cfi_check. We can not represent those addresses
// in the shadow, and must make sure at codegen to place all valid call
// targets above cfi_check.
uptr p = Max(begin, cfi_check);
uint16_t *s = mem_to_shadow(p);
uint16_t *s_end = mem_to_shadow(end - 1) + 1;
uint16_t sv = ((p - cfi_check) >> kShadowGranularity) + 1;
for (; s < s_end; s++, sv++)
*s = sv;
// Sanity checks.
uptr q = p & ~(kShadowAlign - 1);
for (; q < end; q += kShadowAlign) {
assert((uptr)ShadowValue::load(q).get_cfi_check() == cfi_check);
assert((uptr)ShadowValue::load(q + kShadowAlign / 2).get_cfi_check() ==
cfi_check);
assert((uptr)ShadowValue::load(q + kShadowAlign - 1).get_cfi_check() ==
cfi_check);
}
}
// This is a workaround for a glibc bug:
// https://sourceware.org/bugzilla/show_bug.cgi?id=15199
// Other platforms can, hopefully, just do
// dlopen(RTLD_NOLOAD | RTLD_LAZY)
// dlsym("__cfi_check").
static uptr find_cfi_check_in_dso(dl_phdr_info *info) {
const ElfW(Dyn) *dynamic = nullptr;
for (int i = 0; i < info->dlpi_phnum; ++i) {
if (info->dlpi_phdr[i].p_type == PT_DYNAMIC) {
dynamic =
(const ElfW(Dyn) *)(info->dlpi_addr + info->dlpi_phdr[i].p_vaddr);
break;
}
}
if (!dynamic) return 0;
uptr strtab = 0, symtab = 0;
for (const ElfW(Dyn) *p = dynamic; p->d_tag != PT_NULL; ++p) {
if (p->d_tag == DT_SYMTAB)
symtab = p->d_un.d_ptr;
else if (p->d_tag == DT_STRTAB)
strtab = p->d_un.d_ptr;
}
if (symtab > strtab) {
VReport(1, "Can not handle: symtab > strtab (%p > %zx)\n", symtab, strtab);
return 0;
}
// Verify that strtab and symtab are inside of the same LOAD segment.
// This excludes VDSO, which has (very high) bogus strtab and symtab pointers.
int phdr_idx;
for (phdr_idx = 0; phdr_idx < info->dlpi_phnum; phdr_idx++) {
const Elf_Phdr *phdr = &info->dlpi_phdr[phdr_idx];
if (phdr->p_type == PT_LOAD) {
uptr beg = info->dlpi_addr + phdr->p_vaddr;
uptr end = beg + phdr->p_memsz;
if (strtab >= beg && strtab < end && symtab >= beg && symtab < end)
break;
}
}
if (phdr_idx == info->dlpi_phnum) {
// Nope, either different segments or just bogus pointers.
// Can not handle this.
VReport(1, "Can not handle: symtab %p, strtab %zx\n", symtab, strtab);
return 0;
}
for (const ElfW(Sym) *p = (const ElfW(Sym) *)symtab; (ElfW(Addr))p < strtab;
++p) {
char *name = (char*)(strtab + p->st_name);
if (strcmp(name, "__cfi_check") == 0) {
assert(p->st_info == ELF32_ST_INFO(STB_GLOBAL, STT_FUNC));
uptr addr = info->dlpi_addr + p->st_value;
return addr;
}
}
return 0;
}
static int dl_iterate_phdr_cb(dl_phdr_info *info, size_t size, void *data) {
uptr cfi_check = find_cfi_check_in_dso(info);
if (cfi_check)
VReport(1, "Module '%s' __cfi_check %zx\n", info->dlpi_name, cfi_check);
for (int i = 0; i < info->dlpi_phnum; i++) {
const Elf_Phdr *phdr = &info->dlpi_phdr[i];
if (phdr->p_type == PT_LOAD) {
// Jump tables are in the executable segment.
// VTables are in the non-executable one.
// Need to fill shadow for both.
// FIXME: reject writable if vtables are in the r/o segment. Depend on
// PT_RELRO?
uptr cur_beg = info->dlpi_addr + phdr->p_vaddr;
uptr cur_end = cur_beg + phdr->p_memsz;
if (cfi_check) {
VReport(1, " %zx .. %zx\n", cur_beg, cur_end);
fill_shadow(cur_beg, cur_end, cfi_check ? cfi_check : (uptr)(-1));
} else {
fill_shadow_constant(cur_beg, cur_end, kInvalidShadow);
}
}
}
return 0;
}
// Fill shadow for the initial libraries.
static void init_shadow() {
dl_iterate_phdr(dl_iterate_phdr_cb, nullptr);
}
SANITIZER_INTERFACE_ATTRIBUTE extern "C"
void __cfi_slowpath(uptr CallSiteTypeId, void *Ptr) {
uptr Addr = (uptr)Ptr;
VReport(3, "__cfi_slowpath: %zx, %p\n", CallSiteTypeId, Ptr);
ShadowValue sv = ShadowValue::load(Addr);
if (sv.is_invalid()) {
VReport(2, "CFI: invalid memory region for a function pointer (shadow==0): %p\n", Ptr);
Die();
}
if (sv.is_unchecked()) {
VReport(2, "CFI: unchecked call (shadow=FFFF): %p\n", Ptr);
return;
}
CFICheckFn cfi_check = sv.get_cfi_check();
VReport(2, "__cfi_check at %p\n", cfi_check);
cfi_check(CallSiteTypeId, Ptr);
}
static void InitializeFlags() {
SetCommonFlagsDefaults();
__ubsan::Flags *uf = __ubsan::flags();
uf->SetDefaults();
FlagParser cfi_parser;
RegisterCommonFlags(&cfi_parser);
FlagParser ubsan_parser;
__ubsan::RegisterUbsanFlags(&ubsan_parser, uf);
RegisterCommonFlags(&ubsan_parser);
const char *ubsan_default_options = __ubsan::MaybeCallUbsanDefaultOptions();
ubsan_parser.ParseString(ubsan_default_options);
cfi_parser.ParseString(GetEnv("CFI_OPTIONS"));
ubsan_parser.ParseString(GetEnv("UBSAN_OPTIONS"));
SetVerbosity(common_flags()->verbosity);
if (Verbosity()) ReportUnrecognizedFlags();
if (common_flags()->help) {
cfi_parser.PrintFlagDescriptions();
}
}
extern "C" __attribute__((visibility("default")))
#if !SANITIZER_CAN_USE_PREINIT_ARRAY
// On ELF platforms, the constructor is invoked using .preinit_array (see below)
__attribute__((constructor(0)))
#endif
void __cfi_init() {
SanitizerToolName = "CFI";
InitializeFlags();
uptr vma = GetMaxVirtualAddress();
// Shadow is 2 -> 2**kShadowGranularity.
uptr shadow_size = (vma >> (kShadowGranularity - 1)) + 1;
VReport(1, "CFI: VMA size %zx, shadow size %zx\n", vma, shadow_size);
void *shadow = MmapNoReserveOrDie(shadow_size, "CFI shadow");
VReport(1, "CFI: shadow at %zx .. %zx\n", shadow,
reinterpret_cast<uptr>(shadow) + shadow_size);
__cfi_shadow = (uptr)shadow;
init_shadow();
__ubsan::InitAsPlugin();
}
#if SANITIZER_CAN_USE_PREINIT_ARRAY
// On ELF platforms, run cfi initialization before any other constructors.
// On other platforms we use the constructor attribute to arrange to run our
// initialization early.
extern "C" {
__attribute__((section(".preinit_array"),
used)) void (*__cfi_preinit)(void) = __cfi_init;
}
#endif
<commit_msg>[cfi] Fix GCC build.<commit_after>//===-------- cfi.cc ------------------------------------------------------===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This file implements the runtime support for the cross-DSO CFI.
//
//===----------------------------------------------------------------------===//
// FIXME: Intercept dlopen/dlclose.
// FIXME: Support diagnostic mode.
// FIXME: Harden:
// * mprotect shadow, use mremap for updates
// * something else equally important
#include <assert.h>
#include <elf.h>
#include <link.h>
#include <string.h>
typedef ElfW(Phdr) Elf_Phdr;
typedef ElfW(Ehdr) Elf_Ehdr;
#include "interception/interception.h"
#include "sanitizer_common/sanitizer_common.h"
#include "sanitizer_common/sanitizer_flag_parser.h"
#include "ubsan/ubsan_init.h"
#include "ubsan/ubsan_flags.h"
static uptr __cfi_shadow;
static constexpr uptr kShadowGranularity = 12;
static constexpr uptr kShadowAlign = 1UL << kShadowGranularity; // 4096
static constexpr uint16_t kInvalidShadow = 0;
static constexpr uint16_t kUncheckedShadow = 0xFFFFU;
static uint16_t *mem_to_shadow(uptr x) {
return (uint16_t *)(__cfi_shadow + ((x >> kShadowGranularity) << 1));
}
typedef int (*CFICheckFn)(uptr, void *);
class ShadowValue {
uptr addr;
uint16_t v;
explicit ShadowValue(uptr addr, uint16_t v) : addr(addr), v(v) {}
public:
bool is_invalid() const { return v == kInvalidShadow; }
bool is_unchecked() const { return v == kUncheckedShadow; }
CFICheckFn get_cfi_check() const {
assert(!is_invalid() && !is_unchecked());
uptr aligned_addr = addr & ~(kShadowAlign - 1);
uptr p = aligned_addr - (((uptr)v - 1) << kShadowGranularity);
return reinterpret_cast<CFICheckFn>(p);
}
// Load a shadow valud for the given application memory address.
static const ShadowValue load(uptr addr) {
return ShadowValue(addr, *mem_to_shadow(addr));
}
};
static void fill_shadow_constant(uptr begin, uptr end, uint16_t v) {
assert(v == kInvalidShadow || v == kUncheckedShadow);
uint16_t *shadow_begin = mem_to_shadow(begin);
uint16_t *shadow_end = mem_to_shadow(end - 1) + 1;
memset(shadow_begin, v, (shadow_end - shadow_begin) * sizeof(*shadow_begin));
}
static void fill_shadow(uptr begin, uptr end, uptr cfi_check) {
assert((cfi_check & (kShadowAlign - 1)) == 0);
// Don't fill anything below cfi_check. We can not represent those addresses
// in the shadow, and must make sure at codegen to place all valid call
// targets above cfi_check.
uptr p = Max(begin, cfi_check);
uint16_t *s = mem_to_shadow(p);
uint16_t *s_end = mem_to_shadow(end - 1) + 1;
uint16_t sv = ((p - cfi_check) >> kShadowGranularity) + 1;
for (; s < s_end; s++, sv++)
*s = sv;
// Sanity checks.
uptr q = p & ~(kShadowAlign - 1);
for (; q < end; q += kShadowAlign) {
assert((uptr)ShadowValue::load(q).get_cfi_check() == cfi_check);
assert((uptr)ShadowValue::load(q + kShadowAlign / 2).get_cfi_check() ==
cfi_check);
assert((uptr)ShadowValue::load(q + kShadowAlign - 1).get_cfi_check() ==
cfi_check);
}
}
// This is a workaround for a glibc bug:
// https://sourceware.org/bugzilla/show_bug.cgi?id=15199
// Other platforms can, hopefully, just do
// dlopen(RTLD_NOLOAD | RTLD_LAZY)
// dlsym("__cfi_check").
static uptr find_cfi_check_in_dso(dl_phdr_info *info) {
const ElfW(Dyn) *dynamic = nullptr;
for (int i = 0; i < info->dlpi_phnum; ++i) {
if (info->dlpi_phdr[i].p_type == PT_DYNAMIC) {
dynamic =
(const ElfW(Dyn) *)(info->dlpi_addr + info->dlpi_phdr[i].p_vaddr);
break;
}
}
if (!dynamic) return 0;
uptr strtab = 0, symtab = 0;
for (const ElfW(Dyn) *p = dynamic; p->d_tag != PT_NULL; ++p) {
if (p->d_tag == DT_SYMTAB)
symtab = p->d_un.d_ptr;
else if (p->d_tag == DT_STRTAB)
strtab = p->d_un.d_ptr;
}
if (symtab > strtab) {
VReport(1, "Can not handle: symtab > strtab (%p > %zx)\n", symtab, strtab);
return 0;
}
// Verify that strtab and symtab are inside of the same LOAD segment.
// This excludes VDSO, which has (very high) bogus strtab and symtab pointers.
int phdr_idx;
for (phdr_idx = 0; phdr_idx < info->dlpi_phnum; phdr_idx++) {
const Elf_Phdr *phdr = &info->dlpi_phdr[phdr_idx];
if (phdr->p_type == PT_LOAD) {
uptr beg = info->dlpi_addr + phdr->p_vaddr;
uptr end = beg + phdr->p_memsz;
if (strtab >= beg && strtab < end && symtab >= beg && symtab < end)
break;
}
}
if (phdr_idx == info->dlpi_phnum) {
// Nope, either different segments or just bogus pointers.
// Can not handle this.
VReport(1, "Can not handle: symtab %p, strtab %zx\n", symtab, strtab);
return 0;
}
for (const ElfW(Sym) *p = (const ElfW(Sym) *)symtab; (ElfW(Addr))p < strtab;
++p) {
char *name = (char*)(strtab + p->st_name);
if (strcmp(name, "__cfi_check") == 0) {
assert(p->st_info == ELF32_ST_INFO(STB_GLOBAL, STT_FUNC));
uptr addr = info->dlpi_addr + p->st_value;
return addr;
}
}
return 0;
}
static int dl_iterate_phdr_cb(dl_phdr_info *info, size_t size, void *data) {
uptr cfi_check = find_cfi_check_in_dso(info);
if (cfi_check)
VReport(1, "Module '%s' __cfi_check %zx\n", info->dlpi_name, cfi_check);
for (int i = 0; i < info->dlpi_phnum; i++) {
const Elf_Phdr *phdr = &info->dlpi_phdr[i];
if (phdr->p_type == PT_LOAD) {
// Jump tables are in the executable segment.
// VTables are in the non-executable one.
// Need to fill shadow for both.
// FIXME: reject writable if vtables are in the r/o segment. Depend on
// PT_RELRO?
uptr cur_beg = info->dlpi_addr + phdr->p_vaddr;
uptr cur_end = cur_beg + phdr->p_memsz;
if (cfi_check) {
VReport(1, " %zx .. %zx\n", cur_beg, cur_end);
fill_shadow(cur_beg, cur_end, cfi_check ? cfi_check : (uptr)(-1));
} else {
fill_shadow_constant(cur_beg, cur_end, kInvalidShadow);
}
}
}
return 0;
}
// Fill shadow for the initial libraries.
static void init_shadow() {
dl_iterate_phdr(dl_iterate_phdr_cb, nullptr);
}
extern "C" SANITIZER_INTERFACE_ATTRIBUTE
void __cfi_slowpath(uptr CallSiteTypeId, void *Ptr) {
uptr Addr = (uptr)Ptr;
VReport(3, "__cfi_slowpath: %zx, %p\n", CallSiteTypeId, Ptr);
ShadowValue sv = ShadowValue::load(Addr);
if (sv.is_invalid()) {
VReport(2, "CFI: invalid memory region for a function pointer (shadow==0): %p\n", Ptr);
Die();
}
if (sv.is_unchecked()) {
VReport(2, "CFI: unchecked call (shadow=FFFF): %p\n", Ptr);
return;
}
CFICheckFn cfi_check = sv.get_cfi_check();
VReport(2, "__cfi_check at %p\n", cfi_check);
cfi_check(CallSiteTypeId, Ptr);
}
static void InitializeFlags() {
SetCommonFlagsDefaults();
__ubsan::Flags *uf = __ubsan::flags();
uf->SetDefaults();
FlagParser cfi_parser;
RegisterCommonFlags(&cfi_parser);
FlagParser ubsan_parser;
__ubsan::RegisterUbsanFlags(&ubsan_parser, uf);
RegisterCommonFlags(&ubsan_parser);
const char *ubsan_default_options = __ubsan::MaybeCallUbsanDefaultOptions();
ubsan_parser.ParseString(ubsan_default_options);
cfi_parser.ParseString(GetEnv("CFI_OPTIONS"));
ubsan_parser.ParseString(GetEnv("UBSAN_OPTIONS"));
SetVerbosity(common_flags()->verbosity);
if (Verbosity()) ReportUnrecognizedFlags();
if (common_flags()->help) {
cfi_parser.PrintFlagDescriptions();
}
}
extern "C" SANITIZER_INTERFACE_ATTRIBUTE
#if !SANITIZER_CAN_USE_PREINIT_ARRAY
// On ELF platforms, the constructor is invoked using .preinit_array (see below)
__attribute__((constructor(0)))
#endif
void __cfi_init() {
SanitizerToolName = "CFI";
InitializeFlags();
uptr vma = GetMaxVirtualAddress();
// Shadow is 2 -> 2**kShadowGranularity.
uptr shadow_size = (vma >> (kShadowGranularity - 1)) + 1;
VReport(1, "CFI: VMA size %zx, shadow size %zx\n", vma, shadow_size);
void *shadow = MmapNoReserveOrDie(shadow_size, "CFI shadow");
VReport(1, "CFI: shadow at %zx .. %zx\n", shadow,
reinterpret_cast<uptr>(shadow) + shadow_size);
__cfi_shadow = (uptr)shadow;
init_shadow();
__ubsan::InitAsPlugin();
}
#if SANITIZER_CAN_USE_PREINIT_ARRAY
// On ELF platforms, run cfi initialization before any other constructors.
// On other platforms we use the constructor attribute to arrange to run our
// initialization early.
extern "C" {
__attribute__((section(".preinit_array"),
used)) void (*__cfi_preinit)(void) = __cfi_init;
}
#endif
<|endoftext|> |
<commit_before>#include <cstdlib>
#include <cstdio>
#include <cstring>
#include <string>
#include <algorithm>
#include <unistd.h>
#include <sys/time.h>
#include <time.h>
#include "readjpeg.h"
typedef struct
{
float r;
float g;
float b;
} pixel_t;
void cuda_function(int data_size_X, int data_size_Y, float* kernel, pixel_t* in, pixel_t* out, double* t0, double* t1);
void cuda_function2(int data_size_X, int data_size_Y, float* kernel, float* in, float* out, double* t0, double* t1);
void normalize( float * kernel ) {
int sum = 0;
for (int i = 0; i < 25; i++ ) {
sum += kernel[i];
}
for (int i = 0; i < 25 && sum != 0; i++ ) {
kernel[i] /= sum;
}
}
void print_matrix(float *array, int num, int x_size){
int a = 0;
printf("%5.2f, ", array[a]);
for (a = 1; a < num; a++){
if (a%x_size == x_size-1){
printf("%5.2f,\n", array[a]);
} else{
printf("%5.2f, ", array[a]);
}
}
printf("\n");
}
void convert_to_pixel(pixel_t *out, frame_ptr in)
{
for(int y = 0; y < in->image_height; y++)
{
for(int x = 0; x < in->image_width; x++)
{
int r = (int)in->row_pointers[y][in->num_components*x + 0 ];
int g = (int)in->row_pointers[y][in->num_components*x + 1 ];
int b = (int)in->row_pointers[y][in->num_components*x + 2 ];
out[y*in->image_width+x].r = (float)r;
out[y*in->image_width+x].g = (float)g;
out[y*in->image_width+x].b = (float)b;
}
}
}
void convert_to_frame(frame_ptr out, pixel_t *in)
{
for(int y = 0; y < out->image_height; y++)
{
for(int x = 0; x < out->image_width; x++)
{
int r = (int)in[y*out->image_width + x].r;
int g = (int)in[y*out->image_width + x].g;
int b = (int)in[y*out->image_width + x].b;
out->row_pointers[y][out->num_components*x + 0 ] = r;
out->row_pointers[y][out->num_components*x + 1 ] = g;
out->row_pointers[y][out->num_components*x + 2 ] = b;
}
}
}
#define KERNX 5 //this is the x-size of the kernel. It will always be odd.
#define KERNY 5 //this is the y-size of the kernel. It will always be odd.
int main(int argc, char *argv[]){
float kernel_0[] = { 0, 0, 0, 0, 0, // "sharpen"
0, 0,-1, 0, 0,
0,-1, 5,-1, 0,
0, 0,-1, 0, 0,
0, 0, 0, 0, 0, }; normalize(kernel_0);
float kernel_1[]={ 1, 1, 1, 1, 1, // blur
1, 1, 1, 1, 1,
1, 1, 1, 1, 1,
1, 1, 1, 1, 1,
1, 1, 1, 1, 1, }; normalize(kernel_1);
float kernel_2[] = { 1, 1, 1, 1, 1, // weighted median filter
2, 2, 2, 2, 2,
3, 3, 3, 3, 3,
2, 2, 2, 2, 2,
1, 1, 1, 1, 1, };
float kernel_3[]={1,1,1,1,1, // weighted mean filter
1,2,2,2,1,
1,2,3,2,1,
1,2,2,2,1,
1,1,1,1,1, }; normalize(kernel_3);
float kernel_4[] = { 1, 4, 7, 4, 1, // gaussian
4,16,26,16, 4,
7,26,41,26, 7,
4,16,26,16, 4,
1, 4, 7, 4, 1, };
float kernel_5[] = { 0, 0, 0, 0, 0, // "emboss"
0,-2,-1, 0, 0,
0,-1, 1, 1, 0,
0, 0, 1, 2, 0,
0, 0, 0, 0, 0, };
float kernel_6[] = {-1,-1,-1,-1,-1, // "edge detect"
-1,-1,-1,-1,-1,
-1,-1,24,-1,-1,
-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1, };
float* kernels[7] = {kernel_0, kernel_1, kernel_2, kernel_3, kernel_4,
kernel_5, kernel_6};
int c;
int color = 0;
char *inName = NULL;
char *outName = NULL;
int width = -1, height = -1;
int kernel_num = 1;
frame_ptr frame;
pixel_t *inPix = NULL;
pixel_t *outPix = NULL;
//grab command line arguments
while((c = getopt(argc, argv, "i:k:o:c"))!=-1)
{
switch(c)
{
case 'i':
inName = optarg;
break;
case 'o':
outName = optarg;
break;
case 'k':
kernel_num = atoi(optarg);
break;
case 'c':
color = 1;
}
}
//input file name and output names
inName = inName==0 ? (char*)"cpt-kurt.jpg" : inName;
outName = outName==0 ? (char*)"output.jpg" : outName;
//read file
frame = read_JPEG_file(inName);
if(!frame){
printf("unable to read %s\n", inName);
exit(-1);
}
width = frame->image_width;
height = frame->image_height;
inPix = new pixel_t[width*height];
outPix = new pixel_t[width*height];
convert_to_pixel(inPix, frame);
float* inFloats = new float[width*height];
float* outFloats2 = new float[width*height];
for (int i=0; i<width*height; i++){
outPix[i].r = 0;
outPix[i].g = 0;
outPix[i].b = 0;
outFloats2[i] = 0;
inFloats[i] = (inPix[i].r + inPix[i].g + inPix[i].b)/3;
}
float* kernel = kernels[kernel_num];
double t0, t1;
if(color == 1){
cuda_function(width, height, kernel, inPix, outPix, &t0, &t1);
} else {
cuda_function2(width, height, kernel, inFloats, outFloats2, &t0, &t1);
}
printf("%g sec\n", t1-t0);
if(color == 0) {
for (int i=0; i<width*height; i++){
outPix[i].r = outFloats2[i];
outPix[i].g = outFloats2[i];
outPix[i].b = outFloats2[i];
}
}
convert_to_frame(frame, outPix);
write_JPEG_file(outName,frame,75);
destroy_frame(frame);
delete [] inPix;
delete [] outPix;
return 0;
}
<commit_msg>Time stamps<commit_after>#include <cstdlib>
#include <cstdio>
#include <cstring>
#include <string>
#include <algorithm>
#include <unistd.h>
#include <sys/time.h>
#include <time.h>
#include "readjpeg.h"
typedef struct
{
float r;
float g;
float b;
} pixel_t;
void cuda_function(int data_size_X, int data_size_Y, float* kernel, pixel_t* in, pixel_t* out, double* t0, double* t1);
void cuda_function2(int data_size_X, int data_size_Y, float* kernel, float* in, float* out, double* t0, double* t1);
void normalize( float * kernel ) {
int sum = 0;
for (int i = 0; i < 25; i++ ) {
sum += kernel[i];
}
for (int i = 0; i < 25 && sum != 0; i++ ) {
kernel[i] /= sum;
}
}
void print_matrix(float *array, int num, int x_size){
int a = 0;
printf("%5.2f, ", array[a]);
for (a = 1; a < num; a++){
if (a%x_size == x_size-1){
printf("%5.2f,\n", array[a]);
} else{
printf("%5.2f, ", array[a]);
}
}
printf("\n");
}
void convert_to_pixel(pixel_t *out, frame_ptr in)
{
for(int y = 0; y < in->image_height; y++)
{
for(int x = 0; x < in->image_width; x++)
{
int r = (int)in->row_pointers[y][in->num_components*x + 0 ];
int g = (int)in->row_pointers[y][in->num_components*x + 1 ];
int b = (int)in->row_pointers[y][in->num_components*x + 2 ];
out[y*in->image_width+x].r = (float)r;
out[y*in->image_width+x].g = (float)g;
out[y*in->image_width+x].b = (float)b;
}
}
}
void convert_to_frame(frame_ptr out, pixel_t *in)
{
for(int y = 0; y < out->image_height; y++)
{
for(int x = 0; x < out->image_width; x++)
{
int r = (int)in[y*out->image_width + x].r;
int g = (int)in[y*out->image_width + x].g;
int b = (int)in[y*out->image_width + x].b;
out->row_pointers[y][out->num_components*x + 0 ] = r;
out->row_pointers[y][out->num_components*x + 1 ] = g;
out->row_pointers[y][out->num_components*x + 2 ] = b;
}
}
}
#define KERNX 5 //this is the x-size of the kernel. It will always be odd.
#define KERNY 5 //this is the y-size of the kernel. It will always be odd.
int main(int argc, char *argv[]){
double program_start = timestamp();
float kernel_0[] = { 0, 0, 0, 0, 0, // "sharpen"
0, 0,-1, 0, 0,
0,-1, 5,-1, 0,
0, 0,-1, 0, 0,
0, 0, 0, 0, 0, }; normalize(kernel_0);
float kernel_1[]={ 1, 1, 1, 1, 1, // blur
1, 1, 1, 1, 1,
1, 1, 1, 1, 1,
1, 1, 1, 1, 1,
1, 1, 1, 1, 1, }; normalize(kernel_1);
float kernel_2[] = { 1, 1, 1, 1, 1, // weighted median filter
2, 2, 2, 2, 2,
3, 3, 3, 3, 3,
2, 2, 2, 2, 2,
1, 1, 1, 1, 1, };
float kernel_3[]={1,1,1,1,1, // weighted mean filter
1,2,2,2,1,
1,2,3,2,1,
1,2,2,2,1,
1,1,1,1,1, }; normalize(kernel_3);
float kernel_4[] = { 1, 4, 7, 4, 1, // gaussian
4,16,26,16, 4,
7,26,41,26, 7,
4,16,26,16, 4,
1, 4, 7, 4, 1, };
float kernel_5[] = { 0, 0, 0, 0, 0, // "emboss"
0,-2,-1, 0, 0,
0,-1, 1, 1, 0,
0, 0, 1, 2, 0,
0, 0, 0, 0, 0, };
float kernel_6[] = {-1,-1,-1,-1,-1, // "edge detect"
-1,-1,-1,-1,-1,
-1,-1,24,-1,-1,
-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1, };
float* kernels[7] = {kernel_0, kernel_1, kernel_2, kernel_3, kernel_4,
kernel_5, kernel_6};
int c;
int color = 0;
char *inName = NULL;
char *outName = NULL;
int width = -1, height = -1;
int kernel_num = 1;
frame_ptr frame;
pixel_t *inPix = NULL;
pixel_t *outPix = NULL;
//grab command line arguments
while((c = getopt(argc, argv, "i:k:o:c"))!=-1)
{
switch(c)
{
case 'i':
inName = optarg;
break;
case 'o':
outName = optarg;
break;
case 'k':
kernel_num = atoi(optarg);
break;
case 'c':
color = 1;
}
}
//input file name and output names
inName = inName==0 ? (char*)"cpt-kurt.jpg" : inName;
outName = outName==0 ? (char*)"output.jpg" : outName;
//read file
frame = read_JPEG_file(inName);
if(!frame){
printf("unable to read %s\n", inName);
exit(-1);
}
width = frame->image_width;
height = frame->image_height;
inPix = new pixel_t[width*height];
outPix = new pixel_t[width*height];
convert_to_pixel(inPix, frame);
float* inFloats = new float[width*height];
float* outFloats2 = new float[width*height];
for (int i=0; i<width*height; i++){
outPix[i].r = 0;
outPix[i].g = 0;
outPix[i].b = 0;
outFloats2[i] = 0;
inFloats[i] = (inPix[i].r + inPix[i].g + inPix[i].b)/3;
}
float* kernel = kernels[kernel_num];
double t0, t1;
double thing1, thing2;
if(color == 1){
thing1 = timestamp();
cuda_function(width, height, kernel, inPix, outPix, &t0, &t1);
thing2 = timestamp();
} else {
thing1 = timestamp();
cuda_function2(width, height, kernel, inFloats, outFloats2, &t0, &t1);
thing2 = timestamp();
}
printf("%g sec whole function\n", thing2 - thing1);
printf("%g sec kernel\n", t1-t0);
if(color == 0) {
for (int i=0; i<width*height; i++){
outPix[i].r = outFloats2[i];
outPix[i].g = outFloats2[i];
outPix[i].b = outFloats2[i];
}
}
convert_to_frame(frame, outPix);
write_JPEG_file(outName,frame,75);
destroy_frame(frame);
delete [] inPix;
delete [] outPix;
double program_end = timestamp();
printf("%g sec main function\n", program_end - program_start);
return 0;
}
<|endoftext|> |
<commit_before>#include "pathresolver.h"
#include <QDebug>
#include <QFile>
#include <QResource>
PathResolver::PathResolver(QObject *parent) : QObject(parent)
{
}
QString PathResolver::iconPath(const QString &iconName) const
{
#ifdef Q_OS_LINUX
QString possiblePath = "qrc:/linux/images/linux/" + iconName + ".%1";
return possiblePath.arg("png");
#else
return "";
#endif
}
<commit_msg>Minor change.<commit_after>#include "pathresolver.h"
#include <QDebug>
#include <QFile>
#include <QResource>
PathResolver::PathResolver(QObject *parent) : QObject(parent)
{
}
QString PathResolver::iconPath(const QString &iconName) const
{
#ifdef Q_OS_ANDROID
return "";
#endif
#ifdef Q_OS_LINUX
QString possiblePath = "qrc:/linux/images/linux/" + iconName + ".%1";
return possiblePath.arg("png");
#else
return "";
#endif
}
<|endoftext|> |
<commit_before>// Base header file. Must be first.
#include <Include/PlatformDefinitions.hpp>
#include <cassert>
#include <fstream>
#include <iostream>
#include <strstream>
#include <util/PlatformUtils.hpp>
#include <PlatformSupport/DOMStringHelper.hpp>
#include <DOMSupport/DOMSupportDefault.hpp>
#include <XPath/XObjectFactoryDefault.hpp>
#include <XPath/XPathSupportDefault.hpp>
#include <XPath/XPathFactoryDefault.hpp>
#include <XSLT/StylesheetConstructionContextDefault.hpp>
#include <XSLT/StylesheetExecutionContextDefault.hpp>
#include <XSLT/StylesheetRoot.hpp>
#include <XSLT/XSLTEngineImpl.hpp>
#include <XSLT/XSLTInit.hpp>
#include <XSLT/XSLTInputSource.hpp>
#include <XSLT/XSLTProcessorEnvSupportDefault.hpp>
#include <XSLT/XSLTResultTarget.hpp>
#include <XercesParserLiaison/XercesParserLiaison.hpp>
#include <XercesPlatformSupport/TextFileOutputStream.hpp>
#include <XercesPlatformSupport/XercesDOMPrintWriter.hpp>
int
main(
int argc,
const char* /* argv */[])
{
#if !defined(XALAN_NO_NAMESPACES)
using std::cerr;
using std::endl;
using std::ifstream;
using std::ostrstream;
using std::string;
#endif
if (argc != 1)
{
cerr << "Usage: CompileStylesheet"
<< endl
<< endl;
}
else
{
try
{
// Call the static initializer for Xerces...
XMLPlatformUtils::Initialize();
{
// Initialize the Xalan XSLT subsystem...
XSLTInit theInit;
// Create the support objects that are necessary for running the processor...
DOMSupportDefault theDOMSupport;
XercesParserLiaison theParserLiaison(theDOMSupport);
XPathSupportDefault theXPathSupport(theDOMSupport);
XSLTProcessorEnvSupportDefault theXSLTProcessorEnvSupport;
XObjectFactoryDefault theXObjectFactory;
XPathFactoryDefault theXPathFactory;
// Create a processor...
XSLTEngineImpl theProcessor(
theParserLiaison,
theXPathSupport,
theXSLTProcessorEnvSupport,
theXObjectFactory,
theXPathFactory);
// Connect the processor to the support object...
theXSLTProcessorEnvSupport.setProcessor(&theProcessor);
// Create separate factory support objects so the stylesheet's
// factory-created XPath instances are independent from the
// processor's.
XPathFactoryDefault theStylesheetXPathFactory;
// Create a stylesheet construction context, using the
// stylesheet's factory support objects.
StylesheetConstructionContextDefault theConstructionContext(
theProcessor,
theXSLTProcessorEnvSupport,
theStylesheetXPathFactory);
// The execution context uses the same factory support objects as
// the processor, since those objects have the same lifetime as
// other objects created as a result of the execution.
StylesheetExecutionContextDefault theExecutionContext(
theProcessor,
theXSLTProcessorEnvSupport,
theXPathSupport,
theXObjectFactory);
// Our input files. The assumption is that the executable will be run
// from same directory as the input files.
const XalanDOMString theXMLFileName("foo.xml");
const XalanDOMString theXSLFileName("foo.xsl");
// Our stylesheet input source...
XSLTInputSource theStylesheetSource(c_wstr(theXSLFileName));
// Ask the processor to create a StylesheetRoot for the specified
// input XSL. This is the compiled stylesheet. We don't have to
// delete it, since it is owned by the StylesheetConstructionContext
// instance.
StylesheetRoot* const theStylesheetRoot =
theProcessor.processStylesheet(
theStylesheetSource,
theConstructionContext);
assert(theStylesheetRoot != 0);
for (unsigned int i = 0; i < 10; i++)
{
theExecutionContext.setStylesheetRoot(theStylesheetRoot);
// Buffers passed in to ostrstream.
char inBuffer[10];
char outBuffer[10];
// Generate the input and output file names.
ostrstream theFormatterIn(inBuffer, sizeof(inBuffer));
ostrstream theFormatterOut(outBuffer, sizeof(outBuffer));
theFormatterIn << "foo" << i + 1 << ".xml" << '\0';
theFormatterOut << "foo" << i + 1 << ".out" << '\0';
//Generate the XML input and output objects.
XSLTInputSource theInputSource(theFormatterIn.str());
XSLTResultTarget theResultTarget(theFormatterOut.str());
// Do the tranformation...
theProcessor.process(
theInputSource,
theResultTarget,
theExecutionContext);
// Reset the processor and the execution context
// so we can perform the next transformation.
// Reset the parser liaison to clear out the
// source document we just transformed.
theProcessor.reset();
theExecutionContext.reset();
theParserLiaison.reset();
}
}
// Call the static terminator for Xerces...
XMLPlatformUtils::Terminate();
}
catch(...)
{
cerr << "Exception caught!!!"
<< endl
<< endl;
}
}
return 0;
}
<commit_msg>No longer using string class...<commit_after>// Base header file. Must be first.
#include <Include/PlatformDefinitions.hpp>
#include <cassert>
#include <fstream>
#include <iostream>
#include <strstream>
#include <util/PlatformUtils.hpp>
#include <PlatformSupport/DOMStringHelper.hpp>
#include <DOMSupport/DOMSupportDefault.hpp>
#include <XPath/XObjectFactoryDefault.hpp>
#include <XPath/XPathSupportDefault.hpp>
#include <XPath/XPathFactoryDefault.hpp>
#include <XSLT/StylesheetConstructionContextDefault.hpp>
#include <XSLT/StylesheetExecutionContextDefault.hpp>
#include <XSLT/StylesheetRoot.hpp>
#include <XSLT/XSLTEngineImpl.hpp>
#include <XSLT/XSLTInit.hpp>
#include <XSLT/XSLTInputSource.hpp>
#include <XSLT/XSLTProcessorEnvSupportDefault.hpp>
#include <XSLT/XSLTResultTarget.hpp>
#include <XercesParserLiaison/XercesParserLiaison.hpp>
#include <XercesPlatformSupport/TextFileOutputStream.hpp>
#include <XercesPlatformSupport/XercesDOMPrintWriter.hpp>
int
main(
int argc,
const char* /* argv */[])
{
#if !defined(XALAN_NO_NAMESPACES)
using std::cerr;
using std::endl;
using std::ifstream;
using std::ostrstream;
#endif
if (argc != 1)
{
cerr << "Usage: CompileStylesheet"
<< endl
<< endl;
}
else
{
try
{
// Call the static initializer for Xerces...
XMLPlatformUtils::Initialize();
{
// Initialize the Xalan XSLT subsystem...
XSLTInit theInit;
// Create the support objects that are necessary for running the processor...
DOMSupportDefault theDOMSupport;
XercesParserLiaison theParserLiaison(theDOMSupport);
XPathSupportDefault theXPathSupport(theDOMSupport);
XSLTProcessorEnvSupportDefault theXSLTProcessorEnvSupport;
XObjectFactoryDefault theXObjectFactory;
XPathFactoryDefault theXPathFactory;
// Create a processor...
XSLTEngineImpl theProcessor(
theParserLiaison,
theXPathSupport,
theXSLTProcessorEnvSupport,
theXObjectFactory,
theXPathFactory);
// Connect the processor to the support object...
theXSLTProcessorEnvSupport.setProcessor(&theProcessor);
// Create separate factory support objects so the stylesheet's
// factory-created XPath instances are independent from the
// processor's.
XPathFactoryDefault theStylesheetXPathFactory;
// Create a stylesheet construction context, using the
// stylesheet's factory support objects.
StylesheetConstructionContextDefault theConstructionContext(
theProcessor,
theXSLTProcessorEnvSupport,
theStylesheetXPathFactory);
// The execution context uses the same factory support objects as
// the processor, since those objects have the same lifetime as
// other objects created as a result of the execution.
StylesheetExecutionContextDefault theExecutionContext(
theProcessor,
theXSLTProcessorEnvSupport,
theXPathSupport,
theXObjectFactory);
// Our input files. The assumption is that the executable will be run
// from same directory as the input files.
const XalanDOMString theXMLFileName("foo.xml");
const XalanDOMString theXSLFileName("foo.xsl");
// Our stylesheet input source...
XSLTInputSource theStylesheetSource(c_wstr(theXSLFileName));
// Ask the processor to create a StylesheetRoot for the specified
// input XSL. This is the compiled stylesheet. We don't have to
// delete it, since it is owned by the StylesheetConstructionContext
// instance.
StylesheetRoot* const theStylesheetRoot =
theProcessor.processStylesheet(
theStylesheetSource,
theConstructionContext);
assert(theStylesheetRoot != 0);
for (unsigned int i = 0; i < 10; i++)
{
theExecutionContext.setStylesheetRoot(theStylesheetRoot);
// Buffers passed in to ostrstream.
char inBuffer[10];
char outBuffer[10];
// Generate the input and output file names.
ostrstream theFormatterIn(inBuffer, sizeof(inBuffer));
ostrstream theFormatterOut(outBuffer, sizeof(outBuffer));
theFormatterIn << "foo" << i + 1 << ".xml" << '\0';
theFormatterOut << "foo" << i + 1 << ".out" << '\0';
//Generate the XML input and output objects.
XSLTInputSource theInputSource(theFormatterIn.str());
XSLTResultTarget theResultTarget(theFormatterOut.str());
// Do the tranformation...
theProcessor.process(
theInputSource,
theResultTarget,
theExecutionContext);
// Reset the processor and the execution context
// so we can perform the next transformation.
// Reset the parser liaison to clear out the
// source document we just transformed.
theProcessor.reset();
theExecutionContext.reset();
theParserLiaison.reset();
}
}
// Call the static terminator for Xerces...
XMLPlatformUtils::Terminate();
}
catch(...)
{
cerr << "Exception caught!!!"
<< endl
<< endl;
}
}
return 0;
}
<|endoftext|> |
<commit_before>#include <cstdlib>
#include <ctime>
#include <iostream>
#include <vector>
#include <fstream>
#include "SuMo.h"
#include "Timer.h"
using namespace std;
/* subtract pedestal values on-line */
static bool PED_SUBTRCT = false;
static int LIMIT_READOUT_RATE = 6000; //usecs limit between event polling
static int NUM_SEQ_TIMEOUTS = 100; // number of sequential timeouts before ending run
const float MAX_INT_TIMER = 800.; // max cpu timer before ending run (secs)
/* note: usb timeout defined in include/stdUSB.h */
bool overwriteExistingFile = false;
int SuMo::log_data(unsigned int NUM_READS, int trig_mode, int acq_rate, const char *log_filename) {
int check_event;
int asic_baseline[psecSampleCells];
int count = 0;
int psec_cnt = 0;
int last_k;
float _now_, t = 0.;
Timer timer = Timer();
time_t now;
unsigned short sample;
int *Meta;
char logDataFilename[300];
char logMetaFilename[300];
char logPedFilename[300];
char delim = ' ';
// 'scalar' mode
ofstream rate_fs;
if (trig_mode == 2) {
char logRateFilename[300];
sprintf(logRateFilename, "%s.rate", log_filename);
rate_fs.open(logRateFilename, ios::trunc);
}
sprintf(logDataFilename, "%s.acdc", log_filename);
sprintf(logMetaFilename, "%s.meta", log_filename);
sprintf(logPedFilename, "%s.ped", log_filename);
// check if file exists, inquire whether to overwrite
string temp;
while (fileExists(logDataFilename)) {
cout << "file already exists, try new filename: (or enter to overwrite / ctrl-C to quit): ";
getline(cin, temp);
if (temp.empty()) break;
sprintf(logDataFilename, "%s.acdc", temp.c_str());
sprintf(logMetaFilename, "%s.meta", temp.c_str());
sprintf(logPedFilename, "%s.ped", temp.c_str());
}
/* open up file stream */
ofstream dataofs, pedofs, metaofs;
dataofs.open(logDataFilename, ios::trunc);
/* wraparound_correction, if desired: */
int baseline[psecSampleCells];
unwrap_baseline(baseline, 2);
for (int j = 0; j < psecSampleCells; j++) {
asic_baseline[j] = baseline[j];
}
/* Create header */
dataofs << "Event" << delim << "Board" << delim << "Ch";
for (int i = 0; i < psecSampleCells; i++) {
dataofs << delim << "C" << i;
}
dataofs << endl;
pedofs.open(logPedFilename, ios::trunc);
// Create Header
pedofs << "Board" << delim << "Ch";
for (int i = 0; i < psecSampleCells; i++) {
pedofs << delim << "C" << i;
}
pedofs << endl;
/* Print out pedestal data */
for (int board = 0; board < numFrontBoards; board++) {
// Skip inactive boards
if (!DC_ACTIVE[board]) continue;
for (int channel = 0; channel < AC_CHANNELS; channel++) {
pedofs << board << delim << channel + 1;
for (int i = 0; i < psecSampleCells; i++) {
pedofs << delim << PED_DATA[board][channel][i];
}
pedofs << endl;
}
}
pedofs.close();
metaofs.open(logMetaFilename, ios::trunc);
// Create header
metaofs << "Event" << delim << "Board" << delim;
metaofs << "count" << delim << "aa" << delim << "time" << delim << "datetime" << delim
<< "events" << delim << "bin_count_rise" << delim << "self_trig_settings_2" << delim
<< "sys_coincidence_width" << delim << "coincidence_num_chips" << delim
<< "coincidence_num_chans" << delim << "self_trig_settings" << delim
<< "trig_en" << delim << "trig_wait_for_sys" << delim << "trig_rate_only" << delim
<< "trig_sign" << delim << "use_sma_trig_input" << delim
<< "use_coincidence_settings" << delim << "use_trig_valid_as_reset" << delim
<< "coinc_window" << delim << "reg_self_trig" << delim
<< "counts_of_sys_no_local" << delim << "sys_trig_count" << delim
<< "resets_from_firmw" << delim << "firmware_version" << delim
<< "self_trig_mask" << delim << "dig_timestamp_lo" << delim
<< "dig_timestamp_mid" << delim << "dig_timestamp_hi" << delim
<< "dig_event_count" << delim << "event_count" << delim
<< "timestamp_hi" << delim << "timestamp_mid" << delim
<< "timestamp_lo" << delim << "CC_BIN_COUNT" << delim
<< "CC_EVENT_COUNT" << delim << "CC_TIMESTAMP_LO" << delim
<< "CC_TIMESTAMP_MID" << delim << "CC_TIMESTAMP_HI" << delim;
for (int n = 0; n < 5; n++) metaofs << "ro_cnt_chip_" << n << delim;
for (int n = 0; n < 5; n++) metaofs << "ro_target_cnt_chip_" << n << delim;
for (int n = 0; n < 5; n++) metaofs << "vbias_chip_" << n << delim;
for (int n = 0; n < 5; n++) metaofs << "trigger_threshold_chip_" << n << delim;
for (int n = 0; n < 5; n++) metaofs << "ro_dac_value_chip_" << n << delim;
for (int n = 1; n <= AC_CHANNELS; n++) metaofs << "self_trig_scalar_ch_" << n << delim;
metaofs << "time_from_valid_to_trig" << delim << "firmware_reset_time" << delim
<< "last_coincidence_num_chans" << endl;
// read all front end cards
bool all[numFrontBoards];
for (int i = 0; i < numFrontBoards; i++) all[i] = true;
load_ped();
int number_of_frontend_cards = 0;
for (int board = 0; board < numFrontBoards; board++) {
if (DC_ACTIVE[board]) number_of_frontend_cards++;
}
cout << "--------------------------------------------------------------" << endl;
cout << "number of front-end boards detected = " << number_of_frontend_cards
<< " of " << numFrontBoards << " address slots in system" << endl;
cout << "Trying for " << NUM_READS << " events logged to disk, in a timeout window of "
<< MAX_INT_TIMER << " seconds" << endl;
cout << "--------------------------------------------------------------" << endl << endl;
usleep(100000);
bool reset_event = true;
// set read mode to NULL
set_usb_read_mode(0);
if (mode == USB2x) set_usb_read_mode_slaveDevice(0);
system_card_trig_valid(false);
if (mode == USB2x) system_slave_card_trig_valid(false);
//check system trigger number
read_CC(false, false, 100);
int board_trigger = CC_EVENT_COUNT_FROMCC0;
int last_board_trigger = board_trigger;
/* cpu time zero */
timer.start();
for (int event = 0; event < NUM_READS; event++) {
set_usb_read_mode(0);
if (mode == USB2x) set_usb_read_mode_slaveDevice(0);
time(&now);
t = timer.stop();
// interrupt if past specified logging time
if (t > MAX_INT_TIMER) {
cout << endl << "readout timed out at " << t << "on event " << event << endl;
break;
}
// trig_mode = 1 is external source or PSEC4 self trigger
// trig_mode = 0 is over software (USB), i.e. calibration logging
if (trig_mode == 0) {
manage_cc_fifo(1);
if (mode == USB2x) manage_cc_fifo_slaveDevice(1);
// 'rate-only' mode, only pull data every second
if (trig_mode == 2) usleep(3e6);
prep_sync();
if (mode == USB2x) software_trigger_slaveDevice((unsigned int) 15);
software_trigger((unsigned int) 15);
make_sync();
//acq rate limit
usleep(LIMIT_READOUT_RATE); // somewhat arbitrary hard-coded rate limitation
//system_card_trig_valid(false);
//if(mode == USB2x) system_slave_card_trig_valid(false);
} else {
manage_cc_fifo(1);
if (mode == USB2x) manage_cc_fifo_slaveDevice(1);
usleep(100);
for (int iii = 0; iii < 2; iii++) {
system_card_trig_valid(false);
if (mode == USB2x) system_slave_card_trig_valid(false);
}
//send in trig 'valid' signal
sys_wait(100);
prep_sync();
if (mode == USB2x) system_slave_card_trig_valid(true);
system_card_trig_valid(true);
make_sync();
//}
//acq rate limit
usleep(acq_rate + LIMIT_READOUT_RATE);
}
int num_pulls = 0;
int evts = 0;
int digs = 0;
while (board_trigger == last_board_trigger && t < MAX_INT_TIMER) {
read_CC(false, false, 100);
board_trigger = CC_EVENT_COUNT_FROMCC0;
cout << "waiting for trigger... on system event: "
<< board_trigger << " & readout attempt " << event
<< " @time " << t << " \r";
cout.flush();
usleep(1000);
t = timer.stop();
num_pulls++;
if (num_pulls > 100) break;
//if(num_pulls > 10) break; //use this is board trigger does not iterate
}
last_board_trigger = board_trigger;
if (mode == USB2x) system_slave_card_trig_valid(false);
system_card_trig_valid(false);
//set_usb_read_mode_slaveDevice(0), set_usb_read_mode(0);
evts = read_CC(false, false, 0);
for (int chkdig = 0; chkdig < numFrontBoards; chkdig++)
digs += DIGITIZING_START_FLAG[chkdig];
if (evts == 0 || evts != digs) {
print_to_terminal(event, NUM_READS, CC_EVENT_COUNT_FROMCC0, board_trigger, t);
cout << " --NULL-- " << endl;
reset_event = true;
event = event - 1; //repeat event
continue;
}
// show event number at terminal
else {
if ((event + 1) % 1 == 0 || event == 0) {
print_to_terminal(event, NUM_READS, CC_EVENT_COUNT_FROMCC0, board_trigger, t);
cout << " \r";
cout.flush();
}
}
/**************************************/
//Do bulk read on all front-end cards
int numBoards = read_AC(1, all, false);
/**************************************/
sys_wait(10000);
for (int jj = 0; jj < 2; jj++) {
//prep_sync();
//turn off 'trig valid flag' until checking if data in buffer
if (mode == USB2x) system_slave_card_trig_valid(false);
system_card_trig_valid(false);
if (mode == USB2x) set_usb_read_mode_slaveDevice(0);
set_usb_read_mode(0);
}
reset_event = true; //have event, go ahead and reset for next event
// form data for filesave
for (int board = 0; board < numFrontBoards; board++) {
if (BOARDS_READOUT[board] && numBoards > 0) {
psec_cnt = 0;
// assign meta data
Meta = get_AC_info(false, board, false, event, t, t, evts);
for (int ch = 0; ch < AC_CHANNELS; ch++) {
dataofs << event << delim << board << delim << ch + 1;
metaofs << event << delim << board;
if (ch > 0 && ch % 6 == 0) psec_cnt++;
for (int cell = 0; cell < psecSampleCells; cell++) {
sample = adcDat[board]->AC_RAW_DATA[psec_cnt][ch % 6 * 256 + cell];
int ped_subtracted = sample - PED_DATA[board][ch][cell];
dataofs << delim << dec << ped_subtracted; // std::dec
metaofs << delim << adcDat[board]->Meta[cell];
adcDat[board]->Data[ch][cell] = (unsigned int) sample;
}
dataofs << endl;
metaofs << endl;
}
/* wraparound_correction, if desired: */
int baseline[psecSampleCells];
unwrap_baseline(baseline, 2);
for (int j = 0; j < psecSampleCells; j++) {
asic_baseline[j] = baseline[j];
adcDat[board]->Meta[j] = Meta[j];
}
}
// if timeout on only some, but not all boards
else if (numBoards > 0 && BOARDS_TIMEOUT[board] && DC_ACTIVE[board]) {
for (int i = 0; i < AC_CHANNELS; i++) {
if (i > 0 && i % 6 == 0) psec_cnt++;
for (int j = 0; j < psecSampleCells; j++) {
sample = 0xFF;
adcDat[board]->Data[i][j] = sample;
}
}
}
}
last_k = event;
// LOGGING
}
cout << endl;
cout << "Done on readout: " << last_k + 1 << " :: @time " << t << " sec" << endl;
cleanup();
dump_data();
if (trig_mode == 2) rate_fs.close();
cout << "Data saved in file: " << logDataFilename << endl << "*****" << endl;
dataofs.close();
pedofs.close();
metaofs.close();
return 0;
}
void SuMo::print_to_terminal(int k, int NUM_READS, int cc_event, int board_trig, double t) {
cout << "Readout: " << k + 1 << " of " << NUM_READS;
cout << " :: system|sw evt-" << cc_event << "|" << board_trig;
cout << " :: evtflags-";
for (int evt_flag = 0; evt_flag < numFrontBoards; evt_flag++) cout << EVENT_FLAG[evt_flag];
cout << " :: digflags-";
for (int dig_flag = 0; dig_flag < numFrontBoards; dig_flag++) cout << DIGITIZING_START_FLAG[dig_flag];
cout << " :: @time " << t << " sec ";
//cout.flush();
}
<commit_msg>small output rewrite<commit_after>#include <cstdlib>
#include <ctime>
#include <iostream>
#include <vector>
#include <fstream>
#include "SuMo.h"
#include "Timer.h"
using namespace std;
/* subtract pedestal values on-line */
static bool PED_SUBTRCT = false;
static int LIMIT_READOUT_RATE = 6000; //usecs limit between event polling
static int NUM_SEQ_TIMEOUTS = 100; // number of sequential timeouts before ending run
const float MAX_INT_TIMER = 800.; // max cpu timer before ending run (secs)
/* note: usb timeout defined in include/stdUSB.h */
bool overwriteExistingFile = false;
int SuMo::log_data(unsigned int NUM_READS, int trig_mode, int acq_rate, const char *log_filename) {
int check_event;
int asic_baseline[psecSampleCells];
int count = 0;
int psec_cnt = 0;
int last_k;
float _now_, t = 0.;
Timer timer = Timer();
time_t now;
unsigned short sample;
int *Meta;
char logDataFilename[300];
char logMetaFilename[300];
char logPedFilename[300];
char delim = ' ';
// 'scalar' mode
ofstream rate_fs;
if (trig_mode == 2) {
char logRateFilename[300];
sprintf(logRateFilename, "%s.rate", log_filename);
rate_fs.open(logRateFilename, ios::trunc);
}
sprintf(logDataFilename, "%s.acdc", log_filename);
sprintf(logMetaFilename, "%s.meta", log_filename);
sprintf(logPedFilename, "%s.ped", log_filename);
// check if file exists, inquire whether to overwrite
string temp;
while (fileExists(logDataFilename)) {
cout << "file already exists, try new filename: (or enter to overwrite / ctrl-C to quit): ";
getline(cin, temp);
if (temp.empty()) break;
sprintf(logDataFilename, "%s.acdc", temp.c_str());
sprintf(logMetaFilename, "%s.meta", temp.c_str());
sprintf(logPedFilename, "%s.ped", temp.c_str());
}
/* open up file stream */
ofstream dataofs, pedofs, metaofs;
dataofs.open(logDataFilename, ios::trunc);
/* wraparound_correction, if desired: */
int baseline[psecSampleCells];
unwrap_baseline(baseline, 2);
for (int j = 0; j < psecSampleCells; j++) {
asic_baseline[j] = baseline[j];
}
/* Create header */
dataofs << "Event" << delim << "Board" << delim << "Ch";
for (int i = 0; i < psecSampleCells; i++) {
dataofs << delim << "C" << i;
}
dataofs << endl;
pedofs.open(logPedFilename, ios::trunc);
// Create Header
pedofs << "Board" << delim << "Ch";
for (int i = 0; i < psecSampleCells; i++) {
pedofs << delim << "C" << i;
}
pedofs << endl;
/* Print out pedestal data */
for (int board = 0; board < numFrontBoards; board++) {
// Skip inactive boards
if (!DC_ACTIVE[board]) continue;
for (int channel = 0; channel < AC_CHANNELS; channel++) {
pedofs << board << delim << channel + 1;
for (int i = 0; i < psecSampleCells; i++) {
pedofs << delim << PED_DATA[board][channel][i];
}
pedofs << endl;
}
}
pedofs.close();
metaofs.open(logMetaFilename, ios::trunc);
// Create header
metaofs << "Event" << delim << "Board" << delim;
metaofs << "count" << delim << "aa" << delim << "time" << delim << "datetime" << delim
<< "events" << delim << "bin_count_rise" << delim << "self_trig_settings_2" << delim
<< "sys_coincidence_width" << delim << "coincidence_num_chips" << delim
<< "coincidence_num_chans" << delim << "self_trig_settings" << delim
<< "trig_en" << delim << "trig_wait_for_sys" << delim << "trig_rate_only" << delim
<< "trig_sign" << delim << "use_sma_trig_input" << delim
<< "use_coincidence_settings" << delim << "use_trig_valid_as_reset" << delim
<< "coinc_window" << delim << "reg_self_trig" << delim
<< "counts_of_sys_no_local" << delim << "sys_trig_count" << delim
<< "resets_from_firmw" << delim << "firmware_version" << delim
<< "self_trig_mask" << delim << "dig_timestamp_lo" << delim
<< "dig_timestamp_mid" << delim << "dig_timestamp_hi" << delim
<< "dig_event_count" << delim << "event_count" << delim
<< "timestamp_hi" << delim << "timestamp_mid" << delim
<< "timestamp_lo" << delim << "CC_BIN_COUNT" << delim
<< "CC_EVENT_COUNT" << delim << "CC_TIMESTAMP_LO" << delim
<< "CC_TIMESTAMP_MID" << delim << "CC_TIMESTAMP_HI" << delim;
for (int n = 0; n < 5; n++) metaofs << "ro_cnt_chip_" << n << delim;
for (int n = 0; n < 5; n++) metaofs << "ro_target_cnt_chip_" << n << delim;
for (int n = 0; n < 5; n++) metaofs << "vbias_chip_" << n << delim;
for (int n = 0; n < 5; n++) metaofs << "trigger_threshold_chip_" << n << delim;
for (int n = 0; n < 5; n++) metaofs << "ro_dac_value_chip_" << n << delim;
for (int n = 1; n <= AC_CHANNELS; n++) metaofs << "self_trig_scalar_ch_" << n << delim;
metaofs << "time_from_valid_to_trig" << delim << "firmware_reset_time" << delim
<< "last_coincidence_num_chans" << endl;
// read all front end cards
bool all[numFrontBoards];
for (int i = 0; i < numFrontBoards; i++) all[i] = true;
load_ped();
int number_of_frontend_cards = 0;
for (int board = 0; board < numFrontBoards; board++) {
if (DC_ACTIVE[board]) number_of_frontend_cards++;
}
cout << "--------------------------------------------------------------" << endl;
cout << "number of front-end boards detected = " << number_of_frontend_cards
<< " of " << numFrontBoards << " address slots in system" << endl;
cout << "Trying for " << NUM_READS << " events logged to disk, in a timeout window of "
<< MAX_INT_TIMER << " seconds" << endl;
cout << "--------------------------------------------------------------" << endl << endl;
usleep(100000);
bool reset_event = true;
// set read mode to NULL
set_usb_read_mode(0);
if (mode == USB2x) set_usb_read_mode_slaveDevice(0);
system_card_trig_valid(false);
if (mode == USB2x) system_slave_card_trig_valid(false);
//check system trigger number
read_CC(false, false, 100);
int board_trigger = CC_EVENT_COUNT_FROMCC0;
int last_board_trigger = board_trigger;
/* cpu time zero */
timer.start();
for (int event = 0; event < NUM_READS; event++) {
set_usb_read_mode(0);
if (mode == USB2x) set_usb_read_mode_slaveDevice(0);
time(&now);
t = timer.stop();
// interrupt if past specified logging time
if (t > MAX_INT_TIMER) {
cout << endl << "readout timed out at " << t << "on event " << event << endl;
break;
}
// trig_mode = 1 is external source or PSEC4 self trigger
// trig_mode = 0 is over software (USB), i.e. calibration logging
if (trig_mode == 0) {
manage_cc_fifo(1);
if (mode == USB2x) manage_cc_fifo_slaveDevice(1);
// 'rate-only' mode, only pull data every second
if (trig_mode == 2) usleep(3e6);
prep_sync();
if (mode == USB2x) software_trigger_slaveDevice((unsigned int) 15);
software_trigger((unsigned int) 15);
make_sync();
//acq rate limit
usleep(LIMIT_READOUT_RATE); // somewhat arbitrary hard-coded rate limitation
//system_card_trig_valid(false);
//if(mode == USB2x) system_slave_card_trig_valid(false);
} else {
manage_cc_fifo(1);
if (mode == USB2x) manage_cc_fifo_slaveDevice(1);
usleep(100);
for (int iii = 0; iii < 2; iii++) {
system_card_trig_valid(false);
if (mode == USB2x) system_slave_card_trig_valid(false);
}
//send in trig 'valid' signal
sys_wait(100);
prep_sync();
if (mode == USB2x) system_slave_card_trig_valid(true);
system_card_trig_valid(true);
make_sync();
//}
//acq rate limit
usleep(acq_rate + LIMIT_READOUT_RATE);
}
int num_pulls = 0;
int evts = 0;
int digs = 0;
while (board_trigger == last_board_trigger && t < MAX_INT_TIMER) {
read_CC(false, false, 100);
board_trigger = CC_EVENT_COUNT_FROMCC0;
cout << "waiting for trigger... on system event: "
<< board_trigger << " & readout attempt " << event
<< " @time " << t << " \r";
cout.flush();
usleep(1000);
t = timer.stop();
num_pulls++;
if (num_pulls > 100) break;
//if(num_pulls > 10) break; //use this is board trigger does not iterate
}
last_board_trigger = board_trigger;
if (mode == USB2x) system_slave_card_trig_valid(false);
system_card_trig_valid(false);
//set_usb_read_mode_slaveDevice(0), set_usb_read_mode(0);
evts = read_CC(false, false, 0);
for (int chkdig = 0; chkdig < numFrontBoards; chkdig++)
digs += DIGITIZING_START_FLAG[chkdig];
if (evts == 0 || evts != digs) {
cout << " --NULL-- " << endl;
reset_event = true;
event = event - 1; //repeat event
continue;
}
// show event number at terminal
else {
if ((event + 1) % 1 == 0 || event == 0) {
print_to_terminal(event, NUM_READS, CC_EVENT_COUNT_FROMCC0, board_trigger, t);
}
}
/**************************************/
//Do bulk read on all front-end cards
int numBoards = read_AC(1, all, false);
/**************************************/
sys_wait(10000);
for (int jj = 0; jj < 2; jj++) {
//prep_sync();
//turn off 'trig valid flag' until checking if data in buffer
if (mode == USB2x) system_slave_card_trig_valid(false);
system_card_trig_valid(false);
if (mode == USB2x) set_usb_read_mode_slaveDevice(0);
set_usb_read_mode(0);
}
reset_event = true; //have event, go ahead and reset for next event
// form data for filesave
for (int board = 0; board < numFrontBoards; board++) {
if (BOARDS_READOUT[board] && numBoards > 0) {
psec_cnt = 0;
// assign meta data
Meta = get_AC_info(false, board, false, event, t, t, evts);
for (int ch = 0; ch < AC_CHANNELS; ch++) {
dataofs << event << delim << board << delim << ch + 1;
metaofs << event << delim << board;
if (ch > 0 && ch % 6 == 0) psec_cnt++;
for (int cell = 0; cell < psecSampleCells; cell++) {
sample = adcDat[board]->AC_RAW_DATA[psec_cnt][ch % 6 * 256 + cell];
int ped_subtracted = sample - PED_DATA[board][ch][cell];
dataofs << delim << dec << ped_subtracted; // std::dec
metaofs << delim << adcDat[board]->Meta[cell];
adcDat[board]->Data[ch][cell] = (unsigned int) sample;
}
dataofs << endl;
metaofs << endl;
}
/* wraparound_correction, if desired: */
int baseline[psecSampleCells];
unwrap_baseline(baseline, 2);
for (int j = 0; j < psecSampleCells; j++) {
asic_baseline[j] = baseline[j];
adcDat[board]->Meta[j] = Meta[j];
}
}
// if timeout on only some, but not all boards
else if (numBoards > 0 && BOARDS_TIMEOUT[board] && DC_ACTIVE[board]) {
for (int i = 0; i < AC_CHANNELS; i++) {
if (i > 0 && i % 6 == 0) psec_cnt++;
for (int j = 0; j < psecSampleCells; j++) {
sample = 0xFF;
adcDat[board]->Data[i][j] = sample;
}
}
}
}
last_k = event;
// LOGGING
}
cout << endl;
cout << "Done on readout: " << last_k + 1 << " :: @time " << t << " sec" << endl;
cleanup();
dump_data();
if (trig_mode == 2) rate_fs.close();
cout << "Data saved in file: " << logDataFilename << endl << "*****" << endl;
dataofs.close();
pedofs.close();
metaofs.close();
return 0;
}
void SuMo::print_to_terminal(int k, int NUM_READS, int cc_event, int board_trig, double t) {
cout << "\r" << "Readout: " << k + 1 << " of " << NUM_READS;
cout << " :: system|sw evt-" << cc_event << "|" << board_trig;
cout << " :: evtflags-";
for (int evt_flag = 0; evt_flag < numFrontBoards; evt_flag++) cout << EVENT_FLAG[evt_flag];
cout << " :: digflags-";
for (int dig_flag = 0; dig_flag < numFrontBoards; dig_flag++) cout << DIGITIZING_START_FLAG[dig_flag];
cout << " :: @time " << t << " sec " << flush;
}
<|endoftext|> |
<commit_before>#include "maincontrol.h"
#include <QThread>
#include <QDebug>
quibe::MainControl::MainControl(QObject *parent) :
QObject(parent) {
velocidade = 50;
velocidade_counter = 0;
QObject::connect(&serial, SIGNAL(mensagemLida(QByteArray)),
this, SLOT(parse_message(QByteArray)));
}
void quibe::MainControl::comando_esquerda() {
serial.enviaComandoMovimento(ComunicacaoSerial::ESQUERDA, velocidade/10);
qDebug() << "Comando: Esquerda" << endl;
}
void quibe::MainControl::comando_direita() {
serial.enviaComandoMovimento(ComunicacaoSerial::DIREITA, velocidade/10);
qDebug() << "Comando: Direita" << endl;
}
void quibe::MainControl::comando_frente() {
serial.enviaComandoMovimento(ComunicacaoSerial::FRENTE, velocidade/10);
qDebug() << "Comando: Frente" << endl;
}
void quibe::MainControl::comando_tras() {
serial.enviaComandoMovimento(ComunicacaoSerial::TRAS, velocidade/10);
qDebug() << "Comando: Tras" << endl;
}
void quibe::MainControl::comando_subir() {
serial.enviaComandoMovimento(ComunicacaoSerial::SUBIR, velocidade/10);
velocidade_counter++;
//qDebug() << "Comando: Subir" << endl;
qDebug() << "Velocidade Atual: " << velocidade_counter;
}
void quibe::MainControl::comando_descer() {
serial.enviaComandoMovimento(ComunicacaoSerial::DESCER, velocidade/10);
velocidade_counter--;
//qDebug() << "Comando: Descer" << endl;
qDebug() << "Velocidade Atual: " << velocidade_counter;
}
void quibe::MainControl::comando_horario() {
serial.enviaComandoMovimento(ComunicacaoSerial::HORARIO, velocidade/10);
qDebug() << "Comando: Girar Sentido Horário" << endl;
}
void quibe::MainControl::comando_antihorario() {
serial.enviaComandoMovimento(ComunicacaoSerial::ANTIHORARIO, velocidade/10);
qDebug() << "Comando: Girar Sentido Anti-Horário" << endl;
}
void quibe::MainControl::comando_parar() {
serial.enviaComandoMovimento(ComunicacaoSerial::PARAR, velocidade/10);
qDebug() << "Comando: Parar" << endl;
}
void quibe::MainControl::conectar_serial(bool conectar, SerialConfig config) {
if (conectar) {
bool conectado = serial.conectar(config);
emit serial_conectado(conectado);
} else {
serial.desconectar();
emit serial_desconectado();
}
}
void quibe::MainControl::conectar_quadricoptero(bool conectar) {
if (conectar) {
serial.enviaHandshake();
}
else {
// Desconectar
}
}
void quibe::MainControl::comando_decolar_pousar(bool decolar) {
if (decolar) {
emit decolou();
} else emit pousou();
}
void quibe::MainControl::velocidade_alterada(int velocidade) {
this->velocidade = velocidade;
qDebug() << "Velocidade alterada para: " << velocidade << "\%" << endl;
}
void quibe::MainControl::parse_message(QByteArray mensagem) {
switch (mensagem[3]) {
case ComunicacaoSerial::DIAGNOSTIC:
qDebug() << "Recebeu mensagem de diagnóstico";
if (mensagem[4] & ComunicacaoSerial::READY) {
emit quadricoptero_conectado(true);
}
else {
QThread::currentThread()->sleep(1);
serial.enviaHandshake();
}
break;
case ComunicacaoSerial::SONAR_DATA:
qDebug() << "Recebeu dados do sonar";
uint sensor_cima, sensor_baixo, sensor_frente, sensor_tras, sensor_esquerda, sensor_direita;
sensor_cima = (((uint)mensagem[4]) << 8) + ((uint)mensagem[5]);
sensor_baixo = (((uint)mensagem[6]) << 8) + ((uint)mensagem[7]);
sensor_frente = (((uint)mensagem[8]) << 8) + ((uint)mensagem[9]);
sensor_tras = (((uint)mensagem[10] << 8)) + ((uint)mensagem[11]);
sensor_esquerda = (((uint)mensagem[12]) << 8) + ((uint)mensagem[13]);
sensor_direita = (((uint)mensagem[14]) << 8) + ((uint)mensagem[15]);
emit dados_sonar_recebidos(sensor_cima, sensor_baixo, sensor_frente,
sensor_tras, sensor_esquerda, sensor_direita);
break;
case ComunicacaoSerial::MPU6050_DATA:
int roll, pitch, yaw;
roll = (((int)mensagem[4]) << 8) + (((int)mensagem[5]) & 0xFF);
pitch = (((int)mensagem[6]) << 8) + (((int)mensagem[7]) & 0xFF);
yaw = (((int)mensagem[8]) << 8) + (((int)mensagem[9]) & 0xFF);
emit dados_angulo_recebidos(roll, pitch, yaw);
break;
default:
qDebug() << "ERRO! Recebida mensagem inesperada.";
qDebug() << "Data Dump da mensagem:";
for (int i = 0; i < 8; i++) {
qDebug() << mensagem.left(4).toHex();
mensagem.remove(0,4);
}
break;
}
}
<commit_msg>Adicionada divisão dos ângulos na estação base<commit_after>#include "maincontrol.h"
#include <QThread>
#include <QDebug>
quibe::MainControl::MainControl(QObject *parent) :
QObject(parent) {
velocidade = 50;
velocidade_counter = 0;
QObject::connect(&serial, SIGNAL(mensagemLida(QByteArray)),
this, SLOT(parse_message(QByteArray)));
}
void quibe::MainControl::comando_esquerda() {
serial.enviaComandoMovimento(ComunicacaoSerial::ESQUERDA, velocidade/10);
qDebug() << "Comando: Esquerda" << endl;
}
void quibe::MainControl::comando_direita() {
serial.enviaComandoMovimento(ComunicacaoSerial::DIREITA, velocidade/10);
qDebug() << "Comando: Direita" << endl;
}
void quibe::MainControl::comando_frente() {
serial.enviaComandoMovimento(ComunicacaoSerial::FRENTE, velocidade/10);
qDebug() << "Comando: Frente" << endl;
}
void quibe::MainControl::comando_tras() {
serial.enviaComandoMovimento(ComunicacaoSerial::TRAS, velocidade/10);
qDebug() << "Comando: Tras" << endl;
}
void quibe::MainControl::comando_subir() {
serial.enviaComandoMovimento(ComunicacaoSerial::SUBIR, velocidade/10);
velocidade_counter++;
//qDebug() << "Comando: Subir" << endl;
qDebug() << "Velocidade Atual: " << velocidade_counter;
}
void quibe::MainControl::comando_descer() {
serial.enviaComandoMovimento(ComunicacaoSerial::DESCER, velocidade/10);
velocidade_counter--;
//qDebug() << "Comando: Descer" << endl;
qDebug() << "Velocidade Atual: " << velocidade_counter;
}
void quibe::MainControl::comando_horario() {
serial.enviaComandoMovimento(ComunicacaoSerial::HORARIO, velocidade/10);
qDebug() << "Comando: Girar Sentido Horário" << endl;
}
void quibe::MainControl::comando_antihorario() {
serial.enviaComandoMovimento(ComunicacaoSerial::ANTIHORARIO, velocidade/10);
qDebug() << "Comando: Girar Sentido Anti-Horário" << endl;
}
void quibe::MainControl::comando_parar() {
serial.enviaComandoMovimento(ComunicacaoSerial::PARAR, velocidade/10);
qDebug() << "Comando: Parar" << endl;
}
void quibe::MainControl::conectar_serial(bool conectar, SerialConfig config) {
if (conectar) {
bool conectado = serial.conectar(config);
emit serial_conectado(conectado);
} else {
serial.desconectar();
emit serial_desconectado();
}
}
void quibe::MainControl::conectar_quadricoptero(bool conectar) {
if (conectar) {
serial.enviaHandshake();
}
else {
// Desconectar
}
}
void quibe::MainControl::comando_decolar_pousar(bool decolar) {
if (decolar) {
emit decolou();
} else emit pousou();
}
void quibe::MainControl::velocidade_alterada(int velocidade) {
this->velocidade = velocidade;
qDebug() << "Velocidade alterada para: " << velocidade << "\%" << endl;
}
void quibe::MainControl::parse_message(QByteArray mensagem) {
switch (mensagem[3]) {
case ComunicacaoSerial::DIAGNOSTIC:
qDebug() << "Recebeu mensagem de diagnóstico";
if (mensagem[4] & ComunicacaoSerial::READY) {
emit quadricoptero_conectado(true);
}
else {
QThread::currentThread()->sleep(1);
serial.enviaHandshake();
}
break;
case ComunicacaoSerial::SONAR_DATA:
qDebug() << "Recebeu dados do sonar";
uint sensor_cima, sensor_baixo, sensor_frente, sensor_tras, sensor_esquerda, sensor_direita;
sensor_cima = (((uint)mensagem[4]) << 8) + ((uint)mensagem[5]);
sensor_baixo = (((uint)mensagem[6]) << 8) + ((uint)mensagem[7]);
sensor_frente = (((uint)mensagem[8]) << 8) + ((uint)mensagem[9]);
sensor_tras = (((uint)mensagem[10] << 8)) + ((uint)mensagem[11]);
sensor_esquerda = (((uint)mensagem[12]) << 8) + ((uint)mensagem[13]);
sensor_direita = (((uint)mensagem[14]) << 8) + ((uint)mensagem[15]);
emit dados_sonar_recebidos(sensor_cima, sensor_baixo, sensor_frente,
sensor_tras, sensor_esquerda, sensor_direita);
break;
case ComunicacaoSerial::MPU6050_DATA:
int roll, pitch, yaw;
qDebug() << "Leitura do MPU recebido do micro: " << mensagem.toHex();
roll = (((int)mensagem[4]) << 8) + (((int)mensagem[5]) & 0xFF);
pitch = (((int)mensagem[6]) << 8) + (((int)mensagem[7]) & 0xFF);
yaw = (((int)mensagem[8]) << 8) + (((int)mensagem[9]) & 0xFF);
roll /= 60;
pitch /= 60;
yaw /= 60;
emit dados_angulo_recebidos(roll, pitch, yaw);
break;
default:
qDebug() << "ERRO! Recebida mensagem inesperada.";
qDebug() << "Data Dump da mensagem:";
for (int i = 0; i < 8; i++) {
qDebug() << mensagem.left(4).toHex();
mensagem.remove(0,4);
}
break;
}
}
<|endoftext|> |
<commit_before>#include <include/base/cef_logging.h>
#include <brick/cef_handler.h>
#include "edit_account_window.h"
extern char _binary_window_edit_account_glade_start;
extern char _binary_window_edit_account_glade_size;
namespace {
static void
on_save_button(GtkWidget *widget, EditAccountWindow *self) {
bool secure =
gtk_combo_box_get_active(self->window_objects_.protocol_chooser) == 0;
const gchar* domain =
gtk_entry_get_text(self->window_objects_.domain_entry);
const gchar* login =
gtk_entry_get_text(self->window_objects_.login_entry);
const gchar* password =
gtk_entry_get_text(GTK_ENTRY(self->window_objects_.password_entry));
CefRefPtr<Account> check_account(new Account);
check_account->Set(
secure,
domain,
login,
password
);
Account::AuthResult auth_result = check_account->Auth();
if (!auth_result.success) {
std::string body;
switch (auth_result.error_code) {
case Account::ERROR_CODE::HTTP:
body = "HTTP error: " + auth_result.http_error;
break;
case Account::ERROR_CODE::CAPTCHA:
body = "You have exceeded the maximum number of login attempts.\n"
"Please log in <b>browser</b> first";
break;
case Account::ERROR_CODE::OTP:
body = "Account used two-step authentication.\n"
"Please use <b>Application Password</b> for authorization";
break;
case Account::ERROR_CODE::AUTH:
body = "Authentication failed.";
break;
default:
body = "An unknown error occurred :(";
break;
}
GtkWidget *dialog = gtk_message_dialog_new_with_markup(
GTK_WINDOW(self->window_objects_.window),
GTK_DIALOG_DESTROY_WITH_PARENT,
GTK_MESSAGE_ERROR,
GTK_BUTTONS_CLOSE,
NULL
);
gtk_message_dialog_set_markup(GTK_MESSAGE_DIALOG(dialog),
body.c_str());
gtk_dialog_run(GTK_DIALOG(dialog));
gtk_widget_destroy(dialog);
return;
}
self->Save(
secure,
std::string(domain),
std::string(login),
check_account->GetPassword() // Server may update user password while login
);
}
static void
on_cancel_button(GtkWidget *widget, EditAccountWindow *self) {
self->Close();
}
} // namespace
void
EditAccountWindow::Init(CefRefPtr<Account> account, bool switch_on_save) {
GtkBuilder *builder = gtk_builder_new ();
GError* error = NULL;
if (!gtk_builder_add_from_string(builder, &_binary_window_edit_account_glade_start, (gsize)&_binary_window_edit_account_glade_size, &error))
{
LOG(WARNING) << "Failed to build account edditting window: " << error->message;
g_error_free (error);
}
window_objects_.account = account;
window_objects_.switch_on_save = switch_on_save;
window_handler_ = GTK_WIDGET(gtk_builder_get_object(builder, "edit_account_dialog"));
window_objects_.window = window_handler_;
window_objects_.protocol_chooser = GTK_COMBO_BOX(gtk_builder_get_object(builder, "protocol_selector"));
window_objects_.domain_entry = GTK_ENTRY(gtk_builder_get_object(builder, "domain_entry"));
window_objects_.login_entry = GTK_ENTRY(gtk_builder_get_object(builder, "login_entry"));
window_objects_.password_entry = GTK_ENTRY(gtk_builder_get_object(builder, "password_entry"));
g_signal_connect(gtk_builder_get_object(builder, "save_button"), "clicked", G_CALLBACK(on_save_button), this);
g_signal_connect(gtk_builder_get_object(builder, "cancel_button"), "clicked", G_CALLBACK(on_cancel_button), this);
g_object_unref(builder);
gtk_entry_set_text(
window_objects_.domain_entry,
account->GetDomain().c_str()
);
gtk_entry_set_text(
window_objects_.login_entry,
account->GetLogin().c_str()
);
gtk_entry_set_text(
window_objects_.password_entry,
account->GetPassword().c_str()
);
gtk_combo_box_set_active(
window_objects_.protocol_chooser,
account->IsSecure()? 0: 1
);
}
<commit_msg>Проверяем не пусты ли домен/логин/пароль перед сохранением.<commit_after>#include <include/base/cef_logging.h>
#include <brick/cef_handler.h>
#include <et/com_err.h>
#include "edit_account_window.h"
extern char _binary_window_edit_account_glade_start;
extern char _binary_window_edit_account_glade_size;
namespace {
static void
on_save_button(GtkWidget *widget, EditAccountWindow *self) {
bool secure =
gtk_combo_box_get_active(self->window_objects_.protocol_chooser) == 0;
const gchar* domain =
gtk_entry_get_text(self->window_objects_.domain_entry);
const gchar* login =
gtk_entry_get_text(self->window_objects_.login_entry);
const gchar* password =
gtk_entry_get_text(GTK_ENTRY(self->window_objects_.password_entry));
CefRefPtr<Account> check_account(new Account);
bool show_error = false;
std::string error_message;
if (!strlen(domain)) {
show_error = true;
error_message = "Empty domain";
} else if (!strlen(login)) {
show_error = true;
error_message = "Empty login";
} else if (!strlen(password)) {
show_error = true;
error_message = "Empty password";
}
if (!show_error) {
check_account->Set(
secure,
domain,
login,
password
);
Account::AuthResult auth_result = check_account->Auth();
if (!auth_result.success) {
show_error = true;
switch (auth_result.error_code) {
case Account::ERROR_CODE::HTTP:
error_message = "HTTP error: " + auth_result.http_error;
break;
case Account::ERROR_CODE::CAPTCHA:
error_message = "You have exceeded the maximum number of login attempts.\n"
"Please log in <b>browser</b> first";
break;
case Account::ERROR_CODE::OTP:
error_message = "Account used two-step authentication.\n"
"Please use <b>Application Password</b> for authorization";
break;
case Account::ERROR_CODE::AUTH:
error_message = "Authentication failed.";
break;
default:
error_message = "An unknown error occurred :(";
break;
}
}
}
if (show_error) {
GtkWidget *dialog = gtk_message_dialog_new_with_markup(
GTK_WINDOW(self->window_objects_.window),
GTK_DIALOG_DESTROY_WITH_PARENT,
GTK_MESSAGE_ERROR,
GTK_BUTTONS_CLOSE,
NULL
);
gtk_message_dialog_set_markup(GTK_MESSAGE_DIALOG(dialog),
error_message.c_str());
gtk_dialog_run(GTK_DIALOG(dialog));
gtk_widget_destroy(dialog);
return;
}
self->Save(
secure,
std::string(domain),
std::string(login),
check_account->GetPassword() // Server may update user password while login
);
}
static void
on_cancel_button(GtkWidget *widget, EditAccountWindow *self) {
self->Close();
}
} // namespace
void
EditAccountWindow::Init(CefRefPtr<Account> account, bool switch_on_save) {
GtkBuilder *builder = gtk_builder_new ();
GError* error = NULL;
if (!gtk_builder_add_from_string(builder, &_binary_window_edit_account_glade_start, (gsize)&_binary_window_edit_account_glade_size, &error))
{
LOG(WARNING) << "Failed to build account edditting window: " << error->message;
g_error_free (error);
}
window_objects_.account = account;
window_objects_.switch_on_save = switch_on_save;
window_handler_ = GTK_WIDGET(gtk_builder_get_object(builder, "edit_account_dialog"));
window_objects_.window = window_handler_;
window_objects_.protocol_chooser = GTK_COMBO_BOX(gtk_builder_get_object(builder, "protocol_selector"));
window_objects_.domain_entry = GTK_ENTRY(gtk_builder_get_object(builder, "domain_entry"));
window_objects_.login_entry = GTK_ENTRY(gtk_builder_get_object(builder, "login_entry"));
window_objects_.password_entry = GTK_ENTRY(gtk_builder_get_object(builder, "password_entry"));
g_signal_connect(gtk_builder_get_object(builder, "save_button"), "clicked", G_CALLBACK(on_save_button), this);
g_signal_connect(gtk_builder_get_object(builder, "cancel_button"), "clicked", G_CALLBACK(on_cancel_button), this);
g_object_unref(builder);
gtk_entry_set_text(
window_objects_.domain_entry,
account->GetDomain().c_str()
);
gtk_entry_set_text(
window_objects_.login_entry,
account->GetLogin().c_str()
);
gtk_entry_set_text(
window_objects_.password_entry,
account->GetPassword().c_str()
);
gtk_combo_box_set_active(
window_objects_.protocol_chooser,
account->IsSecure()? 0: 1
);
}
<|endoftext|> |
<commit_before>/*
* The Apache Software License, Version 1.1
*
*
* Copyright (c) 2000-2002 The Apache Software Foundation. All rights
* reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
*
* 3. The end-user documentation included with the redistribution,
* if any, must include the following acknowledgment:
* "This product includes software developed by the
* Apache Software Foundation (http://www.apache.org/)."
* Alternately, this acknowledgment may appear in the software itself,
* if and wherever such third-party acknowledgments normally appear.
*
* 4. The names "Xalan" and "Apache Software Foundation" must
* not be used to endorse or promote products derived from this
* software without prior written permission. For written
* permission, please contact [email protected].
*
* 5. Products derived from this software may not be called "Apache",
* nor may "Apache" appear in their name, without prior written
* permission of the Apache Software Foundation.
*
* THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED
* WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
* OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR
* ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
* USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
* OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation and was
* originally based on software copyright (c) 1999, International
* Business Machines, Inc., http://www.ibm.com. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*/
#include "ICUBridge.hpp"
#include <PlatformSupport/DOMStringHelper.hpp>
#include <PlatformSupport/XalanDecimalFormatSymbols.hpp>
#include <PlatformSupport/DoubleSupport.hpp>
#include <unicode/coll.h>
#include <unicode/dcfmtsym.h>
#include <unicode/decimfmt.h>
#include <Include/XalanAutoPtr.hpp>
#if defined(XALAN_NO_NAMESPACES)
typedef vector<UChar> UCharVectorType;
#else
typedef std::vector<UChar> UCharVectorType;
#endif
#if defined(XALAN_XALANDOMCHAR_USHORT_MISMATCH)
inline void
doCopyData(
const XalanDOMChar* theString,
unsigned int theStringLength,
XalanDOMChar* theBuffer)
{
// Copy the data, truncating each character...
for (unsigned int i = 0; i < theStringLength; ++i)
{
// There should be no truncation, since XalanDOMChars
// hold UTF-16 code points, but assert, just in case...
assert(theString[i] == UChar(theString[i]));
theBuffer[i] = theString[i];
}
}
#endif
// Use a stack-based buffer up to this size.
const unsigned int theStackBufferSize = 200u;
const UnicodeString
ICUBridge::XalanDOMCharStringToUnicodeString(const XalanDOMChar* theString)
{
if (theString == 0)
{
return UnicodeString();
}
else
{
#if defined(XALAN_XALANDOMCHAR_USHORT_MISMATCH)
const unsigned int theLength = length(theString);
if (theStackBufferSize > theLength)
{
XalanDOMChar theBuffer[theStackBufferSize];
doCopyData(theString, theLength, theBuffer);
#if U_SIZEOF_WCHAR_T==2
return ICUUnicodeString((wchar_t*)&theBuffer[0], theLength);
#else
return ICUUnicodeString(&theBuffer[0], theLength);
#endif
}
else
{
// Create a buffer to copy out the ICUUnicodeString data...
UCharVectorType theBuffer;
// Resize the buffer appropriately...
theBuffer.resize(theLength);
#if U_SIZEOF_WCHAR_T==2
doCopyData(theString, theLength, (XalanDOMChar*)&theBuffer[0]);
#else
doCopyData(theString, theLength, &theBuffer[0]);
#endif
assert(theLength == theBuffer.size());
return ICUUnicodeString(&theBuffer[0], theLength);
}
#else
return UnicodeString(theString, length(theString));
#endif
}
}
const UnicodeString
ICUBridge::XalanDOMStringToUnicodeString(const XalanDOMString& theString)
{
// Just call up to the XalanDOMChar* version...
return XalanDOMCharStringToUnicodeString(c_wstr(theString));
}
const XalanDOMString
ICUBridge::UnicodeStringToXalanDOMString(const UnicodeString& theString)
{
const int32_t theLength = theString.length();
#if defined(XALAN_XALANDOMCHAR_USHORT_MISMATCH)
// If XalanDOMChar is larger than the ICU's UChar, we have to more work...
// Create a buffer...
XalanDOMCharVectorType theBuffer;
// Reserve the appropriate amount of space...
theBuffer.reserve(theLength);
// Copy the data...
for (int32_t i = 0; i < theLength; ++i)
{
theBuffer.push_back(theString[i]);
}
return XalanDOMString(&theBuffer[0], theBuffer.size());
#else
if (theStackBufferSize > theLength)
{
UChar theBuffer[theStackBufferSize];
// Extract the data...
theString.extract(0, theLength, theBuffer);
return XalanDOMString(theBuffer, theLength);
}
else
{
// Create a buffer to copy out the ICUUnicodeString data...
UCharVectorType theBuffer;
// Resize the buffer appropriately...
theBuffer.resize(theLength);
// Extract the data...
theString.extract(0, theLength, &theBuffer[0]);
assert(theLength == int32_t(theBuffer.size()));
return XalanDOMString(&theBuffer[0], theLength);
}
#endif
}
void
ICUBridge::UnicodeStringToXalanDOMString(
const UnicodeString& theString,
XalanDOMString& theResult)
{
#if defined(XALAN_XALANDOMCHAR_USHORT_MISMATCH)
// If XalanDOMChar is larger than the ICU's UChar, we have to more work.
// Don't bother to provide the optimized version, just call to the
// previous function.
theResult = UnicodeStringToXalanDOMString(theString);
#else
const int32_t theLength = theString.length();
if (theStackBufferSize > theLength)
{
UChar theBuffer[theStackBufferSize];
// Extract the data...
theString.extract(0, theLength, theBuffer);
theResult = XalanDOMString(theBuffer, theLength);
}
else
{
#if defined(XALAN_NO_NAMESPACES)
typedef vector<UChar> UCharVectorType;
#else
typedef std::vector<UChar> UCharVectorType;
#endif
// Create a buffer to copy out the ICUUnicodeString data...
UCharVectorType theBuffer;
// Resize the buffer appropriately...
theBuffer.resize(theLength);
// Extract the data...
theString.extract(0, theLength, &theBuffer[0]);
theResult = XalanDOMString(&theBuffer[0], theBuffer.size());
}
#endif
}
static void
doFormatNumber(
const XalanDOMString& thePattern,
double theNumber,
const XalanDecimalFormatSymbols& theXalanDFS,
UErrorCode& theStatus,
XalanDOMString& theResult)
{
if (theStatus == U_ZERO_ERROR ||
theStatus == U_USING_DEFAULT_ERROR)
{
// Use a XalanAutoPtr, to keep this safe until we construct the DecimalFormat instance.
XalanAutoPtr<DecimalFormatSymbols> theDFS(new DecimalFormatSymbols(theStatus));
// We got a XalanDecimalFormatSymbols, so set the
// corresponding data in the ICU DecimalFormatSymbols.
theDFS->setSymbol(DecimalFormatSymbols::kZeroDigitSymbol, theXalanDFS.getZeroDigit());
theDFS->setSymbol(DecimalFormatSymbols::kGroupingSeparatorSymbol, theXalanDFS.getGroupingSeparator());
theDFS->setSymbol(DecimalFormatSymbols::kDecimalSeparatorSymbol, theXalanDFS.getDecimalSeparator());
theDFS->setSymbol(DecimalFormatSymbols::kPerMillSymbol, theXalanDFS.getPerMill());
theDFS->setSymbol(DecimalFormatSymbols::kPercentSymbol, theXalanDFS.getPercent());
theDFS->setSymbol(DecimalFormatSymbols::kDigitSymbol, theXalanDFS.getDigit());
theDFS->setSymbol(DecimalFormatSymbols::kPatternSeparatorSymbol, theXalanDFS.getPatternSeparator());
theDFS->setSymbol(DecimalFormatSymbols::kInfinitySymbol, ICUBridge::XalanDOMStringToUnicodeString(theXalanDFS.getInfinity()));
theDFS->setSymbol(DecimalFormatSymbols::kNaNSymbol, ICUBridge::XalanDOMStringToUnicodeString(theXalanDFS.getNaN()));
theDFS->setSymbol(DecimalFormatSymbols::kMinusSignSymbol, theXalanDFS.getMinusSign());
theDFS->setSymbol(DecimalFormatSymbols::kCurrencySymbol, ICUBridge::XalanDOMStringToUnicodeString(theXalanDFS.getCurrencySymbol()));
theDFS->setSymbol(DecimalFormatSymbols::kIntlCurrencySymbol, ICUBridge::XalanDOMStringToUnicodeString(theXalanDFS.getInternationalCurrencySymbol()));
theDFS->setSymbol(DecimalFormatSymbols::kMonetarySeparatorSymbol, theXalanDFS.getMonetaryDecimalSeparator());
UnicodeString theUnicodeResult;
// Construct a DecimalFormat. Note that we release the XalanAutoPtr, since the
// DecimalFormat will adopt the DecimalFormatSymbols instance.
DecimalFormat theFormatter(ICUBridge::XalanDOMStringToUnicodeString(thePattern), theDFS.release(), theStatus);
if (theStatus == U_ZERO_ERROR ||
(theStatus >= U_ERROR_INFO_START && theStatus < U_ERROR_INFO_LIMIT))
{
// Do the format...
theFormatter.format(theNumber, theUnicodeResult);
ICUBridge::UnicodeStringToXalanDOMString(theUnicodeResult, theResult);
theStatus = U_ZERO_ERROR;
}
}
}
unsigned long
ICUBridge::FormatNumber(
const XalanDOMString& thePattern,
double theNumber,
const XalanDecimalFormatSymbols* theXalanDFS,
XalanDOMString& theResult)
{
UErrorCode theStatus = U_ZERO_ERROR;
if (theXalanDFS == 0)
{
XalanDecimalFormatSymbols theDefaultSymbols;
doFormatNumber(
thePattern,
theNumber,
theDefaultSymbols,
theStatus,
theResult);
}
else
{
doFormatNumber(
thePattern,
theNumber,
*theXalanDFS,
theStatus,
theResult);
}
return theStatus;
}
int
ICUBridge::collationCompare(
const XalanDOMString& theLHS,
const XalanDOMString& theRHS)
{
// Just call to the XalanDOMChar* version...
return collationCompare(c_wstr(theLHS), c_wstr(theRHS));
}
int
ICUBridge::collationCompare(
const XalanDOMChar* theLHS,
const XalanDOMChar* theRHS)
{
UErrorCode theStatus = U_ZERO_ERROR;
// Create a collator, and keep it in an XalanAutoPtr...
const XalanAutoPtr<Collator> theCollator(Collator::createInstance(theStatus));
if (theStatus == U_ZERO_ERROR || theStatus == U_USING_DEFAULT_ERROR)
{
// OK, do the compare...
return theCollator->compare(
#if defined(XALAN_XALANDOMCHAR_USHORT_MISMATCH)
ICUBridge::XalanDOMCharStringToUnicodeString(theLHS),
ICUBridge::XalanDOMCharStringToUnicodeString(theRHS));
#else
theLHS,
length(theLHS),
theRHS,
length(theRHS));
#endif
}
else
{
// If creating the ICU Collator failed, fall back to the default...
return collationCompare(theLHS, theRHS);
}
}
<commit_msg>Fixed bogus class name.<commit_after>/*
* The Apache Software License, Version 1.1
*
*
* Copyright (c) 2000-2002 The Apache Software Foundation. All rights
* reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
*
* 3. The end-user documentation included with the redistribution,
* if any, must include the following acknowledgment:
* "This product includes software developed by the
* Apache Software Foundation (http://www.apache.org/)."
* Alternately, this acknowledgment may appear in the software itself,
* if and wherever such third-party acknowledgments normally appear.
*
* 4. The names "Xalan" and "Apache Software Foundation" must
* not be used to endorse or promote products derived from this
* software without prior written permission. For written
* permission, please contact [email protected].
*
* 5. Products derived from this software may not be called "Apache",
* nor may "Apache" appear in their name, without prior written
* permission of the Apache Software Foundation.
*
* THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED
* WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
* OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR
* ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
* USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
* OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation and was
* originally based on software copyright (c) 1999, International
* Business Machines, Inc., http://www.ibm.com. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*/
#include "ICUBridge.hpp"
#include <PlatformSupport/DOMStringHelper.hpp>
#include <PlatformSupport/XalanDecimalFormatSymbols.hpp>
#include <PlatformSupport/DoubleSupport.hpp>
#include <unicode/coll.h>
#include <unicode/dcfmtsym.h>
#include <unicode/decimfmt.h>
#include <Include/XalanAutoPtr.hpp>
#if defined(XALAN_NO_NAMESPACES)
typedef vector<UChar> UCharVectorType;
#else
typedef std::vector<UChar> UCharVectorType;
#endif
#if defined(XALAN_XALANDOMCHAR_USHORT_MISMATCH)
inline void
doCopyData(
const XalanDOMChar* theString,
unsigned int theStringLength,
XalanDOMChar* theBuffer)
{
// Copy the data, truncating each character...
for (unsigned int i = 0; i < theStringLength; ++i)
{
// There should be no truncation, since XalanDOMChars
// hold UTF-16 code points, but assert, just in case...
assert(theString[i] == UChar(theString[i]));
theBuffer[i] = theString[i];
}
}
#endif
// Use a stack-based buffer up to this size.
const unsigned int theStackBufferSize = 200u;
const UnicodeString
ICUBridge::XalanDOMCharStringToUnicodeString(const XalanDOMChar* theString)
{
if (theString == 0)
{
return UnicodeString();
}
else
{
#if defined(XALAN_XALANDOMCHAR_USHORT_MISMATCH)
const unsigned int theLength = length(theString);
if (theStackBufferSize > theLength)
{
XalanDOMChar theBuffer[theStackBufferSize];
doCopyData(theString, theLength, theBuffer);
#if U_SIZEOF_WCHAR_T==2
return UnicodeString((wchar_t*)&theBuffer[0], theLength);
#else
return UnicodeString(&theBuffer[0], theLength);
#endif
}
else
{
// Create a buffer to copy out the UnicodeString data...
UCharVectorType theBuffer;
// Resize the buffer appropriately...
theBuffer.resize(theLength);
#if U_SIZEOF_WCHAR_T==2
doCopyData(theString, theLength, (XalanDOMChar*)&theBuffer[0]);
#else
doCopyData(theString, theLength, &theBuffer[0]);
#endif
assert(theLength == theBuffer.size());
return UnicodeString(&theBuffer[0], theLength);
}
#else
return UnicodeString(theString, length(theString));
#endif
}
}
const UnicodeString
ICUBridge::XalanDOMStringToUnicodeString(const XalanDOMString& theString)
{
// Just call up to the XalanDOMChar* version...
return XalanDOMCharStringToUnicodeString(c_wstr(theString));
}
const XalanDOMString
ICUBridge::UnicodeStringToXalanDOMString(const UnicodeString& theString)
{
const int32_t theLength = theString.length();
#if defined(XALAN_XALANDOMCHAR_USHORT_MISMATCH)
// If XalanDOMChar is larger than the ICU's UChar, we have to more work...
// Create a buffer...
XalanDOMCharVectorType theBuffer;
// Reserve the appropriate amount of space...
theBuffer.reserve(theLength);
// Copy the data...
for (int32_t i = 0; i < theLength; ++i)
{
theBuffer.push_back(theString[i]);
}
return XalanDOMString(&theBuffer[0], theBuffer.size());
#else
if (theStackBufferSize > theLength)
{
UChar theBuffer[theStackBufferSize];
// Extract the data...
theString.extract(0, theLength, theBuffer);
return XalanDOMString(theBuffer, theLength);
}
else
{
// Create a buffer to copy out the UnicodeString data...
UCharVectorType theBuffer;
// Resize the buffer appropriately...
theBuffer.resize(theLength);
// Extract the data...
theString.extract(0, theLength, &theBuffer[0]);
assert(theLength == int32_t(theBuffer.size()));
return XalanDOMString(&theBuffer[0], theLength);
}
#endif
}
void
ICUBridge::UnicodeStringToXalanDOMString(
const UnicodeString& theString,
XalanDOMString& theResult)
{
#if defined(XALAN_XALANDOMCHAR_USHORT_MISMATCH)
// If XalanDOMChar is larger than the ICU's UChar, we have to more work.
// Don't bother to provide the optimized version, just call to the
// previous function.
theResult = UnicodeStringToXalanDOMString(theString);
#else
const int32_t theLength = theString.length();
if (theStackBufferSize > theLength)
{
UChar theBuffer[theStackBufferSize];
// Extract the data...
theString.extract(0, theLength, theBuffer);
theResult = XalanDOMString(theBuffer, theLength);
}
else
{
#if defined(XALAN_NO_NAMESPACES)
typedef vector<UChar> UCharVectorType;
#else
typedef std::vector<UChar> UCharVectorType;
#endif
// Create a buffer to copy out the UnicodeString data...
UCharVectorType theBuffer;
// Resize the buffer appropriately...
theBuffer.resize(theLength);
// Extract the data...
theString.extract(0, theLength, &theBuffer[0]);
theResult = XalanDOMString(&theBuffer[0], theBuffer.size());
}
#endif
}
static void
doFormatNumber(
const XalanDOMString& thePattern,
double theNumber,
const XalanDecimalFormatSymbols& theXalanDFS,
UErrorCode& theStatus,
XalanDOMString& theResult)
{
if (theStatus == U_ZERO_ERROR ||
theStatus == U_USING_DEFAULT_ERROR)
{
// Use a XalanAutoPtr, to keep this safe until we construct the DecimalFormat instance.
XalanAutoPtr<DecimalFormatSymbols> theDFS(new DecimalFormatSymbols(theStatus));
// We got a XalanDecimalFormatSymbols, so set the
// corresponding data in the ICU DecimalFormatSymbols.
theDFS->setSymbol(DecimalFormatSymbols::kZeroDigitSymbol, theXalanDFS.getZeroDigit());
theDFS->setSymbol(DecimalFormatSymbols::kGroupingSeparatorSymbol, theXalanDFS.getGroupingSeparator());
theDFS->setSymbol(DecimalFormatSymbols::kDecimalSeparatorSymbol, theXalanDFS.getDecimalSeparator());
theDFS->setSymbol(DecimalFormatSymbols::kPerMillSymbol, theXalanDFS.getPerMill());
theDFS->setSymbol(DecimalFormatSymbols::kPercentSymbol, theXalanDFS.getPercent());
theDFS->setSymbol(DecimalFormatSymbols::kDigitSymbol, theXalanDFS.getDigit());
theDFS->setSymbol(DecimalFormatSymbols::kPatternSeparatorSymbol, theXalanDFS.getPatternSeparator());
theDFS->setSymbol(DecimalFormatSymbols::kInfinitySymbol, ICUBridge::XalanDOMStringToUnicodeString(theXalanDFS.getInfinity()));
theDFS->setSymbol(DecimalFormatSymbols::kNaNSymbol, ICUBridge::XalanDOMStringToUnicodeString(theXalanDFS.getNaN()));
theDFS->setSymbol(DecimalFormatSymbols::kMinusSignSymbol, theXalanDFS.getMinusSign());
theDFS->setSymbol(DecimalFormatSymbols::kCurrencySymbol, ICUBridge::XalanDOMStringToUnicodeString(theXalanDFS.getCurrencySymbol()));
theDFS->setSymbol(DecimalFormatSymbols::kIntlCurrencySymbol, ICUBridge::XalanDOMStringToUnicodeString(theXalanDFS.getInternationalCurrencySymbol()));
theDFS->setSymbol(DecimalFormatSymbols::kMonetarySeparatorSymbol, theXalanDFS.getMonetaryDecimalSeparator());
UnicodeString theUnicodeResult;
// Construct a DecimalFormat. Note that we release the XalanAutoPtr, since the
// DecimalFormat will adopt the DecimalFormatSymbols instance.
DecimalFormat theFormatter(ICUBridge::XalanDOMStringToUnicodeString(thePattern), theDFS.release(), theStatus);
if (theStatus == U_ZERO_ERROR ||
(theStatus >= U_ERROR_INFO_START && theStatus < U_ERROR_INFO_LIMIT))
{
// Do the format...
theFormatter.format(theNumber, theUnicodeResult);
ICUBridge::UnicodeStringToXalanDOMString(theUnicodeResult, theResult);
theStatus = U_ZERO_ERROR;
}
}
}
unsigned long
ICUBridge::FormatNumber(
const XalanDOMString& thePattern,
double theNumber,
const XalanDecimalFormatSymbols* theXalanDFS,
XalanDOMString& theResult)
{
UErrorCode theStatus = U_ZERO_ERROR;
if (theXalanDFS == 0)
{
XalanDecimalFormatSymbols theDefaultSymbols;
doFormatNumber(
thePattern,
theNumber,
theDefaultSymbols,
theStatus,
theResult);
}
else
{
doFormatNumber(
thePattern,
theNumber,
*theXalanDFS,
theStatus,
theResult);
}
return theStatus;
}
int
ICUBridge::collationCompare(
const XalanDOMString& theLHS,
const XalanDOMString& theRHS)
{
// Just call to the XalanDOMChar* version...
return collationCompare(c_wstr(theLHS), c_wstr(theRHS));
}
int
ICUBridge::collationCompare(
const XalanDOMChar* theLHS,
const XalanDOMChar* theRHS)
{
UErrorCode theStatus = U_ZERO_ERROR;
// Create a collator, and keep it in an XalanAutoPtr...
const XalanAutoPtr<Collator> theCollator(Collator::createInstance(theStatus));
if (theStatus == U_ZERO_ERROR || theStatus == U_USING_DEFAULT_ERROR)
{
// OK, do the compare...
return theCollator->compare(
#if defined(XALAN_XALANDOMCHAR_USHORT_MISMATCH)
ICUBridge::XalanDOMCharStringToUnicodeString(theLHS),
ICUBridge::XalanDOMCharStringToUnicodeString(theRHS));
#else
theLHS,
length(theLHS),
theRHS,
length(theRHS));
#endif
}
else
{
// If creating the ICU Collator failed, fall back to the default...
return collationCompare(theLHS, theRHS);
}
}
<|endoftext|> |
<commit_before>/*
This file is part of KDE Kontact.
Copyright (C) 2003 Cornelius Schumacher <[email protected]>
This program is free software; you can redistribute it and/or
modify it under the terms of the GNU General Public
License as published by the Free Software Foundation; either
version 2 of the License, or (at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; see the file COPYING. If not, write to
the Free Software Foundation, Inc., 59 Temple Place - Suite 330,
Boston, MA 02111-1307, USA.
*/
#include <qptrlist.h>
#include <qwidgetstack.h>
#include <qsignal.h>
#include <qobjectlist.h>
#include <qlabel.h>
#include <qimage.h>
#include <qpainter.h>
#include <qbitmap.h>
#include <qfontmetrics.h>
#include <qsignalmapper.h>
#include <qstyle.h>
#include <qframe.h>
#include <qdrawutil.h>
#include <kpopupmenu.h>
#include <kapplication.h>
#include <kdialog.h>
#include <klocale.h>
#include <kiconloader.h>
#include <sidebarextension.h>
#include <kdebug.h>
#include "mainwindow.h"
#include "plugin.h"
#include "prefs.h"
#include "iconsidepane.h"
namespace Kontact
{
//ugly wrapper class for adding an operator< to the Plugin class
class PluginProxy
{
public:
PluginProxy()
: mPlugin( 0 )
{ }
PluginProxy( Plugin *plugin )
: mPlugin( plugin )
{ }
PluginProxy & operator=( Plugin *plugin )
{
mPlugin = plugin;
return *this;
}
bool operator<( PluginProxy &rhs ) const
{
return mPlugin->weight() < rhs.mPlugin->weight();
}
Plugin *plugin() const
{
return mPlugin;
}
private:
Plugin *mPlugin;
};
} //namespace
using namespace Kontact;
EntryItem::EntryItem( Navigator *parent, Kontact::Plugin *plugin )
: QListBoxItem( parent ),
mPlugin( plugin )
{
reloadPixmap();
setCustomHighlighting( true );
setText( plugin->title() );
}
EntryItem::~EntryItem()
{
}
void EntryItem::reloadPixmap()
{
int size = (int)navigator()->viewMode();
if ( size != 0 )
mPixmap = KGlobal::iconLoader()->loadIcon( mPlugin->icon(),
KIcon::Desktop, size );
else
mPixmap = QPixmap();
}
Navigator* EntryItem::navigator() const
{
return static_cast<Navigator*>( listBox() );
}
int EntryItem::width( const QListBox *listbox ) const
{
int w;
if ( text().isEmpty() )
w = mPixmap.width();
else if (navigator()->viewMode() > SmallIcons)
w = QMAX( (int)navigator()->viewMode(), listbox->fontMetrics().width( text() ) );
else
w = (int)navigator()->viewMode() + 4 + listbox->fontMetrics().width( text() );
return w + ( KDialog::marginHint() * 2 );
}
int EntryItem::height( const QListBox *listbox ) const
{
int h;
if ( text().isEmpty() )
h = mPixmap.height() + 4;
else if (navigator()->viewMode() > SmallIcons)
h = (int)navigator()->viewMode() + listbox->fontMetrics().lineSpacing() + 4;
else
h = QMAX( (int)navigator()->viewMode(),
listbox->fontMetrics().lineSpacing() ) +
KDialog::spacingHint() * 2;
return h;
}
void EntryItem::paint( QPainter *p )
{
reloadPixmap();
QListBox *box = listBox();
bool iconAboveText = navigator()->viewMode() > SmallIcons;
int w = box->viewport()->width();
int y = iconAboveText ? 2 : KDialog::spacingHint();
// draw selected
if ( isCurrent() || isSelected() ) {
int h = height( box );
QBrush brush = box->colorGroup().brush( QColorGroup::Highlight );
brush.setColor( brush.color().light( 115 ) );
p->fillRect( 1, 0, w - 2, h - 1, brush );
QPen pen = p->pen();
QPen oldPen = pen;
pen.setColor( box->colorGroup().mid() );
p->setPen( pen );
p->drawPoint( 1, 0 );
p->drawPoint( 1, h - 2 );
p->drawPoint( w - 2, 0 );
p->drawPoint( w - 2, h - 2 );
p->setPen( oldPen );
}
if ( !mPixmap.isNull() ) {
int x = iconAboveText ? ( ( w - mPixmap.width() ) / 2 ) : KDialog::marginHint();
p->drawPixmap( x, y, mPixmap );
}
QColor shadowColor = listBox()->colorGroup().background().dark(115);
if ( isCurrent() || isSelected() ) {
p->setPen( box->colorGroup().highlightedText() );
}
if ( !text().isEmpty() ) {
QFontMetrics fm = p->fontMetrics();
int x = 0;
if (iconAboveText) {
x = ( w - fm.width( text() ) ) / 2;
y += fm.height() - fm.descent() + mPixmap.height();
}
else {
x = KDialog::marginHint() + mPixmap.width() + 4;
if ( mPixmap.height() < fm.height() )
y += fm.ascent() + fm.leading()/2;
else
y += mPixmap.height()/2 - fm.height()/2 + fm.ascent();
}
if ( isCurrent() || isSelected() ) {
p->setPen( box->colorGroup().highlight().dark(115) );
p->drawText( x + ( QApplication::reverseLayout() ? -1 : 1),
y + 1, text() );
p->setPen( box->colorGroup().highlightedText() );
}
else
p->setPen( box->colorGroup().text() );
p->drawText( x, y, text() );
}
}
Navigator::Navigator( SidePaneBase *parent, const char *name )
: KListBox( parent, name ), mSidePane( parent )
{
mViewMode = sizeIntToEnum( Prefs::self()->sidePaneIconSize() );
setSelectionMode( KListBox::Single );
viewport()->setBackgroundMode( PaletteBackground );
setHScrollBarMode( QScrollView::AlwaysOff );
setAcceptDrops( true );
setFocusPolicy( NoFocus );
connect( this, SIGNAL( selectionChanged( QListBoxItem* ) ),
SLOT( slotExecuted( QListBoxItem* ) ) );
connect( this, SIGNAL( rightButtonPressed( QListBoxItem*, const QPoint& ) ),
SLOT( slotShowRMBMenu( QListBoxItem*, const QPoint& ) ) );
mMapper = new QSignalMapper( this );
connect( mMapper, SIGNAL( mapped( int ) ), SLOT( shortCutSelected( int ) ) );
}
QSize Navigator::sizeHint() const
{
return QSize( 100, 100 );
}
void Navigator::setSelected( QListBoxItem *item, bool selected )
{
// Reimplemented to avoid the immediate activation of
// the item. might turn out it doesn't work, we check that
// an confirm from MainWindow::selectPlugin()
if ( selected ) {
EntryItem *entry = static_cast<EntryItem*>( item );
emit pluginActivated( entry->plugin() );
}
}
void Navigator::updatePlugins( QValueList<Kontact::Plugin*> plugins_ )
{
QValueList<Kontact::PluginProxy> plugins;
QValueList<Kontact::Plugin*>::ConstIterator end_ = plugins_.end();
QValueList<Kontact::Plugin*>::ConstIterator it_ = plugins_.begin();
for ( ; it_ != end_; ++it_ )
plugins += PluginProxy( *it_ );
clear();
mActions.setAutoDelete( true );
mActions.clear();
mActions.setAutoDelete( false );
int counter = 0;
int minWidth = 0;
qBubbleSort( plugins );
QValueList<Kontact::PluginProxy>::ConstIterator end = plugins.end();
QValueList<Kontact::PluginProxy>::ConstIterator it = plugins.begin();
for ( ; it != end; ++it ) {
Kontact::Plugin *plugin = ( *it ).plugin();
if ( !plugin->showInSideBar() )
continue;
EntryItem *item = new EntryItem( this, plugin );
if ( item->width( this ) > minWidth )
minWidth = item->width( this );
QString name = QString( "CTRL+%1" ).arg( counter + 1 );
KAction *action = new KAction( plugin->title(), KShortcut( name ),
mMapper, SLOT( map() ),
mSidePane->actionCollection(), name.latin1() );
mMapper->setMapping( action, counter );
counter++;
}
parentWidget()->setFixedWidth( minWidth );
}
void Navigator::dragEnterEvent( QDragEnterEvent *event )
{
kdDebug(5600) << "Navigator::dragEnterEvent()" << endl;
dragMoveEvent( event );
}
void Navigator::dragMoveEvent( QDragMoveEvent *event )
{
kdDebug(5600) << "Navigator::dragEnterEvent()" << endl;
kdDebug(5600) << " Format: " << event->format() << endl;
QListBoxItem *item = itemAt( event->pos() );
if ( !item ) {
event->accept( false );
return;
}
EntryItem *entry = static_cast<EntryItem*>( item );
kdDebug(5600) << " PLUGIN: " << entry->plugin()->identifier() << endl;
event->accept( entry->plugin()->canDecodeDrag( event ) );
}
void Navigator::dropEvent( QDropEvent *event )
{
kdDebug(5600) << "Navigator::dropEvent()" << endl;
QListBoxItem *item = itemAt( event->pos() );
if ( !item ) {
return;
}
EntryItem *entry = static_cast<EntryItem*>( item );
kdDebug(5600) << " PLUGIN: " << entry->plugin()->identifier() << endl;
entry->plugin()->processDropEvent( event );
}
void Navigator::resizeEvent( QResizeEvent *event )
{
QListBox::resizeEvent( event );
triggerUpdate( true );
}
void Navigator::slotExecuted( QListBoxItem *item )
{
if ( !item )
return;
EntryItem *entry = static_cast<EntryItem*>( item );
emit pluginActivated( entry->plugin() );
}
IconViewMode Navigator::sizeIntToEnum(int size) const
{
switch ( size ) {
case int(LargeIcons):
return LargeIcons;
break;
case int(NormalIcons):
return NormalIcons;
break;
case int(SmallIcons):
return SmallIcons;
break;
case int(TextOnly):
return TextOnly;
break;
default:
// Stick with sane values
return NormalIcons;
kdDebug() << "View mode not implemented!" << endl;
break;
}
}
void Navigator::slotShowRMBMenu( QListBoxItem *, const QPoint &pos )
{
KPopupMenu menu;
menu.insertTitle( i18n( "Icon Size" ) );
menu.insertItem( i18n( "Large" ), (int)LargeIcons );
menu.insertItem( i18n( "Normal" ), (int)NormalIcons );
menu.insertItem( i18n( "Small" ), (int)SmallIcons );
menu.insertItem( i18n( "Text Only" ), (int)TextOnly );
int choice = menu.exec( pos );
if ( choice == -1 )
return;
mViewMode = sizeIntToEnum( choice );
Prefs::self()->setSidePaneIconSize( choice );
int maxWidth = 0;
QListBoxItem* it = 0;
for (int i = 0; (it = item(i)) != 0; ++i)
{
int width = it->width(this);
if (width > maxWidth)
maxWidth = width;
}
parentWidget()->setFixedWidth( maxWidth );
triggerUpdate( true );
}
void Navigator::shortCutSelected( int pos )
{
setCurrentItem( pos );
}
IconSidePane::IconSidePane( Core *core, QWidget *parent, const char *name )
: SidePaneBase( core, parent, name )
{
mNavigator = new Navigator( this );
connect( mNavigator, SIGNAL( pluginActivated( Kontact::Plugin* ) ),
SIGNAL( pluginSelected( Kontact::Plugin* ) ) );
setAcceptDrops( true );
}
IconSidePane::~IconSidePane()
{
}
void IconSidePane::updatePlugins()
{
mNavigator->updatePlugins( core()->pluginList() );
}
void IconSidePane::selectPlugin( Kontact::Plugin *plugin )
{
bool blocked = signalsBlocked();
blockSignals( true );
uint i;
for ( i = 0; i < mNavigator->count(); ++i ) {
EntryItem *item = static_cast<EntryItem*>( mNavigator->item( i ) );
if ( item->plugin() == plugin ) {
mNavigator->setCurrentItem( i );
break;
}
}
blockSignals( blocked );
}
void IconSidePane::selectPlugin( const QString &name )
{
bool blocked = signalsBlocked();
blockSignals( true );
uint i;
for ( i = 0; i < mNavigator->count(); ++i ) {
EntryItem *item = static_cast<EntryItem*>( mNavigator->item( i ) );
if ( item->plugin()->identifier() == name ) {
mNavigator->setCurrentItem( i );
break;
}
}
blockSignals( blocked );
}
#include "iconsidepane.moc"
// vim: sw=2 sts=2 et tw=80
<commit_msg>don't lighten the color. was from an earlier experiment. sorry cornelius.<commit_after>/*
This file is part of KDE Kontact.
Copyright (C) 2003 Cornelius Schumacher <[email protected]>
This program is free software; you can redistribute it and/or
modify it under the terms of the GNU General Public
License as published by the Free Software Foundation; either
version 2 of the License, or (at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; see the file COPYING. If not, write to
the Free Software Foundation, Inc., 59 Temple Place - Suite 330,
Boston, MA 02111-1307, USA.
*/
#include <qptrlist.h>
#include <qwidgetstack.h>
#include <qsignal.h>
#include <qobjectlist.h>
#include <qlabel.h>
#include <qimage.h>
#include <qpainter.h>
#include <qbitmap.h>
#include <qfontmetrics.h>
#include <qsignalmapper.h>
#include <qstyle.h>
#include <qframe.h>
#include <qdrawutil.h>
#include <kpopupmenu.h>
#include <kapplication.h>
#include <kdialog.h>
#include <klocale.h>
#include <kiconloader.h>
#include <sidebarextension.h>
#include <kdebug.h>
#include "mainwindow.h"
#include "plugin.h"
#include "prefs.h"
#include "iconsidepane.h"
namespace Kontact
{
//ugly wrapper class for adding an operator< to the Plugin class
class PluginProxy
{
public:
PluginProxy()
: mPlugin( 0 )
{ }
PluginProxy( Plugin *plugin )
: mPlugin( plugin )
{ }
PluginProxy & operator=( Plugin *plugin )
{
mPlugin = plugin;
return *this;
}
bool operator<( PluginProxy &rhs ) const
{
return mPlugin->weight() < rhs.mPlugin->weight();
}
Plugin *plugin() const
{
return mPlugin;
}
private:
Plugin *mPlugin;
};
} //namespace
using namespace Kontact;
EntryItem::EntryItem( Navigator *parent, Kontact::Plugin *plugin )
: QListBoxItem( parent ),
mPlugin( plugin )
{
reloadPixmap();
setCustomHighlighting( true );
setText( plugin->title() );
}
EntryItem::~EntryItem()
{
}
void EntryItem::reloadPixmap()
{
int size = (int)navigator()->viewMode();
if ( size != 0 )
mPixmap = KGlobal::iconLoader()->loadIcon( mPlugin->icon(),
KIcon::Desktop, size );
else
mPixmap = QPixmap();
}
Navigator* EntryItem::navigator() const
{
return static_cast<Navigator*>( listBox() );
}
int EntryItem::width( const QListBox *listbox ) const
{
int w;
if ( text().isEmpty() )
w = mPixmap.width();
else if (navigator()->viewMode() > SmallIcons)
w = QMAX( (int)navigator()->viewMode(), listbox->fontMetrics().width( text() ) );
else
w = (int)navigator()->viewMode() + 4 + listbox->fontMetrics().width( text() );
return w + ( KDialog::marginHint() * 2 );
}
int EntryItem::height( const QListBox *listbox ) const
{
int h;
if ( text().isEmpty() )
h = mPixmap.height() + 4;
else if (navigator()->viewMode() > SmallIcons)
h = (int)navigator()->viewMode() + listbox->fontMetrics().lineSpacing() + 4;
else
h = QMAX( (int)navigator()->viewMode(),
listbox->fontMetrics().lineSpacing() ) +
KDialog::spacingHint() * 2;
return h;
}
void EntryItem::paint( QPainter *p )
{
reloadPixmap();
QListBox *box = listBox();
bool iconAboveText = navigator()->viewMode() > SmallIcons;
int w = box->viewport()->width();
int y = iconAboveText ? 2 : KDialog::spacingHint();
// draw selected
if ( isCurrent() || isSelected() ) {
int h = height( box );
QBrush brush = box->colorGroup().brush( QColorGroup::Highlight );
p->fillRect( 1, 0, w - 2, h - 1, brush );
QPen pen = p->pen();
QPen oldPen = pen;
pen.setColor( box->colorGroup().mid() );
p->setPen( pen );
p->drawPoint( 1, 0 );
p->drawPoint( 1, h - 2 );
p->drawPoint( w - 2, 0 );
p->drawPoint( w - 2, h - 2 );
p->setPen( oldPen );
}
if ( !mPixmap.isNull() ) {
int x = iconAboveText ? ( ( w - mPixmap.width() ) / 2 ) :
KDialog::marginHint();
p->drawPixmap( x, y, mPixmap );
}
QColor shadowColor = listBox()->colorGroup().background().dark(115);
if ( isCurrent() || isSelected() ) {
p->setPen( box->colorGroup().highlightedText() );
}
if ( !text().isEmpty() ) {
QFontMetrics fm = p->fontMetrics();
int x = 0;
if (iconAboveText) {
x = ( w - fm.width( text() ) ) / 2;
y += fm.height() - fm.descent() + mPixmap.height();
}
else {
x = KDialog::marginHint() + mPixmap.width() + 4;
if ( mPixmap.height() < fm.height() )
y += fm.ascent() + fm.leading()/2;
else
y += mPixmap.height()/2 - fm.height()/2 + fm.ascent();
}
if ( isCurrent() || isSelected() ) {
p->setPen( box->colorGroup().highlight().dark(115) );
p->drawText( x + ( QApplication::reverseLayout() ? -1 : 1),
y + 1, text() );
p->setPen( box->colorGroup().highlightedText() );
}
else
p->setPen( box->colorGroup().text() );
p->drawText( x, y, text() );
}
}
Navigator::Navigator( SidePaneBase *parent, const char *name )
: KListBox( parent, name ), mSidePane( parent )
{
mViewMode = sizeIntToEnum( Prefs::self()->sidePaneIconSize() );
setSelectionMode( KListBox::Single );
viewport()->setBackgroundMode( PaletteBackground );
setHScrollBarMode( QScrollView::AlwaysOff );
setAcceptDrops( true );
setFocusPolicy( NoFocus );
connect( this, SIGNAL( selectionChanged( QListBoxItem* ) ),
SLOT( slotExecuted( QListBoxItem* ) ) );
connect( this, SIGNAL( rightButtonPressed( QListBoxItem*, const QPoint& ) ),
SLOT( slotShowRMBMenu( QListBoxItem*, const QPoint& ) ) );
mMapper = new QSignalMapper( this );
connect( mMapper, SIGNAL( mapped( int ) ), SLOT( shortCutSelected( int ) ) );
}
QSize Navigator::sizeHint() const
{
return QSize( 100, 100 );
}
void Navigator::setSelected( QListBoxItem *item, bool selected )
{
// Reimplemented to avoid the immediate activation of
// the item. might turn out it doesn't work, we check that
// an confirm from MainWindow::selectPlugin()
if ( selected ) {
EntryItem *entry = static_cast<EntryItem*>( item );
emit pluginActivated( entry->plugin() );
}
}
void Navigator::updatePlugins( QValueList<Kontact::Plugin*> plugins_ )
{
QValueList<Kontact::PluginProxy> plugins;
QValueList<Kontact::Plugin*>::ConstIterator end_ = plugins_.end();
QValueList<Kontact::Plugin*>::ConstIterator it_ = plugins_.begin();
for ( ; it_ != end_; ++it_ )
plugins += PluginProxy( *it_ );
clear();
mActions.setAutoDelete( true );
mActions.clear();
mActions.setAutoDelete( false );
int counter = 0;
int minWidth = 0;
qBubbleSort( plugins );
QValueList<Kontact::PluginProxy>::ConstIterator end = plugins.end();
QValueList<Kontact::PluginProxy>::ConstIterator it = plugins.begin();
for ( ; it != end; ++it ) {
Kontact::Plugin *plugin = ( *it ).plugin();
if ( !plugin->showInSideBar() )
continue;
EntryItem *item = new EntryItem( this, plugin );
if ( item->width( this ) > minWidth )
minWidth = item->width( this );
QString name = QString( "CTRL+%1" ).arg( counter + 1 );
KAction *action = new KAction( plugin->title(), KShortcut( name ),
mMapper, SLOT( map() ),
mSidePane->actionCollection(), name.latin1() );
mMapper->setMapping( action, counter );
counter++;
}
parentWidget()->setFixedWidth( minWidth );
}
void Navigator::dragEnterEvent( QDragEnterEvent *event )
{
kdDebug(5600) << "Navigator::dragEnterEvent()" << endl;
dragMoveEvent( event );
}
void Navigator::dragMoveEvent( QDragMoveEvent *event )
{
kdDebug(5600) << "Navigator::dragEnterEvent()" << endl;
kdDebug(5600) << " Format: " << event->format() << endl;
QListBoxItem *item = itemAt( event->pos() );
if ( !item ) {
event->accept( false );
return;
}
EntryItem *entry = static_cast<EntryItem*>( item );
kdDebug(5600) << " PLUGIN: " << entry->plugin()->identifier() << endl;
event->accept( entry->plugin()->canDecodeDrag( event ) );
}
void Navigator::dropEvent( QDropEvent *event )
{
kdDebug(5600) << "Navigator::dropEvent()" << endl;
QListBoxItem *item = itemAt( event->pos() );
if ( !item ) {
return;
}
EntryItem *entry = static_cast<EntryItem*>( item );
kdDebug(5600) << " PLUGIN: " << entry->plugin()->identifier() << endl;
entry->plugin()->processDropEvent( event );
}
void Navigator::resizeEvent( QResizeEvent *event )
{
QListBox::resizeEvent( event );
triggerUpdate( true );
}
void Navigator::slotExecuted( QListBoxItem *item )
{
if ( !item )
return;
EntryItem *entry = static_cast<EntryItem*>( item );
emit pluginActivated( entry->plugin() );
}
IconViewMode Navigator::sizeIntToEnum(int size) const
{
switch ( size ) {
case int(LargeIcons):
return LargeIcons;
break;
case int(NormalIcons):
return NormalIcons;
break;
case int(SmallIcons):
return SmallIcons;
break;
case int(TextOnly):
return TextOnly;
break;
default:
// Stick with sane values
return NormalIcons;
kdDebug() << "View mode not implemented!" << endl;
break;
}
}
void Navigator::slotShowRMBMenu( QListBoxItem *, const QPoint &pos )
{
KPopupMenu menu;
menu.insertTitle( i18n( "Icon Size" ) );
menu.insertItem( i18n( "Large" ), (int)LargeIcons );
menu.insertItem( i18n( "Normal" ), (int)NormalIcons );
menu.insertItem( i18n( "Small" ), (int)SmallIcons );
menu.insertItem( i18n( "Text Only" ), (int)TextOnly );
int choice = menu.exec( pos );
if ( choice == -1 )
return;
mViewMode = sizeIntToEnum( choice );
Prefs::self()->setSidePaneIconSize( choice );
int maxWidth = 0;
QListBoxItem* it = 0;
for (int i = 0; (it = item(i)) != 0; ++i)
{
int width = it->width(this);
if (width > maxWidth)
maxWidth = width;
}
parentWidget()->setFixedWidth( maxWidth );
triggerUpdate( true );
}
void Navigator::shortCutSelected( int pos )
{
setCurrentItem( pos );
}
IconSidePane::IconSidePane( Core *core, QWidget *parent, const char *name )
: SidePaneBase( core, parent, name )
{
mNavigator = new Navigator( this );
connect( mNavigator, SIGNAL( pluginActivated( Kontact::Plugin* ) ),
SIGNAL( pluginSelected( Kontact::Plugin* ) ) );
setAcceptDrops( true );
}
IconSidePane::~IconSidePane()
{
}
void IconSidePane::updatePlugins()
{
mNavigator->updatePlugins( core()->pluginList() );
}
void IconSidePane::selectPlugin( Kontact::Plugin *plugin )
{
bool blocked = signalsBlocked();
blockSignals( true );
uint i;
for ( i = 0; i < mNavigator->count(); ++i ) {
EntryItem *item = static_cast<EntryItem*>( mNavigator->item( i ) );
if ( item->plugin() == plugin ) {
mNavigator->setCurrentItem( i );
break;
}
}
blockSignals( blocked );
}
void IconSidePane::selectPlugin( const QString &name )
{
bool blocked = signalsBlocked();
blockSignals( true );
uint i;
for ( i = 0; i < mNavigator->count(); ++i ) {
EntryItem *item = static_cast<EntryItem*>( mNavigator->item( i ) );
if ( item->plugin()->identifier() == name ) {
mNavigator->setCurrentItem( i );
break;
}
}
blockSignals( blocked );
}
#include "iconsidepane.moc"
// vim: sw=2 sts=2 et tw=80
<|endoftext|> |
<commit_before>/*
This file is part of KOrganizer.
Copyright (c) 2001 Cornelius Schumacher <[email protected]>
Copyright (c) 2009 Allen Winter <[email protected]>
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License along
with this program; if not, write to the Free Software Foundation, Inc.,
51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
As a special exception, permission is given to link this program
with any edition of Qt, and distribute the resulting executable,
without including the source code for Qt in the source distribution.
*/
// TODO: validate hand-entered email addresses
// TODO: don't allow duplicates; at least remove dupes when passing back
// TODO: the list in PublishDialog::addresses()
#include "publishdialog.h"
#include <kabc/addresseedialog.h>
#include <kcal/attendee.h>
#include <kcal/person.h>
#include <kpimutils/email.h>
#include <klineedit.h>
#include <klocale.h>
PublishDialog::PublishDialog( QWidget *parent )
: KDialog( parent )
{
setCaption( i18n( "Select Addresses" ) );
setButtons( Ok|Cancel|Help );
setHelp( "group-scheduling", "korganizer" );
QWidget *widget = new QWidget( this );
widget->setObjectName( "PublishFreeBusy" );
mUI.setupUi( widget );
setMainWidget( widget );
mUI.mListWidget->setSelectionMode( QAbstractItemView::SingleSelection );
mUI.mNameLineEdit->setEnabled( false );
mUI.mEmailLineEdit->setEnabled( false );
setButtonToolTip( Ok, i18n( "Send email to these recipients" ) );
setButtonWhatsThis( Ok, i18n( "Clicking the <b>Ok</b> button will cause "
"an email to be sent to the recipients you "
"have entered." ) );
setButtonToolTip( Cancel, i18n( "Cancel recipient selection and the email" ) );
setButtonWhatsThis( Cancel, i18n( "Clicking the <b>Cancel</b> button will "
"cause the email operation to be terminated." ) );
setButtonWhatsThis( Help, i18n( "Click the <b>Help</b> button to read "
"more information about Group Scheduling." ) );
mUI.mNew->setIcon( KIcon( "list-add" ) );
mUI.mRemove->setIcon( KIcon( "list-remove" ) );
mUI.mRemove->setEnabled( false );
mUI.mSelectAddressee->setIcon( KIcon( "view-pim-contacts" ) );
connect( mUI.mListWidget, SIGNAL(itemSelectionChanged()),
SLOT(updateInput()) );
connect( mUI.mNew, SIGNAL(clicked()),
SLOT(addItem()) );
connect( mUI.mRemove, SIGNAL(clicked()),
SLOT(removeItem()) );
connect( mUI.mSelectAddressee, SIGNAL(clicked()),
SLOT(openAddressbook()) );
connect( mUI.mNameLineEdit, SIGNAL(textChanged(const QString &)),
SLOT(updateItem()) );
connect( mUI.mEmailLineEdit, SIGNAL(textChanged(const QString &)),
SLOT(updateItem()) );
}
PublishDialog::~PublishDialog()
{
}
void PublishDialog::addAttendee( Attendee *attendee )
{
mUI.mNameLineEdit->setEnabled( true );
mUI.mEmailLineEdit->setEnabled( true );
QListWidgetItem *item = new QListWidgetItem( mUI.mListWidget );
Person person( attendee->name(), attendee->email() );
item->setText( person.fullName() );
mUI.mListWidget->addItem( item );
mUI.mRemove->setEnabled( true );
}
QString PublishDialog::addresses()
{
QString to = "";
QListWidgetItem *item;
int i, count;
count = mUI.mListWidget->count();
for ( i=0; i<count; i++ ) {
item = mUI.mListWidget->takeItem( i );
to += item->text();
if ( i < count-1 ) {
to += ", ";
}
}
return to;
}
void PublishDialog::addItem()
{
mUI.mNameLineEdit->setEnabled( true );
mUI.mEmailLineEdit->setEnabled( true );
QListWidgetItem *item = new QListWidgetItem( mUI.mListWidget );
mUI.mListWidget->addItem( item );
mUI.mListWidget->setItemSelected( item, true );
mUI.mNameLineEdit->setText( i18n( "(EmptyName)" ) );
mUI.mEmailLineEdit->setText( i18n( "(EmptyEmail)" ) );
mUI.mRemove->setEnabled( true );
}
void PublishDialog::removeItem()
{
QListWidgetItem *item;
item = mUI.mListWidget->selectedItems().first();
if ( !item ) {
return;
}
int row = mUI.mListWidget->row( item );
mUI.mListWidget->takeItem( row );
if ( !mUI.mListWidget->count() ) {
mUI.mNameLineEdit->setText( QString() );
mUI.mNameLineEdit->setEnabled( false );
mUI.mEmailLineEdit->setText( QString() );
mUI.mEmailLineEdit->setEnabled( false );
mUI.mRemove->setEnabled( false );
return;
}
if ( row > 0 ) {
row--;
}
mUI.mListWidget->setCurrentRow( row );
}
void PublishDialog::openAddressbook()
{
KABC::Addressee::List addressList = KABC::AddresseeDialog::getAddressees( this );
if( addressList.isEmpty() ) {
return;
}
KABC::Addressee a = addressList.first();
if ( !a.isEmpty() ) {
int i;
for ( i=0; i<addressList.size(); i++ ) {
a = addressList[i];
mUI.mNameLineEdit->setEnabled( true );
mUI.mEmailLineEdit->setEnabled( true );
QListWidgetItem *item = new QListWidgetItem( mUI.mListWidget );
mUI.mListWidget->setItemSelected( item, true );
mUI.mNameLineEdit->setText( a.realName() );
mUI.mEmailLineEdit->setText( a.preferredEmail() );
mUI.mListWidget->addItem( item );
}
mUI.mRemove->setEnabled( true );
}
}
void PublishDialog::updateItem()
{
if ( !mUI.mListWidget->selectedItems().count() ) {
return;
}
Person person( mUI.mNameLineEdit->text(), mUI.mEmailLineEdit->text() );
QListWidgetItem *item = mUI.mListWidget->selectedItems().first();
item->setText( person.fullName() );
}
void PublishDialog::updateInput()
{
if ( !mUI.mListWidget->selectedItems().count() ) {
return;
}
mUI.mNameLineEdit->setEnabled( true );
mUI.mEmailLineEdit->setEnabled( true );
QListWidgetItem *item = mUI.mListWidget->selectedItems().first();
QString mail, name;
KPIMUtils::extractEmailAddressAndName( item->text(), mail, name );
mUI.mNameLineEdit->setText( name );
mUI.mEmailLineEdit->setText( mail );
}
#include "publishdialog.moc"
<commit_msg>Fix crash<commit_after>/*
This file is part of KOrganizer.
Copyright (c) 2001 Cornelius Schumacher <[email protected]>
Copyright (c) 2009 Allen Winter <[email protected]>
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License along
with this program; if not, write to the Free Software Foundation, Inc.,
51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
As a special exception, permission is given to link this program
with any edition of Qt, and distribute the resulting executable,
without including the source code for Qt in the source distribution.
*/
// TODO: validate hand-entered email addresses
// TODO: don't allow duplicates; at least remove dupes when passing back
// TODO: the list in PublishDialog::addresses()
#include "publishdialog.h"
#include <kabc/addresseedialog.h>
#include <kcal/attendee.h>
#include <kcal/person.h>
#include <kpimutils/email.h>
#include <klineedit.h>
#include <klocale.h>
PublishDialog::PublishDialog( QWidget *parent )
: KDialog( parent )
{
setCaption( i18n( "Select Addresses" ) );
setButtons( Ok|Cancel|Help );
setHelp( "group-scheduling", "korganizer" );
QWidget *widget = new QWidget( this );
widget->setObjectName( "PublishFreeBusy" );
mUI.setupUi( widget );
setMainWidget( widget );
mUI.mListWidget->setSelectionMode( QAbstractItemView::SingleSelection );
mUI.mNameLineEdit->setEnabled( false );
mUI.mEmailLineEdit->setEnabled( false );
setButtonToolTip( Ok, i18n( "Send email to these recipients" ) );
setButtonWhatsThis( Ok, i18n( "Clicking the <b>Ok</b> button will cause "
"an email to be sent to the recipients you "
"have entered." ) );
setButtonToolTip( Cancel, i18n( "Cancel recipient selection and the email" ) );
setButtonWhatsThis( Cancel, i18n( "Clicking the <b>Cancel</b> button will "
"cause the email operation to be terminated." ) );
setButtonWhatsThis( Help, i18n( "Click the <b>Help</b> button to read "
"more information about Group Scheduling." ) );
mUI.mNew->setIcon( KIcon( "list-add" ) );
mUI.mRemove->setIcon( KIcon( "list-remove" ) );
mUI.mRemove->setEnabled( false );
mUI.mSelectAddressee->setIcon( KIcon( "view-pim-contacts" ) );
connect( mUI.mListWidget, SIGNAL(itemSelectionChanged()),
SLOT(updateInput()) );
connect( mUI.mNew, SIGNAL(clicked()),
SLOT(addItem()) );
connect( mUI.mRemove, SIGNAL(clicked()),
SLOT(removeItem()) );
connect( mUI.mSelectAddressee, SIGNAL(clicked()),
SLOT(openAddressbook()) );
connect( mUI.mNameLineEdit, SIGNAL(textChanged(const QString &)),
SLOT(updateItem()) );
connect( mUI.mEmailLineEdit, SIGNAL(textChanged(const QString &)),
SLOT(updateItem()) );
}
PublishDialog::~PublishDialog()
{
}
void PublishDialog::addAttendee( Attendee *attendee )
{
mUI.mNameLineEdit->setEnabled( true );
mUI.mEmailLineEdit->setEnabled( true );
QListWidgetItem *item = new QListWidgetItem( mUI.mListWidget );
Person person( attendee->name(), attendee->email() );
item->setText( person.fullName() );
mUI.mListWidget->addItem( item );
mUI.mRemove->setEnabled( true );
}
QString PublishDialog::addresses()
{
QString to = "";
QListWidgetItem *item;
int i, count;
count = mUI.mListWidget->count();
for ( i=0; i<count; ++i ) {
item = mUI.mListWidget->item( i );
to += item->text();
if ( i < count-1 ) {
to += ", ";
}
}
return to;
}
void PublishDialog::addItem()
{
mUI.mNameLineEdit->setEnabled( true );
mUI.mEmailLineEdit->setEnabled( true );
QListWidgetItem *item = new QListWidgetItem( mUI.mListWidget );
mUI.mListWidget->addItem( item );
mUI.mListWidget->setItemSelected( item, true );
mUI.mNameLineEdit->setText( i18n( "(EmptyName)" ) );
mUI.mEmailLineEdit->setText( i18n( "(EmptyEmail)" ) );
mUI.mRemove->setEnabled( true );
}
void PublishDialog::removeItem()
{
QListWidgetItem *item;
item = mUI.mListWidget->selectedItems().first();
if ( !item ) {
return;
}
int row = mUI.mListWidget->row( item );
mUI.mListWidget->takeItem( row );
if ( !mUI.mListWidget->count() ) {
mUI.mNameLineEdit->setText( QString() );
mUI.mNameLineEdit->setEnabled( false );
mUI.mEmailLineEdit->setText( QString() );
mUI.mEmailLineEdit->setEnabled( false );
mUI.mRemove->setEnabled( false );
return;
}
if ( row > 0 ) {
row--;
}
mUI.mListWidget->setCurrentRow( row );
}
void PublishDialog::openAddressbook()
{
KABC::Addressee::List addressList = KABC::AddresseeDialog::getAddressees( this );
if( addressList.isEmpty() ) {
return;
}
KABC::Addressee a = addressList.first();
if ( !a.isEmpty() ) {
int i;
for ( i=0; i<addressList.size(); i++ ) {
a = addressList[i];
mUI.mNameLineEdit->setEnabled( true );
mUI.mEmailLineEdit->setEnabled( true );
QListWidgetItem *item = new QListWidgetItem( mUI.mListWidget );
mUI.mListWidget->setItemSelected( item, true );
mUI.mNameLineEdit->setText( a.realName() );
mUI.mEmailLineEdit->setText( a.preferredEmail() );
mUI.mListWidget->addItem( item );
}
mUI.mRemove->setEnabled( true );
}
}
void PublishDialog::updateItem()
{
if ( !mUI.mListWidget->selectedItems().count() ) {
return;
}
Person person( mUI.mNameLineEdit->text(), mUI.mEmailLineEdit->text() );
QListWidgetItem *item = mUI.mListWidget->selectedItems().first();
item->setText( person.fullName() );
}
void PublishDialog::updateInput()
{
if ( !mUI.mListWidget->selectedItems().count() ) {
return;
}
mUI.mNameLineEdit->setEnabled( true );
mUI.mEmailLineEdit->setEnabled( true );
QListWidgetItem *item = mUI.mListWidget->selectedItems().first();
QString mail, name;
KPIMUtils::extractEmailAddressAndName( item->text(), mail, name );
mUI.mNameLineEdit->setText( name );
mUI.mEmailLineEdit->setText( mail );
}
#include "publishdialog.moc"
<|endoftext|> |
<commit_before>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: urp_dispatch.cxx,v $
*
* $Revision: 1.15 $
*
* last change: $Author: obo $ $Date: 2006-09-16 16:00:48 $
*
* 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_bridges.hxx"
#include <sal/alloca.h>
#include <osl/mutex.hxx>
#include <osl/diagnose.h>
#include <rtl/alloc.h>
#include <rtl/ustrbuf.hxx>
#include <uno/mapping.hxx>
#include <uno/threadpool.h>
#include <bridges/remote/remote.h>
#include <bridges/remote/stub.hxx>
#include <bridges/remote/proxy.hxx>
#include <bridges/remote/remote.hxx>
#include "urp_bridgeimpl.hxx"
#include "urp_marshal.hxx"
#include "urp_dispatch.hxx"
#include "urp_job.hxx"
#include "urp_writer.hxx"
#include "urp_log.hxx"
using namespace ::rtl;
using namespace ::osl;
using namespace ::com::sun::star::uno;
namespace bridges_urp
{
void SAL_CALL urp_sendCloseConnection( uno_Environment *pEnvRemote )
{
remote_Context *pContext = (remote_Context *) pEnvRemote->pContext;
urp_BridgeImpl *pImpl = (urp_BridgeImpl*) ( pContext->m_pBridgeImpl );
{
MutexGuard guard( pImpl->m_marshalingMutex );
// send immediately
if( ! pImpl->m_blockMarshaler.empty() )
{
pImpl->m_pWriter->touch( sal_True );
}
pImpl->m_pWriter->sendEmptyMessage();
// no more data via this connection !
pImpl->m_pWriter->abort();
}
}
extern "C" void SAL_CALL urp_sendRequest(
uno_Environment *pEnvRemote,
typelib_TypeDescription const * pMemberType,
rtl_uString *pOid,
typelib_InterfaceTypeDescription *pInterfaceType,
void *pReturn,
void *ppArgs[],
uno_Any **ppException )
{
remote_Context *pContext = (remote_Context *) pEnvRemote->pContext;
urp_BridgeImpl *pImpl = (urp_BridgeImpl*) ( pContext->m_pBridgeImpl );
ClientJob job(pEnvRemote, pImpl, pOid, pMemberType, pInterfaceType, pReturn, ppArgs, ppException);
if( job.pack() && ! job.isOneway() )
{
job.wait();
}
}
}
<commit_msg>INTEGRATION: CWS sb23 (1.12.38); FILE MERGED 2006/11/07 08:30:32 sb 1.12.38.5: RESYNC: (1.14-1.15); FILE MERGED 2006/08/21 07:36:41 sb 1.12.38.4: #88601# Made code warning-free. 2006/08/18 16:01:06 sb 1.12.38.3: RESYNC: (1.12-1.14); FILE MERGED 2005/03/23 14:44:29 sb 1.12.38.2: #88601# Ensure that negotiating current context support is finished before any requests are sent. 2005/03/23 14:21:44 sb 1.12.38.1: #88601# Support for current context in binary UNO URP bridge.<commit_after>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: urp_dispatch.cxx,v $
*
* $Revision: 1.16 $
*
* last change: $Author: rt $ $Date: 2006-12-01 14:47:22 $
*
* 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_bridges.hxx"
#include <sal/alloca.h>
#include <osl/mutex.hxx>
#include <osl/diagnose.h>
#include <rtl/alloc.h>
#include <rtl/ustrbuf.hxx>
#include <uno/mapping.hxx>
#include <uno/threadpool.h>
#include <bridges/remote/remote.h>
#include <bridges/remote/stub.hxx>
#include <bridges/remote/proxy.hxx>
#include <bridges/remote/remote.hxx>
#include "urp_bridgeimpl.hxx"
#include "urp_marshal.hxx"
#include "urp_dispatch.hxx"
#include "urp_job.hxx"
#include "urp_writer.hxx"
#include "urp_log.hxx"
using namespace ::rtl;
using namespace ::osl;
using namespace ::com::sun::star::uno;
namespace bridges_urp
{
void SAL_CALL urp_sendCloseConnection( uno_Environment *pEnvRemote )
{
remote_Context *pContext = (remote_Context *) pEnvRemote->pContext;
urp_BridgeImpl *pImpl = (urp_BridgeImpl*) ( pContext->m_pBridgeImpl );
{
MutexGuard guard( pImpl->m_marshalingMutex );
// send immediately
if( ! pImpl->m_blockMarshaler.empty() )
{
pImpl->m_pWriter->touch( sal_True );
}
pImpl->m_pWriter->sendEmptyMessage();
// no more data via this connection !
pImpl->m_pWriter->abort();
}
}
extern "C" void SAL_CALL urp_sendRequest(
uno_Environment *pEnvRemote,
typelib_TypeDescription const * pMemberType,
rtl_uString *pOid,
typelib_InterfaceTypeDescription *pInterfaceType,
void *pReturn,
void *ppArgs[],
uno_Any **ppException )
{
remote_Context *pContext = (remote_Context *) pEnvRemote->pContext;
urp_BridgeImpl *pImpl = (urp_BridgeImpl*) ( pContext->m_pBridgeImpl );
pImpl->m_initialized.wait();
urp_sendRequest_internal(
pEnvRemote, pMemberType, pOid, pInterfaceType, pReturn, ppArgs,
ppException );
}
void SAL_CALL urp_sendRequest_internal(
uno_Environment *pEnvRemote,
typelib_TypeDescription const * pMemberType,
rtl_uString *pOid,
typelib_InterfaceTypeDescription *pInterfaceType,
void *pReturn,
void *ppArgs[],
uno_Any **ppException )
{
remote_Context *pContext = (remote_Context *) pEnvRemote->pContext;
urp_BridgeImpl *pImpl = (urp_BridgeImpl*) ( pContext->m_pBridgeImpl );
ClientJob job(
pEnvRemote, pContext, pImpl, pOid, pMemberType, pInterfaceType, pReturn,
ppArgs, ppException);
if( job.pack() && ! job.isOneway() )
{
job.wait();
}
}
}
<|endoftext|> |
<commit_before>#include "SDL.h"
#include "SDL_image.h"
#include <iostream>
#include <assert.h>
#include "shared/path_creator.hpp"
#include "shared/tdmap.hpp"
#include "shared/sizes.h"
#include <map>
#include <cmath>
#include <set>
#include <boost/foreach.hpp>
#include "graphics/graphics_path.hpp"
using namespace std;
class GUI
{
private:
void logSDLError(std::ostream &os, const std::string &msg)
{
os << msg << " error: " << SDL_GetError() << std::endl;
}
std::map<std::string, SDL_Texture *> loaded_textures;
std::string resPath;
SDL_Texture* loadTexture(const std::string &file, SDL_Renderer *ren)
{
SDL_Texture *texture;
if(loaded_textures.find(file) != loaded_textures.end())
{
texture = loaded_textures[file];
}
else
{
texture = IMG_LoadTexture(ren, (resPath + file).c_str());
if (texture == nullptr)
{
logSDLError(std::cout, "LoadTexture");
}
loaded_textures[file] = texture;
}
return texture;
}
/**
* Draw an SDL_Texture to an SDL_Renderer at position x, y, preserving
* the texture's width and height
* @param tex The source texture we want to draw
* @param ren The renderer we want to draw to
* @param x The x Coordinate to draw to
* @param y The y Coordinate to draw to
*/
void renderTexture(SDL_Texture *tex, SDL_Renderer *ren, int x, int y, int rw, int rh)
{
//Setup the destination rectangle to be at the position we want
SDL_Rect dst;
dst.x = x;
dst.y = y;
dst.w = rw;
dst.h = rh;
SDL_RenderCopy(ren, tex, NULL, &dst);
}
int row_width;
int row_height;
SDL_Renderer * ren;
Path * main_path;
int numrows;
int numcols;
Coordinate screen_to_game_coord(Coordinate c)
{
return Coordinate(c.x / row_width, c.y / row_height);
}
void re_render()
{
std::set<Coordinate> s( diff_coords.begin(), diff_coords.end() );
diff_coords.assign( diff_coords.begin(), diff_coords.end() );
BOOST_FOREACH(Coordinate &screen_cord, diff_coords)
{
Coordinate game_coord = screen_to_game_coord(screen_cord);
renderTexture(background, ren, screen_cord.x, screen_cord.y, row_width, row_height);
if(main_path->in(game_coord.x, game_coord.y))
{
renderTexture(tile, ren, screen_cord.x, screen_cord.y, row_width, row_height);
}
Tower * tower = map->get_tower_at(game_coord);
if(tower != nullptr)
{
SDL_Texture * texture = loadTexture(tower->get_image_string(), ren);
if(texture != nullptr)
{
renderTexture(texture, ren, screen_cord.x, screen_cord.y, row_width, row_height);
}
}
}
}
void fill_screen_tiles()
{
for(int i = 0; i < numrows; i++)
{
for(int j = 0; j < numcols; j++)
{
Coordinate screen_cord = game_to_screen_coord(Coordinate(i, j));
renderTexture(background, ren, screen_cord.x, screen_cord.y, row_width, row_height);
if(main_path->in(i, j))
{
renderTexture(tile, ren, screen_cord.x, screen_cord.y, row_width, row_height);
}
Tower * tower = map->get_tower_at(i, j);
if(tower != nullptr)
{
SDL_Texture * texture = loadTexture(tower->get_image_string(), ren);
Coordinate current_cord = game_to_screen_coord(Coordinate(i, j));
if(texture != nullptr)
{
renderTexture(texture, ren, current_cord.x, current_cord.y, row_width, row_height);
}
}
}
}
}
TDMap * map;
int current_anim_frame;
SDL_Texture * tile;
SDL_Texture * background;
public:
GUI(int rows, int columns, Path * path, TDMap * map)
{
assert(rows > 0 && columns > 0 && path != nullptr && map != nullptr);
current_anim_frame = 0;
row_width = DEFAULT_WIDTH/rows;
row_height = DEFAULT_HEIGHT/columns;
resPath = GRAPHICS_PATH;
numrows = rows;
numcols = columns;
this->map = map;
SDL_Window *win;
main_path = path;
if (SDL_Init(SDL_INIT_EVERYTHING) != 0)
{
logSDLError(std::cout, "SDL_Init");
exit(1);
}
win = SDL_CreateWindow("Tower Defense",
SDL_WINDOWPOS_UNDEFINED, SDL_WINDOWPOS_UNDEFINED, DEFAULT_WIDTH, DEFAULT_HEIGHT, SDL_WINDOW_SHOWN | SDL_WINDOW_ALLOW_HIGHDPI);
if (win == nullptr)
{
logSDLError(std::cout, "CreateWindow");
SDL_Quit();
exit(1);
}
ren = SDL_CreateRenderer(win, -1, SDL_RENDERER_ACCELERATED | SDL_RENDERER_PRESENTVSYNC);
if (ren == nullptr)
{
logSDLError(std::cout, "CreateRenderer");
//TODO free window
SDL_Quit();
exit(1);
}
background = loadTexture("grass.png", ren);
tile = loadTexture("tile.png", ren);
if (background == nullptr || tile == nullptr)
{
logSDLError(std::cout, "Getting Images");
//TODO cleanup
SDL_Quit();
exit(1);
}
fill_screen_tiles();
SDL_RenderPresent(ren);
SDL_Delay(1000);
}
typedef std::pair<std::pair<SDL_Texture *, Coordinate> , std::pair<Coordinate, Coordinate>> anim_type;
std::vector<anim_type> animations;
std::vector<Coordinate> diff_coords;
// takes pixel coords.
// pls take care while using.
void set_up_animation(SDL_Texture * texture, Coordinate from, Coordinate to, bool addToDiff)
{
animations.push_back(anim_type(std::make_pair(texture, from), std::make_pair(from, to)));
diff_coords.push_back(from);
diff_coords.push_back(to);
}
void clear_attack_animations()
{
animations.clear();
}
bool show_animations()
{
re_render();
BOOST_FOREACH(anim_type & animation, animations)
{
SDL_Texture * tex = animation.first.first;
auto from_to = animation.second;
int hdiff = from_to.second.x - from_to.first.x;
int vdiff = from_to.second.y - from_to.first.y;
hdiff = hdiff/ANIMATION_CONSTANT;
vdiff = vdiff/ANIMATION_CONSTANT;
int extra_x = hdiff == 0 ? 0 : hdiff/std::abs(hdiff);
int extra_y = vdiff == 0 ? 0 : vdiff/std::abs(vdiff);
Coordinate game_coord = screen_to_game_coord(animation.first.second);
Coordinate new_game_coord = Coordinate(game_coord.x + extra_x, game_coord.y + extra_y);
Coordinate new_game_coord2 = Coordinate(game_coord.x, game_coord.y + extra_y);
Coordinate new_game_coord3 = Coordinate(game_coord.x + extra_x, game_coord.y);
diff_coords.push_back(game_to_screen_coord(new_game_coord));
diff_coords.push_back(game_to_screen_coord(new_game_coord2));
diff_coords.push_back(game_to_screen_coord(new_game_coord3));
animation.first.second.x += hdiff;
animation.first.second.y += vdiff;
renderTexture(tex, ren, animation.first.second.x, animation.first.second.y, row_width, row_height);
}
if(++current_anim_frame < ANIMATION_CONSTANT)
{
SDL_Delay(10);
return false;
}
return true;
}
void Update()
{
current_anim_frame = 0;
for(int i = 0; i < NUM_ROWS; i++)
{
for(int j = 0; j < NUM_COLS; j++)
{
Tower * tower = map->get_tower_at(i, j);
if(tower != nullptr)
{
Coordinate current_cord = game_to_screen_coord(Coordinate(i, j));
SDL_Texture * attack_texture = loadTexture(tower->get_attack_image_string(), ren);
BOOST_FOREACH(Coordinate c, tower->get_attack_tiles())
{
Coordinate screen_cord = game_to_screen_coord(c);
set_up_animation(attack_texture, current_cord, screen_cord, true);
}
}
BOOST_FOREACH(Sprite * s, map->get_sprites_at(i,j))
{
SDL_Texture * sprite_texture = loadTexture(s->image_string, ren);
Coordinate previous_cord = game_to_screen_coord(s->get_previous_position());
set_up_animation(sprite_texture, previous_cord, game_to_screen_coord(s->get_coordinate()), true);
}
}
}
while(!show_animations())
{
SDL_RenderPresent(ren);
}
re_render();
SDL_Delay(300);
SDL_RenderPresent(ren);
clear_attack_animations();
}
Coordinate game_to_screen_coord(Coordinate game_coord)
{
return Coordinate(game_coord.x * row_width, game_coord.y * row_height);
}
Coordinate game_to_screen_coord(int x, int y)
{
return game_to_screen_coord(Coordinate(x, y));
}
};
<commit_msg>fixing indents<commit_after>#include "SDL.h"
#include "SDL_image.h"
#include <iostream>
#include <assert.h>
#include "shared/path_creator.hpp"
#include "shared/tdmap.hpp"
#include "shared/sizes.h"
#include <map>
#include <cmath>
#include <set>
#include <boost/foreach.hpp>
#include "graphics/graphics_path.hpp"
using namespace std;
class GUI
{
private:
void logSDLError(std::ostream &os, const std::string &msg)
{
os << msg << " error: " << SDL_GetError() << std::endl;
}
std::map<std::string, SDL_Texture *> loaded_textures;
std::string resPath;
SDL_Texture* loadTexture(const std::string &file, SDL_Renderer *ren)
{
SDL_Texture *texture;
if(loaded_textures.find(file) != loaded_textures.end())
{
texture = loaded_textures[file];
}
else
{
texture = IMG_LoadTexture(ren, (resPath + file).c_str());
if (texture == nullptr)
{
logSDLError(std::cout, "LoadTexture");
}
loaded_textures[file] = texture;
}
return texture;
}
/**
* Draw an SDL_Texture to an SDL_Renderer at position x, y, preserving
* the texture's width and height
* @param tex The source texture we want to draw
* @param ren The renderer we want to draw to
* @param x The x Coordinate to draw to
* @param y The y Coordinate to draw to
*/
void renderTexture(SDL_Texture *tex, SDL_Renderer *ren, int x, int y, int rw, int rh)
{
//Setup the destination rectangle to be at the position we want
SDL_Rect dst;
dst.x = x;
dst.y = y;
dst.w = rw;
dst.h = rh;
SDL_RenderCopy(ren, tex, NULL, &dst);
}
int row_width;
int row_height;
SDL_Renderer * ren;
Path * main_path;
int numrows;
int numcols;
Coordinate screen_to_game_coord(Coordinate c)
{
return Coordinate(c.x / row_width, c.y / row_height);
}
void re_render()
{
std::set<Coordinate> s( diff_coords.begin(), diff_coords.end() );
diff_coords.assign( diff_coords.begin(), diff_coords.end() );
BOOST_FOREACH(Coordinate &screen_cord, diff_coords)
{
Coordinate game_coord = screen_to_game_coord(screen_cord);
renderTexture(background, ren, screen_cord.x, screen_cord.y, row_width, row_height);
if(main_path->in(game_coord.x, game_coord.y))
{
renderTexture(tile, ren, screen_cord.x, screen_cord.y, row_width, row_height);
}
Tower * tower = map->get_tower_at(game_coord);
if(tower != nullptr)
{
SDL_Texture * texture = loadTexture(tower->get_image_string(), ren);
if(texture != nullptr)
{
renderTexture(texture, ren, screen_cord.x, screen_cord.y, row_width, row_height);
}
}
}
}
void fill_screen_tiles()
{
for(int i = 0; i < numrows; i++)
{
for(int j = 0; j < numcols; j++)
{
Coordinate screen_cord = game_to_screen_coord(Coordinate(i, j));
renderTexture(background, ren, screen_cord.x, screen_cord.y, row_width, row_height);
if(main_path->in(i, j))
{
renderTexture(tile, ren, screen_cord.x, screen_cord.y, row_width, row_height);
}
Tower * tower = map->get_tower_at(i, j);
if(tower != nullptr)
{
SDL_Texture * texture = loadTexture(tower->get_image_string(), ren);
Coordinate current_cord = game_to_screen_coord(Coordinate(i, j));
if(texture != nullptr)
{
renderTexture(texture, ren, current_cord.x, current_cord.y, row_width, row_height);
}
}
}
}
}
TDMap * map;
int current_anim_frame;
SDL_Texture * tile;
SDL_Texture * background;
public:
GUI(int rows, int columns, Path * path, TDMap * map)
{
assert(rows > 0 && columns > 0 && path != nullptr && map != nullptr);
current_anim_frame = 0;
row_width = DEFAULT_WIDTH/rows;
row_height = DEFAULT_HEIGHT/columns;
resPath = GRAPHICS_PATH;
numrows = rows;
numcols = columns;
this->map = map;
SDL_Window *win;
main_path = path;
if (SDL_Init(SDL_INIT_EVERYTHING) != 0)
{
logSDLError(std::cout, "SDL_Init");
exit(1);
}
win = SDL_CreateWindow("Tower Defense",
SDL_WINDOWPOS_UNDEFINED, SDL_WINDOWPOS_UNDEFINED, DEFAULT_WIDTH, DEFAULT_HEIGHT, SDL_WINDOW_SHOWN | SDL_WINDOW_ALLOW_HIGHDPI);
if (win == nullptr)
{
logSDLError(std::cout, "CreateWindow");
SDL_Quit();
exit(1);
}
ren = SDL_CreateRenderer(win, -1, SDL_RENDERER_ACCELERATED | SDL_RENDERER_PRESENTVSYNC);
if (ren == nullptr)
{
logSDLError(std::cout, "CreateRenderer");
//TODO free window
SDL_Quit();
exit(1);
}
background = loadTexture("grass.png", ren);
tile = loadTexture("tile.png", ren);
if (background == nullptr || tile == nullptr)
{
logSDLError(std::cout, "Getting Images");
//TODO cleanup
SDL_Quit();
exit(1);
}
fill_screen_tiles();
SDL_RenderPresent(ren);
SDL_Delay(1000);
}
typedef std::pair<std::pair<SDL_Texture *, Coordinate> , std::pair<Coordinate, Coordinate>> anim_type;
std::vector<anim_type> animations;
std::vector<Coordinate> diff_coords;
// takes pixel coords.
// pls take care while using.
void set_up_animation(SDL_Texture * texture, Coordinate from, Coordinate to, bool addToDiff)
{
animations.push_back(anim_type(std::make_pair(texture, from), std::make_pair(from, to)));
diff_coords.push_back(from);
diff_coords.push_back(to);
}
void clear_attack_animations()
{
animations.clear();
}
bool show_animations()
{
re_render();
BOOST_FOREACH(anim_type & animation, animations)
{
SDL_Texture * tex = animation.first.first;
auto from_to = animation.second;
int hdiff = from_to.second.x - from_to.first.x;
int vdiff = from_to.second.y - from_to.first.y;
hdiff = hdiff/ANIMATION_CONSTANT;
vdiff = vdiff/ANIMATION_CONSTANT;
int extra_x = hdiff == 0 ? 0 : hdiff/std::abs(hdiff);
int extra_y = vdiff == 0 ? 0 : vdiff/std::abs(vdiff);
Coordinate game_coord = screen_to_game_coord(animation.first.second);
Coordinate new_game_coord = Coordinate(game_coord.x + extra_x, game_coord.y + extra_y);
Coordinate new_game_coord2 = Coordinate(game_coord.x, game_coord.y + extra_y);
Coordinate new_game_coord3 = Coordinate(game_coord.x + extra_x, game_coord.y);
diff_coords.push_back(game_to_screen_coord(new_game_coord));
diff_coords.push_back(game_to_screen_coord(new_game_coord2));
diff_coords.push_back(game_to_screen_coord(new_game_coord3));
animation.first.second.x += hdiff;
animation.first.second.y += vdiff;
renderTexture(tex, ren, animation.first.second.x, animation.first.second.y, row_width, row_height);
}
if(++current_anim_frame < ANIMATION_CONSTANT)
{
SDL_Delay(10);
return false;
}
return true;
}
void Update()
{
current_anim_frame = 0;
for(int i = 0; i < NUM_ROWS; i++)
{
for(int j = 0; j < NUM_COLS; j++)
{
Tower * tower = map->get_tower_at(i, j);
if(tower != nullptr)
{
Coordinate current_cord = game_to_screen_coord(Coordinate(i, j));
SDL_Texture * attack_texture = loadTexture(tower->get_attack_image_string(), ren);
BOOST_FOREACH(Coordinate c, tower->get_attack_tiles())
{
Coordinate screen_cord = game_to_screen_coord(c);
set_up_animation(attack_texture, current_cord, screen_cord, true);
}
}
BOOST_FOREACH(Sprite * s, map->get_sprites_at(i,j))
{
SDL_Texture * sprite_texture = loadTexture(s->image_string, ren);
Coordinate previous_cord = game_to_screen_coord(s->get_previous_position());
set_up_animation(sprite_texture, previous_cord, game_to_screen_coord(s->get_coordinate()), true);
}
}
}
while(!show_animations())
{
SDL_RenderPresent(ren);
}
re_render();
SDL_Delay(300);
SDL_RenderPresent(ren);
clear_attack_animations();
}
Coordinate game_to_screen_coord(Coordinate game_coord)
{
return Coordinate(game_coord.x * row_width, game_coord.y * row_height);
}
Coordinate game_to_screen_coord(int x, int y)
{
return game_to_screen_coord(Coordinate(x, y));
}
};
<|endoftext|> |
<commit_before>/*
* Copyright 2008-2010 NVIDIA Corporation
*
* 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.
*/
/*! \file scan.inl
* \brief Inline file for scan.h.
*/
#include <thrust/detail/config.h>
#include <thrust/detail/device/cuda/dispatch/scan.h>
#include <thrust/detail/static_assert.h>
namespace thrust
{
namespace detail
{
namespace device
{
namespace cuda
{
template<typename InputIterator,
typename OutputIterator,
typename AssociativeOperator>
OutputIterator inclusive_scan(InputIterator first,
InputIterator last,
OutputIterator result,
AssociativeOperator binary_op)
{
// we're attempting to launch a kernel, assert we're compiling with nvcc
// ========================================================================
// X Note to the user: If you've found this line due to a compiler error, X
// X you need to compile your code using nvcc, rather than g++ or cl.exe X
// ========================================================================
THRUST_STATIC_ASSERT( (depend_on_instantiation<InputIterator, THRUST_DEVICE_COMPILER == THRUST_DEVICE_COMPILER_NVCC>::value) );
typedef typename thrust::iterator_value<OutputIterator>::type OutputType;
// whether to use fast_scan or safe_scan
// TODO profile this threshold
#if THRUST_DEVICE_COMPILER == THRUST_DEVICE_COMPILER_NVCC && CUDA_VERSION >= 3010
// CUDA 3.1 and higher support non-pod types in statically-allocated __shared__ memory
static const bool use_fast_scan = sizeof(OutputType) <= 16;
#else
// CUDA 3.0 and earlier must use safe_scan for non-pod types
static const bool use_fast_scan = sizeof(OutputType) <= 16 && thrust::detail::is_pod<OutputType>::value;
#endif
// XXX WAR nvcc unused variable warning
(void) use_fast_scan;
return thrust::detail::device::cuda::dispatch::inclusive_scan
(first, last, result, binary_op,
thrust::detail::integral_constant<bool, use_fast_scan>());
}
template<typename InputIterator,
typename OutputIterator,
typename T,
typename AssociativeOperator>
OutputIterator exclusive_scan(InputIterator first,
InputIterator last,
OutputIterator result,
T init,
AssociativeOperator binary_op)
{
// we're attempting to launch a kernel, assert we're compiling with nvcc
// ========================================================================
// X Note to the user: If you've found this line due to a compiler error, X
// X you need to compile your code using nvcc, rather than g++ or cl.exe X
// ========================================================================
THRUST_STATIC_ASSERT( (depend_on_instantiation<InputIterator, THRUST_DEVICE_COMPILER == THRUST_DEVICE_COMPILER_NVCC>::value) );
typedef typename thrust::iterator_value<OutputIterator>::type OutputType;
// whether to use fast_scan or safe_scan
// TODO profile this threshold
#if THRUST_DEVICE_COMPILER == THRUST_DEVICE_COMPILER_NVCC && CUDA_VERSION >= 3010
// CUDA 3.1 and higher support non-pod types in statically-allocated __shared__ memory
static const bool use_fast_scan = sizeof(OutputType) <= 16;
#else
// CUDA 3.0 and earlier must use safe_scan for non-pod types
static const bool use_fast_scan = sizeof(OutputType) <= 16 && thrust::detail::is_pod<OutputType>::value;
#endif
// XXX WAR nvcc 3.0 unused variable warning
(void) use_fast_scan;
return thrust::detail::device::cuda::dispatch::exclusive_scan
(first, last, result, init, binary_op,
thrust::detail::integral_constant<bool, use_fast_scan>());
}
} // end namespace cuda
} // end namespace device
} // end namespace detail
} // end namespace thrust
<commit_msg>revert to Thrust v1.2 fast_scan/safe_scan dispatch<commit_after>/*
* Copyright 2008-2010 NVIDIA Corporation
*
* 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.
*/
/*! \file scan.inl
* \brief Inline file for scan.h.
*/
#include <thrust/detail/config.h>
#include <thrust/detail/device/cuda/dispatch/scan.h>
#include <thrust/detail/static_assert.h>
namespace thrust
{
namespace detail
{
namespace device
{
namespace cuda
{
template<typename InputIterator,
typename OutputIterator,
typename AssociativeOperator>
OutputIterator inclusive_scan(InputIterator first,
InputIterator last,
OutputIterator result,
AssociativeOperator binary_op)
{
// we're attempting to launch a kernel, assert we're compiling with nvcc
// ========================================================================
// X Note to the user: If you've found this line due to a compiler error, X
// X you need to compile your code using nvcc, rather than g++ or cl.exe X
// ========================================================================
THRUST_STATIC_ASSERT( (depend_on_instantiation<InputIterator, THRUST_DEVICE_COMPILER == THRUST_DEVICE_COMPILER_NVCC>::value) );
typedef typename thrust::iterator_value<OutputIterator>::type OutputType;
// whether to use fast_scan or safe_scan
// TODO profile this threshold
//#if THRUST_DEVICE_COMPILER == THRUST_DEVICE_COMPILER_NVCC && CUDA_VERSION >= 3010
// // CUDA 3.1 and higher support non-pod types in statically-allocated __shared__ memory
// static const bool use_fast_scan = sizeof(OutputType) <= 16;
//#else
// // CUDA 3.0 and earlier must use safe_scan for non-pod types
static const bool use_fast_scan = sizeof(OutputType) <= 16 && thrust::detail::is_pod<OutputType>::value;
//#endif
// XXX WAR nvcc unused variable warning
(void) use_fast_scan;
return thrust::detail::device::cuda::dispatch::inclusive_scan
(first, last, result, binary_op,
thrust::detail::integral_constant<bool, use_fast_scan>());
}
template<typename InputIterator,
typename OutputIterator,
typename T,
typename AssociativeOperator>
OutputIterator exclusive_scan(InputIterator first,
InputIterator last,
OutputIterator result,
T init,
AssociativeOperator binary_op)
{
// we're attempting to launch a kernel, assert we're compiling with nvcc
// ========================================================================
// X Note to the user: If you've found this line due to a compiler error, X
// X you need to compile your code using nvcc, rather than g++ or cl.exe X
// ========================================================================
THRUST_STATIC_ASSERT( (depend_on_instantiation<InputIterator, THRUST_DEVICE_COMPILER == THRUST_DEVICE_COMPILER_NVCC>::value) );
typedef typename thrust::iterator_value<OutputIterator>::type OutputType;
// whether to use fast_scan or safe_scan
// TODO profile this threshold
//#if THRUST_DEVICE_COMPILER == THRUST_DEVICE_COMPILER_NVCC && CUDA_VERSION >= 3010
// // CUDA 3.1 and higher support non-pod types in statically-allocated __shared__ memory
// static const bool use_fast_scan = sizeof(OutputType) <= 16;
//#else
// // CUDA 3.0 and earlier must use safe_scan for non-pod types
static const bool use_fast_scan = sizeof(OutputType) <= 16 && thrust::detail::is_pod<OutputType>::value;
//#endif
// XXX WAR nvcc 3.0 unused variable warning
(void) use_fast_scan;
return thrust::detail::device::cuda::dispatch::exclusive_scan
(first, last, result, init, binary_op,
thrust::detail::integral_constant<bool, use_fast_scan>());
}
} // end namespace cuda
} // end namespace device
} // end namespace detail
} // end namespace thrust
<|endoftext|> |
<commit_before>/*
* Copyright (C) 2005-2006 Tommi Maekitalo
*
* 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.
*
* As a special exception, you may use this file as part of a free
* software library without restriction. Specifically, if other files
* instantiate templates or use macros or inline functions from this
* file, or you compile this file and link it with other files to
* produce an executable, this file does not by itself cause the
* resulting executable to be covered by the GNU General Public
* License. This exception does not however invalidate any other
* reasons why the executable file might be covered by the GNU Library
* General Public License.
*
* 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
*/
#include "tnt/poller.h"
#include "tnt/pollerimpl.h"
#include "tnt/tntnet.h"
#include <cxxtools/syserror.h>
#include <cxxtools/log.h>
#include <ios>
#include <unistd.h>
#include <fcntl.h>
#ifdef WITH_EPOLL
#include <sys/epoll.h>
#include <errno.h>
#endif
log_define("tntnet.poller")
namespace tnt
{
PollerIf::~PollerIf()
{ }
Poller::Poller(Jobqueue& q)
: impl(new PollerImpl(q))
{ }
void Poller::run()
{
impl->run();
}
#ifdef WITH_EPOLL
PollerImpl::PollerImpl(Jobqueue& q)
: queue(q),
pollFd(-1)
{
pollFd = ::epoll_create(256);
if (pollFd < 0)
throw cxxtools::SystemError("epoll_create");
fcntl(notify_pipe.getReadFd(), F_SETFL, O_NONBLOCK);
addFd(notify_pipe.getReadFd());
}
PollerImpl::~PollerImpl()
{
close(pollFd);
}
void PollerImpl::addFd(int fd)
{
log_debug("addFd(" << fd << ')');
epoll_event e;
e.events = EPOLLIN;
e.data.fd = fd;
int ret = ::epoll_ctl(pollFd, EPOLL_CTL_ADD, fd, &e);
if (ret < 0)
throw cxxtools::SystemError("epoll_ctl(EPOLL_CTL_ADD)");
}
bool PollerImpl::removeFd(int fd)
{
log_debug("removeFd(" << fd << ')');
epoll_event e;
e.data.fd = fd;
int ret = ::epoll_ctl(pollFd, EPOLL_CTL_DEL, fd, &e);
if (ret < 0)
{
if (errno == EBADF || errno == ENOENT)
{
log_debug("fd " << fd << " couldn't be removed");
return false;
}
else
throw cxxtools::SystemError("epoll_ctl(EPOLL_CTL_DEL)");
}
return true;
}
void PollerImpl::doStop()
{
log_debug("notify stop");
notify_pipe.write('A');
}
void PollerImpl::addIdleJob(Jobqueue::JobPtr job)
{
log_debug("addIdleJob " << job->getFd());
{
cxxtools::MutexLock lock(mutex);
new_jobs.insert(job);
notify_pipe.write('A');
}
log_debug("addIdleJob ready");
}
void PollerImpl::append_new_jobs()
{
cxxtools::MutexLock lock(mutex);
if (!new_jobs.empty())
{
// append new jobs to current
log_debug("add " << new_jobs.size() << " new jobs to poll-list");
time_t currentTime;
time(¤tTime);
for (new_jobs_type::iterator it = new_jobs.begin();
it != new_jobs.end(); ++it)
{
addFd((*it)->getFd());
jobs[(*it)->getFd()] = *it;
int msec;
if (poll_timeout < 0)
poll_timeout = (*it)->msecToTimeout(currentTime);
else if ((msec = (*it)->msecToTimeout(currentTime)) < poll_timeout)
poll_timeout = msec;
}
new_jobs.clear();
}
}
void PollerImpl::run()
{
epoll_event events[16];
time_t pollTime;
time(&pollTime);
while (!Tntnet::shouldStop())
{
usleep(100);
append_new_jobs();
if (jobs.size() == 0)
poll_timeout = -1;
log_debug("epoll_wait with timeout " << poll_timeout << " ms");
int ret = ::epoll_wait(pollFd, events, 16, poll_timeout);
if (ret < 0)
{
if (errno != EINTR)
throw cxxtools::SystemError("epoll_wait");
}
else if (ret == 0)
{
// timeout reached - check for timed out requests and get next timeout
log_debug("timeout reached");
poll_timeout = -1;
time_t currentTime;
time(¤tTime);
for (jobs_type::iterator it = jobs.begin(); it != jobs.end(); )
{
int msec = it->second->msecToTimeout(currentTime);
if (msec <= 0)
{
log_debug("keep-alive-timeout reached");
jobs_type::iterator it2 = it++;
jobs.erase(it2);
}
else
{
if (poll_timeout < 0 || msec < poll_timeout)
poll_timeout = msec;
++it;
}
}
}
else
{
time_t currentTime;
time(¤tTime);
poll_timeout -= (currentTime - pollTime) * 1000;
if (poll_timeout <= 0)
poll_timeout = 100;
pollTime = currentTime;
// no timeout - process events
log_debug(ret << " events occured");
bool rebuildPollFd = false;
for (int i = 0; i < ret; ++i)
{
if (events[i].data.fd == notify_pipe.getReadFd())
{
if (Tntnet::shouldStop())
{
log_info("stop poller");
break;
}
log_debug("read notify-pipe");
char buffer[64];
ssize_t n = notify_pipe.read(buffer, sizeof(buffer));
log_debug("read returns " << n);
}
else
{
jobs_type::iterator it = jobs.find(events[i].data.fd);
if (it == jobs.end())
{
log_fatal("internal error: job for fd " << events[i].data.fd << " not found in jobs-list");
::close(events[i].data.fd);
rebuildPollFd = true;
}
else
{
Jobqueue::JobPtr j = it->second;
int ev = events[i].events;
jobs.erase(it);
if (!removeFd(events[i].data.fd))
rebuildPollFd = true;
if (ev & EPOLLIN)
{
log_debug("put fd " << it->first << " back in queue");
queue.put(j);
}
else
{
log_debug("remove fd " << it->first << " from queue");
}
}
}
}
if (rebuildPollFd)
{
// rebuild poll-structure
log_warn("need to rebuild poll structure");
close(pollFd);
pollFd = ::epoll_create(256);
if (pollFd < 0)
throw cxxtools::SystemError("epoll_create");
int ret = fcntl(notify_pipe.getReadFd(), F_SETFL, O_NONBLOCK);
if (ret < 0)
throw cxxtools::SystemError("fcntl");
addFd(notify_pipe.getReadFd());
for (jobs_type::iterator it = jobs.begin(); it != jobs.end(); ++it)
addFd(it->first);
}
}
}
}
#else
PollerImpl::PollerImpl(Jobqueue& q)
: queue(q),
poll_timeout(-1)
{
fcntl(notify_pipe.getReadFd(), F_SETFL, O_NONBLOCK);
pollfds.reserve(16);
pollfds[0].fd = notify_pipe.getReadFd();
pollfds[0].events = POLLIN;
pollfds[0].revents = 0;
}
void PollerImpl::append_new_jobs()
{
cxxtools::MutexLock lock(mutex);
if (!new_jobs.empty())
{
// append new jobs to current
log_debug("add " << new_jobs.size() << " new jobs to poll-list");
pollfds.reserve(current_jobs.size() + new_jobs.size() + 1);
time_t currentTime;
time(¤tTime);
for (jobs_type::iterator it = new_jobs.begin();
it != new_jobs.end(); ++it)
{
append(*it);
int msec;
if (poll_timeout < 0)
poll_timeout = (*it)->msecToTimeout(currentTime);
else if ((msec = (*it)->msecToTimeout(currentTime)) < poll_timeout)
poll_timeout = msec;
}
new_jobs.clear();
}
}
void PollerImpl::append(Jobqueue::JobPtr& job)
{
current_jobs.push_back(job);
pollfd& p = *(pollfds.data() + current_jobs.size());
p.fd = job->getFd();
p.events = POLLIN;
}
void PollerImpl::run()
{
while (!Tntnet::shouldStop())
{
usleep(100);
append_new_jobs();
try
{
log_debug("poll timeout=" << poll_timeout);
::poll(pollfds.data(), current_jobs.size() + 1, poll_timeout);
poll_timeout = -1;
if (pollfds[0].revents != 0)
{
if (Tntnet::shouldStop())
{
log_info("stop poller");
break;
}
log_debug("read notify-pipe");
char buffer[64];
ssize_t n = notify_pipe.read(&buffer, sizeof(buffer));
log_debug("read returns " << n);
pollfds[0].revents = 0;
}
if (current_jobs.size() > 0)
dispatch();
}
catch (const std::exception& e)
{
log_error("error in poll-loop: " << e.what());
}
}
}
void PollerImpl::doStop()
{
log_debug("notify stop");
notify_pipe.write('A');
}
void PollerImpl::dispatch()
{
log_debug("dispatch " << current_jobs.size() << " jobs");
time_t currentTime;
time(¤tTime);
for (unsigned i = 0; i < current_jobs.size(); )
{
if (pollfds[i + 1].revents & POLLIN)
{
log_debug("job found " << pollfds[i + 1].fd);
// put job into work-queue
queue.put(current_jobs[i]);
remove(i);
}
else if (pollfds[i + 1].revents != 0)
{
log_debug("pollevent " << std::hex << pollfds[i + 1].revents << " on fd " << pollfds[i + 1].fd);
remove(i);
}
else
{
// check timeout
int msec = current_jobs[i]->msecToTimeout(currentTime);
if (msec <= 0)
{
log_debug("keep-alive-timeout reached");
remove(i);
}
else if (poll_timeout < 0 || msec < poll_timeout)
poll_timeout = msec;
++i;
}
}
}
void PollerImpl::remove(jobs_type::size_type n)
{
// replace job with last job in poller-list
jobs_type::size_type last = current_jobs.size() - 1;
if (n != last)
{
pollfds[n + 1] = pollfds[last + 1];
current_jobs[n] = current_jobs[last];
}
current_jobs.pop_back();
}
void PollerImpl::addIdleJob(Jobqueue::JobPtr job)
{
log_debug("addIdleJob " << job->getFd());
{
cxxtools::MutexLock lock(mutex);
new_jobs.push_back(job);
}
log_debug("notify " << job->getFd());
notify_pipe.write('A');
log_debug("addIdleJob ready");
}
#endif // #else HAVE_EPOLL
}
<commit_msg>bugfix: wrong buffer for notification of poller was used, which may lead to a buffer overflow in very rare cases<commit_after>/*
* Copyright (C) 2005-2006 Tommi Maekitalo
*
* 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.
*
* As a special exception, you may use this file as part of a free
* software library without restriction. Specifically, if other files
* instantiate templates or use macros or inline functions from this
* file, or you compile this file and link it with other files to
* produce an executable, this file does not by itself cause the
* resulting executable to be covered by the GNU General Public
* License. This exception does not however invalidate any other
* reasons why the executable file might be covered by the GNU Library
* General Public License.
*
* 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
*/
#include "tnt/poller.h"
#include "tnt/pollerimpl.h"
#include "tnt/tntnet.h"
#include <cxxtools/syserror.h>
#include <cxxtools/log.h>
#include <ios>
#include <unistd.h>
#include <fcntl.h>
#ifdef WITH_EPOLL
#include <sys/epoll.h>
#include <errno.h>
#endif
log_define("tntnet.poller")
namespace tnt
{
PollerIf::~PollerIf()
{ }
Poller::Poller(Jobqueue& q)
: impl(new PollerImpl(q))
{ }
void Poller::run()
{
impl->run();
}
#ifdef WITH_EPOLL
PollerImpl::PollerImpl(Jobqueue& q)
: queue(q),
pollFd(-1)
{
pollFd = ::epoll_create(256);
if (pollFd < 0)
throw cxxtools::SystemError("epoll_create");
fcntl(notify_pipe.getReadFd(), F_SETFL, O_NONBLOCK);
addFd(notify_pipe.getReadFd());
}
PollerImpl::~PollerImpl()
{
close(pollFd);
}
void PollerImpl::addFd(int fd)
{
log_debug("addFd(" << fd << ')');
epoll_event e;
e.events = EPOLLIN;
e.data.fd = fd;
int ret = ::epoll_ctl(pollFd, EPOLL_CTL_ADD, fd, &e);
if (ret < 0)
throw cxxtools::SystemError("epoll_ctl(EPOLL_CTL_ADD)");
}
bool PollerImpl::removeFd(int fd)
{
log_debug("removeFd(" << fd << ')');
epoll_event e;
e.data.fd = fd;
int ret = ::epoll_ctl(pollFd, EPOLL_CTL_DEL, fd, &e);
if (ret < 0)
{
if (errno == EBADF || errno == ENOENT)
{
log_debug("fd " << fd << " couldn't be removed");
return false;
}
else
throw cxxtools::SystemError("epoll_ctl(EPOLL_CTL_DEL)");
}
return true;
}
void PollerImpl::doStop()
{
log_debug("notify stop");
notify_pipe.write('A');
}
void PollerImpl::addIdleJob(Jobqueue::JobPtr job)
{
log_debug("addIdleJob " << job->getFd());
{
cxxtools::MutexLock lock(mutex);
new_jobs.insert(job);
notify_pipe.write('A');
}
log_debug("addIdleJob ready");
}
void PollerImpl::append_new_jobs()
{
cxxtools::MutexLock lock(mutex);
if (!new_jobs.empty())
{
// append new jobs to current
log_debug("add " << new_jobs.size() << " new jobs to poll-list");
time_t currentTime;
time(¤tTime);
for (new_jobs_type::iterator it = new_jobs.begin();
it != new_jobs.end(); ++it)
{
addFd((*it)->getFd());
jobs[(*it)->getFd()] = *it;
int msec;
if (poll_timeout < 0)
poll_timeout = (*it)->msecToTimeout(currentTime);
else if ((msec = (*it)->msecToTimeout(currentTime)) < poll_timeout)
poll_timeout = msec;
}
new_jobs.clear();
}
}
void PollerImpl::run()
{
epoll_event events[16];
time_t pollTime;
time(&pollTime);
while (!Tntnet::shouldStop())
{
usleep(100);
append_new_jobs();
if (jobs.size() == 0)
poll_timeout = -1;
log_debug("epoll_wait with timeout " << poll_timeout << " ms");
int ret = ::epoll_wait(pollFd, events, 16, poll_timeout);
if (ret < 0)
{
if (errno != EINTR)
throw cxxtools::SystemError("epoll_wait");
}
else if (ret == 0)
{
// timeout reached - check for timed out requests and get next timeout
log_debug("timeout reached");
poll_timeout = -1;
time_t currentTime;
time(¤tTime);
for (jobs_type::iterator it = jobs.begin(); it != jobs.end(); )
{
int msec = it->second->msecToTimeout(currentTime);
if (msec <= 0)
{
log_debug("keep-alive-timeout reached");
jobs_type::iterator it2 = it++;
jobs.erase(it2);
}
else
{
if (poll_timeout < 0 || msec < poll_timeout)
poll_timeout = msec;
++it;
}
}
}
else
{
time_t currentTime;
time(¤tTime);
poll_timeout -= (currentTime - pollTime) * 1000;
if (poll_timeout <= 0)
poll_timeout = 100;
pollTime = currentTime;
// no timeout - process events
log_debug(ret << " events occured");
bool rebuildPollFd = false;
for (int i = 0; i < ret; ++i)
{
if (events[i].data.fd == notify_pipe.getReadFd())
{
if (Tntnet::shouldStop())
{
log_info("stop poller");
break;
}
log_debug("read notify-pipe");
char buffer[64];
ssize_t n = notify_pipe.read(buffer, sizeof(buffer));
log_debug("read returns " << n);
}
else
{
jobs_type::iterator it = jobs.find(events[i].data.fd);
if (it == jobs.end())
{
log_fatal("internal error: job for fd " << events[i].data.fd << " not found in jobs-list");
::close(events[i].data.fd);
rebuildPollFd = true;
}
else
{
Jobqueue::JobPtr j = it->second;
int ev = events[i].events;
jobs.erase(it);
if (!removeFd(events[i].data.fd))
rebuildPollFd = true;
if (ev & EPOLLIN)
{
log_debug("put fd " << it->first << " back in queue");
queue.put(j);
}
else
{
log_debug("remove fd " << it->first << " from queue");
}
}
}
}
if (rebuildPollFd)
{
// rebuild poll-structure
log_warn("need to rebuild poll structure");
close(pollFd);
pollFd = ::epoll_create(256);
if (pollFd < 0)
throw cxxtools::SystemError("epoll_create");
int ret = fcntl(notify_pipe.getReadFd(), F_SETFL, O_NONBLOCK);
if (ret < 0)
throw cxxtools::SystemError("fcntl");
addFd(notify_pipe.getReadFd());
for (jobs_type::iterator it = jobs.begin(); it != jobs.end(); ++it)
addFd(it->first);
}
}
}
}
#else
PollerImpl::PollerImpl(Jobqueue& q)
: queue(q),
poll_timeout(-1)
{
fcntl(notify_pipe.getReadFd(), F_SETFL, O_NONBLOCK);
pollfds.reserve(16);
pollfds[0].fd = notify_pipe.getReadFd();
pollfds[0].events = POLLIN;
pollfds[0].revents = 0;
}
void PollerImpl::append_new_jobs()
{
cxxtools::MutexLock lock(mutex);
if (!new_jobs.empty())
{
// append new jobs to current
log_debug("add " << new_jobs.size() << " new jobs to poll-list");
pollfds.reserve(current_jobs.size() + new_jobs.size() + 1);
time_t currentTime;
time(¤tTime);
for (jobs_type::iterator it = new_jobs.begin();
it != new_jobs.end(); ++it)
{
append(*it);
int msec;
if (poll_timeout < 0)
poll_timeout = (*it)->msecToTimeout(currentTime);
else if ((msec = (*it)->msecToTimeout(currentTime)) < poll_timeout)
poll_timeout = msec;
}
new_jobs.clear();
}
}
void PollerImpl::append(Jobqueue::JobPtr& job)
{
current_jobs.push_back(job);
pollfd& p = *(pollfds.data() + current_jobs.size());
p.fd = job->getFd();
p.events = POLLIN;
}
void PollerImpl::run()
{
while (!Tntnet::shouldStop())
{
usleep(100);
append_new_jobs();
try
{
log_debug("poll timeout=" << poll_timeout);
::poll(pollfds.data(), current_jobs.size() + 1, poll_timeout);
poll_timeout = -1;
if (pollfds[0].revents != 0)
{
if (Tntnet::shouldStop())
{
log_info("stop poller");
break;
}
log_debug("read notify-pipe");
char buffer[64];
ssize_t n = notify_pipe.read(buffer, sizeof(buffer));
log_debug("read returns " << n);
pollfds[0].revents = 0;
}
if (current_jobs.size() > 0)
dispatch();
}
catch (const std::exception& e)
{
log_error("error in poll-loop: " << e.what());
}
}
}
void PollerImpl::doStop()
{
log_debug("notify stop");
notify_pipe.write('A');
}
void PollerImpl::dispatch()
{
log_debug("dispatch " << current_jobs.size() << " jobs");
time_t currentTime;
time(¤tTime);
for (unsigned i = 0; i < current_jobs.size(); )
{
if (pollfds[i + 1].revents & POLLIN)
{
log_debug("job found " << pollfds[i + 1].fd);
// put job into work-queue
queue.put(current_jobs[i]);
remove(i);
}
else if (pollfds[i + 1].revents != 0)
{
log_debug("pollevent " << std::hex << pollfds[i + 1].revents << " on fd " << pollfds[i + 1].fd);
remove(i);
}
else
{
// check timeout
int msec = current_jobs[i]->msecToTimeout(currentTime);
if (msec <= 0)
{
log_debug("keep-alive-timeout reached");
remove(i);
}
else if (poll_timeout < 0 || msec < poll_timeout)
poll_timeout = msec;
++i;
}
}
}
void PollerImpl::remove(jobs_type::size_type n)
{
// replace job with last job in poller-list
jobs_type::size_type last = current_jobs.size() - 1;
if (n != last)
{
pollfds[n + 1] = pollfds[last + 1];
current_jobs[n] = current_jobs[last];
}
current_jobs.pop_back();
}
void PollerImpl::addIdleJob(Jobqueue::JobPtr job)
{
log_debug("addIdleJob " << job->getFd());
{
cxxtools::MutexLock lock(mutex);
new_jobs.push_back(job);
}
log_debug("notify " << job->getFd());
notify_pipe.write('A');
log_debug("addIdleJob ready");
}
#endif // #else HAVE_EPOLL
}
<|endoftext|> |
<commit_before>//===- OptimizerDriver.cpp - Allow BugPoint to run passes safely ----------===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This file defines an interface that allows bugpoint to run various passes
// without the threat of a buggy pass corrupting bugpoint (of course, bugpoint
// may have its own bugs, but that's another story...). It achieves this by
// forking a copy of itself and having the child process do the optimizations.
// If this client dies, we can always fork a new one. :)
//
//===----------------------------------------------------------------------===//
#include "BugDriver.h"
#include "llvm/Module.h"
#include "llvm/PassManager.h"
#include "llvm/Analysis/Verifier.h"
#include "llvm/Bitcode/ReaderWriter.h"
#include "llvm/Target/TargetData.h"
#include "llvm/Support/FileUtilities.h"
#include "llvm/Support/CommandLine.h"
#include "llvm/Support/SystemUtils.h"
#include "llvm/Support/Debug.h"
#include "llvm/Support/ToolOutputFile.h"
#include "llvm/Support/Path.h"
#include "llvm/Support/Program.h"
#define DONT_GET_PLUGIN_LOADER_OPTION
#include "llvm/Support/PluginLoader.h"
#include <fstream>
using namespace llvm;
namespace llvm {
extern cl::opt<std::string> OutputPrefix;
}
namespace {
// ChildOutput - This option captures the name of the child output file that
// is set up by the parent bugpoint process
cl::opt<std::string> ChildOutput("child-output", cl::ReallyHidden);
}
/// writeProgramToFile - This writes the current "Program" to the named bitcode
/// file. If an error occurs, true is returned.
///
bool BugDriver::writeProgramToFile(const std::string &Filename,
const Module *M) const {
std::string ErrInfo;
tool_output_file Out(Filename.c_str(), ErrInfo,
raw_fd_ostream::F_Binary);
if (ErrInfo.empty()) {
WriteBitcodeToFile(M, Out.os());
Out.os().close();
if (!Out.os().has_error()) {
Out.keep();
return false;
}
}
Out.os().clear_error();
return true;
}
/// EmitProgressBitcode - This function is used to output the current Program
/// to a file named "bugpoint-ID.bc".
///
void BugDriver::EmitProgressBitcode(const Module *M,
const std::string &ID,
bool NoFlyer) const {
// Output the input to the current pass to a bitcode file, emit a message
// telling the user how to reproduce it: opt -foo blah.bc
//
std::string Filename = OutputPrefix + "-" + ID + ".bc";
if (writeProgramToFile(Filename, M)) {
errs() << "Error opening file '" << Filename << "' for writing!\n";
return;
}
outs() << "Emitted bitcode to '" << Filename << "'\n";
if (NoFlyer || PassesToRun.empty()) return;
outs() << "\n*** You can reproduce the problem with: ";
if (UseValgrind) outs() << "valgrind ";
outs() << "opt " << Filename << " ";
outs() << getPassesString(PassesToRun) << "\n";
}
cl::opt<bool> SilencePasses("silence-passes", cl::desc("Suppress output of running passes (both stdout and stderr)"));
static cl::list<std::string> OptArgs("opt-args", cl::Positional,
cl::desc("<opt arguments>..."),
cl::ZeroOrMore, cl::PositionalEatsArgs);
/// runPasses - Run the specified passes on Program, outputting a bitcode file
/// and writing the filename into OutputFile if successful. If the
/// optimizations fail for some reason (optimizer crashes), return true,
/// otherwise return false. If DeleteOutput is set to true, the bitcode is
/// deleted on success, and the filename string is undefined. This prints to
/// outs() a single line message indicating whether compilation was successful
/// or failed.
///
bool BugDriver::runPasses(Module *Program,
const std::vector<std::string> &Passes,
std::string &OutputFilename, bool DeleteOutput,
bool Quiet, unsigned NumExtraArgs,
const char * const *ExtraArgs) const {
// setup the output file name
outs().flush();
sys::Path uniqueFilename(OutputPrefix + "-output.bc");
std::string ErrMsg;
if (uniqueFilename.makeUnique(true, &ErrMsg)) {
errs() << getToolName() << ": Error making unique filename: "
<< ErrMsg << "\n";
return(1);
}
OutputFilename = uniqueFilename.str();
// set up the input file name
sys::Path inputFilename(OutputPrefix + "-input.bc");
if (inputFilename.makeUnique(true, &ErrMsg)) {
errs() << getToolName() << ": Error making unique filename: "
<< ErrMsg << "\n";
return(1);
}
std::string ErrInfo;
tool_output_file InFile(inputFilename.c_str(), ErrInfo,
raw_fd_ostream::F_Binary);
if (!ErrInfo.empty()) {
errs() << "Error opening bitcode file: " << inputFilename.str() << "\n";
return 1;
}
WriteBitcodeToFile(Program, InFile.os());
InFile.os().close();
if (InFile.os().has_error()) {
errs() << "Error writing bitcode file: " << inputFilename.str() << "\n";
InFile.os().clear_error();
return 1;
}
sys::Path tool = PrependMainExecutablePath("opt", getToolName(),
(void*)"opt");
if (tool.empty()) {
errs() << "Cannot find `opt' in executable directory!\n";
return 1;
}
// Ok, everything that could go wrong before running opt is done.
InFile.keep();
// setup the child process' arguments
SmallVector<const char*, 8> Args;
std::string Opt = tool.str();
if (UseValgrind) {
Args.push_back("valgrind");
Args.push_back("--error-exitcode=1");
Args.push_back("-q");
Args.push_back(tool.c_str());
} else
Args.push_back(Opt.c_str());
Args.push_back("-o");
Args.push_back(OutputFilename.c_str());
for (unsigned i = 0, e = OptArgs.size(); i != e; ++i)
Args.push_back(OptArgs[i].c_str());
std::vector<std::string> pass_args;
for (unsigned i = 0, e = PluginLoader::getNumPlugins(); i != e; ++i) {
pass_args.push_back( std::string("-load"));
pass_args.push_back( PluginLoader::getPlugin(i));
}
for (std::vector<std::string>::const_iterator I = Passes.begin(),
E = Passes.end(); I != E; ++I )
pass_args.push_back( std::string("-") + (*I) );
for (std::vector<std::string>::const_iterator I = pass_args.begin(),
E = pass_args.end(); I != E; ++I )
Args.push_back(I->c_str());
Args.push_back(inputFilename.c_str());
for (unsigned i = 0; i < NumExtraArgs; ++i)
Args.push_back(*ExtraArgs);
Args.push_back(0);
DEBUG(errs() << "\nAbout to run:\t";
for (unsigned i = 0, e = Args.size()-1; i != e; ++i)
errs() << " " << Args[i];
errs() << "\n";
);
sys::Path prog;
if (UseValgrind)
prog = sys::Program::FindProgramByName("valgrind");
else
prog = tool;
// Redirect stdout and stderr to nowhere if SilencePasses is given
sys::Path Nowhere;
const sys::Path *Redirects[3] = {0, &Nowhere, &Nowhere};
int result = sys::Program::ExecuteAndWait(prog, Args.data(), 0,
(SilencePasses ? Redirects : 0),
Timeout, MemoryLimit, &ErrMsg);
// If we are supposed to delete the bitcode file or if the passes crashed,
// remove it now. This may fail if the file was never created, but that's ok.
if (DeleteOutput || result != 0)
sys::Path(OutputFilename).eraseFromDisk();
// Remove the temporary input file as well
inputFilename.eraseFromDisk();
if (!Quiet) {
if (result == 0)
outs() << "Success!\n";
else if (result > 0)
outs() << "Exited with error code '" << result << "'\n";
else if (result < 0) {
if (result == -1)
outs() << "Execute failed: " << ErrMsg << "\n";
else
outs() << "Crashed with signal #" << abs(result) << "\n";
}
if (result & 0x01000000)
outs() << "Dumped core\n";
}
// Was the child successful?
return result != 0;
}
/// runPassesOn - Carefully run the specified set of pass on the specified
/// module, returning the transformed module on success, or a null pointer on
/// failure.
Module *BugDriver::runPassesOn(Module *M,
const std::vector<std::string> &Passes,
bool AutoDebugCrashes, unsigned NumExtraArgs,
const char * const *ExtraArgs) {
std::string BitcodeResult;
if (runPasses(M, Passes, BitcodeResult, false/*delete*/, true/*quiet*/,
NumExtraArgs, ExtraArgs)) {
if (AutoDebugCrashes) {
errs() << " Error running this sequence of passes"
<< " on the input program!\n";
delete swapProgramIn(M);
EmitProgressBitcode(M, "pass-error", false);
exit(debugOptimizerCrash());
}
return 0;
}
Module *Ret = ParseInputFile(BitcodeResult, Context);
if (Ret == 0) {
errs() << getToolName() << ": Error reading bitcode file '"
<< BitcodeResult << "'!\n";
exit(1);
}
sys::Path(BitcodeResult).eraseFromDisk(); // No longer need the file on disk
return Ret;
}
<commit_msg>fit in 80 cols.<commit_after>//===- OptimizerDriver.cpp - Allow BugPoint to run passes safely ----------===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This file defines an interface that allows bugpoint to run various passes
// without the threat of a buggy pass corrupting bugpoint (of course, bugpoint
// may have its own bugs, but that's another story...). It achieves this by
// forking a copy of itself and having the child process do the optimizations.
// If this client dies, we can always fork a new one. :)
//
//===----------------------------------------------------------------------===//
#include "BugDriver.h"
#include "llvm/Module.h"
#include "llvm/PassManager.h"
#include "llvm/Analysis/Verifier.h"
#include "llvm/Bitcode/ReaderWriter.h"
#include "llvm/Target/TargetData.h"
#include "llvm/Support/FileUtilities.h"
#include "llvm/Support/CommandLine.h"
#include "llvm/Support/SystemUtils.h"
#include "llvm/Support/Debug.h"
#include "llvm/Support/ToolOutputFile.h"
#include "llvm/Support/Path.h"
#include "llvm/Support/Program.h"
#define DONT_GET_PLUGIN_LOADER_OPTION
#include "llvm/Support/PluginLoader.h"
#include <fstream>
using namespace llvm;
namespace llvm {
extern cl::opt<std::string> OutputPrefix;
}
namespace {
// ChildOutput - This option captures the name of the child output file that
// is set up by the parent bugpoint process
cl::opt<std::string> ChildOutput("child-output", cl::ReallyHidden);
}
/// writeProgramToFile - This writes the current "Program" to the named bitcode
/// file. If an error occurs, true is returned.
///
bool BugDriver::writeProgramToFile(const std::string &Filename,
const Module *M) const {
std::string ErrInfo;
tool_output_file Out(Filename.c_str(), ErrInfo,
raw_fd_ostream::F_Binary);
if (ErrInfo.empty()) {
WriteBitcodeToFile(M, Out.os());
Out.os().close();
if (!Out.os().has_error()) {
Out.keep();
return false;
}
}
Out.os().clear_error();
return true;
}
/// EmitProgressBitcode - This function is used to output the current Program
/// to a file named "bugpoint-ID.bc".
///
void BugDriver::EmitProgressBitcode(const Module *M,
const std::string &ID,
bool NoFlyer) const {
// Output the input to the current pass to a bitcode file, emit a message
// telling the user how to reproduce it: opt -foo blah.bc
//
std::string Filename = OutputPrefix + "-" + ID + ".bc";
if (writeProgramToFile(Filename, M)) {
errs() << "Error opening file '" << Filename << "' for writing!\n";
return;
}
outs() << "Emitted bitcode to '" << Filename << "'\n";
if (NoFlyer || PassesToRun.empty()) return;
outs() << "\n*** You can reproduce the problem with: ";
if (UseValgrind) outs() << "valgrind ";
outs() << "opt " << Filename << " ";
outs() << getPassesString(PassesToRun) << "\n";
}
cl::opt<bool> SilencePasses("silence-passes",
cl::desc("Suppress output of running passes (both stdout and stderr)"));
static cl::list<std::string> OptArgs("opt-args", cl::Positional,
cl::desc("<opt arguments>..."),
cl::ZeroOrMore, cl::PositionalEatsArgs);
/// runPasses - Run the specified passes on Program, outputting a bitcode file
/// and writing the filename into OutputFile if successful. If the
/// optimizations fail for some reason (optimizer crashes), return true,
/// otherwise return false. If DeleteOutput is set to true, the bitcode is
/// deleted on success, and the filename string is undefined. This prints to
/// outs() a single line message indicating whether compilation was successful
/// or failed.
///
bool BugDriver::runPasses(Module *Program,
const std::vector<std::string> &Passes,
std::string &OutputFilename, bool DeleteOutput,
bool Quiet, unsigned NumExtraArgs,
const char * const *ExtraArgs) const {
// setup the output file name
outs().flush();
sys::Path uniqueFilename(OutputPrefix + "-output.bc");
std::string ErrMsg;
if (uniqueFilename.makeUnique(true, &ErrMsg)) {
errs() << getToolName() << ": Error making unique filename: "
<< ErrMsg << "\n";
return(1);
}
OutputFilename = uniqueFilename.str();
// set up the input file name
sys::Path inputFilename(OutputPrefix + "-input.bc");
if (inputFilename.makeUnique(true, &ErrMsg)) {
errs() << getToolName() << ": Error making unique filename: "
<< ErrMsg << "\n";
return(1);
}
std::string ErrInfo;
tool_output_file InFile(inputFilename.c_str(), ErrInfo,
raw_fd_ostream::F_Binary);
if (!ErrInfo.empty()) {
errs() << "Error opening bitcode file: " << inputFilename.str() << "\n";
return 1;
}
WriteBitcodeToFile(Program, InFile.os());
InFile.os().close();
if (InFile.os().has_error()) {
errs() << "Error writing bitcode file: " << inputFilename.str() << "\n";
InFile.os().clear_error();
return 1;
}
sys::Path tool = PrependMainExecutablePath("opt", getToolName(),
(void*)"opt");
if (tool.empty()) {
errs() << "Cannot find `opt' in executable directory!\n";
return 1;
}
// Ok, everything that could go wrong before running opt is done.
InFile.keep();
// setup the child process' arguments
SmallVector<const char*, 8> Args;
std::string Opt = tool.str();
if (UseValgrind) {
Args.push_back("valgrind");
Args.push_back("--error-exitcode=1");
Args.push_back("-q");
Args.push_back(tool.c_str());
} else
Args.push_back(Opt.c_str());
Args.push_back("-o");
Args.push_back(OutputFilename.c_str());
for (unsigned i = 0, e = OptArgs.size(); i != e; ++i)
Args.push_back(OptArgs[i].c_str());
std::vector<std::string> pass_args;
for (unsigned i = 0, e = PluginLoader::getNumPlugins(); i != e; ++i) {
pass_args.push_back( std::string("-load"));
pass_args.push_back( PluginLoader::getPlugin(i));
}
for (std::vector<std::string>::const_iterator I = Passes.begin(),
E = Passes.end(); I != E; ++I )
pass_args.push_back( std::string("-") + (*I) );
for (std::vector<std::string>::const_iterator I = pass_args.begin(),
E = pass_args.end(); I != E; ++I )
Args.push_back(I->c_str());
Args.push_back(inputFilename.c_str());
for (unsigned i = 0; i < NumExtraArgs; ++i)
Args.push_back(*ExtraArgs);
Args.push_back(0);
DEBUG(errs() << "\nAbout to run:\t";
for (unsigned i = 0, e = Args.size()-1; i != e; ++i)
errs() << " " << Args[i];
errs() << "\n";
);
sys::Path prog;
if (UseValgrind)
prog = sys::Program::FindProgramByName("valgrind");
else
prog = tool;
// Redirect stdout and stderr to nowhere if SilencePasses is given
sys::Path Nowhere;
const sys::Path *Redirects[3] = {0, &Nowhere, &Nowhere};
int result = sys::Program::ExecuteAndWait(prog, Args.data(), 0,
(SilencePasses ? Redirects : 0),
Timeout, MemoryLimit, &ErrMsg);
// If we are supposed to delete the bitcode file or if the passes crashed,
// remove it now. This may fail if the file was never created, but that's ok.
if (DeleteOutput || result != 0)
sys::Path(OutputFilename).eraseFromDisk();
// Remove the temporary input file as well
inputFilename.eraseFromDisk();
if (!Quiet) {
if (result == 0)
outs() << "Success!\n";
else if (result > 0)
outs() << "Exited with error code '" << result << "'\n";
else if (result < 0) {
if (result == -1)
outs() << "Execute failed: " << ErrMsg << "\n";
else
outs() << "Crashed with signal #" << abs(result) << "\n";
}
if (result & 0x01000000)
outs() << "Dumped core\n";
}
// Was the child successful?
return result != 0;
}
/// runPassesOn - Carefully run the specified set of pass on the specified
/// module, returning the transformed module on success, or a null pointer on
/// failure.
Module *BugDriver::runPassesOn(Module *M,
const std::vector<std::string> &Passes,
bool AutoDebugCrashes, unsigned NumExtraArgs,
const char * const *ExtraArgs) {
std::string BitcodeResult;
if (runPasses(M, Passes, BitcodeResult, false/*delete*/, true/*quiet*/,
NumExtraArgs, ExtraArgs)) {
if (AutoDebugCrashes) {
errs() << " Error running this sequence of passes"
<< " on the input program!\n";
delete swapProgramIn(M);
EmitProgressBitcode(M, "pass-error", false);
exit(debugOptimizerCrash());
}
return 0;
}
Module *Ret = ParseInputFile(BitcodeResult, Context);
if (Ret == 0) {
errs() << getToolName() << ": Error reading bitcode file '"
<< BitcodeResult << "'!\n";
exit(1);
}
sys::Path(BitcodeResult).eraseFromDisk(); // No longer need the file on disk
return Ret;
}
<|endoftext|> |
<commit_before>//===-- clang-format/ClangFormat.cpp - Clang format tool ------------------===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
///
/// \file
/// \brief This file implements a clang-format tool that automatically formats
/// (fragments of) C++ code.
///
//===----------------------------------------------------------------------===//
#include "clang/Basic/Diagnostic.h"
#include "clang/Basic/DiagnosticOptions.h"
#include "clang/Basic/FileManager.h"
#include "clang/Basic/SourceManager.h"
#include "clang/Basic/Version.h"
#include "clang/Format/Format.h"
#include "clang/Lex/Lexer.h"
#include "clang/Rewrite/Core/Rewriter.h"
#include "llvm/ADT/StringMap.h"
#include "llvm/Support/Debug.h"
#include "llvm/Support/FileSystem.h"
#include "llvm/Support/Signals.h"
using namespace llvm;
static cl::opt<bool> Help("h", cl::desc("Alias for -help"), cl::Hidden);
// Mark all our options with this category, everything else (except for -version
// and -help) will be hidden.
static cl::OptionCategory ClangFormatCategory("Clang-format options");
static cl::list<unsigned>
Offsets("offset",
cl::desc("Format a range starting at this byte offset.\n"
"Multiple ranges can be formatted by specifying\n"
"several -offset and -length pairs.\n"
"Can only be used with one input file."),
cl::cat(ClangFormatCategory));
static cl::list<unsigned>
Lengths("length",
cl::desc("Format a range of this length (in bytes).\n"
"Multiple ranges can be formatted by specifying\n"
"several -offset and -length pairs.\n"
"When only a single -offset is specified without\n"
"-length, clang-format will format up to the end\n"
"of the file.\n"
"Can only be used with one input file."),
cl::cat(ClangFormatCategory));
static cl::list<std::string>
LineRanges("lines", cl::desc("<start line>:<end line> - format a range of\n"
"lines (both 1-based).\n"
"Multiple ranges can be formatted by specifying\n"
"several -lines arguments.\n"
"Can't be used with -offset and -length.\n"
"Can only be used with one input file."),
cl::cat(ClangFormatCategory));
static cl::opt<std::string>
Style("style",
cl::desc(clang::format::StyleOptionHelpDescription),
cl::init("file"), cl::cat(ClangFormatCategory));
static cl::opt<std::string>
FallbackStyle("fallback-style",
cl::desc("The name of the predefined style used as a fallback in "
"case clang-format is invoked with -style=file, but can "
"not find the .clang-format file to use."),
cl::init("LLVM"), cl::cat(ClangFormatCategory));
static cl::opt<std::string>
AssumeFilename("assume-filename",
cl::desc("When reading from stdin, clang-format assumes this\n"
"filename to look for a style config file (with\n"
"-style=file)."),
cl::cat(ClangFormatCategory));
static cl::opt<bool> Inplace("i",
cl::desc("Inplace edit <file>s, if specified."),
cl::cat(ClangFormatCategory));
static cl::opt<bool> OutputXML("output-replacements-xml",
cl::desc("Output replacements as XML."),
cl::cat(ClangFormatCategory));
static cl::opt<bool>
DumpConfig("dump-config",
cl::desc("Dump configuration options to stdout and exit.\n"
"Can be used with -style option."),
cl::cat(ClangFormatCategory));
static cl::opt<unsigned>
Cursor("cursor",
cl::desc("The position of the cursor when invoking\n"
"clang-format from an editor integration"),
cl::init(0), cl::cat(ClangFormatCategory));
static cl::list<std::string> FileNames(cl::Positional, cl::desc("[<file> ...]"),
cl::cat(ClangFormatCategory));
namespace clang {
namespace format {
static FileID createInMemoryFile(StringRef FileName, const MemoryBuffer *Source,
SourceManager &Sources, FileManager &Files) {
const FileEntry *Entry = Files.getVirtualFile(FileName == "-" ? "<stdin>" :
FileName,
Source->getBufferSize(), 0);
Sources.overrideFileContents(Entry, Source, true);
return Sources.createFileID(Entry, SourceLocation(), SrcMgr::C_User);
}
// Parses <start line>:<end line> input to a pair of line numbers.
// Returns true on error.
static bool parseLineRange(StringRef Input, unsigned &FromLine,
unsigned &ToLine) {
std::pair<StringRef, StringRef> LineRange = Input.split(':');
return LineRange.first.getAsInteger(0, FromLine) ||
LineRange.second.getAsInteger(0, ToLine);
}
static bool fillRanges(SourceManager &Sources, FileID ID,
const MemoryBuffer *Code,
std::vector<CharSourceRange> &Ranges) {
if (!LineRanges.empty()) {
if (!Offsets.empty() || !Lengths.empty()) {
llvm::errs() << "error: cannot use -lines with -offset/-length\n";
return true;
}
for (unsigned i = 0, e = LineRanges.size(); i < e; ++i) {
unsigned FromLine, ToLine;
if (parseLineRange(LineRanges[i], FromLine, ToLine)) {
llvm::errs() << "error: invalid <start line>:<end line> pair\n";
return true;
}
if (FromLine > ToLine) {
llvm::errs() << "error: start line should be less than end line\n";
return true;
}
SourceLocation Start = Sources.translateLineCol(ID, FromLine, 1);
SourceLocation End = Sources.translateLineCol(ID, ToLine, UINT_MAX);
if (Start.isInvalid() || End.isInvalid())
return true;
Ranges.push_back(CharSourceRange::getCharRange(Start, End));
}
return false;
}
if (Offsets.empty())
Offsets.push_back(0);
if (Offsets.size() != Lengths.size() &&
!(Offsets.size() == 1 && Lengths.empty())) {
llvm::errs()
<< "error: number of -offset and -length arguments must match.\n";
return true;
}
for (unsigned i = 0, e = Offsets.size(); i != e; ++i) {
if (Offsets[i] >= Code->getBufferSize()) {
llvm::errs() << "error: offset " << Offsets[i]
<< " is outside the file\n";
return true;
}
SourceLocation Start =
Sources.getLocForStartOfFile(ID).getLocWithOffset(Offsets[i]);
SourceLocation End;
if (i < Lengths.size()) {
if (Offsets[i] + Lengths[i] > Code->getBufferSize()) {
llvm::errs() << "error: invalid length " << Lengths[i]
<< ", offset + length (" << Offsets[i] + Lengths[i]
<< ") is outside the file.\n";
return true;
}
End = Start.getLocWithOffset(Lengths[i]);
} else {
End = Sources.getLocForEndOfFile(ID);
}
Ranges.push_back(CharSourceRange::getCharRange(Start, End));
}
return false;
}
static void outputReplacementXML(StringRef Text) {
size_t From = 0;
size_t Index;
while ((Index = Text.find_first_of("\n\r", From)) != StringRef::npos) {
llvm::outs() << Text.substr(From, Index - From);
switch (Text[Index]) {
case '\n':
llvm::outs() << " ";
break;
case '\r':
llvm::outs() << " ";
break;
default:
llvm_unreachable("Unexpected character encountered!");
}
From = Index + 1;
}
llvm::outs() << Text.substr(From);
}
// Returns true on error.
static bool format(StringRef FileName) {
FileManager Files((FileSystemOptions()));
DiagnosticsEngine Diagnostics(
IntrusiveRefCntPtr<DiagnosticIDs>(new DiagnosticIDs),
new DiagnosticOptions);
SourceManager Sources(Diagnostics, Files);
OwningPtr<MemoryBuffer> Code;
if (error_code ec = MemoryBuffer::getFileOrSTDIN(FileName, Code)) {
llvm::errs() << ec.message() << "\n";
return true;
}
if (Code->getBufferSize() == 0)
return false; // Empty files are formatted correctly.
FileID ID = createInMemoryFile(FileName, Code.get(), Sources, Files);
std::vector<CharSourceRange> Ranges;
if (fillRanges(Sources, ID, Code.get(), Ranges))
return true;
FormatStyle FormatStyle = getStyle(
Style, (FileName == "-") ? AssumeFilename : FileName, FallbackStyle);
Lexer Lex(ID, Sources.getBuffer(ID), Sources,
getFormattingLangOpts(FormatStyle.Standard));
tooling::Replacements Replaces = reformat(FormatStyle, Lex, Sources, Ranges);
if (OutputXML) {
llvm::outs()
<< "<?xml version='1.0'?>\n<replacements xml:space='preserve'>\n";
for (tooling::Replacements::const_iterator I = Replaces.begin(),
E = Replaces.end();
I != E; ++I) {
llvm::outs() << "<replacement "
<< "offset='" << I->getOffset() << "' "
<< "length='" << I->getLength() << "'>";
outputReplacementXML(I->getReplacementText());
llvm::outs() << "</replacement>\n";
}
llvm::outs() << "</replacements>\n";
} else {
Rewriter Rewrite(Sources, LangOptions());
tooling::applyAllReplacements(Replaces, Rewrite);
if (Inplace) {
if (Rewrite.overwriteChangedFiles())
return true;
} else {
if (Cursor.getNumOccurrences() != 0)
outs() << "{ \"Cursor\": " << tooling::shiftedCodePosition(
Replaces, Cursor) << " }\n";
Rewrite.getEditBuffer(ID).write(outs());
}
}
return false;
}
} // namespace format
} // namespace clang
static void PrintVersion() {
raw_ostream &OS = outs();
OS << clang::getClangToolFullVersion("clang-format") << '\n';
}
int main(int argc, const char **argv) {
llvm::sys::PrintStackTraceOnErrorSignal();
// Hide unrelated options.
StringMap<cl::Option*> Options;
cl::getRegisteredOptions(Options);
for (StringMap<cl::Option *>::iterator I = Options.begin(), E = Options.end();
I != E; ++I) {
if (I->second->Category != &ClangFormatCategory && I->first() != "help" &&
I->first() != "version")
I->second->setHiddenFlag(cl::ReallyHidden);
}
cl::SetVersionPrinter(PrintVersion);
cl::ParseCommandLineOptions(
argc, argv,
"A tool to format C/C++/Obj-C code.\n\n"
"If no arguments are specified, it formats the code from standard input\n"
"and writes the result to the standard output.\n"
"If <file>s are given, it reformats the files. If -i is specified\n"
"together with <file>s, the files are edited in-place. Otherwise, the\n"
"result is written to the standard output.\n");
if (Help)
cl::PrintHelpMessage();
if (DumpConfig) {
std::string Config =
clang::format::configurationAsText(clang::format::getStyle(
Style, FileNames.empty() ? AssumeFilename : FileNames[0],
FallbackStyle));
llvm::outs() << Config << "\n";
return 0;
}
bool Error = false;
switch (FileNames.size()) {
case 0:
Error = clang::format::format("-");
break;
case 1:
Error = clang::format::format(FileNames[0]);
break;
default:
if (!Offsets.empty() || !Lengths.empty() || !LineRanges.empty()) {
llvm::errs() << "error: -offset, -length and -lines can only be used for "
"single file.\n";
return 1;
}
for (unsigned i = 0; i < FileNames.size(); ++i)
Error |= clang::format::format(FileNames[i]);
break;
}
return Error ? 1 : 0;
}
<commit_msg>Add newlines to fallback-style description. Patch by Kamal Essoufi\!<commit_after>//===-- clang-format/ClangFormat.cpp - Clang format tool ------------------===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
///
/// \file
/// \brief This file implements a clang-format tool that automatically formats
/// (fragments of) C++ code.
///
//===----------------------------------------------------------------------===//
#include "clang/Basic/Diagnostic.h"
#include "clang/Basic/DiagnosticOptions.h"
#include "clang/Basic/FileManager.h"
#include "clang/Basic/SourceManager.h"
#include "clang/Basic/Version.h"
#include "clang/Format/Format.h"
#include "clang/Lex/Lexer.h"
#include "clang/Rewrite/Core/Rewriter.h"
#include "llvm/ADT/StringMap.h"
#include "llvm/Support/Debug.h"
#include "llvm/Support/FileSystem.h"
#include "llvm/Support/Signals.h"
using namespace llvm;
static cl::opt<bool> Help("h", cl::desc("Alias for -help"), cl::Hidden);
// Mark all our options with this category, everything else (except for -version
// and -help) will be hidden.
static cl::OptionCategory ClangFormatCategory("Clang-format options");
static cl::list<unsigned>
Offsets("offset",
cl::desc("Format a range starting at this byte offset.\n"
"Multiple ranges can be formatted by specifying\n"
"several -offset and -length pairs.\n"
"Can only be used with one input file."),
cl::cat(ClangFormatCategory));
static cl::list<unsigned>
Lengths("length",
cl::desc("Format a range of this length (in bytes).\n"
"Multiple ranges can be formatted by specifying\n"
"several -offset and -length pairs.\n"
"When only a single -offset is specified without\n"
"-length, clang-format will format up to the end\n"
"of the file.\n"
"Can only be used with one input file."),
cl::cat(ClangFormatCategory));
static cl::list<std::string>
LineRanges("lines", cl::desc("<start line>:<end line> - format a range of\n"
"lines (both 1-based).\n"
"Multiple ranges can be formatted by specifying\n"
"several -lines arguments.\n"
"Can't be used with -offset and -length.\n"
"Can only be used with one input file."),
cl::cat(ClangFormatCategory));
static cl::opt<std::string>
Style("style",
cl::desc(clang::format::StyleOptionHelpDescription),
cl::init("file"), cl::cat(ClangFormatCategory));
static cl::opt<std::string>
FallbackStyle("fallback-style",
cl::desc("The name of the predefined style used as a\n"
"fallback in case clang-format is invoked with\n"
"-style=file, but can not find the .clang-format\n"
"file to use."),
cl::init("LLVM"), cl::cat(ClangFormatCategory));
static cl::opt<std::string>
AssumeFilename("assume-filename",
cl::desc("When reading from stdin, clang-format assumes this\n"
"filename to look for a style config file (with\n"
"-style=file)."),
cl::cat(ClangFormatCategory));
static cl::opt<bool> Inplace("i",
cl::desc("Inplace edit <file>s, if specified."),
cl::cat(ClangFormatCategory));
static cl::opt<bool> OutputXML("output-replacements-xml",
cl::desc("Output replacements as XML."),
cl::cat(ClangFormatCategory));
static cl::opt<bool>
DumpConfig("dump-config",
cl::desc("Dump configuration options to stdout and exit.\n"
"Can be used with -style option."),
cl::cat(ClangFormatCategory));
static cl::opt<unsigned>
Cursor("cursor",
cl::desc("The position of the cursor when invoking\n"
"clang-format from an editor integration"),
cl::init(0), cl::cat(ClangFormatCategory));
static cl::list<std::string> FileNames(cl::Positional, cl::desc("[<file> ...]"),
cl::cat(ClangFormatCategory));
namespace clang {
namespace format {
static FileID createInMemoryFile(StringRef FileName, const MemoryBuffer *Source,
SourceManager &Sources, FileManager &Files) {
const FileEntry *Entry = Files.getVirtualFile(FileName == "-" ? "<stdin>" :
FileName,
Source->getBufferSize(), 0);
Sources.overrideFileContents(Entry, Source, true);
return Sources.createFileID(Entry, SourceLocation(), SrcMgr::C_User);
}
// Parses <start line>:<end line> input to a pair of line numbers.
// Returns true on error.
static bool parseLineRange(StringRef Input, unsigned &FromLine,
unsigned &ToLine) {
std::pair<StringRef, StringRef> LineRange = Input.split(':');
return LineRange.first.getAsInteger(0, FromLine) ||
LineRange.second.getAsInteger(0, ToLine);
}
static bool fillRanges(SourceManager &Sources, FileID ID,
const MemoryBuffer *Code,
std::vector<CharSourceRange> &Ranges) {
if (!LineRanges.empty()) {
if (!Offsets.empty() || !Lengths.empty()) {
llvm::errs() << "error: cannot use -lines with -offset/-length\n";
return true;
}
for (unsigned i = 0, e = LineRanges.size(); i < e; ++i) {
unsigned FromLine, ToLine;
if (parseLineRange(LineRanges[i], FromLine, ToLine)) {
llvm::errs() << "error: invalid <start line>:<end line> pair\n";
return true;
}
if (FromLine > ToLine) {
llvm::errs() << "error: start line should be less than end line\n";
return true;
}
SourceLocation Start = Sources.translateLineCol(ID, FromLine, 1);
SourceLocation End = Sources.translateLineCol(ID, ToLine, UINT_MAX);
if (Start.isInvalid() || End.isInvalid())
return true;
Ranges.push_back(CharSourceRange::getCharRange(Start, End));
}
return false;
}
if (Offsets.empty())
Offsets.push_back(0);
if (Offsets.size() != Lengths.size() &&
!(Offsets.size() == 1 && Lengths.empty())) {
llvm::errs()
<< "error: number of -offset and -length arguments must match.\n";
return true;
}
for (unsigned i = 0, e = Offsets.size(); i != e; ++i) {
if (Offsets[i] >= Code->getBufferSize()) {
llvm::errs() << "error: offset " << Offsets[i]
<< " is outside the file\n";
return true;
}
SourceLocation Start =
Sources.getLocForStartOfFile(ID).getLocWithOffset(Offsets[i]);
SourceLocation End;
if (i < Lengths.size()) {
if (Offsets[i] + Lengths[i] > Code->getBufferSize()) {
llvm::errs() << "error: invalid length " << Lengths[i]
<< ", offset + length (" << Offsets[i] + Lengths[i]
<< ") is outside the file.\n";
return true;
}
End = Start.getLocWithOffset(Lengths[i]);
} else {
End = Sources.getLocForEndOfFile(ID);
}
Ranges.push_back(CharSourceRange::getCharRange(Start, End));
}
return false;
}
static void outputReplacementXML(StringRef Text) {
size_t From = 0;
size_t Index;
while ((Index = Text.find_first_of("\n\r", From)) != StringRef::npos) {
llvm::outs() << Text.substr(From, Index - From);
switch (Text[Index]) {
case '\n':
llvm::outs() << " ";
break;
case '\r':
llvm::outs() << " ";
break;
default:
llvm_unreachable("Unexpected character encountered!");
}
From = Index + 1;
}
llvm::outs() << Text.substr(From);
}
// Returns true on error.
static bool format(StringRef FileName) {
FileManager Files((FileSystemOptions()));
DiagnosticsEngine Diagnostics(
IntrusiveRefCntPtr<DiagnosticIDs>(new DiagnosticIDs),
new DiagnosticOptions);
SourceManager Sources(Diagnostics, Files);
OwningPtr<MemoryBuffer> Code;
if (error_code ec = MemoryBuffer::getFileOrSTDIN(FileName, Code)) {
llvm::errs() << ec.message() << "\n";
return true;
}
if (Code->getBufferSize() == 0)
return false; // Empty files are formatted correctly.
FileID ID = createInMemoryFile(FileName, Code.get(), Sources, Files);
std::vector<CharSourceRange> Ranges;
if (fillRanges(Sources, ID, Code.get(), Ranges))
return true;
FormatStyle FormatStyle = getStyle(
Style, (FileName == "-") ? AssumeFilename : FileName, FallbackStyle);
Lexer Lex(ID, Sources.getBuffer(ID), Sources,
getFormattingLangOpts(FormatStyle.Standard));
tooling::Replacements Replaces = reformat(FormatStyle, Lex, Sources, Ranges);
if (OutputXML) {
llvm::outs()
<< "<?xml version='1.0'?>\n<replacements xml:space='preserve'>\n";
for (tooling::Replacements::const_iterator I = Replaces.begin(),
E = Replaces.end();
I != E; ++I) {
llvm::outs() << "<replacement "
<< "offset='" << I->getOffset() << "' "
<< "length='" << I->getLength() << "'>";
outputReplacementXML(I->getReplacementText());
llvm::outs() << "</replacement>\n";
}
llvm::outs() << "</replacements>\n";
} else {
Rewriter Rewrite(Sources, LangOptions());
tooling::applyAllReplacements(Replaces, Rewrite);
if (Inplace) {
if (Rewrite.overwriteChangedFiles())
return true;
} else {
if (Cursor.getNumOccurrences() != 0)
outs() << "{ \"Cursor\": " << tooling::shiftedCodePosition(
Replaces, Cursor) << " }\n";
Rewrite.getEditBuffer(ID).write(outs());
}
}
return false;
}
} // namespace format
} // namespace clang
static void PrintVersion() {
raw_ostream &OS = outs();
OS << clang::getClangToolFullVersion("clang-format") << '\n';
}
int main(int argc, const char **argv) {
llvm::sys::PrintStackTraceOnErrorSignal();
// Hide unrelated options.
StringMap<cl::Option*> Options;
cl::getRegisteredOptions(Options);
for (StringMap<cl::Option *>::iterator I = Options.begin(), E = Options.end();
I != E; ++I) {
if (I->second->Category != &ClangFormatCategory && I->first() != "help" &&
I->first() != "version")
I->second->setHiddenFlag(cl::ReallyHidden);
}
cl::SetVersionPrinter(PrintVersion);
cl::ParseCommandLineOptions(
argc, argv,
"A tool to format C/C++/Obj-C code.\n\n"
"If no arguments are specified, it formats the code from standard input\n"
"and writes the result to the standard output.\n"
"If <file>s are given, it reformats the files. If -i is specified\n"
"together with <file>s, the files are edited in-place. Otherwise, the\n"
"result is written to the standard output.\n");
if (Help)
cl::PrintHelpMessage();
if (DumpConfig) {
std::string Config =
clang::format::configurationAsText(clang::format::getStyle(
Style, FileNames.empty() ? AssumeFilename : FileNames[0],
FallbackStyle));
llvm::outs() << Config << "\n";
return 0;
}
bool Error = false;
switch (FileNames.size()) {
case 0:
Error = clang::format::format("-");
break;
case 1:
Error = clang::format::format(FileNames[0]);
break;
default:
if (!Offsets.empty() || !Lengths.empty() || !LineRanges.empty()) {
llvm::errs() << "error: -offset, -length and -lines can only be used for "
"single file.\n";
return 1;
}
for (unsigned i = 0; i < FileNames.size(); ++i)
Error |= clang::format::format(FileNames[i]);
break;
}
return Error ? 1 : 0;
}
<|endoftext|> |
<commit_before>/*
Copyright 2008 Brain Research Institute, Melbourne, Australia
Written by J-Donald Tournier, 27/11/09.
This file is part of MRtrix.
MRtrix 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.
MRtrix 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 MRtrix. If not, see <http://www.gnu.org/licenses/>.
*/
#include "command.h"
#include "progressbar.h"
#include "memory.h"
#include "image.h"
// #include "header.h"
#include "algo/threaded_loop.h"
#include "math/math.h"
#include "math/median.h"
#include <limits>
#include <vector>
using namespace MR;
using namespace App;
const char* operations[] = {
"mean",
"median",
"sum",
"product",
"rms",
"var",
"std",
"min",
"max",
"absmax", // Maximum of absolute values
"magmax", // Value for which the magnitude is the maximum (i.e. preserves signed-ness)
NULL
};
void usage ()
{
DESCRIPTION
+ "compute summary statistic on image intensities either across images, "
"or along a specified axis for a single image. Supported operations are:"
+ "mean, median, sum, product, rms (root-mean-square value), var (unbiased variance), "
"std (unbiased standard deviation), min, max, absmax (maximum absolute value), "
"magmax (value with maximum absolute value, preserving its sign)."
+ "See also 'mrcalc' to compute per-voxel operations.";
ARGUMENTS
+ Argument ("input", "the input image.").type_image_in ().allow_multiple()
+ Argument ("operation", "the operation to apply, one of: " + join(operations, ", ") + ".").type_choice (operations)
+ Argument ("output", "the output image.").type_image_out ();
OPTIONS
+ Option ("axis", "perform operation along a specified axis of a single input image")
+ Argument ("index").type_integer();
}
typedef float value_type;
class Mean {
public:
Mean () : sum (0.0), count (0) { }
void operator() (value_type val) {
if (std::isfinite (val)) {
sum += val;
++count;
}
}
value_type result () const {
if (!count)
return NAN;
return sum / count;
}
double sum;
size_t count;
};
class Median {
public:
Median () { }
void operator() (value_type val) {
if (!std::isnan (val))
values.push_back(val);
}
value_type result () {
return Math::median(values);
}
std::vector<value_type> values;
};
class Sum {
public:
Sum () : sum (0.0) { }
void operator() (value_type val) {
if (std::isfinite (val))
sum += val;
}
value_type result () const {
return sum;
}
double sum;
};
class Product {
public:
Product () : product (0.0) { }
void operator() (value_type val) {
if (std::isfinite (val))
product += val;
}
value_type result () const {
return product;
}
double product;
};
class RMS {
public:
RMS() : sum (0.0), count (0) { }
void operator() (value_type val) {
if (std::isfinite (val)) {
sum += Math::pow2 (val);
++count;
}
}
value_type result() const {
if (!count)
return NAN;
return std::sqrt(sum / count);
}
double sum;
size_t count;
};
class Var {
public:
Var () : sum (0.0), sum_sqr (0.0), count (0) { }
void operator() (value_type val) {
if (std::isfinite (val)) {
sum += val;
sum_sqr += Math::pow2 (val);
++count;
}
}
value_type result () const {
if (count < 2)
return NAN;
return (sum_sqr - Math::pow2 (sum) / static_cast<double> (count)) / (static_cast<double> (count) - 1.0);
}
double sum, sum_sqr;
size_t count;
};
class Std : public Var {
public:
Std() : Var() { }
value_type result () const { return std::sqrt (Var::result()); }
};
class Min {
public:
Min () : min (std::numeric_limits<value_type>::infinity()) { }
void operator() (value_type val) {
if (std::isfinite (val) && val < min)
min = val;
}
value_type result () const { return std::isfinite (min) ? min : NAN; }
value_type min;
};
class Max {
public:
Max () : max (-std::numeric_limits<value_type>::infinity()) { }
void operator() (value_type val) {
if (std::isfinite (val) && val > max)
max = val;
}
value_type result () const { return std::isfinite (max) ? max : NAN; }
value_type max;
};
class AbsMax {
public:
AbsMax () : max (-std::numeric_limits<value_type>::infinity()) { }
void operator() (value_type val) {
if (std::isfinite (val) && std::abs(val) > max)
max = std::abs(val);
}
value_type result () const { return std::isfinite (max) ? max : NAN; }
value_type max;
};
class MagMax {
public:
MagMax () : max (-std::numeric_limits<value_type>::infinity()) { }
MagMax (const int i) : max (-std::numeric_limits<value_type>::infinity()) { }
void operator() (value_type val) {
if (std::isfinite (val) && (!std::isfinite (max) || std::abs(val) > std::abs (max)))
max = val;
}
value_type result () const { return std::isfinite (max) ? max : NAN; }
value_type max;
};
template <class Operation>
class AxisKernel {
public:
AxisKernel (size_t axis) : axis (axis) { }
template <class InputImageType, class OutputImageType>
void operator() (InputImageType& in, OutputImageType& out) {
Operation op;
for (in[axis] = 0; in[axis] < in.size(axis); ++in[axis])
op (in.value());
out.value() = op.result();
}
protected:
const size_t axis;
};
class ImageKernelBase {
public:
ImageKernelBase (const std::string& path) :
output_path (path) { }
virtual ~ImageKernelBase() { }
virtual void process (const Header& image_in) = 0;
protected:
const std::string output_path;
};
template <class Operation>
class ImageKernel : public ImageKernelBase {
protected:
class InitFunctor {
public:
template <class ImageType>
void operator() (ImageType& out) const { out.value() = Operation(); }
};
class ProcessFunctor {
public:
template <class ImageType1, class ImageType2>
void operator() (ImageType1& out, ImageType2& in) const {
Operation op = out.value();
op (in.value());
out.value() = op;
}
};
class ResultFunctor {
public:
template <class ImageType1, class ImageType2>
void operator() (ImageType1& out, ImageType2& in) const {
Operation op = in.value();
out.value() = op.result();
}
};
public:
ImageKernel (const Header& header, const std::string& path) :
ImageKernelBase (path),
header (header),
image (header) {
ThreadedLoop (image).run (InitFunctor(), image);
}
~ImageKernel()
{
Image<value_type> out (output_path, header);
ThreadedLoop (image).run (ResultFunctor(), out, image);
}
void process (const Header& image_in)
{
Image<value_type> in (image_in);
ThreadedLoop (image).run (ProcessFunctor(), image, in);
}
protected:
const Header& header;
Image<Operation> image;
};
void run ()
{
const size_t num_inputs = argument.size() - 2;
const int op = argument[num_inputs];
const std::string& output_path = argument.back();
Options opt = get_options ("axis");
if (opt.size()) {
if (num_inputs != 1)
throw Exception ("Option -axis only applies if a single input image is used");
const size_t axis = opt[0][0];
auto image_in = Header::open (argument[0]).get_image<value_type>().with_direct_io (Stride::contiguous_along_axis (axis));
if (axis >= image_in.ndim())
throw Exception ("Cannot perform operation along axis " + str (axis) + "; image only has " + str(image_in.ndim()) + " axes");
Header header_out (image_in.header());
header_out.datatype() = DataType::Float32;
header_out.size(axis) = 1;
squeeze_dim (header_out);
auto image_out = Header::create (output_path, header_out).get_image<float>();
// auto image_out = Header::allocate (header_out).get_image<float>();
// Image image_out (output_path, header_out);
ThreadedLoop loop (std::string("computing ") + operations[op] + " along axis " + str(axis) + "...", image_out);
switch (op) {
case 0: loop.run (AxisKernel<Mean> (axis), image_in, image_out); return;
case 1: loop.run (AxisKernel<Median> (axis), image_in, image_out); return;
case 2: loop.run (AxisKernel<Sum> (axis), image_in, image_out); return;
case 3: loop.run (AxisKernel<Product>(axis), image_in, image_out); return;
case 4: loop.run (AxisKernel<RMS> (axis), image_in, image_out); return;
case 5: loop.run (AxisKernel<Var> (axis), image_in, image_out); return;
case 6: loop.run (AxisKernel<Std> (axis), image_in, image_out); return;
case 7: loop.run (AxisKernel<Min> (axis), image_in, image_out); return;
case 8: loop.run (AxisKernel<Max> (axis), image_in, image_out); return;
case 9: loop.run (AxisKernel<AbsMax> (axis), image_in, image_out); return;
case 10: loop.run (AxisKernel<MagMax> (axis), image_in, image_out); return;
default: assert (0);
}
} else {
if (num_inputs < 2)
throw Exception ("mrmath requires either multiple input images, or the -axis option to be provided");
// Pre-load all image headers
std::vector<std::unique_ptr<Header>> headers_in;
// Header of first input image is the template to which all other input images are compared
// auto header = Header::open (argument[0]);
headers_in.push_back (std::unique_ptr<Header> (new Header::open (argument[0])));
Header header (*headers_in[0]);
// Wipe any excess unary-dimensional axes
while (header.dim (header.ndim() - 1) == 1)
header.set_ndim (header.ndim() - 1);
// Verify that dimensions of all input images adequately match
for (size_t i = 1; i != num_inputs; ++i) {
const std::string path = argument[i];
headers_in.push_back (std::unique_ptr<Header> (new Header::open (path)));
const Header& temp (*headers_in[i]);
if (temp.ndim() < header.ndim())
throw Exception ("Image " + path + " has fewer axes than first imput image " + header.name());
for (size_t axis = 0; axis != header.ndim(); ++axis) {
if (temp.dim(axis) != header.dim(axis))
throw Exception ("Dimensions of image " + path + " do not match those of first input image " + header.name());
}
for (size_t axis = header.ndim(); axis != temp.ndim(); ++axis) {
if (temp.dim(axis) != 1)
throw Exception ("Image " + path + " has axis with non-unary dimension beyond first input image " + header.name());
}
}
// Instantiate a kernel depending on the operation requested
std::unique_ptr<ImageKernelBase> kernel;
switch (op) {
case 0: kernel.reset (new ImageKernel<Mean> (header, output_path)); break;
case 1: kernel.reset (new ImageKernel<Median> (header, output_path)); break;
case 2: kernel.reset (new ImageKernel<Sum> (header, output_path)); break;
case 3: kernel.reset (new ImageKernel<Product> (header, output_path)); break;
case 4: kernel.reset (new ImageKernel<RMS> (header, output_path)); break;
case 5: kernel.reset (new ImageKernel<Var> (header, output_path)); break;
case 6: kernel.reset (new ImageKernel<Std> (header, output_path)); break;
case 7: kernel.reset (new ImageKernel<Min> (header, output_path)); break;
case 8: kernel.reset (new ImageKernel<Max> (header, output_path)); break;
case 9: kernel.reset (new ImageKernel<AbsMax> (header, output_path)); break;
case 10: kernel.reset (new ImageKernel<MagMax> (header, output_path)); break;
default: assert (0);
}
// Feed the input images to the kernel one at a time
{
ProgressBar progress (std::string("computing ") + operations[op] + " across "
+ str(headers_in.size()) + " images...", num_inputs);
for (size_t i = 0; i != headers_in.size(); ++i) {
kernel->process (*headers_in[i]);
++progress;
}
}
// Image output is handled by the kernel destructor
}
}
<commit_msg>syntax overhaul: mrmath: still incomplete<commit_after>/*
Copyright 2008 Brain Research Institute, Melbourne, Australia
Written by J-Donald Tournier, 27/11/09.
This file is part of MRtrix.
MRtrix 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.
MRtrix 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 MRtrix. If not, see <http://www.gnu.org/licenses/>.
*/
#include "command.h"
#include "progressbar.h"
#include "memory.h"
#include "image.h"
// #include "header.h"
#include "algo/threaded_loop.h"
#include "math/math.h"
#include "math/median.h"
#include <limits>
#include <vector>
using namespace MR;
using namespace App;
const char* operations[] = {
"mean",
"median",
"sum",
"product",
"rms",
"var",
"std",
"min",
"max",
"absmax", // Maximum of absolute values
"magmax", // Value for which the magnitude is the maximum (i.e. preserves signed-ness)
NULL
};
void usage ()
{
DESCRIPTION
+ "compute summary statistic on image intensities either across images, "
"or along a specified axis for a single image. Supported operations are:"
+ "mean, median, sum, product, rms (root-mean-square value), var (unbiased variance), "
"std (unbiased standard deviation), min, max, absmax (maximum absolute value), "
"magmax (value with maximum absolute value, preserving its sign)."
+ "See also 'mrcalc' to compute per-voxel operations.";
ARGUMENTS
+ Argument ("input", "the input image.").type_image_in ().allow_multiple()
+ Argument ("operation", "the operation to apply, one of: " + join(operations, ", ") + ".").type_choice (operations)
+ Argument ("output", "the output image.").type_image_out ();
OPTIONS
+ Option ("axis", "perform operation along a specified axis of a single input image")
+ Argument ("index").type_integer();
}
typedef float value_type;
class Mean {
public:
Mean () : sum (0.0), count (0) { }
void operator() (value_type val) {
if (std::isfinite (val)) {
sum += val;
++count;
}
}
value_type result () const {
if (!count)
return NAN;
return sum / count;
}
double sum;
size_t count;
};
class Median {
public:
Median () { }
void operator() (value_type val) {
if (!std::isnan (val))
values.push_back(val);
}
value_type result () {
return Math::median(values);
}
std::vector<value_type> values;
};
class Sum {
public:
Sum () : sum (0.0) { }
void operator() (value_type val) {
if (std::isfinite (val))
sum += val;
}
value_type result () const {
return sum;
}
double sum;
};
class Product {
public:
Product () : product (0.0) { }
void operator() (value_type val) {
if (std::isfinite (val))
product += val;
}
value_type result () const {
return product;
}
double product;
};
class RMS {
public:
RMS() : sum (0.0), count (0) { }
void operator() (value_type val) {
if (std::isfinite (val)) {
sum += Math::pow2 (val);
++count;
}
}
value_type result() const {
if (!count)
return NAN;
return std::sqrt(sum / count);
}
double sum;
size_t count;
};
class Var {
public:
Var () : sum (0.0), sum_sqr (0.0), count (0) { }
void operator() (value_type val) {
if (std::isfinite (val)) {
sum += val;
sum_sqr += Math::pow2 (val);
++count;
}
}
value_type result () const {
if (count < 2)
return NAN;
return (sum_sqr - Math::pow2 (sum) / static_cast<double> (count)) / (static_cast<double> (count) - 1.0);
}
double sum, sum_sqr;
size_t count;
};
class Std : public Var {
public:
Std() : Var() { }
value_type result () const { return std::sqrt (Var::result()); }
};
class Min {
public:
Min () : min (std::numeric_limits<value_type>::infinity()) { }
void operator() (value_type val) {
if (std::isfinite (val) && val < min)
min = val;
}
value_type result () const { return std::isfinite (min) ? min : NAN; }
value_type min;
};
class Max {
public:
Max () : max (-std::numeric_limits<value_type>::infinity()) { }
void operator() (value_type val) {
if (std::isfinite (val) && val > max)
max = val;
}
value_type result () const { return std::isfinite (max) ? max : NAN; }
value_type max;
};
class AbsMax {
public:
AbsMax () : max (-std::numeric_limits<value_type>::infinity()) { }
void operator() (value_type val) {
if (std::isfinite (val) && std::abs(val) > max)
max = std::abs(val);
}
value_type result () const { return std::isfinite (max) ? max : NAN; }
value_type max;
};
class MagMax {
public:
MagMax () : max (-std::numeric_limits<value_type>::infinity()) { }
MagMax (const int i) : max (-std::numeric_limits<value_type>::infinity()) { }
void operator() (value_type val) {
if (std::isfinite (val) && (!std::isfinite (max) || std::abs(val) > std::abs (max)))
max = val;
}
value_type result () const { return std::isfinite (max) ? max : NAN; }
value_type max;
};
template <class Operation>
class AxisKernel {
public:
AxisKernel (size_t axis) : axis (axis) { }
template <class InputImageType, class OutputImageType>
void operator() (InputImageType& in, OutputImageType& out) {
Operation op;
for (in[axis] = 0; in[axis] < in.size(axis); ++in[axis])
op (in.value());
out.value() = op.result();
}
protected:
const size_t axis;
};
class ImageKernelBase {
public:
ImageKernelBase (const std::string& path) :
output_path (path) { }
virtual ~ImageKernelBase() { }
virtual void process (const Header& image_in) = 0;
protected:
const std::string output_path;
};
template <class Operation>
class ImageKernel : public ImageKernelBase {
protected:
class InitFunctor {
public:
template <class ImageType>
void operator() (ImageType& out) const { out.value() = Operation(); }
};
class ProcessFunctor {
public:
template <class ImageType1, class ImageType2>
void operator() (ImageType1& out, ImageType2& in) const {
Operation op = out.value();
op (in.value());
out.value() = op;
}
};
class ResultFunctor {
public:
template <class ImageType1, class ImageType2>
void operator() (ImageType1& out, ImageType2& in) const {
Operation op = in.value();
out.value() = op.result();
}
};
public:
ImageKernel (const Header& header, const std::string& path) :
ImageKernelBase (path),
header (header){
image = header.get_image<float>();
ThreadedLoop (image).run (InitFunctor(), image);
}
~ImageKernel()
{
Image<value_type> out (output_path, header);
ThreadedLoop (image).run (ResultFunctor(), out, image);
}
void process (const Header& image_in)
{
Image<value_type> in (image_in);
ThreadedLoop (image).run (ProcessFunctor(), image, in);
}
protected:
const Header& header;
Image<float> image;
// Image<Operation> image;
};
void run ()
{
const size_t num_inputs = argument.size() - 2;
const int op = argument[num_inputs];
const std::string& output_path = argument.back();
Options opt = get_options ("axis");
if (opt.size()) {
if (num_inputs != 1)
throw Exception ("Option -axis only applies if a single input image is used");
const size_t axis = opt[0][0];
auto image_in = Header::open (argument[0]).get_image<value_type>().with_direct_io (Stride::contiguous_along_axis (axis));
if (axis >= image_in.ndim())
throw Exception ("Cannot perform operation along axis " + str (axis) + "; image only has " + str(image_in.ndim()) + " axes");
Header header_out (image_in.header());
header_out.datatype() = DataType::Float32;
header_out.size(axis) = 1;
squeeze_dim (header_out);
auto image_out = Header::create (output_path, header_out).get_image<float>();
// auto image_out = Header::allocate (header_out).get_image<float>();
// Image image_out (output_path, header_out);
ThreadedLoop loop (std::string("computing ") + operations[op] + " along axis " + str(axis) + "...", image_out);
switch (op) {
case 0: loop.run (AxisKernel<Mean> (axis), image_in, image_out); return;
case 1: loop.run (AxisKernel<Median> (axis), image_in, image_out); return;
case 2: loop.run (AxisKernel<Sum> (axis), image_in, image_out); return;
case 3: loop.run (AxisKernel<Product>(axis), image_in, image_out); return;
case 4: loop.run (AxisKernel<RMS> (axis), image_in, image_out); return;
case 5: loop.run (AxisKernel<Var> (axis), image_in, image_out); return;
case 6: loop.run (AxisKernel<Std> (axis), image_in, image_out); return;
case 7: loop.run (AxisKernel<Min> (axis), image_in, image_out); return;
case 8: loop.run (AxisKernel<Max> (axis), image_in, image_out); return;
case 9: loop.run (AxisKernel<AbsMax> (axis), image_in, image_out); return;
case 10: loop.run (AxisKernel<MagMax> (axis), image_in, image_out); return;
default: assert (0);
}
} else {
if (num_inputs < 2)
throw Exception ("mrmath requires either multiple input images, or the -axis option to be provided");
// Pre-load all image headers
std::vector<Header> headers_in;
// std::vector<std::unique_ptr<Header>> headers_in;
// Header of first input image is the template to which all other input images are compared
// auto header = Header::open (argument[0]);
// headers_in.push_back (std::unique_ptr<Header> (new Header (Header::open (argument[0]))));
headers_in.push_back (Header::open (argument[0]));
Header header (headers_in[0]);
// Wipe any excess unary-dimensional axes
while (header.size (header.ndim() - 1) == 1)
header.set_ndim (header.ndim() - 1);
// Verify that dimensions of all input images adequately match
for (size_t i = 1; i != num_inputs; ++i) {
const std::string path = argument[i];
// headers_in.push_back (std::unique_ptr<Header> (new Header (Header::open (path))));
headers_in.push_back (Header::open (path));
const Header temp (headers_in[i]);
if (temp.ndim() < header.ndim())
throw Exception ("Image " + path + " has fewer axes than first imput image " + header.name());
for (size_t axis = 0; axis != header.ndim(); ++axis) {
if (temp.size(axis) != header.size(axis))
throw Exception ("Dimensions of image " + path + " do not match those of first input image " + header.name());
}
for (size_t axis = header.ndim(); axis != temp.ndim(); ++axis) {
if (temp.size(axis) != 1)
throw Exception ("Image " + path + " has axis with non-unary dimension beyond first input image " + header.name());
}
}
// Instantiate a kernel depending on the operation requested
std::unique_ptr<ImageKernelBase> kernel;
switch (op) {
case 0: kernel.reset (new ImageKernel<Mean> (header, output_path)); break;
case 1: kernel.reset (new ImageKernel<Median> (header, output_path)); break;
case 2: kernel.reset (new ImageKernel<Sum> (header, output_path)); break;
case 3: kernel.reset (new ImageKernel<Product> (header, output_path)); break;
case 4: kernel.reset (new ImageKernel<RMS> (header, output_path)); break;
case 5: kernel.reset (new ImageKernel<Var> (header, output_path)); break;
case 6: kernel.reset (new ImageKernel<Std> (header, output_path)); break;
case 7: kernel.reset (new ImageKernel<Min> (header, output_path)); break;
case 8: kernel.reset (new ImageKernel<Max> (header, output_path)); break;
case 9: kernel.reset (new ImageKernel<AbsMax> (header, output_path)); break;
case 10: kernel.reset (new ImageKernel<MagMax> (header, output_path)); break;
default: assert (0);
}
// Feed the input images to the kernel one at a time
{
ProgressBar progress (std::string("computing ") + operations[op] + " across "
+ str(headers_in.size()) + " images...", num_inputs);
for (size_t i = 0; i != headers_in.size(); ++i) {
kernel->process (headers_in[i]);
++progress;
}
}
// Image output is handled by the kernel destructor
}
}
<|endoftext|> |
<commit_before>// Copyright (c) 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/test_file_util.h"
#include <windows.h>
#include <vector>
#include "base/file_util.h"
#include "base/scoped_handle.h"
namespace file_util {
// We could use GetSystemInfo to get the page size, but this serves
// our purpose fine since 4K is the page size on x86 as well as x64.
static const ptrdiff_t kPageSize = 4096;
bool EvictFileFromSystemCache(const wchar_t* file) {
// Request exclusive access to the file and overwrite it with no buffering.
ScopedHandle file_handle(
CreateFile(file, GENERIC_READ | GENERIC_WRITE, 0, NULL,
OPEN_EXISTING, FILE_FLAG_NO_BUFFERING, NULL));
if (!file_handle)
return false;
// Get some attributes to restore later.
BY_HANDLE_FILE_INFORMATION bhi = {0};
CHECK(::GetFileInformationByHandle(file_handle, &bhi));
// Execute in chunks. It could be optimized. We want to do few of these since
// these operations will be slow without the cache.
// Non-buffered reads and writes need to be sector aligned and since sector
// sizes typically range from 512-4096 bytes, we just use the page size.
// The buffer size is twice the size of a page (minus one) since we need to
// get an aligned pointer into the buffer that we can use.
char buffer[2 * kPageSize - 1];
// Get an aligned pointer into buffer.
char* read_write = reinterpret_cast<char*>(
reinterpret_cast<ptrdiff_t>(buffer + kPageSize - 1) & ~(kPageSize - 1));
DCHECK((reinterpret_cast<int>(read_write) % kPageSize) == 0);
// If the file size isn't a multiple of kPageSize, we'll need special
// processing.
bool file_is_page_aligned = true;
int total_bytes = 0;
DWORD bytes_read, bytes_written;
for (;;) {
bytes_read = 0;
ReadFile(file_handle, read_write, kPageSize, &bytes_read, NULL);
if (bytes_read == 0)
break;
if (bytes_read < kPageSize) {
// Zero out the remaining part of the buffer.
// WriteFile will fail if we provide a buffer size that isn't a
// sector multiple, so we'll have to write the entire buffer with
// padded zeros and then use SetEndOfFile to truncate the file.
ZeroMemory(read_write + bytes_read, kPageSize - bytes_read);
file_is_page_aligned = false;
}
// Move back to the position we just read from.
// Note that SetFilePointer will also fail if total_bytes isn't sector
// aligned, but that shouldn't happen here.
DCHECK((total_bytes % kPageSize) == 0);
SetFilePointer(file_handle, total_bytes, NULL, FILE_BEGIN);
if (!WriteFile(file_handle, read_write, kPageSize, &bytes_written, NULL) ||
bytes_written != kPageSize) {
DCHECK(false);
return false;
}
total_bytes += bytes_read;
// If this is false, then we just processed the last portion of the file.
if (!file_is_page_aligned)
break;
}
if (!file_is_page_aligned) {
// The size of the file isn't a multiple of the page size, so we'll have
// to open the file again, this time without the FILE_FLAG_NO_BUFFERING
// flag and use SetEndOfFile to mark EOF.
file_handle.Set(CreateFile(file, GENERIC_WRITE, 0, NULL, OPEN_EXISTING,
0, NULL));
CHECK(SetFilePointer(file_handle, total_bytes, NULL, FILE_BEGIN) !=
INVALID_SET_FILE_POINTER);
CHECK(::SetEndOfFile(file_handle));
}
// Restore the file attributes.
CHECK(::SetFileTime(file_handle, &bhi.ftCreationTime, &bhi.ftLastAccessTime,
&bhi.ftLastWriteTime));
return true;
}
// Like CopyFileNoCache but recursively copies all files and subdirectories
// in the given input directory to the output directory.
bool CopyRecursiveDirNoCache(const std::wstring& source_dir,
const std::wstring& dest_dir) {
// Try to create the directory if it doesn't already exist.
if (!CreateDirectory(dest_dir)) {
if (GetLastError() != ERROR_ALREADY_EXISTS)
return false;
}
std::vector<std::wstring> files_copied;
std::wstring src(source_dir);
file_util::AppendToPath(&src, L"*");
WIN32_FIND_DATA fd;
HANDLE fh = FindFirstFile(src.c_str(), &fd);
if (fh == INVALID_HANDLE_VALUE)
return false;
do {
std::wstring cur_file(fd.cFileName);
if (cur_file == L"." || cur_file == L"..")
continue; // Skip these special entries.
std::wstring cur_source_path(source_dir);
file_util::AppendToPath(&cur_source_path, cur_file);
std::wstring cur_dest_path(dest_dir);
file_util::AppendToPath(&cur_dest_path, cur_file);
if (fd.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) {
// Recursively copy a subdirectory. We stripped "." and ".." already.
if (!CopyRecursiveDirNoCache(cur_source_path, cur_dest_path)) {
FindClose(fh);
return false;
}
} else {
// Copy the file.
if (!::CopyFile(cur_source_path.c_str(), cur_dest_path.c_str(), false)) {
FindClose(fh);
return false;
}
// We don't check for errors from this function, often, we are copying
// files that are in the repository, and they will have read-only set.
// This will prevent us from evicting from the cache, but these don't
// matter anyway.
EvictFileFromSystemCache(cur_dest_path.c_str());
}
} while (FindNextFile(fh, &fd));
FindClose(fh);
return true;
}
} // namespace file_util
<commit_msg>Fix CloseHandle blunder. I was thinking that the handle would be closed by Set, but of course I need to close the handle before the CreateFile call... doh!<commit_after>// Copyright (c) 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/test_file_util.h"
#include <windows.h>
#include <vector>
#include "base/file_util.h"
#include "base/scoped_handle.h"
namespace file_util {
// We could use GetSystemInfo to get the page size, but this serves
// our purpose fine since 4K is the page size on x86 as well as x64.
static const ptrdiff_t kPageSize = 4096;
bool EvictFileFromSystemCache(const wchar_t* file) {
// Request exclusive access to the file and overwrite it with no buffering.
ScopedHandle file_handle(
CreateFile(file, GENERIC_READ | GENERIC_WRITE, 0, NULL,
OPEN_EXISTING, FILE_FLAG_NO_BUFFERING, NULL));
if (!file_handle)
return false;
// Get some attributes to restore later.
BY_HANDLE_FILE_INFORMATION bhi = {0};
CHECK(::GetFileInformationByHandle(file_handle, &bhi));
// Execute in chunks. It could be optimized. We want to do few of these since
// these operations will be slow without the cache.
// Non-buffered reads and writes need to be sector aligned and since sector
// sizes typically range from 512-4096 bytes, we just use the page size.
// The buffer size is twice the size of a page (minus one) since we need to
// get an aligned pointer into the buffer that we can use.
char buffer[2 * kPageSize - 1];
// Get an aligned pointer into buffer.
char* read_write = reinterpret_cast<char*>(
reinterpret_cast<ptrdiff_t>(buffer + kPageSize - 1) & ~(kPageSize - 1));
DCHECK((reinterpret_cast<int>(read_write) % kPageSize) == 0);
// If the file size isn't a multiple of kPageSize, we'll need special
// processing.
bool file_is_page_aligned = true;
int total_bytes = 0;
DWORD bytes_read, bytes_written;
for (;;) {
bytes_read = 0;
ReadFile(file_handle, read_write, kPageSize, &bytes_read, NULL);
if (bytes_read == 0)
break;
if (bytes_read < kPageSize) {
// Zero out the remaining part of the buffer.
// WriteFile will fail if we provide a buffer size that isn't a
// sector multiple, so we'll have to write the entire buffer with
// padded zeros and then use SetEndOfFile to truncate the file.
ZeroMemory(read_write + bytes_read, kPageSize - bytes_read);
file_is_page_aligned = false;
}
// Move back to the position we just read from.
// Note that SetFilePointer will also fail if total_bytes isn't sector
// aligned, but that shouldn't happen here.
DCHECK((total_bytes % kPageSize) == 0);
SetFilePointer(file_handle, total_bytes, NULL, FILE_BEGIN);
if (!WriteFile(file_handle, read_write, kPageSize, &bytes_written, NULL) ||
bytes_written != kPageSize) {
DCHECK(false);
return false;
}
total_bytes += bytes_read;
// If this is false, then we just processed the last portion of the file.
if (!file_is_page_aligned)
break;
}
if (!file_is_page_aligned) {
// The size of the file isn't a multiple of the page size, so we'll have
// to open the file again, this time without the FILE_FLAG_NO_BUFFERING
// flag and use SetEndOfFile to mark EOF.
file_handle.Set(NULL);
file_handle.Set(CreateFile(file, GENERIC_WRITE, 0, NULL, OPEN_EXISTING,
0, NULL));
CHECK(SetFilePointer(file_handle, total_bytes, NULL, FILE_BEGIN) !=
INVALID_SET_FILE_POINTER);
CHECK(::SetEndOfFile(file_handle));
}
// Restore the file attributes.
CHECK(::SetFileTime(file_handle, &bhi.ftCreationTime, &bhi.ftLastAccessTime,
&bhi.ftLastWriteTime));
return true;
}
// Like CopyFileNoCache but recursively copies all files and subdirectories
// in the given input directory to the output directory.
bool CopyRecursiveDirNoCache(const std::wstring& source_dir,
const std::wstring& dest_dir) {
// Try to create the directory if it doesn't already exist.
if (!CreateDirectory(dest_dir)) {
if (GetLastError() != ERROR_ALREADY_EXISTS)
return false;
}
std::vector<std::wstring> files_copied;
std::wstring src(source_dir);
file_util::AppendToPath(&src, L"*");
WIN32_FIND_DATA fd;
HANDLE fh = FindFirstFile(src.c_str(), &fd);
if (fh == INVALID_HANDLE_VALUE)
return false;
do {
std::wstring cur_file(fd.cFileName);
if (cur_file == L"." || cur_file == L"..")
continue; // Skip these special entries.
std::wstring cur_source_path(source_dir);
file_util::AppendToPath(&cur_source_path, cur_file);
std::wstring cur_dest_path(dest_dir);
file_util::AppendToPath(&cur_dest_path, cur_file);
if (fd.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) {
// Recursively copy a subdirectory. We stripped "." and ".." already.
if (!CopyRecursiveDirNoCache(cur_source_path, cur_dest_path)) {
FindClose(fh);
return false;
}
} else {
// Copy the file.
if (!::CopyFile(cur_source_path.c_str(), cur_dest_path.c_str(), false)) {
FindClose(fh);
return false;
}
// We don't check for errors from this function, often, we are copying
// files that are in the repository, and they will have read-only set.
// This will prevent us from evicting from the cache, but these don't
// matter anyway.
EvictFileFromSystemCache(cur_dest_path.c_str());
}
} while (FindNextFile(fh, &fd));
FindClose(fh);
return true;
}
} // namespace file_util
<|endoftext|> |
<commit_before>#include "player.hpp"
namespace msrv {
namespace player_foobar2000 {
namespace {
class TrackQueryImpl : public TrackQuery
{
public:
TrackQueryImpl(TitleFormatVector columnsVal)
: columns(std::move(columnsVal))
{
}
TitleFormatVector columns;
};
inline double clampVolume(double value)
{
return std::max(std::min(value, 0.0), static_cast<double>(playback_control::volume_mute));
}
}
std::vector<std::string> PlayerImpl::evaluatePlaybackColumns(const TitleFormatVector& compiledColumns)
{
std::vector<std::string> result;
result.reserve(compiledColumns.size());
pfc::string8 buffer;
for (auto& compiledColumn : compiledColumns)
{
auto ret = playbackControl_->playback_format_title(
nullptr,
buffer,
compiledColumn,
nullptr,
playback_control::display_level_all);
if (!ret)
{
result.clear();
return result;
}
result.emplace_back(buffer.get_ptr(), buffer.get_length());
}
return result;
}
PlaybackState PlayerImpl::getPlaybackState()
{
if (playbackControl_->is_paused())
return PlaybackState::PAUSED;
if (playbackControl_->is_playing())
return PlaybackState::PLAYING;
return PlaybackState::STOPPED;
}
void PlayerImpl::queryVolume(VolumeInfo* volume)
{
volume->type = VolumeType::DB;
volume->min = playback_control::volume_mute;
volume->max = 0.0;
volume->value = playbackControl_->get_volume();
volume->isMuted = playbackControl_->is_muted();
}
void PlayerImpl::queryActiveItem(ActiveItemInfo* info, TrackQuery* queryPtr)
{
t_size activePlaylist;
t_size activeItem;
info->position = playbackControl_->playback_get_position();
info->duration = playbackControl_->playback_get_length_ex();
if (queryPtr)
{
info->columns = evaluatePlaybackColumns(
static_cast<TrackQueryImpl*>(queryPtr)->columns);
}
if (playlistManager_->get_playing_item_location(&activePlaylist, &activeItem))
{
info->playlistId = playlists_->getId(activePlaylist);
info->playlistIndex = activePlaylist;
info->index = activeItem;
}
else
{
info->playlistIndex = -1;
info->index = -1;
}
}
PlayerStatePtr PlayerImpl::queryPlayerState(TrackQuery* activeItemQuery)
{
playlists_->ensureInitialized();
auto state = std::make_unique<PlayerState>();
state->playbackState = getPlaybackState();
queryVolume(&state->volume);
queryActiveItem(&state->activeItem, activeItemQuery);
state->playbackMode = playlistManager_->playback_order_get_active();
state->playbackModes = &playbackModes_;
return state;
}
void PlayerImpl::playCurrent()
{
playbackControl_->play_or_unpause();
}
void PlayerImpl::playItem(const PlaylistRef& plref, int32_t itemIndex)
{
auto playlist = playlists_->resolve(plref);
if (isValidItemIndex(playlist, itemIndex))
playlistManager_->playlist_execute_default_action(playlist, itemIndex);
}
void PlayerImpl::playRandom()
{
playbackControl_->start(playback_control::track_command_rand);
}
void PlayerImpl::playNext()
{
playbackControl_->next();
}
void PlayerImpl::playPrevious()
{
playbackControl_->previous();
}
void PlayerImpl::stop()
{
playbackControl_->stop();
}
void PlayerImpl::pause()
{
playbackControl_->pause(true);
}
void PlayerImpl::togglePause()
{
playbackControl_->toggle_pause();
}
void PlayerImpl::setMuted(Switch val)
{
switch (val)
{
case Switch::FALSE:
if (playbackControl_->is_muted())
playbackControl_->volume_mute_toggle();
break;
case Switch::TRUE:
if (!playbackControl_->is_muted())
playbackControl_->volume_mute_toggle();
break;
case Switch::TOGGLE:
playbackControl_->volume_mute_toggle();
break;
}
}
void PlayerImpl::seekAbsolute(double offsetSeconds)
{
playbackControl_->playback_seek(offsetSeconds);
}
void PlayerImpl::seekRelative(double offsetSeconds)
{
playbackControl_->playback_seek_delta(offsetSeconds);
}
void PlayerImpl::setVolume(double val)
{
playbackControl_->set_volume(static_cast<float>(clampVolume(val)));
}
void PlayerImpl::initPlaybackModes()
{
t_size count = playlistManager_->playback_order_get_count();
playbackModes_.reserve(count);
for (t_size i = 0; i < count; i++)
playbackModes_.emplace_back(playlistManager_->playback_order_get_name(i));
}
void PlayerImpl::setPlaybackMode(int32_t val)
{
t_size count = playlistManager_->playback_order_get_count();
if (val < 0 || static_cast<t_size>(val) >= count)
throw InvalidRequestException("Invalid playback mode");
playlistManager_->playback_order_set_active(val);
}
TrackQueryPtr PlayerImpl::createTrackQuery(const std::vector<std::string>& columns)
{
return std::make_unique<TrackQueryImpl>(compileColumns(columns));
}
}}
<commit_msg>player_control.cpp: activate playlist when playing item (fixes #55)<commit_after>#include "player.hpp"
namespace msrv {
namespace player_foobar2000 {
namespace {
class TrackQueryImpl : public TrackQuery
{
public:
TrackQueryImpl(TitleFormatVector columnsVal)
: columns(std::move(columnsVal))
{
}
TitleFormatVector columns;
};
inline double clampVolume(double value)
{
return std::max(std::min(value, 0.0), static_cast<double>(playback_control::volume_mute));
}
}
std::vector<std::string> PlayerImpl::evaluatePlaybackColumns(const TitleFormatVector& compiledColumns)
{
std::vector<std::string> result;
result.reserve(compiledColumns.size());
pfc::string8 buffer;
for (auto& compiledColumn : compiledColumns)
{
auto ret = playbackControl_->playback_format_title(
nullptr,
buffer,
compiledColumn,
nullptr,
playback_control::display_level_all);
if (!ret)
{
result.clear();
return result;
}
result.emplace_back(buffer.get_ptr(), buffer.get_length());
}
return result;
}
PlaybackState PlayerImpl::getPlaybackState()
{
if (playbackControl_->is_paused())
return PlaybackState::PAUSED;
if (playbackControl_->is_playing())
return PlaybackState::PLAYING;
return PlaybackState::STOPPED;
}
void PlayerImpl::queryVolume(VolumeInfo* volume)
{
volume->type = VolumeType::DB;
volume->min = playback_control::volume_mute;
volume->max = 0.0;
volume->value = playbackControl_->get_volume();
volume->isMuted = playbackControl_->is_muted();
}
void PlayerImpl::queryActiveItem(ActiveItemInfo* info, TrackQuery* queryPtr)
{
t_size activePlaylist;
t_size activeItem;
info->position = playbackControl_->playback_get_position();
info->duration = playbackControl_->playback_get_length_ex();
if (queryPtr)
{
info->columns = evaluatePlaybackColumns(
static_cast<TrackQueryImpl*>(queryPtr)->columns);
}
if (playlistManager_->get_playing_item_location(&activePlaylist, &activeItem))
{
info->playlistId = playlists_->getId(activePlaylist);
info->playlistIndex = activePlaylist;
info->index = activeItem;
}
else
{
info->playlistIndex = -1;
info->index = -1;
}
}
PlayerStatePtr PlayerImpl::queryPlayerState(TrackQuery* activeItemQuery)
{
playlists_->ensureInitialized();
auto state = std::make_unique<PlayerState>();
state->playbackState = getPlaybackState();
queryVolume(&state->volume);
queryActiveItem(&state->activeItem, activeItemQuery);
state->playbackMode = playlistManager_->playback_order_get_active();
state->playbackModes = &playbackModes_;
return state;
}
void PlayerImpl::playCurrent()
{
playbackControl_->play_or_unpause();
}
void PlayerImpl::playItem(const PlaylistRef& plref, int32_t itemIndex)
{
auto playlist = playlists_->resolve(plref);
if (!isValidItemIndex(playlist, itemIndex))
return;
playlistManager_->set_active_playlist(playlist);
playlistManager_->playlist_execute_default_action(playlist, itemIndex);
}
void PlayerImpl::playRandom()
{
playbackControl_->start(playback_control::track_command_rand);
}
void PlayerImpl::playNext()
{
playbackControl_->next();
}
void PlayerImpl::playPrevious()
{
playbackControl_->previous();
}
void PlayerImpl::stop()
{
playbackControl_->stop();
}
void PlayerImpl::pause()
{
playbackControl_->pause(true);
}
void PlayerImpl::togglePause()
{
playbackControl_->toggle_pause();
}
void PlayerImpl::setMuted(Switch val)
{
switch (val)
{
case Switch::FALSE:
if (playbackControl_->is_muted())
playbackControl_->volume_mute_toggle();
break;
case Switch::TRUE:
if (!playbackControl_->is_muted())
playbackControl_->volume_mute_toggle();
break;
case Switch::TOGGLE:
playbackControl_->volume_mute_toggle();
break;
}
}
void PlayerImpl::seekAbsolute(double offsetSeconds)
{
playbackControl_->playback_seek(offsetSeconds);
}
void PlayerImpl::seekRelative(double offsetSeconds)
{
playbackControl_->playback_seek_delta(offsetSeconds);
}
void PlayerImpl::setVolume(double val)
{
playbackControl_->set_volume(static_cast<float>(clampVolume(val)));
}
void PlayerImpl::initPlaybackModes()
{
t_size count = playlistManager_->playback_order_get_count();
playbackModes_.reserve(count);
for (t_size i = 0; i < count; i++)
playbackModes_.emplace_back(playlistManager_->playback_order_get_name(i));
}
void PlayerImpl::setPlaybackMode(int32_t val)
{
t_size count = playlistManager_->playback_order_get_count();
if (val < 0 || static_cast<t_size>(val) >= count)
throw InvalidRequestException("Invalid playback mode");
playlistManager_->playback_order_set_active(val);
}
TrackQueryPtr PlayerImpl::createTrackQuery(const std::vector<std::string>& columns)
{
return std::make_unique<TrackQueryImpl>(compileColumns(columns));
}
}}
<|endoftext|> |
<commit_before>#include <iostream>
#include <fstream>
#include <QUrl>
#include <QFileInfo>
#include "kernel.h"
#include "ilwisdata.h"
#include "resource.h"
#include "identity.h"
#include "OperationExpression.h"
#include "operationmetadata.h"
#include "operation.h"
#include "commandhandler.h"
#include "script.h"
#include "parserlexer/IlwisScriptLexer.h"
#include "parserlexer/IlwisScriptParser.h"
#include "symboltable.h"
using namespace Ilwis;
OperationImplementation *Script::create(quint64 metaid, const Ilwis::OperationExpression &expr)
{
return new Script(metaid, expr);
}
Script::Script()
{
}
Script::Script(quint64 metaid,const Ilwis::OperationExpression &expr) : OperationImplementation(metaid, expr)
{
}
OperationImplementation::State Script::prepare() {
QString txt = _expression.parm(0).value();
QUrl url(txt);
if ( url.isValid() && url.scheme() == "file") {
QFileInfo inf( url.toLocalFile());
bool exists = inf.exists();
if (exists && inf.suffix() == "isf") {
std::string text;
std::ifstream in(inf.absoluteFilePath().toLatin1(), std::ios_base::in);
if(in.is_open() && in.good()) {
while(!in.eof()) {
std::string line;
std::getline(in, line);
text += line + ";";
}
char *buf = new char[text.size()];
memcpy(buf,text.c_str(), text.size());
_buffer.reset( buf );
_bufferSize = text.size();
return sPREPARED;
}
} else {
return sPREPAREFAILED;
}
} else {
return sPREPARED;
}
return sNOTPREPARED;
}
bool Script::execute(ExecutionContext *ctx)
{
if (_prepState == sNOTPREPARED)
if((_prepState = prepare()) != sPREPARED)
return false;
ANTLR3_UINT8 * bufferData = (ANTLR3_UINT8 *) _buffer.get();
for(int i=0; i < _bufferSize; ++i) {
if ( bufferData[i] == '\n') { //replace newlines with ; which are the actual seperators
bufferData[i]=';';
}
}
if ( bufferData[_bufferSize - 1] != ';')
bufferData[_bufferSize - 1] = ';';
pANTLR3_INPUT_STREAM input = antlr3StringStreamNew(bufferData, ANTLR3_ENC_8BIT, _bufferSize, (pANTLR3_UINT8)"ScriptText");
if(input == NULL)
return false;
pilwisscriptLexer lxr = ilwisscriptLexerNew(input);
if(lxr == NULL)
return false;
//Creates an empty token stream.
pANTLR3_COMMON_TOKEN_STREAM tstream = antlr3CommonTokenStreamSourceNew(ANTLR3_SIZE_HINT, TOKENSOURCE(lxr));
if(tstream == NULL)
return false;
//Creates a parser.
pilwisscriptParser psr = ilwisscriptParserNew(tstream);
if(psr == NULL)
return false;
//Run the parser rule. This also runs the lexer to create the token stream.
ASTNode *scr = psr->script(psr);
SymbolTable symbols;
bool ok = scr->evaluate(symbols, 1000);
return ok;
}
quint64 Script::createMetadata()
{
QString urlTxt = QString("ilwis://operations/script");
QUrl url(urlTxt);
Resource res(url, itOPERATIONMETADATA);
res.addProperty("namespace","ilwis");
res.addProperty("longname","ilwisscript");
res.addProperty("syntax","script file|script scriptline(,scriptline)*");
res.addProperty("inparameters","1");
res.addProperty("pin_1_type", itFILE | itSTRING);
res.addProperty("pin_1_name", TR("input script file"));
res.addProperty("pin_1_domain","none");
res.addProperty("pin_1_desc",TR("input file containing script commands"));
res.addProperty("outparameters",1);
res.addProperty("pout_1_type", itBOOL);
res.addProperty("pout_1_name", TR("succes"));
res.addProperty("pout_1_domain","bool");
res.addProperty("pout_1_desc",TR("returns the succes of the execution of the script"));
res.prepare();
urlTxt += "=" + QString::number(res.id());
res.setUrl(QUrl(urlTxt));
// IOperationMetaData md;
// if(!md.prepare(res)) {
// return i64UNDEF;
// }
mastercatalog()->addItems({res});
return res.id();
}
<commit_msg>added preparse stage for if statements<commit_after>#include <iostream>
#include <fstream>
#include <QUrl>
#include <QFileInfo>
#include "kernel.h"
#include "ilwisdata.h"
#include "resource.h"
#include "identity.h"
#include "OperationExpression.h"
#include "operationmetadata.h"
#include "operation.h"
#include "commandhandler.h"
#include "script.h"
#include "parserlexer/IlwisScriptLexer.h"
#include "parserlexer/IlwisScriptParser.h"
#include "symboltable.h"
using namespace Ilwis;
OperationImplementation *Script::create(quint64 metaid, const Ilwis::OperationExpression &expr)
{
return new Script(metaid, expr);
}
Script::Script()
{
}
Script::Script(quint64 metaid,const Ilwis::OperationExpression &expr) : OperationImplementation(metaid, expr)
{
}
OperationImplementation::State Script::prepare() {
QString txt = _expression.parm(0).value();
QUrl url(txt);
if ( url.isValid() && url.scheme() == "file") {
QFileInfo inf( url.toLocalFile());
bool exists = inf.exists();
if (exists && inf.suffix() == "isf") {
std::string text;
std::ifstream in(inf.absoluteFilePath().toLatin1(), std::ios_base::in);
bool ignorenl=false;
if(in.is_open() && in.good()) {
while(!in.eof()) {
std::string line;
std::getline(in, line);
if (line.find("if ") != std::string::npos){
ignorenl=true;
}
if (line.find("endif") != std::string::npos){
ignorenl=false;
}
text += line + (ignorenl ? " " : ";");
}
char *buf = new char[text.size()];
memcpy(buf,text.c_str(), text.size());
_buffer.reset( buf );
_bufferSize = text.size();
return sPREPARED;
}
} else {
return sPREPAREFAILED;
}
} else {
return sPREPARED;
}
return sNOTPREPARED;
}
bool Script::execute(ExecutionContext *ctx)
{
if (_prepState == sNOTPREPARED)
if((_prepState = prepare()) != sPREPARED)
return false;
ANTLR3_UINT8 * bufferData = (ANTLR3_UINT8 *) _buffer.get();
pANTLR3_INPUT_STREAM input = antlr3StringStreamNew(bufferData, ANTLR3_ENC_8BIT, _bufferSize, (pANTLR3_UINT8)"ScriptText");
if(input == NULL)
return false;
pilwisscriptLexer lxr = ilwisscriptLexerNew(input);
if(lxr == NULL)
return false;
//Creates an empty token stream.
pANTLR3_COMMON_TOKEN_STREAM tstream = antlr3CommonTokenStreamSourceNew(ANTLR3_SIZE_HINT, TOKENSOURCE(lxr));
if(tstream == NULL)
return false;
//Creates a parser.
pilwisscriptParser psr = ilwisscriptParserNew(tstream);
if(psr == NULL)
return false;
//Run the parser rule. This also runs the lexer to create the token stream.
ASTNode *scr = psr->script(psr);
SymbolTable symbols;
bool ok = scr->evaluate(symbols, 1000);
return ok;
}
quint64 Script::createMetadata()
{
QString urlTxt = QString("ilwis://operations/script");
QUrl url(urlTxt);
Resource res(url, itOPERATIONMETADATA);
res.addProperty("namespace","ilwis");
res.addProperty("longname","ilwisscript");
res.addProperty("syntax","script file|script scriptline(,scriptline)*");
res.addProperty("inparameters","1");
res.addProperty("pin_1_type", itFILE | itSTRING);
res.addProperty("pin_1_name", TR("input script file"));
res.addProperty("pin_1_domain","none");
res.addProperty("pin_1_desc",TR("input file containing script commands"));
res.addProperty("outparameters",1);
res.addProperty("pout_1_type", itBOOL);
res.addProperty("pout_1_name", TR("succes"));
res.addProperty("pout_1_domain","bool");
res.addProperty("pout_1_desc",TR("returns the succes of the execution of the script"));
res.prepare();
urlTxt += "=" + QString::number(res.id());
res.setUrl(QUrl(urlTxt));
// IOperationMetaData md;
// if(!md.prepare(res)) {
// return i64UNDEF;
// }
mastercatalog()->addItems({res});
return res.id();
}
<|endoftext|> |
<commit_before>#include "ChatBot.h"
// Konstruktor
ChatBot::ChatBot()
{
}
// Destruktor
ChatBot::~ChatBot()
{
}
// Verbindung zum Server aufbauen
void ChatBot::connectToServer(const char *host, int port)
{
// Socket wird erstellt
sock = socket(AF_INET, SOCK_STREAM, 0);
if (sock < 0)
{
perror("Fehler Socket");
disconnect();
exit(1);
}
// Host wird ueberprueft
hostent *hp = gethostbyname(host);
if (!hp)
{
perror("Host nicht gefunden...");
disconnect();
exit(1);
}
// Serverinformation wird festgelegt
sockaddr_in sin;
memset((char*)&sin, 0, sizeof(sin));
sin.sin_family = AF_INET;
memcpy((char*)&sin.sin_addr, hp->h_addr, hp->h_length);
sin.sin_port = htons(port);
memset(&(sin.sin_zero), 0, 8*sizeof(char));
// Verbindung mit dem Server
if (connect(sock, (sockaddr*) &sin, sizeof(sin)) == -1)
{
perror("Verbindung fehlgeschlagen...");
disconnect();
exit(1);
}
}
// Verbindung trennen
void ChatBot::disconnect()
{
close(sock);
}
// Funktion um Nachrichten an den Server zu schicken
void ChatBot::sendToServer(string m)
{
send(sock, m.c_str(), m.length(), 0);
}
void ChatBot::pingpong(string m)
{
}
void ChatBot::botIdentify(string nick, string user, string pw)
{
}
void ChatBot::botSkills(string m)
{
}
void ChatBot::botLoop()
{
}
<commit_msg>Bot als Klasse angelegt. Verbindung mit Server funktioniert<commit_after>#include "ChatBot.h"
// Konstruktor
ChatBot::ChatBot()
{
}
// Destruktor
ChatBot::~ChatBot()
{
}
// Verbindung zum Server aufbauen
void ChatBot::connectToServer(const char *host, int port)
{
// Socket wird erstellt
sock = socket(AF_INET, SOCK_STREAM, 0);
if (sock < 0)
{
perror("Fehler Socket");
disconnect();
exit(1);
}
// Host wird ueberprueft
hostent *hp = gethostbyname(host);
if (!hp)
{
perror("Host nicht gefunden...");
disconnect();
exit(1);
}
// Serverinformation wird festgelegt
sockaddr_in sin;
memset((char*)&sin, 0, sizeof(sin));
sin.sin_family = AF_INET;
memcpy((char*)&sin.sin_addr, hp->h_addr, hp->h_length);
sin.sin_port = htons(port);
memset(&(sin.sin_zero), 0, 8*sizeof(char));
// Verbindung mit dem Server
if (connect(sock, (sockaddr*) &sin, sizeof(sin)) == -1)
{
perror("Verbindung fehlgeschlagen...");
disconnect();
exit(1);
}
}
// Verbindung trennen
void ChatBot::disconnect()
{
close(sock);
}
// Funktion um Nachrichten an den Server zu schicken
void ChatBot::sendToServer(string m)
{
send(sock, m.c_str(), m.length(), 0);
}
void ChatBot::pingpong(string m)
{
}
void ChatBot::botIdentify(string nick, string user, string pw)
{
}
void ChatBot::botSkills(string m)
{
}
void ChatBot::botLoop()
{
}
<|endoftext|> |
<commit_before>// Copyright (c) 2011, the Dart project authors. Please see the AUTHORS file
// for details. All rights reserved. Use of this source code is governed by a
// BSD-style license that can be found in the LICENSE file.
#include "vm/message_handler.h"
#include "vm/dart.h"
#include "vm/lockers.h"
#include "vm/os.h"
#include "vm/port.h"
#include "vm/thread_interrupter.h"
namespace dart {
DECLARE_FLAG(bool, trace_isolates);
DECLARE_FLAG(bool, trace_service_pause_events);
class MessageHandlerTask : public ThreadPool::Task {
public:
explicit MessageHandlerTask(MessageHandler* handler)
: handler_(handler) {
ASSERT(handler != NULL);
}
virtual void Run() {
handler_->TaskCallback();
}
private:
MessageHandler* handler_;
DISALLOW_COPY_AND_ASSIGN(MessageHandlerTask);
};
MessageHandler::MessageHandler()
: queue_(new MessageQueue()),
oob_queue_(new MessageQueue()),
oob_message_handling_allowed_(true),
live_ports_(0),
paused_(0),
pause_on_start_(false),
pause_on_exit_(false),
paused_on_start_(false),
paused_on_exit_(false),
paused_timestamp_(-1),
pool_(NULL),
task_(NULL),
start_callback_(NULL),
end_callback_(NULL),
callback_data_(0) {
ASSERT(queue_ != NULL);
ASSERT(oob_queue_ != NULL);
}
MessageHandler::~MessageHandler() {
delete queue_;
delete oob_queue_;
}
const char* MessageHandler::name() const {
return "<unnamed>";
}
#if defined(DEBUG)
void MessageHandler::CheckAccess() {
// By default there is no checking.
}
#endif
void MessageHandler::MessageNotify(Message::Priority priority) {
// By default, there is no custom message notification.
}
void MessageHandler::Run(ThreadPool* pool,
StartCallback start_callback,
EndCallback end_callback,
CallbackData data) {
MonitorLocker ml(&monitor_);
if (FLAG_trace_isolates) {
OS::Print("[+] Starting message handler:\n"
"\thandler: %s\n",
name());
}
ASSERT(pool_ == NULL);
pool_ = pool;
start_callback_ = start_callback;
end_callback_ = end_callback;
callback_data_ = data;
task_ = new MessageHandlerTask(this);
pool_->Run(task_);
}
void MessageHandler::PostMessage(Message* message, bool before_events) {
Message::Priority saved_priority;
{
MonitorLocker ml(&monitor_);
if (FLAG_trace_isolates) {
const char* source_name = "<native code>";
Isolate* source_isolate = Isolate::Current();
if (source_isolate) {
source_name = source_isolate->name();
}
OS::Print("[>] Posting message:\n"
"\tlen: %" Pd "\n"
"\tsource: %s\n"
"\tdest: %s\n"
"\tdest_port: %" Pd64 "\n",
message->len(), source_name, name(), message->dest_port());
}
saved_priority = message->priority();
if (message->IsOOB()) {
oob_queue_->Enqueue(message, before_events);
} else {
queue_->Enqueue(message, before_events);
}
message = NULL; // Do not access message. May have been deleted.
if (pool_ != NULL && task_ == NULL) {
task_ = new MessageHandlerTask(this);
pool_->Run(task_);
}
}
// Invoke any custom message notification.
MessageNotify(saved_priority);
}
Message* MessageHandler::DequeueMessage(Message::Priority min_priority) {
// TODO(turnidge): Add assert that monitor_ is held here.
Message* message = oob_queue_->Dequeue();
if ((message == NULL) && (min_priority < Message::kOOBPriority)) {
message = queue_->Dequeue();
}
return message;
}
bool MessageHandler::HandleMessages(bool allow_normal_messages,
bool allow_multiple_normal_messages) {
// If isolate() returns NULL StartIsolateScope does nothing.
StartIsolateScope start_isolate(isolate());
// ThreadInterrupter may have gone to sleep waiting while waiting for
// an isolate to start handling messages.
ThreadInterrupter::WakeUp();
// TODO(turnidge): Add assert that monitor_ is held here.
bool result = true;
Message::Priority min_priority = (allow_normal_messages && !paused()) ?
Message::kNormalPriority : Message::kOOBPriority;
Message* message = DequeueMessage(min_priority);
while (message != NULL) {
intptr_t message_len = message->len();
if (FLAG_trace_isolates) {
OS::Print("[<] Handling message:\n"
"\tlen: %" Pd "\n"
"\thandler: %s\n"
"\tport: %" Pd64 "\n",
message_len, name(), message->dest_port());
}
// Release the monitor_ temporarily while we handle the message.
// The monitor was acquired in MessageHandler::TaskCallback().
monitor_.Exit();
Message::Priority saved_priority = message->priority();
Dart_Port saved_dest_port = message->dest_port();
result = HandleMessage(message);
message = NULL; // May be deleted by now.
monitor_.Enter();
if (FLAG_trace_isolates) {
OS::Print("[.] Message handled:\n"
"\tlen: %" Pd "\n"
"\thandler: %s\n"
"\tport: %" Pd64 "\n",
message_len, name(), saved_dest_port);
}
if (!result) {
// If we hit an error, we're done processing messages.
break;
}
// Some callers want to process only one normal message and then quit. At
// the same time it is OK to process multiple OOB messages.
if ((saved_priority == Message::kNormalPriority) &&
!allow_multiple_normal_messages) {
break;
}
// Reevaluate the minimum allowable priority as the paused state might
// have changed as part of handling the message.
min_priority = (allow_normal_messages && !paused()) ?
Message::kNormalPriority : Message::kOOBPriority;
message = DequeueMessage(min_priority);
}
return result;
}
bool MessageHandler::HandleNextMessage() {
// We can only call HandleNextMessage when this handler is not
// assigned to a thread pool.
MonitorLocker ml(&monitor_);
ASSERT(pool_ == NULL);
#if defined(DEBUG)
CheckAccess();
#endif
return HandleMessages(true, false);
}
bool MessageHandler::HandleOOBMessages() {
if (!oob_message_handling_allowed_) {
return true;
}
MonitorLocker ml(&monitor_);
#if defined(DEBUG)
CheckAccess();
#endif
return HandleMessages(false, false);
}
bool MessageHandler::HasOOBMessages() {
MonitorLocker ml(&monitor_);
return !oob_queue_->IsEmpty();
}
void MessageHandler::TaskCallback() {
ASSERT(Isolate::Current() == NULL);
bool ok = true;
bool run_end_callback = false;
bool notify_paused_on_exit = false;
{
MonitorLocker ml(&monitor_);
// Initialize the message handler by running its start function,
// if we have one. For an isolate, this will run the isolate's
// main() function.
if (pause_on_start()) {
if (!paused_on_start_) {
// Temporarily drop the lock when calling out to NotifyPauseOnStart.
// This avoids a dead lock that can occur when this message handler
// tries to post a message while a message is being posted to it.
paused_on_start_ = true;
paused_timestamp_ = OS::GetCurrentTimeMillis();
monitor_.Exit();
NotifyPauseOnStart();
monitor_.Enter();
}
HandleMessages(false, false);
if (pause_on_start()) {
// Still paused.
task_ = NULL; // No task in queue.
return;
} else {
paused_on_start_ = false;
paused_timestamp_ = -1;
}
}
if (start_callback_) {
// Release the monitor_ temporarily while we call the start callback.
// The monitor was acquired with the MonitorLocker above.
monitor_.Exit();
ok = start_callback_(callback_data_);
ASSERT(Isolate::Current() == NULL);
start_callback_ = NULL;
monitor_.Enter();
}
// Handle any pending messages for this message handler.
if (ok) {
ok = HandleMessages(true, true);
}
task_ = NULL; // No task in queue.
if (!ok || !HasLivePorts()) {
if (pause_on_exit()) {
if (!paused_on_exit_) {
if (FLAG_trace_service_pause_events) {
OS::PrintErr("Isolate %s paused before exiting. "
"Use the Observatory to release it.\n", name());
}
notify_paused_on_exit = true;
paused_on_exit_ = true;
paused_timestamp_ = OS::GetCurrentTimeMillis();
}
} else {
if (FLAG_trace_isolates) {
OS::Print("[-] Stopping message handler (%s):\n"
"\thandler: %s\n",
(ok ? "no live ports" : "error"),
name());
}
pool_ = NULL;
run_end_callback = true;
paused_on_exit_ = false;
paused_timestamp_ = -1;
}
}
}
// At this point we no longer hold the message handler lock.
if (notify_paused_on_exit) {
NotifyPauseOnExit();
}
if (run_end_callback && end_callback_ != NULL) {
end_callback_(callback_data_);
// The handler may have been deleted after this point.
}
}
void MessageHandler::ClosePort(Dart_Port port) {
MonitorLocker ml(&monitor_);
if (FLAG_trace_isolates) {
OS::Print("[-] Closing port:\n"
"\thandler: %s\n"
"\tport: %" Pd64 "\n"
"\tports: live(%" Pd ")\n",
name(), port, live_ports_);
}
}
void MessageHandler::CloseAllPorts() {
MonitorLocker ml(&monitor_);
if (FLAG_trace_isolates) {
OS::Print("[-] Closing all ports:\n"
"\thandler: %s\n",
name());
}
queue_->Clear();
oob_queue_->Clear();
}
void MessageHandler::increment_live_ports() {
MonitorLocker ml(&monitor_);
#if defined(DEBUG)
CheckAccess();
#endif
live_ports_++;
}
void MessageHandler::decrement_live_ports() {
MonitorLocker ml(&monitor_);
#if defined(DEBUG)
CheckAccess();
#endif
live_ports_--;
}
MessageHandler::AcquiredQueues::AcquiredQueues()
: handler_(NULL) {
}
MessageHandler::AcquiredQueues::~AcquiredQueues() {
Reset(NULL);
}
void MessageHandler::AcquiredQueues::Reset(MessageHandler* handler) {
if (handler_ != NULL) {
// Release ownership. The OOB flag is set without holding the monitor.
handler_->monitor_.Exit();
handler_->oob_message_handling_allowed_ = true;
}
handler_ = handler;
if (handler_ == NULL) {
return;
}
ASSERT(handler_ != NULL);
// Take ownership. The OOB flag is set without holding the monitor.
handler_->oob_message_handling_allowed_ = false;
handler_->monitor_.Enter();
}
void MessageHandler::AcquireQueues(AcquiredQueues* acquired_queues) {
ASSERT(acquired_queues != NULL);
// No double dipping.
ASSERT(acquired_queues->handler_ == NULL);
acquired_queues->Reset(this);
}
} // namespace dart
<commit_msg>Fix a bug PauseOnExit notification.<commit_after>// Copyright (c) 2011, the Dart project authors. Please see the AUTHORS file
// for details. All rights reserved. Use of this source code is governed by a
// BSD-style license that can be found in the LICENSE file.
#include "vm/message_handler.h"
#include "vm/dart.h"
#include "vm/lockers.h"
#include "vm/os.h"
#include "vm/port.h"
#include "vm/thread_interrupter.h"
namespace dart {
DECLARE_FLAG(bool, trace_isolates);
DECLARE_FLAG(bool, trace_service_pause_events);
class MessageHandlerTask : public ThreadPool::Task {
public:
explicit MessageHandlerTask(MessageHandler* handler)
: handler_(handler) {
ASSERT(handler != NULL);
}
virtual void Run() {
handler_->TaskCallback();
}
private:
MessageHandler* handler_;
DISALLOW_COPY_AND_ASSIGN(MessageHandlerTask);
};
MessageHandler::MessageHandler()
: queue_(new MessageQueue()),
oob_queue_(new MessageQueue()),
oob_message_handling_allowed_(true),
live_ports_(0),
paused_(0),
pause_on_start_(false),
pause_on_exit_(false),
paused_on_start_(false),
paused_on_exit_(false),
paused_timestamp_(-1),
pool_(NULL),
task_(NULL),
start_callback_(NULL),
end_callback_(NULL),
callback_data_(0) {
ASSERT(queue_ != NULL);
ASSERT(oob_queue_ != NULL);
}
MessageHandler::~MessageHandler() {
delete queue_;
delete oob_queue_;
}
const char* MessageHandler::name() const {
return "<unnamed>";
}
#if defined(DEBUG)
void MessageHandler::CheckAccess() {
// By default there is no checking.
}
#endif
void MessageHandler::MessageNotify(Message::Priority priority) {
// By default, there is no custom message notification.
}
void MessageHandler::Run(ThreadPool* pool,
StartCallback start_callback,
EndCallback end_callback,
CallbackData data) {
MonitorLocker ml(&monitor_);
if (FLAG_trace_isolates) {
OS::Print("[+] Starting message handler:\n"
"\thandler: %s\n",
name());
}
ASSERT(pool_ == NULL);
pool_ = pool;
start_callback_ = start_callback;
end_callback_ = end_callback;
callback_data_ = data;
task_ = new MessageHandlerTask(this);
pool_->Run(task_);
}
void MessageHandler::PostMessage(Message* message, bool before_events) {
Message::Priority saved_priority;
{
MonitorLocker ml(&monitor_);
if (FLAG_trace_isolates) {
const char* source_name = "<native code>";
Isolate* source_isolate = Isolate::Current();
if (source_isolate) {
source_name = source_isolate->name();
}
OS::Print("[>] Posting message:\n"
"\tlen: %" Pd "\n"
"\tsource: %s\n"
"\tdest: %s\n"
"\tdest_port: %" Pd64 "\n",
message->len(), source_name, name(), message->dest_port());
}
saved_priority = message->priority();
if (message->IsOOB()) {
oob_queue_->Enqueue(message, before_events);
} else {
queue_->Enqueue(message, before_events);
}
message = NULL; // Do not access message. May have been deleted.
if (pool_ != NULL && task_ == NULL) {
task_ = new MessageHandlerTask(this);
pool_->Run(task_);
}
}
// Invoke any custom message notification.
MessageNotify(saved_priority);
}
Message* MessageHandler::DequeueMessage(Message::Priority min_priority) {
// TODO(turnidge): Add assert that monitor_ is held here.
Message* message = oob_queue_->Dequeue();
if ((message == NULL) && (min_priority < Message::kOOBPriority)) {
message = queue_->Dequeue();
}
return message;
}
bool MessageHandler::HandleMessages(bool allow_normal_messages,
bool allow_multiple_normal_messages) {
// If isolate() returns NULL StartIsolateScope does nothing.
StartIsolateScope start_isolate(isolate());
// ThreadInterrupter may have gone to sleep waiting while waiting for
// an isolate to start handling messages.
ThreadInterrupter::WakeUp();
// TODO(turnidge): Add assert that monitor_ is held here.
bool result = true;
Message::Priority min_priority = (allow_normal_messages && !paused()) ?
Message::kNormalPriority : Message::kOOBPriority;
Message* message = DequeueMessage(min_priority);
while (message != NULL) {
intptr_t message_len = message->len();
if (FLAG_trace_isolates) {
OS::Print("[<] Handling message:\n"
"\tlen: %" Pd "\n"
"\thandler: %s\n"
"\tport: %" Pd64 "\n",
message_len, name(), message->dest_port());
}
// Release the monitor_ temporarily while we handle the message.
// The monitor was acquired in MessageHandler::TaskCallback().
monitor_.Exit();
Message::Priority saved_priority = message->priority();
Dart_Port saved_dest_port = message->dest_port();
result = HandleMessage(message);
message = NULL; // May be deleted by now.
monitor_.Enter();
if (FLAG_trace_isolates) {
OS::Print("[.] Message handled:\n"
"\tlen: %" Pd "\n"
"\thandler: %s\n"
"\tport: %" Pd64 "\n",
message_len, name(), saved_dest_port);
}
if (!result) {
// If we hit an error, we're done processing messages.
break;
}
// Some callers want to process only one normal message and then quit. At
// the same time it is OK to process multiple OOB messages.
if ((saved_priority == Message::kNormalPriority) &&
!allow_multiple_normal_messages) {
break;
}
// Reevaluate the minimum allowable priority as the paused state might
// have changed as part of handling the message.
min_priority = (allow_normal_messages && !paused()) ?
Message::kNormalPriority : Message::kOOBPriority;
message = DequeueMessage(min_priority);
}
return result;
}
bool MessageHandler::HandleNextMessage() {
// We can only call HandleNextMessage when this handler is not
// assigned to a thread pool.
MonitorLocker ml(&monitor_);
ASSERT(pool_ == NULL);
#if defined(DEBUG)
CheckAccess();
#endif
return HandleMessages(true, false);
}
bool MessageHandler::HandleOOBMessages() {
if (!oob_message_handling_allowed_) {
return true;
}
MonitorLocker ml(&monitor_);
#if defined(DEBUG)
CheckAccess();
#endif
return HandleMessages(false, false);
}
bool MessageHandler::HasOOBMessages() {
MonitorLocker ml(&monitor_);
return !oob_queue_->IsEmpty();
}
void MessageHandler::TaskCallback() {
ASSERT(Isolate::Current() == NULL);
bool ok = true;
bool run_end_callback = false;
{
MonitorLocker ml(&monitor_);
// Initialize the message handler by running its start function,
// if we have one. For an isolate, this will run the isolate's
// main() function.
if (pause_on_start()) {
if (!paused_on_start_) {
// Temporarily drop the lock when calling out to NotifyPauseOnStart.
// This avoids a dead lock that can occur when this message handler
// tries to post a message while a message is being posted to it.
paused_on_start_ = true;
paused_timestamp_ = OS::GetCurrentTimeMillis();
monitor_.Exit();
NotifyPauseOnStart();
monitor_.Enter();
}
// More messages may have come in while we released monitor_.
HandleMessages(false, false);
if (pause_on_start()) {
// Still paused.
ASSERT(oob_queue_->IsEmpty());
task_ = NULL; // No task in queue.
return;
} else {
paused_on_start_ = false;
paused_timestamp_ = -1;
}
}
if (start_callback_) {
// Release the monitor_ temporarily while we call the start callback.
// The monitor was acquired with the MonitorLocker above.
monitor_.Exit();
ok = start_callback_(callback_data_);
ASSERT(Isolate::Current() == NULL);
start_callback_ = NULL;
monitor_.Enter();
}
// Handle any pending messages for this message handler.
if (ok) {
ok = HandleMessages(true, true);
}
if (!ok || !HasLivePorts()) {
if (pause_on_exit()) {
if (!paused_on_exit_) {
if (FLAG_trace_service_pause_events) {
OS::PrintErr("Isolate %s paused before exiting. "
"Use the Observatory to release it.\n", name());
}
// Temporarily drop the lock when calling out to NotifyPauseOnExit.
// This avoids a dead lock that can occur when this message handler
// tries to post a message while a message is being posted to it.
paused_on_exit_ = true;
paused_timestamp_ = OS::GetCurrentTimeMillis();
monitor_.Exit();
NotifyPauseOnExit();
monitor_.Enter();
}
// More messages may have come in while we released monitor_.
HandleMessages(false, false);
if (pause_on_exit()) {
// Still paused.
ASSERT(oob_queue_->IsEmpty());
task_ = NULL; // No task in queue.
return;
} else {
paused_on_exit_ = false;
paused_timestamp_ = -1;
}
}
if (FLAG_trace_isolates) {
OS::Print("[-] Stopping message handler (%s):\n"
"\thandler: %s\n",
(ok ? "no live ports" : "error"),
name());
}
pool_ = NULL;
run_end_callback = true;
}
// Clear the task_ last. We don't want any other tasks to start up
// until we are done with all messages and pause notifications.
ASSERT(oob_queue_->IsEmpty());
ASSERT(!ok || queue_->IsEmpty());
task_ = NULL;
}
if (run_end_callback && end_callback_ != NULL) {
end_callback_(callback_data_);
// The handler may have been deleted after this point.
}
}
void MessageHandler::ClosePort(Dart_Port port) {
MonitorLocker ml(&monitor_);
if (FLAG_trace_isolates) {
OS::Print("[-] Closing port:\n"
"\thandler: %s\n"
"\tport: %" Pd64 "\n"
"\tports: live(%" Pd ")\n",
name(), port, live_ports_);
}
}
void MessageHandler::CloseAllPorts() {
MonitorLocker ml(&monitor_);
if (FLAG_trace_isolates) {
OS::Print("[-] Closing all ports:\n"
"\thandler: %s\n",
name());
}
queue_->Clear();
oob_queue_->Clear();
}
void MessageHandler::increment_live_ports() {
MonitorLocker ml(&monitor_);
#if defined(DEBUG)
CheckAccess();
#endif
live_ports_++;
}
void MessageHandler::decrement_live_ports() {
MonitorLocker ml(&monitor_);
#if defined(DEBUG)
CheckAccess();
#endif
live_ports_--;
}
MessageHandler::AcquiredQueues::AcquiredQueues()
: handler_(NULL) {
}
MessageHandler::AcquiredQueues::~AcquiredQueues() {
Reset(NULL);
}
void MessageHandler::AcquiredQueues::Reset(MessageHandler* handler) {
if (handler_ != NULL) {
// Release ownership. The OOB flag is set without holding the monitor.
handler_->monitor_.Exit();
handler_->oob_message_handling_allowed_ = true;
}
handler_ = handler;
if (handler_ == NULL) {
return;
}
ASSERT(handler_ != NULL);
// Take ownership. The OOB flag is set without holding the monitor.
handler_->oob_message_handling_allowed_ = false;
handler_->monitor_.Enter();
}
void MessageHandler::AcquireQueues(AcquiredQueues* acquired_queues) {
ASSERT(acquired_queues != NULL);
// No double dipping.
ASSERT(acquired_queues->handler_ == NULL);
acquired_queues->Reset(this);
}
} // namespace dart
<|endoftext|> |
<commit_before>#include <babylon/materials/node/node_material_connection_point.h>
#include <babylon/babylon_stl_util.h>
#include <babylon/core/json_util.h>
#include <babylon/materials/node/blocks/input/input_block.h>
#include <babylon/materials/node/node_material_block.h>
namespace BABYLON {
bool NodeMaterialConnectionPoint::AreEquivalentTypes(NodeMaterialBlockConnectionPointTypes type1,
NodeMaterialBlockConnectionPointTypes type2)
{
switch (type1) {
case NodeMaterialBlockConnectionPointTypes::Vector3: {
if (type2 == NodeMaterialBlockConnectionPointTypes::Color3) {
return true;
}
break;
}
case NodeMaterialBlockConnectionPointTypes::Vector4: {
if (type2 == NodeMaterialBlockConnectionPointTypes::Color4) {
return true;
}
break;
}
case NodeMaterialBlockConnectionPointTypes::Color3: {
if (type2 == NodeMaterialBlockConnectionPointTypes::Vector3) {
return true;
}
break;
}
case NodeMaterialBlockConnectionPointTypes::Color4: {
if (type2 == NodeMaterialBlockConnectionPointTypes::Vector4) {
return true;
}
break;
}
default:
break;
}
return false;
}
NodeMaterialConnectionPoint::NodeMaterialConnectionPoint(
const std::string& iName, const NodeMaterialBlockPtr& ownerBlock,
const NodeMaterialConnectionPointDirection& direction)
: _ownerBlock{nullptr}
, _connectedPoint{nullptr}
, _typeConnectionSource{nullptr}
, _defaultConnectionPointType{std::nullopt}
, _linkedConnectionSource{nullptr}
, _acceptedConnectionPointType{nullptr}
, _enforceAssociatedVariableName{false}
, direction{this, &NodeMaterialConnectionPoint::get_direction}
, needDualDirectionValidation{false}
, associatedVariableName{this, &NodeMaterialConnectionPoint::get_associatedVariableName,
&NodeMaterialConnectionPoint::set_associatedVariableName}
, innerType{this, &NodeMaterialConnectionPoint::get_innerType}
, type{this, &NodeMaterialConnectionPoint::get_type, &NodeMaterialConnectionPoint::set_type}
, isOptional{false}
, isExposedOnFrame{false}
, exposedPortPosition{-1}
, _prioritizeVertex{false}
, target{this, &NodeMaterialConnectionPoint::get_target,
&NodeMaterialConnectionPoint::set_target}
, isConnected{this, &NodeMaterialConnectionPoint::get_isConnected}
, isConnectedToInputBlock{this, &NodeMaterialConnectionPoint::get_isConnectedToInputBlock}
, connectInputBlock{this, &NodeMaterialConnectionPoint::get_connectInputBlock}
, connectedPoint{this, &NodeMaterialConnectionPoint::get_connectedPoint}
, ownerBlock{this, &NodeMaterialConnectionPoint::get_ownerBlock}
, sourceBlock{this, &NodeMaterialConnectionPoint::get_sourceBlock}
, connectedBlocks{this, &NodeMaterialConnectionPoint::get_connectedBlocks}
, endpoints{this, &NodeMaterialConnectionPoint::get_endpoints}
, hasEndpoints{this, &NodeMaterialConnectionPoint::get_hasEndpoints}
, isConnectedInVertexShader{this, &NodeMaterialConnectionPoint::get_isConnectedInVertexShader}
, isConnectedInFragmentShader{this,
&NodeMaterialConnectionPoint::get_isConnectedInFragmentShader}
, _target{NodeMaterialBlockTargets::VertexAndFragment}
, _type{NodeMaterialBlockConnectionPointTypes::Float}
, _connectInputBlock{nullptr}
, _sourceBlock{nullptr}
{
_ownerBlock = ownerBlock;
name = iName;
_direction = direction;
}
NodeMaterialConnectionPointDirection& NodeMaterialConnectionPoint::get_direction()
{
return _direction;
}
std::string NodeMaterialConnectionPoint::get_associatedVariableName() const
{
if (_ownerBlock->isInput()) {
auto inputBlock = std::static_pointer_cast<InputBlock>(_ownerBlock);
if (inputBlock) {
return inputBlock->associatedVariableName();
}
}
if ((!_enforceAssociatedVariableName || _associatedVariableName.empty()) && _connectedPoint) {
return _connectedPoint->associatedVariableName();
}
return _associatedVariableName;
}
void NodeMaterialConnectionPoint::set_associatedVariableName(std::string value)
{
_associatedVariableName = value;
}
NodeMaterialBlockConnectionPointTypes& NodeMaterialConnectionPoint::get_innerType()
{
if (_linkedConnectionSource && _linkedConnectionSource->isConnected()) {
return type();
}
return _type;
}
NodeMaterialBlockConnectionPointTypes& NodeMaterialConnectionPoint::get_type()
{
if (_type == NodeMaterialBlockConnectionPointTypes::AutoDetect) {
if (_ownerBlock->isInput()) {
auto inputBlock = std::static_pointer_cast<InputBlock>(_ownerBlock);
if (inputBlock) {
return inputBlock->type();
}
}
if (_connectedPoint) {
return _connectedPoint->type();
}
if (_linkedConnectionSource && _linkedConnectionSource->isConnected()) {
return _linkedConnectionSource->type();
}
}
if (_type == NodeMaterialBlockConnectionPointTypes::BasedOnInput) {
if (_typeConnectionSource) {
if (!_typeConnectionSource->isConnected() && _defaultConnectionPointType) {
return *_defaultConnectionPointType;
}
return _typeConnectionSource->type();
}
else if (_defaultConnectionPointType) {
return *_defaultConnectionPointType;
}
}
return _type;
}
void NodeMaterialConnectionPoint::set_type(const NodeMaterialBlockConnectionPointTypes& value)
{
_type = value;
}
NodeMaterialBlockTargets& NodeMaterialConnectionPoint::get_target()
{
if (!_prioritizeVertex || !_ownerBlock) {
return _target;
}
if (_target != NodeMaterialBlockTargets::VertexAndFragment) {
return _target;
}
if (_ownerBlock->target() == NodeMaterialBlockTargets::Fragment) {
_tmpTarget = NodeMaterialBlockTargets::Fragment;
return _tmpTarget;
}
_tmpTarget = NodeMaterialBlockTargets::Vertex;
return _tmpTarget;
}
void NodeMaterialConnectionPoint::set_target(const NodeMaterialBlockTargets& value)
{
_target = value;
}
bool NodeMaterialConnectionPoint::get_isConnected() const
{
return connectedPoint() != nullptr || hasEndpoints();
}
bool NodeMaterialConnectionPoint::get_isConnectedToInputBlock() const
{
return connectedPoint() != nullptr && connectedPoint()->ownerBlock()->isInput();
}
InputBlockPtr& NodeMaterialConnectionPoint::get_connectInputBlock()
{
if (!isConnectedToInputBlock()) {
_connectInputBlock = nullptr;
return _connectInputBlock;
}
_connectInputBlock = std::static_pointer_cast<InputBlock>(connectedPoint()->ownerBlock());
return _connectInputBlock;
}
NodeMaterialConnectionPointPtr& NodeMaterialConnectionPoint::get_connectedPoint()
{
return _connectedPoint;
}
NodeMaterialBlockPtr& NodeMaterialConnectionPoint::get_ownerBlock()
{
return _ownerBlock;
}
NodeMaterialBlockPtr& NodeMaterialConnectionPoint::get_sourceBlock()
{
if (!_connectedPoint) {
_sourceBlock = nullptr;
return _sourceBlock;
}
_sourceBlock = _connectedPoint->ownerBlock();
return _sourceBlock;
}
std::vector<NodeMaterialBlockPtr>& NodeMaterialConnectionPoint::get_connectedBlocks()
{
_connectedBlocks.clear();
if (_endpoints.empty()) {
return _connectedBlocks;
}
for (const auto& e : _endpoints) {
_connectedBlocks.emplace_back(e->ownerBlock());
}
return _connectedBlocks;
}
std::vector<NodeMaterialConnectionPointPtr>& NodeMaterialConnectionPoint::get_endpoints()
{
return _endpoints;
}
bool NodeMaterialConnectionPoint::get_hasEndpoints() const
{
return !_endpoints.empty();
}
bool NodeMaterialConnectionPoint::get_isConnectedInVertexShader() const
{
if (target() == NodeMaterialBlockTargets::Vertex) {
return true;
}
if (!hasEndpoints()) {
return false;
}
for (const auto& endpoint : _endpoints) {
if (endpoint->ownerBlock()->target() == NodeMaterialBlockTargets::Vertex) {
return true;
}
if (endpoint->target() == NodeMaterialBlockTargets::Vertex) {
return true;
}
if (endpoint->ownerBlock()->target() == NodeMaterialBlockTargets::Neutral
|| endpoint->ownerBlock()->target() == NodeMaterialBlockTargets::VertexAndFragment) {
for (const auto& o : endpoint->ownerBlock()->outputs()) {
if (o->isConnectedInVertexShader()) {
return true;
}
}
}
}
return false;
}
bool NodeMaterialConnectionPoint::get_isConnectedInFragmentShader() const
{
if (target() == NodeMaterialBlockTargets::Fragment) {
return true;
}
if (!hasEndpoints()) {
return false;
}
for (const auto& endpoint : _endpoints) {
if (endpoint->ownerBlock()->target() == NodeMaterialBlockTargets::Fragment) {
return true;
}
if (endpoint->ownerBlock()->target() == NodeMaterialBlockTargets::Neutral
|| endpoint->ownerBlock()->target() == NodeMaterialBlockTargets::VertexAndFragment) {
for (const auto& o : endpoint->ownerBlock()->outputs()) {
if (o->isConnectedInFragmentShader()) {
return true;
}
}
}
}
return false;
}
std::optional<std::pair<NodeMaterialBlockPtr, std::string>>
NodeMaterialConnectionPoint::createCustomInputBlock()
{
return std::nullopt;
}
std::string NodeMaterialConnectionPoint::getClassName() const
{
return "NodeMaterialConnectionPoint";
}
bool NodeMaterialConnectionPoint::canConnectTo(const NodeMaterialConnectionPoint& connectionPoint)
{
return checkCompatibilityState(connectionPoint)
== NodeMaterialConnectionPointCompatibilityStates::Compatible;
}
NodeMaterialConnectionPointCompatibilityStates NodeMaterialConnectionPoint::checkCompatibilityState(
const NodeMaterialConnectionPoint& connectionPoint)
{
const auto& iOwnerBlock = _ownerBlock;
const auto& otherBlock = connectionPoint.ownerBlock();
if (iOwnerBlock->target() == NodeMaterialBlockTargets::Fragment) {
// Let's check we are not going reverse
if (otherBlock->target() == NodeMaterialBlockTargets::Vertex) {
return NodeMaterialConnectionPointCompatibilityStates::TargetIncompatible;
}
for (const auto& output : otherBlock->outputs()) {
if (output->isConnectedInVertexShader()) {
return NodeMaterialConnectionPointCompatibilityStates::TargetIncompatible;
}
}
}
if (type != connectionPoint.type
&& connectionPoint.innerType() != NodeMaterialBlockConnectionPointTypes::AutoDetect) {
// Equivalents
if (NodeMaterialConnectionPoint::AreEquivalentTypes(type, connectionPoint.type)) {
return NodeMaterialConnectionPointCompatibilityStates::Compatible;
}
// Accepted types
if ((!connectionPoint.acceptedConnectionPointTypes.empty()
&& stl_util::contains(connectionPoint.acceptedConnectionPointTypes, type))
|| (connectionPoint._acceptedConnectionPointType
&& NodeMaterialConnectionPoint::AreEquivalentTypes(
connectionPoint._acceptedConnectionPointType->type, type))) {
return NodeMaterialConnectionPointCompatibilityStates::Compatible;
}
else {
return NodeMaterialConnectionPointCompatibilityStates::TypeIncompatible;
}
}
// Excluded
if ((!connectionPoint.excludedConnectionPointTypes.empty()
&& stl_util::contains(connectionPoint.excludedConnectionPointTypes, type))) {
return NodeMaterialConnectionPointCompatibilityStates::TypeIncompatible;
}
// Check hierarchy
auto targetBlock = otherBlock;
auto iSourceBlock = ownerBlock();
if (direction() == NodeMaterialConnectionPointDirection::Input) {
targetBlock = ownerBlock();
iSourceBlock = otherBlock;
}
if (targetBlock->isAnAncestorOf(iSourceBlock)) {
return NodeMaterialConnectionPointCompatibilityStates::HierarchyIssue;
}
return NodeMaterialConnectionPointCompatibilityStates::Compatible;
}
NodeMaterialConnectionPoint&
NodeMaterialConnectionPoint::connectTo(const NodeMaterialConnectionPointPtr& connectionPoint,
bool ignoreConstraints)
{
if (!ignoreConstraints && !canConnectTo(*connectionPoint)) {
throw std::runtime_error("Cannot connect these two connectors.");
}
_endpoints.emplace_back(connectionPoint);
connectionPoint->_connectedPoint = shared_from_this();
_enforceAssociatedVariableName = false;
onConnectionObservable.notifyObservers(connectionPoint.get());
connectionPoint->onConnectionObservable.notifyObservers(this);
return *this;
}
NodeMaterialConnectionPoint&
NodeMaterialConnectionPoint::disconnectFrom(const NodeMaterialConnectionPointPtr& endpoint)
{
auto index = stl_util::index_of(_endpoints, endpoint);
if (index == -1) {
return *this;
}
stl_util::splice(_endpoints, index, 1);
endpoint->_connectedPoint = nullptr;
_enforceAssociatedVariableName = false;
endpoint->_enforceAssociatedVariableName = false;
return *this;
}
json NodeMaterialConnectionPoint::serialize(bool /*isInput*/) const
{
return nullptr;
}
void NodeMaterialConnectionPoint::dispose()
{
onConnectionObservable.clear();
}
} // end of namespace BABYLON
<commit_msg>Added extra target type check<commit_after>#include <babylon/materials/node/node_material_connection_point.h>
#include <babylon/babylon_stl_util.h>
#include <babylon/core/json_util.h>
#include <babylon/materials/node/blocks/input/input_block.h>
#include <babylon/materials/node/node_material_block.h>
namespace BABYLON {
bool NodeMaterialConnectionPoint::AreEquivalentTypes(NodeMaterialBlockConnectionPointTypes type1,
NodeMaterialBlockConnectionPointTypes type2)
{
switch (type1) {
case NodeMaterialBlockConnectionPointTypes::Vector3: {
if (type2 == NodeMaterialBlockConnectionPointTypes::Color3) {
return true;
}
break;
}
case NodeMaterialBlockConnectionPointTypes::Vector4: {
if (type2 == NodeMaterialBlockConnectionPointTypes::Color4) {
return true;
}
break;
}
case NodeMaterialBlockConnectionPointTypes::Color3: {
if (type2 == NodeMaterialBlockConnectionPointTypes::Vector3) {
return true;
}
break;
}
case NodeMaterialBlockConnectionPointTypes::Color4: {
if (type2 == NodeMaterialBlockConnectionPointTypes::Vector4) {
return true;
}
break;
}
default:
break;
}
return false;
}
NodeMaterialConnectionPoint::NodeMaterialConnectionPoint(
const std::string& iName, const NodeMaterialBlockPtr& ownerBlock,
const NodeMaterialConnectionPointDirection& direction)
: _ownerBlock{nullptr}
, _connectedPoint{nullptr}
, _typeConnectionSource{nullptr}
, _defaultConnectionPointType{std::nullopt}
, _linkedConnectionSource{nullptr}
, _acceptedConnectionPointType{nullptr}
, _enforceAssociatedVariableName{false}
, direction{this, &NodeMaterialConnectionPoint::get_direction}
, needDualDirectionValidation{false}
, associatedVariableName{this, &NodeMaterialConnectionPoint::get_associatedVariableName,
&NodeMaterialConnectionPoint::set_associatedVariableName}
, innerType{this, &NodeMaterialConnectionPoint::get_innerType}
, type{this, &NodeMaterialConnectionPoint::get_type, &NodeMaterialConnectionPoint::set_type}
, isOptional{false}
, isExposedOnFrame{false}
, exposedPortPosition{-1}
, _prioritizeVertex{false}
, target{this, &NodeMaterialConnectionPoint::get_target,
&NodeMaterialConnectionPoint::set_target}
, isConnected{this, &NodeMaterialConnectionPoint::get_isConnected}
, isConnectedToInputBlock{this, &NodeMaterialConnectionPoint::get_isConnectedToInputBlock}
, connectInputBlock{this, &NodeMaterialConnectionPoint::get_connectInputBlock}
, connectedPoint{this, &NodeMaterialConnectionPoint::get_connectedPoint}
, ownerBlock{this, &NodeMaterialConnectionPoint::get_ownerBlock}
, sourceBlock{this, &NodeMaterialConnectionPoint::get_sourceBlock}
, connectedBlocks{this, &NodeMaterialConnectionPoint::get_connectedBlocks}
, endpoints{this, &NodeMaterialConnectionPoint::get_endpoints}
, hasEndpoints{this, &NodeMaterialConnectionPoint::get_hasEndpoints}
, isConnectedInVertexShader{this, &NodeMaterialConnectionPoint::get_isConnectedInVertexShader}
, isConnectedInFragmentShader{this,
&NodeMaterialConnectionPoint::get_isConnectedInFragmentShader}
, _target{NodeMaterialBlockTargets::VertexAndFragment}
, _type{NodeMaterialBlockConnectionPointTypes::Float}
, _connectInputBlock{nullptr}
, _sourceBlock{nullptr}
{
_ownerBlock = ownerBlock;
name = iName;
_direction = direction;
}
NodeMaterialConnectionPointDirection& NodeMaterialConnectionPoint::get_direction()
{
return _direction;
}
std::string NodeMaterialConnectionPoint::get_associatedVariableName() const
{
if (_ownerBlock->isInput()) {
auto inputBlock = std::static_pointer_cast<InputBlock>(_ownerBlock);
if (inputBlock) {
return inputBlock->associatedVariableName();
}
}
if ((!_enforceAssociatedVariableName || _associatedVariableName.empty()) && _connectedPoint) {
return _connectedPoint->associatedVariableName();
}
return _associatedVariableName;
}
void NodeMaterialConnectionPoint::set_associatedVariableName(std::string value)
{
_associatedVariableName = value;
}
NodeMaterialBlockConnectionPointTypes& NodeMaterialConnectionPoint::get_innerType()
{
if (_linkedConnectionSource && _linkedConnectionSource->isConnected()) {
return type();
}
return _type;
}
NodeMaterialBlockConnectionPointTypes& NodeMaterialConnectionPoint::get_type()
{
if (_type == NodeMaterialBlockConnectionPointTypes::AutoDetect) {
if (_ownerBlock->isInput()) {
auto inputBlock = std::static_pointer_cast<InputBlock>(_ownerBlock);
if (inputBlock) {
return inputBlock->type();
}
}
if (_connectedPoint) {
return _connectedPoint->type();
}
if (_linkedConnectionSource && _linkedConnectionSource->isConnected()) {
return _linkedConnectionSource->type();
}
}
if (_type == NodeMaterialBlockConnectionPointTypes::BasedOnInput) {
if (_typeConnectionSource) {
if (!_typeConnectionSource->isConnected() && _defaultConnectionPointType) {
return *_defaultConnectionPointType;
}
return _typeConnectionSource->type();
}
else if (_defaultConnectionPointType) {
return *_defaultConnectionPointType;
}
}
return _type;
}
void NodeMaterialConnectionPoint::set_type(const NodeMaterialBlockConnectionPointTypes& value)
{
_type = value;
}
NodeMaterialBlockTargets& NodeMaterialConnectionPoint::get_target()
{
if (!_prioritizeVertex || !_ownerBlock) {
return _target;
}
if (_target != NodeMaterialBlockTargets::VertexAndFragment) {
return _target;
}
if (_ownerBlock->target() == NodeMaterialBlockTargets::Fragment) {
_tmpTarget = NodeMaterialBlockTargets::Fragment;
return _tmpTarget;
}
_tmpTarget = NodeMaterialBlockTargets::Vertex;
return _tmpTarget;
}
void NodeMaterialConnectionPoint::set_target(const NodeMaterialBlockTargets& value)
{
_target = value;
}
bool NodeMaterialConnectionPoint::get_isConnected() const
{
return connectedPoint() != nullptr || hasEndpoints();
}
bool NodeMaterialConnectionPoint::get_isConnectedToInputBlock() const
{
return connectedPoint() != nullptr && connectedPoint()->ownerBlock()->isInput();
}
InputBlockPtr& NodeMaterialConnectionPoint::get_connectInputBlock()
{
if (!isConnectedToInputBlock()) {
_connectInputBlock = nullptr;
return _connectInputBlock;
}
_connectInputBlock = std::static_pointer_cast<InputBlock>(connectedPoint()->ownerBlock());
return _connectInputBlock;
}
NodeMaterialConnectionPointPtr& NodeMaterialConnectionPoint::get_connectedPoint()
{
return _connectedPoint;
}
NodeMaterialBlockPtr& NodeMaterialConnectionPoint::get_ownerBlock()
{
return _ownerBlock;
}
NodeMaterialBlockPtr& NodeMaterialConnectionPoint::get_sourceBlock()
{
if (!_connectedPoint) {
_sourceBlock = nullptr;
return _sourceBlock;
}
_sourceBlock = _connectedPoint->ownerBlock();
return _sourceBlock;
}
std::vector<NodeMaterialBlockPtr>& NodeMaterialConnectionPoint::get_connectedBlocks()
{
_connectedBlocks.clear();
if (_endpoints.empty()) {
return _connectedBlocks;
}
for (const auto& e : _endpoints) {
_connectedBlocks.emplace_back(e->ownerBlock());
}
return _connectedBlocks;
}
std::vector<NodeMaterialConnectionPointPtr>& NodeMaterialConnectionPoint::get_endpoints()
{
return _endpoints;
}
bool NodeMaterialConnectionPoint::get_hasEndpoints() const
{
return !_endpoints.empty();
}
bool NodeMaterialConnectionPoint::get_isConnectedInVertexShader() const
{
if (target() == NodeMaterialBlockTargets::Vertex) {
return true;
}
if (!hasEndpoints()) {
return false;
}
for (const auto& endpoint : _endpoints) {
if (endpoint->ownerBlock()->target() == NodeMaterialBlockTargets::Vertex) {
return true;
}
if (endpoint->target() == NodeMaterialBlockTargets::Vertex) {
return true;
}
if (endpoint->ownerBlock()->target() == NodeMaterialBlockTargets::Neutral
|| endpoint->ownerBlock()->target() == NodeMaterialBlockTargets::VertexAndFragment) {
for (const auto& o : endpoint->ownerBlock()->outputs()) {
if (o->isConnectedInVertexShader()) {
return true;
}
}
}
}
return false;
}
bool NodeMaterialConnectionPoint::get_isConnectedInFragmentShader() const
{
if (target() == NodeMaterialBlockTargets::Fragment) {
return true;
}
if (!hasEndpoints()) {
return false;
}
for (const auto& endpoint : _endpoints) {
if (endpoint->ownerBlock()->target() == NodeMaterialBlockTargets::Fragment) {
return true;
}
if (endpoint->ownerBlock()->target() == NodeMaterialBlockTargets::Neutral
|| endpoint->ownerBlock()->target() == NodeMaterialBlockTargets::VertexAndFragment) {
for (const auto& o : endpoint->ownerBlock()->outputs()) {
if (o->isConnectedInFragmentShader()) {
return true;
}
}
}
}
return false;
}
std::optional<std::pair<NodeMaterialBlockPtr, std::string>>
NodeMaterialConnectionPoint::createCustomInputBlock()
{
return std::nullopt;
}
std::string NodeMaterialConnectionPoint::getClassName() const
{
return "NodeMaterialConnectionPoint";
}
bool NodeMaterialConnectionPoint::canConnectTo(const NodeMaterialConnectionPoint& connectionPoint)
{
return checkCompatibilityState(connectionPoint)
== NodeMaterialConnectionPointCompatibilityStates::Compatible;
}
NodeMaterialConnectionPointCompatibilityStates NodeMaterialConnectionPoint::checkCompatibilityState(
const NodeMaterialConnectionPoint& connectionPoint)
{
const auto& iOwnerBlock = _ownerBlock;
const auto& otherBlock = connectionPoint.ownerBlock();
if (iOwnerBlock->target() == NodeMaterialBlockTargets::Fragment) {
// Let's check we are not going reverse
if (otherBlock->target() == NodeMaterialBlockTargets::Vertex) {
return NodeMaterialConnectionPointCompatibilityStates::TargetIncompatible;
}
for (const auto& output : otherBlock->outputs()) {
if (output->ownerBlock()->target() != NodeMaterialBlockTargets::Neutral
&& output->isConnectedInVertexShader()) {
return NodeMaterialConnectionPointCompatibilityStates::TargetIncompatible;
}
}
}
if (type != connectionPoint.type
&& connectionPoint.innerType() != NodeMaterialBlockConnectionPointTypes::AutoDetect) {
// Equivalents
if (NodeMaterialConnectionPoint::AreEquivalentTypes(type, connectionPoint.type)) {
return NodeMaterialConnectionPointCompatibilityStates::Compatible;
}
// Accepted types
if ((!connectionPoint.acceptedConnectionPointTypes.empty()
&& stl_util::contains(connectionPoint.acceptedConnectionPointTypes, type))
|| (connectionPoint._acceptedConnectionPointType
&& NodeMaterialConnectionPoint::AreEquivalentTypes(
connectionPoint._acceptedConnectionPointType->type, type))) {
return NodeMaterialConnectionPointCompatibilityStates::Compatible;
}
else {
return NodeMaterialConnectionPointCompatibilityStates::TypeIncompatible;
}
}
// Excluded
if ((!connectionPoint.excludedConnectionPointTypes.empty()
&& stl_util::contains(connectionPoint.excludedConnectionPointTypes, type))) {
return NodeMaterialConnectionPointCompatibilityStates::TypeIncompatible;
}
// Check hierarchy
auto targetBlock = otherBlock;
auto iSourceBlock = ownerBlock();
if (direction() == NodeMaterialConnectionPointDirection::Input) {
targetBlock = ownerBlock();
iSourceBlock = otherBlock;
}
if (targetBlock->isAnAncestorOf(iSourceBlock)) {
return NodeMaterialConnectionPointCompatibilityStates::HierarchyIssue;
}
return NodeMaterialConnectionPointCompatibilityStates::Compatible;
}
NodeMaterialConnectionPoint&
NodeMaterialConnectionPoint::connectTo(const NodeMaterialConnectionPointPtr& connectionPoint,
bool ignoreConstraints)
{
if (!ignoreConstraints && !canConnectTo(*connectionPoint)) {
throw std::runtime_error("Cannot connect these two connectors.");
}
_endpoints.emplace_back(connectionPoint);
connectionPoint->_connectedPoint = shared_from_this();
_enforceAssociatedVariableName = false;
onConnectionObservable.notifyObservers(connectionPoint.get());
connectionPoint->onConnectionObservable.notifyObservers(this);
return *this;
}
NodeMaterialConnectionPoint&
NodeMaterialConnectionPoint::disconnectFrom(const NodeMaterialConnectionPointPtr& endpoint)
{
auto index = stl_util::index_of(_endpoints, endpoint);
if (index == -1) {
return *this;
}
stl_util::splice(_endpoints, index, 1);
endpoint->_connectedPoint = nullptr;
_enforceAssociatedVariableName = false;
endpoint->_enforceAssociatedVariableName = false;
return *this;
}
json NodeMaterialConnectionPoint::serialize(bool /*isInput*/) const
{
return nullptr;
}
void NodeMaterialConnectionPoint::dispose()
{
onConnectionObservable.clear();
}
} // end of namespace BABYLON
<|endoftext|> |
<commit_before>#include <iostream>
#include "submodules/block_oled/Firmware/pong/oled/Edison_OLED.h"
#include "submodules/block_oled/Firmware/pong/gpio/gpio.h"
#include "math.h"
#include <stdio.h>
using namespace std;
// Function prototypes:
void setupOLED();
void startScreen();
void drawGame();
void cleanUp();
// Define an edOLED object:
edOLED oled;
// Pin definitions:
// All buttons have pull-up resistors on-board, so just declare
// them as regular INPUT's
gpio BUTTON_UP(47, INPUT);
gpio BUTTON_DOWN(44, INPUT);
gpio BUTTON_LEFT(165, INPUT);
gpio BUTTON_RIGHT(45, INPUT);
gpio BUTTON_SELECT(48, INPUT);
gpio BUTTON_A(49, INPUT);
gpio BUTTON_B(46, INPUT);
int main(int argc, char * argv[])
{
printf("WASSUP!?\r\n");
setupOLED();
while(1)
{
drawGame();
}
cleanUp();
return 0;
}
void setupOLED()
{
oled.begin();
//oled.clear(PAGE);
oled.display();
oled.setFontType(0);
}
// Draw the paddles, ball and score:
void drawGame()
{
oled.clear(PAGE);
oled.display();
}
void cleanUp()
{
oled.clear(PAGE);
oled.display();
}
<commit_msg>removed the drawgame clear part...<commit_after>#include <iostream>
#include "submodules/block_oled/Firmware/pong/oled/Edison_OLED.h"
#include "submodules/block_oled/Firmware/pong/gpio/gpio.h"
#include "math.h"
#include <stdio.h>
using namespace std;
// Function prototypes:
void setupOLED();
void startScreen();
void drawGame();
void cleanUp();
// Define an edOLED object:
edOLED oled;
// Pin definitions:
// All buttons have pull-up resistors on-board, so just declare
// them as regular INPUT's
gpio BUTTON_UP(47, INPUT);
gpio BUTTON_DOWN(44, INPUT);
gpio BUTTON_LEFT(165, INPUT);
gpio BUTTON_RIGHT(45, INPUT);
gpio BUTTON_SELECT(48, INPUT);
gpio BUTTON_A(49, INPUT);
gpio BUTTON_B(46, INPUT);
int main(int argc, char * argv[])
{
printf("WASSUP!?\r\n");
setupOLED();
while(1)
{
// drawGame();
}
cleanUp();
return 0;
}
void setupOLED()
{
oled.begin();
//oled.clear(PAGE);
oled.display();
oled.setFontType(0);
}
// Draw the paddles, ball and score:
void drawGame()
{
oled.clear(PAGE);
oled.display();
}
void cleanUp()
{
oled.clear(PAGE);
oled.display();
}
<|endoftext|> |
<commit_before>// Copyright eeGeo Ltd (2012-2015), All Rights Reserved
#include "NavRoutingCustomLocationPicker.h"
#include "IAppCameraLocationPicker.h"
#include "AppCameraLocationPicker.h"
#include "NavRoutingLocationModel.h"
#include "INavRoutingModel.h"
namespace ExampleApp
{
namespace NavRouting
{
namespace SdkModel
{
NavRoutingCustomLocationPicker::NavRoutingCustomLocationPicker(
INavRoutingModel& navRoutingModel,
AppCamera::SdkModel::IAppCameraLocationPicker& cameraLocationPicker
)
: m_navRoutingModel(navRoutingModel)
, m_cameraLocationPicker(cameraLocationPicker)
{
}
NavRoutingCustomLocationPicker::~NavRoutingCustomLocationPicker()
{
}
void NavRoutingCustomLocationPicker::StartSearching(bool forStartLocation)
{
m_isSearching = true;
m_isStartLocation = forStartLocation;
}
void NavRoutingCustomLocationPicker::StopSearching()
{
m_isSearching = false;
}
bool NavRoutingCustomLocationPicker::HandleTouchTap(float screenX, float screenY)
{
if(!m_isSearching)
{
return false;
}
AppCamera::SdkModel::AppCameraLocationPickerResult result = m_cameraLocationPicker.PickLocation(screenX, screenY);
if(!result.IsValidResult())
{
return true;
}
NavRoutingLocationModel locationModel("Custom location",
result.GetLocation(),
result.IsIndoors(),
result.GetIndoorId(),
result.GetIndoorFloorNumber());
if(m_isStartLocation)
{
m_navRoutingModel.SetStartLocation(locationModel);
}
else
{
m_navRoutingModel.SetEndLocation(locationModel);
}
return true;
}
}
}
}
<commit_msg>Fixed uninitalised state data for nav location picking. Buddy: Mark<commit_after>// Copyright eeGeo Ltd (2012-2015), All Rights Reserved
#include "NavRoutingCustomLocationPicker.h"
#include "IAppCameraLocationPicker.h"
#include "AppCameraLocationPicker.h"
#include "NavRoutingLocationModel.h"
#include "INavRoutingModel.h"
namespace ExampleApp
{
namespace NavRouting
{
namespace SdkModel
{
NavRoutingCustomLocationPicker::NavRoutingCustomLocationPicker(
INavRoutingModel& navRoutingModel,
AppCamera::SdkModel::IAppCameraLocationPicker& cameraLocationPicker
)
: m_navRoutingModel(navRoutingModel)
, m_cameraLocationPicker(cameraLocationPicker)
, m_isSearching(false)
, m_isStartLocation(false)
{
}
NavRoutingCustomLocationPicker::~NavRoutingCustomLocationPicker()
{
}
void NavRoutingCustomLocationPicker::StartSearching(bool forStartLocation)
{
m_isSearching = true;
m_isStartLocation = forStartLocation;
}
void NavRoutingCustomLocationPicker::StopSearching()
{
m_isSearching = false;
}
bool NavRoutingCustomLocationPicker::HandleTouchTap(float screenX, float screenY)
{
if(!m_isSearching)
{
return false;
}
AppCamera::SdkModel::AppCameraLocationPickerResult result = m_cameraLocationPicker.PickLocation(screenX, screenY);
if(!result.IsValidResult())
{
return true;
}
NavRoutingLocationModel locationModel("Custom location",
result.GetLocation(),
result.IsIndoors(),
result.GetIndoorId(),
result.GetIndoorFloorNumber());
if(m_isStartLocation)
{
m_navRoutingModel.SetStartLocation(locationModel);
}
else
{
m_navRoutingModel.SetEndLocation(locationModel);
}
return true;
}
}
}
}
<|endoftext|> |
<commit_before>/*!
\file rs_mesh_base.cpp
\brief This file implements base class for reservoir simulation meshes
\author Mark Khait
\date 2009-07-20
*/
#include "bs_mesh_stdafx.h"
#include "rs_mesh_base.h"
using namespace blue_sky;
rs_mesh_base ::rs_mesh_base ()
{
depths = give_kernel::Instance().create_object(bs_array<t_float>::bs_type());
actnum_array = 0;
poro_array = 0;
ntg_array = 0;
multpv_array = 0;
}
void
rs_mesh_base ::init_props (const sp_hdm_t hdm)
{
minpv = hdm->get_prop ()->get_f ("minimal_pore_volume");
minsv = hdm->get_prop ()->get_f ("minimal_splice_volume");
max_thickness = hdm->get_prop ()->get_f ("maximum_splice_thickness");
darcy_constant = hdm->get_darcy_constant ();
spv_float data_array;
spv_int sp_actnum_array;
sp_actnum_array = hdm->get_pool ()->get_i_data("ACTNUM");
if (sp_actnum_array->size()) actnum_array = &(*sp_actnum_array)[0];
n_elements = static_cast <t_long> (sp_actnum_array->size ());
n_active_elements = std::accumulate(sp_actnum_array->begin(), sp_actnum_array->end(),0);
data_array = hdm->get_pool ()->get_fp_data("PORO");
if (data_array->size()) poro_array = &(*data_array)[0];
data_array = hdm->get_pool ()->get_fp_data("NTG");
if (data_array && data_array->size()) ntg_array = &(*data_array)[0];
data_array = hdm->get_pool ()->get_fp_data("MULTPV");
if (data_array && data_array->size()) multpv_array = &(*data_array)[0];
}
int rs_mesh_base::init_int_to_ext()
{
t_long n_ext = t_long(ext_to_int->size());
if (n_ext == 0)
return -1;
int_to_ext->init (n_active_elements, 0);
t_long *int_to_ext_data = int_to_ext->data ();
t_long *ext_to_int_data = ext_to_int->data ();
for (t_long i = 0; i < n_ext; i++)
{
if (ext_to_int_data[i] != -1)
{
if (ext_to_int_data[i] >= n_active_elements)
{
bs_throw_exception (boost::format ("ext_to_int[%d] == %d >= %d") % i % ext_to_int_data[i] % n_active_elements);
}
int_to_ext_data[ext_to_int_data[i]] = i;
}
}
return 0;
}
void rs_mesh_base::check_data() const
{
base_t::check_data ();
if (minpv < 0)
bs_throw_exception (boost::format ("minpv = %d is out of range")% minpv);
if (minsv < 0)
bs_throw_exception (boost::format ("minsv = %d is out of range")% minsv);
if (max_thickness < 0)
bs_throw_exception (boost::format ("max_thickness = %d is out of range")% max_thickness);
if (!actnum_array)
bs_throw_exception ("ACTNUM array is not initialized");
if (!poro_array)
bs_throw_exception ("PORO array is not initialized");
if (!depths->size ())
bs_throw_exception ("depths array is not initialized");
}
//BS_INST_STRAT(rs_mesh_base);
<commit_msg>A bit better error reporting in init_int_to_ext<commit_after>/*!
\file rs_mesh_base.cpp
\brief This file implements base class for reservoir simulation meshes
\author Mark Khait
\date 2009-07-20
*/
#include "bs_mesh_stdafx.h"
#include "rs_mesh_base.h"
using namespace blue_sky;
rs_mesh_base ::rs_mesh_base ()
{
depths = give_kernel::Instance().create_object(bs_array<t_float>::bs_type());
actnum_array = 0;
poro_array = 0;
ntg_array = 0;
multpv_array = 0;
}
void
rs_mesh_base ::init_props (const sp_hdm_t hdm)
{
minpv = hdm->get_prop ()->get_f ("minimal_pore_volume");
minsv = hdm->get_prop ()->get_f ("minimal_splice_volume");
max_thickness = hdm->get_prop ()->get_f ("maximum_splice_thickness");
darcy_constant = hdm->get_darcy_constant ();
spv_float data_array;
spv_int sp_actnum_array;
sp_actnum_array = hdm->get_pool ()->get_i_data("ACTNUM");
if (sp_actnum_array->size()) actnum_array = &(*sp_actnum_array)[0];
n_elements = static_cast <t_long> (sp_actnum_array->size ());
n_active_elements = std::accumulate(sp_actnum_array->begin(), sp_actnum_array->end(),0);
data_array = hdm->get_pool ()->get_fp_data("PORO");
if (data_array->size()) poro_array = &(*data_array)[0];
data_array = hdm->get_pool ()->get_fp_data("NTG");
if (data_array && data_array->size()) ntg_array = &(*data_array)[0];
data_array = hdm->get_pool ()->get_fp_data("MULTPV");
if (data_array && data_array->size()) multpv_array = &(*data_array)[0];
}
int rs_mesh_base::init_int_to_ext()
{
t_long n_ext = t_long(ext_to_int->size());
if (n_ext == 0)
return -1;
int_to_ext->init (n_active_elements, 0);
t_long *int_to_ext_data = int_to_ext->data ();
t_long *ext_to_int_data = ext_to_int->data ();
stdv_long wrong;
stdv_long wrong_idx;
for (t_long i = 0; i < n_ext; i++)
{
if (ext_to_int_data[i] != -1)
{
if (ext_to_int_data[i] >= n_active_elements)
{
wrong.push_back (ext_to_int_data[i]);
wrong_idx.push_back (i);
}
else
{
int_to_ext_data[ext_to_int_data[i]] = i;
}
}
}
if (wrong.size ())
{
for (size_t i = 0, cnt = wrong.size (); i < cnt; ++i)
{
BOSERR (section::mesh, level::error)
<< boost::format ("ext_to_int[%d] == %s >= %d") % wrong_idx[i] % wrong[i] % n_active_elements
<< bs_end;
}
bs_throw_exception ("ext_to_int out of n_active_elements");
}
return 0;
}
void rs_mesh_base::check_data() const
{
base_t::check_data ();
if (minpv < 0)
bs_throw_exception (boost::format ("minpv = %d is out of range")% minpv);
if (minsv < 0)
bs_throw_exception (boost::format ("minsv = %d is out of range")% minsv);
if (max_thickness < 0)
bs_throw_exception (boost::format ("max_thickness = %d is out of range")% max_thickness);
if (!actnum_array)
bs_throw_exception ("ACTNUM array is not initialized");
if (!poro_array)
bs_throw_exception ("PORO array is not initialized");
if (!depths->size ())
bs_throw_exception ("depths array is not initialized");
}
//BS_INST_STRAT(rs_mesh_base);
<|endoftext|> |
<commit_before>//* This file is part of the MOOSE framework
//* https://www.mooseframework.org
//*
//* All rights reserved, see COPYRIGHT for full restrictions
//* https://github.com/idaholab/moose/blob/master/COPYRIGHT
//*
//* Licensed under LGPL 2.1, please see LICENSE for details
//* https://www.gnu.org/licenses/lgpl-2.1.html
#include "JinSlabCoeffFunc.h"
#include "ElectromagneticEnums.h"
#include <complex>
registerMooseObject("ElectromagneticsTestApp", JinSlabCoeffFunc);
InputParameters
JinSlabCoeffFunc::validParams()
{
InputParameters params = Function::validParams();
params.addClassDescription(
"Function describing a wave incident on a surface at a given angle, wavenumber, and domain "
"length, for use in the slab reflection benchmark.");
params.addRequiredParam<Real>("k", "Wavenumber");
params.addRequiredParam<Real>("theta", "Wave Incidence angle, in degrees");
params.addRequiredParam<Real>("length", "Length of slab domain");
MooseEnum component("real imaginary");
params.addParam<MooseEnum>("component", component, "Real or Imaginary wave component");
return params;
}
JinSlabCoeffFunc::JinSlabCoeffFunc(const InputParameters & parameters)
: Function(parameters),
_k(getParam<Real>("k")),
_theta(getParam<Real>("theta")),
_length(getParam<Real>("length")),
_component(getParam<MooseEnum>("component"))
{
}
Real
JinSlabCoeffFunc::value(Real /*t*/, const Point & p) const
{
std::complex<double> jay(0, 1);
std::complex<double> eps_r = 4.0 + (2.0 - jay * 0.1) * std::pow((1 - p(0) / _length), 2);
std::complex<double> mu_r(2, -0.1);
std::complex<double> val =
mu_r * std::pow(_k, 2) * (eps_r - (1 / mu_r) * std::pow(sin(_theta * libMesh::pi / 180.), 2));
if (_component == electromagnetics::REAL)
{
return val.real();
}
else
{
return val.imag();
}
}
<commit_msg>Fixup int vs double issue with std::complex and GCC<commit_after>//* This file is part of the MOOSE framework
//* https://www.mooseframework.org
//*
//* All rights reserved, see COPYRIGHT for full restrictions
//* https://github.com/idaholab/moose/blob/master/COPYRIGHT
//*
//* Licensed under LGPL 2.1, please see LICENSE for details
//* https://www.gnu.org/licenses/lgpl-2.1.html
#include "JinSlabCoeffFunc.h"
#include "ElectromagneticEnums.h"
#include <complex>
registerMooseObject("ElectromagneticsTestApp", JinSlabCoeffFunc);
InputParameters
JinSlabCoeffFunc::validParams()
{
InputParameters params = Function::validParams();
params.addClassDescription(
"Function describing a wave incident on a surface at a given angle, wavenumber, and domain "
"length, for use in the slab reflection benchmark.");
params.addRequiredParam<Real>("k", "Wavenumber");
params.addRequiredParam<Real>("theta", "Wave Incidence angle, in degrees");
params.addRequiredParam<Real>("length", "Length of slab domain");
MooseEnum component("real imaginary");
params.addParam<MooseEnum>("component", component, "Real or Imaginary wave component");
return params;
}
JinSlabCoeffFunc::JinSlabCoeffFunc(const InputParameters & parameters)
: Function(parameters),
_k(getParam<Real>("k")),
_theta(getParam<Real>("theta")),
_length(getParam<Real>("length")),
_component(getParam<MooseEnum>("component"))
{
}
Real
JinSlabCoeffFunc::value(Real /*t*/, const Point & p) const
{
std::complex<double> jay(0, 1);
std::complex<double> eps_r = 4.0 + (2.0 - jay * 0.1) * std::pow((1 - p(0) / _length), 2);
std::complex<double> mu_r(2, -0.1);
std::complex<double> val =
mu_r * std::pow(_k, 2) * (eps_r - (1.0 / mu_r) * std::pow(sin(_theta * libMesh::pi / 180.), 2));
if (_component == electromagnetics::REAL)
{
return val.real();
}
else
{
return val.imag();
}
}
<|endoftext|> |
<commit_before>/*
================================================
* ######
* ######### ##
* #### ### ##
* ## ## ##
* ## ## ## ## #### ### ######
* ## ## ## ## ###### ##### ######
* ## ## ## ## ### ## ### ##
* ## # ## ## ## ## ## ##### ##
* ## ## ## ## ## ## ## ##### ##
* ### ## ## ## ## ### # ## ##
* ########## ####### ####### ###### ##
* #### ## ###### #### #### ##
* ##
* ## CREATE: 2013-09-04
* #
================================================
QuestLAB 外部资源文件加载接口
================================================
*/
#include "../QstLibs/QstLibs.h"
/* 外部库引用 */
#ifndef _CR_NO_PRAGMA_LIB_
#pragma comment (lib, "QstLibs_msc.lib")
#endif
/* 从宿主传过来的参数 */
static socket_t s_netw = NULL;
static const ansi_t* s_root = NULL;
#if defined(_CR_BUILD_DLL_)
/*
=======================================
DLL 入口点
=======================================
*/
BOOL WINAPI
DllMain (
__CR_IN__ HANDLE hinst,
__CR_IN__ DWORD reason,
__CR_UU__ LPVOID reserved
)
{
switch (reason)
{
case DLL_PROCESS_ATTACH:
s_netw = NULL;
s_root = NULL;
break;
case DLL_PROCESS_DETACH:
TRY_FREE(s_root)
break;
}
CR_NOUSE(hinst);
CR_NOUSE(reserved);
return (TRUE);
}
#endif /* _CR_BUILD_DLL_ */
/*****************************************************************************/
/* 接口实现 */
/*****************************************************************************/
/*
---------------------------------------
启动加载器
---------------------------------------
*/
static void_t
res_init (
__CR_IN__ socket_t netw,
__CR_IN__ const ansi_t* root
)
{
if (netw != NULL)
s_netw = netw;
SAFE_FREE(s_root)
if (root != NULL)
s_root = str_dupA(root);
}
/*
---------------------------------------
释放加载器
---------------------------------------
*/
static void_t
res_kill (void_t)
{
s_netw = NULL;
SAFE_FREE(s_root)
}
/*
---------------------------------------
加载外部文件
---------------------------------------
*/
static bool_t
res_load (
__CR_OT__ sEX_FILE* filex,
__CR_IN__ const ansi_t* type,
__CR_IN__ const ansi_t* mount,
__CR_IN__ const ansi_t* name,
__CR_IN__ uint_t cpage
)
{
ansi_t* path;
ansi_t* full;
/* 跳过名称的根 */
if (is_slashA(*name))
name++;
/* 直接使用名称预读 */
if (s_root != NULL) {
full = path_appendA(s_root, name);
if (full == NULL)
return (FALSE);
if (file_existA(full)) {
filex->is_free = TRUE;
set_ldrA(&filex->ex_file, full, "", 0, 0);
filex->ex_file.page = cpage;
return (TRUE);
}
mem_free(full);
}
else {
if (file_existA(name)) {
filex->is_free = FALSE;
set_ldrA(&filex->ex_file, name, "", 0, 0);
filex->ex_file.page = cpage;
return (TRUE);
}
}
leng_t idx, size;
/* 以挂载名为根目录预读 */
if (str_cmpA(mount, QST_STR_GLOBALS) != 0) {
size = str_lenA(mount);
for (idx = 0; idx < size; idx++) {
if (mount[idx] == '|')
break;
}
/* 包中包不做预读, 只做一层的预读 */
if (idx >= size) {
if (s_root != NULL)
path = path_appendA(s_root, mount);
else
path = str_dupA(mount);
if (path == NULL)
return (FALSE);
filext_removeA(path);
full = path_appendA(path, name);
mem_free(path);
if (full == NULL)
return (FALSE);
if (file_existA(full)) {
filex->is_free = TRUE;
set_ldrA(&filex->ex_file, full, "", 0, 0);
filex->ex_file.page = cpage;
return (TRUE);
}
mem_free(full);
}
}
/* 使用网络接口加载 */
if (s_netw == NULL)
return (FALSE);
/* 发送资源加载命令 */
full = str_fmtA("res:load \"%s\" \"%s\" \"%s\" %u",
type, mount, name, cpage);
if (full == NULL)
return (FALSE);
if (!cmd_shl_send(s_netw, full)) {
mem_free(full);
return (FALSE);
}
mem_free(full); /* 加大网络超时五倍 */
socket_set_timeout(s_netw, -1, QST_TCP_TOUT * 5);
/* 等待资源加载返回 */
for (;;)
{
uint_t argc;
ansi_t** argv;
/* 接收一条消息, 出错退出 */
full = netw_cmd_recv(s_netw);
if (full == NULL)
break;
/* 判断是不是需要的消息 */
path = cmd_shl_get(full);
mem_free(full);
if (path == NULL)
continue;
argv = cmd_shl_split(path, &argc);
if (argv == NULL) {
mem_free(path);
break;
}
if ((argc < 2) ||
(str_cmpA(argv[1], type) != 0)) {
mem_free(argv);
mem_free(path);
continue;
}
if (str_cmpA(argv[0], "res:fail") == 0) {
mem_free(argv);
mem_free(path);
break;
}
if (str_cmpA(argv[0], "res:okay") == 0) {
if (argc < 3) {
mem_free(argv);
mem_free(path);
break;
}
void_t* data;
/* 返回读取的内存数据 */
size = str2intA(argv[2]);
mem_free(argv);
mem_free(path);
if (size == 0)
break;
data = share_file_get(type, size);
if (data == NULL)
break;
filex->is_free = TRUE;
set_ldrM(&filex->ex_file, data, size, "", 0, 0);
filex->ex_file.page = cpage;
socket_set_timeout(s_netw, -1, QST_TCP_TOUT);
return (TRUE);
}
mem_free(argv);
mem_free(path);
}
/* 从循环出来表示失败 */
socket_set_timeout(s_netw, -1, QST_TCP_TOUT);
return (FALSE);
}
/*****************************************************************************/
/* 接口导出 */
/*****************************************************************************/
/* 外部文件加载接口表 */
static const sRES_LOADER
s_res_loader = { res_init, res_kill, res_load };
/*
=======================================
获取外部文件加载接口表
=======================================
*/
CR_API const sRES_LOADER*
res_loader_get (void_t)
{
return (&s_res_loader);
}
<commit_msg>ResLoader: 过滤非法的返回数据大小<commit_after>/*
================================================
* ######
* ######### ##
* #### ### ##
* ## ## ##
* ## ## ## ## #### ### ######
* ## ## ## ## ###### ##### ######
* ## ## ## ## ### ## ### ##
* ## # ## ## ## ## ## ##### ##
* ## ## ## ## ## ## ## ##### ##
* ### ## ## ## ## ### # ## ##
* ########## ####### ####### ###### ##
* #### ## ###### #### #### ##
* ##
* ## CREATE: 2013-09-04
* #
================================================
QuestLAB 外部资源文件加载接口
================================================
*/
#include "../QstLibs/QstLibs.h"
/* 外部库引用 */
#ifndef _CR_NO_PRAGMA_LIB_
#pragma comment (lib, "QstLibs_msc.lib")
#endif
/* 从宿主传过来的参数 */
static socket_t s_netw = NULL;
static const ansi_t* s_root = NULL;
#if defined(_CR_BUILD_DLL_)
/*
=======================================
DLL 入口点
=======================================
*/
BOOL WINAPI
DllMain (
__CR_IN__ HANDLE hinst,
__CR_IN__ DWORD reason,
__CR_UU__ LPVOID reserved
)
{
switch (reason)
{
case DLL_PROCESS_ATTACH:
s_netw = NULL;
s_root = NULL;
break;
case DLL_PROCESS_DETACH:
TRY_FREE(s_root)
break;
}
CR_NOUSE(hinst);
CR_NOUSE(reserved);
return (TRUE);
}
#endif /* _CR_BUILD_DLL_ */
/*****************************************************************************/
/* 接口实现 */
/*****************************************************************************/
/*
---------------------------------------
启动加载器
---------------------------------------
*/
static void_t
res_init (
__CR_IN__ socket_t netw,
__CR_IN__ const ansi_t* root
)
{
if (netw != NULL)
s_netw = netw;
SAFE_FREE(s_root)
if (root != NULL)
s_root = str_dupA(root);
}
/*
---------------------------------------
释放加载器
---------------------------------------
*/
static void_t
res_kill (void_t)
{
s_netw = NULL;
SAFE_FREE(s_root)
}
/*
---------------------------------------
加载外部文件
---------------------------------------
*/
static bool_t
res_load (
__CR_OT__ sEX_FILE* filex,
__CR_IN__ const ansi_t* type,
__CR_IN__ const ansi_t* mount,
__CR_IN__ const ansi_t* name,
__CR_IN__ uint_t cpage
)
{
ansi_t* path;
ansi_t* full;
/* 跳过名称的根 */
if (is_slashA(*name))
name++;
/* 直接使用名称预读 */
if (s_root != NULL) {
full = path_appendA(s_root, name);
if (full == NULL)
return (FALSE);
if (file_existA(full)) {
filex->is_free = TRUE;
set_ldrA(&filex->ex_file, full, "", 0, 0);
filex->ex_file.page = cpage;
return (TRUE);
}
mem_free(full);
}
else {
if (file_existA(name)) {
filex->is_free = FALSE;
set_ldrA(&filex->ex_file, name, "", 0, 0);
filex->ex_file.page = cpage;
return (TRUE);
}
}
leng_t idx, size;
/* 以挂载名为根目录预读 */
if (str_cmpA(mount, QST_STR_GLOBALS) != 0) {
size = str_lenA(mount);
for (idx = 0; idx < size; idx++) {
if (mount[idx] == '|')
break;
}
/* 包中包不做预读, 只做一层的预读 */
if (idx >= size) {
if (s_root != NULL)
path = path_appendA(s_root, mount);
else
path = str_dupA(mount);
if (path == NULL)
return (FALSE);
filext_removeA(path);
full = path_appendA(path, name);
mem_free(path);
if (full == NULL)
return (FALSE);
if (file_existA(full)) {
filex->is_free = TRUE;
set_ldrA(&filex->ex_file, full, "", 0, 0);
filex->ex_file.page = cpage;
return (TRUE);
}
mem_free(full);
}
}
/* 使用网络接口加载 */
if (s_netw == NULL)
return (FALSE);
/* 发送资源加载命令 */
full = str_fmtA("res:load \"%s\" \"%s\" \"%s\" %u",
type, mount, name, cpage);
if (full == NULL)
return (FALSE);
if (!cmd_shl_send(s_netw, full)) {
mem_free(full);
return (FALSE);
}
mem_free(full); /* 加大网络超时五倍 */
socket_set_timeout(s_netw, -1, QST_TCP_TOUT * 5);
/* 等待资源加载返回 */
for (;;)
{
uint_t argc;
ansi_t** argv;
/* 接收一条消息, 出错退出 */
full = netw_cmd_recv(s_netw);
if (full == NULL)
break;
/* 判断是不是需要的消息 */
path = cmd_shl_get(full);
mem_free(full);
if (path == NULL)
continue;
argv = cmd_shl_split(path, &argc);
if (argv == NULL) {
mem_free(path);
break;
}
if ((argc < 2) ||
(str_cmpA(argv[1], type) != 0)) {
mem_free(argv);
mem_free(path);
continue;
}
if (str_cmpA(argv[0], "res:fail") == 0) {
mem_free(argv);
mem_free(path);
break;
}
if (str_cmpA(argv[0], "res:okay") == 0) {
if (argc < 3) {
mem_free(argv);
mem_free(path);
break;
}
void_t* data;
/* 返回读取的内存数据 */
size = str2intA(argv[2]);
mem_free(argv);
mem_free(path);
if ((dist_t)size <= 0)
break;
data = share_file_get(type, size);
if (data == NULL)
break;
filex->is_free = TRUE;
set_ldrM(&filex->ex_file, data, size, "", 0, 0);
filex->ex_file.page = cpage;
socket_set_timeout(s_netw, -1, QST_TCP_TOUT);
return (TRUE);
}
mem_free(argv);
mem_free(path);
}
/* 从循环出来表示失败 */
socket_set_timeout(s_netw, -1, QST_TCP_TOUT);
return (FALSE);
}
/*****************************************************************************/
/* 接口导出 */
/*****************************************************************************/
/* 外部文件加载接口表 */
static const sRES_LOADER
s_res_loader = { res_init, res_kill, res_load };
/*
=======================================
获取外部文件加载接口表
=======================================
*/
CR_API const sRES_LOADER*
res_loader_get (void_t)
{
return (&s_res_loader);
}
<|endoftext|> |
<commit_before><commit_msg>Prediction: process and normalize the feature map tensor<commit_after><|endoftext|> |
<commit_before>#include "glincludes.h"
#include "camera.h"
#include <stdio.h>
#include "volumeRenderer.h"
#include "voxelization.h"
//static VoxelMaker* voxel_maker_ptr_s;
static VoxelStructure* voxel_struct_ptr;
static GLuint texName;
static int _x,_y,_z;
//box and its index
static GLfloat vertice[] ={
-1.0f, 1.0f, -1.0f,
1.0f, 1.0f, -1.0f,
1.0f, 1.0f, 1.0f,
-1.0f, 1.0f, 1.0f,
-1.0f, -1.0f, -1.0f,
1.0f, -1.0f, -1.0f,
1.0f, -1.0f, 1.0f,
-1.0f, -1.0f, 1.0f
};
static GLfloat color[] = {
0.0f, 0.0f, 0.0f,
0.0f, 0.0f, 1.0f,
0.0f, 1.0f, 0.0f,
0.0f, 1.0f, 1.0f,
1.0f, 0.0f, 0.0f,
1.0f, 0.0f, 1.0f,
1.0f, 1.0f, 0.0f,
1.0f, 1.0f, 1.0f
};
static GLfloat texcoord[] = {
0.0f, 1.0f, 0.0f,
1.0f, 1.0f, 0.0f,
1.0f, 1.0f, 1.0f,
0.0f, 1.0f, 1.0f,
0.0f, 0.0f, 0.0f,
1.0f, 0.0f, 0.0f,
1.0f, 0.0f, 1.0f,
0.0f, 0.0f, 1.0f
};
static GLushort index[] =
{
3, 2, 6, 7,
1, 5, 6, 2,
6, 5, 4, 7,
5, 1, 0, 4,
0, 3, 7, 4,
0, 1, 2, 3
};
//the file is .raw
bool loadTextures() {
/* FILE *pFile = fopen(RAWFILENAME,"rb");
if (NULL == pFile) {
return false;
}
int size = XMAX*YMAX*ZMAX;
unsigned char *pVolume = new unsigned char[size];
bool ok = (size == fread(pVolume,sizeof(unsigned char), size,pFile));
fclose(pFile);*/
voxel_struct_ptr->get_size(_x, _y, _z);
texName = voxel_struct_ptr->Creat3DTexture();
glBindTexture(GL_TEXTURE_3D, texName);
glTexParameteri(GL_TEXTURE_3D, GL_TEXTURE_WRAP_S, GL_REPEAT);
glTexParameteri(GL_TEXTURE_3D, GL_TEXTURE_WRAP_T, GL_REPEAT);
glTexParameteri(GL_TEXTURE_3D, GL_TEXTURE_WRAP_R, GL_REPEAT);
glTexParameteri(GL_TEXTURE_3D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
glTexParameteri(GL_TEXTURE_3D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
//VoxelMaker::SaveToFile(voxel_struct_ptr, ".\\voxelfiles\\earth_voxel_1024.txt");
return true;
}
void init(void)
{
glewInit();
glClearColor(0.0, 0.0, 0.0, 0.0);
glShadeModel(GL_SMOOTH);
/***************test voxel maker*************************/
<<<<<<< HEAD
voxel_maker_ptr_s = VoxelMaker::MakeObjToVoxel("earth.obj", 128);
=======
//voxel_struct_ptr = VoxelMaker::MakeObjToVoxel("earth.obj", 1024);
voxel_struct_ptr = VoxelMaker::LoadVoxelFromFile(".\\voxelfiles\\earth_voxel_128.txt");
>>>>>>> xmm_notebook
/***************test voxel maker*************************/
/***************test renderer*************************/
loadTextures();
/***************test renderer*************************/
}
void display()
{
glClear(GL_DEPTH_BUFFER_BIT | GL_COLOR_BUFFER_BIT);
/***************test renderer*************************/
cameraDisplay();
glm::mat4 mv = View * Model;
glm::mat4 p = Projection;
//int _x,_y,_z;
//voxel_maker_ptr_s->GetSize(_x, _y, _z);
//VolumeRenderer::drawPhysicsWorld(texName, &mv, &p,XMAX, YMAX, ZMAX);
VolumeRenderer::drawPhysicsWorld(texName, &mv, &p,_x, _y, _z);
/***************test renderer*************************/
/***************test voxel maker*************************/
//int _x,_y,_z;
//voxel_maker_ptr_s->GetSize(_x, _y, _z);
//voxel_maker_ptr_s->DrawDepth(glm::ivec3(0, 0, 0), glm::ivec3(_x, _y, _z));
/***************test voxel maker*************************/
glutPostRedisplay();
glutSwapBuffers();
}
int main(int argc, char** argv)
{
glutInit(&argc, argv);
glutInitDisplayMode(GLUT_DOUBLE | GLUT_RGBA | GLUT_DEPTH);
glutInitWindowSize(SCREENWIDTH, SCREENHEIGHT);
glutInitWindowPosition(0, 0);
glutCreateWindow(argv[0]);
init();
glutDisplayFunc(display);
cameraLoop();
glutMainLoop();
return 0;
}
<commit_msg>改回并合并<commit_after>#include "glincludes.h"
#include "camera.h"
#include <stdio.h>
#include "volumeRenderer.h"
#include "voxelization.h"
//static VoxelMaker* voxel_maker_ptr_s;
static VoxelStructure* voxel_struct_ptr;
static GLuint texName;
static int _x,_y,_z;
//box and its index
static GLfloat vertice[] ={
-1.0f, 1.0f, -1.0f,
1.0f, 1.0f, -1.0f,
1.0f, 1.0f, 1.0f,
-1.0f, 1.0f, 1.0f,
-1.0f, -1.0f, -1.0f,
1.0f, -1.0f, -1.0f,
1.0f, -1.0f, 1.0f,
-1.0f, -1.0f, 1.0f
};
static GLfloat color[] = {
0.0f, 0.0f, 0.0f,
0.0f, 0.0f, 1.0f,
0.0f, 1.0f, 0.0f,
0.0f, 1.0f, 1.0f,
1.0f, 0.0f, 0.0f,
1.0f, 0.0f, 1.0f,
1.0f, 1.0f, 0.0f,
1.0f, 1.0f, 1.0f
};
static GLfloat texcoord[] = {
0.0f, 1.0f, 0.0f,
1.0f, 1.0f, 0.0f,
1.0f, 1.0f, 1.0f,
0.0f, 1.0f, 1.0f,
0.0f, 0.0f, 0.0f,
1.0f, 0.0f, 0.0f,
1.0f, 0.0f, 1.0f,
0.0f, 0.0f, 1.0f
};
static GLushort index[] =
{
3, 2, 6, 7,
1, 5, 6, 2,
6, 5, 4, 7,
5, 1, 0, 4,
0, 3, 7, 4,
0, 1, 2, 3
};
//the file is .raw
bool loadTextures() {
/* FILE *pFile = fopen(RAWFILENAME,"rb");
if (NULL == pFile) {
return false;
}
int size = XMAX*YMAX*ZMAX;
unsigned char *pVolume = new unsigned char[size];
bool ok = (size == fread(pVolume,sizeof(unsigned char), size,pFile));
fclose(pFile);*/
voxel_struct_ptr->get_size(_x, _y, _z);
texName = voxel_struct_ptr->Creat3DTexture();
glBindTexture(GL_TEXTURE_3D, texName);
glTexParameteri(GL_TEXTURE_3D, GL_TEXTURE_WRAP_S, GL_REPEAT);
glTexParameteri(GL_TEXTURE_3D, GL_TEXTURE_WRAP_T, GL_REPEAT);
glTexParameteri(GL_TEXTURE_3D, GL_TEXTURE_WRAP_R, GL_REPEAT);
glTexParameteri(GL_TEXTURE_3D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
glTexParameteri(GL_TEXTURE_3D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
//VoxelMaker::SaveToFile(voxel_struct_ptr, ".\\voxelfiles\\earth_voxel_1024.txt");
return true;
}
void init(void)
{
glewInit();
glClearColor(0.0, 0.0, 0.0, 0.0);
glShadeModel(GL_SMOOTH);
/***************test voxel maker*************************/
//voxel_struct_ptr = VoxelMaker::MakeObjToVoxel("earth.obj", 1024);
voxel_struct_ptr = VoxelMaker::LoadVoxelFromFile(".\\voxelfiles\\earth_voxel_128.txt");
/***************test voxel maker*************************/
/***************test renderer*************************/
loadTextures();
/***************test renderer*************************/
}
void display()
{
glClear(GL_DEPTH_BUFFER_BIT | GL_COLOR_BUFFER_BIT);
/***************test renderer*************************/
cameraDisplay();
glm::mat4 mv = View * Model;
glm::mat4 p = Projection;
//int _x,_y,_z;
//voxel_maker_ptr_s->GetSize(_x, _y, _z);
//VolumeRenderer::drawPhysicsWorld(texName, &mv, &p,XMAX, YMAX, ZMAX);
VolumeRenderer::drawPhysicsWorld(texName, &mv, &p,_x, _y, _z);
/***************test renderer*************************/
/***************test voxel maker*************************/
//int _x,_y,_z;
//voxel_maker_ptr_s->GetSize(_x, _y, _z);
//voxel_maker_ptr_s->DrawDepth(glm::ivec3(0, 0, 0), glm::ivec3(_x, _y, _z));
/***************test voxel maker*************************/
glutPostRedisplay();
glutSwapBuffers();
}
int main(int argc, char** argv)
{
glutInit(&argc, argv);
glutInitDisplayMode(GLUT_DOUBLE | GLUT_RGBA | GLUT_DEPTH);
glutInitWindowSize(SCREENWIDTH, SCREENHEIGHT);
glutInitWindowPosition(0, 0);
glutCreateWindow(argv[0]);
init();
glutDisplayFunc(display);
cameraLoop();
glutMainLoop();
return 0;
}
<|endoftext|> |
<commit_before>/*
================================================
* ######
* ######### ##
* #### ### ##
* ## ## ##
* ## ## ## ## #### ### ######
* ## ## ## ## ###### ##### ######
* ## ## ## ## ### ## ### ##
* ## # ## ## ## ## ## ##### ##
* ## ## ## ## ## ## ## ##### ##
* ### ## ## ## ## ### # ## ##
* ########## ####### ####### ###### ##
* #### ## ###### #### #### ##
* ##
* ## CREATE: 2015-07-20
* #
================================================
QuestLAB Python 脚本启动器
================================================
*/
#include "../QstLibs/QstLibs.h"
/* 应用的名称 */
#ifndef EXE_XNAME
#define EXE_XNAME "RunPython"
#define WIN_TITLE "RunPython"
#define WIN_CLASS "RunPythonCLSS"
#define WIN_ICONF "RunPython.ini"
#define WIN_XCONF "RunPython.xml"
#endif
/*
=======================================
WinMain 程序入口
=======================================
*/
int WINAPI
WinMain (
__CR_IN__ HINSTANCE curt_app,
__CR_IN__ HINSTANCE prev_app,
__CR_IN__ LPSTR cmd_line,
__CR_IN__ int cmd_show
)
{
uint_t argc;
ansi_t** argv;
CR_NOUSE(curt_app);
CR_NOUSE(prev_app);
CR_NOUSE(cmd_show);
/* 建立 CrHack 系统 */
if (!set_app_type(CR_APP_GUI))
return (QST_ERROR);
/* 获取命令行参数, 不包括进程文件名 */
argv = misc_get_param(cmd_line, &argc);
/* 参数解析 <脚本文件> */
if (argc < 1)
return (QST_ERROR);
leng_t size;
ansi_t* root;
ansi_t* exec;
/* 合成 PYTHONHOME 目录 */
exec = file_load_as_strA(QST_ROOT_START);
if (exec == NULL)
return (QST_ERROR);
root = str_fmtA("%s\\python", exec);
mem_free(exec);
if (root == NULL)
return (QST_ERROR);
DWORD cf = 0;
/* 根据扩展名选择用哪个启动 */
if (filext_checkA(argv[0], ".py")) {
exec = str_fmtA("%s.exe \"%s\"", root, argv[0]);
cf = CREATE_NEW_CONSOLE;
}
else
if (filext_checkA(argv[0], ".pyw")) {
exec = str_fmtA("%sw.exe \"%s\"", root, argv[0]);
cf = CREATE_NO_WINDOW;
}
else {
exec = NULL;
}
if (exec == NULL) {
mem_free(root);
return (QST_ERROR);
}
STARTUPINFOA si;
PROCESS_INFORMATION pi;
/* 启动脚本 */
mem_zero(&si, sizeof(si));
si.cb = sizeof(STARTUPINFOA);
SetEnvironmentVariableA("PYTHONHOME", root);
size = str_lenA(root);
size -= str_lenA("\\python");
root[size] = 0x00;
if (CreateProcessA(NULL, exec, NULL, NULL, FALSE,
cf, NULL, root, &si, &pi)) {
WaitForSingleObject(pi.hProcess, INFINITE);
CloseHandle(pi.hThread);
CloseHandle(pi.hProcess);
}
mem_free(exec);
mem_free(root);
return (QST_OKAY);
}
<commit_msg>RunPython: 支持从任何目录执行脚本<commit_after>/*
================================================
* ######
* ######### ##
* #### ### ##
* ## ## ##
* ## ## ## ## #### ### ######
* ## ## ## ## ###### ##### ######
* ## ## ## ## ### ## ### ##
* ## # ## ## ## ## ## ##### ##
* ## ## ## ## ## ## ## ##### ##
* ### ## ## ## ## ### # ## ##
* ########## ####### ####### ###### ##
* #### ## ###### #### #### ##
* ##
* ## CREATE: 2015-07-20
* #
================================================
QuestLAB Python 脚本启动器
================================================
*/
#include "../QstLibs/QstLibs.h"
/* 应用的名称 */
#ifndef EXE_XNAME
#define EXE_XNAME "RunPython"
#define WIN_TITLE "RunPython"
#define WIN_CLASS "RunPythonCLSS"
#define WIN_ICONF "RunPython.ini"
#define WIN_XCONF "RunPython.xml"
#endif
/*
=======================================
WinMain 程序入口
=======================================
*/
int WINAPI
WinMain (
__CR_IN__ HINSTANCE curt_app,
__CR_IN__ HINSTANCE prev_app,
__CR_IN__ LPSTR cmd_line,
__CR_IN__ int cmd_show
)
{
uint_t argc;
ansi_t** argv;
CR_NOUSE(curt_app);
CR_NOUSE(prev_app);
CR_NOUSE(cmd_show);
/* 建立 CrHack 系统 */
if (!set_app_type(CR_APP_GUI))
return (QST_ERROR);
/* 获取命令行参数, 不包括进程文件名 */
argv = misc_get_param(cmd_line, &argc);
/* 参数解析 <脚本文件> [相对路径] */
if (argc < 1)
return (QST_ERROR);
leng_t size;
ansi_t* root;
ansi_t* exec;
/* 合成 PYTHONHOME 目录 */
exec = file_load_as_strA(QST_ROOT_START);
if (exec == NULL) {
if (argc < 2)
return (QST_ERROR);
root = str_fmtA("%s\\" QST_ROOT_START, argv[1]);
if (root == NULL)
return (QST_ERROR);
exec = file_load_as_strA(root);
mem_free(root);
if (exec == NULL)
return (QST_ERROR);
}
root = str_fmtA("%s\\python", exec);
mem_free(exec);
if (root == NULL)
return (QST_ERROR);
DWORD cf = 0;
/* 根据扩展名选择用哪个启动 */
if (filext_checkA(argv[0], ".py")) {
exec = str_fmtA("%s.exe \"%s\"", root, argv[0]);
cf = CREATE_NEW_CONSOLE;
}
else
if (filext_checkA(argv[0], ".pyw")) {
exec = str_fmtA("%sw.exe \"%s\"", root, argv[0]);
cf = CREATE_NO_WINDOW;
}
else {
exec = NULL;
}
if (exec == NULL) {
mem_free(root);
return (QST_ERROR);
}
STARTUPINFOA si;
PROCESS_INFORMATION pi;
/* 启动脚本 */
mem_zero(&si, sizeof(si));
si.cb = sizeof(STARTUPINFOA);
SetEnvironmentVariableA("PYTHONHOME", root);
size = str_lenA(root);
size -= str_lenA("\\python");
root[size] = 0x00;
if (CreateProcessA(NULL, exec, NULL, NULL, FALSE,
cf, NULL, root, &si, &pi)) {
WaitForSingleObject(pi.hProcess, INFINITE);
CloseHandle(pi.hThread);
CloseHandle(pi.hProcess);
}
mem_free(exec);
mem_free(root);
return (QST_OKAY);
}
<|endoftext|> |
<commit_before>/*************************************************************************
*
* $RCSfile: basicmigration.hxx,v $
*
* $Revision: 1.2 $
*
* last change: $Author: rt $ $Date: 2005-01-27 14:26:43 $
*
* The Contents of this file are made available subject to the terms of
* either of the following licenses
*
* - GNU Lesser General Public License Version 2.1
* - Sun Industry Standards Source License Version 1.1
*
* Sun Microsystems Inc., October, 2000
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2000 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
*
* Sun Industry Standards Source License Version 1.1
* =================================================
* The contents of this file are subject to the Sun Industry Standards
* Source License Version 1.1 (the "License"); You may not use this file
* except in compliance with the License. You may obtain a copy of the
* License at http://www.openoffice.org/license.html.
*
* Software provided under this License is provided on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
* WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
* MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
* See the License for the specific provisions governing your rights and
* obligations concerning the Software.
*
* The Initial Developer of the Original Code is: Sun Microsystems, Inc.
*
* Copyright: 2000 by Sun Microsystems, Inc.
*
* All Rights Reserved.
*
* Contributor(s): _______________________________________
*
*
************************************************************************/
#ifndef _DESKTOP_BASICMIGRATION_HXX_
#define _DESKTOP_BASICMIGRATION_HXX_
#ifndef _COM_SUN_STAR_LANG_XSERVICEINFO_HPP_
#include <com/sun/star/lang/XServiceInfo.hpp>
#endif
#ifndef _COM_SUN_STAR_LANG_XINITIALIZATION_HPP_
#include <com/sun/star/lang/XInitialization.hpp>
#endif
#ifndef _COM_SUN_STAR_TASK_XJOB_HPP_
#include <com/sun/star/task/XJob.hpp>
#endif
#ifndef _COM_SUN_STAR_UNO_XCOMPONENTCONTEXT_HPP_
#include <com/sun/star/uno/XComponentContext.hpp>
#endif
#ifndef _CPPUHELPER_IMPLBASE3_HXX_
#include <cppuhelper/implbase3.hxx>
#endif
#ifndef _OSL_MUTEX_HXX_
#include <osl/mutex.hxx>
#endif
#ifndef _OSL_FILE_HXX_
#include <osl/file.hxx>
#endif
#include <vector>
#include <memory>
class INetURLObject;
//.........................................................................
namespace migration
{
//.........................................................................
::rtl::OUString SAL_CALL BasicMigration_getImplementationName();
::com::sun::star::uno::Sequence< ::rtl::OUString > SAL_CALL BasicMigration_getSupportedServiceNames();
::com::sun::star::uno::Reference< ::com::sun::star::uno::XInterface > SAL_CALL BasicMigration_create(
::com::sun::star::uno::Reference< ::com::sun::star::uno::XComponentContext > const & xContext )
SAL_THROW( (::com::sun::star::uno::Exception) );
// =============================================================================
// class BasicMigration
// =============================================================================
typedef ::std::vector< ::rtl::OUString > TStringVector;
typedef ::std::auto_ptr< TStringVector > TStringVectorPtr;
typedef ::cppu::WeakImplHelper3<
::com::sun::star::lang::XServiceInfo,
::com::sun::star::lang::XInitialization,
::com::sun::star::task::XJob > BasicMigration_BASE;
class BasicMigration : public BasicMigration_BASE
{
private:
::osl::Mutex m_aMutex;
::rtl::OUString m_sSourceDir;
TStringVectorPtr getFiles( const ::rtl::OUString& rBaseURL ) const;
::osl::FileBase::RC checkAndCreateDirectory( INetURLObject& rDirURL );
void copyFiles();
public:
BasicMigration();
virtual ~BasicMigration();
// XServiceInfo
virtual ::rtl::OUString SAL_CALL getImplementationName()
throw (::com::sun::star::uno::RuntimeException);
virtual sal_Bool SAL_CALL supportsService( const ::rtl::OUString& rServiceName )
throw (::com::sun::star::uno::RuntimeException);
virtual ::com::sun::star::uno::Sequence< ::rtl::OUString > SAL_CALL getSupportedServiceNames()
throw (::com::sun::star::uno::RuntimeException);
// XInitialization
virtual void SAL_CALL initialize( const ::com::sun::star::uno::Sequence< ::com::sun::star::uno::Any >& aArguments )
throw (::com::sun::star::uno::Exception, ::com::sun::star::uno::RuntimeException);
// XJob
virtual ::com::sun::star::uno::Any SAL_CALL execute(
const ::com::sun::star::uno::Sequence< ::com::sun::star::beans::NamedValue >& Arguments )
throw (::com::sun::star::lang::IllegalArgumentException, ::com::sun::star::uno::Exception,
::com::sun::star::uno::RuntimeException);
};
//.........................................................................
} // namespace migration
//.........................................................................
#endif // _DESKTOP_BASICMIGRATION_HXX_
<commit_msg>INTEGRATION: CWS lo5 (1.2.88); FILE MERGED 2005/04/28 11:24:45 tbe 1.2.88.1: #i48275# migration of auto correction files<commit_after>/*************************************************************************
*
* $RCSfile: basicmigration.hxx,v $
*
* $Revision: 1.3 $
*
* last change: $Author: rt $ $Date: 2005-05-13 08:10:05 $
*
* The Contents of this file are made available subject to the terms of
* either of the following licenses
*
* - GNU Lesser General Public License Version 2.1
* - Sun Industry Standards Source License Version 1.1
*
* Sun Microsystems Inc., October, 2000
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2000 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
*
* Sun Industry Standards Source License Version 1.1
* =================================================
* The contents of this file are subject to the Sun Industry Standards
* Source License Version 1.1 (the "License"); You may not use this file
* except in compliance with the License. You may obtain a copy of the
* License at http://www.openoffice.org/license.html.
*
* Software provided under this License is provided on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
* WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
* MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
* See the License for the specific provisions governing your rights and
* obligations concerning the Software.
*
* The Initial Developer of the Original Code is: Sun Microsystems, Inc.
*
* Copyright: 2000 by Sun Microsystems, Inc.
*
* All Rights Reserved.
*
* Contributor(s): _______________________________________
*
*
************************************************************************/
#ifndef _DESKTOP_BASICMIGRATION_HXX_
#define _DESKTOP_BASICMIGRATION_HXX_
#ifndef _DESKTOP_MISC_HXX_
#include "misc.hxx"
#endif
#ifndef _COM_SUN_STAR_LANG_XSERVICEINFO_HPP_
#include <com/sun/star/lang/XServiceInfo.hpp>
#endif
#ifndef _COM_SUN_STAR_LANG_XINITIALIZATION_HPP_
#include <com/sun/star/lang/XInitialization.hpp>
#endif
#ifndef _COM_SUN_STAR_TASK_XJOB_HPP_
#include <com/sun/star/task/XJob.hpp>
#endif
#ifndef _COM_SUN_STAR_UNO_XCOMPONENTCONTEXT_HPP_
#include <com/sun/star/uno/XComponentContext.hpp>
#endif
#ifndef _CPPUHELPER_IMPLBASE3_HXX_
#include <cppuhelper/implbase3.hxx>
#endif
#ifndef _OSL_MUTEX_HXX_
#include <osl/mutex.hxx>
#endif
#ifndef _OSL_FILE_HXX_
#include <osl/file.hxx>
#endif
class INetURLObject;
//.........................................................................
namespace migration
{
//.........................................................................
::rtl::OUString SAL_CALL BasicMigration_getImplementationName();
::com::sun::star::uno::Sequence< ::rtl::OUString > SAL_CALL BasicMigration_getSupportedServiceNames();
::com::sun::star::uno::Reference< ::com::sun::star::uno::XInterface > SAL_CALL BasicMigration_create(
::com::sun::star::uno::Reference< ::com::sun::star::uno::XComponentContext > const & xContext )
SAL_THROW( (::com::sun::star::uno::Exception) );
// =============================================================================
// class BasicMigration
// =============================================================================
typedef ::cppu::WeakImplHelper3<
::com::sun::star::lang::XServiceInfo,
::com::sun::star::lang::XInitialization,
::com::sun::star::task::XJob > BasicMigration_BASE;
class BasicMigration : public BasicMigration_BASE
{
private:
::osl::Mutex m_aMutex;
::rtl::OUString m_sSourceDir;
TStringVectorPtr getFiles( const ::rtl::OUString& rBaseURL ) const;
::osl::FileBase::RC checkAndCreateDirectory( INetURLObject& rDirURL );
void copyFiles();
public:
BasicMigration();
virtual ~BasicMigration();
// XServiceInfo
virtual ::rtl::OUString SAL_CALL getImplementationName()
throw (::com::sun::star::uno::RuntimeException);
virtual sal_Bool SAL_CALL supportsService( const ::rtl::OUString& rServiceName )
throw (::com::sun::star::uno::RuntimeException);
virtual ::com::sun::star::uno::Sequence< ::rtl::OUString > SAL_CALL getSupportedServiceNames()
throw (::com::sun::star::uno::RuntimeException);
// XInitialization
virtual void SAL_CALL initialize( const ::com::sun::star::uno::Sequence< ::com::sun::star::uno::Any >& aArguments )
throw (::com::sun::star::uno::Exception, ::com::sun::star::uno::RuntimeException);
// XJob
virtual ::com::sun::star::uno::Any SAL_CALL execute(
const ::com::sun::star::uno::Sequence< ::com::sun::star::beans::NamedValue >& Arguments )
throw (::com::sun::star::lang::IllegalArgumentException, ::com::sun::star::uno::Exception,
::com::sun::star::uno::RuntimeException);
};
//.........................................................................
} // namespace migration
//.........................................................................
#endif // _DESKTOP_BASICMIGRATION_HXX_
<|endoftext|> |
<commit_before>//
// Copyright (C) 2007-2016 SIPez LLC. All rights reserved.
//
// Copyright (C) 2007 SIPfoundry Inc.
// Licensed by SIPfoundry under the LGPL license.
//
// $$
///////////////////////////////////////////////////////////////////////////////
// Author: Alexander Chemeris <Alexander DOT Chemeris AT SIPez DOT com>
// SYSTEM INCLUDES
#include <assert.h>
// APPLICATION INCLUDES
#include <mp/MpAudioOutputConnection.h>
#include <mp/MpOutputDeviceDriver.h>
#include <mp/MpDspUtils.h>
#include <os/OsLock.h>
#include <os/OsDefs.h> // for min macro
#include <os/OsSysLog.h>
//#define RTL_ENABLED
//#define RTL_AUDIO_ENABLED
#ifdef RTL_ENABLED
#include <rtl_macro.h>
#else
#define RTL_BLOCK(x)
#define RTL_EVENT(x,y)
#endif
// EXTERNAL FUNCTIONS
// EXTERNAL VARIABLES
// CONSTANTS
// STATIC VARIABLE INITIALIZATIONS
// PRIVATE CLASSES
// DEFINES
#define DEBUG_PRINT
#undef DEBUG_PRINT
// MACROS
#ifdef DEBUG_PRINT // [
# define debugPrintf printf
#else // DEBUG_PRINT ][
static void debugPrintf(...) {}
#endif // DEBUG_PRINT ]
/* //////////////////////////// PUBLIC //////////////////////////////////// */
/* ============================ CREATORS ================================== */
MpAudioOutputConnection::MpAudioOutputConnection(MpOutputDeviceHandle deviceId,
MpOutputDeviceDriver *deviceDriver)
: UtlInt(deviceId)
, mMutex(OsMutexBase::Q_PRIORITY)
, mUseCount(0)
, mpDeviceDriver(deviceDriver)
, mCurrentFrameTime(0)
, mMixerBufferLength(0)
, mpMixerBuffer(NULL)
, mMixerBufferBegin(0)
, readyForDataCallbackNotf((intptr_t)this, readyForDataCallback)
, mpFlowgraphTicker(NULL)
{
assert(mpDeviceDriver != NULL);
};
MpAudioOutputConnection::~MpAudioOutputConnection()
{
}
/* ============================ MANIPULATORS ============================== */
OsStatus MpAudioOutputConnection::enableDevice(unsigned samplesPerFrame,
unsigned samplesPerSec,
MpFrameTime currentFrameTime,
MpFrameTime mixerBufferLength)
{
OsStatus result = OS_FAILED;
OsLock lock(mMutex);
assert(samplesPerFrame > 0);
assert(samplesPerSec > 0);
if (mpDeviceDriver->isEnabled())
{
OsSysLog::add(FAC_MP, PRI_DEBUG,
"MpAudioOutputConnection::enableDevice() device (%s id: %d) already enabled status: %d",
mpDeviceDriver->getDeviceName().data(),
getValue(),
OS_INVALID_STATE);
return(OS_INVALID_STATE);
}
// Mixer buffer length can't be zero.
if (mixerBufferLength == 0)
{
return OS_NOT_SUPPORTED;
}
// Set current frame time for this connection.
mCurrentFrameTime = currentFrameTime;
// Calculate number of samples in mixer buffer.
// I.e. convert from milliseconds to samples and round to frame boundary.
// Note: this calculation may overflow (e.g. 10000msec*44100Hz > 4294967296smp).
unsigned bufferSamples = mixerBufferLength*samplesPerSec/1000;
bufferSamples = ((bufferSamples + samplesPerFrame - 1) / samplesPerFrame)
* samplesPerFrame;
// Initialize mixer buffer. All mixer buffer related variables will be set here.
if (initMixerBuffer(bufferSamples) != OS_SUCCESS)
{
return result;
}
// Enable device driver
result = mpDeviceDriver->enableDevice(samplesPerFrame,
samplesPerSec,
mCurrentFrameTime,
readyForDataCallbackNotf);
return result;
}
OsStatus MpAudioOutputConnection::disableDevice()
{
OsStatus result = OS_FAILED;
OsLock lock(mMutex);
// Disable device and set result code.
result = mpDeviceDriver->disableDevice();
// Free mixer buffer if device was set to disabled state.
if (!mpDeviceDriver->isEnabled())
{
// Do not check return code, as it is not critical if it fails.
freeMixerBuffer();
}
return result;
}
OsStatus MpAudioOutputConnection::enableFlowgraphTicker(OsNotification *pFlowgraphTicker)
{
OsStatus result = OS_SUCCESS;
OsLock lock(mMutex);
assert(mpFlowgraphTicker == NULL);
// Set flowgraph ticker
mpFlowgraphTicker = pFlowgraphTicker;
return result;
}
OsStatus MpAudioOutputConnection::disableFlowgraphTicker()
{
OsStatus result = OS_SUCCESS;
OsLock lock(mMutex);
assert(mpFlowgraphTicker != NULL);
// Clear flowgraph ticker notification
mpFlowgraphTicker = NULL;
return result;
}
OsStatus MpAudioOutputConnection::pushFrameBeginning(unsigned int numSamples,
const MpAudioSample* samples,
MpFrameTime &frameTime)
{
OsStatus result = OS_SUCCESS;
RTL_BLOCK("MpAudioOutputConnection::pushFrame");
assert(numSamples > 0);
// From now we access internal data. Take lock.
OsLock lock(mMutex);
RTL_EVENT("MpAudioOutputConnection::pushFrame_frameTime", frameTime);
RTL_EVENT("MpAudioOutputConnection::pushFrame_currentTime", mCurrentFrameTime);
RTL_EVENT("MpAudioOutputConnection::pushFrame", this->getValue());
// Do nothing if no audio was pushed. Mixer buffer will be filled with
// silence or data from other sources.
if (samples != NULL)
{
// Mix frame to the very beginning of the mixer buffer.
result = mixFrame(mMixerBufferBegin, samples, numSamples);
}
frameTime = mCurrentFrameTime;
return result;
};
OsStatus MpAudioOutputConnection::pushFrame(unsigned int numSamples,
const MpAudioSample* samples,
MpFrameTime frameTime)
{
OsStatus result = OS_SUCCESS;
RTL_EVENT("MpAudioOutputConnection::pushFrame", -1);
assert(numSamples > 0);
// From now we access internal data. Take lock.
OsLock lock(mMutex);
RTL_EVENT("MpAudioOutputConnection::pushFrame_frameTime", frameTime);
RTL_EVENT("MpAudioOutputConnection::pushFrame_currentTime", mCurrentFrameTime);
RTL_EVENT("MpAudioOutputConnection::pushFrame", this->getValue());
// Check for late frame. Check for early frame is done inside mixFrame().
if (MpDspUtils::compareSerials(frameTime, mCurrentFrameTime) < 0)
{
OsSysLog::add(FAC_MP, PRI_WARNING,
"MpAudioOutputConnection::pushFrame()"
" OS_INVALID_STATE frameTime=%d, currentTime=%d\n",
frameTime, mCurrentFrameTime);
result = OS_INVALID_STATE;
RTL_EVENT("MpAudioOutputConnection::pushFrame", result);
return result;
}
if(mpDeviceDriver->isEnabled())
{
// Convert frameTime to offset in mixer buffer.
// Note: frameTime >= mCurrentFrameTime.
unsigned mixerBufferOffsetFrames =
(frameTime-mCurrentFrameTime) / mpDeviceDriver->getFramePeriod();
unsigned mixerBufferOffsetSamples =
mixerBufferOffsetFrames * mpDeviceDriver->getSamplesPerFrame();
// Don't touch mix buffer if no audio was pushed. Mixer buffer will be filled
// with silence or data from other sources.
if (samples != NULL)
{
// Mix this data with other sources.
result = mixFrame(mixerBufferOffsetSamples, samples, numSamples);
if(result != OS_SUCCESS)
{
OsSysLog::add(FAC_MP, PRI_WARNING,
"MpAudioOutputConnection::pushFrame mixFrame(%d, %p, %d) returned: %d"
" frameTime=%d, currentTime=%d\n",
(int)mixerBufferOffsetSamples, samples, numSamples, result,
frameTime, mCurrentFrameTime);
}
}
else
{
// Just check for late frame.
result = isLateToMix(mixerBufferOffsetSamples, numSamples);
}
}
else
{
result = OS_INVALID_STATE;
}
RTL_EVENT("MpAudioOutputConnection::pushFrame", result);
return result;
};
/* ============================ ACCESSORS ================================= */
MpFrameTime MpAudioOutputConnection::getCurrentFrameTime() const
{
OsLock lock(mMutex);
return mCurrentFrameTime;
}
/* ============================ INQUIRY =================================== */
/* //////////////////////////// PROTECTED ///////////////////////////////// */
OsStatus MpAudioOutputConnection::initMixerBuffer(unsigned mixerBufferLength)
{
// We cannot allocate buffer of zero length.
if (mixerBufferLength == 0)
{
return OS_FAILED;
}
// Deallocate mixer buffer if it is allocated.
// Do not check return value. Nothing fatal may happen inside.
freeMixerBuffer();
// Initialize variables.
mMixerBufferLength = mixerBufferLength;
mpMixerBuffer = new MpAudioSample[mMixerBufferLength];
mMixerBufferBegin = 0;
// Clear buffer data.
memset(mpMixerBuffer, 0, mMixerBufferLength*sizeof(MpAudioSample));
return OS_SUCCESS;
}
OsStatus MpAudioOutputConnection::freeMixerBuffer()
{
mMixerBufferLength = 0;
if (mpMixerBuffer != NULL)
{
delete[] mpMixerBuffer;
mpMixerBuffer = NULL;
}
mMixerBufferBegin = 0;
return OS_SUCCESS;
}
OsStatus MpAudioOutputConnection::mixFrame(unsigned frameOffset,
const MpAudioSample* samples,
unsigned numSamples)
{
assert(numSamples > 0);
assert(samples != NULL);
// Check for late frame.
if (isLateToMix(frameOffset, numSamples) == OS_LIMIT_REACHED)
{
OsSysLog::add(FAC_MP, PRI_WARNING,
"MpAudioOutputConnection::mixFrame()"
" OS_LIMIT_REACHED offset=%d, samples=%d, bufferLength=%d\n",
frameOffset, numSamples, mMixerBufferLength);
return OS_LIMIT_REACHED;
}
// Calculate frame start as if buffer is linear
unsigned frameBegin = mMixerBufferBegin+frameOffset;
// and wrap it because it is circular actually.
if (frameBegin >= mMixerBufferLength)
{
frameBegin -= mMixerBufferLength;
}
// Calculate size of first chunk to mix.
unsigned firstChunkSize = sipx_min(numSamples, mMixerBufferLength-frameBegin);
// Counter variables for next two loops
unsigned srcIndex, dstIndex;
// from frame begin to buffer wrap
for (srcIndex=0, dstIndex=frameBegin;
srcIndex<firstChunkSize;
srcIndex++, dstIndex++)
{
mpMixerBuffer[dstIndex] += samples[srcIndex];
}
// from buffer wrap to frame end
for (dstIndex=0;
srcIndex<numSamples;
srcIndex++, dstIndex++)
{
mpMixerBuffer[dstIndex] += samples[srcIndex];
}
return OS_SUCCESS;
}
OsStatus MpAudioOutputConnection::advanceMixerBuffer(unsigned numSamples)
{
// If buffer could be copied in one pass
if(numSamples <= 0)
{
OsSysLog::add(FAC_MP, PRI_ERR, "MpAudioOutputConnection::advanceMixerBuffer invoked with: %d samples\n", numSamples);
assert(numSamples > 0);
}
else if(numSamples > mMixerBufferLength)
{
OsSysLog::add(FAC_MP, PRI_ERR, "MpAudioOutputConnection::advanceMixerBuffer invoked with numSamples: %d > mMixerBufferLength: %d\n",
numSamples, mMixerBufferLength);
assert(numSamples <= mMixerBufferLength);
}
else if (mMixerBufferBegin+numSamples <= mMixerBufferLength)
{
memset(&mpMixerBuffer[mMixerBufferBegin],
0,
numSamples*sizeof(MpAudioSample));
mMixerBufferBegin += numSamples;
mMixerBufferBegin %= mMixerBufferLength;
}
else
{
unsigned firstChunkSize = mMixerBufferLength-mMixerBufferBegin;
memset(&mpMixerBuffer[mMixerBufferBegin],
0,
firstChunkSize*sizeof(MpAudioSample));
memset(&mpMixerBuffer[0],
0,
(numSamples-firstChunkSize)*sizeof(MpAudioSample));
mMixerBufferBegin = numSamples - firstChunkSize;
}
return OS_SUCCESS;
}
void MpAudioOutputConnection::readyForDataCallback(const intptr_t userData,
const intptr_t eventData)
{
OsStatus result;
MpAudioOutputConnection *pConnection = (MpAudioOutputConnection*)userData;
RTL_BLOCK("MpAudioOutputConnection::tickerCallBack");
if (pConnection->mMutex.acquire(OsTime(5)) == OS_SUCCESS)
{
// Push data to device driver and forget.
result = pConnection->mpDeviceDriver->pushFrame(
pConnection->mpDeviceDriver->getSamplesPerFrame(),
pConnection->mpMixerBuffer+pConnection->mMixerBufferBegin,
pConnection->mCurrentFrameTime);
debugPrintf("MpAudioOutputConnection::readyForDataCallback()"
" frame=%d, pushFrame result=%d\n",
pConnection->mCurrentFrameTime, result);
// assert(result == OS_SUCCESS);
// Advance mixer buffer and frame time.
pConnection->advanceMixerBuffer(pConnection->mpDeviceDriver->getSamplesPerFrame());
pConnection->mCurrentFrameTime +=
pConnection->mpDeviceDriver->getSamplesPerFrame() * 1000
/ pConnection->mpDeviceDriver->getSamplesPerSec();
RTL_EVENT("MpAudioOutputConnection::tickerCallBack_currentFrameTime",
pConnection->mCurrentFrameTime);
pConnection->mMutex.release();
}
// Signal frame processing interval start if requested.
if (pConnection->mpFlowgraphTicker)
{
pConnection->mpFlowgraphTicker->signal(0);
}
}
/* //////////////////////////// PRIVATE /////////////////////////////////// */
/* ============================ FUNCTIONS ================================= */
<commit_msg>Added compile time conditional logging for output device ticker method invocation and mutex aquisition.<commit_after>//
// Copyright (C) 2007-2016 SIPez LLC. All rights reserved.
//
// Copyright (C) 2007 SIPfoundry Inc.
// Licensed by SIPfoundry under the LGPL license.
//
// $$
///////////////////////////////////////////////////////////////////////////////
// Author: Alexander Chemeris <Alexander DOT Chemeris AT SIPez DOT com>
// SYSTEM INCLUDES
#include <assert.h>
// APPLICATION INCLUDES
#include <mp/MpAudioOutputConnection.h>
#include <mp/MpOutputDeviceDriver.h>
#include <mp/MpDspUtils.h>
#include <os/OsLock.h>
#include <os/OsDefs.h> // for min macro
#include <os/OsSysLog.h>
// milliseconds
//#define LOG_HEART_BEAT_PERIOD 100
//#define RTL_ENABLED
//#define RTL_AUDIO_ENABLED
#ifdef RTL_ENABLED
#include <rtl_macro.h>
#else
#define RTL_BLOCK(x)
#define RTL_EVENT(x,y)
#endif
// EXTERNAL FUNCTIONS
// EXTERNAL VARIABLES
// CONSTANTS
// STATIC VARIABLE INITIALIZATIONS
// PRIVATE CLASSES
// DEFINES
// MACROS
/* //////////////////////////// PUBLIC //////////////////////////////////// */
/* ============================ CREATORS ================================== */
MpAudioOutputConnection::MpAudioOutputConnection(MpOutputDeviceHandle deviceId,
MpOutputDeviceDriver *deviceDriver)
: UtlInt(deviceId)
, mMutex(OsMutexBase::Q_PRIORITY)
, mUseCount(0)
, mpDeviceDriver(deviceDriver)
, mCurrentFrameTime(0)
, mMixerBufferLength(0)
, mpMixerBuffer(NULL)
, mMixerBufferBegin(0)
, readyForDataCallbackNotf((intptr_t)this, readyForDataCallback)
, mpFlowgraphTicker(NULL)
{
assert(mpDeviceDriver != NULL);
};
MpAudioOutputConnection::~MpAudioOutputConnection()
{
}
/* ============================ MANIPULATORS ============================== */
OsStatus MpAudioOutputConnection::enableDevice(unsigned samplesPerFrame,
unsigned samplesPerSec,
MpFrameTime currentFrameTime,
MpFrameTime mixerBufferLength)
{
OsStatus result = OS_FAILED;
OsLock lock(mMutex);
assert(samplesPerFrame > 0);
assert(samplesPerSec > 0);
if (mpDeviceDriver->isEnabled())
{
OsSysLog::add(FAC_MP, PRI_DEBUG,
"MpAudioOutputConnection::enableDevice() device (%s id: %d) already enabled status: %d",
mpDeviceDriver->getDeviceName().data(),
getValue(),
OS_INVALID_STATE);
return(OS_INVALID_STATE);
}
// Mixer buffer length can't be zero.
if (mixerBufferLength == 0)
{
return OS_NOT_SUPPORTED;
}
// Set current frame time for this connection.
mCurrentFrameTime = currentFrameTime;
// Calculate number of samples in mixer buffer.
// I.e. convert from milliseconds to samples and round to frame boundary.
// Note: this calculation may overflow (e.g. 10000msec*44100Hz > 4294967296smp).
unsigned bufferSamples = mixerBufferLength*samplesPerSec/1000;
bufferSamples = ((bufferSamples + samplesPerFrame - 1) / samplesPerFrame)
* samplesPerFrame;
// Initialize mixer buffer. All mixer buffer related variables will be set here.
if (initMixerBuffer(bufferSamples) != OS_SUCCESS)
{
return result;
}
// Enable device driver
result = mpDeviceDriver->enableDevice(samplesPerFrame,
samplesPerSec,
mCurrentFrameTime,
readyForDataCallbackNotf);
return result;
}
OsStatus MpAudioOutputConnection::disableDevice()
{
OsStatus result = OS_FAILED;
OsLock lock(mMutex);
// Disable device and set result code.
result = mpDeviceDriver->disableDevice();
// Free mixer buffer if device was set to disabled state.
if (!mpDeviceDriver->isEnabled())
{
// Do not check return code, as it is not critical if it fails.
freeMixerBuffer();
}
return result;
}
OsStatus MpAudioOutputConnection::enableFlowgraphTicker(OsNotification *pFlowgraphTicker)
{
OsStatus result = OS_SUCCESS;
OsLock lock(mMutex);
assert(mpFlowgraphTicker == NULL);
// Set flowgraph ticker
mpFlowgraphTicker = pFlowgraphTicker;
return result;
}
OsStatus MpAudioOutputConnection::disableFlowgraphTicker()
{
OsStatus result = OS_SUCCESS;
OsLock lock(mMutex);
assert(mpFlowgraphTicker != NULL);
// Clear flowgraph ticker notification
mpFlowgraphTicker = NULL;
return result;
}
OsStatus MpAudioOutputConnection::pushFrameBeginning(unsigned int numSamples,
const MpAudioSample* samples,
MpFrameTime &frameTime)
{
OsStatus result = OS_SUCCESS;
RTL_BLOCK("MpAudioOutputConnection::pushFrame");
assert(numSamples > 0);
// From now we access internal data. Take lock.
OsLock lock(mMutex);
RTL_EVENT("MpAudioOutputConnection::pushFrame_frameTime", frameTime);
RTL_EVENT("MpAudioOutputConnection::pushFrame_currentTime", mCurrentFrameTime);
RTL_EVENT("MpAudioOutputConnection::pushFrame", this->getValue());
// Do nothing if no audio was pushed. Mixer buffer will be filled with
// silence or data from other sources.
if (samples != NULL)
{
// Mix frame to the very beginning of the mixer buffer.
result = mixFrame(mMixerBufferBegin, samples, numSamples);
}
frameTime = mCurrentFrameTime;
return result;
};
OsStatus MpAudioOutputConnection::pushFrame(unsigned int numSamples,
const MpAudioSample* samples,
MpFrameTime frameTime)
{
OsStatus result = OS_SUCCESS;
RTL_EVENT("MpAudioOutputConnection::pushFrame", -1);
assert(numSamples > 0);
// From now we access internal data. Take lock.
OsLock lock(mMutex);
RTL_EVENT("MpAudioOutputConnection::pushFrame_frameTime", frameTime);
RTL_EVENT("MpAudioOutputConnection::pushFrame_currentTime", mCurrentFrameTime);
RTL_EVENT("MpAudioOutputConnection::pushFrame", this->getValue());
// Check for late frame. Check for early frame is done inside mixFrame().
if (MpDspUtils::compareSerials(frameTime, mCurrentFrameTime) < 0)
{
OsSysLog::add(FAC_MP, PRI_WARNING,
"MpAudioOutputConnection::pushFrame()"
" OS_INVALID_STATE frameTime=%d, currentTime=%d\n",
frameTime, mCurrentFrameTime);
result = OS_INVALID_STATE;
RTL_EVENT("MpAudioOutputConnection::pushFrame", result);
return result;
}
if(mpDeviceDriver->isEnabled())
{
// Convert frameTime to offset in mixer buffer.
// Note: frameTime >= mCurrentFrameTime.
unsigned mixerBufferOffsetFrames =
(frameTime-mCurrentFrameTime) / mpDeviceDriver->getFramePeriod();
unsigned mixerBufferOffsetSamples =
mixerBufferOffsetFrames * mpDeviceDriver->getSamplesPerFrame();
// Don't touch mix buffer if no audio was pushed. Mixer buffer will be filled
// with silence or data from other sources.
if (samples != NULL)
{
// Mix this data with other sources.
result = mixFrame(mixerBufferOffsetSamples, samples, numSamples);
if(result != OS_SUCCESS)
{
OsSysLog::add(FAC_MP, PRI_WARNING,
"MpAudioOutputConnection::pushFrame mixFrame(%d, %p, %d) returned: %d"
" frameTime=%d, currentTime=%d\n",
(int)mixerBufferOffsetSamples, samples, numSamples, result,
frameTime, mCurrentFrameTime);
}
}
else
{
// Just check for late frame.
result = isLateToMix(mixerBufferOffsetSamples, numSamples);
}
}
else
{
result = OS_INVALID_STATE;
}
RTL_EVENT("MpAudioOutputConnection::pushFrame", result);
return result;
};
/* ============================ ACCESSORS ================================= */
MpFrameTime MpAudioOutputConnection::getCurrentFrameTime() const
{
OsLock lock(mMutex);
return mCurrentFrameTime;
}
/* ============================ INQUIRY =================================== */
/* //////////////////////////// PROTECTED ///////////////////////////////// */
OsStatus MpAudioOutputConnection::initMixerBuffer(unsigned mixerBufferLength)
{
// We cannot allocate buffer of zero length.
if (mixerBufferLength == 0)
{
return OS_FAILED;
}
// Deallocate mixer buffer if it is allocated.
// Do not check return value. Nothing fatal may happen inside.
freeMixerBuffer();
// Initialize variables.
mMixerBufferLength = mixerBufferLength;
mpMixerBuffer = new MpAudioSample[mMixerBufferLength];
mMixerBufferBegin = 0;
// Clear buffer data.
memset(mpMixerBuffer, 0, mMixerBufferLength*sizeof(MpAudioSample));
return OS_SUCCESS;
}
OsStatus MpAudioOutputConnection::freeMixerBuffer()
{
mMixerBufferLength = 0;
if (mpMixerBuffer != NULL)
{
delete[] mpMixerBuffer;
mpMixerBuffer = NULL;
}
mMixerBufferBegin = 0;
return OS_SUCCESS;
}
OsStatus MpAudioOutputConnection::mixFrame(unsigned frameOffset,
const MpAudioSample* samples,
unsigned numSamples)
{
assert(numSamples > 0);
assert(samples != NULL);
// Check for late frame.
if (isLateToMix(frameOffset, numSamples) == OS_LIMIT_REACHED)
{
OsSysLog::add(FAC_MP, PRI_WARNING,
"MpAudioOutputConnection::mixFrame()"
" OS_LIMIT_REACHED offset=%d, samples=%d, bufferLength=%d\n",
frameOffset, numSamples, mMixerBufferLength);
return OS_LIMIT_REACHED;
}
// Calculate frame start as if buffer is linear
unsigned frameBegin = mMixerBufferBegin+frameOffset;
// and wrap it because it is circular actually.
if (frameBegin >= mMixerBufferLength)
{
frameBegin -= mMixerBufferLength;
}
// Calculate size of first chunk to mix.
unsigned firstChunkSize = sipx_min(numSamples, mMixerBufferLength-frameBegin);
// Counter variables for next two loops
unsigned srcIndex, dstIndex;
// from frame begin to buffer wrap
for (srcIndex=0, dstIndex=frameBegin;
srcIndex<firstChunkSize;
srcIndex++, dstIndex++)
{
mpMixerBuffer[dstIndex] += samples[srcIndex];
}
// from buffer wrap to frame end
for (dstIndex=0;
srcIndex<numSamples;
srcIndex++, dstIndex++)
{
mpMixerBuffer[dstIndex] += samples[srcIndex];
}
return OS_SUCCESS;
}
OsStatus MpAudioOutputConnection::advanceMixerBuffer(unsigned numSamples)
{
// If buffer could be copied in one pass
if(numSamples <= 0)
{
OsSysLog::add(FAC_MP, PRI_ERR, "MpAudioOutputConnection::advanceMixerBuffer invoked with: %d samples\n", numSamples);
assert(numSamples > 0);
}
else if(numSamples > mMixerBufferLength)
{
OsSysLog::add(FAC_MP, PRI_ERR, "MpAudioOutputConnection::advanceMixerBuffer invoked with numSamples: %d > mMixerBufferLength: %d\n",
numSamples, mMixerBufferLength);
assert(numSamples <= mMixerBufferLength);
}
else if (mMixerBufferBegin+numSamples <= mMixerBufferLength)
{
memset(&mpMixerBuffer[mMixerBufferBegin],
0,
numSamples*sizeof(MpAudioSample));
mMixerBufferBegin += numSamples;
mMixerBufferBegin %= mMixerBufferLength;
}
else
{
unsigned firstChunkSize = mMixerBufferLength-mMixerBufferBegin;
memset(&mpMixerBuffer[mMixerBufferBegin],
0,
firstChunkSize*sizeof(MpAudioSample));
memset(&mpMixerBuffer[0],
0,
(numSamples-firstChunkSize)*sizeof(MpAudioSample));
mMixerBufferBegin = numSamples - firstChunkSize;
}
return OS_SUCCESS;
}
void MpAudioOutputConnection::readyForDataCallback(const intptr_t userData,
const intptr_t eventData)
{
OsStatus result;
MpAudioOutputConnection *pConnection = (MpAudioOutputConnection*)userData;
RTL_BLOCK("MpAudioOutputConnection::tickerCallBack");
#ifdef LOG_HEART_BEAT_PERIOD
if(pConnection->mCurrentFrameTime % LOG_HEART_BEAT_PERIOD == 0)
{
OsSysLog::add(FAC_MP, PRI_DEBUG,
"MpAudioOutputConnection::readyForDataCallback aquiring mutex frame time: %d",
pConnection->mCurrentFrameTime);
}
#endif
if (pConnection->mMutex.acquire(OsTime(5)) == OS_SUCCESS)
{
// Push data to device driver and forget.
result = pConnection->mpDeviceDriver->pushFrame(
pConnection->mpDeviceDriver->getSamplesPerFrame(),
pConnection->mpMixerBuffer+pConnection->mMixerBufferBegin,
pConnection->mCurrentFrameTime);
#ifdef LOG_HEART_BEAT_PERIOD
if(pConnection->mCurrentFrameTime % LOG_HEART_BEAT_PERIOD == 0)
{
OsSysLog::add(FAC_MP, PRI_DEBUG,
"MpAudioOutputConnection::readyForDataCallback()"
" frame=%d, pushFrame result=%d\n",
pConnection->mCurrentFrameTime, result);
}
#else
SIPX_UNUSED(result);
#endif
// assert(result == OS_SUCCESS);
// Advance mixer buffer and frame time.
pConnection->advanceMixerBuffer(pConnection->mpDeviceDriver->getSamplesPerFrame());
pConnection->mCurrentFrameTime +=
pConnection->mpDeviceDriver->getSamplesPerFrame() * 1000
/ pConnection->mpDeviceDriver->getSamplesPerSec();
RTL_EVENT("MpAudioOutputConnection::tickerCallBack_currentFrameTime",
pConnection->mCurrentFrameTime);
pConnection->mMutex.release();
}
// Signal frame processing interval start if requested.
if (pConnection->mpFlowgraphTicker)
{
pConnection->mpFlowgraphTicker->signal(0);
}
}
/* //////////////////////////// PRIVATE /////////////////////////////////// */
/* ============================ FUNCTIONS ================================= */
<|endoftext|> |
<commit_before>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: SlideSorterViewShell.hxx,v $
*
* $Revision: 1.10 $
*
* last change: $Author: kz $ $Date: 2006-12-12 17:37: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_SLIDESORTER_SLIDE_SORTER_VIEW_SHELL_HXX
#define SD_SLIDESORTER_SLIDE_SORTER_VIEW_SHELL_HXX
#include "ViewShell.hxx"
#include "SlideSorterViewShell.hxx"
#include "glob.hxx"
#ifndef _SFX_SHELL_HXX
#include <sfx2/shell.hxx>
#endif
#ifndef _VIEWFAC_HXX
#include <sfx2/viewfac.hxx>
#endif
class ScrollBarBox;
class TabBar;
class Window;
namespace sd { namespace slidesorter { namespace model {
class SlideSorterModel;
} } }
namespace sd { namespace slidesorter { namespace view {
class SlideSorterView;
} } }
namespace sd { namespace slidesorter { namespace controller {
class Listener;
class SlideSorterController;
class SlotManager;
} } }
namespace sd { namespace slidesorter {
class SlideSorterViewShell
: public ViewShell
{
friend class controller::SlotManager;
public:
TYPEINFO();
SFX_DECL_INTERFACE(SD_IF_SDSLIDESORTERVIEWSHELL)
enum TabBarEntry
{
TBE_SWITCH = 0,
TBE_SLIDES = 1,
TBE_MASTER_PAGES = 2
};
static SfxShell* CreateInstance (
sal_Int32 nId,
SfxShell* pParent,
void* pUserData,
ViewShellBase& rBase);
SlideSorterViewShell (
SfxViewFrame* pFrame,
ViewShellBase& rViewShellBase,
::Window* pParentWindow,
FrameView* pFrameView);
virtual ~SlideSorterViewShell (void);
/** Late initialization that has to be called after a new instance has
completed its construction.
*/
virtual void Init (bool bIsMainViewShell);
/** Return a slide sorter that is currently displayed in one of the
panes that belong to the given ViewShellBase object.
When there is only one slide sorter visible then that one is
returned. When two (or more) are visible then the one in the center
pane is returned. When no slidesorter is visible then NULL is
returned.
*/
static SlideSorterViewShell* GetSlideSorter (ViewShellBase& rBase);
virtual void GetFocus (void);
virtual void LoseFocus (void);
virtual SdPage* GetActualPage (void);
/// inherited from sd::ViewShell
virtual SdPage* getCurrentPage() const;
void ExecCtrl (SfxRequest& rRequest);
virtual void GetCtrlState (SfxItemSet &rSet);
virtual void FuSupport (SfxRequest& rRequest);
virtual void FuTemporary (SfxRequest& rRequest);
virtual void GetStatusBarState (SfxItemSet& rSet);
virtual void FuPermanent (SfxRequest& rRequest);
void GetAttrState (SfxItemSet& rSet);
void ExecStatusBar (SfxRequest& rRequest);
virtual void Command (const CommandEvent& rEvent, ::sd::Window* pWindow);
virtual void GetMenuState (SfxItemSet &rSet);
virtual void ReadFrameViewData (FrameView* pView);
virtual void WriteFrameViewData (void);
/** Set the zoom factor. The given value is clipped against an upper
bound.
@param nZoom
An integer percent value, i.e. nZoom/100 is the actual zoom
factor.
*/
virtual void SetZoom (long int nZoom);
virtual void SetZoomRect (const Rectangle& rZoomRect);
/** This is a callback method used by the active window to delegate its
Paint() call to. This view shell itself delegates it to the view.
*/
virtual void Paint(const Rectangle& rRect, ::sd::Window* pWin);
/** Place and size the controls and windows. You may want to call this
method when something has changed that for instance affects the
visibility state of the scroll bars.
*/
virtual void ArrangeGUIElements (void);
/** Return the control of the vertical scroll bar.
*/
ScrollBar* GetVerticalScrollBar (void) const;
/** Return the control of the horizontal scroll bar.
*/
ScrollBar* GetHorizontalScrollBar (void) const;
/** Return the scroll bar filler that paints the little square that is
enclosed by the two scroll bars.
*/
ScrollBarBox* GetScrollBarFiller (void) const;
/** Set the tab bar to the given mode.
@param eEntry
When TBE_SWITCH is given, then switch between the two tabs.
*/
TabBarEntry SwitchTabBar (TabBarEntry eEntry);
controller::SlideSorterController& GetSlideSorterController (void);
//===== Drag and Drop =====================================================
virtual void StartDrag (
const Point& rDragPt,
::Window* pWindow );
virtual void DragFinished (
sal_Int8 nDropAction);
virtual sal_Int8 AcceptDrop (
const AcceptDropEvent& rEvt,
DropTargetHelper& rTargetHelper,
::sd::Window* pTargetWindow = NULL,
USHORT nPage = SDRPAGE_NOTFOUND,
USHORT nLayer = SDRPAGE_NOTFOUND );
virtual sal_Int8 ExecuteDrop (
const ExecuteDropEvent& rEvt,
DropTargetHelper& rTargetHelper,
::sd::Window* pTargetWindow = NULL,
USHORT nPage = SDRPAGE_NOTFOUND,
USHORT nLayer = SDRPAGE_NOTFOUND);
/** Return the selected pages by putting them into the given container.
The container does not have to be empty. It is not cleared.
*/
void GetSelectedPages (::std::vector<SdPage*>& pPageContainer);
/** Add a listener that is called when the selection of the slide sorter
changes.
@param rListener
When this method is called multiple times for the same listener
the second and all following calls are ignored. Each listener
is added only once.
*/
void AddSelectionChangeListener (const Link& rListener);
/** Remove a listener that was called when the selection of the slide
sorter changes.
@param rListener
It is save to pass a listener that was not added are has been
removed previously. Such calls are ignored.
*/
void RemoveSelectionChangeListener (const Link& rListener);
virtual ::std::auto_ptr<DrawSubController> CreateSubController (void);
/** Create an accessible object representing the specified window.
@param pWindow
The returned object makes the document displayed in this window
accessible.
@return
Returns an <type>AccessibleSlideSorterView</type> object.
*/
virtual ::com::sun::star::uno::Reference<
::com::sun::star::accessibility::XAccessible>
CreateAccessibleDocumentView (::sd::Window* pWindow);
protected:
::std::auto_ptr<controller::SlideSorterController> mpSlideSorterController;
::std::auto_ptr<model::SlideSorterModel> mpSlideSorterModel;
::std::auto_ptr<view::SlideSorterView> mpSlideSorterView;
virtual SvBorder GetBorder (bool bOuterResize);
/** This virtual method makes it possible to create a specialization of
the slide sorter view shell that works with its own implementation
of model, view, and controller. The default implementation simply
calls the CreateModel(), CreateView(), and CreateController()
methods in this order.
*/
virtual void CreateModelViewController (void);
/** Create the model for the view shell. When called from the default
implementation of CreateModelViewController() then neither view nor
controller do exist. Test their pointers when in doubt.
*/
virtual model::SlideSorterModel* CreateModel (void);
/** Create the view for the view shell. When called from the default
implementation of CreateModelViewController() then the model but not
the controller does exist. Test their pointers when in doubt.
*/
virtual view::SlideSorterView* CreateView (void);
/** Create the controller for the view shell. When called from the default
implementation of CreateModelViewController() then both the view and
the controller do exist. Test their pointers when in doubt.
*/
virtual controller::SlideSorterController* CreateController (void);
/** This method is overloaded to handle a missing tool bar correctly.
This is the case when the slide sorter is not the main view shell.
*/
virtual SfxUndoManager* ImpGetUndoManager (void) const;
private:
::std::auto_ptr<TabBar> mpTabBar;
/** Set this flag to <TRUE/> to force a layout before the next paint.
*/
bool mbLayoutPending;
/** Create the controls for the slide sorter. This are the tab bar
for switching the edit mode, the scroll bar, and the actual
slide sorter view window.
This method is usually called exactly one time from the
constructor.
*/
void SetupControls (::Window* pParentWindow);
/** This method is usually called exactly one time from the
constructor.
*/
void SetupListeners (void);
/** Release the listeners that have been installed in SetupListeners().
*/
void ReleaseListeners (void);
/** This method overwrites the one from our base class: We do our own
scroll bar and the base class call is thus unnecessary. It simply
calls UpdateScrollBars(false).
*/
virtual void UpdateScrollBars (void);
};
} } // end of namespace ::sd::slidesorter
#endif
<commit_msg>INTEGRATION: CWS components1 (1.10.38); FILE MERGED 2007/01/29 17:25:34 af 1.10.38.1: #i68075# New RelocateToParentWindow() method.<commit_after>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: SlideSorterViewShell.hxx,v $
*
* $Revision: 1.11 $
*
* last change: $Author: rt $ $Date: 2007-04-03 16:06: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_SLIDESORTER_SLIDE_SORTER_VIEW_SHELL_HXX
#define SD_SLIDESORTER_SLIDE_SORTER_VIEW_SHELL_HXX
#include "ViewShell.hxx"
#include "SlideSorterViewShell.hxx"
#include "glob.hxx"
#ifndef _SFX_SHELL_HXX
#include <sfx2/shell.hxx>
#endif
#ifndef _VIEWFAC_HXX
#include <sfx2/viewfac.hxx>
#endif
class ScrollBarBox;
class TabBar;
class Window;
namespace sd { namespace slidesorter { namespace model {
class SlideSorterModel;
} } }
namespace sd { namespace slidesorter { namespace view {
class SlideSorterView;
} } }
namespace sd { namespace slidesorter { namespace controller {
class Listener;
class SlideSorterController;
class SlotManager;
} } }
namespace sd { namespace slidesorter {
class SlideSorterViewShell
: public ViewShell
{
friend class controller::SlotManager;
public:
TYPEINFO();
SFX_DECL_INTERFACE(SD_IF_SDSLIDESORTERVIEWSHELL)
enum TabBarEntry
{
TBE_SWITCH = 0,
TBE_SLIDES = 1,
TBE_MASTER_PAGES = 2
};
static SfxShell* CreateInstance (
sal_Int32 nId,
SfxShell* pParent,
void* pUserData,
ViewShellBase& rBase);
SlideSorterViewShell (
SfxViewFrame* pFrame,
ViewShellBase& rViewShellBase,
::Window* pParentWindow,
FrameView* pFrameView);
virtual ~SlideSorterViewShell (void);
/** Late initialization that has to be called after a new instance has
completed its construction.
*/
virtual void Init (bool bIsMainViewShell);
/** Return a slide sorter that is currently displayed in one of the
panes that belong to the given ViewShellBase object.
When there is only one slide sorter visible then that one is
returned. When two (or more) are visible then the one in the center
pane is returned. When no slidesorter is visible then NULL is
returned.
*/
static SlideSorterViewShell* GetSlideSorter (ViewShellBase& rBase);
virtual void GetFocus (void);
virtual void LoseFocus (void);
virtual SdPage* GetActualPage (void);
/// inherited from sd::ViewShell
virtual SdPage* getCurrentPage() const;
void ExecCtrl (SfxRequest& rRequest);
virtual void GetCtrlState (SfxItemSet &rSet);
virtual void FuSupport (SfxRequest& rRequest);
virtual void FuTemporary (SfxRequest& rRequest);
virtual void GetStatusBarState (SfxItemSet& rSet);
virtual void FuPermanent (SfxRequest& rRequest);
void GetAttrState (SfxItemSet& rSet);
void ExecStatusBar (SfxRequest& rRequest);
virtual void Command (const CommandEvent& rEvent, ::sd::Window* pWindow);
virtual void GetMenuState (SfxItemSet &rSet);
virtual void ReadFrameViewData (FrameView* pView);
virtual void WriteFrameViewData (void);
/** Set the zoom factor. The given value is clipped against an upper
bound.
@param nZoom
An integer percent value, i.e. nZoom/100 is the actual zoom
factor.
*/
virtual void SetZoom (long int nZoom);
virtual void SetZoomRect (const Rectangle& rZoomRect);
/** This is a callback method used by the active window to delegate its
Paint() call to. This view shell itself delegates it to the view.
*/
virtual void Paint(const Rectangle& rRect, ::sd::Window* pWin);
/** Place and size the controls and windows. You may want to call this
method when something has changed that for instance affects the
visibility state of the scroll bars.
*/
virtual void ArrangeGUIElements (void);
/** Return the control of the vertical scroll bar.
*/
ScrollBar* GetVerticalScrollBar (void) const;
/** Return the control of the horizontal scroll bar.
*/
ScrollBar* GetHorizontalScrollBar (void) const;
/** Return the scroll bar filler that paints the little square that is
enclosed by the two scroll bars.
*/
ScrollBarBox* GetScrollBarFiller (void) const;
/** Set the tab bar to the given mode.
@param eEntry
When TBE_SWITCH is given, then switch between the two tabs.
*/
TabBarEntry SwitchTabBar (TabBarEntry eEntry);
controller::SlideSorterController& GetSlideSorterController (void);
//===== Drag and Drop =====================================================
virtual void StartDrag (
const Point& rDragPt,
::Window* pWindow );
virtual void DragFinished (
sal_Int8 nDropAction);
virtual sal_Int8 AcceptDrop (
const AcceptDropEvent& rEvt,
DropTargetHelper& rTargetHelper,
::sd::Window* pTargetWindow = NULL,
USHORT nPage = SDRPAGE_NOTFOUND,
USHORT nLayer = SDRPAGE_NOTFOUND );
virtual sal_Int8 ExecuteDrop (
const ExecuteDropEvent& rEvt,
DropTargetHelper& rTargetHelper,
::sd::Window* pTargetWindow = NULL,
USHORT nPage = SDRPAGE_NOTFOUND,
USHORT nLayer = SDRPAGE_NOTFOUND);
/** Return the selected pages by putting them into the given container.
The container does not have to be empty. It is not cleared.
*/
void GetSelectedPages (::std::vector<SdPage*>& pPageContainer);
/** Add a listener that is called when the selection of the slide sorter
changes.
@param rListener
When this method is called multiple times for the same listener
the second and all following calls are ignored. Each listener
is added only once.
*/
void AddSelectionChangeListener (const Link& rListener);
/** Remove a listener that was called when the selection of the slide
sorter changes.
@param rListener
It is save to pass a listener that was not added are has been
removed previously. Such calls are ignored.
*/
void RemoveSelectionChangeListener (const Link& rListener);
virtual ::std::auto_ptr<DrawSubController> CreateSubController (void);
/** Create an accessible object representing the specified window.
@param pWindow
The returned object makes the document displayed in this window
accessible.
@return
Returns an <type>AccessibleSlideSorterView</type> object.
*/
virtual ::com::sun::star::uno::Reference<
::com::sun::star::accessibility::XAccessible>
CreateAccessibleDocumentView (::sd::Window* pWindow);
/** Try to relocate all toplevel window elements to the given parent
window.
*/
virtual bool RelocateToParentWindow (::Window* pParentWindow);
protected:
::std::auto_ptr<controller::SlideSorterController> mpSlideSorterController;
::std::auto_ptr<model::SlideSorterModel> mpSlideSorterModel;
::std::auto_ptr<view::SlideSorterView> mpSlideSorterView;
virtual SvBorder GetBorder (bool bOuterResize);
/** This virtual method makes it possible to create a specialization of
the slide sorter view shell that works with its own implementation
of model, view, and controller. The default implementation simply
calls the CreateModel(), CreateView(), and CreateController()
methods in this order.
*/
virtual void CreateModelViewController (void);
/** Create the model for the view shell. When called from the default
implementation of CreateModelViewController() then neither view nor
controller do exist. Test their pointers when in doubt.
*/
virtual model::SlideSorterModel* CreateModel (void);
/** Create the view for the view shell. When called from the default
implementation of CreateModelViewController() then the model but not
the controller does exist. Test their pointers when in doubt.
*/
virtual view::SlideSorterView* CreateView (void);
/** Create the controller for the view shell. When called from the default
implementation of CreateModelViewController() then both the view and
the controller do exist. Test their pointers when in doubt.
*/
virtual controller::SlideSorterController* CreateController (void);
/** This method is overloaded to handle a missing tool bar correctly.
This is the case when the slide sorter is not the main view shell.
*/
virtual SfxUndoManager* ImpGetUndoManager (void) const;
private:
::std::auto_ptr<TabBar> mpTabBar;
/** Set this flag to <TRUE/> to force a layout before the next paint.
*/
bool mbLayoutPending;
/** Create the controls for the slide sorter. This are the tab bar
for switching the edit mode, the scroll bar, and the actual
slide sorter view window.
This method is usually called exactly one time from the
constructor.
*/
void SetupControls (::Window* pParentWindow);
/** This method is usually called exactly one time from the
constructor.
*/
void SetupListeners (void);
/** Release the listeners that have been installed in SetupListeners().
*/
void ReleaseListeners (void);
/** This method overwrites the one from our base class: We do our own
scroll bar and the base class call is thus unnecessary. It simply
calls UpdateScrollBars(false).
*/
virtual void UpdateScrollBars (void);
};
} } // end of namespace ::sd::slidesorter
#endif
<|endoftext|> |
<commit_before>/*
For more information, please see: http://software.sci.utah.edu
The MIT License
Copyright (c) 2008 Scientific Computing and Imaging Institute,
University of Utah.
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.
*/
/**
\file SystemInfo.cpp
\author Jens Krueger
SCI Institute
University of Utah
\date July 2008
*/
#include "SystemInfo.h"
#include "StdDefines.h"
#ifdef _WIN32
#include <windows.h>
#else
#ifdef TUVOK_OS_APPLE
#include <sys/sysctl.h>
#else
#include <cstdio>
#include <iostream>
#include <sstream>
#include <sys/resource.h>
#include <sys/sysinfo.h>
#include <sys/time.h>
#include "IO/KeyValueFileParser.h"
#endif
#endif
SystemInfo::SystemInfo(UINT64 iDefaultCPUMemSize, UINT64 iDefaultGPUMemSize) :
m_iProgrammBitWith(sizeof(void*)*8),
m_iUseMaxCPUMem(iDefaultCPUMemSize),
m_iUseMaxGPUMem(iDefaultGPUMemSize),
m_iCPUMemSize(iDefaultCPUMemSize),
m_iGPUMemSize(iDefaultGPUMemSize),
m_bIsCPUSizeComputed(false),
m_bIsGPUSizeComputed(false),
m_bIsNumberOfCPUsComputed(false),
m_bIsDirectX10Capable(false)
{
UINT32 iNumberOfCPUs = ComputeNumCPUs();
if (iNumberOfCPUs > 0) {
m_iNumberOfCPUs = iNumberOfCPUs;
m_bIsNumberOfCPUsComputed = true;
}
UINT64 iCPUMemSize = ComputeCPUMemSize();
if (iCPUMemSize > 0) {
m_iCPUMemSize = iCPUMemSize;
m_bIsCPUSizeComputed = true;
}
UINT64 iGPUMemSize = ComputeGPUMemory(); // also sets m_bIsDirectX10Capable
if (iGPUMemSize > 0) {
m_iGPUMemSize = iGPUMemSize;
m_bIsGPUSizeComputed = true;
}
}
UINT32 SystemInfo::ComputeNumCPUs() {
#ifdef _WIN32
SYSTEM_INFO siSysInfo;
GetSystemInfo(&siSysInfo);
return siSysInfo.dwNumberOfProcessors;
#else
#ifdef TUVOK_OS_APPLE
return 0;
#else
return 0;
#endif
#endif
}
#ifdef __linux__
#ifndef NDEBUG
# define DBG(str) do { std::cerr << str << std::endl; } while(0)
#else
# define DBG(str) /* nothing */
#endif
static unsigned long lnx_mem_sysinfo() {
struct sysinfo si;
if(sysinfo(&si) < 0) {
perror("sysinfo");
return 0;
}
return si.totalram;
}
static UINT64 lnx_mem_rlimit() {
struct rlimit limit;
// RLIMIT_MEMLOCK returns 32768 (that's *bytes*) on my 6gb-RAM system, so
// that number is worthless to us.
// RLIMIT_DATA isn't great, because it gets the entire data segment size
// allowable, not just the heap size ...
if(getrlimit(RLIMIT_DATA, &limit) != 0) {
perror("getrlimit");
return 0;
}
// Frequently the information given by getrlimit(2) is essentially
// worthless, because it assumes we don't care about swapping.
if(limit.rlim_cur == RLIM_INFINITY || limit.rlim_max == RLIM_INFINITY) {
DBG("getrlimit gave useless info...");
return 0;
}
return limit.rlim_max;
}
static UINT64 lnx_mem_proc() {
KeyValueFileParser meminfo("/proc/meminfo");
if(!meminfo.FileReadable()) {
DBG("could not open proc memory filesystem");
return 0;
}
KeyValPair *mem_total = meminfo.GetData("MemTotal");
if(mem_total == NULL) {
DBG("proc mem fs did not have a `MemTotal' entry.");
return 0;
}
std::istringstream mem_strm(mem_total->strValue);
UINT64 mem;
mem_strm >> mem;
return mem * 1024;
}
static UINT64 lnx_mem() {
UINT64 m;
if((m = lnx_mem_proc()) == 0) {
DBG("proc failed, falling back to rlimit");
if((m = lnx_mem_rlimit()) == 0) {
DBG("rlimit failed, falling back to sysinfo");
if((m = lnx_mem_sysinfo()) == 0) {
DBG("all memory lookups failed; pretending you have 1Gb of memory.");
return 1024*1024*1024;
}
}
}
return m;
}
#endif
UINT64 SystemInfo::ComputeCPUMemSize() {
#ifdef _WIN32
MEMORYSTATUSEX statex;
statex.dwLength = sizeof (statex);
GlobalMemoryStatusEx (&statex);
return statex.ullTotalPhys;
#else
#ifdef TUVOK_OS_APPLE
UINT64 phys = 0;
int mib[2] = { CTL_HW, HW_PHYSMEM };
size_t len = sizeof(phys);
if (sysctl(mib, 2, &phys, &len, NULL, 0) != 0) return 0;
return phys;
#elif defined(__linux__)
return static_cast<UINT64>(lnx_mem());
#else
std::cerr << "Unknown system, can't lookup max memory. "
<< "Using a hard setting of 10 gb." << std::endl;
return 1024*1024*1024*10;
#endif
#endif
}
#if defined(_WIN32) && defined(USE_DIRECTX)
#define INITGUID
#include <string.h>
#include <stdio.h>
#include <assert.h>
#include <d3d9.h>
#include <multimon.h>
#pragma comment( lib, "d3d9.lib" )
HRESULT GetVideoMemoryViaDirectDraw( HMONITOR hMonitor, DWORD* pdwAvailableVidMem );
HRESULT GetVideoMemoryViaDXGI( HMONITOR hMonitor, SIZE_T* pDedicatedVideoMemory, SIZE_T* pDedicatedSystemMemory, SIZE_T* pSharedSystemMemory );
#ifndef SAFE_RELEASE
#define SAFE_RELEASE(p) { if (p) { (p)->Release(); (p)=NULL; } }
#endif
typedef IDirect3D9* ( WINAPI* LPDIRECT3DCREATE9 )( UINT );
LPDIRECT3DCREATE9 pDirect3DCreate9;
UINT64 SystemInfo::ComputeGPUMemory( )
{
HINSTANCE hD3D9 = LoadLibrary( L"d3d9.dll" );
if (!hD3D9) return 0;
pDirect3DCreate9 = ( LPDIRECT3DCREATE9 )GetProcAddress( hD3D9, "Direct3DCreate9" );
if (!pDirect3DCreate9) {
FreeLibrary( hD3D9 );
return 0;
}
IDirect3D9* pD3D9 = NULL;
pD3D9 = pDirect3DCreate9( D3D_SDK_VERSION );
if( pD3D9 )
{
UINT dwAdapterCount = pD3D9->GetAdapterCount();
if (dwAdapterCount > 0) {
UINT iAdapter = 0;
HMONITOR hMonitor = pD3D9->GetAdapterMonitor( iAdapter );
SIZE_T DedicatedVideoMemory;
SIZE_T DedicatedSystemMemory;
SIZE_T SharedSystemMemory;
if( SUCCEEDED( GetVideoMemoryViaDXGI( hMonitor, &DedicatedVideoMemory, &DedicatedSystemMemory, &SharedSystemMemory ) ) )
{
m_bIsDirectX10Capable = true;
SAFE_RELEASE( pD3D9 );
return UINT64(DedicatedVideoMemory);
} else {
DWORD dwAvailableVidMem;
if( SUCCEEDED( GetVideoMemoryViaDirectDraw( hMonitor, &dwAvailableVidMem ) ) ) {
SAFE_RELEASE( pD3D9 );
FreeLibrary( hD3D9 );
return UINT64(DedicatedVideoMemory);
} else {
SAFE_RELEASE( pD3D9 );
FreeLibrary( hD3D9 );
return 0;
}
}
}
SAFE_RELEASE( pD3D9 );
FreeLibrary( hD3D9 );
return 0;
}
else
{
FreeLibrary( hD3D9 );
return 0;
}
}
#else
UINT64 SystemInfo::ComputeGPUMemory( )
{
#ifdef TUVOK_OS_APPLE
return 0;
#else // Linux
return 0;
#endif
}
#endif
<commit_msg>Fix the include, and thus the build.<commit_after>/*
For more information, please see: http://software.sci.utah.edu
The MIT License
Copyright (c) 2008 Scientific Computing and Imaging Institute,
University of Utah.
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.
*/
/**
\file SystemInfo.cpp
\author Jens Krueger
SCI Institute
University of Utah
\date July 2008
*/
#include "SystemInfo.h"
#include "StdTuvokDefines.h"
#ifdef _WIN32
#include <windows.h>
#else
#ifdef TUVOK_OS_APPLE
#include <sys/sysctl.h>
#else
#include <cstdio>
#include <iostream>
#include <sstream>
#include <sys/resource.h>
#include <sys/sysinfo.h>
#include <sys/time.h>
#include "IO/KeyValueFileParser.h"
#endif
#endif
SystemInfo::SystemInfo(UINT64 iDefaultCPUMemSize, UINT64 iDefaultGPUMemSize) :
m_iProgrammBitWith(sizeof(void*)*8),
m_iUseMaxCPUMem(iDefaultCPUMemSize),
m_iUseMaxGPUMem(iDefaultGPUMemSize),
m_iCPUMemSize(iDefaultCPUMemSize),
m_iGPUMemSize(iDefaultGPUMemSize),
m_bIsCPUSizeComputed(false),
m_bIsGPUSizeComputed(false),
m_bIsNumberOfCPUsComputed(false),
m_bIsDirectX10Capable(false)
{
UINT32 iNumberOfCPUs = ComputeNumCPUs();
if (iNumberOfCPUs > 0) {
m_iNumberOfCPUs = iNumberOfCPUs;
m_bIsNumberOfCPUsComputed = true;
}
UINT64 iCPUMemSize = ComputeCPUMemSize();
if (iCPUMemSize > 0) {
m_iCPUMemSize = iCPUMemSize;
m_bIsCPUSizeComputed = true;
}
UINT64 iGPUMemSize = ComputeGPUMemory(); // also sets m_bIsDirectX10Capable
if (iGPUMemSize > 0) {
m_iGPUMemSize = iGPUMemSize;
m_bIsGPUSizeComputed = true;
}
}
UINT32 SystemInfo::ComputeNumCPUs() {
#ifdef _WIN32
SYSTEM_INFO siSysInfo;
GetSystemInfo(&siSysInfo);
return siSysInfo.dwNumberOfProcessors;
#else
#ifdef TUVOK_OS_APPLE
return 0;
#else
return 0;
#endif
#endif
}
#ifdef __linux__
#ifndef NDEBUG
# define DBG(str) do { std::cerr << str << std::endl; } while(0)
#else
# define DBG(str) /* nothing */
#endif
static unsigned long lnx_mem_sysinfo() {
struct sysinfo si;
if(sysinfo(&si) < 0) {
perror("sysinfo");
return 0;
}
return si.totalram;
}
static UINT64 lnx_mem_rlimit() {
struct rlimit limit;
// RLIMIT_MEMLOCK returns 32768 (that's *bytes*) on my 6gb-RAM system, so
// that number is worthless to us.
// RLIMIT_DATA isn't great, because it gets the entire data segment size
// allowable, not just the heap size ...
if(getrlimit(RLIMIT_DATA, &limit) != 0) {
perror("getrlimit");
return 0;
}
// Frequently the information given by getrlimit(2) is essentially
// worthless, because it assumes we don't care about swapping.
if(limit.rlim_cur == RLIM_INFINITY || limit.rlim_max == RLIM_INFINITY) {
DBG("getrlimit gave useless info...");
return 0;
}
return limit.rlim_max;
}
static UINT64 lnx_mem_proc() {
KeyValueFileParser meminfo("/proc/meminfo");
if(!meminfo.FileReadable()) {
DBG("could not open proc memory filesystem");
return 0;
}
KeyValPair *mem_total = meminfo.GetData("MemTotal");
if(mem_total == NULL) {
DBG("proc mem fs did not have a `MemTotal' entry.");
return 0;
}
std::istringstream mem_strm(mem_total->strValue);
UINT64 mem;
mem_strm >> mem;
return mem * 1024;
}
static UINT64 lnx_mem() {
UINT64 m;
if((m = lnx_mem_proc()) == 0) {
DBG("proc failed, falling back to rlimit");
if((m = lnx_mem_rlimit()) == 0) {
DBG("rlimit failed, falling back to sysinfo");
if((m = lnx_mem_sysinfo()) == 0) {
DBG("all memory lookups failed; pretending you have 1Gb of memory.");
return 1024*1024*1024;
}
}
}
return m;
}
#endif
UINT64 SystemInfo::ComputeCPUMemSize() {
#ifdef _WIN32
MEMORYSTATUSEX statex;
statex.dwLength = sizeof (statex);
GlobalMemoryStatusEx (&statex);
return statex.ullTotalPhys;
#else
#ifdef TUVOK_OS_APPLE
UINT64 phys = 0;
int mib[2] = { CTL_HW, HW_PHYSMEM };
size_t len = sizeof(phys);
if (sysctl(mib, 2, &phys, &len, NULL, 0) != 0) return 0;
return phys;
#elif defined(__linux__)
return static_cast<UINT64>(lnx_mem());
#else
std::cerr << "Unknown system, can't lookup max memory. "
<< "Using a hard setting of 10 gb." << std::endl;
return 1024*1024*1024*10;
#endif
#endif
}
#if defined(_WIN32) && defined(USE_DIRECTX)
#define INITGUID
#include <string.h>
#include <stdio.h>
#include <assert.h>
#include <d3d9.h>
#include <multimon.h>
#pragma comment( lib, "d3d9.lib" )
HRESULT GetVideoMemoryViaDirectDraw( HMONITOR hMonitor, DWORD* pdwAvailableVidMem );
HRESULT GetVideoMemoryViaDXGI( HMONITOR hMonitor, SIZE_T* pDedicatedVideoMemory, SIZE_T* pDedicatedSystemMemory, SIZE_T* pSharedSystemMemory );
#ifndef SAFE_RELEASE
#define SAFE_RELEASE(p) { if (p) { (p)->Release(); (p)=NULL; } }
#endif
typedef IDirect3D9* ( WINAPI* LPDIRECT3DCREATE9 )( UINT );
LPDIRECT3DCREATE9 pDirect3DCreate9;
UINT64 SystemInfo::ComputeGPUMemory( )
{
HINSTANCE hD3D9 = LoadLibrary( L"d3d9.dll" );
if (!hD3D9) return 0;
pDirect3DCreate9 = ( LPDIRECT3DCREATE9 )GetProcAddress( hD3D9, "Direct3DCreate9" );
if (!pDirect3DCreate9) {
FreeLibrary( hD3D9 );
return 0;
}
IDirect3D9* pD3D9 = NULL;
pD3D9 = pDirect3DCreate9( D3D_SDK_VERSION );
if( pD3D9 )
{
UINT dwAdapterCount = pD3D9->GetAdapterCount();
if (dwAdapterCount > 0) {
UINT iAdapter = 0;
HMONITOR hMonitor = pD3D9->GetAdapterMonitor( iAdapter );
SIZE_T DedicatedVideoMemory;
SIZE_T DedicatedSystemMemory;
SIZE_T SharedSystemMemory;
if( SUCCEEDED( GetVideoMemoryViaDXGI( hMonitor, &DedicatedVideoMemory, &DedicatedSystemMemory, &SharedSystemMemory ) ) )
{
m_bIsDirectX10Capable = true;
SAFE_RELEASE( pD3D9 );
return UINT64(DedicatedVideoMemory);
} else {
DWORD dwAvailableVidMem;
if( SUCCEEDED( GetVideoMemoryViaDirectDraw( hMonitor, &dwAvailableVidMem ) ) ) {
SAFE_RELEASE( pD3D9 );
FreeLibrary( hD3D9 );
return UINT64(DedicatedVideoMemory);
} else {
SAFE_RELEASE( pD3D9 );
FreeLibrary( hD3D9 );
return 0;
}
}
}
SAFE_RELEASE( pD3D9 );
FreeLibrary( hD3D9 );
return 0;
}
else
{
FreeLibrary( hD3D9 );
return 0;
}
}
#else
UINT64 SystemInfo::ComputeGPUMemory( )
{
#ifdef TUVOK_OS_APPLE
return 0;
#else // Linux
return 0;
#endif
}
#endif
<|endoftext|> |
<commit_before>#include "bvs/bvs.h"
#include "bvs/traits.h"
#include "control.h"
#include "loader.h"
#ifdef BVS_LOG_SYSTEM
#include "logsystem.h"
#endif
BVS::BVS::BVS(int argc, char** argv, std::function<void()>shutdownHandler)
: config{"bvs", argc, argv},
shutdownHandler(shutdownHandler),
info(Info{config, 0, {}, {}}),
#ifdef BVS_LOG_SYSTEM
logSystem{LogSystem::connectToLogSystem()},
logger{"BVS"},
#endif
loader{new Loader{info}},
control{new Control{loader->modules, *this, info}},
moduleStack{}
{
#ifdef BVS_LOG_SYSTEM
logSystem->updateSettings(config);
logSystem->updateLoggerLevels(config);
#endif
}
BVS::BVS::~BVS()
{
delete control;
delete loader;
}
BVS::BVS& BVS::BVS::loadModules()
{
// get module list from config
std::vector<std::string> moduleList;
config.getValue("BVS.modules", moduleList);
std::string poolName;
// check length
if (moduleList.size()==0)
{
LOG(1, "No modules specified, nothing to load!");
return *this;
}
// load all selected modules
bool asThread;
for (auto& it : moduleList)
{
asThread = false;
poolName.clear();
// check for thread selection ('+' prefix) and system settings
if (it[0]=='+')
{
it.erase(0, 1);
if (it[0]=='[')
{
LOG(0, "Cannot start module in thread AND pool!");
exit(1);
}
asThread = true;
}
if (it[0]=='[')
{
size_t pos = it.find_first_of(']');
poolName = it.substr(1, pos-1);
it.erase(0, pos+1);
}
loadModule(it , asThread, poolName);
}
return *this;
}
BVS::BVS& BVS::BVS::loadModule(const std::string& moduleTraits, bool asThread, std::string poolName)
{
std::string id;
std::string library;
std::string configuration;
std::string options;
// adapt to module thread/pools settings
bool moduleThreads = config.getValue<bool>("BVS.moduleThreads", bvs_module_threads);
bool forceModuleThreads = config.getValue<bool>("BVS.forceModuleThreads", bvs_module_force_threads);
bool modulePools = config.getValue<bool>("BVS.modulePools", bvs_module_pools);
if (forceModuleThreads) asThread = true;
if (!moduleThreads) asThread = false;
if (!modulePools) poolName.clear();
// separate id, library, configuration and options
size_t separator = moduleTraits.find_first_of(".()");
if (separator==std::string::npos) id = moduleTraits;
else if (moduleTraits.at(separator)=='.')
{
id = moduleTraits.substr(0, separator);
options = moduleTraits.substr(separator+1, std::string::npos);
}
else if (moduleTraits.at(separator)=='(')
{
size_t dot = moduleTraits.find_first_of('.');
size_t rp = moduleTraits.find_first_of(')');
id = moduleTraits.substr(0, separator);
library = moduleTraits.substr(separator+1, rp-separator-1);
options = moduleTraits.substr(rp+2<moduleTraits.size()?rp+2:rp+1, std::string::npos);
if (dot<rp)
{
library = moduleTraits.substr(separator+1, dot-separator-1);
configuration = moduleTraits.substr(dot+1, rp-dot-1);
}
}
if (library.empty()) library = id;
if (configuration.empty()) configuration = id;
// load
loader->load(id, library, configuration, options, asThread, poolName);
control->startModule(id);
moduleStack.push(id);
return *this;
}
BVS::BVS& BVS::BVS::unloadModules()
{
while (!moduleStack.empty())
{
if(loader->modules.find(moduleStack.top())!=loader->modules.end())
{
unloadModule(moduleStack.top());
}
moduleStack.pop();
}
return *this;
}
BVS::BVS& BVS::BVS::unloadModule(const std::string& id)
{
SystemFlag state = control->queryActiveFlag();
if (state!=SystemFlag::QUIT)
{
control->sendCommand(SystemFlag::PAUSE);
control->waitUntilInactive(id);
}
control->purgeData(id);
control->quitModule(id);
loader->unload(id);
if (state!=SystemFlag::QUIT) control->sendCommand(state);
return *this;
}
BVS::BVS& BVS::BVS::loadConfigFile(const std::string& configFile)
{
config.loadConfigFile(configFile);
#ifdef BVS_LOG_SYSTEM
logSystem->updateSettings(config);
logSystem->updateLoggerLevels(config);
#endif
return *this;
}
BVS::BVS& BVS::BVS::setLogSystemVerbosity(const unsigned short verbosity)
{
#ifdef BVS_LOG_SYSTEM
if (logSystem) logSystem->setSystemVerbosity(verbosity);
#else
(void) verbosity;
#endif
return *this;
}
BVS::BVS& BVS::BVS::enableLogFile(const std::string& file, bool append)
{
#ifdef BVS_LOG_SYSTEM
if (logSystem) logSystem->enableLogFile(file, append);
#else
(void) file;
(void) append;
#endif
return *this;
}
BVS::BVS& BVS::BVS::disableLogFile()
{
#ifdef BVS_LOG_SYSTEM
if (logSystem) logSystem->disableLogFile();
#endif
return *this;
}
BVS::BVS& BVS::BVS::enableLogConsole(const std::ostream& out)
{
#ifdef BVS_LOG_SYSTEM
if (logSystem) logSystem->enableLogConsole(out);
#else
(void) out;
#endif
return *this;
}
BVS::BVS& BVS::BVS::disableLogConsole()
{
#ifdef BVS_LOG_SYSTEM
if (logSystem) logSystem->disableLogConsole();
#endif
return *this;
}
BVS::BVS& BVS::BVS::connectAllModules()
{
loader->connectAllModules();
return *this;
}
BVS::BVS& BVS::BVS::connectModule(const std::string id)
{
loader->connectModule(id, config.getValue<bool>("BVS.connectorTypeMatching", bvs_connector_type_matching));
return *this;
}
BVS::BVS& BVS::BVS::start(bool forkMasterController)
{
control->masterController(forkMasterController);
return *this;
}
BVS::BVS& BVS::BVS::run()
{
control->sendCommand(SystemFlag::RUN);
return *this;
}
BVS::BVS& BVS::BVS::step()
{
control->sendCommand(SystemFlag::STEP);
return *this;
}
BVS::BVS& BVS::BVS::pause()
{
control->sendCommand(SystemFlag::PAUSE);
return *this;
}
BVS::BVS& BVS::BVS::hotSwap(const std::string& id)
{
#ifdef BVS_MODULE_HOTSWAP
if (control->modules.find(id)!=control->modules.end())
{
SystemFlag state = control->queryActiveFlag();
control->sendCommand(SystemFlag::PAUSE);
control->waitUntilInactive(id);
loader->hotSwapModule(id);
control->sendCommand(state);
}
else
{
LOG(0, "'" << id << "' not found!");
}
#else //BVS_MODULE_HOTSWAP
LOG(0, "ERROR: HotSwap disabled, could not hotswap: '" << id << "'!");
#endif //BVS_MODULE_HOTSWAP
return *this;
}
BVS::BVS& BVS::BVS::quit()
{
control->sendCommand(SystemFlag::QUIT);
unloadModules();
return *this;
}
<commit_msg>bvs: always wait for running instances<commit_after>#include "bvs/bvs.h"
#include "bvs/traits.h"
#include "control.h"
#include "loader.h"
#ifdef BVS_LOG_SYSTEM
#include "logsystem.h"
#endif
BVS::BVS::BVS(int argc, char** argv, std::function<void()>shutdownHandler)
: config{"bvs", argc, argv},
shutdownHandler(shutdownHandler),
info(Info{config, 0, {}, {}}),
#ifdef BVS_LOG_SYSTEM
logSystem{LogSystem::connectToLogSystem()},
logger{"BVS"},
#endif
loader{new Loader{info}},
control{new Control{loader->modules, *this, info}},
moduleStack{}
{
#ifdef BVS_LOG_SYSTEM
logSystem->updateSettings(config);
logSystem->updateLoggerLevels(config);
#endif
}
BVS::BVS::~BVS()
{
delete control;
delete loader;
}
BVS::BVS& BVS::BVS::loadModules()
{
// get module list from config
std::vector<std::string> moduleList;
config.getValue("BVS.modules", moduleList);
std::string poolName;
// check length
if (moduleList.size()==0)
{
LOG(1, "No modules specified, nothing to load!");
return *this;
}
// load all selected modules
bool asThread;
for (auto& it : moduleList)
{
asThread = false;
poolName.clear();
// check for thread selection ('+' prefix) and system settings
if (it[0]=='+')
{
it.erase(0, 1);
if (it[0]=='[')
{
LOG(0, "Cannot start module in thread AND pool!");
exit(1);
}
asThread = true;
}
if (it[0]=='[')
{
size_t pos = it.find_first_of(']');
poolName = it.substr(1, pos-1);
it.erase(0, pos+1);
}
loadModule(it , asThread, poolName);
}
return *this;
}
BVS::BVS& BVS::BVS::loadModule(const std::string& moduleTraits, bool asThread, std::string poolName)
{
std::string id;
std::string library;
std::string configuration;
std::string options;
// adapt to module thread/pools settings
bool moduleThreads = config.getValue<bool>("BVS.moduleThreads", bvs_module_threads);
bool forceModuleThreads = config.getValue<bool>("BVS.forceModuleThreads", bvs_module_force_threads);
bool modulePools = config.getValue<bool>("BVS.modulePools", bvs_module_pools);
if (forceModuleThreads) asThread = true;
if (!moduleThreads) asThread = false;
if (!modulePools) poolName.clear();
// separate id, library, configuration and options
size_t separator = moduleTraits.find_first_of(".()");
if (separator==std::string::npos) id = moduleTraits;
else if (moduleTraits.at(separator)=='.')
{
id = moduleTraits.substr(0, separator);
options = moduleTraits.substr(separator+1, std::string::npos);
}
else if (moduleTraits.at(separator)=='(')
{
size_t dot = moduleTraits.find_first_of('.');
size_t rp = moduleTraits.find_first_of(')');
id = moduleTraits.substr(0, separator);
library = moduleTraits.substr(separator+1, rp-separator-1);
options = moduleTraits.substr(rp+2<moduleTraits.size()?rp+2:rp+1, std::string::npos);
if (dot<rp)
{
library = moduleTraits.substr(separator+1, dot-separator-1);
configuration = moduleTraits.substr(dot+1, rp-dot-1);
}
}
if (library.empty()) library = id;
if (configuration.empty()) configuration = id;
// load
loader->load(id, library, configuration, options, asThread, poolName);
control->startModule(id);
moduleStack.push(id);
return *this;
}
BVS::BVS& BVS::BVS::unloadModules()
{
while (!moduleStack.empty())
{
if(loader->modules.find(moduleStack.top())!=loader->modules.end())
{
unloadModule(moduleStack.top());
}
moduleStack.pop();
}
return *this;
}
BVS::BVS& BVS::BVS::unloadModule(const std::string& id)
{
SystemFlag state = control->queryActiveFlag();
if (state!=SystemFlag::QUIT) control->sendCommand(SystemFlag::PAUSE);
control->waitUntilInactive(id);
control->purgeData(id);
control->quitModule(id);
loader->unload(id);
if (state!=SystemFlag::QUIT) control->sendCommand(state);
return *this;
}
BVS::BVS& BVS::BVS::loadConfigFile(const std::string& configFile)
{
config.loadConfigFile(configFile);
#ifdef BVS_LOG_SYSTEM
logSystem->updateSettings(config);
logSystem->updateLoggerLevels(config);
#endif
return *this;
}
BVS::BVS& BVS::BVS::setLogSystemVerbosity(const unsigned short verbosity)
{
#ifdef BVS_LOG_SYSTEM
if (logSystem) logSystem->setSystemVerbosity(verbosity);
#else
(void) verbosity;
#endif
return *this;
}
BVS::BVS& BVS::BVS::enableLogFile(const std::string& file, bool append)
{
#ifdef BVS_LOG_SYSTEM
if (logSystem) logSystem->enableLogFile(file, append);
#else
(void) file;
(void) append;
#endif
return *this;
}
BVS::BVS& BVS::BVS::disableLogFile()
{
#ifdef BVS_LOG_SYSTEM
if (logSystem) logSystem->disableLogFile();
#endif
return *this;
}
BVS::BVS& BVS::BVS::enableLogConsole(const std::ostream& out)
{
#ifdef BVS_LOG_SYSTEM
if (logSystem) logSystem->enableLogConsole(out);
#else
(void) out;
#endif
return *this;
}
BVS::BVS& BVS::BVS::disableLogConsole()
{
#ifdef BVS_LOG_SYSTEM
if (logSystem) logSystem->disableLogConsole();
#endif
return *this;
}
BVS::BVS& BVS::BVS::connectAllModules()
{
loader->connectAllModules();
return *this;
}
BVS::BVS& BVS::BVS::connectModule(const std::string id)
{
loader->connectModule(id, config.getValue<bool>("BVS.connectorTypeMatching", bvs_connector_type_matching));
return *this;
}
BVS::BVS& BVS::BVS::start(bool forkMasterController)
{
control->masterController(forkMasterController);
return *this;
}
BVS::BVS& BVS::BVS::run()
{
control->sendCommand(SystemFlag::RUN);
return *this;
}
BVS::BVS& BVS::BVS::step()
{
control->sendCommand(SystemFlag::STEP);
return *this;
}
BVS::BVS& BVS::BVS::pause()
{
control->sendCommand(SystemFlag::PAUSE);
return *this;
}
BVS::BVS& BVS::BVS::hotSwap(const std::string& id)
{
#ifdef BVS_MODULE_HOTSWAP
if (control->modules.find(id)!=control->modules.end())
{
SystemFlag state = control->queryActiveFlag();
control->sendCommand(SystemFlag::PAUSE);
control->waitUntilInactive(id);
loader->hotSwapModule(id);
control->sendCommand(state);
}
else
{
LOG(0, "'" << id << "' not found!");
}
#else //BVS_MODULE_HOTSWAP
LOG(0, "ERROR: HotSwap disabled, could not hotswap: '" << id << "'!");
#endif //BVS_MODULE_HOTSWAP
return *this;
}
BVS::BVS& BVS::BVS::quit()
{
control->sendCommand(SystemFlag::QUIT);
unloadModules();
return *this;
}
<|endoftext|> |
<commit_before>#define MYSQLPP_NOT_HEADER
#include "platform.h"
#include "field_names.h"
#include "result2.hh"
void FieldNames::init(const ResUse *res) {
int num = res->num_fields();
reserve(num);
for (int i = 0; i < num; i++) {
std::string p(res->fields()[i].name); str_to_lwr(p); push_back(p);
}
}
<commit_msg>- #include filename fix - Code style improvements<commit_after>#define MYSQLPP_NOT_HEADER
#include "platform.h"
#include "field_names.h"
#include "result.h"
void FieldNames::init(const ResUse *res)
{
int num = res->num_fields();
reserve(num);
for (int i = 0; i < num; i++) {
std::string p(res->fields()[i].name);
str_to_lwr(p);
push_back(p);
}
}
<|endoftext|> |
<commit_before>#include "StudentTRand.h"
#include "NormalRand.h"
#include "CauchyRand.h"
StudentTRand::StudentTRand(double degree, double location, double scale)
{
SetDegree(degree);
SetLocation(location);
SetScale(scale);
}
std::string StudentTRand::Name() const
{
if (mu == 0.0 && sigma == 1.0)
return "Student's t(" + toStringWithPrecision(GetDegree()) + ")";
return "Student's t(" + toStringWithPrecision(GetDegree()) + ", "
+ toStringWithPrecision(GetLocation()) + ", "
+ toStringWithPrecision(GetScale()) + ")";
}
void StudentTRand::SetDegree(double degree)
{
nu = degree > 0 ? degree : 1;
Y.SetParameters(0.5 * nu, 1.0);
nup1Half = 0.5 * (nu + 1);
pdfCoef = std::lgamma(nup1Half);
pdfCoef -= 0.5 * M_LNPI;
pdfCoef -= Y.GetLogGammaFunction();
logBetaFun = -pdfCoef;
pdfCoef -= 0.5 * std::log(nu);
}
void StudentTRand::SetLocation(double location)
{
mu = location;
}
void StudentTRand::SetScale(double scale)
{
sigma = scale > 0 ? scale : 1.0;
logSigma = std::log(sigma);
}
double StudentTRand::f(const double & x) const
{
/// adjustment
double x0 = x - mu;
x0 /= sigma;
double xSq = x0 * x0;
if (nu == 1) /// Cauchy distribution
return M_1_PI / (sigma * (1 + xSq));
if (nu == 2)
return 1.0 / (sigma * std::pow(2.0 + xSq, 1.5));
if (nu == 3) {
double y = 3 + xSq;
return 6 * M_SQRT3 * M_1_PI / (sigma * y * y);
}
return std::exp(logf(x));
}
double StudentTRand::logf(const double & x) const
{
/// adjustment
double x0 = x - mu;
x0 /= sigma;
double xSq = x0 * x0;
if (nu == 1) /// Cauchy distribution
return std::log(M_1_PI / (sigma * (1 + xSq)));
if (nu == 2) {
return -logSigma - 1.5 * std::log(2.0 + xSq);
}
if (nu == 3) {
double y = 3 + xSq;
y = 6 * M_SQRT3 * M_1_PI / (sigma * y * y);
return std::log(y);
}
double y = -nup1Half * std::log1p(xSq / nu);
return pdfCoef + y - logSigma;
}
double StudentTRand::F(const double & x) const
{
double x0 = x - mu;
x0 /= sigma;
if (x0 == 0.0)
return 0.5;
if (nu == 1) {
/// Cauchy distribution
return 0.5 + M_1_PI * RandMath::atan(x0);
}
if (nu == 2) {
return 0.5 + 0.5 * x0 / std::sqrt(2 + x0 * x0);
}
if (nu == 3) {
double y = M_SQRT3 * x0 / (x0 * x0 + 3);
y += RandMath::atan(x0 / M_SQRT3);
return 0.5 + M_1_PI * y;
}
double t = nu / (x0 * x0 + nu);
double y = 0.5 * RandMath::ibeta(t, 0.5 * nu, 0.5, logBetaFun, std::log(t), std::log1p(-t));
return (x0 > 0.0) ? (1.0 - y) : y;
}
double StudentTRand::S(const double & x) const
{
double x0 = x - mu;
x0 /= sigma;
if (x0 == 0.0)
return 0.5;
if (nu == 1) {
/// Cauchy distribution
return 0.5 + M_1_PI * RandMath::atan(-x0);
}
if (nu == 2) {
return 0.5 - 0.5 * x0 / std::sqrt(2 + x0 * x0);
}
if (nu == 3) {
double y = M_SQRT3 * x0 / (x0 * x0 + 3);
y += RandMath::atan(x0 / M_SQRT3);
return 0.5 - M_1_PI * y;
}
double t = nu / (x0 * x0 + nu);
double y = 0.5 * RandMath::ibeta(t, 0.5 * nu, 0.5, logBetaFun, std::log(t), std::log1p(-t));
return (x0 > 0.0) ? y : 1.0 - y;
}
double StudentTRand::Variate() const
{
if (nu == 1)
return CauchyRand::Variate(mu, sigma);
return mu + sigma * NormalRand::StandardVariate() / Y.Variate();
}
void StudentTRand::Sample(std::vector<double> &outputData) const
{
if (nu == 1) {
for (double &var : outputData)
var = CauchyRand::Variate(mu, sigma);
}
else {
Y.Sample(outputData);
for (double &var : outputData)
var = mu + sigma * NormalRand::StandardVariate() / var;
}
}
double StudentTRand::Mean() const
{
return (nu > 1) ? mu : NAN;
}
double StudentTRand::Variance() const
{
if (nu > 2)
return sigma * sigma * nu / (nu - 2);
return (nu > 1) ? INFINITY : NAN;
}
std::complex<double> StudentTRand::CFImpl(double t) const
{
double x = std::sqrt(nu) * std::fabs(t * sigma); // value of sqrt(nu) can be hashed
double vHalf = 0.5 * nu;
double y = vHalf * std::log(x);
y -= Y.GetLogGammaFunction();
y -= (vHalf - 1) * M_LN2;
y += RandMath::logModifiedBesselSecondKind(x, vHalf);
double costmu = std::cos(t * mu), sintmu = std::sin(t * mu);
std::complex<double> cf(costmu, sintmu);
return std::exp(y) * cf;
}
double StudentTRand::quantileImpl(double p) const
{
double temp = p - 0.5;
if (nu == 1)
return std::tan(M_PI * temp) * sigma + mu;
double pq = p * (1.0 - p);
if (nu == 2)
return sigma * 2.0 * temp * std::sqrt(0.5 / pq) + mu;
if (nu == 4)
{
double alpha = 2 * std::sqrt(pq);
double beta = std::cos(std::acos(alpha) / 3.0) / alpha - 1;
return mu + sigma * 2 * RandMath::sign(temp) * std::sqrt(beta);
}
return ContinuousDistribution::quantileImpl(p);
}
double StudentTRand::quantileImpl1m(double p) const
{
double temp = 0.5 - p;
if (nu == 1)
return std::tan(M_PI * temp) * sigma + mu;
double pq = p * (1.0 - p);
if (nu == 2)
return sigma * 2 * temp * std::sqrt(0.5 / pq) + mu;
if (nu == 4)
{
double alpha = 2 * std::sqrt(pq);
double beta = std::cos(std::acos(alpha) / 3.0) / alpha - 1;
return mu + sigma * 2 * RandMath::sign(temp) * std::sqrt(beta);
}
return ContinuousDistribution::quantileImpl1m(p);
}
double StudentTRand::Median() const
{
return mu;
}
double StudentTRand::Mode() const
{
return mu;
}
double StudentTRand::Skewness() const
{
return (nu > 3) ? 0.0 : NAN;
}
double StudentTRand::ExcessKurtosis() const
{
if (nu > 4)
return 6 / (nu - 4);
return (nu > 2) ? INFINITY : NAN;
}
<commit_msg>Update StudentTRand.cpp<commit_after>#include "StudentTRand.h"
#include "NormalRand.h"
#include "CauchyRand.h"
StudentTRand::StudentTRand(double degree, double location, double scale)
{
SetDegree(degree);
SetLocation(location);
SetScale(scale);
}
std::string StudentTRand::Name() const
{
if (mu == 0.0 && sigma == 1.0)
return "Student's t(" + toStringWithPrecision(GetDegree()) + ")";
return "Student's t(" + toStringWithPrecision(GetDegree()) + ", "
+ toStringWithPrecision(GetLocation()) + ", "
+ toStringWithPrecision(GetScale()) + ")";
}
void StudentTRand::SetDegree(double degree)
{
nu = degree > 0 ? degree : 1;
Y.SetParameters(0.5 * nu, 1.0);
nup1Half = 0.5 * (nu + 1);
pdfCoef = std::lgamma(nup1Half);
pdfCoef -= 0.5 * M_LNPI;
pdfCoef -= Y.GetLogGammaFunction();
logBetaFun = -pdfCoef;
pdfCoef -= 0.5 * std::log(nu);
}
void StudentTRand::SetLocation(double location)
{
mu = location;
}
void StudentTRand::SetScale(double scale)
{
sigma = scale > 0 ? scale : 1.0;
logSigma = std::log(sigma);
}
double StudentTRand::f(const double & x) const
{
/// adjustment
double x0 = x - mu;
x0 /= sigma;
double xSq = x0 * x0;
if (nu == 1) /// Cauchy distribution
return M_1_PI / (sigma * (1 + xSq));
if (nu == 2)
return 1.0 / (sigma * std::pow(2.0 + xSq, 1.5));
if (nu == 3) {
double y = 3 + xSq;
return 6 * M_SQRT3 * M_1_PI / (sigma * y * y);
}
return std::exp(logf(x));
}
double StudentTRand::logf(const double & x) const
{
/// adjustment
double x0 = x - mu;
x0 /= sigma;
double xSq = x0 * x0;
if (nu == 1) /// Cauchy distribution
return -std::log1p(xSq) - logSigma - M_LNPI;
if (nu == 2)
return -logSigma - 1.5 * std::log(2.0 + xSq);
if (nu == 3) {
double y = 3 + xSq;
y = 6 * M_SQRT3 * M_1_PI / (sigma * y * y);
return std::log(y);
}
double y = -nup1Half * std::log1p(xSq / nu);
return pdfCoef + y - logSigma;
}
double StudentTRand::F(const double & x) const
{
double x0 = x - mu;
x0 /= sigma;
if (x0 == 0.0)
return 0.5;
if (nu == 1) {
/// Cauchy distribution
return 0.5 + M_1_PI * RandMath::atan(x0);
}
if (nu == 2) {
return 0.5 + 0.5 * x0 / std::sqrt(2 + x0 * x0);
}
if (nu == 3) {
double y = M_SQRT3 * x0 / (x0 * x0 + 3);
y += RandMath::atan(x0 / M_SQRT3);
return 0.5 + M_1_PI * y;
}
double t = nu / (x0 * x0 + nu);
double y = 0.5 * RandMath::ibeta(t, 0.5 * nu, 0.5, logBetaFun, std::log(t), std::log1p(-t));
return (x0 > 0.0) ? (1.0 - y) : y;
}
double StudentTRand::S(const double & x) const
{
double x0 = x - mu;
x0 /= sigma;
if (x0 == 0.0)
return 0.5;
if (nu == 1) {
/// Cauchy distribution
return 0.5 + M_1_PI * RandMath::atan(-x0);
}
if (nu == 2) {
return 0.5 - 0.5 * x0 / std::sqrt(2 + x0 * x0);
}
if (nu == 3) {
double y = M_SQRT3 * x0 / (x0 * x0 + 3);
y += RandMath::atan(x0 / M_SQRT3);
return 0.5 - M_1_PI * y;
}
double t = nu / (x0 * x0 + nu);
double y = 0.5 * RandMath::ibeta(t, 0.5 * nu, 0.5, logBetaFun, std::log(t), std::log1p(-t));
return (x0 > 0.0) ? y : 1.0 - y;
}
double StudentTRand::Variate() const
{
if (nu == 1)
return CauchyRand::Variate(mu, sigma);
return mu + sigma * NormalRand::StandardVariate() / Y.Variate();
}
void StudentTRand::Sample(std::vector<double> &outputData) const
{
if (nu == 1) {
for (double &var : outputData)
var = CauchyRand::Variate(mu, sigma);
}
else {
Y.Sample(outputData);
for (double &var : outputData)
var = mu + sigma * NormalRand::StandardVariate() / var;
}
}
double StudentTRand::Mean() const
{
return (nu > 1) ? mu : NAN;
}
double StudentTRand::Variance() const
{
if (nu > 2)
return sigma * sigma * nu / (nu - 2);
return (nu > 1) ? INFINITY : NAN;
}
std::complex<double> StudentTRand::CFImpl(double t) const
{
double x = std::sqrt(nu) * std::fabs(t * sigma); // value of sqrt(nu) can be hashed
double vHalf = 0.5 * nu;
double y = vHalf * std::log(x);
y -= Y.GetLogGammaFunction();
y -= (vHalf - 1) * M_LN2;
y += RandMath::logModifiedBesselSecondKind(x, vHalf);
double costmu = std::cos(t * mu), sintmu = std::sin(t * mu);
std::complex<double> cf(costmu, sintmu);
return std::exp(y) * cf;
}
double StudentTRand::quantileImpl(double p) const
{
double temp = p - 0.5;
if (nu == 1)
return std::tan(M_PI * temp) * sigma + mu;
double pq = p * (1.0 - p);
if (nu == 2)
return sigma * 2.0 * temp * std::sqrt(0.5 / pq) + mu;
if (nu == 4)
{
double alpha = 2 * std::sqrt(pq);
double beta = std::cos(std::acos(alpha) / 3.0) / alpha - 1;
return mu + sigma * 2 * RandMath::sign(temp) * std::sqrt(beta);
}
return ContinuousDistribution::quantileImpl(p);
}
double StudentTRand::quantileImpl1m(double p) const
{
double temp = 0.5 - p;
if (nu == 1)
return std::tan(M_PI * temp) * sigma + mu;
double pq = p * (1.0 - p);
if (nu == 2)
return sigma * 2 * temp * std::sqrt(0.5 / pq) + mu;
if (nu == 4)
{
double alpha = 2 * std::sqrt(pq);
double beta = std::cos(std::acos(alpha) / 3.0) / alpha - 1;
return mu + sigma * 2 * RandMath::sign(temp) * std::sqrt(beta);
}
return ContinuousDistribution::quantileImpl1m(p);
}
double StudentTRand::Median() const
{
return mu;
}
double StudentTRand::Mode() const
{
return mu;
}
double StudentTRand::Skewness() const
{
return (nu > 3) ? 0.0 : NAN;
}
double StudentTRand::ExcessKurtosis() const
{
if (nu > 4)
return 6 / (nu - 4);
return (nu > 2) ? INFINITY : NAN;
}
<|endoftext|> |
<commit_before>#pragma once
#include <type_traits>
#include <tuple>
#include <agency/detail/integer_sequence.hpp>
#define __DEFINE_HAS_NESTED_TYPE(trait_name, nested_type_name) \
template<typename T> \
struct trait_name \
{ \
typedef char yes_type; \
typedef int no_type; \
template<typename S> static yes_type test(typename S::nested_type_name *); \
template<typename S> static no_type test(...); \
static bool const value = sizeof(test<T>(0)) == sizeof(yes_type);\
typedef std::integral_constant<bool, value> type;\
};
#define __DEFINE_HAS_NESTED_CLASS_TEMPLATE(trait_name, nested_class_template_name) \
template<typename T, typename... Types> \
struct trait_name \
{ \
typedef char yes_type; \
typedef int no_type; \
template<typename S> static yes_type test(typename S::template nested_class_template_name<Types...> *); \
template<typename S> static no_type test(...); \
static bool const value = sizeof(test<T>(0)) == sizeof(yes_type);\
typedef std::integral_constant<bool, value> type;\
};
#ifdef __NVCC__
#define __DEFINE_HAS_NESTED_MEMBER(trait_name, nested_member_name) \
template<typename T> \
struct trait_name \
{ \
typedef char yes_type; \
typedef int no_type; \
template<int i> struct swallow_int {}; \
template<typename S> static yes_type test(swallow_int<sizeof(S::nested_member_name)>*); \
template<typename S> static no_type test(...); \
static bool const value = sizeof(test<T>(0)) == sizeof(yes_type);\
typedef std::integral_constant<bool, value> type;\
};
#else
#define __DEFINE_HAS_NESTED_MEMBER(trait_name, nested_member_name) \
template<typename T> \
struct trait_name \
{ \
typedef char yes_type; \
typedef int no_type; \
template<typename S> static yes_type test(decltype(S::nested_member_name)*); \
template<typename S> static no_type test(...); \
static bool const value = sizeof(test<T>(0)) == sizeof(yes_type);\
typedef std::integral_constant<bool, value> type;\
};
#endif
namespace agency
{
namespace detail
{
template<bool b, typename T, typename F>
struct lazy_conditional
{
using type = typename T::type;
};
template<typename T, typename F>
struct lazy_conditional<false,T,F>
{
using type = typename F::type;
};
template<typename T>
struct identity
{
typedef T type;
};
template<class T>
using decay_t = typename std::decay<T>::type;
template<class T>
using result_of_t = typename std::result_of<T>::type;
template<class... Types> struct type_list {};
template<class TypeList> struct type_list_size;
template<class... Types>
struct type_list_size<type_list<Types...>> : std::integral_constant<size_t, sizeof...(Types)> {};
template<size_t i, class TypeList>
struct type_list_element_impl;
template<class T0, class... Types>
struct type_list_element_impl<0,type_list<T0,Types...>>
{
using type = T0;
};
template<size_t i, class T0, class... Types>
struct type_list_element_impl<i,type_list<T0,Types...>>
{
using type = typename type_list_element_impl<i-1,type_list<Types...>>::type;
};
template<size_t i, class TypeList>
using type_list_element = typename type_list_element_impl<i,TypeList>::type;
template<class TypeList, class IndexSequence>
struct type_list_take_impl_impl;
template<class TypeList, size_t... I>
struct type_list_take_impl_impl<TypeList, index_sequence<I...>>
{
using type = type_list<
type_list_element<I,TypeList>...
>;
};
template<size_t n, class TypeList>
struct type_list_take_impl;
template<size_t n, class... Types>
struct type_list_take_impl<n,type_list<Types...>>
{
using type = typename type_list_take_impl_impl<
type_list<Types...>,
make_index_sequence<n>
>::type;
};
template<size_t n, class TypeList>
using type_list_take = typename type_list_take_impl<n,TypeList>::type;
namespace type_list_detail
{
template<int a, int b>
struct max : std::integral_constant<
int,
(a < b ? b : a)
>
{};
} // end type_list_detail
template<size_t n, class TypeList>
using type_list_drop = type_list_take<
type_list_detail::max<
0,
type_list_size<TypeList>::value - n
>::value,
TypeList
>;
template<class TypeList>
using type_list_drop_last = type_list_drop<1,TypeList>;
template<class T, class TypeList>
struct is_constructible_from_type_list;
template<class T, class... Types>
struct is_constructible_from_type_list<T,type_list<Types...>>
: std::is_constructible<T,Types...>
{};
template<class T0, class TypeList>
struct type_list_prepend;
template<class T0, class... Types>
struct type_list_prepend<T0, type_list<Types...>>
{
using type = type_list<T0, Types...>;
};
template<class T, size_t n>
struct repeat_type_impl
{
using rest = typename repeat_type_impl<T,n-1>::type;
using type = typename type_list_prepend<
T,
rest
>::type;
};
template<class T>
struct repeat_type_impl<T,0>
{
using type = type_list<>;
};
template<class T, size_t n>
using repeat_type = typename repeat_type_impl<T,n>::type;
template<class... Conditions>
struct static_and;
template<>
struct static_and<> : std::true_type {};
template<class Condition, class... Conditions>
struct static_and<Condition, Conditions...>
: std::integral_constant<
bool,
Condition::value && static_and<Conditions...>::value
>
{};
template<class... Conditions>
struct static_or;
template<>
struct static_or<> : std::false_type {};
template<class Condition, class... Conditions>
struct static_or<Condition, Conditions...>
: std::integral_constant<
bool,
Condition::value || static_or<Conditions...>::value
>
{};
__DEFINE_HAS_NESTED_MEMBER(has_value, value);
template<class T>
struct is_tuple : has_value<std::tuple_size<T>> {};
template<class Indices, class Tuple>
struct tuple_type_list_impl;
template<size_t... Indices, class Tuple>
struct tuple_type_list_impl<index_sequence<Indices...>, Tuple>
{
using type = type_list<
typename std::tuple_element<Indices,Tuple>::type...
>;
};
template<class T, class Enable = void>
struct tuple_type_list;
template<class Tuple>
struct tuple_type_list<Tuple, typename std::enable_if<is_tuple<Tuple>::value>::type>
{
using type = typename tuple_type_list_impl<
make_index_sequence<std::tuple_size<Tuple>::value>,
Tuple
>::type;
};
template<class>
struct is_empty_tuple;
template<class T>
struct is_empty_tuple_impl_impl;
template<class... Types>
struct is_empty_tuple_impl_impl<type_list<Types...>>
{
using type = static_and<
static_or<
std::is_empty<Types>,
is_empty_tuple<Types>
>...
>;
};
template<class T, class Enable = void>
struct is_empty_tuple_impl : std::false_type {};
template<class Tuple>
struct is_empty_tuple_impl<Tuple, typename std::enable_if<is_tuple<Tuple>::value>::type>
{
using type = typename is_empty_tuple_impl_impl<
typename tuple_type_list<Tuple>::type
>::type;
};
template<class Tuple>
struct is_empty_tuple : is_empty_tuple_impl<Tuple>::type {};
template<class T>
struct lazy_add_lvalue_reference
{
using type = typename std::add_lvalue_reference<typename T::type>::type;
};
template<class T, template<class...> class Template>
struct is_instance_of : std::false_type {};
template<class... Types, template<class...> class Template>
struct is_instance_of<Template<Types...>,Template> : std::true_type {};
} // end detail
} // end agency
<commit_msg>Put type_list in its own header<commit_after>#pragma once
#include <type_traits>
#include <tuple>
#include <agency/detail/integer_sequence.hpp>
#include <agency/detail/type_list.hpp>
#define __DEFINE_HAS_NESTED_TYPE(trait_name, nested_type_name) \
template<typename T> \
struct trait_name \
{ \
typedef char yes_type; \
typedef int no_type; \
template<typename S> static yes_type test(typename S::nested_type_name *); \
template<typename S> static no_type test(...); \
static bool const value = sizeof(test<T>(0)) == sizeof(yes_type);\
typedef std::integral_constant<bool, value> type;\
};
#define __DEFINE_HAS_NESTED_CLASS_TEMPLATE(trait_name, nested_class_template_name) \
template<typename T, typename... Types> \
struct trait_name \
{ \
typedef char yes_type; \
typedef int no_type; \
template<typename S> static yes_type test(typename S::template nested_class_template_name<Types...> *); \
template<typename S> static no_type test(...); \
static bool const value = sizeof(test<T>(0)) == sizeof(yes_type);\
typedef std::integral_constant<bool, value> type;\
};
#ifdef __NVCC__
#define __DEFINE_HAS_NESTED_MEMBER(trait_name, nested_member_name) \
template<typename T> \
struct trait_name \
{ \
typedef char yes_type; \
typedef int no_type; \
template<int i> struct swallow_int {}; \
template<typename S> static yes_type test(swallow_int<sizeof(S::nested_member_name)>*); \
template<typename S> static no_type test(...); \
static bool const value = sizeof(test<T>(0)) == sizeof(yes_type);\
typedef std::integral_constant<bool, value> type;\
};
#else
#define __DEFINE_HAS_NESTED_MEMBER(trait_name, nested_member_name) \
template<typename T> \
struct trait_name \
{ \
typedef char yes_type; \
typedef int no_type; \
template<typename S> static yes_type test(decltype(S::nested_member_name)*); \
template<typename S> static no_type test(...); \
static bool const value = sizeof(test<T>(0)) == sizeof(yes_type);\
typedef std::integral_constant<bool, value> type;\
};
#endif
namespace agency
{
namespace detail
{
template<bool b, typename T, typename F>
struct lazy_conditional
{
using type = typename T::type;
};
template<typename T, typename F>
struct lazy_conditional<false,T,F>
{
using type = typename F::type;
};
template<typename T>
struct identity
{
typedef T type;
};
template<class T>
using decay_t = typename std::decay<T>::type;
template<class T>
using result_of_t = typename std::result_of<T>::type;
template<class T, size_t n>
struct repeat_type_impl
{
using rest = typename repeat_type_impl<T,n-1>::type;
using type = typename type_list_prepend<
T,
rest
>::type;
};
template<class T>
struct repeat_type_impl<T,0>
{
using type = type_list<>;
};
template<class T, size_t n>
using repeat_type = typename repeat_type_impl<T,n>::type;
template<class... Conditions>
struct static_and;
template<>
struct static_and<> : std::true_type {};
template<class Condition, class... Conditions>
struct static_and<Condition, Conditions...>
: std::integral_constant<
bool,
Condition::value && static_and<Conditions...>::value
>
{};
template<class... Conditions>
struct static_or;
template<>
struct static_or<> : std::false_type {};
template<class Condition, class... Conditions>
struct static_or<Condition, Conditions...>
: std::integral_constant<
bool,
Condition::value || static_or<Conditions...>::value
>
{};
__DEFINE_HAS_NESTED_MEMBER(has_value, value);
template<class T>
struct is_tuple : has_value<std::tuple_size<T>> {};
template<class Indices, class Tuple>
struct tuple_type_list_impl;
template<size_t... Indices, class Tuple>
struct tuple_type_list_impl<index_sequence<Indices...>, Tuple>
{
using type = type_list<
typename std::tuple_element<Indices,Tuple>::type...
>;
};
template<class T, class Enable = void>
struct tuple_type_list;
template<class Tuple>
struct tuple_type_list<Tuple, typename std::enable_if<is_tuple<Tuple>::value>::type>
{
using type = typename tuple_type_list_impl<
make_index_sequence<std::tuple_size<Tuple>::value>,
Tuple
>::type;
};
template<class>
struct is_empty_tuple;
template<class T>
struct is_empty_tuple_impl_impl;
template<class... Types>
struct is_empty_tuple_impl_impl<type_list<Types...>>
{
using type = static_and<
static_or<
std::is_empty<Types>,
is_empty_tuple<Types>
>...
>;
};
template<class T, class Enable = void>
struct is_empty_tuple_impl : std::false_type {};
template<class Tuple>
struct is_empty_tuple_impl<Tuple, typename std::enable_if<is_tuple<Tuple>::value>::type>
{
using type = typename is_empty_tuple_impl_impl<
typename tuple_type_list<Tuple>::type
>::type;
};
template<class Tuple>
struct is_empty_tuple : is_empty_tuple_impl<Tuple>::type {};
template<class T>
struct lazy_add_lvalue_reference
{
using type = typename std::add_lvalue_reference<typename T::type>::type;
};
template<class T, template<class...> class Template>
struct is_instance_of : std::false_type {};
template<class... Types, template<class...> class Template>
struct is_instance_of<Template<Types...>,Template> : std::true_type {};
} // end detail
} // end agency
<|endoftext|> |
<commit_before>/*
* StreamServerManager.cpp
*
* Created on: Sep 10, 2015
* Author: alarrosa14
*/
#include <chrono>
#include "lz4.h"
#include "lz4frame.h"
#include "StreamServerManager.h"
StreamServerManager::StreamServerManager(void) {
waitForNewFrameMutex.lock();
}
StreamServerManager::~StreamServerManager(void) {}
void StreamServerManager::setEnabled(const bool &isEnabled) {
this->enabled = isEnabled;
}
void StreamServerManager::setCompressionEnabled(const bool &compression) {
this->compressionEnabled = compression;
}
void StreamServerManager::setAddress(const string &address) {
this->address = address;
}
void StreamServerManager::setPixelQuantity(const int &pixelQty){
this->pixelQuantity = pixelQty;
}
void StreamServerManager::setPort(const int &port){
this->port = port;
}
bool StreamServerManager::getEnabled() {
return this->enabled;
}
bool StreamServerManager::getCompressionEnabled() {
return this->compressionEnabled;
}
string StreamServerManager::getAddress() {
return this->address;
}
int StreamServerManager::getPixelQuantity() {
return this->pixelQuantity;
}
int StreamServerManager::getPort(){
return this->port;
}
void StreamServerManager::setupStreamingSender() {
cout << "Server config: " << this->address << endl << this->port << endl;
cout << "Compression enabled? " << (this->compressionEnabled ? "True" : "False") << endl;
string url = "http://" + this->address + ":" + to_string(this->port);
cout << "Setting up Streaming Server: " << url << endl;
udpManager.Create();
cout << this->address.c_str() << this->port << endl;
if (!udpManager.Connect(this->address.c_str(), this->port));
cout << endl << endl << "Error connecting socket!" << endl << endl;
udpManager.SetNonBlocking(true);
}
void StreamServerManager::addFrameToSendBuffer(DTFrame* newFrame) {
lock();
this->sendBuffer.push_back(newFrame);
unlock();
waitForNewFrameMutex.unlock();
}
void convertToArrayOfBytes(void* data, int length, unsigned char *buffer) {
char* ptr = (char*)data;
for (int i = 0; i < length; i++)
buffer[i] = *ptr++;
};
uint64_t htonll(uint64_t n) {
#if __BYTE_ORDER == __BIG_ENDIAN
return n;
#else
return (((uint64_t)htonl(n)) << 32) + htonl(n >> 32);
#endif
}
uint64_t ntohll(uint64_t n) {
return htonll(n);
}
void StreamServerManager::threadedFunction() {
const int frameSize = this->pixelQuantity*3;
size_t compressedBufferMaxSize;
unsigned char *compressedBuffer = NULL;
if (compressionEnabled) {
compressedBufferMaxSize = LZ4F_compressFrameBound(frameSize, NULL);
compressedBuffer = new unsigned char[compressedBufferMaxSize];
}
const int bufferSize = ((compressionEnabled && compressedBufferMaxSize > frameSize) ? compressedBufferMaxSize : frameSize) + sizeof(uint64_t);
unsigned char *buffer = new unsigned char[bufferSize];
while(isThreadRunning()) {
waitForNewFrameMutex.lock();
lock();
if(this->sendBuffer.size()>0){
vector<DTFrame*>::iterator it = this->sendBuffer.begin();
this->sendBuffer.erase(it);
unlock();
uint8_t* raw_frame = (*it)->getRawFrameData();
int raw_frame_length = (*it)->getPixelQuantity()*3;
assert(raw_frame_length == this->pixelQuantity*3);
using namespace std::chrono;
uint64_t ms = htonll(duration_cast< milliseconds >(
system_clock::now().time_since_epoch()
).count());
convertToArrayOfBytes(&ms, sizeof(ms), buffer);
if (compressionEnabled) {
size_t compressedBufferSize = LZ4F_compressFrame(compressedBuffer, compressedBufferMaxSize, raw_frame, raw_frame_length, NULL);
convertToArrayOfBytes(compressedBuffer, compressedBufferSize, buffer + sizeof(ms));
this->udpManager.Send((char*) buffer, sizeof(ms) + compressedBufferSize);
} else {
convertToArrayOfBytes(raw_frame, raw_frame_length, buffer + sizeof(ms));
this->udpManager.Send((char*) buffer, bufferSize);
}
} else {
unlock();
}
}
this->udpManager.Close();
delete[]buffer;
delete[]compressedBuffer;
}
<commit_msg>Now sending a 1 byte long timestamp in each frame to Sendero Streaming Server<commit_after>/*
* StreamServerManager.cpp
*
* Created on: Sep 10, 2015
* Author: alarrosa14
*/
#include <chrono>
#include "lz4.h"
#include "lz4frame.h"
#include "StreamServerManager.h"
StreamServerManager::StreamServerManager(void) {
waitForNewFrameMutex.lock();
}
StreamServerManager::~StreamServerManager(void) {}
void StreamServerManager::setEnabled(const bool &isEnabled) {
this->enabled = isEnabled;
}
void StreamServerManager::setCompressionEnabled(const bool &compression) {
this->compressionEnabled = compression;
}
void StreamServerManager::setAddress(const string &address) {
this->address = address;
}
void StreamServerManager::setPixelQuantity(const int &pixelQty){
this->pixelQuantity = pixelQty;
}
void StreamServerManager::setPort(const int &port){
this->port = port;
}
bool StreamServerManager::getEnabled() {
return this->enabled;
}
bool StreamServerManager::getCompressionEnabled() {
return this->compressionEnabled;
}
string StreamServerManager::getAddress() {
return this->address;
}
int StreamServerManager::getPixelQuantity() {
return this->pixelQuantity;
}
int StreamServerManager::getPort(){
return this->port;
}
void StreamServerManager::setupStreamingSender() {
cout << "Server config: " << this->address << endl << this->port << endl;
cout << "Compression enabled? " << (this->compressionEnabled ? "True" : "False") << endl;
string url = "http://" + this->address + ":" + to_string(this->port);
cout << "Setting up Streaming Server: " << url << endl;
udpManager.Create();
cout << this->address.c_str() << this->port << endl;
if (!udpManager.Connect(this->address.c_str(), this->port));
cout << endl << endl << "Error connecting socket!" << endl << endl;
udpManager.SetNonBlocking(true);
}
void StreamServerManager::addFrameToSendBuffer(DTFrame* newFrame) {
lock();
this->sendBuffer.push_back(newFrame);
unlock();
waitForNewFrameMutex.unlock();
}
void convertToArrayOfBytes(void* data, int length, unsigned char *buffer) {
char* ptr = (char*)data;
for (int i = 0; i < length; i++)
buffer[i] = *ptr++;
};
uint64_t htonll(uint64_t n) {
#if __BYTE_ORDER == __BIG_ENDIAN
return n;
#else
return (((uint64_t)htonl(n)) << 32) + htonl(n >> 32);
#endif
}
uint64_t ntohll(uint64_t n) {
return htonll(n);
}
void StreamServerManager::threadedFunction() {
uint8_t currentSeqNmb = 0;
const int frameSize = this->pixelQuantity*3;
size_t compressedBufferMaxSize;
unsigned char *compressedBuffer = NULL;
if (compressionEnabled) {
compressedBufferMaxSize = LZ4F_compressFrameBound(frameSize, NULL);
compressedBuffer = new unsigned char[compressedBufferMaxSize];
}
const int bufferSize = ((compressionEnabled && compressedBufferMaxSize > frameSize) ? compressedBufferMaxSize : frameSize) + sizeof(uint64_t) + sizeof(uint8_t);
unsigned char *buffer = new unsigned char[bufferSize];
using namespace std::chrono;
while(isThreadRunning()) {
waitForNewFrameMutex.lock();
lock();
if(this->sendBuffer.size()>0){
vector<DTFrame*>::iterator it = this->sendBuffer.begin();
this->sendBuffer.erase(it);
unlock();
uint8_t* raw_frame = (*it)->getRawFrameData();
int raw_frame_length = (*it)->getPixelQuantity()*3;
assert(raw_frame_length == this->pixelQuantity*3);
uint64_t ms = htonll(duration_cast< milliseconds >(
system_clock::now().time_since_epoch()
).count());
convertToArrayOfBytes(&ms, sizeof(ms), buffer);
convertToArrayOfBytes(¤tSeqNmb, sizeof(currentSeqNmb), buffer + sizeof(ms));
if (compressionEnabled) {
size_t compressedBufferSize = LZ4F_compressFrame(compressedBuffer, compressedBufferMaxSize, raw_frame, raw_frame_length, NULL);
convertToArrayOfBytes(compressedBuffer, compressedBufferSize, buffer + sizeof(ms) + sizeof(currentSeqNmb));
this->udpManager.Send((char*) buffer, sizeof(ms) + sizeof(currentSeqNmb) + compressedBufferSize);
} else {
convertToArrayOfBytes(raw_frame, raw_frame_length, buffer + sizeof(ms));
this->udpManager.Send((char*) buffer, bufferSize);
}
currentSeqNmb = (currentSeqNmb + 1) % 256;
} else {
unlock();
}
}
this->udpManager.Close();
delete[]buffer;
delete[]compressedBuffer;
}
<|endoftext|> |
<commit_before>#include "details/pass/build-ast-to-ir/scope.h"
#include "details/grammar/nany.h"
#include "details/ast/ast.h"
#include <limits>
using namespace Yuni;
namespace Nany
{
namespace IR
{
namespace Producer
{
namespace // anonymous
{
struct NumberDef final
{
// Is the number signed or unsigned ?
bool isUnsigned = false;
// Is the number a floating-point number ?
bool isFloat = false;
// how many bits used by the number ? (32 by default)
uint bits = 32;
// Sign of the number: ' ', '+', '-'
char sign = ' ';
//! The first part of the number
uint64_t part1 = 0;
//! Second part of the number
AnyString part2; // the second part may have additional zero
};
static constexpr inline bool validNumberOfBits(uint32_t bits)
{
return bits == 32 or bits == 64 or bits == 16 or bits == 8;
}
static bool convertASTNumberToDouble(double& value, uint64 part1, const AnyString& part2, char sign)
{
if (part1 == 0 and part2.empty()) // obvious zero value
{
value = 0.;
}
else
{
ShortString128 tmp;
if (sign == '-') // append the sign of the number
tmp += '-';
tmp << part1;
if (not part2.empty())
tmp << '.' << part2;
if (unlikely(not tmp.to<double>(value)))
{
value = 0.;
return false;
}
}
return true;
}
} // anonymous namespace
template<bool BuiltinT, class DefT>
inline bool Scope::generateNumberCode(uint32_t& localvar, const DefT& numdef, const AST::Node& node)
{
// checking for invalid float values
nytype_t type = nyt_void;
// class name
AnyString cn;
uint32_t hardcodedlvid;
if (not numdef.isFloat)
{
if (not numdef.isUnsigned)
{
switch (numdef.bits)
{
case 64: type = nyt_i64; if (not BuiltinT) cn = "i64"; break;
case 32: type = nyt_i32; if (not BuiltinT) cn = "i32"; break;
case 16: type = nyt_i16; if (not BuiltinT) cn = "i16"; break;
case 8: type = nyt_i8; if (not BuiltinT) cn = "i8"; break;
}
}
else
{
switch (numdef.bits)
{
case 64: type = nyt_u64; if (not BuiltinT) cn = "u64"; break;
case 32: type = nyt_u32; if (not BuiltinT) cn = "u32"; break;
case 16: type = nyt_u16; if (not BuiltinT) cn = "u16"; break;
case 8: type = nyt_u8; if (not BuiltinT) cn = "u8"; break;
}
}
if (numdef.part1 != 0)
{
bool invalidcast = false;
if (numdef.sign == ' ' or numdef.sign == '+')
{
if (not numdef.isUnsigned)
{
switch (numdef.bits)
{
case 64: invalidcast = (numdef.part1 > std::numeric_limits<int32_t>::max()); break;
case 32: invalidcast = (numdef.part1 > std::numeric_limits<int32_t>::max()); break;
case 16: invalidcast = (numdef.part1 > std::numeric_limits<int16_t>::max()); break;
case 8: invalidcast = (numdef.part1 > std::numeric_limits< int8_t>::max()); break;
}
}
else
{
switch (numdef.bits)
{
case 64: break;
case 32: invalidcast = (numdef.part1 > std::numeric_limits<uint32_t>::max()); break;
case 16: invalidcast = (numdef.part1 > std::numeric_limits<uint16_t>::max()); break;
case 8: invalidcast = (numdef.part1 > std::numeric_limits< uint8_t>::max()); break;
}
}
}
else
{
if (not numdef.isUnsigned)
{
if (numdef.part1 < static_cast<uint64_t>(std::numeric_limits<int64_t>::max()))
{
int64_t sv = static_cast<int64_t>(numdef.part1);
switch (numdef.bits)
{
case 64: invalidcast = (sv < std::numeric_limits<int32_t>::min()); break;
case 32: invalidcast = (sv < std::numeric_limits<int32_t>::min()); break;
case 16: invalidcast = (sv < std::numeric_limits<int16_t>::min()); break;
case 8: invalidcast = (sv < std::numeric_limits< int8_t>::min()); break;
}
}
else
invalidcast = true;
}
else
invalidcast = true;
}
if (unlikely(invalidcast))
{
error(node) << "invalid " << ((numdef.isUnsigned) ? "unsigned " : "signed ")
<< numdef.bits << "bits integer";
return false;
}
}
hardcodedlvid = createLocalBuiltinInt(node, type, numdef.part1);
}
else
{
// converting the number into a double
double value;
if (unlikely(not convertASTNumberToDouble(value, numdef.part1, numdef.part2, numdef.sign)))
return (error(node) << "invalid floating point number");
type = (numdef.bits == 32) ? nyt_f32 : nyt_f64;
if (not BuiltinT)
cn.adapt((numdef.bits == 32) ? "f32" : "f64", 3);
hardcodedlvid = createLocalBuiltinFloat(node, type, value);
}
if (BuiltinT)
{
localvar = hardcodedlvid;
return true;
}
else
{
if (!context.reuse.literal.node)
context.prepareReuseForLiterals();
assert(not cn.empty());
context.reuse.literal.classname->text = cn;
ShortString16 lvidstr;
lvidstr = hardcodedlvid;
context.reuse.literal.lvidnode->text = lvidstr;
bool success = visitASTExprNew(*(context.reuse.literal.node), localvar);
// avoid crap in the debugger
context.reuse.literal.classname->text.clear();
context.reuse.literal.lvidnode->text.clear();
return success;
}
}
bool Scope::visitASTExprNumber(const AST::Node& node, yuint32& localvar)
{
assert(node.rule == AST::rgNumber);
assert(not node.children.empty());
// Number definition
NumberDef numdef;
// is a builtin ? (__i32, __f64...)
// (always generate builtin types when not importing the NSL)
bool builtin = (not Config::importNSL);
emitDebugpos(node);
for (auto& childptr: node.children)
{
switch (childptr->rule)
{
case AST::rgNumberValue: // standard number definition
{
bool firstPart = true;
for (auto& subnodeptr: childptr->children)
{
switch (subnodeptr->rule)
{
case AST::rgInteger:
{
if (likely(firstPart))
{
if (not subnodeptr->text.to<uint64>(numdef.part1))
{
error(*subnodeptr) << "invalid integer value";
return false;
}
firstPart = false;
}
else
{
numdef.part2 = subnodeptr->text;
numdef.part2.trimRight('0'); // remove useless zeros
// as far as we know, it is a float64 by default
numdef.isFloat = true;
}
break;
}
default:
{
ice(*subnodeptr) << "[expr-number]";
return false;
}
}
}
break;
}
case AST::rgNumberSign: // + -
{
assert(not childptr->text.empty() and "invalid ast");
numdef.sign = childptr->text[0];
assert(numdef.sign == '+' or numdef.sign == '-');
break;
}
case AST::rgNumberQualifier: // unsigned / signed / float
{
for (auto& subnodeptr: childptr->children)
{
auto& subnode = *(subnodeptr);
switch (subnode.rule)
{
case AST::rgNumberQualifierType:
{
assert(not subnode.text.empty());
uint offset = 0;
if (subnode.text.first() == '_' and subnode.text[1] == '_')
{
offset = 2;
builtin = true;
}
for (uint i = offset; i < subnode.text.size(); ++i)
{
switch (subnode.text[i])
{
case 'i': numdef.isUnsigned = false; break;
case 'u': numdef.isUnsigned = true; break;
case 'f': numdef.isFloat = true; break;
default: error(node) << "invalid number qualifier. Got '"
<< subnode.text.first() << "', expected 'i', 'u' or 'f'";
}
}
break;
}
case AST::rgInteger:
{
if (likely(subnode.text.size() < 10))
{
numdef.bits = subnode.text.to<uint>();
if (unlikely(not validNumberOfBits(numdef.bits)))
return (error(subnode) << "invalid integer size");
}
else
{
error(subnode) << "integer too large";
return false;
}
break;
}
default:
{
ice(subnode) << "[expr-number]";
return false;
}
}
}
break;
}
default:
{
ice(*childptr) << "[expr-number]";
return false;
}
}
}
assert(numdef.bits == 64 or numdef.bits == 32 or numdef.bits == 16 or numdef.bits == 8);
return (not builtin)
? generateNumberCode<false>(localvar, numdef, node)
: generateNumberCode<true> (localvar, numdef, node);
}
} // namespace Producer
} // namespace IR
} // namespace Nany
<commit_msg>fixed invalid interpretation of negative numbers<commit_after>#include "details/pass/build-ast-to-ir/scope.h"
#include "details/grammar/nany.h"
#include "details/ast/ast.h"
#include <limits>
using namespace Yuni;
namespace Nany
{
namespace IR
{
namespace Producer
{
namespace // anonymous
{
struct NumberDef final
{
// Is the number signed or unsigned ?
bool isUnsigned = false;
// Is the number a floating-point number ?
bool isFloat = false;
// how many bits used by the number ? (32 by default)
uint bits = 32;
// Sign of the number: ' ', '+', '-'
char sign = ' ';
//! The first part of the number
uint64_t part1 = 0;
//! Second part of the number
AnyString part2; // the second part may have additional zero
};
static constexpr inline bool validNumberOfBits(uint32_t bits)
{
return bits == 32 or bits == 64 or bits == 16 or bits == 8;
}
static bool convertASTNumberToDouble(double& value, uint64 part1, const AnyString& part2, char sign)
{
if (part1 == 0 and part2.empty()) // obvious zero value
{
value = 0.;
}
else
{
ShortString128 tmp;
if (sign == '-') // append the sign of the number
tmp += '-';
tmp << part1;
if (not part2.empty())
tmp << '.' << part2;
if (unlikely(not tmp.to<double>(value)))
{
value = 0.;
return false;
}
}
return true;
}
} // anonymous namespace
template<bool BuiltinT, class DefT>
inline bool Scope::generateNumberCode(uint32_t& localvar, const DefT& numdef, const AST::Node& node)
{
// checking for invalid float values
nytype_t type = nyt_void;
// class name
AnyString cn;
uint32_t hardcodedlvid;
bool negate = false;
if (not numdef.isFloat)
{
if (not numdef.isUnsigned)
{
switch (numdef.bits)
{
case 64: type = nyt_i64; if (not BuiltinT) cn = "i64"; break;
case 32: type = nyt_i32; if (not BuiltinT) cn = "i32"; break;
case 16: type = nyt_i16; if (not BuiltinT) cn = "i16"; break;
case 8: type = nyt_i8; if (not BuiltinT) cn = "i8"; break;
}
}
else
{
switch (numdef.bits)
{
case 64: type = nyt_u64; if (not BuiltinT) cn = "u64"; break;
case 32: type = nyt_u32; if (not BuiltinT) cn = "u32"; break;
case 16: type = nyt_u16; if (not BuiltinT) cn = "u16"; break;
case 8: type = nyt_u8; if (not BuiltinT) cn = "u8"; break;
}
}
if (numdef.part1 != 0)
{
bool invalidcast = false;
negate = (numdef.sign == '-');
if (not negate)
{
if (not numdef.isUnsigned)
{
switch (numdef.bits)
{
case 64: invalidcast = (numdef.part1 > std::numeric_limits<int32_t>::max()); break;
case 32: invalidcast = (numdef.part1 > std::numeric_limits<int32_t>::max()); break;
case 16: invalidcast = (numdef.part1 > std::numeric_limits<int16_t>::max()); break;
case 8: invalidcast = (numdef.part1 > std::numeric_limits< int8_t>::max()); break;
}
}
else
{
switch (numdef.bits)
{
case 64: break;
case 32: invalidcast = (numdef.part1 > std::numeric_limits<uint32_t>::max()); break;
case 16: invalidcast = (numdef.part1 > std::numeric_limits<uint16_t>::max()); break;
case 8: invalidcast = (numdef.part1 > std::numeric_limits< uint8_t>::max()); break;
}
}
}
else
{
if (not numdef.isUnsigned)
{
if (numdef.part1 < static_cast<uint64_t>(std::numeric_limits<int64_t>::max()))
{
int64_t sv = static_cast<int64_t>(numdef.part1);
switch (numdef.bits)
{
case 64: invalidcast = (sv < std::numeric_limits<int32_t>::min()); break;
case 32: invalidcast = (sv < std::numeric_limits<int32_t>::min()); break;
case 16: invalidcast = (sv < std::numeric_limits<int16_t>::min()); break;
case 8: invalidcast = (sv < std::numeric_limits< int8_t>::min()); break;
}
}
else
invalidcast = true;
}
else
invalidcast = true;
}
if (unlikely(invalidcast))
{
error(node) << "invalid " << ((numdef.isUnsigned) ? "unsigned " : "signed ")
<< numdef.bits << "bits integer";
return false;
}
}
uint64_t number = (not negate)
? numdef.part1
: (uint64_t)( - static_cast<int64_t>(numdef.part1)); // reinterpret to avoid unwanted type promotion
hardcodedlvid = createLocalBuiltinInt(node, type, number);
}
else
{
// converting the number into a double
double value;
if (unlikely(not convertASTNumberToDouble(value, numdef.part1, numdef.part2, numdef.sign)))
return (error(node) << "invalid floating point number");
type = (numdef.bits == 32) ? nyt_f32 : nyt_f64;
if (not BuiltinT)
cn.adapt((numdef.bits == 32) ? "f32" : "f64", 3);
hardcodedlvid = createLocalBuiltinFloat(node, type, value);
}
if (BuiltinT)
{
localvar = hardcodedlvid;
return true;
}
else
{
if (!context.reuse.literal.node)
context.prepareReuseForLiterals();
assert(not cn.empty());
context.reuse.literal.classname->text = cn;
ShortString16 lvidstr;
lvidstr = hardcodedlvid;
context.reuse.literal.lvidnode->text = lvidstr;
bool success = visitASTExprNew(*(context.reuse.literal.node), localvar);
// avoid crap in the debugger
context.reuse.literal.classname->text.clear();
context.reuse.literal.lvidnode->text.clear();
return success;
}
}
bool Scope::visitASTExprNumber(const AST::Node& node, yuint32& localvar)
{
assert(node.rule == AST::rgNumber);
assert(not node.children.empty());
// Number definition
NumberDef numdef;
// is a builtin ? (__i32, __f64...)
// (always generate builtin types when not importing the NSL)
bool builtin = (not Config::importNSL);
emitDebugpos(node);
for (auto& childptr: node.children)
{
switch (childptr->rule)
{
case AST::rgNumberValue: // standard number definition
{
bool firstPart = true;
for (auto& subnodeptr: childptr->children)
{
switch (subnodeptr->rule)
{
case AST::rgInteger:
{
if (likely(firstPart))
{
if (not subnodeptr->text.to<uint64>(numdef.part1))
{
error(*subnodeptr) << "invalid integer value";
return false;
}
firstPart = false;
}
else
{
numdef.part2 = subnodeptr->text;
numdef.part2.trimRight('0'); // remove useless zeros
// as far as we know, it is a float64 by default
numdef.isFloat = true;
}
break;
}
default:
{
ice(*subnodeptr) << "[expr-number]";
return false;
}
}
}
break;
}
case AST::rgNumberSign: // + -
{
assert(not childptr->text.empty() and "invalid ast");
numdef.sign = childptr->text[0];
assert(numdef.sign == '+' or numdef.sign == '-');
break;
}
case AST::rgNumberQualifier: // unsigned / signed / float
{
for (auto& subnodeptr: childptr->children)
{
auto& subnode = *(subnodeptr);
switch (subnode.rule)
{
case AST::rgNumberQualifierType:
{
assert(not subnode.text.empty());
uint offset = 0;
if (subnode.text.first() == '_' and subnode.text[1] == '_')
{
offset = 2;
builtin = true;
}
for (uint i = offset; i < subnode.text.size(); ++i)
{
switch (subnode.text[i])
{
case 'i': numdef.isUnsigned = false; break;
case 'u': numdef.isUnsigned = true; break;
case 'f': numdef.isFloat = true; break;
default: error(node) << "invalid number qualifier. Got '"
<< subnode.text.first() << "', expected 'i', 'u' or 'f'";
}
}
break;
}
case AST::rgInteger:
{
if (likely(subnode.text.size() < 10))
{
numdef.bits = subnode.text.to<uint>();
if (unlikely(not validNumberOfBits(numdef.bits)))
return (error(subnode) << "invalid integer size");
}
else
{
error(subnode) << "integer too large";
return false;
}
break;
}
default:
{
ice(subnode) << "[expr-number]";
return false;
}
}
}
break;
}
default:
{
ice(*childptr) << "[expr-number]";
return false;
}
}
}
assert(numdef.bits == 64 or numdef.bits == 32 or numdef.bits == 16 or numdef.bits == 8);
return (not builtin)
? generateNumberCode<false>(localvar, numdef, node)
: generateNumberCode<true> (localvar, numdef, node);
}
} // namespace Producer
} // namespace IR
} // namespace Nany
<|endoftext|> |
<commit_before>//===-------------------------- SILCombine --------------------------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2015 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See http://swift.org/LICENSE.txt for license information
// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
//
// A port of LLVM's InstCombine pass to SIL. Its main purpose is for performing
// small combining operations/peepholes at the SIL level. It additionally
// performs dead code elimination when it initially adds instructions to the
// work queue in order to reduce compile time by not visiting trivially dead
// instructions.
//
//===----------------------------------------------------------------------===//
#define DEBUG_TYPE "sil-combine"
#include "swift/SILPasses/Passes.h"
#include "SILCombiner.h"
#include "swift/SIL/SILBuilder.h"
#include "swift/SIL/SILVisitor.h"
#include "swift/SILAnalysis/AliasAnalysis.h"
#include "swift/SILAnalysis/SimplifyInstruction.h"
#include "swift/SILPasses/Transforms.h"
#include "swift/SILPasses/Utils/Local.h"
#include "llvm/ADT/SmallPtrSet.h"
#include "llvm/ADT/SmallVector.h"
#include "llvm/ADT/Statistic.h"
#include "llvm/Support/Debug.h"
using namespace swift;
STATISTIC(NumSimplified, "Number of instructions simplified");
STATISTIC(NumCombined, "Number of instructions combined");
STATISTIC(NumDeadInst, "Number of dead insts eliminated");
//===----------------------------------------------------------------------===//
// Utility Methods
//===----------------------------------------------------------------------===//
/// addReachableCodeToWorklist - Walk the function in depth-first order, adding
/// all reachable code to the worklist.
///
/// This has a couple of tricks to make the code faster and more powerful. In
/// particular, we DCE instructions as we go, to avoid adding them to the
/// worklist (this significantly speeds up SILCombine on code where many
/// instructions are dead or constant).
void SILCombiner::addReachableCodeToWorklist(SILBasicBlock *BB) {
llvm::SmallVector<SILBasicBlock*, 256> Worklist;
llvm::SmallVector<SILInstruction*, 128> InstrsForSILCombineWorklist;
llvm::SmallPtrSet<SILBasicBlock*, 64> Visited;
Worklist.push_back(BB);
do {
BB = Worklist.pop_back_val();
// We have now visited this block! If we've already been here, ignore it.
if (!Visited.insert(BB).second) continue;
for (SILBasicBlock::iterator BBI = BB->begin(), E = BB->end(); BBI != E; ) {
SILInstruction *Inst = BBI++;
// DCE instruction if trivially dead.
if (isInstructionTriviallyDead(Inst)) {
++NumDeadInst;
DEBUG(llvm::dbgs() << "SC: DCE: " << *Inst << '\n');
// We pass in false here since we need to signal to
// eraseInstFromFunction to not add this instruction's operands to the
// worklist since we have not initialized the worklist yet.
//
// The reason to just use a default argument here is that it allows us
// to centralize all instruction removal in SILCombine into this one
// function. This is important if we want to be able to update analyses
// in a clean manner.
eraseInstFromFunction(*Inst, false /*Don't add operands to worklist*/);
continue;
}
InstrsForSILCombineWorklist.push_back(Inst);
}
// Recursively visit successors.
for (auto SI = BB->succ_begin(), SE = BB->succ_end(); SI != SE; ++SI)
Worklist.push_back(*SI);
} while (!Worklist.empty());
// Once we've found all of the instructions to add to the worklist, add them
// in reverse order. This way SILCombine will visit from the top of the
// function down. This jives well with the way that it adds all uses of
// instructions to the worklist after doing a transformation, thus avoiding
// some N^2 behavior in pathological cases.
addInitialGroup(InstrsForSILCombineWorklist);
}
//===----------------------------------------------------------------------===//
// Implementation
//===----------------------------------------------------------------------===//
void SILCombineWorklist::add(SILInstruction *I) {
if (!WorklistMap.insert(std::make_pair(I, Worklist.size())).second)
return;
DEBUG(llvm::dbgs() << "SC: ADD: " << *I << '\n');
Worklist.push_back(I);
}
bool SILCombiner::doOneIteration(SILFunction &F, unsigned Iteration) {
MadeChange = false;
DEBUG(llvm::dbgs() << "\n\nSILCOMBINE ITERATION #" << Iteration << " on "
<< F.getName() << "\n");
// Add reachable instructions to our worklist.
addReachableCodeToWorklist(F.begin());
// Process until we run out of items in our worklist.
while (!Worklist.isEmpty()) {
SILInstruction *I = Worklist.removeOne();
// When we erase an instruction, we use the map in the worklist to check if
// the instruction is in the worklist. If it is, we replace it with null
// instead of shifting all members of the worklist towards the front. This
// check makes sure that if we run into any such residual null pointers, we
// skip them.
if (I == 0)
continue;
// Check to see if we can DCE the instruction.
if (isInstructionTriviallyDead(I)) {
DEBUG(llvm::dbgs() << "SC: DCE: " << *I << '\n');
eraseInstFromFunction(*I);
++NumDeadInst;
MadeChange = true;
continue;
}
// Check to see if we can instsimplify the instruction.
if (SILValue Result = simplifyInstruction(I)) {
++NumSimplified;
DEBUG(llvm::dbgs() << "SC: Simplify Old = " << *I << '\n'
<< " New = " << *Result.getDef() << '\n');
// Everything uses the new instruction now.
replaceInstUsesWith(*I, Result.getDef(), 0, Result.getResultNumber());
// Push the new instruction and any users onto the worklist.
Worklist.addUsersToWorklist(Result.getDef());
eraseInstFromFunction(*I);
MadeChange = true;
continue;
}
// If we have reached this point, all attempts to do simple simplifications
// have failed. Prepare to SILCombine.
Builder->setInsertionPoint(I->getParent(), I);
#ifndef NDEBUG
std::string OrigI;
#endif
DEBUG(llvm::raw_string_ostream SS(OrigI); I->print(SS); OrigI = SS.str(););
DEBUG(llvm::dbgs() << "SC: Visiting: " << OrigI << '\n');
if (SILInstruction *Result = visit(I)) {
++NumCombined;
// Should we replace the old instruction with a new one?
if (Result != I) {
// Insert the new instruction into the basic block.
I->getParent()->getInstList().insert(I, Result);
DEBUG(llvm::dbgs() << "SC: Old = " << *I << '\n'
<< " New = " << *Result << '\n');
// Everything uses the new instruction now.
replaceInstUsesWith(*I, Result);
// Push the new instruction and any users onto the worklist.
Worklist.add(Result);
Worklist.addUsersToWorklist(Result);
eraseInstFromFunction(*I);
} else {
DEBUG(llvm::dbgs() << "SC: Mod = " << OrigI << '\n'
<< " New = " << *I << '\n');
// If the instruction was modified, it's possible that it is now dead.
// if so, remove it.
if (isInstructionTriviallyDead(I)) {
eraseInstFromFunction(*I);
} else {
Worklist.add(I);
Worklist.addUsersToWorklist(I);
}
}
MadeChange = true;
}
// Our tracking list has been accumulating instructions created by the
// SILBuilder during this iteration. Go through the tracking list and add
// its contents to the worklist and then clear said list in preparation for
// the next iteration.
for (SILInstruction *I : TrackingList)
Worklist.add(I);
TrackingList.clear();
}
Worklist.zap();
return MadeChange;
}
void SILCombineWorklist::addInitialGroup(ArrayRef<SILInstruction *> List) {
assert(Worklist.empty() && "Worklist must be empty to add initial group");
Worklist.reserve(List.size()+16);
WorklistMap.resize(List.size());
DEBUG(llvm::dbgs() << "SC: ADDING: " << List.size()
<< " instrs to worklist\n");
while (!List.empty()) {
SILInstruction *I = List.back();
List = List.slice(0, List.size()-1);
WorklistMap.insert(std::make_pair(I, Worklist.size()));
Worklist.push_back(I);
}
}
bool SILCombiner::runOnFunction(SILFunction &F) {
clear();
// Create a SILBuilder for F and initialize the tracking list.
SILBuilder B(F);
B.setTrackingList(&TrackingList);
Builder = &B;
bool Changed = false;
// Perform iterations until we do not make any changes.
while (doOneIteration(F, Iteration)) {
Changed = true;
Iteration++;
}
// Cleanup the builder and return whether or not we made any changes.
Builder = nullptr;
return Changed;
}
// Insert the instruction New before instruction Old in Old's parent BB. Add
// New to the worklist.
SILInstruction *SILCombiner::insertNewInstBefore(SILInstruction *New,
SILInstruction &Old) {
assert(New && New->getParent() == 0 &&
"New instruction already inserted into a basic block!");
SILBasicBlock *BB = Old.getParent();
BB->getInstList().insert(&Old, New); // Insert inst
Worklist.add(New);
return New;
}
// This method is to be used when an instruction is found to be dead,
// replacable with another preexisting expression. Here we add all uses of I
// to the worklist, replace all uses of I with the new value, then return I,
// so that the combiner will know that I was modified.
SILInstruction *SILCombiner::replaceInstUsesWith(SILInstruction &I,
ValueBase *V) {
Worklist.addUsersToWorklist(&I); // Add all modified instrs to worklist.
DEBUG(llvm::dbgs() << "SC: Replacing " << I << "\n"
" with " << *V << '\n');
I.replaceAllUsesWith(V);
return &I;
}
/// This is meant to be used when one is attempting to replace only one of the
/// results of I with a result of V.
SILInstruction *
SILCombiner::
replaceInstUsesWith(SILInstruction &I, ValueBase *V, unsigned IIndex,
unsigned VIndex) {
assert(IIndex < I.getNumTypes() && "Can not have more results than "
"types.");
assert(VIndex < V->getNumTypes() && "Can not have more results than "
"types.");
// Add all modified instrs to worklist.
Worklist.addUsersToWorklist(&I, IIndex);
DEBUG(llvm::dbgs() << "SC: Replacing " << I << "\n"
" with " << *V << '\n');
SILValue(&I, IIndex).replaceAllUsesWith(SILValue(V, VIndex));
return &I;
}
// Some instructions can never be "trivially dead" due to side effects or
// producing a void value. In those cases, since we can not rely on
// SILCombines trivially dead instruction DCE in order to delete the
// instruction, visit methods should use this method to delete the given
// instruction and upon completion of their peephole return the value returned
// by this method.
SILInstruction *SILCombiner::eraseInstFromFunction(SILInstruction &I,
bool AddOperandsToWorklist) {
DEBUG(llvm::dbgs() << "SC: ERASE " << I << '\n');
assert(I.use_empty() && "Cannot erase instruction that is used!");
// Make sure that we reprocess all operands now that we reduced their
// use counts.
if (I.getNumOperands() < 8 && AddOperandsToWorklist)
for (auto &OpI : I.getAllOperands())
if (SILInstruction *Op = llvm::dyn_cast<SILInstruction>(&*OpI.get()))
Worklist.add(Op);
// If we have a call graph and we've removing an apply, remove the
// associated edges from the call graph.
if (CG)
if (auto *AI = dyn_cast<ApplyInst>(&I))
CG->removeEdgesForApply(AI, true /*Ignore Missing*/);
Worklist.remove(&I);
I.eraseFromParent();
MadeChange = true;
return nullptr; // Don't do anything with I
}
//===----------------------------------------------------------------------===//
// Entry Points
//===----------------------------------------------------------------------===//
namespace {
class SILCombine : public SILFunctionTransform {
/// The entry point to the transformation.
void run() override {
auto *AA = PM->getAnalysis<AliasAnalysis>();
// Call Graph Analysis in case we need to perform Call Graph updates.
auto *CGA = PM->getAnalysis<CallGraphAnalysis>();
SILCombiner Combiner(AA, CGA->getCallGraphOrNull(),
getOptions().RemoveRuntimeAsserts);
bool Changed = Combiner.runOnFunction(*getFunction());
if (Changed) {
// Ignore invalidation messages for all analyses that we keep up to date
// manually.
CGA->lock();
// Invalidate everything else.
invalidateAnalysis(SILAnalysis::PreserveKind::Nothing);
// Unlock all of the analyses that we locked.
CGA->unlock();
}
}
StringRef getName() override { return "SIL Combine"; }
};
} // end anonymous namespace
SILTransform *swift::createSILCombine() {
return new SILCombine();
}
<commit_msg>Use correct method name. NFC.<commit_after>//===-------------------------- SILCombine --------------------------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2015 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See http://swift.org/LICENSE.txt for license information
// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
//
// A port of LLVM's InstCombine pass to SIL. Its main purpose is for performing
// small combining operations/peepholes at the SIL level. It additionally
// performs dead code elimination when it initially adds instructions to the
// work queue in order to reduce compile time by not visiting trivially dead
// instructions.
//
//===----------------------------------------------------------------------===//
#define DEBUG_TYPE "sil-combine"
#include "swift/SILPasses/Passes.h"
#include "SILCombiner.h"
#include "swift/SIL/SILBuilder.h"
#include "swift/SIL/SILVisitor.h"
#include "swift/SILAnalysis/AliasAnalysis.h"
#include "swift/SILAnalysis/SimplifyInstruction.h"
#include "swift/SILPasses/Transforms.h"
#include "swift/SILPasses/Utils/Local.h"
#include "llvm/ADT/SmallPtrSet.h"
#include "llvm/ADT/SmallVector.h"
#include "llvm/ADT/Statistic.h"
#include "llvm/Support/Debug.h"
using namespace swift;
STATISTIC(NumSimplified, "Number of instructions simplified");
STATISTIC(NumCombined, "Number of instructions combined");
STATISTIC(NumDeadInst, "Number of dead insts eliminated");
//===----------------------------------------------------------------------===//
// Utility Methods
//===----------------------------------------------------------------------===//
/// addReachableCodeToWorklist - Walk the function in depth-first order, adding
/// all reachable code to the worklist.
///
/// This has a couple of tricks to make the code faster and more powerful. In
/// particular, we DCE instructions as we go, to avoid adding them to the
/// worklist (this significantly speeds up SILCombine on code where many
/// instructions are dead or constant).
void SILCombiner::addReachableCodeToWorklist(SILBasicBlock *BB) {
llvm::SmallVector<SILBasicBlock*, 256> Worklist;
llvm::SmallVector<SILInstruction*, 128> InstrsForSILCombineWorklist;
llvm::SmallPtrSet<SILBasicBlock*, 64> Visited;
Worklist.push_back(BB);
do {
BB = Worklist.pop_back_val();
// We have now visited this block! If we've already been here, ignore it.
if (!Visited.insert(BB).second) continue;
for (SILBasicBlock::iterator BBI = BB->begin(), E = BB->end(); BBI != E; ) {
SILInstruction *Inst = BBI++;
// DCE instruction if trivially dead.
if (isInstructionTriviallyDead(Inst)) {
++NumDeadInst;
DEBUG(llvm::dbgs() << "SC: DCE: " << *Inst << '\n');
// We pass in false here since we need to signal to
// eraseInstFromFunction to not add this instruction's operands to the
// worklist since we have not initialized the worklist yet.
//
// The reason to just use a default argument here is that it allows us
// to centralize all instruction removal in SILCombine into this one
// function. This is important if we want to be able to update analyses
// in a clean manner.
eraseInstFromFunction(*Inst, false /*Don't add operands to worklist*/);
continue;
}
InstrsForSILCombineWorklist.push_back(Inst);
}
// Recursively visit successors.
for (auto SI = BB->succ_begin(), SE = BB->succ_end(); SI != SE; ++SI)
Worklist.push_back(*SI);
} while (!Worklist.empty());
// Once we've found all of the instructions to add to the worklist, add them
// in reverse order. This way SILCombine will visit from the top of the
// function down. This jives well with the way that it adds all uses of
// instructions to the worklist after doing a transformation, thus avoiding
// some N^2 behavior in pathological cases.
addInitialGroup(InstrsForSILCombineWorklist);
}
//===----------------------------------------------------------------------===//
// Implementation
//===----------------------------------------------------------------------===//
void SILCombineWorklist::add(SILInstruction *I) {
if (!WorklistMap.insert(std::make_pair(I, Worklist.size())).second)
return;
DEBUG(llvm::dbgs() << "SC: ADD: " << *I << '\n');
Worklist.push_back(I);
}
bool SILCombiner::doOneIteration(SILFunction &F, unsigned Iteration) {
MadeChange = false;
DEBUG(llvm::dbgs() << "\n\nSILCOMBINE ITERATION #" << Iteration << " on "
<< F.getName() << "\n");
// Add reachable instructions to our worklist.
addReachableCodeToWorklist(F.begin());
// Process until we run out of items in our worklist.
while (!Worklist.isEmpty()) {
SILInstruction *I = Worklist.removeOne();
// When we erase an instruction, we use the map in the worklist to check if
// the instruction is in the worklist. If it is, we replace it with null
// instead of shifting all members of the worklist towards the front. This
// check makes sure that if we run into any such residual null pointers, we
// skip them.
if (I == 0)
continue;
// Check to see if we can DCE the instruction.
if (isInstructionTriviallyDead(I)) {
DEBUG(llvm::dbgs() << "SC: DCE: " << *I << '\n');
eraseInstFromFunction(*I);
++NumDeadInst;
MadeChange = true;
continue;
}
// Check to see if we can instsimplify the instruction.
if (SILValue Result = simplifyInstruction(I)) {
++NumSimplified;
DEBUG(llvm::dbgs() << "SC: Simplify Old = " << *I << '\n'
<< " New = " << *Result.getDef() << '\n');
// Everything uses the new instruction now.
replaceInstUsesWith(*I, Result.getDef(), 0, Result.getResultNumber());
// Push the new instruction and any users onto the worklist.
Worklist.addUsersToWorklist(Result.getDef());
eraseInstFromFunction(*I);
MadeChange = true;
continue;
}
// If we have reached this point, all attempts to do simple simplifications
// have failed. Prepare to SILCombine.
Builder->setInsertionPoint(I->getParent(), I);
#ifndef NDEBUG
std::string OrigI;
#endif
DEBUG(llvm::raw_string_ostream SS(OrigI); I->print(SS); OrigI = SS.str(););
DEBUG(llvm::dbgs() << "SC: Visiting: " << OrigI << '\n');
if (SILInstruction *Result = visit(I)) {
++NumCombined;
// Should we replace the old instruction with a new one?
if (Result != I) {
// Insert the new instruction into the basic block.
I->getParent()->getInstList().insert(I, Result);
DEBUG(llvm::dbgs() << "SC: Old = " << *I << '\n'
<< " New = " << *Result << '\n');
// Everything uses the new instruction now.
replaceInstUsesWith(*I, Result);
// Push the new instruction and any users onto the worklist.
Worklist.add(Result);
Worklist.addUsersToWorklist(Result);
eraseInstFromFunction(*I);
} else {
DEBUG(llvm::dbgs() << "SC: Mod = " << OrigI << '\n'
<< " New = " << *I << '\n');
// If the instruction was modified, it's possible that it is now dead.
// if so, remove it.
if (isInstructionTriviallyDead(I)) {
eraseInstFromFunction(*I);
} else {
Worklist.add(I);
Worklist.addUsersToWorklist(I);
}
}
MadeChange = true;
}
// Our tracking list has been accumulating instructions created by the
// SILBuilder during this iteration. Go through the tracking list and add
// its contents to the worklist and then clear said list in preparation for
// the next iteration.
for (SILInstruction *I : TrackingList)
Worklist.add(I);
TrackingList.clear();
}
Worklist.zap();
return MadeChange;
}
void SILCombineWorklist::addInitialGroup(ArrayRef<SILInstruction *> List) {
assert(Worklist.empty() && "Worklist must be empty to add initial group");
Worklist.reserve(List.size()+16);
WorklistMap.resize(List.size());
DEBUG(llvm::dbgs() << "SC: ADDING: " << List.size()
<< " instrs to worklist\n");
while (!List.empty()) {
SILInstruction *I = List.back();
List = List.slice(0, List.size()-1);
WorklistMap.insert(std::make_pair(I, Worklist.size()));
Worklist.push_back(I);
}
}
bool SILCombiner::runOnFunction(SILFunction &F) {
clear();
// Create a SILBuilder for F and initialize the tracking list.
SILBuilder B(F);
B.setTrackingList(&TrackingList);
Builder = &B;
bool Changed = false;
// Perform iterations until we do not make any changes.
while (doOneIteration(F, Iteration)) {
Changed = true;
Iteration++;
}
// Cleanup the builder and return whether or not we made any changes.
Builder = nullptr;
return Changed;
}
// Insert the instruction New before instruction Old in Old's parent BB. Add
// New to the worklist.
SILInstruction *SILCombiner::insertNewInstBefore(SILInstruction *New,
SILInstruction &Old) {
assert(New && New->getParent() == 0 &&
"New instruction already inserted into a basic block!");
SILBasicBlock *BB = Old.getParent();
BB->getInstList().insert(&Old, New); // Insert inst
Worklist.add(New);
return New;
}
// This method is to be used when an instruction is found to be dead,
// replacable with another preexisting expression. Here we add all uses of I
// to the worklist, replace all uses of I with the new value, then return I,
// so that the combiner will know that I was modified.
SILInstruction *SILCombiner::replaceInstUsesWith(SILInstruction &I,
ValueBase *V) {
Worklist.addUsersToWorklist(&I); // Add all modified instrs to worklist.
DEBUG(llvm::dbgs() << "SC: Replacing " << I << "\n"
" with " << *V << '\n');
I.replaceAllUsesWith(V);
return &I;
}
/// This is meant to be used when one is attempting to replace only one of the
/// results of I with a result of V.
SILInstruction *
SILCombiner::
replaceInstUsesWith(SILInstruction &I, ValueBase *V, unsigned IIndex,
unsigned VIndex) {
assert(IIndex < I.getNumTypes() && "Can not have more results than "
"types.");
assert(VIndex < V->getNumTypes() && "Can not have more results than "
"types.");
// Add all modified instrs to worklist.
Worklist.addUsersToWorklist(&I, IIndex);
DEBUG(llvm::dbgs() << "SC: Replacing " << I << "\n"
" with " << *V << '\n');
SILValue(&I, IIndex).replaceAllUsesWith(SILValue(V, VIndex));
return &I;
}
// Some instructions can never be "trivially dead" due to side effects or
// producing a void value. In those cases, since we can not rely on
// SILCombines trivially dead instruction DCE in order to delete the
// instruction, visit methods should use this method to delete the given
// instruction and upon completion of their peephole return the value returned
// by this method.
SILInstruction *SILCombiner::eraseInstFromFunction(SILInstruction &I,
bool AddOperandsToWorklist) {
DEBUG(llvm::dbgs() << "SC: ERASE " << I << '\n');
assert(I.use_empty() && "Cannot erase instruction that is used!");
// Make sure that we reprocess all operands now that we reduced their
// use counts.
if (I.getNumOperands() < 8 && AddOperandsToWorklist)
for (auto &OpI : I.getAllOperands())
if (SILInstruction *Op = llvm::dyn_cast<SILInstruction>(&*OpI.get()))
Worklist.add(Op);
// If we have a call graph and we've removing an apply, remove the
// associated edges from the call graph.
if (CG)
if (auto *AI = dyn_cast<ApplyInst>(&I))
CG->removeEdgesForApply(AI, true /*Ignore Missing*/);
Worklist.remove(&I);
I.eraseFromParent();
MadeChange = true;
return nullptr; // Don't do anything with I
}
//===----------------------------------------------------------------------===//
// Entry Points
//===----------------------------------------------------------------------===//
namespace {
class SILCombine : public SILFunctionTransform {
/// The entry point to the transformation.
void run() override {
auto *AA = PM->getAnalysis<AliasAnalysis>();
// Call Graph Analysis in case we need to perform Call Graph updates.
auto *CGA = PM->getAnalysis<CallGraphAnalysis>();
SILCombiner Combiner(AA, CGA->getCallGraphOrNull(),
getOptions().RemoveRuntimeAsserts);
bool Changed = Combiner.runOnFunction(*getFunction());
if (Changed) {
// Ignore invalidation messages for all analyses that we keep up to date
// manually.
CGA->lockInvalidation();
// Invalidate everything else.
invalidateAnalysis(SILAnalysis::PreserveKind::Nothing);
// Unlock all of the analyses that we locked.
CGA->unlockInvalidation();
}
}
StringRef getName() override { return "SIL Combine"; }
};
} // end anonymous namespace
SILTransform *swift::createSILCombine() {
return new SILCombine();
}
<|endoftext|> |
<commit_before>/**
* @file macro_legalize.cpp
* @author Yibo Lin
* @date Jun 2018
*/
#include "utility/src/torch.h"
#include "utility/src/LegalizationDB.h"
#include "utility/src/LegalizationDBUtils.h"
#include "macro_legalize/src/hannan_legalize.h"
#include "macro_legalize/src/lp_legalize.h"
DREAMPLACE_BEGIN_NAMESPACE
/// @brief The macro legalization follows the way of floorplanning,
/// because macros have quite different sizes.
/// @return true if legal
template <typename T>
bool macroLegalizationLauncher(LegalizationDB<T> db);
#define CHECK_FLAT(x) AT_ASSERTM(!x.is_cuda() && x.ndimension() == 1, #x "must be a flat tensor on CPU")
#define CHECK_EVEN(x) AT_ASSERTM((x.numel()&1) == 0, #x "must have even number of elements")
#define CHECK_CONTIGUOUS(x) AT_ASSERTM(x.is_contiguous(), #x "must be contiguous")
/// @brief legalize layout with greedy legalization.
/// Only movable nodes will be moved. Fixed nodes and filler nodes are fixed.
///
/// @param init_pos initial locations of nodes, including movable nodes, fixed nodes, and filler nodes, [0, num_movable_nodes) are movable nodes, [num_movable_nodes, num_nodes-num_filler_nodes) are fixed nodes, [num_nodes-num_filler_nodes, num_nodes) are filler nodes
/// @param node_size_x width of nodes, including movable nodes, fixed nodes, and filler nodes, [0, num_movable_nodes) are movable nodes, [num_movable_nodes, num_nodes-num_filler_nodes) are fixed nodes, [num_nodes-num_filler_nodes, num_nodes) are filler nodes
/// @param node_size_y height of nodes, including movable nodes, fixed nodes, and filler nodes, same as node_size_x
/// @param xl left edge of bounding box of layout area
/// @param yl bottom edge of bounding box of layout area
/// @param xh right edge of bounding box of layout area
/// @param yh top edge of bounding box of layout area
/// @param site_width width of a placement site
/// @param row_height height of a placement row
/// @param num_bins_x number of bins in horizontal direction
/// @param num_bins_y number of bins in vertical direction
/// @param num_nodes total number of nodes, including movable nodes, fixed nodes, and filler nodes; fixed nodes are in the range of [num_movable_nodes, num_nodes-num_filler_nodes)
/// @param num_movable_nodes number of movable nodes, movable nodes are in the range of [0, num_movable_nodes)
/// @param number of filler nodes, filler nodes are in the range of [num_nodes-num_filler_nodes, num_nodes)
at::Tensor macro_legalization_forward(
at::Tensor init_pos,
at::Tensor pos,
at::Tensor node_size_x,
at::Tensor node_size_y,
at::Tensor flat_region_boxes,
at::Tensor flat_region_boxes_start,
at::Tensor node2fence_region_map,
double xl,
double yl,
double xh,
double yh,
double site_width, double row_height,
int num_bins_x,
int num_bins_y,
int num_movable_nodes,
int num_terminal_NIs,
int num_filler_nodes
)
{
CHECK_FLAT(init_pos);
CHECK_EVEN(init_pos);
CHECK_CONTIGUOUS(init_pos);
auto pos_copy = pos.clone();
hr_clock_rep timer_start, timer_stop;
timer_start = get_globaltime();
// Call the cuda kernel launcher
DREAMPLACE_DISPATCH_FLOATING_TYPES(pos.type(), "macroLegalizationLauncher", [&] {
auto db = make_placedb<scalar_t>(
init_pos,
pos_copy,
node_size_x,
node_size_y,
flat_region_boxes, flat_region_boxes_start, node2fence_region_map,
xl, yl, xh, yh,
site_width, row_height,
num_bins_x,
num_bins_y,
num_movable_nodes,
num_terminal_NIs,
num_filler_nodes
);
macroLegalizationLauncher<scalar_t>(db);
});
timer_stop = get_globaltime();
dreamplacePrint(kINFO, "Macro legalization takes %g ms\n", (timer_stop-timer_start)*get_timer_period());
return pos_copy;
}
template <typename T>
bool check_macro_legality(LegalizationDB<T> db, const std::vector<int>& macros, bool fast_check)
{
// check legality between movable and fixed macros
// for debug only, so it is slow
auto checkOverlap2Nodes = [&](int i, int node_id1, T xl1, T yl1, T width1, T height1, int j, int node_id2, T xl2, T yl2, T width2, T height2) {
T xh1 = xl1 + width1;
T yh1 = yl1 + height1;
T xh2 = xl2 + width2;
T yh2 = yl2 + height2;
if (std::min(xh1, xh2) > std::max(xl1, xl2) && std::min(yh1, yh2) > std::max(yl1, yl2))
{
dreamplacePrint((fast_check)? kWARN : kERROR, "macro %d (%g, %g, %g, %g) var %d overlaps with macro %d (%g, %g, %g, %g) var %d, fixed: %d\n",
node_id1, xl1, yl1, xh1, yh1, i,
node_id2, xl2, yl2, xh2, yh2, j,
(int)(node_id2 >= db.num_movable_nodes)
);
return true;
}
return false;
};
bool legal = true;
for (unsigned int i = 0, ie = macros.size(); i < ie; ++i)
{
int node_id1 = macros[i];
T xl1 = db.x[node_id1];
T yl1 = db.y[node_id1];
T width1 = db.node_size_x[node_id1];
T height1 = db.node_size_y[node_id1];
// constraints with other macros
for (unsigned int j = i+1; j < ie; ++j)
{
int node_id2 = macros[j];
T xl2 = db.x[node_id2];
T yl2 = db.y[node_id2];
T width2 = db.node_size_x[node_id2];
T height2 = db.node_size_y[node_id2];
bool overlap = checkOverlap2Nodes(i, node_id1, xl1, yl1, width1, height1, j, node_id2, xl2, yl2, width2, height2);
if (overlap)
{
legal = false;
if (fast_check)
{
return legal;
}
}
}
// constraints with fixed macros
// when considering fixed macros, there is no guarantee to find legal solution
// with current ad-hoc constraint graphs
for (int j = db.num_movable_nodes; j < db.num_nodes; ++j)
{
int node_id2 = j;
T xl2 = db.init_x[node_id2];
T yl2 = db.init_y[node_id2];
T width2 = db.node_size_x[node_id2];
T height2 = db.node_size_y[node_id2];
bool overlap = checkOverlap2Nodes(i, node_id1, xl1, yl1, width1, height1, j, node_id2, xl2, yl2, width2, height2);
if (overlap)
{
legal = false;
if (fast_check)
{
return legal;
}
}
}
}
if (legal)
{
dreamplacePrint(kDEBUG, "Macro legality check PASSED\n");
}
else
{
dreamplacePrint(kERROR, "Macro legality check FAILED\n");
}
return legal;
}
template <typename T>
T compute_displace(const LegalizationDB<T>& db, const std::vector<int>& macros)
{
T displace = 0;
for (auto node_id : macros)
{
displace += std::abs(db.init_x[node_id]-db.x[node_id]) + std::abs(db.init_y[node_id]-db.y[node_id]);
}
return displace;
}
template <typename T>
bool macroLegalizationLauncher(LegalizationDB<T> db)
{
// collect macros
std::vector<int> macros;
for (int i = 0; i < db.num_movable_nodes; ++i)
{
if (db.is_dummy_fixed(i))
{
macros.push_back(i);
#ifdef DEBUG
dreamplacePrint(kDEBUG, "macro %d %gx%g\n", i, db.node_size_x[i], db.node_size_y[i]);
#endif
}
}
dreamplacePrint(kINFO, "Macro legalization: regard %lu cells as dummy fixed (movable macros)\n", macros.size());
// in case there is no movable macros
if (macros.empty())
{
return true;
}
// first round with LP
lpLegalizeLauncher(db, macros);
dreamplacePrint(kINFO, "Macro displacement %g\n", compute_displace(db, macros));
bool legal = check_macro_legality(db, macros, true);
// try Hannan grid legalization if still not legal
if (!legal)
{
legal = hannanLegalizeLauncher(db, macros);
dreamplacePrint(kINFO, "Macro displacement %g\n", compute_displace(db, macros));
legal = check_macro_legality(db, macros, false);
// refine with LP if legal
if (legal)
{
lpLegalizeLauncher(db, macros);
dreamplacePrint(kINFO, "Macro displacement %g\n", compute_displace(db, macros));
}
}
dreamplacePrint(kINFO, "Align macros to site and rows\n");
// align the lower left corner to row and site
for (unsigned int i = 0, ie = macros.size(); i < ie; ++i)
{
int node_id = macros[i];
db.x[node_id] = db.align2site(db.x[node_id], db.node_size_x[node_id]);
db.y[node_id] = db.align2row(db.y[node_id], db.node_size_y[node_id]);
}
legal = check_macro_legality(db, macros, false);
return legal;
}
DREAMPLACE_END_NAMESPACE
PYBIND11_MODULE(TORCH_EXTENSION_NAME, m) {
m.def("forward", &DREAMPLACE_NAMESPACE::macro_legalization_forward, "Macro legalization forward");
}
<commit_msg>add try and error scheme to macro legalization<commit_after>/**
* @file macro_legalize.cpp
* @author Yibo Lin
* @date Jun 2018
*/
#include "utility/src/torch.h"
#include "utility/src/LegalizationDB.h"
#include "utility/src/LegalizationDBUtils.h"
#include "macro_legalize/src/hannan_legalize.h"
#include "macro_legalize/src/lp_legalize.h"
DREAMPLACE_BEGIN_NAMESPACE
/// @brief The macro legalization follows the way of floorplanning,
/// because macros have quite different sizes.
/// @return true if legal
template <typename T>
bool macroLegalizationLauncher(LegalizationDB<T> db);
#define CHECK_FLAT(x) AT_ASSERTM(!x.is_cuda() && x.ndimension() == 1, #x "must be a flat tensor on CPU")
#define CHECK_EVEN(x) AT_ASSERTM((x.numel()&1) == 0, #x "must have even number of elements")
#define CHECK_CONTIGUOUS(x) AT_ASSERTM(x.is_contiguous(), #x "must be contiguous")
/// @brief legalize layout with greedy legalization.
/// Only movable nodes will be moved. Fixed nodes and filler nodes are fixed.
///
/// @param init_pos initial locations of nodes, including movable nodes, fixed nodes, and filler nodes, [0, num_movable_nodes) are movable nodes, [num_movable_nodes, num_nodes-num_filler_nodes) are fixed nodes, [num_nodes-num_filler_nodes, num_nodes) are filler nodes
/// @param node_size_x width of nodes, including movable nodes, fixed nodes, and filler nodes, [0, num_movable_nodes) are movable nodes, [num_movable_nodes, num_nodes-num_filler_nodes) are fixed nodes, [num_nodes-num_filler_nodes, num_nodes) are filler nodes
/// @param node_size_y height of nodes, including movable nodes, fixed nodes, and filler nodes, same as node_size_x
/// @param xl left edge of bounding box of layout area
/// @param yl bottom edge of bounding box of layout area
/// @param xh right edge of bounding box of layout area
/// @param yh top edge of bounding box of layout area
/// @param site_width width of a placement site
/// @param row_height height of a placement row
/// @param num_bins_x number of bins in horizontal direction
/// @param num_bins_y number of bins in vertical direction
/// @param num_nodes total number of nodes, including movable nodes, fixed nodes, and filler nodes; fixed nodes are in the range of [num_movable_nodes, num_nodes-num_filler_nodes)
/// @param num_movable_nodes number of movable nodes, movable nodes are in the range of [0, num_movable_nodes)
/// @param number of filler nodes, filler nodes are in the range of [num_nodes-num_filler_nodes, num_nodes)
at::Tensor macro_legalization_forward(
at::Tensor init_pos,
at::Tensor pos,
at::Tensor node_size_x,
at::Tensor node_size_y,
at::Tensor flat_region_boxes,
at::Tensor flat_region_boxes_start,
at::Tensor node2fence_region_map,
double xl,
double yl,
double xh,
double yh,
double site_width, double row_height,
int num_bins_x,
int num_bins_y,
int num_movable_nodes,
int num_terminal_NIs,
int num_filler_nodes
)
{
CHECK_FLAT(init_pos);
CHECK_EVEN(init_pos);
CHECK_CONTIGUOUS(init_pos);
auto pos_copy = pos.clone();
hr_clock_rep timer_start, timer_stop;
timer_start = get_globaltime();
// Call the cuda kernel launcher
DREAMPLACE_DISPATCH_FLOATING_TYPES(pos.type(), "macroLegalizationLauncher", [&] {
auto db = make_placedb<scalar_t>(
init_pos,
pos_copy,
node_size_x,
node_size_y,
flat_region_boxes, flat_region_boxes_start, node2fence_region_map,
xl, yl, xh, yh,
site_width, row_height,
num_bins_x,
num_bins_y,
num_movable_nodes,
num_terminal_NIs,
num_filler_nodes
);
macroLegalizationLauncher<scalar_t>(db);
});
timer_stop = get_globaltime();
dreamplacePrint(kINFO, "Macro legalization takes %g ms\n", (timer_stop-timer_start)*get_timer_period());
return pos_copy;
}
template <typename T>
bool check_macro_legality(LegalizationDB<T> db, const std::vector<int>& macros, bool fast_check)
{
// check legality between movable and fixed macros
// for debug only, so it is slow
auto checkOverlap2Nodes = [&](int i, int node_id1, T xl1, T yl1, T width1, T height1, int j, int node_id2, T xl2, T yl2, T width2, T height2) {
T xh1 = xl1 + width1;
T yh1 = yl1 + height1;
T xh2 = xl2 + width2;
T yh2 = yl2 + height2;
if (std::min(xh1, xh2) > std::max(xl1, xl2) && std::min(yh1, yh2) > std::max(yl1, yl2))
{
dreamplacePrint((fast_check)? kWARN : kERROR, "macro %d (%g, %g, %g, %g) var %d overlaps with macro %d (%g, %g, %g, %g) var %d, fixed: %d\n",
node_id1, xl1, yl1, xh1, yh1, i,
node_id2, xl2, yl2, xh2, yh2, j,
(int)(node_id2 >= db.num_movable_nodes)
);
return true;
}
return false;
};
bool legal = true;
for (unsigned int i = 0, ie = macros.size(); i < ie; ++i)
{
int node_id1 = macros[i];
T xl1 = db.x[node_id1];
T yl1 = db.y[node_id1];
T width1 = db.node_size_x[node_id1];
T height1 = db.node_size_y[node_id1];
// constraints with other macros
for (unsigned int j = i+1; j < ie; ++j)
{
int node_id2 = macros[j];
T xl2 = db.x[node_id2];
T yl2 = db.y[node_id2];
T width2 = db.node_size_x[node_id2];
T height2 = db.node_size_y[node_id2];
bool overlap = checkOverlap2Nodes(i, node_id1, xl1, yl1, width1, height1, j, node_id2, xl2, yl2, width2, height2);
if (overlap)
{
legal = false;
if (fast_check)
{
return legal;
}
}
}
// constraints with fixed macros
// when considering fixed macros, there is no guarantee to find legal solution
// with current ad-hoc constraint graphs
for (int j = db.num_movable_nodes; j < db.num_nodes; ++j)
{
int node_id2 = j;
T xl2 = db.init_x[node_id2];
T yl2 = db.init_y[node_id2];
T width2 = db.node_size_x[node_id2];
T height2 = db.node_size_y[node_id2];
bool overlap = checkOverlap2Nodes(i, node_id1, xl1, yl1, width1, height1, j, node_id2, xl2, yl2, width2, height2);
if (overlap)
{
legal = false;
if (fast_check)
{
return legal;
}
}
}
}
if (legal)
{
dreamplacePrint(kDEBUG, "Macro legality check PASSED\n");
}
else
{
dreamplacePrint(kERROR, "Macro legality check FAILED\n");
}
return legal;
}
template <typename T>
T compute_displace(const LegalizationDB<T>& db, const std::vector<int>& macros)
{
T displace = 0;
for (auto node_id : macros)
{
displace += std::abs(db.init_x[node_id]-db.x[node_id]) + std::abs(db.init_y[node_id]-db.y[node_id]);
}
return displace;
}
template <typename T>
bool macroLegalizationLauncher(LegalizationDB<T> db)
{
// collect macros
std::vector<int> macros;
for (int i = 0; i < db.num_movable_nodes; ++i)
{
if (db.is_dummy_fixed(i))
{
macros.push_back(i);
#ifdef DEBUG
dreamplacePrint(kDEBUG, "macro %d %gx%g\n", i, db.node_size_x[i], db.node_size_y[i]);
#endif
}
}
dreamplacePrint(kINFO, "Macro legalization: regard %lu cells as dummy fixed (movable macros)\n", macros.size());
// in case there is no movable macros
if (macros.empty())
{
return true;
}
// store the best legalization solution found
std::vector<T> best_x (macros.size());
std::vector<T> best_y (macros.size());
T best_displace = std::numeric_limits<T>::max();
// update current best solution
auto update_best = [&](bool legal, T displace){
if (legal && displace < best_displace)
{
for (unsigned int i = 0, ie = macros.size(); i < ie; ++i)
{
int macro_id = macros[i];
best_x[i] = db.x[macro_id];
best_y[i] = db.y[macro_id];
}
best_displace = displace;
}
};
// first round with LP
lpLegalizeLauncher(db, macros);
dreamplacePrint(kINFO, "Macro displacement %g\n", compute_displace(db, macros));
bool legal = check_macro_legality(db, macros, true);
// try Hannan grid legalization if still not legal
if (!legal)
{
legal = hannanLegalizeLauncher(db, macros);
T displace = compute_displace(db, macros);
dreamplacePrint(kINFO, "Macro displacement %g\n", displace);
legal = check_macro_legality(db, macros, true);
update_best(legal, displace);
// refine with LP if legal
if (legal)
{
lpLegalizeLauncher(db, macros);
displace = compute_displace(db, macros);
dreamplacePrint(kINFO, "Macro displacement %g\n", displace);
legal = check_macro_legality(db, macros, true);
update_best(legal, displace);
}
}
// apply best solution
if (best_displace < std::numeric_limits<T>::max())
{
dreamplacePrint(kINFO, "use best macro displacement %g\n", best_displace);
for (unsigned int i = 0, ie = macros.size(); i < ie; ++i)
{
int macro_id = macros[i];
db.x[macro_id] = best_x[i];
db.y[macro_id] = best_y[i];
}
}
dreamplacePrint(kINFO, "Align macros to site and rows\n");
// align the lower left corner to row and site
for (unsigned int i = 0, ie = macros.size(); i < ie; ++i)
{
int node_id = macros[i];
db.x[node_id] = db.align2site(db.x[node_id], db.node_size_x[node_id]);
db.y[node_id] = db.align2row(db.y[node_id], db.node_size_y[node_id]);
}
legal = check_macro_legality(db, macros, false);
return legal;
}
DREAMPLACE_END_NAMESPACE
PYBIND11_MODULE(TORCH_EXTENSION_NAME, m) {
m.def("forward", &DREAMPLACE_NAMESPACE::macro_legalization_forward, "Macro legalization forward");
}
<|endoftext|> |
<commit_before>/*
* CompilationDatabase.cpp
*
* Copyright (C) 2009-12 by RStudio, Inc.
*
* Unless you have received this program directly from RStudio pursuant
* to the terms of a commercial license agreement with RStudio, then
* this program is licensed to you under the terms of version 3 of the
* GNU Affero General Public License. This program is distributed WITHOUT
* ANY EXPRESS OR IMPLIED WARRANTY, INCLUDING THOSE OF NON-INFRINGEMENT,
* MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE. Please refer to the
* AGPL (http://www.gnu.org/licenses/agpl-3.0.txt) for more details.
*
*/
#include "CompilationDatabase.hpp"
#include <algorithm>
#include <boost/regex.hpp>
#include <boost/algorithm/string.hpp>
#include <boost/algorithm/string/trim_all.hpp>
#include <core/Error.hpp>
#include <core/PerformanceTimer.hpp>
#include <core/FileSerializer.hpp>
#include <core/r_util/RToolsInfo.hpp>
#include <core/system/Process.hpp>
#include <core/system/Environment.hpp>
#include "LibClang.hpp"
#include "SourceIndex.hpp"
#include <session/projects/SessionProjects.hpp>
#include <session/SessionModuleContext.hpp>
using namespace core ;
namespace session {
namespace modules {
namespace clang {
namespace libclang {
namespace {
std::string readDependencyAttributes(const core::FilePath& cppPath)
{
// read file
std::string contents;
Error error = core::readStringFromFile(cppPath, &contents);
if (error)
{
LOG_ERROR(error);
return std::string();
}
// find dependency attributes
std::string attributes;
boost::regex re(
"^\\s*//\\s*\\[\\[Rcpp::(\\w+)(\\(.*?\\))?\\]\\]\\s*$");
boost::sregex_token_iterator it(contents.begin(), contents.end(), re, 0);
boost::sregex_token_iterator end;
for ( ; it != end; ++it)
{
std::string attrib = *it;
boost::algorithm::trim_all(attrib);
attributes.append(attrib);
}
// return them
return attributes;
}
std::vector<std::string> argsForSourceCpp(const core::FilePath& cppPath)
{
// get path to R script
FilePath rScriptPath;
Error error = module_context::rScriptPath(&rScriptPath);
if (error)
{
LOG_ERROR(error);
return std::vector<std::string>();
}
// setup args and options
std::vector<std::string> args;
core::system::ProcessOptions options;
// always run as a slave
args.push_back("--slave");
// setup environment to force make into --dry-run mode
core::system::Options env;
core::system::environment(&env);
core::system::setenv(&env, "MAKE", "make --dry-run");
core::system::setenv(&env, "R_MAKEVARS_USER", "");
core::system::setenv(&env, "R_MAKEVARS_SITE", "");
// for packrat projects we execute the profile and set the working
// directory to the project directory; for other contexts we just
// propagate the R_LIBS
if (module_context::packratContext().modeOn)
{
options.workingDir = projects::projectContext().directory();
args.push_back("--no-save");
args.push_back("--no-restore");
}
else
{
args.push_back("--vanilla");
std::string libPaths = module_context::libPathsString();
if (!libPaths.empty())
core::system::setenv(&env, "R_LIBS", libPaths);
}
// add rtools to path if we need to
std::string warning;
module_context::addRtoolsToPathIfNecessary(&env, &warning);
// set environment into options
options.environment = env;
// add command to arguments
args.push_back("-e");
boost::format fmt("Rcpp::sourceCpp('%1%', showOutput = TRUE)");
args.push_back(boost::str(fmt % cppPath.absolutePath()));
// execute and capture output
core::system::ProcessResult result;
error = core::system::runProgram(
core::string_utils::utf8ToSystem(rScriptPath.absolutePath()),
args,
"",
options,
&result);
if (error)
{
LOG_ERROR(error);
return std::vector<std::string>();
}
// break into lines
std::vector<std::string> lines;
boost::algorithm::split(lines, result.stdOut,
boost::algorithm::is_any_of("\r\n"));
// find the line with the compilation and add it's args
std::vector<std::string> compileArgs;
std::string compile = "-c " + cppPath.filename() + " -o " + cppPath.stem();
BOOST_FOREACH(const std::string& line, lines)
{
if (line.find(compile) != std::string::npos)
{
// find arguments libclang might care about
boost::regex re("-[I|D|i|f|s](?:\\\"[^\\\"]+\\\"|[^ ]+)");
boost::sregex_token_iterator it(line.begin(), line.end(), re, 0);
boost::sregex_token_iterator end;
for ( ; it != end; ++it)
{
// remove quotes and add it to the compile args
std::string arg = *it;
boost::algorithm::replace_all(arg, "\"", "");
compileArgs.push_back(arg);
}
break;
}
}
// return the args
return compileArgs;
}
} // anonymous namespace
CompilationDatabase::~CompilationDatabase()
{
try
{
}
catch(...)
{
}
}
void CompilationDatabase::updateForPackageCppAddition(
const core::FilePath& cppPath)
{
// if we don't have this source file already then fully update
if (argsMap_.find(cppPath.absolutePath()) == argsMap_.end())
updateForCurrentPackage();
}
void CompilationDatabase::updateForCurrentPackage()
{
}
void CompilationDatabase::updateForStandaloneCpp(const core::FilePath& cppPath)
{
TIME_FUNCTION
// if we don't have Rcpp attributes then forget it
if (!module_context::haveRcppAttributes())
return;
// read the dependency attributes within the cpp file to compare to
// previous sets of attributes we've used to generate compilation args.
// bail if we've already generated based on these attributes
std::string attributes = readDependencyAttributes(cppPath);
AttribsMap::const_iterator it = attribsMap_.find(cppPath.absolutePath());
if (it != attribsMap_.end() && it->second == attributes)
return;
// baseline arguments
std::vector<std::string> args;
std::string builtinHeaders = "-I" + clang().builtinHeaders();
args.push_back(builtinHeaders);
#if defined(_WIN32)
std::vector<std::string> rtoolsArgs = rToolsArgs();
std::copy(rtoolsArgs.begin(), rtoolsArgs.end(), std::back_inserter(args));
#elif defined(__APPLE__)
args.push_back("-stdlib=libstdc++");
#endif
// arguments for this translation unit
std::vector<std::string> fileArgs = argsForSourceCpp(cppPath);
// if we got args then update
if (!fileArgs.empty())
{
// combine them
std::copy(fileArgs.begin(), fileArgs.end(), std::back_inserter(args));
// update if necessary
updateIfNecessary(cppPath.absolutePath(), args);
// save attributes to prevent recomputation
attribsMap_[cppPath.absolutePath()] = attributes;
}
}
std::vector<std::string> CompilationDatabase::argsForFile(
const std::string& cppPath) const
{
ArgsMap::const_iterator it = argsMap_.find(cppPath);
if (it != argsMap_.end())
return it->second;
else
return std::vector<std::string>();
}
std::vector<std::string> CompilationDatabase::rToolsArgs() const
{
#ifdef _WIN32
if (rToolsArgs_.empty())
{
// scan for Rtools
std::vector<core::r_util::RToolsInfo> rTools;
Error error = core::r_util::scanRegistryForRTools(&rTools);
if (error)
LOG_ERROR(error);
// enumerate them to see if we have a compatible version
// (go in reverse order for most recent first)
std::vector<r_util::RToolsInfo>::const_reverse_iterator it = rTools.rbegin();
for ( ; it != rTools.rend(); ++it)
{
if (module_context::isRtoolsCompatible(*it))
{
FilePath rtoolsPath = it->installPath();
rToolsArgs_.push_back("-I" + rtoolsPath.childPath(
"gcc-4.6.3/i686-w64-mingw32/include").absolutePath());
rToolsArgs_.push_back("-I" + rtoolsPath.childPath(
"gcc-4.6.3/include/c++/4.6.3").absolutePath());
std::string bits = "-I" + rtoolsPath.childPath(
"gcc-4.6.3/include/c++/4.6.3/i686-w64-mingw32").absolutePath();
#ifdef _WIN64
bits += "/64";
#endif
rToolsArgs_.push_back(bits);
break;
}
}
}
#endif
return rToolsArgs_;
}
void CompilationDatabase::updateIfNecessary(
const std::string& cppPath,
const std::vector<std::string>& args)
{
// get existing args
std::vector<std::string> existingArgs = argsForFile(cppPath);
if (args != existingArgs)
{
// invalidate the source index
sourceIndex().removeTranslationUnit(cppPath);
// update
argsMap_[cppPath] = args;
}
}
CompilationDatabase& compilationDatabase()
{
static CompilationDatabase instance;
return instance;
}
} // namespace libclang
} // namespace clang
} // namespace modules
} // namesapce session
<commit_msg>use dryRun for sourcecpp<commit_after>/*
* CompilationDatabase.cpp
*
* Copyright (C) 2009-12 by RStudio, Inc.
*
* Unless you have received this program directly from RStudio pursuant
* to the terms of a commercial license agreement with RStudio, then
* this program is licensed to you under the terms of version 3 of the
* GNU Affero General Public License. This program is distributed WITHOUT
* ANY EXPRESS OR IMPLIED WARRANTY, INCLUDING THOSE OF NON-INFRINGEMENT,
* MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE. Please refer to the
* AGPL (http://www.gnu.org/licenses/agpl-3.0.txt) for more details.
*
*/
#include "CompilationDatabase.hpp"
#include <algorithm>
#include <boost/regex.hpp>
#include <boost/algorithm/string.hpp>
#include <boost/algorithm/string/trim_all.hpp>
#include <core/Error.hpp>
#include <core/PerformanceTimer.hpp>
#include <core/FileSerializer.hpp>
#include <core/r_util/RToolsInfo.hpp>
#include <core/system/Process.hpp>
#include <core/system/Environment.hpp>
#include "LibClang.hpp"
#include "SourceIndex.hpp"
#include <session/projects/SessionProjects.hpp>
#include <session/SessionModuleContext.hpp>
using namespace core ;
namespace session {
namespace modules {
namespace clang {
namespace libclang {
namespace {
std::string readDependencyAttributes(const core::FilePath& cppPath)
{
// read file
std::string contents;
Error error = core::readStringFromFile(cppPath, &contents);
if (error)
{
LOG_ERROR(error);
return std::string();
}
// find dependency attributes
std::string attributes;
boost::regex re(
"^\\s*//\\s*\\[\\[Rcpp::(\\w+)(\\(.*?\\))?\\]\\]\\s*$");
boost::sregex_token_iterator it(contents.begin(), contents.end(), re, 0);
boost::sregex_token_iterator end;
for ( ; it != end; ++it)
{
std::string attrib = *it;
boost::algorithm::trim_all(attrib);
attributes.append(attrib);
}
// return them
return attributes;
}
std::vector<std::string> argsForSourceCpp(const core::FilePath& cppPath)
{
// get path to R script
FilePath rScriptPath;
Error error = module_context::rScriptPath(&rScriptPath);
if (error)
{
LOG_ERROR(error);
return std::vector<std::string>();
}
// setup args and options
std::vector<std::string> args;
core::system::ProcessOptions options;
// always run as a slave
args.push_back("--slave");
// setup environment to force make into --dry-run mode
core::system::Options env;
core::system::environment(&env);
core::system::setenv(&env, "MAKE", "make --dry-run");
core::system::setenv(&env, "R_MAKEVARS_USER", "");
core::system::setenv(&env, "R_MAKEVARS_SITE", "");
// for packrat projects we execute the profile and set the working
// directory to the project directory; for other contexts we just
// propagate the R_LIBS
if (module_context::packratContext().modeOn)
{
options.workingDir = projects::projectContext().directory();
args.push_back("--no-save");
args.push_back("--no-restore");
}
else
{
args.push_back("--vanilla");
std::string libPaths = module_context::libPathsString();
if (!libPaths.empty())
core::system::setenv(&env, "R_LIBS", libPaths);
}
// add rtools to path if we need to
std::string warning;
module_context::addRtoolsToPathIfNecessary(&env, &warning);
// set environment into options
options.environment = env;
// add command to arguments
args.push_back("-e");
boost::format fmt("Rcpp::sourceCpp('%1%', showOutput = TRUE, dryRun = TRUE)");
args.push_back(boost::str(fmt % cppPath.absolutePath()));
// execute and capture output
core::system::ProcessResult result;
error = core::system::runProgram(
core::string_utils::utf8ToSystem(rScriptPath.absolutePath()),
args,
"",
options,
&result);
if (error)
{
LOG_ERROR(error);
return std::vector<std::string>();
}
// break into lines
std::vector<std::string> lines;
boost::algorithm::split(lines, result.stdOut,
boost::algorithm::is_any_of("\r\n"));
// find the line with the compilation and add it's args
std::vector<std::string> compileArgs;
std::string compile = "-c " + cppPath.filename() + " -o " + cppPath.stem();
BOOST_FOREACH(const std::string& line, lines)
{
if (line.find(compile) != std::string::npos)
{
// find arguments libclang might care about
boost::regex re("-[I|D|i|f|s](?:\\\"[^\\\"]+\\\"|[^ ]+)");
boost::sregex_token_iterator it(line.begin(), line.end(), re, 0);
boost::sregex_token_iterator end;
for ( ; it != end; ++it)
{
// remove quotes and add it to the compile args
std::string arg = *it;
boost::algorithm::replace_all(arg, "\"", "");
compileArgs.push_back(arg);
}
break;
}
}
// return the args
return compileArgs;
}
} // anonymous namespace
CompilationDatabase::~CompilationDatabase()
{
try
{
}
catch(...)
{
}
}
void CompilationDatabase::updateForPackageCppAddition(
const core::FilePath& cppPath)
{
// if we don't have this source file already then fully update
if (argsMap_.find(cppPath.absolutePath()) == argsMap_.end())
updateForCurrentPackage();
}
void CompilationDatabase::updateForCurrentPackage()
{
}
void CompilationDatabase::updateForStandaloneCpp(const core::FilePath& cppPath)
{
TIME_FUNCTION
// if we don't have a recent version of Rcpp (that can do dryRun with
// sourceCpp) then forget it
if (!module_context::isPackageVersionInstalled("Rcpp", "0.11.2.7"))
return;
// read the dependency attributes within the cpp file to compare to
// previous sets of attributes we've used to generate compilation args.
// bail if we've already generated based on these attributes
std::string attributes = readDependencyAttributes(cppPath);
AttribsMap::const_iterator it = attribsMap_.find(cppPath.absolutePath());
if (it != attribsMap_.end() && it->second == attributes)
return;
// baseline arguments
std::vector<std::string> args;
std::string builtinHeaders = "-I" + clang().builtinHeaders();
args.push_back(builtinHeaders);
#if defined(_WIN32)
std::vector<std::string> rtoolsArgs = rToolsArgs();
std::copy(rtoolsArgs.begin(), rtoolsArgs.end(), std::back_inserter(args));
#elif defined(__APPLE__)
args.push_back("-stdlib=libstdc++");
#endif
// arguments for this translation unit
std::vector<std::string> fileArgs = argsForSourceCpp(cppPath);
// if we got args then update
if (!fileArgs.empty())
{
// combine them
std::copy(fileArgs.begin(), fileArgs.end(), std::back_inserter(args));
// update if necessary
updateIfNecessary(cppPath.absolutePath(), args);
// save attributes to prevent recomputation
attribsMap_[cppPath.absolutePath()] = attributes;
}
}
std::vector<std::string> CompilationDatabase::argsForFile(
const std::string& cppPath) const
{
ArgsMap::const_iterator it = argsMap_.find(cppPath);
if (it != argsMap_.end())
return it->second;
else
return std::vector<std::string>();
}
std::vector<std::string> CompilationDatabase::rToolsArgs() const
{
#ifdef _WIN32
if (rToolsArgs_.empty())
{
// scan for Rtools
std::vector<core::r_util::RToolsInfo> rTools;
Error error = core::r_util::scanRegistryForRTools(&rTools);
if (error)
LOG_ERROR(error);
// enumerate them to see if we have a compatible version
// (go in reverse order for most recent first)
std::vector<r_util::RToolsInfo>::const_reverse_iterator it = rTools.rbegin();
for ( ; it != rTools.rend(); ++it)
{
if (module_context::isRtoolsCompatible(*it))
{
FilePath rtoolsPath = it->installPath();
rToolsArgs_.push_back("-I" + rtoolsPath.childPath(
"gcc-4.6.3/i686-w64-mingw32/include").absolutePath());
rToolsArgs_.push_back("-I" + rtoolsPath.childPath(
"gcc-4.6.3/include/c++/4.6.3").absolutePath());
std::string bits = "-I" + rtoolsPath.childPath(
"gcc-4.6.3/include/c++/4.6.3/i686-w64-mingw32").absolutePath();
#ifdef _WIN64
bits += "/64";
#endif
rToolsArgs_.push_back(bits);
break;
}
}
}
#endif
return rToolsArgs_;
}
void CompilationDatabase::updateIfNecessary(
const std::string& cppPath,
const std::vector<std::string>& args)
{
// get existing args
std::vector<std::string> existingArgs = argsForFile(cppPath);
if (args != existingArgs)
{
// invalidate the source index
sourceIndex().removeTranslationUnit(cppPath);
// update
argsMap_[cppPath] = args;
}
}
CompilationDatabase& compilationDatabase()
{
static CompilationDatabase instance;
return instance;
}
} // namespace libclang
} // namespace clang
} // namespace modules
} // namesapce session
<|endoftext|> |
<commit_before>/*************************************************************************
*
* $RCSfile: AdabasStatDlg.cxx,v $
*
* $Revision: 1.4 $
*
* last change: $Author: vg $ $Date: 2005-02-21 12:40: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 EXPRESS 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): Ocke Janssen
*
*
************************************************************************/
#ifndef DBAUI_ADABASSTATDLG_HXX
#include "AdabasStatDlg.hxx"
#endif
#ifndef DBAUI_ADABASSTATDLG_HRC
#include "AdabasStatDlg.hrc"
#endif
#ifndef _DBU_DLG_HRC_
#include "dbu_dlg.hrc"
#endif
#ifndef _DBAUI_MODULE_DBU_HXX_
#include "moduledbu.hxx"
#endif
#ifndef _DBAUI_DATASOURCEITEMS_HXX_
#include "dsitems.hxx"
#endif
#ifndef _SFXSTRITEM_HXX
#include <svtools/stritem.hxx>
#endif
#ifndef _SFXENUMITEM_HXX
#include <svtools/eitem.hxx>
#endif
#ifndef _SFXINTITEM_HXX
#include <svtools/intitem.hxx>
#endif
#ifndef _VCL_STDTEXT_HXX
#include <vcl/stdtext.hxx>
#endif
#ifndef _SV_MSGBOX_HXX
#include <vcl/msgbox.hxx>
#endif
#ifndef _DBAUI_DATASOURCEITEMS_HXX_
#include "dsitems.hxx"
#endif
#ifndef DBAUI_DRIVERSETTINGS_HXX
#include "DriverSettings.hxx"
#endif
#ifndef _DBAUI_DBADMINIMPL_HXX_
#include "DbAdminImpl.hxx"
#endif
#ifndef _DBAUI_PROPERTYSETITEM_HXX_
#include "propertysetitem.hxx"
#endif
#ifndef _DBAUI_ADMINPAGES_HXX_
#include "adminpages.hxx"
#endif
#ifndef DBAUI_ADABASPAGE_HXX
#include "AdabasPage.hxx"
#endif
//.........................................................................
namespace dbaui
{
//.........................................................................
using namespace ::com::sun::star::uno;
using namespace ::com::sun::star::beans;
using namespace ::com::sun::star::lang;
using namespace ::com::sun::star::sdbc;
//========================================================================
//= OAdabasStatPageDlg
//========================================================================
OAdabasStatPageDlg::OAdabasStatPageDlg(Window* _pParent
, SfxItemSet* _pItems
,const Reference< XMultiServiceFactory >& _rxORB
,const ::com::sun::star::uno::Any& _aDataSourceName)
:SfxTabDialog(_pParent, ModuleRes(DLG_DATABASE_ADABASADMIN), _pItems)
{
m_pImpl = ::std::auto_ptr<ODbDataSourceAdministrationHelper>(new ODbDataSourceAdministrationHelper(_rxORB,_pParent,this));
m_pImpl->setCurrentDataSourceName(_aDataSourceName);
Reference< XPropertySet > xDatasource = m_pImpl->getCurrentDataSource();
m_pImpl->translateProperties(xDatasource, *GetInputSetImpl());
SetInputSet(GetInputSetImpl());
// propagate this set as our new input set and reset the example set
delete pExampleSet;
pExampleSet = new SfxItemSet(*GetInputSetImpl());
DATASOURCE_TYPE eType = m_pImpl->getDatasourceType(*GetInputSetImpl());
switch ( eType )
{
case DST_ADABAS:
AddTabPage(TAB_PAG_ADABAS_SETTINGS, String(ResId(STR_PAGETITLE_ADABAS_STATISTIC)), ODriversSettings::CreateAdabas,0, sal_False, 1);
break;
case DST_DBASE:
case DST_FLAT:
case DST_MSACCESS:
case DST_ADO:
case DST_ODBC:
case DST_MYSQL_ODBC:
case DST_MYSQL_JDBC:
case DST_LDAP:
case DST_CALC:
case DST_MOZILLA:
case DST_THUNDERBIRD:
case DST_EVOLUTION:
case DST_OUTLOOK :
case DST_OUTLOOKEXP:
case DST_JDBC:
case DST_ORACLE_JDBC:
case DST_USERDEFINE1: /// first user defined driver
case DST_USERDEFINE2:
case DST_USERDEFINE3:
case DST_USERDEFINE4:
case DST_USERDEFINE5:
case DST_USERDEFINE6:
case DST_USERDEFINE7:
case DST_USERDEFINE8:
case DST_USERDEFINE9:
case DST_USERDEFINE10:
default:
OSL_ENSURE(0,"Not supported for other types thasn adabas!");
break;
}
// remove the reset button - it's meaning is much too ambiguous in this dialog
RemoveResetButton();
FreeResource();
}
// -----------------------------------------------------------------------
OAdabasStatPageDlg::~OAdabasStatPageDlg()
{
SetInputSet(NULL);
DELETEZ(pExampleSet);
}
// -----------------------------------------------------------------------
short OAdabasStatPageDlg::Execute()
{
short nRet = SfxTabDialog::Execute();
if ( nRet == RET_OK )
{
pExampleSet->Put(*GetOutputItemSet());
m_pImpl->saveChanges(*pExampleSet);
}
return nRet;
}
//-------------------------------------------------------------------------
void OAdabasStatPageDlg::PageCreated(USHORT _nId, SfxTabPage& _rPage)
{
// register ourself as modified listener
static_cast<OGenericAdministrationPage&>(_rPage).SetServiceFactory(m_pImpl->getORB());
static_cast<OGenericAdministrationPage&>(_rPage).SetAdminDialog(this,this);
AdjustLayout();
Window *pWin = GetViewWindow();
if(pWin)
pWin->Invalidate();
SfxTabDialog::PageCreated(_nId, _rPage);
}
// -----------------------------------------------------------------------------
const SfxItemSet* OAdabasStatPageDlg::getOutputSet() const
{
return GetExampleSet();
}
// -----------------------------------------------------------------------------
SfxItemSet* OAdabasStatPageDlg::getWriteOutputSet()
{
return pExampleSet;
}
// -----------------------------------------------------------------------------
::std::pair< Reference<XConnection>,sal_Bool> OAdabasStatPageDlg::createConnection()
{
return m_pImpl->createConnection();
}
// -----------------------------------------------------------------------------
Reference< XMultiServiceFactory > OAdabasStatPageDlg::getORB()
{
return m_pImpl->getORB();
}
// -----------------------------------------------------------------------------
Reference< XDriver > OAdabasStatPageDlg::getDriver()
{
return m_pImpl->getDriver();
}
// -----------------------------------------------------------------------------
DATASOURCE_TYPE OAdabasStatPageDlg::getDatasourceType(const SfxItemSet& _rSet) const
{
return m_pImpl->getDatasourceType(_rSet);
}
// -----------------------------------------------------------------------------
void OAdabasStatPageDlg::clearPassword()
{
m_pImpl->clearPassword();
}
// -----------------------------------------------------------------------------
void OAdabasStatPageDlg::setTitle(const ::rtl::OUString& _sTitle)
{
SetText(_sTitle);
}
//-------------------------------------------------------------------------
sal_Bool OAdabasStatPageDlg::saveDatasource()
{
return PrepareLeaveCurrentPage();
}
//.........................................................................
} // namespace dbaui
//.........................................................................
<commit_msg>INTEGRATION: CWS wizopendb (1.4.60); FILE MERGED 2005/06/06 10:40:38 fs 1.4.60.1: #i42477# allow the 'New Database' wizard to load existing documents<commit_after>/*************************************************************************
*
* $RCSfile: AdabasStatDlg.cxx,v $
*
* $Revision: 1.5 $
*
* last change: $Author: kz $ $Date: 2005-06-30 16:30:03 $
*
* The Contents of this file are made available subject to the terms of
* either of the following licenses
*
* - GNU Lesser General Public License Version 2.1
* - Sun Industry Standards Source License Version 1.1
*
* Sun Microsystems Inc., October, 2000
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2000 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
*
* Sun Industry Standards Source License Version 1.1
* =================================================
* The contents of this file are subject to the Sun Industry Standards
* Source License Version 1.1 (the "License"); You may not use this file
* except in compliance with the License. You may obtain a copy of the
* License at http://www.openoffice.org/license.html.
*
* Software provided under this License is provided on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESS 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): Ocke Janssen
*
*
************************************************************************/
#ifndef DBAUI_ADABASSTATDLG_HXX
#include "AdabasStatDlg.hxx"
#endif
#ifndef DBAUI_ADABASSTATDLG_HRC
#include "AdabasStatDlg.hrc"
#endif
#ifndef _DBU_DLG_HRC_
#include "dbu_dlg.hrc"
#endif
#ifndef _DBAUI_MODULE_DBU_HXX_
#include "moduledbu.hxx"
#endif
#ifndef _DBAUI_DATASOURCEITEMS_HXX_
#include "dsitems.hxx"
#endif
#ifndef _SFXSTRITEM_HXX
#include <svtools/stritem.hxx>
#endif
#ifndef _SFXENUMITEM_HXX
#include <svtools/eitem.hxx>
#endif
#ifndef _SFXINTITEM_HXX
#include <svtools/intitem.hxx>
#endif
#ifndef _VCL_STDTEXT_HXX
#include <vcl/stdtext.hxx>
#endif
#ifndef _SV_MSGBOX_HXX
#include <vcl/msgbox.hxx>
#endif
#ifndef _DBAUI_DATASOURCEITEMS_HXX_
#include "dsitems.hxx"
#endif
#ifndef DBAUI_DRIVERSETTINGS_HXX
#include "DriverSettings.hxx"
#endif
#ifndef _DBAUI_DBADMINIMPL_HXX_
#include "DbAdminImpl.hxx"
#endif
#ifndef _DBAUI_PROPERTYSETITEM_HXX_
#include "propertysetitem.hxx"
#endif
#ifndef _DBAUI_ADMINPAGES_HXX_
#include "adminpages.hxx"
#endif
#ifndef DBAUI_ADABASPAGE_HXX
#include "AdabasPage.hxx"
#endif
//.........................................................................
namespace dbaui
{
//.........................................................................
using namespace ::com::sun::star::uno;
using namespace ::com::sun::star::beans;
using namespace ::com::sun::star::lang;
using namespace ::com::sun::star::sdbc;
//========================================================================
//= OAdabasStatPageDlg
//========================================================================
OAdabasStatPageDlg::OAdabasStatPageDlg(Window* _pParent
, SfxItemSet* _pItems
,const Reference< XMultiServiceFactory >& _rxORB
,const ::com::sun::star::uno::Any& _aDataSourceName)
:SfxTabDialog(_pParent, ModuleRes(DLG_DATABASE_ADABASADMIN), _pItems)
{
m_pImpl = ::std::auto_ptr<ODbDataSourceAdministrationHelper>(new ODbDataSourceAdministrationHelper(_rxORB,_pParent,this));
m_pImpl->setDataSourceOrName(_aDataSourceName);
Reference< XPropertySet > xDatasource = m_pImpl->getCurrentDataSource();
m_pImpl->translateProperties(xDatasource, *GetInputSetImpl());
SetInputSet(GetInputSetImpl());
// propagate this set as our new input set and reset the example set
delete pExampleSet;
pExampleSet = new SfxItemSet(*GetInputSetImpl());
DATASOURCE_TYPE eType = m_pImpl->getDatasourceType(*GetInputSetImpl());
switch ( eType )
{
case DST_ADABAS:
AddTabPage(TAB_PAG_ADABAS_SETTINGS, String(ResId(STR_PAGETITLE_ADABAS_STATISTIC)), ODriversSettings::CreateAdabas,0, sal_False, 1);
break;
case DST_DBASE:
case DST_FLAT:
case DST_MSACCESS:
case DST_ADO:
case DST_ODBC:
case DST_MYSQL_ODBC:
case DST_MYSQL_JDBC:
case DST_LDAP:
case DST_CALC:
case DST_MOZILLA:
case DST_THUNDERBIRD:
case DST_EVOLUTION:
case DST_OUTLOOK :
case DST_OUTLOOKEXP:
case DST_JDBC:
case DST_ORACLE_JDBC:
case DST_USERDEFINE1: /// first user defined driver
case DST_USERDEFINE2:
case DST_USERDEFINE3:
case DST_USERDEFINE4:
case DST_USERDEFINE5:
case DST_USERDEFINE6:
case DST_USERDEFINE7:
case DST_USERDEFINE8:
case DST_USERDEFINE9:
case DST_USERDEFINE10:
default:
OSL_ENSURE(0,"Not supported for other types thasn adabas!");
break;
}
// remove the reset button - it's meaning is much too ambiguous in this dialog
RemoveResetButton();
FreeResource();
}
// -----------------------------------------------------------------------
OAdabasStatPageDlg::~OAdabasStatPageDlg()
{
SetInputSet(NULL);
DELETEZ(pExampleSet);
}
// -----------------------------------------------------------------------
short OAdabasStatPageDlg::Execute()
{
short nRet = SfxTabDialog::Execute();
if ( nRet == RET_OK )
{
pExampleSet->Put(*GetOutputItemSet());
m_pImpl->saveChanges(*pExampleSet);
}
return nRet;
}
//-------------------------------------------------------------------------
void OAdabasStatPageDlg::PageCreated(USHORT _nId, SfxTabPage& _rPage)
{
// register ourself as modified listener
static_cast<OGenericAdministrationPage&>(_rPage).SetServiceFactory(m_pImpl->getORB());
static_cast<OGenericAdministrationPage&>(_rPage).SetAdminDialog(this,this);
AdjustLayout();
Window *pWin = GetViewWindow();
if(pWin)
pWin->Invalidate();
SfxTabDialog::PageCreated(_nId, _rPage);
}
// -----------------------------------------------------------------------------
const SfxItemSet* OAdabasStatPageDlg::getOutputSet() const
{
return GetExampleSet();
}
// -----------------------------------------------------------------------------
SfxItemSet* OAdabasStatPageDlg::getWriteOutputSet()
{
return pExampleSet;
}
// -----------------------------------------------------------------------------
::std::pair< Reference<XConnection>,sal_Bool> OAdabasStatPageDlg::createConnection()
{
return m_pImpl->createConnection();
}
// -----------------------------------------------------------------------------
Reference< XMultiServiceFactory > OAdabasStatPageDlg::getORB()
{
return m_pImpl->getORB();
}
// -----------------------------------------------------------------------------
Reference< XDriver > OAdabasStatPageDlg::getDriver()
{
return m_pImpl->getDriver();
}
// -----------------------------------------------------------------------------
DATASOURCE_TYPE OAdabasStatPageDlg::getDatasourceType(const SfxItemSet& _rSet) const
{
return m_pImpl->getDatasourceType(_rSet);
}
// -----------------------------------------------------------------------------
void OAdabasStatPageDlg::clearPassword()
{
m_pImpl->clearPassword();
}
// -----------------------------------------------------------------------------
void OAdabasStatPageDlg::setTitle(const ::rtl::OUString& _sTitle)
{
SetText(_sTitle);
}
//-------------------------------------------------------------------------
sal_Bool OAdabasStatPageDlg::saveDatasource()
{
return PrepareLeaveCurrentPage();
}
//.........................................................................
} // namespace dbaui
//.........................................................................
<|endoftext|> |
<commit_before>/*************************************************************************
*
* $RCSfile: VertSplitView.hxx,v $
*
* $Revision: 1.3 $
*
* last change: $Author: vg $ $Date: 2005-03-10 16:51:01 $
*
* The Contents of this file are made available subject to the terms of
* either of the following licenses
*
* - GNU Lesser General Public License Version 2.1
* - Sun Industry Standards Source License Version 1.1
*
* Sun Microsystems Inc., October, 2000
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2000 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
*
* Sun Industry Standards Source License Version 1.1
* =================================================
* The contents of this file are subject to the Sun Industry Standards
* Source License Version 1.1 (the License); You may not use this file
* except in compliance with the License. You may obtain a copy of the
* License at http://www.openoffice.org/license.html.
*
* Software provided under this License is provided on an AS IS basis,
* WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
* WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
* MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
* See the License for the specific provisions governing your rights and
* obligations concerning the Software.
*
* The Initial Developer of the Original Code is: Sun Microsystems, Inc.
*
* Copyright: 2000 by Sun Microsystems, Inc.
*
* All Rights Reserved.
*
* Contributor(s): Ocke Janssen
*
*
************************************************************************/
#ifndef DBAUI_VERTSPLITVIEW_HXX
#define DBAUI_VERTSPLITVIEW_HXX
#ifndef _SV_SPLIT_HXX
#include <vcl/split.hxx>
#endif
namespace dbaui
{
//==================================================================
class OSplitterView : public Window
{
Splitter* m_pSplitter;
Window* m_pLeft;
Window* m_pRight;
sal_Bool m_bVertical;
void ImplInitSettings( BOOL bFont, BOOL bForeground, BOOL bBackground );
DECL_LINK( SplitHdl, Splitter* );
protected:
virtual void DataChanged(const DataChangedEvent& rDCEvt);
public:
OSplitterView(Window* _pParent,sal_Bool _bVertical = sal_True);
virtual ~OSplitterView();
// window overloads
virtual void GetFocus();
void setSplitter(Splitter* _pSplitter);
void set(Window* _pRight,Window* _pLeft = NULL);
virtual void Resize();
};
}
#endif // DBAUI_VERTSPLITVIEW_HXX
<commit_msg>INTEGRATION: CWS ooo19126 (1.3.104); FILE MERGED 2005/09/05 17:34:32 rt 1.3.104.1: #i54170# Change license header: remove SISSL<commit_after>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: VertSplitView.hxx,v $
*
* $Revision: 1.4 $
*
* last change: $Author: rt $ $Date: 2005-09-08 15:41:29 $
*
* The Contents of this file are made available subject to
* the terms of GNU Lesser General Public License Version 2.1.
*
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2005 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
************************************************************************/
#ifndef DBAUI_VERTSPLITVIEW_HXX
#define DBAUI_VERTSPLITVIEW_HXX
#ifndef _SV_SPLIT_HXX
#include <vcl/split.hxx>
#endif
namespace dbaui
{
//==================================================================
class OSplitterView : public Window
{
Splitter* m_pSplitter;
Window* m_pLeft;
Window* m_pRight;
sal_Bool m_bVertical;
void ImplInitSettings( BOOL bFont, BOOL bForeground, BOOL bBackground );
DECL_LINK( SplitHdl, Splitter* );
protected:
virtual void DataChanged(const DataChangedEvent& rDCEvt);
public:
OSplitterView(Window* _pParent,sal_Bool _bVertical = sal_True);
virtual ~OSplitterView();
// window overloads
virtual void GetFocus();
void setSplitter(Splitter* _pSplitter);
void set(Window* _pRight,Window* _pLeft = NULL);
virtual void Resize();
};
}
#endif // DBAUI_VERTSPLITVIEW_HXX
<|endoftext|> |
<commit_before>/*
* Funambol is a mobile platform developed by Funambol, Inc.
* Copyright (C) 2003 - 2007 Funambol, Inc.
*
* This program is free software; you can redistribute it and/or modify it under
* the terms of the GNU Affero General Public License version 3 as published by
* the Free Software Foundation with the addition of the following permission
* added to Section 15 as permitted in Section 7(a): FOR ANY PART OF THE COVERED
* WORK IN WHICH THE COPYRIGHT IS OWNED BY FUNAMBOL, FUNAMBOL DISCLAIMS THE
* WARRANTY OF NON INFRINGEMENT OF THIRD PARTY RIGHTS.
*
* 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, see http://www.gnu.org/licenses or write to
* the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
* MA 02110-1301 USA.
*
* You can contact Funambol, Inc. headquarters at 643 Bair Island Road, Suite
* 305, Redwood City, CA 94063, USA, or at email address [email protected].
*
* The interactive user interfaces in modified source and object code versions
* of this program must display Appropriate Legal Notices, as required under
* Section 5 of the GNU Affero General Public License version 3.
*
* In accordance with Section 7(b) of the GNU Affero General Public License
* version 3, these Appropriate Legal Notices must retain the display of the
* "Powered by Funambol" logo. If the display of the logo is not reasonably
* feasible for technical reasons, the Appropriate Legal Notices must display
* the words "Powered by Funambol".
*/
#include "push/FSocket.h"
#include "base/SymbianLog.h"
#include "base/util/stringUtils.h"
#include "base/util/symbianUtils.h"
#include "base/FConnection.h"
#include "base/globalsdef.h"
USE_NAMESPACE
StringBuffer FSocket::lIP;
FSocket* FSocket::createSocket(const StringBuffer& peer, int32_t port)
{
return FSocket::NewL(peer, port);
}
FSocket* FSocket::NewL(const StringBuffer& peer, int32_t port)
{
FSocket* self = FSocket::NewLC(peer, port);
CleanupStack::Pop( self );
return self;
}
FSocket* FSocket::NewLC(const StringBuffer& peer, int32_t port)
{
FSocket* self = new ( ELeave ) FSocket();
CleanupStack::PushL( self );
self->ConstructL(peer, port);
if (self->getLastStatus() != KErrNone) {
// Something wrong.
delete self;
return NULL;
}
return self;
}
void FSocket::ConstructL(const StringBuffer& peer, int32_t port)
{
//LOG.debug("FSocket::ConstructL");
StringBuffer errorMsg;
RHostResolver resolver;
RBuf serverName;
TNameEntry hostAddress;
TInetAddr address;
serverName.Assign(stringBufferToNewBuf(peer));
//
// Get the connection manager instance
//
FConnection* connection = FConnection::getInstance();
if (!connection) {
iStatus = -1;
errorMsg = "Error opening connection";
goto error;
}
// Session is owned by FConnection!
RSocketServ* session = connection->getSession();
//
// Open the Client Socket tcp/ip
//
#ifdef __WINSCW__
// WINSCW: simply open the socket
TInt res = iSocket.Open(*session, KAfInet, KSockStream, KProtocolInetTcp);
#else
// GCCE: use the existing connection
// If first time, connect to gprs
if (!connection->isConnected()) {
LOG.debug("Starting connection");
// TODO: remove the iap name: it's already set inside FConnection
connection->startConnection("Ask");
}
RConnection* conn = connection->getConnection();
LOG.debug("Opening socket and associate with existing connection");
TInt res = iSocket.Open(*session, KAfInet, KSockStream, KProtocolInetTcp, *conn);
LOG.debug("Socket opened (err = %d)", res);
#endif
if (res != KErrNone) {
iStatus = -1;
errorMsg = "Error opening socket";
goto error;
}
// This works if serverName is the ip address, like "x.y.z.w"
res = address.Input(serverName);
if (res != KErrNone) {
// Try to resolve the host address
LOG.debug("resolve IP address...");
res = resolver.Open(*session, KAfInet, KProtocolInetTcp);
if (res != KErrNone) {
iStatus = -2;
errorMsg = "Host resolver open failed";
goto error;
}
resolver.GetByName(serverName, hostAddress, iStatus);
User::WaitForRequest(iStatus);
resolver.Close();
if (iStatus != KErrNone) {
errorMsg = "DNS lookup failed";
goto error;
}
// Set the socket server address/port
address = hostAddress().iAddr;
}
address.SetPort(port);
// --- Connect to host ---
LOG.debug("Socket connect...");
iSocket.Connect(address, iStatus);
User::WaitForRequest(iStatus);
if (iStatus != KErrNone) {
errorMsg = "Failed to connect to Server";
goto error;
}
return;
error:
LOG.error(errorMsg.c_str());
return;
}
FSocket::FSocket()
{
iStatus = 0;
}
FSocket::~FSocket()
{
close();
}
int32_t FSocket::writeBuffer(const int8_t* buffer, int32_t len)
{
// This doesn't copy the buffer in memory.
TPtr8 data((TUint8*)buffer, len);
data.SetLength(len);
// Sends data to the remote host.
iSocket.Write(data, iStatus);
User::WaitForRequest(iStatus);
if (iStatus == KErrNone) {
return len;
}
else {
LOG.error("FSocket: error writing on socket (status = %d)", iStatus.Int());
return -1;
}
}
int32_t FSocket::readBuffer(int8_t* buffer, int32_t maxLen)
{
RBuf8 data;
data.CreateL(maxLen);
// Receives data from a remote host and completes when data is available.
TSockXfrLength len;
iSocket.RecvOneOrMore(data, 0, iStatus, len);
User::WaitForRequest(iStatus);
TInt msgLen = len();
if (iStatus == KErrNone) {
if (msgLen <= maxLen) {
// OK. Copy the message into the preallocated buffer.
memcpy(buffer, data.Ptr(), msgLen);
return msgLen;
}
else {
LOG.error("FSocket: error reading, message too big (%d > %d) -> rejected.", msgLen, maxLen);
iStatus = -1;
return -1;
}
}
else if (iStatus == KErrEof) {
// Either the remote connection is closed, or the socket has been shutdown.
LOG.info("FSocket: read interrupted (connection closed)");
buffer = NULL;
return -1;
}
else {
LOG.error("FSocket: error reading on socket (status = %d)", iStatus.Int());
buffer = NULL;
return -1;
}
}
void FSocket::close()
{
//LOG.debug("FSocket::close");
// TODO: shutdown if I/O in progress?
//iSocket.Shutdown(RSocket::EImmediate, iStatus);
iSocket.CancelAll();
iSocket.Close();
}
const StringBuffer& FSocket::address() const {
return lAddress;
}
const StringBuffer& FSocket::peerAddress() const {
return pAddress;
}
const StringBuffer& FSocket::localIP() {
return lIP;
}
<commit_msg>Starts connection (if not connected) using the default IAP. It can be set previously in FConnection class.<commit_after>/*
* Funambol is a mobile platform developed by Funambol, Inc.
* Copyright (C) 2003 - 2007 Funambol, Inc.
*
* This program is free software; you can redistribute it and/or modify it under
* the terms of the GNU Affero General Public License version 3 as published by
* the Free Software Foundation with the addition of the following permission
* added to Section 15 as permitted in Section 7(a): FOR ANY PART OF THE COVERED
* WORK IN WHICH THE COPYRIGHT IS OWNED BY FUNAMBOL, FUNAMBOL DISCLAIMS THE
* WARRANTY OF NON INFRINGEMENT OF THIRD PARTY RIGHTS.
*
* 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, see http://www.gnu.org/licenses or write to
* the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
* MA 02110-1301 USA.
*
* You can contact Funambol, Inc. headquarters at 643 Bair Island Road, Suite
* 305, Redwood City, CA 94063, USA, or at email address [email protected].
*
* The interactive user interfaces in modified source and object code versions
* of this program must display Appropriate Legal Notices, as required under
* Section 5 of the GNU Affero General Public License version 3.
*
* In accordance with Section 7(b) of the GNU Affero General Public License
* version 3, these Appropriate Legal Notices must retain the display of the
* "Powered by Funambol" logo. If the display of the logo is not reasonably
* feasible for technical reasons, the Appropriate Legal Notices must display
* the words "Powered by Funambol".
*/
#include "push/FSocket.h"
#include "base/SymbianLog.h"
#include "base/util/stringUtils.h"
#include "base/util/symbianUtils.h"
#include "base/FConnection.h"
#include "base/globalsdef.h"
USE_NAMESPACE
StringBuffer FSocket::lIP;
FSocket* FSocket::createSocket(const StringBuffer& peer, int32_t port)
{
return FSocket::NewL(peer, port);
}
FSocket* FSocket::NewL(const StringBuffer& peer, int32_t port)
{
FSocket* self = FSocket::NewLC(peer, port);
CleanupStack::Pop( self );
return self;
}
FSocket* FSocket::NewLC(const StringBuffer& peer, int32_t port)
{
FSocket* self = new ( ELeave ) FSocket();
CleanupStack::PushL( self );
self->ConstructL(peer, port);
if (self->getLastStatus() != KErrNone) {
// Something wrong.
delete self;
return NULL;
}
return self;
}
void FSocket::ConstructL(const StringBuffer& peer, int32_t port)
{
//LOG.debug("FSocket::ConstructL");
StringBuffer errorMsg;
RHostResolver resolver;
RBuf serverName;
TNameEntry hostAddress;
TInetAddr address;
serverName.Assign(stringBufferToNewBuf(peer));
//
// Get the connection manager instance
//
FConnection* connection = FConnection::getInstance();
if (!connection) {
iStatus = -1;
errorMsg = "Error opening connection";
goto error;
}
// Session is owned by FConnection!
RSocketServ* session = connection->getSession();
//
// Open the Client Socket tcp/ip
//
#ifdef __WINSCW__
// WINSCW: simply open the socket
TInt res = iSocket.Open(*session, KAfInet, KSockStream, KProtocolInetTcp);
#else
// GCCE: use the existing connection
// If first time, connect to gprs
if (!connection->isConnected()) {
LOG.debug("Starting connection");
connection->startConnection();
}
RConnection* conn = connection->getConnection();
LOG.debug("Opening socket and associate with existing connection");
TInt res = iSocket.Open(*session, KAfInet, KSockStream, KProtocolInetTcp, *conn);
//LOG.debug("Socket opened (err = %d)", res);
#endif
if (res != KErrNone) {
iStatus = -1;
errorMsg = "Error opening socket";
goto error;
}
// This works if serverName is the ip address, like "x.y.z.w"
res = address.Input(serverName);
if (res != KErrNone) {
// Try to resolve the host address
LOG.debug("resolve IP address...");
res = resolver.Open(*session, KAfInet, KProtocolInetTcp);
if (res != KErrNone) {
iStatus = -2;
errorMsg = "Host resolver open failed";
goto error;
}
resolver.GetByName(serverName, hostAddress, iStatus);
User::WaitForRequest(iStatus);
resolver.Close();
if (iStatus != KErrNone) {
errorMsg = "DNS lookup failed";
goto error;
}
// Set the socket server address/port
address = hostAddress().iAddr;
}
address.SetPort(port);
// --- Connect to host ---
LOG.debug("Socket connect...");
iSocket.Connect(address, iStatus);
User::WaitForRequest(iStatus);
if (iStatus != KErrNone) {
errorMsg = "Failed to connect to Server";
goto error;
}
return;
error:
LOG.error(errorMsg.c_str());
return;
}
FSocket::FSocket()
{
iStatus = 0;
}
FSocket::~FSocket()
{
close();
}
int32_t FSocket::writeBuffer(const int8_t* buffer, int32_t len)
{
// This doesn't copy the buffer in memory.
TPtr8 data((TUint8*)buffer, len);
data.SetLength(len);
// Sends data to the remote host.
iSocket.Write(data, iStatus);
User::WaitForRequest(iStatus);
if (iStatus == KErrNone) {
return len;
}
else {
LOG.error("FSocket: error writing on socket (status = %d)", iStatus.Int());
return -1;
}
}
int32_t FSocket::readBuffer(int8_t* buffer, int32_t maxLen)
{
StringBuffer errorMsg;
RBuf8 data;
data.CreateL(maxLen);
// Receives data from a remote host and completes when data is available.
TSockXfrLength len;
iSocket.RecvOneOrMore(data, 0, iStatus, len);
User::WaitForRequest(iStatus);
TInt msgLen = len();
if (iStatus == KErrNone) {
if (msgLen <= maxLen) {
// OK. Copy the message into the preallocated buffer.
memcpy(buffer, data.Ptr(), msgLen);
return msgLen;
}
else {
errorMsg.sprintf("FSocket: error reading, message too big (%d > %d) -> rejected.", msgLen, maxLen);
goto error;
}
}
else if (iStatus == KErrEof) {
// Either the remote connection is closed, or the socket has been shutdown.
errorMsg = "FSocket: read interrupted (connection closed)";
goto error;
}
else {
errorMsg.sprintf("FSocket: error reading on socket (status = %d)", iStatus.Int());
goto error;
}
error:
LOG.error(errorMsg.c_str());
buffer = NULL;
return -1;
}
void FSocket::close()
{
//LOG.debug("FSocket::close");
// TODO: shutdown if I/O in progress?
//iSocket.Shutdown(RSocket::EImmediate, iStatus);
iSocket.CancelAll();
iSocket.Close();
}
const StringBuffer& FSocket::address() const {
return lAddress;
}
const StringBuffer& FSocket::peerAddress() const {
return pAddress;
}
const StringBuffer& FSocket::localIP() {
return lIP;
}
<|endoftext|> |
<commit_before>/* bzflag
* Copyright (c) 1993 - 2006 Tim Riker
*
* This package is free software; you can redistribute it and/or
* modify it under the terms of the license found in the file
* named COPYING that should have accompanied this file.
*
* THIS PACKAGE IS PROVIDED ``AS IS'' AND WITHOUT ANY EXPRESS OR
* IMPLIED WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.
*/
#include "common.h"
// implementation header
#include "BZDBLocal.h"
// system headers
#include <stdio.h>
#include <string.h>
#include <string>
// common headers
#include "StateDatabase.h"
#include "ParseColor.h"
/******************************************************************************/
//
// BZDBbool
//
BZDBbool::BZDBbool(const std::string& _name, bool defVal, bool save)
: BZDBLocal(_name, save), data(defVal)
{
BZDBLocalManager::manager.addEntry(this);
DEBUG3("Added BZDBbool(%s) callback\n", name.c_str());
return;
}
BZDBbool::~BZDBbool()
{
return;
}
void BZDBbool::callback()
{
data = BZDB.isTrue(name);
DEBUG4("BZDBbool(%s) = %s\n", name.c_str(), data ? "true" : "false");
return;
}
void BZDBbool::staticCallback(const std::string& /*name*/, void* data)
{
((BZDBbool*)data)->callback();
return;
}
void BZDBbool::addCallbacks()
{
if (BZDB.isSet(name)) {
fprintf(stderr, "BZDBbool duplicate \"%s\".\n", name.c_str());
exit(1);
}
BZDB.setBool(name, data);
BZDB.setDefault(name, BZDB.get(name));
BZDB.setPersistent(name, saveOnExit);
BZDB.addCallback(name, staticCallback, this);
return;
}
void BZDBbool::removeCallbacks()
{
BZDB.removeCallback(name, staticCallback, this);
return;
}
/******************************************************************************/
//
// BZDBint
//
BZDBint::BZDBint(const std::string& _name, int defVal,
int _min, int _max, bool _neverZero, bool save)
: BZDBLocal(_name, save), data(defVal),
min(_min), max(_max), neverZero(_neverZero)
{
BZDBLocalManager::manager.addEntry(this);
DEBUG3("Added BZDBint(%s) callback\n", name.c_str());
return;
}
BZDBint::~BZDBint()
{
return;
}
void BZDBint::callback()
{
int tmp = BZDB.evalInt(name);
if ((min != INT_MIN) && (tmp < min)) {
DEBUG3("BZDBint(%s) min: %f < %f\n", name.c_str(), tmp, min);
tmp = min; // clamp to min
}
if ((max != INT_MAX) && (tmp > max)) {
DEBUG3("BZDBint(%s) max: %f > %f\n", name.c_str(), tmp, max);
tmp = max; // clamp to max
}
if (neverZero && (tmp == 0)) {
DEBUG3("BZDBint(%s) neverZero\n", name.c_str());
return; // bail out
}
data = tmp; // set the new value
DEBUG4("BZDBint(%s) = %i\n", name.c_str(), data);
return;
}
void BZDBint::staticCallback(const std::string& /*name*/, void* data)
{
((BZDBint*)data)->callback();
return;
}
void BZDBint::addCallbacks()
{
if (BZDB.isSet(name)) {
fprintf(stderr, "BZDBint duplicate \"%s\".\n", name.c_str());
exit(1);
}
BZDB.setInt(name, data);
BZDB.setDefault(name, BZDB.get(name));
BZDB.setPersistent(name, saveOnExit);
BZDB.addCallback(name, staticCallback, this);
return;
}
void BZDBint::removeCallbacks()
{
BZDB.removeCallback(name, staticCallback, this);
return;
}
/******************************************************************************/
//
// BZDBfloat
//
BZDBfloat::BZDBfloat(const std::string& _name, float defVal,
float _min, float _max,
bool _neverZero, bool save)
: BZDBLocal(_name, save), data(defVal),
min(_min), max(_max), neverZero(_neverZero)
{
BZDBLocalManager::manager.addEntry(this);
DEBUG3("Added BZDBfloat(%s) callback\n", name.c_str());
return;
}
BZDBfloat::~BZDBfloat()
{
return;
}
void BZDBfloat::callback()
{
float tmp = BZDB.eval(name);
if ((min != -MAXFLOAT) && (tmp < min)) {
DEBUG3("BZDBfloat(%s) min: %f < %f\n", name.c_str(), tmp, min);
tmp = min; // clamp to min
}
if ((max != +MAXFLOAT) && (tmp > max)) {
DEBUG3("BZDBfloat(%s) max: %f > %f\n", name.c_str(), tmp, max);
tmp = max; // clamp to max
}
if (neverZero && (tmp == 0.0f)) {
DEBUG3("BZDBfloat(%s) neverZero\n", name.c_str());
return; // bail out
}
data = tmp; // set the new value
DEBUG4("BZDBfloat(%s) = %f\n", name.c_str(), data);
return;
}
void BZDBfloat::staticCallback(const std::string& /*name*/, void* data)
{
((BZDBfloat*)data)->callback();
return;
}
void BZDBfloat::addCallbacks()
{
if (BZDB.isSet(name)) {
fprintf(stderr, "BZDBfloat duplicate \"%s\".\n", name.c_str());
exit(1);
}
BZDB.setFloat(name, data);
BZDB.setDefault(name, BZDB.get(name));
BZDB.setPersistent(name, saveOnExit);
BZDB.addCallback(name, staticCallback, this);
return;
}
void BZDBfloat::removeCallbacks()
{
BZDB.removeCallback(name, staticCallback, this);
return;
}
/******************************************************************************/
//
// BZDBcolor
//
BZDBcolor::BZDBcolor(const std::string& _name,
float r, float g, float b, float a,
bool _neverAlpha, bool save)
: BZDBLocal(_name, save), neverAlpha(_neverAlpha)
{
data[0] = r;
data[1] = g;
data[2] = b;
data[3] = a;
BZDBLocalManager::manager.addEntry(this);
DEBUG3("Added BZDBcolor(%s) callback\n", name.c_str());
return;
}
BZDBcolor::~BZDBcolor()
{
return;
}
void BZDBcolor::callback()
{
const std::string& expr = BZDB.get(name);
float color[4];
if (!parseColorString(expr, color)) {
DEBUG3("BZDBcolor(%s) bad string: %s\n", name.c_str(), expr.c_str());
return;
}
if (neverAlpha && (color[3] < 1.0f)) {
DEBUG3("BZDBcolor(%s) made opaque: %f\n", name.c_str(), color[3]);
color[3] = 1.0f;
}
// set the new value
memcpy(data, color, sizeof(float[4]));
DEBUG4("BZDBcolor(%s) = %f, %f, %f, %f\n", name.c_str(),
data[0], data[1], data[2], data[3]);
return;
}
void BZDBcolor::staticCallback(const std::string& /*name*/, void* data)
{
((BZDBcolor*)data)->callback();
return;
}
void BZDBcolor::addCallbacks()
{
if (BZDB.isSet(name)) {
fprintf(stderr, "BZDBcolor duplicate \"%s\".\n", name.c_str());
exit(1);
}
char buf[256];
snprintf(buf, 256, " %f %f %f %f", data[0], data[1], data[2], data[3]);
BZDB.set(name, buf);
BZDB.setDefault(name, BZDB.get(name));
BZDB.setPersistent(name, saveOnExit);
BZDB.addCallback(name, staticCallback, this);
return;
}
void BZDBcolor::removeCallbacks()
{
BZDB.removeCallback(name, staticCallback, this);
return;
}
/******************************************************************************/
//
// BZDBstring
//
BZDBstring::BZDBstring(const std::string& _name, const std::string& defVal,
bool _neverEmpty, bool save)
: BZDBLocal(_name, save),
data(defVal), neverEmpty(_neverEmpty)
{
BZDBLocalManager::manager.addEntry(this);
DEBUG3("Added BZDBstring(%s) callback\n", name.c_str());
return;
}
BZDBstring::~BZDBstring()
{
return;
}
void BZDBstring::callback()
{
const std::string& tmp = BZDB.get(name);
if (neverEmpty && (tmp.size() <= 0)) {
DEBUG3("BZDBstring(%s) empty string: %s\n", name.c_str(), tmp.c_str());
return;
}
data = tmp; // set the new value
DEBUG4("BZDBstring(%s) = %s\n", name.c_str(), data.c_str());
return;
}
void BZDBstring::staticCallback(const std::string& /*name*/, void* data)
{
((BZDBstring*)data)->callback();
return;
}
void BZDBstring::addCallbacks()
{
if (BZDB.isSet(name)) {
fprintf(stderr, "BZDBstring duplicate \"%s\".\n", name.c_str());
exit(1);
}
BZDB.set(name, data);
BZDB.setDefault(name, BZDB.get(name));
BZDB.setPersistent(name, saveOnExit);
BZDB.addCallback(name, staticCallback, this);
return;
}
void BZDBstring::removeCallbacks()
{
BZDB.removeCallback(name, staticCallback, this);
return;
}
/******************************************************************************/
BZDBLocalManager::BZDBLocalManager BZDBLocalManager::manager;
static std::vector<BZDBLocal*>& getEntryVector()
{
static std::vector<BZDBLocal*> vec;
return vec;
}
BZDBLocalManager::BZDBLocalManager()
{
return;
}
BZDBLocalManager::~BZDBLocalManager()
{
return;
}
bool BZDBLocalManager::addEntry(BZDBLocal* entry)
{
std::vector<BZDBLocal*>& vec = getEntryVector();
vec.push_back(entry);
return true;
}
void BZDBLocalManager::init()
{
std::vector<BZDBLocal*>& entries = getEntryVector();
for (unsigned int i = 0; i < entries.size(); i++) {
entries[i]->addCallbacks();
}
return;
}
void BZDBLocalManager::kill()
{
std::vector<BZDBLocal*>& entries = getEntryVector();
for (unsigned int i = 0; i < entries.size(); i++) {
entries[i]->removeCallbacks();
}
return;
}
/******************************************************************************/
// Local Variables: ***
// mode:C++ ***
// tab-width: 8 ***
// c-basic-offset: 2 ***
// indent-tabs-mode: t ***
// End: ***
// ex: shiftwidth=2 tabstop=8
<commit_msg>class type already known<commit_after>/* bzflag
* Copyright (c) 1993 - 2006 Tim Riker
*
* This package is free software; you can redistribute it and/or
* modify it under the terms of the license found in the file
* named COPYING that should have accompanied this file.
*
* THIS PACKAGE IS PROVIDED ``AS IS'' AND WITHOUT ANY EXPRESS OR
* IMPLIED WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.
*/
#include "common.h"
// implementation header
#include "BZDBLocal.h"
// system headers
#include <stdio.h>
#include <string.h>
#include <string>
// common headers
#include "StateDatabase.h"
#include "ParseColor.h"
// Function Prototypes
// -------------------
static void safeSetInt(const std::string& name, int value);
static void safeSetFloat(const std::string& name, float value);
static void safeSetString(const std::string& name, const std::string&value);
/******************************************************************************/
//
// BZDBbool
//
BZDBbool::BZDBbool(const std::string& _name, bool defVal, bool save)
: BZDBLocal(_name, save), data(defVal)
{
BZDBLocalManager::manager.addEntry(this);
DEBUG3("Added BZDBbool(%s) callback\n", name.c_str());
return;
}
BZDBbool::~BZDBbool()
{
return;
}
void BZDBbool::callback()
{
data = BZDB.isTrue(name);
DEBUG4("BZDBbool(%s) = %s\n", name.c_str(), data ? "true" : "false");
return;
}
void BZDBbool::staticCallback(const std::string& /*name*/, void* data)
{
((BZDBbool*)data)->callback();
return;
}
void BZDBbool::addCallbacks()
{
if (BZDB.isSet(name)) {
fprintf(stderr, "BZDBbool duplicate \"%s\".\n", name.c_str());
exit(1);
}
BZDB.setBool(name, data);
BZDB.setDefault(name, BZDB.get(name));
BZDB.setPersistent(name, saveOnExit);
BZDB.addCallback(name, staticCallback, this);
return;
}
void BZDBbool::removeCallbacks()
{
BZDB.removeCallback(name, staticCallback, this);
return;
}
/******************************************************************************/
//
// BZDBint
//
BZDBint::BZDBint(const std::string& _name, int defVal,
int _min, int _max, bool _neverZero, bool save)
: BZDBLocal(_name, save), data(defVal),
min(_min), max(_max), neverZero(_neverZero)
{
BZDBLocalManager::manager.addEntry(this);
DEBUG3("Added BZDBint(%s) callback\n", name.c_str());
return;
}
BZDBint::~BZDBint()
{
return;
}
void BZDBint::callback()
{
int tmp = BZDB.evalInt(name);
if (tmp < min) {
DEBUG3("BZDBint(%s) min: %f < %f\n", name.c_str(), tmp, min);
tmp = min; // clamp to min
safeSetInt(name, tmp);
}
if (tmp > max) {
DEBUG3("BZDBint(%s) max: %f > %f\n", name.c_str(), tmp, max);
tmp = max; // clamp to max
safeSetInt(name, tmp);
}
if (neverZero && (tmp == 0)) {
DEBUG3("BZDBint(%s) neverZero\n", name.c_str());
return; // bail out
}
data = tmp; // set the new value
DEBUG4("BZDBint(%s) = %i\n", name.c_str(), data);
return;
}
void BZDBint::staticCallback(const std::string& /*name*/, void* data)
{
((BZDBint*)data)->callback();
return;
}
void BZDBint::addCallbacks()
{
if (BZDB.isSet(name)) {
fprintf(stderr, "BZDBint duplicate \"%s\".\n", name.c_str());
exit(1);
}
BZDB.setInt(name, data);
BZDB.setDefault(name, BZDB.get(name));
BZDB.setPersistent(name, saveOnExit);
BZDB.addCallback(name, staticCallback, this);
return;
}
void BZDBint::removeCallbacks()
{
BZDB.removeCallback(name, staticCallback, this);
return;
}
/******************************************************************************/
//
// BZDBfloat
//
BZDBfloat::BZDBfloat(const std::string& _name, float defVal,
float _min, float _max,
bool _neverZero, bool save)
: BZDBLocal(_name, save), data(defVal),
min(_min), max(_max), neverZero(_neverZero)
{
BZDBLocalManager::manager.addEntry(this);
DEBUG3("Added BZDBfloat(%s) callback\n", name.c_str());
return;
}
BZDBfloat::~BZDBfloat()
{
return;
}
void BZDBfloat::callback()
{
float tmp = BZDB.eval(name);
if (tmp < min) {
DEBUG3("BZDBfloat(%s) min: %f < %f\n", name.c_str(), tmp, min);
tmp = min; // clamp to min
safeSetFloat(name, tmp);
}
if (tmp > max) {
DEBUG3("BZDBfloat(%s) max: %f > %f\n", name.c_str(), tmp, max);
tmp = max; // clamp to max
safeSetFloat(name, tmp);
}
if (neverZero && (tmp == 0.0f)) {
DEBUG3("BZDBfloat(%s) neverZero\n", name.c_str());
return; // bail out
}
data = tmp; // set the new value
DEBUG4("BZDBfloat(%s) = %f\n", name.c_str(), data);
return;
}
void BZDBfloat::staticCallback(const std::string& /*name*/, void* data)
{
((BZDBfloat*)data)->callback();
return;
}
void BZDBfloat::addCallbacks()
{
if (BZDB.isSet(name)) {
fprintf(stderr, "BZDBfloat duplicate \"%s\".\n", name.c_str());
exit(1);
}
BZDB.setFloat(name, data);
BZDB.setDefault(name, BZDB.get(name));
BZDB.setPersistent(name, saveOnExit);
BZDB.addCallback(name, staticCallback, this);
return;
}
void BZDBfloat::removeCallbacks()
{
BZDB.removeCallback(name, staticCallback, this);
return;
}
/******************************************************************************/
//
// BZDBcolor
//
BZDBcolor::BZDBcolor(const std::string& _name,
float r, float g, float b, float a,
bool _neverAlpha, bool save)
: BZDBLocal(_name, save), neverAlpha(_neverAlpha)
{
data[0] = r;
data[1] = g;
data[2] = b;
data[3] = a;
BZDBLocalManager::manager.addEntry(this);
DEBUG3("Added BZDBcolor(%s) callback\n", name.c_str());
return;
}
BZDBcolor::~BZDBcolor()
{
return;
}
void BZDBcolor::callback()
{
const std::string& expr = BZDB.get(name);
float color[4];
if (!parseColorString(expr, color)) {
DEBUG3("BZDBcolor(%s) bad string: %s\n", name.c_str(), expr.c_str());
return;
}
if (neverAlpha && (color[3] < 1.0f)) {
DEBUG3("BZDBcolor(%s) made opaque: %f\n", name.c_str(), color[3]);
color[3] = 1.0f;
char buf[256];
snprintf(buf, 256, " %f %f %f %f", color[0], color[1], color[2], color[3]);
safeSetString(name, buf);
}
// set the new value
memcpy(data, color, sizeof(float[4]));
DEBUG4("BZDBcolor(%s) = %f, %f, %f, %f\n", name.c_str(),
data[0], data[1], data[2], data[3]);
return;
}
void BZDBcolor::staticCallback(const std::string& /*name*/, void* data)
{
((BZDBcolor*)data)->callback();
return;
}
void BZDBcolor::addCallbacks()
{
if (BZDB.isSet(name)) {
fprintf(stderr, "BZDBcolor duplicate \"%s\".\n", name.c_str());
exit(1);
}
char buf[256];
snprintf(buf, 256, " %f %f %f %f", data[0], data[1], data[2], data[3]);
BZDB.set(name, buf);
BZDB.setDefault(name, BZDB.get(name));
BZDB.setPersistent(name, saveOnExit);
BZDB.addCallback(name, staticCallback, this);
return;
}
void BZDBcolor::removeCallbacks()
{
BZDB.removeCallback(name, staticCallback, this);
return;
}
/******************************************************************************/
//
// BZDBstring
//
BZDBstring::BZDBstring(const std::string& _name, const std::string& defVal,
bool _neverEmpty, bool save)
: BZDBLocal(_name, save),
data(defVal), neverEmpty(_neverEmpty)
{
BZDBLocalManager::manager.addEntry(this);
DEBUG3("Added BZDBstring(%s) callback\n", name.c_str());
return;
}
BZDBstring::~BZDBstring()
{
return;
}
void BZDBstring::callback()
{
const std::string& tmp = BZDB.get(name);
if (neverEmpty && (tmp.size() <= 0)) {
DEBUG3("BZDBstring(%s) empty string: %s\n", name.c_str(), tmp.c_str());
safeSetString(name, tmp);
return;
}
data = tmp; // set the new value
DEBUG4("BZDBstring(%s) = %s\n", name.c_str(), data.c_str());
return;
}
void BZDBstring::staticCallback(const std::string& /*name*/, void* data)
{
((BZDBstring*)data)->callback();
return;
}
void BZDBstring::addCallbacks()
{
if (BZDB.isSet(name)) {
fprintf(stderr, "BZDBstring duplicate \"%s\".\n", name.c_str());
exit(1);
}
BZDB.set(name, data);
BZDB.setDefault(name, BZDB.get(name));
BZDB.setPersistent(name, saveOnExit);
BZDB.addCallback(name, staticCallback, this);
return;
}
void BZDBstring::removeCallbacks()
{
BZDB.removeCallback(name, staticCallback, this);
return;
}
/******************************************************************************/
BZDBLocalManager BZDBLocalManager::manager;
static std::vector<BZDBLocal*>& getEntryVector()
{
static std::vector<BZDBLocal*> vec;
return vec;
}
BZDBLocalManager::BZDBLocalManager()
{
return;
}
BZDBLocalManager::~BZDBLocalManager()
{
return;
}
bool BZDBLocalManager::addEntry(BZDBLocal* entry)
{
std::vector<BZDBLocal*>& vec = getEntryVector();
vec.push_back(entry);
return true;
}
void BZDBLocalManager::init()
{
std::vector<BZDBLocal*>& entries = getEntryVector();
for (unsigned int i = 0; i < entries.size(); i++) {
entries[i]->addCallbacks();
}
return;
}
void BZDBLocalManager::kill()
{
std::vector<BZDBLocal*>& entries = getEntryVector();
for (unsigned int i = 0; i < entries.size(); i++) {
entries[i]->removeCallbacks();
}
return;
}
/******************************************************************************/
/******************************************************************************/
static bool Inside = false;
static void safeSetInt(const std::string& name, int value)
{
if (!Inside) {
Inside = true;
BZDB.setInt(name, value);
Inside = false;
}
return;
}
static void safeSetFloat(const std::string& name, float value)
{
if (!Inside) {
Inside = true;
BZDB.setFloat(name, value);
Inside = false;
}
return;
}
static void safeSetString(const std::string& name, const std::string&value)
{
if (!Inside) {
Inside = true;
BZDB.set(name, value);
Inside = false;
}
return;
}
/******************************************************************************/
// Local Variables: ***
// mode:C++ ***
// tab-width: 8 ***
// c-basic-offset: 2 ***
// indent-tabs-mode: t ***
// End: ***
// ex: shiftwidth=2 tabstop=8
<|endoftext|> |
<commit_before>//____________________________________________________
void AliTRDmakeRecoParam()
{
AliCDBMetaData *metaData= new AliCDBMetaData();
metaData->SetObjectClassName("TObjArray");
metaData->SetResponsible("Alexandru Bercuci");
metaData->SetBeamPeriod(1);
metaData->SetAliRootVersion("05-21-01"); //root version
metaData->SetComment("Ideal reconstruction parameters for low, high and cosmic runs");
AliCDBId id("TRD/Calib/RecoParam", 0, AliCDBRunRange::Infinity());
AliCDBManager *man = AliCDBManager::Instance();
AliCDBStorage *gStorLoc = man->GetStorage("local://$ALICE_ROOT/OCDB");
if (!gStorLoc) {
return;
}
gStorLoc->Put(CreateRecoParamObject(), id, metaData);
return;
}
//____________________________________________________
TObjArray* CreateRecoParamObject()
{
TObjArray *recos = new TObjArray(4);
AliTRDrecoParam *rec = 0x0;
recos->AddLast(rec = AliTRDrecoParam::GetLowFluxParam());
rec->SetAsDefault();
rec->SetNameTitle("Default", "TRD Default Reco Param");
// further settings for low flux reco param
// reco->SetThisAndThat()
recos->AddLast(rec = AliTRDrecoParam::GetLowFluxParam());
rec->SetEventSpecie(AliRecoParam::kLowMult);
rec->SetNameTitle("LOW", "TRD Low Flux Reco Param");
recos->AddLast(rec = AliTRDrecoParam::GetHighFluxParam());
rec->SetEventSpecie(AliRecoParam::kHighMult);
rec->SetNameTitle("HIGH", "TRD High Flux Reco Param");
recos->AddLast(rec = AliTRDrecoParam::GetCosmicTestParam());
rec->SetEventSpecie(AliRecoParam::kCosmic);
rec->SetNameTitle("COSMIC", "TRD Cosmic Reco Param");
rec->SetRawStreamVersion("FAST");
recos->AddLast(rec = AliTRDrecoParam::GetCosmicTestParam());
rec->SetEventSpecie(AliRecoParam::kCalib);
rec->SetNameTitle("CALIBRATION", "TRD Calibration Reco Param");
rec->SetRawStreamVersion("FAST");
// recos->AddLast(rec = AliTRDrecoParam::GetLowFluxParam());
// rec->SetNameTitle("HLT", "TRD HLT Reco Param");
// rec->SetChi2Y(.1);
// rec->SetChi2Z(5.);
return recos;
}
<commit_msg>Update reco param object (Markus)<commit_after>//____________________________________________________
void AliTRDmakeRecoParam()
{
AliCDBMetaData *metaData= new AliCDBMetaData();
metaData->SetObjectClassName("TObjArray");
metaData->SetResponsible("Alexandru Bercuci");
metaData->SetBeamPeriod(1);
metaData->SetAliRootVersion("05-21-01"); //root version
metaData->SetComment("Ideal reconstruction parameters for low, high and cosmic runs");
AliCDBId id("TRD/Calib/RecoParam", 0, AliCDBRunRange::Infinity());
AliCDBManager *man = AliCDBManager::Instance();
AliCDBStorage *gStorLoc = man->GetStorage("local://$ALICE_ROOT/OCDB");
if (!gStorLoc) {
return;
}
gStorLoc->Put(CreateRecoParamObject(), id, metaData);
return;
}
//____________________________________________________
TObjArray* CreateRecoParamObject()
{
TObjArray *recos = new TObjArray(4);
AliTRDrecoParam *rec = 0x0;
recos->AddLast(rec = AliTRDrecoParam::GetLowFluxParam());
rec->SetAsDefault();
rec->SetEventSpecie(AliRecoParam::kLowMult);
rec->SetNameTitle("LOW", "TRD Low Flux Reco Param");
rec->SetStreamLevel(AliTRDrecoParam::kTracker, 1);
// further settings for low flux reco param
// reco->SetThisAndThat()
recos->AddLast(rec = AliTRDrecoParam::GetHighFluxParam());
rec->SetEventSpecie(AliRecoParam::kHighMult);
rec->SetNameTitle("HIGH", "TRD High Flux Reco Param");
rec->SetStreamLevel(AliTRDrecoParam::kTracker, 1);
recos->AddLast(rec = AliTRDrecoParam::GetCosmicTestParam());
rec->SetEventSpecie(AliRecoParam::kCosmic);
rec->SetNameTitle("COSMIC", "TRD Cosmic Reco Param");
rec->SetStreamLevel(AliTRDrecoParam::kTracker, 1);
rec->SetRawStreamVersion("FAST");
recos->AddLast(rec = AliTRDrecoParam::GetCosmicTestParam());
rec->SetEventSpecie(AliRecoParam::kCalib);
rec->SetNameTitle("CALIBRATION", "TRD Calibration Reco Param");
rec->SetStreamLevel(AliTRDrecoParam::kTracker, 1);
rec->SetRawStreamVersion("FAST");
// recos->AddLast(rec = AliTRDrecoParam::GetLowFluxParam());
// rec->SetNameTitle("HLT", "TRD HLT Reco Param");
// rec->SetChi2Y(.1);
// rec->SetChi2Z(5.);
return recos;
}
<|endoftext|> |
<commit_before>/**
* Purity in C++17
* ===============
*
* Very naive attempt.
*
* Note: Compile with -std=c++17.
*/
#include <tuple>
template <typename T, typename ...Args>
class pure_io {
public:
template <T F()>
static constexpr T
fapply() noexcept
{
static_assert(noexcept(F()), "constant function required");
constexpr auto ret = F();
return ret;
}
template <typename F, typename G>
static constexpr T
lapply(F f, G g) noexcept
{
constexpr auto ret = f(g());
return ret;
}
};
template <auto N>
constexpr auto
foo()
{
return N * 2;
}
template <auto X, auto Y>
constexpr auto
bar()
{
return foo<X + Y>();
}
template <auto N>
constexpr auto
baz()
{
return N + 1;
}
int
main()
{
constexpr auto n0 = pure_io<int>::fapply<bar<0, 42>>();
static_assert(n0 == 84, "foo bar oops");
static_assert(pure_io<int>::fapply<baz<n0>>() == 85, "baz oops");
auto f_vals = [] {
return std::make_tuple(0, 42);
};
auto f_swap = [](auto args) {
return std::make_tuple(std::get<1>(args),
std::get<0>(args));
};
constexpr auto n1 = pure_io<std::tuple<int, int>>::lapply(f_swap, f_vals);
static_assert(std::get<0>(n1) == 42 && std::get<1>(n1) == 0,
"lambda oops");
return 0;
}
<commit_msg>updated purity1z: static_assert args gen lambda<commit_after>/**
* Purity in C++17
* ===============
*
* Very naive attempt.
*
* Note: Compile with -std=c++17.
*/
#include <tuple>
class pure_io {
public:
template <auto F()>
static constexpr auto
fapply() noexcept
{
static_assert(noexcept(F()), "constant function required");
constexpr auto ret = F();
return ret;
}
template <typename F, typename G>
static constexpr auto
lapply(F f, G g) noexcept
{
static_assert(noexcept(g()), "no-param lambda required at arg#1");
constexpr auto ret = f(g());
return ret;
}
};
template <auto N>
constexpr auto
foo()
{
return N * 2;
}
template <auto X, auto Y>
constexpr auto
bar()
{
return foo<X + Y>();
}
template <auto N>
constexpr auto
baz()
{
return N + 1;
}
int
main()
{
constexpr auto n0 = pure_io::fapply<bar<0, 42>>();
static_assert(n0 == 84, "foo bar oops");
static_assert(pure_io::fapply<baz<n0>>() == 85, "baz oops");
auto f_vals = [] {
return std::make_tuple(0, 42);
};
auto f_swap = [](auto args) {
return std::make_tuple(std::get<1>(args),
std::get<0>(args));
};
constexpr auto n1 = pure_io::lapply(f_swap, f_vals);
static_assert(std::get<0>(n1) == 42 && std::get<1>(n1) == 0,
"lambda oops");
return 0;
}
<|endoftext|> |
<commit_before>/*
* Copyright 2011 Christoph Bumiller
* 2014 Red Hat Inc.
*
* Permission is hereby granted, free of charge, to any person obtaining a
* copy of this software and associated documentation files (the "Software"),
* to deal in the Software without restriction, including without limitation
* the rights to use, copy, modify, merge, publish, distribute, sublicense,
* and/or sell copies of the Software, and to permit persons to whom the
* Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
* THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR
* OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
* ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
* OTHER DEALINGS IN THE SOFTWARE.
*/
#include "codegen/nv50_ir.h"
#include "codegen/nv50_ir_build_util.h"
#include "codegen/nv50_ir_target_nvc0.h"
#include "codegen/nv50_ir_lowering_gm107.h"
#include <limits>
namespace nv50_ir {
#define QOP_ADD 0
#define QOP_SUBR 1
#define QOP_SUB 2
#define QOP_MOV2 3
// UL UR LL LR
#define QUADOP(q, r, s, t) \
((QOP_##q << 6) | (QOP_##r << 4) | \
(QOP_##s << 2) | (QOP_##t << 0))
bool
GM107LoweringPass::handleManualTXD(TexInstruction *i)
{
static const uint8_t qOps[4][2] =
{
{ QUADOP(MOV2, ADD, MOV2, ADD), QUADOP(MOV2, MOV2, ADD, ADD) }, // l0
{ QUADOP(SUBR, MOV2, SUBR, MOV2), QUADOP(MOV2, MOV2, ADD, ADD) }, // l1
{ QUADOP(MOV2, ADD, MOV2, ADD), QUADOP(SUBR, SUBR, MOV2, MOV2) }, // l2
{ QUADOP(SUBR, MOV2, SUBR, MOV2), QUADOP(SUBR, SUBR, MOV2, MOV2) }, // l3
};
Value *def[4][4];
Value *crd[3];
Value *tmp;
Instruction *tex, *add;
Value *zero = bld.loadImm(bld.getSSA(), 0);
int l, c;
const int dim = i->tex.target.getDim();
const int array = i->tex.target.isArray();
i->op = OP_TEX; // no need to clone dPdx/dPdy later
for (c = 0; c < dim; ++c)
crd[c] = bld.getScratch();
tmp = bld.getScratch();
for (l = 0; l < 4; ++l) {
// mov coordinates from lane l to all lanes
bld.mkOp(OP_QUADON, TYPE_NONE, NULL);
for (c = 0; c < dim; ++c) {
bld.mkOp2(OP_SHFL, TYPE_F32, crd[c], i->getSrc(c + array), bld.mkImm(l));
add = bld.mkOp2(OP_QUADOP, TYPE_F32, crd[c], crd[c], zero);
add->subOp = 0x00;
add->lanes = 1; /* abused for .ndv */
}
// add dPdx from lane l to lanes dx
for (c = 0; c < dim; ++c) {
bld.mkOp2(OP_SHFL, TYPE_F32, tmp, i->dPdx[c].get(), bld.mkImm(l));
add = bld.mkOp2(OP_QUADOP, TYPE_F32, crd[c], tmp, crd[c]);
add->subOp = qOps[l][0];
add->lanes = 1; /* abused for .ndv */
}
// add dPdy from lane l to lanes dy
for (c = 0; c < dim; ++c) {
bld.mkOp2(OP_SHFL, TYPE_F32, tmp, i->dPdy[c].get(), bld.mkImm(l));
add = bld.mkOp2(OP_QUADOP, TYPE_F32, crd[c], tmp, crd[c]);
add->subOp = qOps[l][1];
add->lanes = 1; /* abused for .ndv */
}
// texture
bld.insert(tex = cloneForward(func, i));
for (c = 0; c < dim; ++c)
tex->setSrc(c + array, crd[c]);
bld.mkOp(OP_QUADPOP, TYPE_NONE, NULL);
// save results
for (c = 0; i->defExists(c); ++c) {
Instruction *mov;
def[c][l] = bld.getSSA();
mov = bld.mkMov(def[c][l], tex->getDef(c));
mov->fixed = 1;
mov->lanes = 1 << l;
}
}
for (c = 0; i->defExists(c); ++c) {
Instruction *u = bld.mkOp(OP_UNION, TYPE_U32, i->getDef(c));
for (l = 0; l < 4; ++l)
u->setSrc(l, def[c][l]);
}
i->bb->remove(i);
return true;
}
bool
GM107LoweringPass::handleDFDX(Instruction *insn)
{
Instruction *shfl;
int qop = 0, xid = 0;
switch (insn->op) {
case OP_DFDX:
qop = QUADOP(SUB, SUBR, SUB, SUBR);
xid = 1;
break;
case OP_DFDY:
qop = QUADOP(SUB, SUB, SUBR, SUBR);
xid = 2;
break;
default:
assert(!"invalid dfdx opcode");
break;
}
shfl = bld.mkOp2(OP_SHFL, TYPE_F32, bld.getScratch(),
insn->getSrc(0), bld.mkImm(xid));
shfl->subOp = NV50_IR_SUBOP_SHFL_BFLY;
insn->op = OP_QUADOP;
insn->subOp = qop;
insn->lanes = 0; /* abused for !.ndv */
insn->setSrc(1, insn->getSrc(0));
insn->setSrc(0, shfl->getDef(0));
return true;
}
bool
GM107LoweringPass::handlePFETCH(Instruction *i)
{
Value *tmp0 = bld.getScratch();
Value *tmp1 = bld.getScratch();
Value *tmp2 = bld.getScratch();
bld.mkOp1(OP_RDSV, TYPE_U32, tmp0, bld.mkSysVal(SV_INVOCATION_INFO, 0));
bld.mkOp2(OP_SHR , TYPE_U32, tmp1, tmp0, bld.mkImm(16));
bld.mkOp2(OP_AND , TYPE_U32, tmp0, tmp0, bld.mkImm(0xff));
bld.mkOp2(OP_AND , TYPE_U32, tmp1, tmp1, bld.mkImm(0xff));
bld.mkOp1(OP_MOV , TYPE_U32, tmp2, bld.mkImm(i->getSrc(0)->reg.data.u32));
bld.mkOp3(OP_MAD , TYPE_U32, tmp0, tmp0, tmp1, tmp2);
i->setSrc(0, tmp0);
i->setSrc(1, NULL);
return true;
}
bool
GM107LoweringPass::handlePOPCNT(Instruction *i)
{
Value *tmp = bld.mkOp2v(OP_AND, i->sType, bld.getScratch(),
i->getSrc(0), i->getSrc(1));
i->setSrc(0, tmp);
i->setSrc(1, NULL);
return TRUE;
}
//
// - add quadop dance for texturing
// - put FP outputs in GPRs
// - convert instruction sequences
//
bool
GM107LoweringPass::visit(Instruction *i)
{
bld.setPosition(i, false);
if (i->cc != CC_ALWAYS)
checkPredicate(i);
switch (i->op) {
case OP_TEX:
case OP_TXB:
case OP_TXL:
case OP_TXF:
case OP_TXG:
return handleTEX(i->asTex());
case OP_TXD:
return handleTXD(i->asTex());
case OP_TXLQ:
return handleTXLQ(i->asTex());
case OP_TXQ:
return handleTXQ(i->asTex());
case OP_EX2:
bld.mkOp1(OP_PREEX2, TYPE_F32, i->getDef(0), i->getSrc(0));
i->setSrc(0, i->getDef(0));
break;
case OP_POW:
return handlePOW(i);
case OP_DIV:
return handleDIV(i);
case OP_MOD:
return handleMOD(i);
case OP_SQRT:
return handleSQRT(i);
case OP_EXPORT:
return handleEXPORT(i);
case OP_PFETCH:
return handlePFETCH(i);
case OP_EMIT:
case OP_RESTART:
return handleOUT(i);
case OP_RDSV:
return handleRDSV(i);
case OP_WRSV:
return handleWRSV(i);
case OP_LOAD:
if (i->src(0).getFile() == FILE_SHADER_INPUT) {
if (prog->getType() == Program::TYPE_COMPUTE) {
i->getSrc(0)->reg.file = FILE_MEMORY_CONST;
i->getSrc(0)->reg.fileIndex = 0;
} else
if (prog->getType() == Program::TYPE_GEOMETRY &&
i->src(0).isIndirect(0)) {
// XXX: this assumes vec4 units
Value *ptr = bld.mkOp2v(OP_SHL, TYPE_U32, bld.getSSA(),
i->getIndirect(0, 0), bld.mkImm(4));
i->setIndirect(0, 0, ptr);
} else {
i->op = OP_VFETCH;
assert(prog->getType() != Program::TYPE_FRAGMENT); // INTERP
}
}
break;
case OP_ATOM:
{
const bool cctl = i->src(0).getFile() == FILE_MEMORY_GLOBAL;
handleATOM(i);
handleCasExch(i, cctl);
}
break;
case OP_SULDB:
case OP_SULDP:
case OP_SUSTB:
case OP_SUSTP:
case OP_SUREDB:
case OP_SUREDP:
handleSurfaceOpNVE4(i->asTex());
break;
case OP_DFDX:
case OP_DFDY:
handleDFDX(i);
break;
case OP_POPCNT:
handlePOPCNT(i);
break;
default:
break;
}
return true;
}
} // namespace nv50_ir
<commit_msg>gm107/ir: add support for indirect const buffer selection<commit_after>/*
* Copyright 2011 Christoph Bumiller
* 2014 Red Hat Inc.
*
* Permission is hereby granted, free of charge, to any person obtaining a
* copy of this software and associated documentation files (the "Software"),
* to deal in the Software without restriction, including without limitation
* the rights to use, copy, modify, merge, publish, distribute, sublicense,
* and/or sell copies of the Software, and to permit persons to whom the
* Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
* THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR
* OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
* ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
* OTHER DEALINGS IN THE SOFTWARE.
*/
#include "codegen/nv50_ir.h"
#include "codegen/nv50_ir_build_util.h"
#include "codegen/nv50_ir_target_nvc0.h"
#include "codegen/nv50_ir_lowering_gm107.h"
#include <limits>
namespace nv50_ir {
#define QOP_ADD 0
#define QOP_SUBR 1
#define QOP_SUB 2
#define QOP_MOV2 3
// UL UR LL LR
#define QUADOP(q, r, s, t) \
((QOP_##q << 6) | (QOP_##r << 4) | \
(QOP_##s << 2) | (QOP_##t << 0))
bool
GM107LoweringPass::handleManualTXD(TexInstruction *i)
{
static const uint8_t qOps[4][2] =
{
{ QUADOP(MOV2, ADD, MOV2, ADD), QUADOP(MOV2, MOV2, ADD, ADD) }, // l0
{ QUADOP(SUBR, MOV2, SUBR, MOV2), QUADOP(MOV2, MOV2, ADD, ADD) }, // l1
{ QUADOP(MOV2, ADD, MOV2, ADD), QUADOP(SUBR, SUBR, MOV2, MOV2) }, // l2
{ QUADOP(SUBR, MOV2, SUBR, MOV2), QUADOP(SUBR, SUBR, MOV2, MOV2) }, // l3
};
Value *def[4][4];
Value *crd[3];
Value *tmp;
Instruction *tex, *add;
Value *zero = bld.loadImm(bld.getSSA(), 0);
int l, c;
const int dim = i->tex.target.getDim();
const int array = i->tex.target.isArray();
i->op = OP_TEX; // no need to clone dPdx/dPdy later
for (c = 0; c < dim; ++c)
crd[c] = bld.getScratch();
tmp = bld.getScratch();
for (l = 0; l < 4; ++l) {
// mov coordinates from lane l to all lanes
bld.mkOp(OP_QUADON, TYPE_NONE, NULL);
for (c = 0; c < dim; ++c) {
bld.mkOp2(OP_SHFL, TYPE_F32, crd[c], i->getSrc(c + array), bld.mkImm(l));
add = bld.mkOp2(OP_QUADOP, TYPE_F32, crd[c], crd[c], zero);
add->subOp = 0x00;
add->lanes = 1; /* abused for .ndv */
}
// add dPdx from lane l to lanes dx
for (c = 0; c < dim; ++c) {
bld.mkOp2(OP_SHFL, TYPE_F32, tmp, i->dPdx[c].get(), bld.mkImm(l));
add = bld.mkOp2(OP_QUADOP, TYPE_F32, crd[c], tmp, crd[c]);
add->subOp = qOps[l][0];
add->lanes = 1; /* abused for .ndv */
}
// add dPdy from lane l to lanes dy
for (c = 0; c < dim; ++c) {
bld.mkOp2(OP_SHFL, TYPE_F32, tmp, i->dPdy[c].get(), bld.mkImm(l));
add = bld.mkOp2(OP_QUADOP, TYPE_F32, crd[c], tmp, crd[c]);
add->subOp = qOps[l][1];
add->lanes = 1; /* abused for .ndv */
}
// texture
bld.insert(tex = cloneForward(func, i));
for (c = 0; c < dim; ++c)
tex->setSrc(c + array, crd[c]);
bld.mkOp(OP_QUADPOP, TYPE_NONE, NULL);
// save results
for (c = 0; i->defExists(c); ++c) {
Instruction *mov;
def[c][l] = bld.getSSA();
mov = bld.mkMov(def[c][l], tex->getDef(c));
mov->fixed = 1;
mov->lanes = 1 << l;
}
}
for (c = 0; i->defExists(c); ++c) {
Instruction *u = bld.mkOp(OP_UNION, TYPE_U32, i->getDef(c));
for (l = 0; l < 4; ++l)
u->setSrc(l, def[c][l]);
}
i->bb->remove(i);
return true;
}
bool
GM107LoweringPass::handleDFDX(Instruction *insn)
{
Instruction *shfl;
int qop = 0, xid = 0;
switch (insn->op) {
case OP_DFDX:
qop = QUADOP(SUB, SUBR, SUB, SUBR);
xid = 1;
break;
case OP_DFDY:
qop = QUADOP(SUB, SUB, SUBR, SUBR);
xid = 2;
break;
default:
assert(!"invalid dfdx opcode");
break;
}
shfl = bld.mkOp2(OP_SHFL, TYPE_F32, bld.getScratch(),
insn->getSrc(0), bld.mkImm(xid));
shfl->subOp = NV50_IR_SUBOP_SHFL_BFLY;
insn->op = OP_QUADOP;
insn->subOp = qop;
insn->lanes = 0; /* abused for !.ndv */
insn->setSrc(1, insn->getSrc(0));
insn->setSrc(0, shfl->getDef(0));
return true;
}
bool
GM107LoweringPass::handlePFETCH(Instruction *i)
{
Value *tmp0 = bld.getScratch();
Value *tmp1 = bld.getScratch();
Value *tmp2 = bld.getScratch();
bld.mkOp1(OP_RDSV, TYPE_U32, tmp0, bld.mkSysVal(SV_INVOCATION_INFO, 0));
bld.mkOp2(OP_SHR , TYPE_U32, tmp1, tmp0, bld.mkImm(16));
bld.mkOp2(OP_AND , TYPE_U32, tmp0, tmp0, bld.mkImm(0xff));
bld.mkOp2(OP_AND , TYPE_U32, tmp1, tmp1, bld.mkImm(0xff));
bld.mkOp1(OP_MOV , TYPE_U32, tmp2, bld.mkImm(i->getSrc(0)->reg.data.u32));
bld.mkOp3(OP_MAD , TYPE_U32, tmp0, tmp0, tmp1, tmp2);
i->setSrc(0, tmp0);
i->setSrc(1, NULL);
return true;
}
bool
GM107LoweringPass::handlePOPCNT(Instruction *i)
{
Value *tmp = bld.mkOp2v(OP_AND, i->sType, bld.getScratch(),
i->getSrc(0), i->getSrc(1));
i->setSrc(0, tmp);
i->setSrc(1, NULL);
return TRUE;
}
//
// - add quadop dance for texturing
// - put FP outputs in GPRs
// - convert instruction sequences
//
bool
GM107LoweringPass::visit(Instruction *i)
{
bld.setPosition(i, false);
if (i->cc != CC_ALWAYS)
checkPredicate(i);
switch (i->op) {
case OP_TEX:
case OP_TXB:
case OP_TXL:
case OP_TXF:
case OP_TXG:
return handleTEX(i->asTex());
case OP_TXD:
return handleTXD(i->asTex());
case OP_TXLQ:
return handleTXLQ(i->asTex());
case OP_TXQ:
return handleTXQ(i->asTex());
case OP_EX2:
bld.mkOp1(OP_PREEX2, TYPE_F32, i->getDef(0), i->getSrc(0));
i->setSrc(0, i->getDef(0));
break;
case OP_POW:
return handlePOW(i);
case OP_DIV:
return handleDIV(i);
case OP_MOD:
return handleMOD(i);
case OP_SQRT:
return handleSQRT(i);
case OP_EXPORT:
return handleEXPORT(i);
case OP_PFETCH:
return handlePFETCH(i);
case OP_EMIT:
case OP_RESTART:
return handleOUT(i);
case OP_RDSV:
return handleRDSV(i);
case OP_WRSV:
return handleWRSV(i);
case OP_LOAD:
if (i->src(0).getFile() == FILE_SHADER_INPUT) {
if (prog->getType() == Program::TYPE_COMPUTE) {
i->getSrc(0)->reg.file = FILE_MEMORY_CONST;
i->getSrc(0)->reg.fileIndex = 0;
} else
if (prog->getType() == Program::TYPE_GEOMETRY &&
i->src(0).isIndirect(0)) {
// XXX: this assumes vec4 units
Value *ptr = bld.mkOp2v(OP_SHL, TYPE_U32, bld.getSSA(),
i->getIndirect(0, 0), bld.mkImm(4));
i->setIndirect(0, 0, ptr);
} else {
i->op = OP_VFETCH;
assert(prog->getType() != Program::TYPE_FRAGMENT); // INTERP
}
} else if (i->src(0).getFile() == FILE_MEMORY_CONST) {
if (i->src(0).isIndirect(1)) {
Value *ptr;
if (i->src(0).isIndirect(0))
ptr = bld.mkOp3v(OP_INSBF, TYPE_U32, bld.getSSA(),
i->getIndirect(0, 1), bld.mkImm(0x1010),
i->getIndirect(0, 0));
else
ptr = bld.mkOp2v(OP_SHL, TYPE_U32, bld.getSSA(),
i->getIndirect(0, 1), bld.mkImm(16));
i->setIndirect(0, 1, NULL);
i->setIndirect(0, 0, ptr);
i->subOp = NV50_IR_SUBOP_LDC_IS;
}
}
break;
case OP_ATOM:
{
const bool cctl = i->src(0).getFile() == FILE_MEMORY_GLOBAL;
handleATOM(i);
handleCasExch(i, cctl);
}
break;
case OP_SULDB:
case OP_SULDP:
case OP_SUSTB:
case OP_SUSTP:
case OP_SUREDB:
case OP_SUREDP:
handleSurfaceOpNVE4(i->asTex());
break;
case OP_DFDX:
case OP_DFDY:
handleDFDX(i);
break;
case OP_POPCNT:
handlePOPCNT(i);
break;
default:
break;
}
return true;
}
} // namespace nv50_ir
<|endoftext|> |
<commit_before>#include "src/fillers.h"
#include "src/utils.h"
/* ***** */
void gfx_flatFill(const gfx_Triangle *t, gfx_drawBuffer *buffer, enum TriangleType type)
{
const gfx_Vertex *v0 = &t->vertices[0];
const gfx_Vertex *v1 = &t->vertices[1];
const gfx_Vertex *v2 = &t->vertices[2];
double y, invDy, dxLeft, dxRight, xLeft, xRight, prestep;
int currLine, numScanlines, x0, x1, yDir = 1;
// variables used if depth test is enabled
float startInvZ, endInvZ, invZ0, invZ1, invZ2, invY02;
if(type == FLAT_BOTTOM)
{
invDy = 1.0 / (v2->position.y - v0->position.y);
numScanlines = ceil(v2->position.y) - ceil(v0->position.y);
prestep = ceil(v0->position.y) - v0->position.y;
// todo: handle line sizes of height < 1
if(v2->position.y - v0->position.y < 1) return;
}
else
{
invDy = 1.0 / (v0->position.y - v2->position.y);
yDir = -1;
numScanlines = ceil(v0->position.y) - ceil(v2->position.y);
prestep = ceil(v2->position.y) - v2->position.y;
// todo: handle line sizes of height < 1
if(v0->position.y - v2->position.y < 1) return;
}
dxLeft = (v2->position.x - v0->position.x) * invDy;
dxRight = (v1->position.x - v0->position.x) * invDy;
xLeft = v0->position.x + dxLeft * prestep;
xRight = v0->position.x + dxRight * prestep;
// skip the unnecessary divisions if there's no depth testing
if(buffer->drawOpts.depthFunc != DF_ALWAYS)
{
invZ0 = 1.f / v0->position.z;
invZ1 = 1.f / v1->position.z;
invZ2 = 1.f / v2->position.z;
invY02 = 1.f / (v0->position.y - v2->position.y);
}
for(currLine = 0, y = ceil(v0->position.y); currLine <= numScanlines; y += yDir)
{
x0 = ceil(xLeft);
x1 = ceil(xRight);
// interpolate 1/z only if depth testing is enabled
if(buffer->drawOpts.depthFunc != DF_ALWAYS)
{
float r1 = (v0->position.y - y) * invY02;
startInvZ = LERP(invZ0, invZ2, r1);
endInvZ = LERP(invZ0, invZ1, r1);
gfx_drawLine(x0, y, 1.f/startInvZ, x1, y, 1.f/endInvZ, t->color, buffer);
}
else
gfx_drawLine(x0, y, 0.f, x1, y, 0.f, t->color, buffer);
if(++currLine < numScanlines)
{
xLeft += dxLeft;
xRight += dxRight;
}
}
}
/* ***** */
void gfx_perspectiveTextureMap(const gfx_Triangle *t, gfx_drawBuffer *buffer, enum TriangleType type)
{
const gfx_Vertex *v0 = &t->vertices[0];
const gfx_Vertex *v1 = &t->vertices[1];
const gfx_Vertex *v2 = &t->vertices[2];
double x, y, invDy, dxLeft, dxRight, prestep, yDir = 1;
double startX, endX, startXPrestep, endXPrestep;
int useColorKey = buffer->drawOpts.colorKey != -1 ? 1 : 0;
int texW = t->texture->width - 1;
int texH = t->texture->height - 1;
int texArea = texW * texH;
int currLine, numScanlines;
float invZ0, invZ1, invZ2, invY02 = 1.f;
if(type == FLAT_BOTTOM)
{
invDy = 1.0 / (v2->position.y - v0->position.y);
numScanlines = ceil(v2->position.y) - ceil(v0->position.y);
prestep = ceil(v0->position.y) - v0->position.y;
// todo: handle line sizes of height < 1
if(v2->position.y - v0->position.y < 1) return;
}
else
{
invDy = 1.0 / (v0->position.y - v2->position.y);
yDir = -1;
numScanlines = ceil(v0->position.y) - ceil(v2->position.y);
prestep = ceil(v2->position.y) - v2->position.y;
// todo: handle line sizes of height < 1
if(v0->position.y - v2->position.y < 1) return;
}
dxLeft = (v2->position.x - v0->position.x) * invDy;
dxRight = (v1->position.x - v0->position.x) * invDy;
startX = v0->position.x;
endX = startX;
startXPrestep = v0->position.x + dxLeft * prestep;
endXPrestep = v0->position.x + dxRight * prestep;
invZ0 = 1.f / v0->position.z;
invZ1 = 1.f / v1->position.z;
invZ2 = 1.f / v2->position.z;
invY02 = 1.f / (v0->position.y - v2->position.y);
for(currLine = 0, y = v0->position.y; currLine <= numScanlines; y += yDir)
{
float startInvZ, endInvZ, r1, invLineLength = 0.f;
float startU = texW, startV = texH, endU = texW, endV = texH;
r1 = (v0->position.y - y) * invY02;
startInvZ = LERP(invZ0, invZ2, r1);
endInvZ = LERP(invZ0, invZ1, r1);
startU *= LERP(v0->uv.u * invZ0, v2->uv.u * invZ2, r1);
startV *= LERP(v0->uv.v * invZ0, v2->uv.v * invZ2, r1);
endU *= LERP(v0->uv.u * invZ0, v1->uv.u * invZ1, r1);
endV *= LERP(v0->uv.v * invZ0, v1->uv.v * invZ1, r1);
if(startX != endX)
invLineLength = 1.f / (endX - startX);
for(x = startXPrestep; x <= endXPrestep; ++x)
{
// interpolate 1/z for each pixel in the scanline
float r = (x - startX) * invLineLength;
float lerpInvZ = LERP(startInvZ, endInvZ, r);
float z = 1.f/lerpInvZ;
float u = z * LERP(startU, endU, r);
float v = z * LERP(startV, endV, r);
// fetch texture data with a texArea modulus for proper effect in case u or v are > 1
unsigned char pixel = t->texture->data[((int)u + ((int)v * t->texture->height)) % texArea];
if(!useColorKey || (useColorKey && pixel != (unsigned char)buffer->drawOpts.colorKey))
{
// DF_ALWAYS = no depth test
if(buffer->drawOpts.depthFunc == DF_ALWAYS)
gfx_drawPixel(ceil(x), ceil(y), pixel, buffer);
else
gfx_drawPixelWithDepth(ceil(x), ceil(y), lerpInvZ, pixel, buffer);
}
}
if(++currLine < numScanlines)
{
startX += dxLeft;
endX += dxRight;
startXPrestep += dxLeft;
endXPrestep += dxRight;
}
}
}
/* ***** */
void gfx_affineTextureMap(const gfx_Triangle *t, gfx_drawBuffer *buffer, enum TriangleType type)
{
const gfx_Vertex *v0 = &t->vertices[0];
const gfx_Vertex *v1 = &t->vertices[1];
const gfx_Vertex *v2 = &t->vertices[2];
double x, y, invDy, dxLeft, dxRight, prestep, yDir = 1;
double startU, startV, invDx, du, dv, startX, endX;
float duLeft, dvLeft, duRight, dvRight;
float texW = t->texture->width - 1;
float texH = t->texture->height - 1;
int useColorKey = buffer->drawOpts.colorKey != -1 ? 1 : 0;
int texArea = texW * texH;
int currLine, numScanlines;
// variables used only if depth test is enabled
float invZ0, invZ1, invZ2, invY02 = 1.f;
if(type == FLAT_BOTTOM)
{
invDy = 1.f / (v2->position.y - v0->position.y);
numScanlines = ceil(v2->position.y) - ceil(v0->position.y);
prestep = ceil(v0->position.y) - v0->position.y;
// todo: handle line sizes of height < 1
if(v2->position.y - v0->position.y < 1) return;
}
else
{
invDy = 1.f / (v0->position.y - v2->position.y);
yDir = -1;
numScanlines = ceil(v0->position.y) - ceil(v2->position.y);
prestep = ceil(v2->position.y) - v2->position.y;
// todo: handle line sizes of height < 1
if(v0->position.y - v2->position.y < 1) return;
}
dxLeft = (v2->position.x - v0->position.x) * invDy;
dxRight = (v1->position.x - v0->position.x) * invDy;
duLeft = texW * (v2->uv.u - v0->uv.u) * invDy;
dvLeft = texH * (v2->uv.v - v0->uv.v) * invDy;
duRight = texW * (v1->uv.u - v0->uv.u) * invDy;
dvRight = texH * (v1->uv.v - v0->uv.v) * invDy;
startU = texW * v0->uv.u + duLeft * prestep;
startV = texH * v0->uv.v + dvLeft * prestep;
// With triangles the texture gradients (u,v slopes over the triangle surface)
// are guaranteed to be constant, so we need to calculate du and dv only once.
invDx = 1.f / (dxRight - dxLeft);
du = (duRight - duLeft) * invDx;
dv = (dvRight - dvLeft) * invDx;
startX = v0->position.x + dxLeft * prestep;
endX = v0->position.x + dxRight * prestep;
// skip the unnecessary divisions if there's no depth testing
if(buffer->drawOpts.depthFunc != DF_ALWAYS)
{
invZ0 = 1.f / v0->position.z;
invZ1 = 1.f / v1->position.z;
invZ2 = 1.f / v2->position.z;
invY02 = 1.f / (v0->position.y - v2->position.y);
}
for(currLine = 0, y = v0->position.y; currLine <= numScanlines; y += yDir)
{
float u = startU;
float v = startV;
// variables used only if depth test is enabled
float startInvZ, endInvZ, invLineLength = 0.f;
// interpolate 1/z only if depth testing is enabled
if(buffer->drawOpts.depthFunc != DF_ALWAYS)
{
float r1 = (v0->position.y - y) * invY02;
startInvZ = LERP(invZ0, invZ2, r1);
endInvZ = LERP(invZ0, invZ1, r1);
if(startX != endX)
invLineLength = 1.f / (endX - startX);
}
for(x = startX; x <= endX; ++x)
{
// fetch texture data with a texArea modulus for proper effect in case u or v are > 1
unsigned char pixel = t->texture->data[((int)u + ((int)v * t->texture->height)) % texArea];
if(!useColorKey || (useColorKey && pixel != (unsigned char)buffer->drawOpts.colorKey))
{
// DF_ALWAYS = no depth test
if(buffer->drawOpts.depthFunc == DF_ALWAYS)
gfx_drawPixel(ceil(x), ceil(y), pixel, buffer);
else
{
float r = (x - startX) * invLineLength;
float lerpInvZ = LERP(startInvZ, endInvZ, r);
gfx_drawPixelWithDepth(ceil(x), ceil(y), lerpInvZ, pixel, buffer);
}
}
u += du;
v += dv;
}
if(++currLine < numScanlines)
{
startX += dxLeft;
endX += dxRight;
startU += duLeft;
startV += dvLeft;
}
}
}
<commit_msg>fixed single scanline depth buffer glitch<commit_after>#include "src/fillers.h"
#include "src/utils.h"
/* ***** */
void gfx_flatFill(const gfx_Triangle *t, gfx_drawBuffer *buffer, enum TriangleType type)
{
const gfx_Vertex *v0 = &t->vertices[0];
const gfx_Vertex *v1 = &t->vertices[1];
const gfx_Vertex *v2 = &t->vertices[2];
double y, invDy, dxLeft, dxRight, xLeft, xRight, prestep;
int currLine, numScanlines, x0, x1, yDir = 1;
// variables used if depth test is enabled
float startInvZ, endInvZ, invZ0, invZ1, invZ2, invY02;
if(type == FLAT_BOTTOM)
{
invDy = 1.0 / (v2->position.y - v0->position.y);
numScanlines = ceil(v2->position.y) - ceil(v0->position.y);
prestep = ceil(v0->position.y) - v0->position.y;
// todo: handle line sizes of height < 1
if(v2->position.y - v0->position.y < 1) return;
}
else
{
invDy = 1.0 / (v0->position.y - v2->position.y);
yDir = -1;
numScanlines = ceil(v0->position.y) - ceil(v2->position.y);
prestep = ceil(v2->position.y) - v2->position.y;
// todo: handle line sizes of height < 1
if(v0->position.y - v2->position.y < 1) return;
}
dxLeft = (v2->position.x - v0->position.x) * invDy;
dxRight = (v1->position.x - v0->position.x) * invDy;
xLeft = v0->position.x + dxLeft * prestep;
xRight = v0->position.x + dxRight * prestep;
// skip the unnecessary divisions if there's no depth testing
if(buffer->drawOpts.depthFunc != DF_ALWAYS)
{
invZ0 = 1.f / v0->position.z;
invZ1 = 1.f / v1->position.z;
invZ2 = 1.f / v2->position.z;
invY02 = 1.f / (v0->position.y - v2->position.y);
}
for(currLine = 0, y = ceil(v0->position.y); currLine <= numScanlines; y += yDir)
{
x0 = ceil(xLeft);
x1 = ceil(xRight);
// interpolate 1/z only if depth testing is enabled
if(buffer->drawOpts.depthFunc != DF_ALWAYS)
{
float r1 = (v0->position.y - y) * invY02;
startInvZ = LERP(invZ0, invZ2, r1);
endInvZ = LERP(invZ0, invZ1, r1);
gfx_drawLine(x0, y, 1.f/startInvZ, x1, y, 1.f/endInvZ, t->color, buffer);
}
else
gfx_drawLine(x0, y, 0.f, x1, y, 0.f, t->color, buffer);
if(++currLine < numScanlines)
{
xLeft += dxLeft;
xRight += dxRight;
}
}
}
/* ***** */
void gfx_perspectiveTextureMap(const gfx_Triangle *t, gfx_drawBuffer *buffer, enum TriangleType type)
{
const gfx_Vertex *v0 = &t->vertices[0];
const gfx_Vertex *v1 = &t->vertices[1];
const gfx_Vertex *v2 = &t->vertices[2];
double x, y, invDy, dxLeft, dxRight, prestep, yDir = 1;
double startX, endX, startXPrestep, endXPrestep;
int useColorKey = buffer->drawOpts.colorKey != -1 ? 1 : 0;
int texW = t->texture->width - 1;
int texH = t->texture->height - 1;
int texArea = texW * texH;
int currLine, numScanlines;
float invZ0, invZ1, invZ2, invY02 = 1.f;
if(type == FLAT_BOTTOM)
{
invDy = 1.0 / (v2->position.y - v0->position.y);
numScanlines = ceil(v2->position.y) - ceil(v0->position.y);
prestep = ceil(v0->position.y) - v0->position.y;
// todo: handle line sizes of height < 1
if(v2->position.y - v0->position.y < 1) return;
}
else
{
invDy = 1.0 / (v0->position.y - v2->position.y);
yDir = -1;
numScanlines = ceil(v0->position.y) - ceil(v2->position.y);
prestep = ceil(v2->position.y) - v2->position.y;
// todo: handle line sizes of height < 1
if(v0->position.y - v2->position.y < 1) return;
}
dxLeft = (v2->position.x - v0->position.x) * invDy;
dxRight = (v1->position.x - v0->position.x) * invDy;
startX = v0->position.x;
endX = startX;
startXPrestep = v0->position.x + dxLeft * prestep;
endXPrestep = v0->position.x + dxRight * prestep;
invZ0 = 1.f / v0->position.z;
invZ1 = 1.f / v1->position.z;
invZ2 = 1.f / v2->position.z;
invY02 = 1.f / (v0->position.y - v2->position.y);
for(currLine = 0, y = v0->position.y; currLine <= numScanlines; y += yDir)
{
float startInvZ, endInvZ, r1, invLineLength = 0.f;
float startU = texW, startV = texH, endU = texW, endV = texH;
r1 = (v0->position.y - y) * invY02;
startInvZ = LERP(invZ0, invZ2, r1);
endInvZ = LERP(invZ0, invZ1, r1);
startU *= LERP(v0->uv.u * invZ0, v2->uv.u * invZ2, r1);
startV *= LERP(v0->uv.v * invZ0, v2->uv.v * invZ2, r1);
endU *= LERP(v0->uv.u * invZ0, v1->uv.u * invZ1, r1);
endV *= LERP(v0->uv.v * invZ0, v1->uv.v * invZ1, r1);
if(startX != endX)
invLineLength = 1.f / (endX - startX);
for(x = startXPrestep; x <= endXPrestep; ++x)
{
// interpolate 1/z for each pixel in the scanline
float r = (x - startX) * invLineLength;
float lerpInvZ = LERP(startInvZ, endInvZ, r);
float z = 1.f/lerpInvZ;
float u = z * LERP(startU, endU, r);
float v = z * LERP(startV, endV, r);
// fetch texture data with a texArea modulus for proper effect in case u or v are > 1
unsigned char pixel = t->texture->data[((int)u + ((int)v * t->texture->height)) % texArea];
if(!useColorKey || (useColorKey && pixel != (unsigned char)buffer->drawOpts.colorKey))
{
// DF_ALWAYS = no depth test
if(buffer->drawOpts.depthFunc == DF_ALWAYS)
gfx_drawPixel(ceil(x), ceil(y), pixel, buffer);
else
gfx_drawPixelWithDepth(ceil(x), ceil(y), lerpInvZ, pixel, buffer);
}
}
startX += dxLeft;
endX += dxRight;
if(++currLine < numScanlines)
{
startXPrestep += dxLeft;
endXPrestep += dxRight;
}
}
}
/* ***** */
void gfx_affineTextureMap(const gfx_Triangle *t, gfx_drawBuffer *buffer, enum TriangleType type)
{
const gfx_Vertex *v0 = &t->vertices[0];
const gfx_Vertex *v1 = &t->vertices[1];
const gfx_Vertex *v2 = &t->vertices[2];
double x, y, invDy, dxLeft, dxRight, prestep, yDir = 1;
double startU, startV, invDx, du, dv, startX, endX;
float duLeft, dvLeft, duRight, dvRight;
float texW = t->texture->width - 1;
float texH = t->texture->height - 1;
int useColorKey = buffer->drawOpts.colorKey != -1 ? 1 : 0;
int texArea = texW * texH;
int currLine, numScanlines;
// variables used only if depth test is enabled
float invZ0, invZ1, invZ2, invY02 = 1.f;
if(type == FLAT_BOTTOM)
{
invDy = 1.f / (v2->position.y - v0->position.y);
numScanlines = ceil(v2->position.y) - ceil(v0->position.y);
prestep = ceil(v0->position.y) - v0->position.y;
// todo: handle line sizes of height < 1
if(v2->position.y - v0->position.y < 1) return;
}
else
{
invDy = 1.f / (v0->position.y - v2->position.y);
yDir = -1;
numScanlines = ceil(v0->position.y) - ceil(v2->position.y);
prestep = ceil(v2->position.y) - v2->position.y;
// todo: handle line sizes of height < 1
if(v0->position.y - v2->position.y < 1) return;
}
dxLeft = (v2->position.x - v0->position.x) * invDy;
dxRight = (v1->position.x - v0->position.x) * invDy;
duLeft = texW * (v2->uv.u - v0->uv.u) * invDy;
dvLeft = texH * (v2->uv.v - v0->uv.v) * invDy;
duRight = texW * (v1->uv.u - v0->uv.u) * invDy;
dvRight = texH * (v1->uv.v - v0->uv.v) * invDy;
startU = texW * v0->uv.u + duLeft * prestep;
startV = texH * v0->uv.v + dvLeft * prestep;
// With triangles the texture gradients (u,v slopes over the triangle surface)
// are guaranteed to be constant, so we need to calculate du and dv only once.
invDx = 1.f / (dxRight - dxLeft);
du = (duRight - duLeft) * invDx;
dv = (dvRight - dvLeft) * invDx;
startX = v0->position.x + dxLeft * prestep;
endX = v0->position.x + dxRight * prestep;
// skip the unnecessary divisions if there's no depth testing
if(buffer->drawOpts.depthFunc != DF_ALWAYS)
{
invZ0 = 1.f / v0->position.z;
invZ1 = 1.f / v1->position.z;
invZ2 = 1.f / v2->position.z;
invY02 = 1.f / (v0->position.y - v2->position.y);
}
for(currLine = 0, y = v0->position.y; currLine <= numScanlines; y += yDir)
{
float u = startU;
float v = startV;
// variables used only if depth test is enabled
float startInvZ, endInvZ, invLineLength = 0.f;
// interpolate 1/z only if depth testing is enabled
if(buffer->drawOpts.depthFunc != DF_ALWAYS)
{
float r1 = (v0->position.y - y) * invY02;
startInvZ = LERP(invZ0, invZ2, r1);
endInvZ = LERP(invZ0, invZ1, r1);
if(startX != endX)
invLineLength = 1.f / (endX - startX);
}
for(x = startX; x <= endX; ++x)
{
// fetch texture data with a texArea modulus for proper effect in case u or v are > 1
unsigned char pixel = t->texture->data[((int)u + ((int)v * t->texture->height)) % texArea];
if(!useColorKey || (useColorKey && pixel != (unsigned char)buffer->drawOpts.colorKey))
{
// DF_ALWAYS = no depth test
if(buffer->drawOpts.depthFunc == DF_ALWAYS)
gfx_drawPixel(ceil(x), ceil(y), pixel, buffer);
else
{
float r = (x - startX) * invLineLength;
float lerpInvZ = LERP(startInvZ, endInvZ, r);
gfx_drawPixelWithDepth(ceil(x), ceil(y), lerpInvZ, pixel, buffer);
}
}
u += du;
v += dv;
}
if(++currLine < numScanlines)
{
startX += dxLeft;
endX += dxRight;
startU += duLeft;
startV += dvLeft;
}
}
}
<|endoftext|> |
<commit_before>// Copyright 2017 Intermodalics 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 "tango_ros_native/occupancy_grid_file_io.h"
#include <cmath>
#include <fstream>
#include <iostream>
#include <geometry_msgs/Quaternion.h>
#include <tf/LinearMath/Matrix3x3.h>
#include <glog/logging.h>
#include <yaml-cpp/yaml.h>
namespace {
void AddTrailingSlashToDirectoryPathIfNeeded(std::string& directory_path) {
if (!directory_path.empty() && directory_path.back() != '/') {
directory_path += "/";
}
}
} // namespace
namespace occupancy_grid_file_io {
bool SaveOccupancyGridToFiles(
const std::string& map_name, const std::string& map_uuid,
const std::string& map_directory, const nav_msgs::OccupancyGrid& occupancy_grid) {
return SaveOccupancyGridDataToPgmFile(map_name, map_directory, occupancy_grid)
&& SaveOccupancyGridMetadataToYamlFile(map_name, map_uuid, map_directory, occupancy_grid.info);
}
bool SaveOccupancyGridDataToPgmFile(
const std::string& map_name, const std::string& map_directory,
const nav_msgs::OccupancyGrid& occupancy_grid) {
std::string map_directory_with_trailing_slash = map_directory;
AddTrailingSlashToDirectoryPathIfNeeded(map_directory_with_trailing_slash);
std::string map_pgm_file_path = map_directory_with_trailing_slash + map_name + ".pgm";
FILE* pgm_file = fopen(map_pgm_file_path.c_str(), "w");
if (!pgm_file) {
LOG(ERROR) << "Could no open file " << map_pgm_file_path;
return false;
}
fprintf(pgm_file, "P5\n# CREATOR: TangoRosStreamer %.3f m/pix\n%d %d\n255\n",
occupancy_grid.info.resolution,
occupancy_grid.info.width, occupancy_grid.info.height);
for (size_t i = 0; i < occupancy_grid.info.height; ++i) {
for (size_t j = 0; j < occupancy_grid.info.width; ++j) {
// Need to invert the ordering of the cells to
// produce an image with pixel (0,0) in the top-left corner.
int value = occupancy_grid.data[j + (occupancy_grid.info.height - i - 1) * occupancy_grid.info.width];
if (value == 0) {
fputc(254, pgm_file);
} else if (value == +100) {
fputc(000, pgm_file);
} else {
fputc(205, pgm_file);
}
}
}
fclose(pgm_file);
return true;
}
bool SaveOccupancyGridMetadataToYamlFile(
const std::string& map_name, const std::string& map_uuid,
const std::string& map_directory, const nav_msgs::MapMetaData& map_metadata) {
std::string map_directory_with_trailing_slash = map_directory;
AddTrailingSlashToDirectoryPathIfNeeded(map_directory_with_trailing_slash);
std::string image_name = map_name;
if (image_name.empty())
image_name = "\"\"";
std::string uuid = map_uuid;
if (uuid.empty())
uuid = "\"\"";
std::string map_yaml_file_path = map_directory_with_trailing_slash + map_name + ".yaml";
FILE* yaml_file = fopen(map_yaml_file_path.c_str(), "w");
if (!yaml_file) {
LOG(ERROR) << "Could no open file " << map_yaml_file_path;
return false;
}
tf::Matrix3x3 mat(tf::Quaternion(map_metadata.origin.orientation.x,
map_metadata.origin.orientation.y,
map_metadata.origin.orientation.z,
map_metadata.origin.orientation.w));
double yaw, pitch, roll;
mat.getEulerYPR(yaw, pitch, roll);
if (std::isnan(yaw))
yaw = 0.0;
fprintf(yaml_file, "image: %s.pgm\nresolution: %f\norigin: [%f, %f, %f]\nnegate: 0\n"
"occupied_thresh: 0.65\nfree_thresh: 0.196\nuuid: %s\n\n",
map_name.c_str(), map_metadata.resolution, map_metadata.origin.position.x,
map_metadata.origin.position.y, yaw, uuid.c_str());
fclose(yaml_file);
return true;
}
bool LoadOccupancyGridFromFiles(
const std::string& map_name, const std::string& map_directory,
nav_msgs::OccupancyGrid* occupancy_grid, std::string* map_uuid) {
int negate;
double occupied_threshold;
double free_threshold;
bool result = LoadOccupancyGridMetadataFromYamlFile(
map_name, map_directory, &(occupancy_grid->info), &negate,
&occupied_threshold, &free_threshold, map_uuid);
return result && LoadOccupancyGridDataFromPgmFile(
map_name, map_directory, negate, occupied_threshold, free_threshold,
occupancy_grid);
}
bool LoadOccupancyGridDataFromPgmFile(
const std::string& map_name, const std::string& map_directory,
bool negate, double occupied_threshold, double free_threshold,
nav_msgs::OccupancyGrid* occupancy_grid) {
std::string map_directory_with_trailing_slash = map_directory;
AddTrailingSlashToDirectoryPathIfNeeded(map_directory_with_trailing_slash);
std::string map_pgm_file_path = map_directory_with_trailing_slash + map_name + ".pgm";
std::ifstream pgm_file(map_pgm_file_path, std::ios::binary);
if (pgm_file.fail()) {
LOG(ERROR) << "Could no open file " << map_pgm_file_path;
return false;
}
// First line contains file type.
std::string file_type;
getline(pgm_file, file_type);
LOG(INFO) << file_type;
if (file_type.compare("P5") != 0) {
LOG(ERROR) << "Pgm file type error. Type is " << file_type
<< " while supported type is P5.";
return false;
}
// Second line contains comment.
std::string comment;
getline(pgm_file, comment);
LOG(INFO) << comment;
// Third line contains size.
std::string image_size;
getline(pgm_file, image_size);
std::stringstream size_stream(image_size);
size_stream >> occupancy_grid->info.width >> occupancy_grid->info.height;
LOG(INFO) << "Image size is " << occupancy_grid->info.width << "x" << occupancy_grid->info.height;
// Fourth line contains max value.
std::string max_value_string;
getline(pgm_file, max_value_string);
std::stringstream max_val_stream(max_value_string);
int max_value = 0;
max_val_stream >> max_value;
// Following lines contain binary data.
int pixel_array[occupancy_grid->info.height * occupancy_grid->info.width];
for (size_t i = 0; i < occupancy_grid->info.height * occupancy_grid->info.width; ++i) {
char pixel = pgm_file.get();
pixel_array[i] = static_cast<int>(pixel);
}
// Need to invert the ordering of the pixels to
// produce a map with cell (0,0) in the lower-left corner.
occupancy_grid->data.reserve(occupancy_grid->info.height * occupancy_grid->info.width);
for (size_t i = 0; i < occupancy_grid->info.height; ++i) {
for (size_t j = 0; j < occupancy_grid->info.width; ++j) {
int value = pixel_array[j + (occupancy_grid->info.height - i - 1) * occupancy_grid->info.width];
if (negate)
value = max_value - value;
double occupancy = (max_value - value) / static_cast<double>(max_value);
if (occupancy < free_threshold) {
occupancy_grid->data.push_back(0);
} else if (occupancy > occupied_threshold) {
occupancy_grid->data.push_back(100);
} else {
occupancy_grid->data.push_back(-1);
}
}
}
pgm_file.close();
return true;
}
bool LoadOccupancyGridMetadataFromYamlFile(
const std::string& map_name, const std::string& map_directory,
nav_msgs::MapMetaData* map_metadata, int* negate,
double* occupied_threshold, double* free_threshold, std::string* map_uuid) {
std::string map_directory_with_trailing_slash = map_directory;
AddTrailingSlashToDirectoryPathIfNeeded(map_directory_with_trailing_slash);
std::string map_yam_file_path = map_directory_with_trailing_slash + map_name + ".yaml";
std::ifstream yaml_file(map_yam_file_path.c_str());
if (yaml_file.fail()) {
LOG(ERROR) << "Could no open file " << map_yam_file_path;
return false;
}
YAML::Node node = YAML::Load(yaml_file);
try {
map_metadata->resolution = node["resolution"].as<double>();
} catch (YAML::RepresentationException& e) {
LOG(ERROR) << "The map does not contain a resolution tag or it is invalid. " << e.msg;
return false;
}
try {
*negate = node["negate"].as<int>();
} catch (YAML::RepresentationException& e) {
LOG(ERROR) << "The map does not contain a negate tag or it is invalid. " << e.msg;
return false;
}
try {
*occupied_threshold = node["occupied_thresh"].as<double>();
} catch (YAML::RepresentationException& e) {
LOG(ERROR) << "The map does not contain an occupied_thresh tag or it is invalid. " << e.msg;
return false;
}
try {
*free_threshold = node["free_thresh"].as<double>();
} catch (YAML::RepresentationException& e) {
LOG(ERROR) << "The map does not contain a free_thresh tag or it is invalid. " << e.msg;
return false;
}
try {
map_metadata->origin.position.x = node["origin"][0].as<double>();
map_metadata->origin.position.y = node["origin"][1].as<double>();
map_metadata->origin.position.z = 0.0;
tf::Quaternion quaternion;
double yaw = node["origin"][2].as<double>();
quaternion.setRPY(0., 0., yaw);
map_metadata->origin.orientation.x = quaternion.x();
map_metadata->origin.orientation.y = quaternion.y();
map_metadata->origin.orientation.z = quaternion.z();
map_metadata->origin.orientation.w = quaternion.w();
} catch (YAML::RepresentationException& e) {
LOG(ERROR) << "The map does not contain an origin tag or it is invalid. " << e.msg;
return false;
}
try {
*map_uuid = node["uuid"].as<std::string>();
} catch (YAML::RepresentationException& e) {
LOG(WARNING) << "The map does not contain a uuid tag or it is invalid. " << e.msg;
}
yaml_file.close();
return true;
}
} // namespace occupancy_grid_file_io
<commit_msg>Create occupancy grid directory if it does not exist<commit_after>// Copyright 2017 Intermodalics 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 "tango_ros_native/occupancy_grid_file_io.h"
#include <cmath>
#include <fstream>
#include <iostream>
#include <sys/stat.h>
#include <unistd.h>
#include <geometry_msgs/Quaternion.h>
#include <tf/LinearMath/Matrix3x3.h>
#include <glog/logging.h>
#include <yaml-cpp/yaml.h>
namespace {
void AddTrailingSlashToDirectoryPathIfNeeded(std::string& directory_path) {
if (!directory_path.empty() && directory_path.back() != '/') {
directory_path += '/';
}
}
bool DirectoryPathExists(const std::string& path) {
struct stat st;
if (stat(path.c_str(), &st) == 0 && (st.st_mode & S_IFDIR)) {
return true;
} else {
return false;
}
}
int MakeDirectoryPath(const std::string& input_path, mode_t mode) {
if (input_path.empty()) {
// Path is empty, there is nothing to create so we return success.
return 0;
}
size_t previous_slash_pos = 0;
size_t current_slash_pos;
std::string dir;
int make_dir_status = 0;
std::string path = input_path;
CHECK(!path.empty());
AddTrailingSlashToDirectoryPathIfNeeded(path);
while ((current_slash_pos = path.find_first_of('/', previous_slash_pos)) !=
std::string::npos) {
dir = path.substr(0, current_slash_pos++);
previous_slash_pos = current_slash_pos;
if (dir.empty())
continue; // If leading / first time is 0 length.
if (dir == ".")
continue;
if ((make_dir_status = mkdir(dir.c_str(), mode)) && errno != EEXIST) {
return make_dir_status;
}
}
return 0;
}
} // namespace
namespace occupancy_grid_file_io {
bool SaveOccupancyGridToFiles(
const std::string& map_name, const std::string& map_uuid,
const std::string& map_directory, const nav_msgs::OccupancyGrid& occupancy_grid) {
return SaveOccupancyGridDataToPgmFile(map_name, map_directory, occupancy_grid)
&& SaveOccupancyGridMetadataToYamlFile(map_name, map_uuid, map_directory, occupancy_grid.info);
}
bool SaveOccupancyGridDataToPgmFile(
const std::string& map_name, const std::string& map_directory,
const nav_msgs::OccupancyGrid& occupancy_grid) {
std::string map_directory_with_trailing_slash = map_directory;
AddTrailingSlashToDirectoryPathIfNeeded(map_directory_with_trailing_slash);
if (!DirectoryPathExists(map_directory_with_trailing_slash)) {
LOG(INFO) << "Directory " << map_directory_with_trailing_slash << " does not exist, creating it now.";
if (MakeDirectoryPath(map_directory_with_trailing_slash, S_IRWXU | S_IRWXG | S_IROTH | S_IXOTH) != 0) {
LOG(ERROR) << "Could not create directory: " << map_directory_with_trailing_slash;
return false;
}
}
std::string map_pgm_file_path = map_directory_with_trailing_slash + map_name + ".pgm";
FILE* pgm_file = fopen(map_pgm_file_path.c_str(), "w");
if (!pgm_file) {
LOG(ERROR) << "Could no open file " << map_pgm_file_path;
return false;
}
fprintf(pgm_file, "P5\n# CREATOR: TangoRosStreamer %.3f m/pix\n%d %d\n255\n",
occupancy_grid.info.resolution,
occupancy_grid.info.width, occupancy_grid.info.height);
for (size_t i = 0; i < occupancy_grid.info.height; ++i) {
for (size_t j = 0; j < occupancy_grid.info.width; ++j) {
// Need to invert the ordering of the cells to
// produce an image with pixel (0,0) in the top-left corner.
int value = occupancy_grid.data[j + (occupancy_grid.info.height - i - 1) * occupancy_grid.info.width];
if (value == 0) {
fputc(254, pgm_file);
} else if (value == +100) {
fputc(000, pgm_file);
} else {
fputc(205, pgm_file);
}
}
}
fclose(pgm_file);
LOG(INFO) << "Map image successfully saved to " << map_pgm_file_path;
return true;
}
bool SaveOccupancyGridMetadataToYamlFile(
const std::string& map_name, const std::string& map_uuid,
const std::string& map_directory, const nav_msgs::MapMetaData& map_metadata) {
std::string map_directory_with_trailing_slash = map_directory;
AddTrailingSlashToDirectoryPathIfNeeded(map_directory_with_trailing_slash);
if (!DirectoryPathExists(map_directory_with_trailing_slash)) {
LOG(INFO) << "Directory " << map_directory_with_trailing_slash << " does not exist, creating it now.";
if (MakeDirectoryPath(map_directory_with_trailing_slash, S_IRWXU | S_IRWXG | S_IROTH | S_IXOTH) != 0) {
LOG(ERROR) << "Could not create directory: " << map_directory_with_trailing_slash;
return false;
}
}
std::string image_name = map_name;
if (image_name.empty())
image_name = "\"\"";
std::string uuid = map_uuid;
if (uuid.empty())
uuid = "\"\"";
std::string map_yaml_file_path = map_directory_with_trailing_slash + map_name + ".yaml";
FILE* yaml_file = fopen(map_yaml_file_path.c_str(), "w");
if (!yaml_file) {
LOG(ERROR) << "Could no open file " << map_yaml_file_path;
return false;
}
tf::Matrix3x3 mat(tf::Quaternion(map_metadata.origin.orientation.x,
map_metadata.origin.orientation.y,
map_metadata.origin.orientation.z,
map_metadata.origin.orientation.w));
double yaw, pitch, roll;
mat.getEulerYPR(yaw, pitch, roll);
if (std::isnan(yaw))
yaw = 0.0;
fprintf(yaml_file, "image: %s.pgm\nresolution: %f\norigin: [%f, %f, %f]\nnegate: 0\n"
"occupied_thresh: 0.65\nfree_thresh: 0.196\nuuid: %s\n\n",
map_name.c_str(), map_metadata.resolution, map_metadata.origin.position.x,
map_metadata.origin.position.y, yaw, uuid.c_str());
fclose(yaml_file);
LOG(INFO) << "Map yaml file successfully saved to " << map_yaml_file_path;
return true;
}
bool LoadOccupancyGridFromFiles(
const std::string& map_name, const std::string& map_directory,
nav_msgs::OccupancyGrid* occupancy_grid, std::string* map_uuid) {
int negate;
double occupied_threshold;
double free_threshold;
bool result = LoadOccupancyGridMetadataFromYamlFile(
map_name, map_directory, &(occupancy_grid->info), &negate,
&occupied_threshold, &free_threshold, map_uuid);
return result && LoadOccupancyGridDataFromPgmFile(
map_name, map_directory, negate, occupied_threshold, free_threshold,
occupancy_grid);
}
bool LoadOccupancyGridDataFromPgmFile(
const std::string& map_name, const std::string& map_directory,
bool negate, double occupied_threshold, double free_threshold,
nav_msgs::OccupancyGrid* occupancy_grid) {
std::string map_directory_with_trailing_slash = map_directory;
AddTrailingSlashToDirectoryPathIfNeeded(map_directory_with_trailing_slash);
std::string map_pgm_file_path = map_directory_with_trailing_slash + map_name + ".pgm";
std::ifstream pgm_file(map_pgm_file_path, std::ios::binary);
if (pgm_file.fail()) {
LOG(ERROR) << "Could no open file " << map_pgm_file_path;
return false;
}
// First line contains file type.
std::string file_type;
getline(pgm_file, file_type);
LOG(INFO) << file_type;
if (file_type.compare("P5") != 0) {
LOG(ERROR) << "Pgm file type error. Type is " << file_type
<< " while supported type is P5.";
return false;
}
// Second line contains comment.
std::string comment;
getline(pgm_file, comment);
LOG(INFO) << comment;
// Third line contains size.
std::string image_size;
getline(pgm_file, image_size);
std::stringstream size_stream(image_size);
size_stream >> occupancy_grid->info.width >> occupancy_grid->info.height;
LOG(INFO) << "Image size is " << occupancy_grid->info.width << "x" << occupancy_grid->info.height;
// Fourth line contains max value.
std::string max_value_string;
getline(pgm_file, max_value_string);
std::stringstream max_val_stream(max_value_string);
int max_value = 0;
max_val_stream >> max_value;
// Following lines contain binary data.
int pixel_array[occupancy_grid->info.height * occupancy_grid->info.width];
for (size_t i = 0; i < occupancy_grid->info.height * occupancy_grid->info.width; ++i) {
char pixel = pgm_file.get();
pixel_array[i] = static_cast<int>(pixel);
}
// Need to invert the ordering of the pixels to
// produce a map with cell (0,0) in the lower-left corner.
occupancy_grid->data.reserve(occupancy_grid->info.height * occupancy_grid->info.width);
for (size_t i = 0; i < occupancy_grid->info.height; ++i) {
for (size_t j = 0; j < occupancy_grid->info.width; ++j) {
int value = pixel_array[j + (occupancy_grid->info.height - i - 1) * occupancy_grid->info.width];
if (negate)
value = max_value - value;
double occupancy = (max_value - value) / static_cast<double>(max_value);
if (occupancy < free_threshold) {
occupancy_grid->data.push_back(0);
} else if (occupancy > occupied_threshold) {
occupancy_grid->data.push_back(100);
} else {
occupancy_grid->data.push_back(-1);
}
}
}
pgm_file.close();
LOG(INFO) << "Map image successfully loaded from " << map_pgm_file_path;
return true;
}
bool LoadOccupancyGridMetadataFromYamlFile(
const std::string& map_name, const std::string& map_directory,
nav_msgs::MapMetaData* map_metadata, int* negate,
double* occupied_threshold, double* free_threshold, std::string* map_uuid) {
std::string map_directory_with_trailing_slash = map_directory;
AddTrailingSlashToDirectoryPathIfNeeded(map_directory_with_trailing_slash);
std::string map_yam_file_path = map_directory_with_trailing_slash + map_name + ".yaml";
std::ifstream yaml_file(map_yam_file_path.c_str());
if (yaml_file.fail()) {
LOG(ERROR) << "Could no open file " << map_yam_file_path;
return false;
}
YAML::Node node = YAML::Load(yaml_file);
try {
map_metadata->resolution = node["resolution"].as<double>();
} catch (YAML::RepresentationException& e) {
LOG(ERROR) << "The map does not contain a resolution tag or it is invalid. " << e.msg;
return false;
}
try {
*negate = node["negate"].as<int>();
} catch (YAML::RepresentationException& e) {
LOG(ERROR) << "The map does not contain a negate tag or it is invalid. " << e.msg;
return false;
}
try {
*occupied_threshold = node["occupied_thresh"].as<double>();
} catch (YAML::RepresentationException& e) {
LOG(ERROR) << "The map does not contain an occupied_thresh tag or it is invalid. " << e.msg;
return false;
}
try {
*free_threshold = node["free_thresh"].as<double>();
} catch (YAML::RepresentationException& e) {
LOG(ERROR) << "The map does not contain a free_thresh tag or it is invalid. " << e.msg;
return false;
}
try {
map_metadata->origin.position.x = node["origin"][0].as<double>();
map_metadata->origin.position.y = node["origin"][1].as<double>();
map_metadata->origin.position.z = 0.0;
tf::Quaternion quaternion;
double yaw = node["origin"][2].as<double>();
quaternion.setRPY(0., 0., yaw);
map_metadata->origin.orientation.x = quaternion.x();
map_metadata->origin.orientation.y = quaternion.y();
map_metadata->origin.orientation.z = quaternion.z();
map_metadata->origin.orientation.w = quaternion.w();
} catch (YAML::RepresentationException& e) {
LOG(ERROR) << "The map does not contain an origin tag or it is invalid. " << e.msg;
return false;
}
try {
*map_uuid = node["uuid"].as<std::string>();
} catch (YAML::RepresentationException& e) {
LOG(WARNING) << "The map does not contain a uuid tag or it is invalid. " << e.msg;
}
yaml_file.close();
LOG(INFO) << "Map yaml file successfully loaded from " << map_yam_file_path;
return true;
}
} // namespace occupancy_grid_file_io
<|endoftext|> |
<commit_before>#include <cctype>
#include <cstdlib>
#include <cstring>
#include <stdio.h>
#include <v8.h>
#include <node.h>
#include <node_buffer.h>
#include <openssl/bn.h>
#include <openssl/buffer.h>
#include <openssl/ecdsa.h>
#include <openssl/evp.h>
#include <openssl/rand.h>
#include <openssl/sha.h>
#include <openssl/ripemd.h>
using namespace std;
using namespace v8;
using namespace node;
static Handle<Value> VException(const char *msg) {
HandleScope scope;
return ThrowException(Exception::Error(String::New(msg)));
}
static Handle<Value>
new_keypair (const Arguments& args)
{
HandleScope scope;
EC_KEY* pkey;
// Generate
pkey = EC_KEY_new_by_curve_name(NID_secp256k1);
if (pkey == NULL) {
return VException("Error from EC_KEY_new_by_curve_name");
}
if (!EC_KEY_generate_key(pkey)) {
return VException("Error from EC_KEY_generate_key");
}
// Export private
unsigned int priv_size = i2d_ECPrivateKey(pkey, NULL);
if (!priv_size) {
return VException("Error from i2d_ECPrivateKey(pkey, NULL)");
}
unsigned char *priv = (unsigned char *)malloc(priv_size);
if (i2d_ECPrivateKey(pkey, &priv) != priv_size) {
return VException("Error from i2d_ECPrivateKey(pkey, &priv)");
}
// Export public
unsigned int pub_size = i2o_ECPublicKey(pkey, NULL);
if (!pub_size) {
return VException("Error from i2o_ECPublicKey(pkey, NULL)");
}
unsigned char *pub = (unsigned char *)malloc(pub_size);
if (i2o_ECPublicKey(pkey, &pub) != pub_size) {
return VException("Error from i2o_ECPublicKey(pkey, &pub)");
}
// Return [priv_buf, pub_buf]
Local<Array> a = Array::New(2);
Buffer *priv_buf = Buffer::New(priv_size);
memcpy(Buffer::Data(priv_buf), priv, priv_size);
a->Set(Integer::New(0), priv_buf->handle_);
Buffer *pub_buf = Buffer::New(pub_size);
memcpy(Buffer::Data(pub_buf), pub, pub_size);
a->Set(Integer::New(1), pub_buf->handle_);
EC_KEY_free(pkey);
free(priv);
free(pub);
return scope.Close(a);
}
static Handle<Value>
pubkey_to_address256 (const Arguments& args)
{
HandleScope scope;
if (args.Length() != 1) {
return VException("One argument expected: pubkey Buffer");
}
if (!Buffer::HasInstance(args[0])) {
return VException("One argument expected: pubkey Buffer");
}
v8::Handle<v8::Object> pub_buf = args[0]->ToObject();
unsigned char *pub_data = (unsigned char *) Buffer::Data(pub_buf);
// sha256(pubkey)
unsigned char hash1[SHA256_DIGEST_LENGTH];
SHA256_CTX c;
SHA256_Init(&c);
SHA256_Update(&c, pub_data, Buffer::Length(pub_buf));
SHA256_Final(hash1, &c);
// ripemd160(sha256(pubkey))
unsigned char hash2[RIPEMD160_DIGEST_LENGTH];
RIPEMD160_CTX c2;
RIPEMD160_Init(&c2);
RIPEMD160_Update(&c2, hash1, SHA256_DIGEST_LENGTH);
RIPEMD160_Final(hash2, &c2);
// x = '\x00' + ripemd160(sha256(pubkey))
// LATER: make the version an optional argument
unsigned char address256[1 + RIPEMD160_DIGEST_LENGTH + 4];
address256[0] = 0;
memcpy(address256 + 1, hash2, RIPEMD160_DIGEST_LENGTH);
// sha256(x)
unsigned char hash3[SHA256_DIGEST_LENGTH];
SHA256_CTX c3;
SHA256_Init(&c3);
SHA256_Update(&c3, address256, 1 + RIPEMD160_DIGEST_LENGTH);
SHA256_Final(hash3, &c3);
// address256 = (x + sha256(x)[:4])
memcpy(
address256 + (1 + RIPEMD160_DIGEST_LENGTH),
hash3,
4);
Buffer *address256_buf = Buffer::New(1 + RIPEMD160_DIGEST_LENGTH + 4);
memcpy(Buffer::Data(address256_buf), address256, 1 + RIPEMD160_DIGEST_LENGTH + 4);
return scope.Close(address256_buf->handle_);
}
static const char* BASE58_ALPHABET = "123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz";
static Handle<Value>
base58_encode (const Arguments& args)
{
HandleScope scope;
if (args.Length() != 1) {
return VException("One argument expected: a Buffer");
}
if (!Buffer::HasInstance(args[0])) {
return VException("One argument expected: a Buffer");
}
v8::Handle<v8::Object> buf = args[0]->ToObject();
unsigned char *buf_data = (unsigned char *) Buffer::Data(buf);
int buf_length = Buffer::Length(buf);
BN_CTX *ctx = BN_CTX_new();
BIGNUM *bn = BN_bin2bn(buf_data, buf_length, NULL);
BIGNUM *bn58 = BN_new();
BN_set_word(bn58, 58);
BIGNUM *bn0 = BN_new();
BN_set_word(bn0, 0);
BIGNUM *dv = BN_new();
BIGNUM *rem = BN_new();
// TODO: compute safe length
char *str = new char[100];
unsigned int c;
int i, j, j2;
i = 0;
while (BN_cmp(bn, bn0) > 0) {
if (!BN_div(dv, rem, bn, bn58, ctx)) {
return VException("BN_div failed");
}
bn = dv;
c = BN_get_word(rem);
str[i] = BASE58_ALPHABET[c];
i++;
}
// Leading zeros
for (j = 0; j < buf_length; j++) {
if (buf_data[j] != 0) {
break;
}
str[i] = BASE58_ALPHABET[0];
i++;
}
// Terminator
str[i] = 0;
// Reverse string
int numSwaps = (i / 2);
char tmp;
for (j = 0; j < numSwaps; j++) {
j2 = i - 1 - j;
tmp = str[j];
str[j] = str[j2];
str[j2] = tmp;
}
BN_free(bn);
BN_free(bn58);
BN_free(bn0);
BN_free(dv);
BN_free(rem);
BN_CTX_free(ctx);
Local<String> ret = String::New(str);
delete [] str;
return scope.Close(ret);
}
static Handle<Value>
base58_decode (const Arguments& args)
{
HandleScope scope;
if (args.Length() != 1) {
return VException("One argument expected: a String");
}
if (!args[0]->IsString()) {
return VException("One argument expected: a String");
}
BN_CTX *ctx = BN_CTX_new();
BIGNUM *bn58 = BN_new();
BN_set_word(bn58, 58);
BIGNUM *bn = BN_new();
BN_set_word(bn, 0);
BIGNUM *bnChar = BN_new();
String::Utf8Value str(args[0]->ToString());
char *psz = *str;
while (isspace(*psz))
psz++;
// Convert big endian string to bignum
for (const char* p = psz; *p; p++) {
const char* p1 = strchr(BASE58_ALPHABET, *p);
if (p1 == NULL) {
while (isspace(*p))
p++;
if (*p != '\0')
return VException("Error");
break;
}
BN_set_word(bnChar, p1 - BASE58_ALPHABET);
if (!BN_mul(bn, bn, bn58, ctx))
return VException("BN_mul failed");
if (!BN_add(bn, bn, bnChar))
return VException("BN_add failed");
}
// Get bignum as little endian data
unsigned int tmpLen = BN_num_bytes(bn);
unsigned char *tmp = (unsigned char *)malloc(tmpLen);
BN_bn2bin(bn, tmp);
// Trim off sign byte if present
if (tmpLen >= 2 && tmp[tmpLen-1] == 0 && tmp[tmpLen-2] >= 0x80)
tmpLen--;
// Restore leading zeros
int nLeadingZeros = 0;
for (const char* p = psz; *p == BASE58_ALPHABET[0]; p++)
nLeadingZeros++;
// Allocate buffer and zero it
Buffer *buf = Buffer::New(nLeadingZeros + tmpLen);
char* data = Buffer::Data(buf);
memset(data, 0, nLeadingZeros + tmpLen);
memcpy(data+nLeadingZeros, tmp, tmpLen);
BN_free(bn58);
BN_free(bn);
BN_free(bnChar);
BN_CTX_free(ctx);
free(tmp);
return scope.Close(buf->handle_);
}
extern "C" void
init (Handle<Object> target)
{
HandleScope scope;
target->Set(String::New("new_keypair"), FunctionTemplate::New(new_keypair)->GetFunction());
target->Set(String::New("pubkey_to_address256"), FunctionTemplate::New(pubkey_to_address256)->GetFunction());
target->Set(String::New("base58_encode"), FunctionTemplate::New(base58_encode)->GetFunction());
target->Set(String::New("base58_decode"), FunctionTemplate::New(base58_decode)->GetFunction());
}
<commit_msg>Fixed double free in base58_encode().<commit_after>#include <cctype>
#include <cstdlib>
#include <cstring>
#include <stdio.h>
#include <v8.h>
#include <node.h>
#include <node_buffer.h>
#include <openssl/bn.h>
#include <openssl/buffer.h>
#include <openssl/ecdsa.h>
#include <openssl/evp.h>
#include <openssl/rand.h>
#include <openssl/sha.h>
#include <openssl/ripemd.h>
using namespace std;
using namespace v8;
using namespace node;
static Handle<Value> VException(const char *msg) {
HandleScope scope;
return ThrowException(Exception::Error(String::New(msg)));
}
static Handle<Value>
new_keypair (const Arguments& args)
{
HandleScope scope;
EC_KEY* pkey;
// Generate
pkey = EC_KEY_new_by_curve_name(NID_secp256k1);
if (pkey == NULL) {
return VException("Error from EC_KEY_new_by_curve_name");
}
if (!EC_KEY_generate_key(pkey)) {
return VException("Error from EC_KEY_generate_key");
}
// Export private
unsigned int priv_size = i2d_ECPrivateKey(pkey, NULL);
if (!priv_size) {
return VException("Error from i2d_ECPrivateKey(pkey, NULL)");
}
unsigned char *priv = (unsigned char *)malloc(priv_size);
if (i2d_ECPrivateKey(pkey, &priv) != priv_size) {
return VException("Error from i2d_ECPrivateKey(pkey, &priv)");
}
// Export public
unsigned int pub_size = i2o_ECPublicKey(pkey, NULL);
if (!pub_size) {
return VException("Error from i2o_ECPublicKey(pkey, NULL)");
}
unsigned char *pub = (unsigned char *)malloc(pub_size);
if (i2o_ECPublicKey(pkey, &pub) != pub_size) {
return VException("Error from i2o_ECPublicKey(pkey, &pub)");
}
// Return [priv_buf, pub_buf]
Local<Array> a = Array::New(2);
Buffer *priv_buf = Buffer::New(priv_size);
memcpy(Buffer::Data(priv_buf), priv, priv_size);
a->Set(Integer::New(0), priv_buf->handle_);
Buffer *pub_buf = Buffer::New(pub_size);
memcpy(Buffer::Data(pub_buf), pub, pub_size);
a->Set(Integer::New(1), pub_buf->handle_);
EC_KEY_free(pkey);
free(priv);
free(pub);
return scope.Close(a);
}
static Handle<Value>
pubkey_to_address256 (const Arguments& args)
{
HandleScope scope;
if (args.Length() != 1) {
return VException("One argument expected: pubkey Buffer");
}
if (!Buffer::HasInstance(args[0])) {
return VException("One argument expected: pubkey Buffer");
}
v8::Handle<v8::Object> pub_buf = args[0]->ToObject();
unsigned char *pub_data = (unsigned char *) Buffer::Data(pub_buf);
// sha256(pubkey)
unsigned char hash1[SHA256_DIGEST_LENGTH];
SHA256_CTX c;
SHA256_Init(&c);
SHA256_Update(&c, pub_data, Buffer::Length(pub_buf));
SHA256_Final(hash1, &c);
// ripemd160(sha256(pubkey))
unsigned char hash2[RIPEMD160_DIGEST_LENGTH];
RIPEMD160_CTX c2;
RIPEMD160_Init(&c2);
RIPEMD160_Update(&c2, hash1, SHA256_DIGEST_LENGTH);
RIPEMD160_Final(hash2, &c2);
// x = '\x00' + ripemd160(sha256(pubkey))
// LATER: make the version an optional argument
unsigned char address256[1 + RIPEMD160_DIGEST_LENGTH + 4];
address256[0] = 0;
memcpy(address256 + 1, hash2, RIPEMD160_DIGEST_LENGTH);
// sha256(x)
unsigned char hash3[SHA256_DIGEST_LENGTH];
SHA256_CTX c3;
SHA256_Init(&c3);
SHA256_Update(&c3, address256, 1 + RIPEMD160_DIGEST_LENGTH);
SHA256_Final(hash3, &c3);
// address256 = (x + sha256(x)[:4])
memcpy(
address256 + (1 + RIPEMD160_DIGEST_LENGTH),
hash3,
4);
Buffer *address256_buf = Buffer::New(1 + RIPEMD160_DIGEST_LENGTH + 4);
memcpy(Buffer::Data(address256_buf), address256, 1 + RIPEMD160_DIGEST_LENGTH + 4);
return scope.Close(address256_buf->handle_);
}
static const char* BASE58_ALPHABET = "123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz";
static Handle<Value>
base58_encode (const Arguments& args)
{
HandleScope scope;
if (args.Length() != 1) {
return VException("One argument expected: a Buffer");
}
if (!Buffer::HasInstance(args[0])) {
return VException("One argument expected: a Buffer");
}
v8::Handle<v8::Object> buf = args[0]->ToObject();
unsigned char *buf_data = (unsigned char *) Buffer::Data(buf);
int buf_length = Buffer::Length(buf);
BN_CTX *ctx = BN_CTX_new();
BIGNUM *bn = BN_bin2bn(buf_data, buf_length, NULL);
BIGNUM *bn58 = BN_new();
BN_set_word(bn58, 58);
BIGNUM *bn0 = BN_new();
BN_set_word(bn0, 0);
BIGNUM *dv = BN_new();
BIGNUM *rem = BN_new();
// TODO: compute safe length
char *str = new char[100];
unsigned int c;
int i, j, j2;
i = 0;
while (BN_cmp(bn, bn0) > 0) {
if (!BN_div(dv, rem, bn, bn58, ctx)) {
return VException("BN_div failed");
}
if (bn != dv) {
BN_free(bn);
bn = dv;
}
c = BN_get_word(rem);
str[i] = BASE58_ALPHABET[c];
i++;
}
// Leading zeros
for (j = 0; j < buf_length; j++) {
if (buf_data[j] != 0) {
break;
}
str[i] = BASE58_ALPHABET[0];
i++;
}
// Terminator
str[i] = 0;
// Reverse string
int numSwaps = (i / 2);
char tmp;
for (j = 0; j < numSwaps; j++) {
j2 = i - 1 - j;
tmp = str[j];
str[j] = str[j2];
str[j2] = tmp;
}
BN_free(bn);
BN_free(bn58);
BN_free(bn0);
BN_free(rem);
BN_CTX_free(ctx);
Local<String> ret = String::New(str);
delete [] str;
return scope.Close(ret);
}
static Handle<Value>
base58_decode (const Arguments& args)
{
HandleScope scope;
if (args.Length() != 1) {
return VException("One argument expected: a String");
}
if (!args[0]->IsString()) {
return VException("One argument expected: a String");
}
BN_CTX *ctx = BN_CTX_new();
BIGNUM *bn58 = BN_new();
BN_set_word(bn58, 58);
BIGNUM *bn = BN_new();
BN_set_word(bn, 0);
BIGNUM *bnChar = BN_new();
String::Utf8Value str(args[0]->ToString());
char *psz = *str;
while (isspace(*psz))
psz++;
// Convert big endian string to bignum
for (const char* p = psz; *p; p++) {
const char* p1 = strchr(BASE58_ALPHABET, *p);
if (p1 == NULL) {
while (isspace(*p))
p++;
if (*p != '\0')
return VException("Error");
break;
}
BN_set_word(bnChar, p1 - BASE58_ALPHABET);
if (!BN_mul(bn, bn, bn58, ctx))
return VException("BN_mul failed");
if (!BN_add(bn, bn, bnChar))
return VException("BN_add failed");
}
// Get bignum as little endian data
unsigned int tmpLen = BN_num_bytes(bn);
unsigned char *tmp = (unsigned char *)malloc(tmpLen);
BN_bn2bin(bn, tmp);
// Trim off sign byte if present
if (tmpLen >= 2 && tmp[tmpLen-1] == 0 && tmp[tmpLen-2] >= 0x80)
tmpLen--;
// Restore leading zeros
int nLeadingZeros = 0;
for (const char* p = psz; *p == BASE58_ALPHABET[0]; p++)
nLeadingZeros++;
// Allocate buffer and zero it
Buffer *buf = Buffer::New(nLeadingZeros + tmpLen);
char* data = Buffer::Data(buf);
memset(data, 0, nLeadingZeros + tmpLen);
memcpy(data+nLeadingZeros, tmp, tmpLen);
BN_free(bn58);
BN_free(bn);
BN_free(bnChar);
BN_CTX_free(ctx);
free(tmp);
return scope.Close(buf->handle_);
}
extern "C" void
init (Handle<Object> target)
{
HandleScope scope;
target->Set(String::New("new_keypair"), FunctionTemplate::New(new_keypair)->GetFunction());
target->Set(String::New("pubkey_to_address256"), FunctionTemplate::New(pubkey_to_address256)->GetFunction());
target->Set(String::New("base58_encode"), FunctionTemplate::New(base58_encode)->GetFunction());
target->Set(String::New("base58_decode"), FunctionTemplate::New(base58_decode)->GetFunction());
}
<|endoftext|> |
<commit_before>/****************************************************************************
**
** Copyright (C) 2011 Nokia Corporation and/or its subsidiary(-ies).
** All rights reserved.
** Contact: Nokia Corporation ([email protected])
**
** This file is part of the test suite of the Qt Toolkit.
**
** $QT_BEGIN_LICENSE:LGPL$
** No Commercial Usage
** This file contains pre-release code and may not be distributed.
** You may use this file in accordance with the terms and conditions
** contained in the Technology Preview License Agreement accompanying
** this package.
**
** GNU Lesser General Public License Usage
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 as published by the Free Software
** Foundation and appearing in the file LICENSE.LGPL included in the
** packaging of this file. Please review the following information to
** ensure the GNU Lesser General Public License version 2.1 requirements
** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, Nokia gives you certain additional
** rights. These rights are described in the Nokia Qt LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
** If you have questions regarding the use of this file, please contact
** Nokia at [email protected].
**
**
**
**
**
**
**
**
** $QT_END_LICENSE$
**
****************************************************************************/
#include <qtest.h>
#include <QtDeclarative/qdeclarativeengine.h>
#include <QtDeclarative/qdeclarativecomponent.h>
#include <QtDeclarative/qsgview.h>
#include <private/qsgrectangle_p.h>
#include <private/qsgimage_p.h>
#include <private/qsganimatedimage_p.h>
#include <QSignalSpy>
#include <QtDeclarative/qdeclarativecontext.h>
#include "../shared/testhttpserver.h"
#include "../../../shared/util.h"
#ifdef Q_OS_SYMBIAN
// In Symbian OS test data is located in applications private dir
#define SRCDIR "."
#endif
class tst_qsganimatedimage : public QObject
{
Q_OBJECT
public:
tst_qsganimatedimage() {}
private slots:
void play();
void pause();
void stopped();
void setFrame();
void frameCount();
void mirror_running();
void mirror_notRunning();
void mirror_notRunning_data();
void remote();
void remote_data();
void sourceSize();
void sourceSizeReadOnly();
void invalidSource();
void qtbug_16520();
void progressAndStatusChanges();
};
void tst_qsganimatedimage::play()
{
QDeclarativeEngine engine;
QDeclarativeComponent component(&engine, QUrl::fromLocalFile(SRCDIR "/data/stickman.qml"));
QSGAnimatedImage *anim = qobject_cast<QSGAnimatedImage *>(component.create());
QVERIFY(anim);
QVERIFY(anim->isPlaying());
delete anim;
}
void tst_qsganimatedimage::pause()
{
QDeclarativeEngine engine;
QDeclarativeComponent component(&engine, QUrl::fromLocalFile(SRCDIR "/data/stickmanpause.qml"));
QSGAnimatedImage *anim = qobject_cast<QSGAnimatedImage *>(component.create());
QVERIFY(anim);
QVERIFY(anim->isPlaying());
QVERIFY(anim->isPaused());
delete anim;
}
void tst_qsganimatedimage::stopped()
{
QDeclarativeEngine engine;
QDeclarativeComponent component(&engine, QUrl::fromLocalFile(SRCDIR "/data/stickmanstopped.qml"));
QSGAnimatedImage *anim = qobject_cast<QSGAnimatedImage *>(component.create());
QVERIFY(anim);
QVERIFY(!anim->isPlaying());
QCOMPARE(anim->currentFrame(), 0);
delete anim;
}
void tst_qsganimatedimage::setFrame()
{
QDeclarativeEngine engine;
QDeclarativeComponent component(&engine, QUrl::fromLocalFile(SRCDIR "/data/stickmanpause.qml"));
QSGAnimatedImage *anim = qobject_cast<QSGAnimatedImage *>(component.create());
QVERIFY(anim);
QVERIFY(anim->isPlaying());
QCOMPARE(anim->currentFrame(), 2);
delete anim;
}
void tst_qsganimatedimage::frameCount()
{
QDeclarativeEngine engine;
QDeclarativeComponent component(&engine, QUrl::fromLocalFile(SRCDIR "/data/colors.qml"));
QSGAnimatedImage *anim = qobject_cast<QSGAnimatedImage *>(component.create());
QVERIFY(anim);
QVERIFY(anim->isPlaying());
QCOMPARE(anim->frameCount(), 3);
delete anim;
}
void tst_qsganimatedimage::mirror_running()
{
// test where mirror is set to true after animation has started
QSGView *canvas = new QSGView;
canvas->show();
canvas->setSource(QUrl::fromLocalFile(SRCDIR "/data/hearts.qml"));
QSGAnimatedImage *anim = qobject_cast<QSGAnimatedImage *>(canvas->rootObject());
QVERIFY(anim);
int width = anim->property("width").toInt();
QCOMPARE(anim->currentFrame(), 0);
QPixmap frame0 = canvas->renderPixmap();
anim->setCurrentFrame(1);
QPixmap frame1 = canvas->renderPixmap();
anim->setCurrentFrame(0);
QSignalSpy spy(anim, SIGNAL(frameChanged()));
anim->setPlaying(true);
QTRY_VERIFY(spy.count() == 1); spy.clear();
anim->setProperty("mirror", true);
QCOMPARE(anim->currentFrame(), 1);
QPixmap frame1_flipped = canvas->renderPixmap();
QTRY_VERIFY(spy.count() == 1); spy.clear();
QCOMPARE(anim->currentFrame(), 0); // animation only has 2 frames, should cycle back to first
QPixmap frame0_flipped = canvas->renderPixmap();
QTransform transform;
transform.translate(width, 0).scale(-1, 1.0);
QPixmap frame0_expected = frame0.transformed(transform);
QPixmap frame1_expected = frame1.transformed(transform);
QCOMPARE(frame0_flipped, frame0_expected);
QCOMPARE(frame1_flipped, frame1_expected);
delete canvas;
}
void tst_qsganimatedimage::mirror_notRunning()
{
QFETCH(QUrl, fileUrl);
QSGView *canvas = new QSGView;
canvas->show();
canvas->setSource(fileUrl);
QSGAnimatedImage *anim = qobject_cast<QSGAnimatedImage *>(canvas->rootObject());
QVERIFY(anim);
int width = anim->property("width").toInt();
QPixmap screenshot = canvas->renderPixmap();
QTransform transform;
transform.translate(width, 0).scale(-1, 1.0);
QPixmap expected = screenshot.transformed(transform);
int frame = anim->currentFrame();
bool playing = anim->isPlaying();
bool paused = anim->isPlaying();
anim->setProperty("mirror", true);
screenshot = canvas->renderPixmap();
QSKIP("Skip while QTBUG-19351 and QTBUG-19252 are not resolved", SkipSingle);
QCOMPARE(screenshot, expected);
// mirroring should not change the current frame or playing status
QCOMPARE(anim->currentFrame(), frame);
QCOMPARE(anim->isPlaying(), playing);
QCOMPARE(anim->isPaused(), paused);
delete canvas;
}
void tst_qsganimatedimage::mirror_notRunning_data()
{
QTest::addColumn<QUrl>("fileUrl");
QTest::newRow("paused") << QUrl::fromLocalFile(SRCDIR "/data/stickmanpause.qml");
QTest::newRow("stopped") << QUrl::fromLocalFile(SRCDIR "/data/stickmanstopped.qml");
}
void tst_qsganimatedimage::remote()
{
QFETCH(QString, fileName);
QFETCH(bool, paused);
TestHTTPServer server(14449);
QVERIFY(server.isValid());
server.serveDirectory(SRCDIR "/data");
QDeclarativeEngine engine;
QDeclarativeComponent component(&engine, QUrl("http://127.0.0.1:14449/" + fileName));
QTRY_VERIFY(component.isReady());
QSGAnimatedImage *anim = qobject_cast<QSGAnimatedImage *>(component.create());
QVERIFY(anim);
QTRY_VERIFY(anim->isPlaying());
if (paused) {
QTRY_VERIFY(anim->isPaused());
QCOMPARE(anim->currentFrame(), 2);
}
QVERIFY(anim->status() != QSGAnimatedImage::Error);
delete anim;
}
void tst_qsganimatedimage::sourceSize()
{
QDeclarativeEngine engine;
QDeclarativeComponent component(&engine, QUrl::fromLocalFile(SRCDIR "/data/stickmanscaled.qml"));
QSGAnimatedImage *anim = qobject_cast<QSGAnimatedImage *>(component.create());
QVERIFY(anim);
QCOMPARE(anim->width(),240.0);
QCOMPARE(anim->height(),180.0);
QCOMPARE(anim->sourceSize(),QSize(160,120));
delete anim;
}
void tst_qsganimatedimage::sourceSizeReadOnly()
{
QDeclarativeEngine engine;
QDeclarativeComponent component(&engine, QUrl::fromLocalFile(SRCDIR "/data/stickmanerror1.qml"));
QVERIFY(component.isError());
QCOMPARE(component.errors().at(0).description(), QString("Invalid property assignment: \"sourceSize\" is a read-only property"));
}
void tst_qsganimatedimage::remote_data()
{
QTest::addColumn<QString>("fileName");
QTest::addColumn<bool>("paused");
QTest::newRow("playing") << "stickman.qml" << false;
QTest::newRow("paused") << "stickmanpause.qml" << true;
}
void tst_qsganimatedimage::invalidSource()
{
QDeclarativeEngine engine;
QDeclarativeComponent component(&engine);
component.setData("import QtQuick 2.0\n AnimatedImage { source: \"no-such-file.gif\" }", QUrl::fromLocalFile(""));
QVERIFY(component.isReady());
QTest::ignoreMessage(QtWarningMsg, "file::2:2: QML AnimatedImage: Error Reading Animated Image File file:no-such-file.gif");
QSGAnimatedImage *anim = qobject_cast<QSGAnimatedImage *>(component.create());
QVERIFY(anim);
QVERIFY(!anim->isPlaying());
QVERIFY(!anim->isPaused());
QCOMPARE(anim->currentFrame(), 0);
QCOMPARE(anim->frameCount(), 0);
QTRY_VERIFY(anim->status() == 3);
}
void tst_qsganimatedimage::qtbug_16520()
{
TestHTTPServer server(14449);
QVERIFY(server.isValid());
server.serveDirectory(SRCDIR "/data");
QDeclarativeEngine engine;
QDeclarativeComponent component(&engine, QUrl::fromLocalFile(SRCDIR "/data/qtbug-16520.qml"));
QTRY_VERIFY(component.isReady());
QSGRectangle *root = qobject_cast<QSGRectangle *>(component.create());
QVERIFY(root);
QSGAnimatedImage *anim = root->findChild<QSGAnimatedImage*>("anim");
anim->setProperty("source", "http://127.0.0.1:14449/stickman.gif");
QTRY_VERIFY(anim->opacity() == 0);
QTRY_VERIFY(anim->opacity() == 1);
delete anim;
}
void tst_qsganimatedimage::progressAndStatusChanges()
{
TestHTTPServer server(14449);
QVERIFY(server.isValid());
server.serveDirectory(SRCDIR "/data");
QDeclarativeEngine engine;
QString componentStr = "import QtQuick 2.0\nAnimatedImage { source: srcImage }";
QDeclarativeContext *ctxt = engine.rootContext();
ctxt->setContextProperty("srcImage", QUrl::fromLocalFile(SRCDIR "/data/stickman.gif"));
QDeclarativeComponent component(&engine);
component.setData(componentStr.toLatin1(), QUrl::fromLocalFile(""));
QSGImage *obj = qobject_cast<QSGImage*>(component.create());
QVERIFY(obj != 0);
QVERIFY(obj->status() == QSGImage::Ready);
QTRY_VERIFY(obj->progress() == 1.0);
QSignalSpy sourceSpy(obj, SIGNAL(sourceChanged(const QUrl &)));
QSignalSpy progressSpy(obj, SIGNAL(progressChanged(qreal)));
QSignalSpy statusSpy(obj, SIGNAL(statusChanged(QSGImageBase::Status)));
// Loading local file
ctxt->setContextProperty("srcImage", QUrl::fromLocalFile(SRCDIR "/data/colors.gif"));
QTRY_VERIFY(obj->status() == QSGImage::Ready);
QTRY_VERIFY(obj->progress() == 1.0);
QTRY_COMPARE(sourceSpy.count(), 1);
QTRY_COMPARE(progressSpy.count(), 0);
QTRY_COMPARE(statusSpy.count(), 0);
// Loading remote file
ctxt->setContextProperty("srcImage", "http://127.0.0.1:14449/stickman.gif");
QTRY_VERIFY(obj->status() == QSGImage::Loading);
QTRY_VERIFY(obj->progress() == 0.0);
QTRY_VERIFY(obj->status() == QSGImage::Ready);
QTRY_VERIFY(obj->progress() == 1.0);
QTRY_COMPARE(sourceSpy.count(), 2);
QTRY_VERIFY(progressSpy.count() > 1);
QTRY_COMPARE(statusSpy.count(), 2);
ctxt->setContextProperty("srcImage", "");
QTRY_VERIFY(obj->status() == QSGImage::Null);
QTRY_VERIFY(obj->progress() == 0.0);
QTRY_COMPARE(sourceSpy.count(), 3);
QTRY_VERIFY(progressSpy.count() > 2);
QTRY_COMPARE(statusSpy.count(), 3);
}
QTEST_MAIN(tst_qsganimatedimage)
#include "tst_qsganimatedimage.moc"
<commit_msg>Skip another pixmap comparison test.<commit_after>/****************************************************************************
**
** Copyright (C) 2011 Nokia Corporation and/or its subsidiary(-ies).
** All rights reserved.
** Contact: Nokia Corporation ([email protected])
**
** This file is part of the test suite of the Qt Toolkit.
**
** $QT_BEGIN_LICENSE:LGPL$
** No Commercial Usage
** This file contains pre-release code and may not be distributed.
** You may use this file in accordance with the terms and conditions
** contained in the Technology Preview License Agreement accompanying
** this package.
**
** GNU Lesser General Public License Usage
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 as published by the Free Software
** Foundation and appearing in the file LICENSE.LGPL included in the
** packaging of this file. Please review the following information to
** ensure the GNU Lesser General Public License version 2.1 requirements
** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, Nokia gives you certain additional
** rights. These rights are described in the Nokia Qt LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
** If you have questions regarding the use of this file, please contact
** Nokia at [email protected].
**
**
**
**
**
**
**
**
** $QT_END_LICENSE$
**
****************************************************************************/
#include <qtest.h>
#include <QtDeclarative/qdeclarativeengine.h>
#include <QtDeclarative/qdeclarativecomponent.h>
#include <QtDeclarative/qsgview.h>
#include <private/qsgrectangle_p.h>
#include <private/qsgimage_p.h>
#include <private/qsganimatedimage_p.h>
#include <QSignalSpy>
#include <QtDeclarative/qdeclarativecontext.h>
#include "../shared/testhttpserver.h"
#include "../../../shared/util.h"
#ifdef Q_OS_SYMBIAN
// In Symbian OS test data is located in applications private dir
#define SRCDIR "."
#endif
class tst_qsganimatedimage : public QObject
{
Q_OBJECT
public:
tst_qsganimatedimage() {}
private slots:
void play();
void pause();
void stopped();
void setFrame();
void frameCount();
void mirror_running();
void mirror_notRunning();
void mirror_notRunning_data();
void remote();
void remote_data();
void sourceSize();
void sourceSizeReadOnly();
void invalidSource();
void qtbug_16520();
void progressAndStatusChanges();
};
void tst_qsganimatedimage::play()
{
QDeclarativeEngine engine;
QDeclarativeComponent component(&engine, QUrl::fromLocalFile(SRCDIR "/data/stickman.qml"));
QSGAnimatedImage *anim = qobject_cast<QSGAnimatedImage *>(component.create());
QVERIFY(anim);
QVERIFY(anim->isPlaying());
delete anim;
}
void tst_qsganimatedimage::pause()
{
QDeclarativeEngine engine;
QDeclarativeComponent component(&engine, QUrl::fromLocalFile(SRCDIR "/data/stickmanpause.qml"));
QSGAnimatedImage *anim = qobject_cast<QSGAnimatedImage *>(component.create());
QVERIFY(anim);
QVERIFY(anim->isPlaying());
QVERIFY(anim->isPaused());
delete anim;
}
void tst_qsganimatedimage::stopped()
{
QDeclarativeEngine engine;
QDeclarativeComponent component(&engine, QUrl::fromLocalFile(SRCDIR "/data/stickmanstopped.qml"));
QSGAnimatedImage *anim = qobject_cast<QSGAnimatedImage *>(component.create());
QVERIFY(anim);
QVERIFY(!anim->isPlaying());
QCOMPARE(anim->currentFrame(), 0);
delete anim;
}
void tst_qsganimatedimage::setFrame()
{
QDeclarativeEngine engine;
QDeclarativeComponent component(&engine, QUrl::fromLocalFile(SRCDIR "/data/stickmanpause.qml"));
QSGAnimatedImage *anim = qobject_cast<QSGAnimatedImage *>(component.create());
QVERIFY(anim);
QVERIFY(anim->isPlaying());
QCOMPARE(anim->currentFrame(), 2);
delete anim;
}
void tst_qsganimatedimage::frameCount()
{
QDeclarativeEngine engine;
QDeclarativeComponent component(&engine, QUrl::fromLocalFile(SRCDIR "/data/colors.qml"));
QSGAnimatedImage *anim = qobject_cast<QSGAnimatedImage *>(component.create());
QVERIFY(anim);
QVERIFY(anim->isPlaying());
QCOMPARE(anim->frameCount(), 3);
delete anim;
}
void tst_qsganimatedimage::mirror_running()
{
// test where mirror is set to true after animation has started
QSGView *canvas = new QSGView;
canvas->show();
canvas->setSource(QUrl::fromLocalFile(SRCDIR "/data/hearts.qml"));
QSGAnimatedImage *anim = qobject_cast<QSGAnimatedImage *>(canvas->rootObject());
QVERIFY(anim);
int width = anim->property("width").toInt();
QCOMPARE(anim->currentFrame(), 0);
QPixmap frame0 = canvas->renderPixmap();
anim->setCurrentFrame(1);
QPixmap frame1 = canvas->renderPixmap();
anim->setCurrentFrame(0);
QSignalSpy spy(anim, SIGNAL(frameChanged()));
anim->setPlaying(true);
QTRY_VERIFY(spy.count() == 1); spy.clear();
anim->setProperty("mirror", true);
QCOMPARE(anim->currentFrame(), 1);
QPixmap frame1_flipped = canvas->renderPixmap();
QTRY_VERIFY(spy.count() == 1); spy.clear();
QCOMPARE(anim->currentFrame(), 0); // animation only has 2 frames, should cycle back to first
QPixmap frame0_flipped = canvas->renderPixmap();
QSKIP("Skip while QTBUG-19351 and QTBUG-19252 are not resolved", SkipSingle);
QTransform transform;
transform.translate(width, 0).scale(-1, 1.0);
QPixmap frame0_expected = frame0.transformed(transform);
QPixmap frame1_expected = frame1.transformed(transform);
QCOMPARE(frame0_flipped, frame0_expected);
QCOMPARE(frame1_flipped, frame1_expected);
delete canvas;
}
void tst_qsganimatedimage::mirror_notRunning()
{
QFETCH(QUrl, fileUrl);
QSGView *canvas = new QSGView;
canvas->show();
canvas->setSource(fileUrl);
QSGAnimatedImage *anim = qobject_cast<QSGAnimatedImage *>(canvas->rootObject());
QVERIFY(anim);
int width = anim->property("width").toInt();
QPixmap screenshot = canvas->renderPixmap();
QTransform transform;
transform.translate(width, 0).scale(-1, 1.0);
QPixmap expected = screenshot.transformed(transform);
int frame = anim->currentFrame();
bool playing = anim->isPlaying();
bool paused = anim->isPlaying();
anim->setProperty("mirror", true);
screenshot = canvas->renderPixmap();
QSKIP("Skip while QTBUG-19351 and QTBUG-19252 are not resolved", SkipSingle);
QCOMPARE(screenshot, expected);
// mirroring should not change the current frame or playing status
QCOMPARE(anim->currentFrame(), frame);
QCOMPARE(anim->isPlaying(), playing);
QCOMPARE(anim->isPaused(), paused);
delete canvas;
}
void tst_qsganimatedimage::mirror_notRunning_data()
{
QTest::addColumn<QUrl>("fileUrl");
QTest::newRow("paused") << QUrl::fromLocalFile(SRCDIR "/data/stickmanpause.qml");
QTest::newRow("stopped") << QUrl::fromLocalFile(SRCDIR "/data/stickmanstopped.qml");
}
void tst_qsganimatedimage::remote()
{
QFETCH(QString, fileName);
QFETCH(bool, paused);
TestHTTPServer server(14449);
QVERIFY(server.isValid());
server.serveDirectory(SRCDIR "/data");
QDeclarativeEngine engine;
QDeclarativeComponent component(&engine, QUrl("http://127.0.0.1:14449/" + fileName));
QTRY_VERIFY(component.isReady());
QSGAnimatedImage *anim = qobject_cast<QSGAnimatedImage *>(component.create());
QVERIFY(anim);
QTRY_VERIFY(anim->isPlaying());
if (paused) {
QTRY_VERIFY(anim->isPaused());
QCOMPARE(anim->currentFrame(), 2);
}
QVERIFY(anim->status() != QSGAnimatedImage::Error);
delete anim;
}
void tst_qsganimatedimage::sourceSize()
{
QDeclarativeEngine engine;
QDeclarativeComponent component(&engine, QUrl::fromLocalFile(SRCDIR "/data/stickmanscaled.qml"));
QSGAnimatedImage *anim = qobject_cast<QSGAnimatedImage *>(component.create());
QVERIFY(anim);
QCOMPARE(anim->width(),240.0);
QCOMPARE(anim->height(),180.0);
QCOMPARE(anim->sourceSize(),QSize(160,120));
delete anim;
}
void tst_qsganimatedimage::sourceSizeReadOnly()
{
QDeclarativeEngine engine;
QDeclarativeComponent component(&engine, QUrl::fromLocalFile(SRCDIR "/data/stickmanerror1.qml"));
QVERIFY(component.isError());
QCOMPARE(component.errors().at(0).description(), QString("Invalid property assignment: \"sourceSize\" is a read-only property"));
}
void tst_qsganimatedimage::remote_data()
{
QTest::addColumn<QString>("fileName");
QTest::addColumn<bool>("paused");
QTest::newRow("playing") << "stickman.qml" << false;
QTest::newRow("paused") << "stickmanpause.qml" << true;
}
void tst_qsganimatedimage::invalidSource()
{
QDeclarativeEngine engine;
QDeclarativeComponent component(&engine);
component.setData("import QtQuick 2.0\n AnimatedImage { source: \"no-such-file.gif\" }", QUrl::fromLocalFile(""));
QVERIFY(component.isReady());
QTest::ignoreMessage(QtWarningMsg, "file::2:2: QML AnimatedImage: Error Reading Animated Image File file:no-such-file.gif");
QSGAnimatedImage *anim = qobject_cast<QSGAnimatedImage *>(component.create());
QVERIFY(anim);
QVERIFY(!anim->isPlaying());
QVERIFY(!anim->isPaused());
QCOMPARE(anim->currentFrame(), 0);
QCOMPARE(anim->frameCount(), 0);
QTRY_VERIFY(anim->status() == 3);
}
void tst_qsganimatedimage::qtbug_16520()
{
TestHTTPServer server(14449);
QVERIFY(server.isValid());
server.serveDirectory(SRCDIR "/data");
QDeclarativeEngine engine;
QDeclarativeComponent component(&engine, QUrl::fromLocalFile(SRCDIR "/data/qtbug-16520.qml"));
QTRY_VERIFY(component.isReady());
QSGRectangle *root = qobject_cast<QSGRectangle *>(component.create());
QVERIFY(root);
QSGAnimatedImage *anim = root->findChild<QSGAnimatedImage*>("anim");
anim->setProperty("source", "http://127.0.0.1:14449/stickman.gif");
QTRY_VERIFY(anim->opacity() == 0);
QTRY_VERIFY(anim->opacity() == 1);
delete anim;
}
void tst_qsganimatedimage::progressAndStatusChanges()
{
TestHTTPServer server(14449);
QVERIFY(server.isValid());
server.serveDirectory(SRCDIR "/data");
QDeclarativeEngine engine;
QString componentStr = "import QtQuick 2.0\nAnimatedImage { source: srcImage }";
QDeclarativeContext *ctxt = engine.rootContext();
ctxt->setContextProperty("srcImage", QUrl::fromLocalFile(SRCDIR "/data/stickman.gif"));
QDeclarativeComponent component(&engine);
component.setData(componentStr.toLatin1(), QUrl::fromLocalFile(""));
QSGImage *obj = qobject_cast<QSGImage*>(component.create());
QVERIFY(obj != 0);
QVERIFY(obj->status() == QSGImage::Ready);
QTRY_VERIFY(obj->progress() == 1.0);
QSignalSpy sourceSpy(obj, SIGNAL(sourceChanged(const QUrl &)));
QSignalSpy progressSpy(obj, SIGNAL(progressChanged(qreal)));
QSignalSpy statusSpy(obj, SIGNAL(statusChanged(QSGImageBase::Status)));
// Loading local file
ctxt->setContextProperty("srcImage", QUrl::fromLocalFile(SRCDIR "/data/colors.gif"));
QTRY_VERIFY(obj->status() == QSGImage::Ready);
QTRY_VERIFY(obj->progress() == 1.0);
QTRY_COMPARE(sourceSpy.count(), 1);
QTRY_COMPARE(progressSpy.count(), 0);
QTRY_COMPARE(statusSpy.count(), 0);
// Loading remote file
ctxt->setContextProperty("srcImage", "http://127.0.0.1:14449/stickman.gif");
QTRY_VERIFY(obj->status() == QSGImage::Loading);
QTRY_VERIFY(obj->progress() == 0.0);
QTRY_VERIFY(obj->status() == QSGImage::Ready);
QTRY_VERIFY(obj->progress() == 1.0);
QTRY_COMPARE(sourceSpy.count(), 2);
QTRY_VERIFY(progressSpy.count() > 1);
QTRY_COMPARE(statusSpy.count(), 2);
ctxt->setContextProperty("srcImage", "");
QTRY_VERIFY(obj->status() == QSGImage::Null);
QTRY_VERIFY(obj->progress() == 0.0);
QTRY_COMPARE(sourceSpy.count(), 3);
QTRY_VERIFY(progressSpy.count() > 2);
QTRY_COMPARE(statusSpy.count(), 3);
}
QTEST_MAIN(tst_qsganimatedimage)
#include "tst_qsganimatedimage.moc"
<|endoftext|> |
<commit_before>//
// $Id$
//
#include "FFMpegDecoder.h"
#include "Player.h"
#include "../base/Exception.h"
#include "../base/Logger.h"
#include "../base/ScopeTimer.h"
#include <iostream>
#include <sstream>
#include <unistd.h>
using namespace std;
namespace avg {
bool FFMpegDecoder::m_bInitialized = false;
FFMpegDecoder::FFMpegDecoder ()
: m_pFormatContext(0),
m_pVStream(0),
m_pPacketData(0)
{
initVideoSupport();
}
FFMpegDecoder::~FFMpegDecoder ()
{
if (m_pFormatContext) {
close();
}
}
void avcodecError(const string & filename, int err)
{
switch(err) {
case AVERROR_NUMEXPECTED:
AVG_TRACE(Logger::ERROR,
filename << ": Incorrect image filename syntax.");
AVG_TRACE(Logger::ERROR,
"Use '%%d' to specify the image number:");
AVG_TRACE(Logger::ERROR,
" for img1.jpg, img2.jpg, ..., use 'img%%d.jpg';");
AVG_TRACE(Logger::ERROR,
" for img001.jpg, img002.jpg, ..., use 'img%%03d.jpg'.");
break;
case AVERROR_INVALIDDATA:
AVG_TRACE(Logger::ERROR,
filename << ": Error while parsing header");
break;
case AVERROR_NOFMT:
AVG_TRACE(Logger::ERROR,
filename << ": Unknown format");
break;
default:
AVG_TRACE(Logger::ERROR,
filename << ": Error while opening file (Num:" << err << ")");
break;
}
// TODO: Continue without video.
exit(-1);
}
void dump_stream_info(AVFormatContext *s)
{
cerr << "Stream info: " << endl;
if (s->track != 0)
fprintf(stderr, " Track: %d\n", s->track);
if (s->title[0] != '\0')
fprintf(stderr, " Title: %s\n", s->title);
if (s->author[0] != '\0')
fprintf(stderr, " Author: %s\n", s->author);
if (s->album[0] != '\0')
fprintf(stderr, " Album: %s\n", s->album);
if (s->year != 0)
fprintf(stderr, " Year: %d\n", s->year);
if (s->genre[0] != '\0')
fprintf(stderr, " Genre: %s\n", s->genre);
}
bool FFMpegDecoder::open (const std::string& sFilename,
int* pWidth, int* pHeight)
{
AVFormatParameters params;
int err;
m_sFilename = sFilename;
AVG_TRACE(Logger::PROFILE, "Opening " << sFilename);
memset(¶ms, 0, sizeof(params));
params.image_format = 0;
err = av_open_input_file(&m_pFormatContext, sFilename.c_str(),
0, 0, ¶ms);
if (err < 0) {
avcodecError(sFilename, err);
}
err = av_find_stream_info(m_pFormatContext);
if (err < 0) {
AVG_TRACE(Logger::ERROR,
sFilename << ": Could not find codec parameters.");
return false;
}
av_read_play(m_pFormatContext);
m_VStreamIndex = -1;
for(int i = 0; i < m_pFormatContext->nb_streams; i++) {
#if LIBAVFORMAT_BUILD < ((49<<16)+(0<<8)+0)
AVCodecContext *enc = &m_pFormatContext->streams[i]->codec;
#else
AVCodecContext *enc = m_pFormatContext->streams[i]->codec;
#endif
switch(enc->codec_type) {
/*
case CODEC_TYPE_AUDIO:
if (audio_index < 0 && !audio_disable)
audio_index = i;
break;
*/
case CODEC_TYPE_VIDEO:
if (m_VStreamIndex < 0)
m_VStreamIndex = i;
break;
default:
break;
}
}
// dump_format(m_pFormatContext, 0, m_sFilename.c_str(), 0);
// dump_stream_info(m_pFormatContext);
if (m_VStreamIndex < 0) {
AVG_TRACE(Logger::ERROR,
sFilename << " does not contain any video streams.");
return false;
}
AVCodecContext *enc;
#if LIBAVFORMAT_BUILD < ((49<<16)+(0<<8)+0)
enc = &(m_pFormatContext->streams[m_VStreamIndex]->codec);
#else
enc = m_pFormatContext->streams[m_VStreamIndex]->codec;
#endif
// enc->debug = 0x0001; // see avcodec.h
AVCodec * codec = avcodec_find_decoder(enc->codec_id);
if (!codec ||
avcodec_open(enc, codec) < 0)
{
AVG_TRACE(Logger::ERROR,
sFilename << ": could not open codec (?!).");
return false;
}
m_pVStream = m_pFormatContext->streams[m_VStreamIndex];
#if LIBAVFORMAT_BUILD < ((49<<16)+(0<<8)+0)
*pWidth = m_pVStream->codec.width;
*pHeight = m_pVStream->codec.height;
#else
*pWidth = m_pVStream->codec->width;
*pHeight = m_pVStream->codec->height;
#endif
m_bFirstPacket = true;
m_PacketLenLeft = 0;
m_bEOF = false;
return true;
}
void FFMpegDecoder::close()
{
AVG_TRACE(Logger::PROFILE, "Closing " << m_sFilename);
AVCodecContext * enc;
#if LIBAVFORMAT_BUILD < ((49<<16)+(0<<8)+0)
enc = &(m_pFormatContext->streams[m_VStreamIndex]->codec);
#else
enc = m_pFormatContext->streams[m_VStreamIndex]->codec;
#endif
if (!m_bFirstPacket) {
av_free_packet(&m_Packet);
}
m_pPacketData = 0;
avcodec_close(enc);
m_pVStream = 0;
av_close_input_file(m_pFormatContext);
m_pFormatContext = 0;
}
void FFMpegDecoder::seek(int DestFrame, int CurFrame)
{
#if LIBAVFORMAT_BUILD <= 4616
av_seek_frame(m_pFormatContext, m_VStreamIndex,
int((double(DestFrame)*1000000*1000)/m_pVStream->r_frame_rate));
#else
#if LIBAVFORMAT_BUILD < ((49<<16)+(0<<8)+0)
av_seek_frame(m_pFormatContext, m_VStreamIndex,
int((double(DestFrame)*1000000*1000)/m_pVStream->r_frame_rate), 0);
#else
double framerate = (m_pVStream->r_frame_rate.num)/m_pVStream->r_frame_rate.den;
av_seek_frame(m_pFormatContext, m_VStreamIndex,
int((double(DestFrame)*1000000*1000)/framerate), 0);
#endif
#endif
}
int FFMpegDecoder::getNumFrames()
{
// This is broken for some videos, but the code here is correct.
// So fix the videos or ffmpeg :-).
#if LIBAVFORMAT_BUILD < ((49<<16)+(0<<8)+0)
return m_pVStream->r_frame_rate*(m_pVStream->duration/AV_TIME_BASE);
#else
return (m_pVStream->r_frame_rate.num/m_pVStream->r_frame_rate.den)*(m_pVStream->duration/AV_TIME_BASE);
#endif
}
double FFMpegDecoder::getFPS()
{
#if LIBAVFORMAT_BUILD < ((49<<16)+(0<<8)+0)
return m_pVStream->r_frame_rate;
#else
return (m_pVStream->r_frame_rate.num/m_pVStream->r_frame_rate.den);
#endif
}
static ProfilingZone RenderToBmpProfilingZone(" FFMpegDecoder::renderToBmp");
static ProfilingZone ImgConvertProfilingZone(" FFMpegDecoder::img_convert");
bool FFMpegDecoder::renderToBmp(BitmapPtr pBmp)
{
ScopeTimer Timer(RenderToBmpProfilingZone);
AVFrame Frame;
readFrame(Frame);
if (!m_bEOF) {
AVPicture DestPict;
unsigned char * pDestBits = pBmp->getPixels();
DestPict.data[0] = pDestBits;
DestPict.data[1] = pDestBits+1;
DestPict.data[2] = pDestBits+2;
DestPict.data[3] = pDestBits+3;
DestPict.linesize[0] = pBmp->getStride();
DestPict.linesize[1] = pBmp->getStride();
DestPict.linesize[2] = pBmp->getStride();
DestPict.linesize[3] = pBmp->getStride();
int DestFmt;
switch(pBmp->getPixelFormat()) {
case R8G8B8X8:
DestFmt = PIX_FMT_RGBA32;
break;
case B8G8R8X8:
// This isn't supported directly by FFMpeg.
DestFmt = PIX_FMT_RGBA32;
DestPict.data[1] = pDestBits+3;
DestPict.data[3] = pDestBits+1;
break;
case R8G8B8:
DestFmt = PIX_FMT_RGB24;
break;
case B8G8R8:
DestFmt = PIX_FMT_BGR24;
break;
case YCbCr422:
DestFmt = PIX_FMT_YUV422;
break;
default:
AVG_TRACE(Logger::ERROR, "FFMpegDecoder: Dest format "
<< pBmp->getPixelFormatString() << " not supported.");
assert(false);
}
#if LIBAVFORMAT_BUILD < ((49<<16)+(0<<8)+0)
AVCodecContext *enc = &m_pVStream->codec;
#else
AVCodecContext *enc = m_pVStream->codec;
#endif
{
ScopeTimer Timer(ImgConvertProfilingZone);
img_convert(&DestPict, DestFmt,
(AVPicture*)&Frame, enc->pix_fmt,
enc->width, enc->height);
}
}
return m_bEOF;
}
bool FFMpegDecoder::isYCbCrSupported()
{
return true;
}
bool FFMpegDecoder::canRenderToBuffer(int BPP)
{
//TODO: This is a bug: We should enable direct rendering if DFB is being
// used and not just compiled in!
#ifdef AVG_ENABLE_DFB
return (BPP == 24);
#else
return false;
#endif
}
void FFMpegDecoder::initVideoSupport()
{
if (!m_bInitialized) {
av_register_all();
m_bInitialized = true;
// Avoid libavcodec console spam - turn this up again when libavcodec
// doesn't spam anymore :-).
// av_log_set_level(AV_LOG_DEBUG);
av_log_set_level(AV_LOG_QUIET);
}
}
void FFMpegDecoder::readFrame(AVFrame& Frame)
{
#if LIBAVFORMAT_BUILD < ((49<<16)+(0<<8)+0)
AVCodecContext *enc = &m_pVStream->codec;
#else
AVCodecContext *enc = m_pVStream->codec;
#endif
if (enc->codec_id == CODEC_ID_RAWVIDEO) {
AVPacket Packet;
m_bEOF = getNextVideoPacket(Packet);
if (m_bEOF) {
return ;
}
avpicture_fill((AVPicture*)&Frame, Packet.data,
enc->pix_fmt,
enc->width, enc->height);
av_free_packet(&Packet);
} else {
int gotPicture = 0;
while (!gotPicture) {
if (m_PacketLenLeft <= 0) {
if (!m_bFirstPacket) {
av_free_packet(&m_Packet);
}
m_bFirstPacket = false;
m_bEOF = getNextVideoPacket(m_Packet);
if (m_bEOF) {
return ;
}
m_PacketLenLeft = m_Packet.size;
m_pPacketData = m_Packet.data;
}
int Len1 = avcodec_decode_video(enc, &Frame,
&gotPicture, m_pPacketData, m_PacketLenLeft);
if (Len1 < 0) {
AVG_TRACE(Logger::WARNING, "Error decoding " <<
m_sFilename);
// TODO: simulate eof.
}
m_pPacketData += Len1;
m_PacketLenLeft -= Len1;
}
/*
cerr << "coded_picture_number: " << Frame.coded_picture_number <<
", display_picture_number: " << Frame.display_picture_number <<
", pts: " << Frame.pts << endl;
cerr << "key_frame: " << Frame.key_frame <<
", pict_type: " << Frame.pict_type << endl;
AVFrac spts = m_pVStream->pts;
cerr << "Stream.pts: " << spts.val + double(spts.num)/spts.den << endl;
*/
}
}
bool FFMpegDecoder::getNextVideoPacket(AVPacket & Packet) {
AVPacket CurPacket;
int err = av_read_frame(m_pFormatContext, &CurPacket);
if (err < 0) {
return true;
}
while (CurPacket.stream_index != m_VStreamIndex) {
av_free_packet(&CurPacket);
int err = av_read_frame(m_pFormatContext, &CurPacket);
if (err < 0) {
return true;
}
}
Packet = CurPacket;
/* if (Packet.pts != AV_NOPTS_VALUE) {
cerr << "Packet.pts: " <<
double(Packet.pts)*m_pFormatContext->pts_num/m_pFormatContext->pts_den << endl;
}
*/
return false;
}
}
<commit_msg>Cleaned up profiling output.<commit_after>//
// $Id$
//
#include "FFMpegDecoder.h"
#include "Player.h"
#include "../base/Exception.h"
#include "../base/Logger.h"
#include "../base/ScopeTimer.h"
#include <iostream>
#include <sstream>
#include <unistd.h>
using namespace std;
namespace avg {
bool FFMpegDecoder::m_bInitialized = false;
FFMpegDecoder::FFMpegDecoder ()
: m_pFormatContext(0),
m_pVStream(0),
m_pPacketData(0)
{
initVideoSupport();
}
FFMpegDecoder::~FFMpegDecoder ()
{
if (m_pFormatContext) {
close();
}
}
void avcodecError(const string & filename, int err)
{
switch(err) {
case AVERROR_NUMEXPECTED:
AVG_TRACE(Logger::ERROR,
filename << ": Incorrect image filename syntax.");
AVG_TRACE(Logger::ERROR,
"Use '%%d' to specify the image number:");
AVG_TRACE(Logger::ERROR,
" for img1.jpg, img2.jpg, ..., use 'img%%d.jpg';");
AVG_TRACE(Logger::ERROR,
" for img001.jpg, img002.jpg, ..., use 'img%%03d.jpg'.");
break;
case AVERROR_INVALIDDATA:
AVG_TRACE(Logger::ERROR,
filename << ": Error while parsing header");
break;
case AVERROR_NOFMT:
AVG_TRACE(Logger::ERROR,
filename << ": Unknown format");
break;
default:
AVG_TRACE(Logger::ERROR,
filename << ": Error while opening file (Num:" << err << ")");
break;
}
// TODO: Continue without video.
exit(-1);
}
void dump_stream_info(AVFormatContext *s)
{
cerr << "Stream info: " << endl;
if (s->track != 0)
fprintf(stderr, " Track: %d\n", s->track);
if (s->title[0] != '\0')
fprintf(stderr, " Title: %s\n", s->title);
if (s->author[0] != '\0')
fprintf(stderr, " Author: %s\n", s->author);
if (s->album[0] != '\0')
fprintf(stderr, " Album: %s\n", s->album);
if (s->year != 0)
fprintf(stderr, " Year: %d\n", s->year);
if (s->genre[0] != '\0')
fprintf(stderr, " Genre: %s\n", s->genre);
}
bool FFMpegDecoder::open (const std::string& sFilename,
int* pWidth, int* pHeight)
{
AVFormatParameters params;
int err;
m_sFilename = sFilename;
AVG_TRACE(Logger::PROFILE, "Opening " << sFilename);
memset(¶ms, 0, sizeof(params));
params.image_format = 0;
err = av_open_input_file(&m_pFormatContext, sFilename.c_str(),
0, 0, ¶ms);
if (err < 0) {
avcodecError(sFilename, err);
}
err = av_find_stream_info(m_pFormatContext);
if (err < 0) {
AVG_TRACE(Logger::ERROR,
sFilename << ": Could not find codec parameters.");
return false;
}
av_read_play(m_pFormatContext);
m_VStreamIndex = -1;
for(int i = 0; i < m_pFormatContext->nb_streams; i++) {
#if LIBAVFORMAT_BUILD < ((49<<16)+(0<<8)+0)
AVCodecContext *enc = &m_pFormatContext->streams[i]->codec;
#else
AVCodecContext *enc = m_pFormatContext->streams[i]->codec;
#endif
switch(enc->codec_type) {
/*
case CODEC_TYPE_AUDIO:
if (audio_index < 0 && !audio_disable)
audio_index = i;
break;
*/
case CODEC_TYPE_VIDEO:
if (m_VStreamIndex < 0)
m_VStreamIndex = i;
break;
default:
break;
}
}
// dump_format(m_pFormatContext, 0, m_sFilename.c_str(), 0);
// dump_stream_info(m_pFormatContext);
if (m_VStreamIndex < 0) {
AVG_TRACE(Logger::ERROR,
sFilename << " does not contain any video streams.");
return false;
}
AVCodecContext *enc;
#if LIBAVFORMAT_BUILD < ((49<<16)+(0<<8)+0)
enc = &(m_pFormatContext->streams[m_VStreamIndex]->codec);
#else
enc = m_pFormatContext->streams[m_VStreamIndex]->codec;
#endif
// enc->debug = 0x0001; // see avcodec.h
AVCodec * codec = avcodec_find_decoder(enc->codec_id);
if (!codec ||
avcodec_open(enc, codec) < 0)
{
AVG_TRACE(Logger::ERROR,
sFilename << ": could not open codec (?!).");
return false;
}
m_pVStream = m_pFormatContext->streams[m_VStreamIndex];
#if LIBAVFORMAT_BUILD < ((49<<16)+(0<<8)+0)
*pWidth = m_pVStream->codec.width;
*pHeight = m_pVStream->codec.height;
#else
*pWidth = m_pVStream->codec->width;
*pHeight = m_pVStream->codec->height;
#endif
m_bFirstPacket = true;
m_PacketLenLeft = 0;
m_bEOF = false;
return true;
}
void FFMpegDecoder::close()
{
AVG_TRACE(Logger::PROFILE, "Closing " << m_sFilename);
AVCodecContext * enc;
#if LIBAVFORMAT_BUILD < ((49<<16)+(0<<8)+0)
enc = &(m_pFormatContext->streams[m_VStreamIndex]->codec);
#else
enc = m_pFormatContext->streams[m_VStreamIndex]->codec;
#endif
if (!m_bFirstPacket) {
av_free_packet(&m_Packet);
}
m_pPacketData = 0;
avcodec_close(enc);
m_pVStream = 0;
av_close_input_file(m_pFormatContext);
m_pFormatContext = 0;
}
void FFMpegDecoder::seek(int DestFrame, int CurFrame)
{
#if LIBAVFORMAT_BUILD <= 4616
av_seek_frame(m_pFormatContext, m_VStreamIndex,
int((double(DestFrame)*1000000*1000)/m_pVStream->r_frame_rate));
#else
#if LIBAVFORMAT_BUILD < ((49<<16)+(0<<8)+0)
av_seek_frame(m_pFormatContext, m_VStreamIndex,
int((double(DestFrame)*1000000*1000)/m_pVStream->r_frame_rate), 0);
#else
double framerate = (m_pVStream->r_frame_rate.num)/m_pVStream->r_frame_rate.den;
av_seek_frame(m_pFormatContext, m_VStreamIndex,
int((double(DestFrame)*1000000*1000)/framerate), 0);
#endif
#endif
}
int FFMpegDecoder::getNumFrames()
{
// This is broken for some videos, but the code here is correct.
// So fix the videos or ffmpeg :-).
#if LIBAVFORMAT_BUILD < ((49<<16)+(0<<8)+0)
return m_pVStream->r_frame_rate*(m_pVStream->duration/AV_TIME_BASE);
#else
return (m_pVStream->r_frame_rate.num/m_pVStream->r_frame_rate.den)*(m_pVStream->duration/AV_TIME_BASE);
#endif
}
double FFMpegDecoder::getFPS()
{
#if LIBAVFORMAT_BUILD < ((49<<16)+(0<<8)+0)
return m_pVStream->r_frame_rate;
#else
return (m_pVStream->r_frame_rate.num/m_pVStream->r_frame_rate.den);
#endif
}
static ProfilingZone RenderToBmpProfilingZone(" FFMpeg: renderToBmp");
static ProfilingZone ImgConvertProfilingZone(" FFMpeg: img_convert");
bool FFMpegDecoder::renderToBmp(BitmapPtr pBmp)
{
ScopeTimer Timer(RenderToBmpProfilingZone);
AVFrame Frame;
readFrame(Frame);
if (!m_bEOF) {
AVPicture DestPict;
unsigned char * pDestBits = pBmp->getPixels();
DestPict.data[0] = pDestBits;
DestPict.data[1] = pDestBits+1;
DestPict.data[2] = pDestBits+2;
DestPict.data[3] = pDestBits+3;
DestPict.linesize[0] = pBmp->getStride();
DestPict.linesize[1] = pBmp->getStride();
DestPict.linesize[2] = pBmp->getStride();
DestPict.linesize[3] = pBmp->getStride();
int DestFmt;
switch(pBmp->getPixelFormat()) {
case R8G8B8X8:
DestFmt = PIX_FMT_RGBA32;
break;
case B8G8R8X8:
// This isn't supported directly by FFMpeg.
DestFmt = PIX_FMT_RGBA32;
DestPict.data[1] = pDestBits+3;
DestPict.data[3] = pDestBits+1;
break;
case R8G8B8:
DestFmt = PIX_FMT_RGB24;
break;
case B8G8R8:
DestFmt = PIX_FMT_BGR24;
break;
case YCbCr422:
DestFmt = PIX_FMT_YUV422;
break;
default:
AVG_TRACE(Logger::ERROR, "FFMpegDecoder: Dest format "
<< pBmp->getPixelFormatString() << " not supported.");
assert(false);
}
#if LIBAVFORMAT_BUILD < ((49<<16)+(0<<8)+0)
AVCodecContext *enc = &m_pVStream->codec;
#else
AVCodecContext *enc = m_pVStream->codec;
#endif
{
ScopeTimer Timer(ImgConvertProfilingZone);
img_convert(&DestPict, DestFmt,
(AVPicture*)&Frame, enc->pix_fmt,
enc->width, enc->height);
}
}
return m_bEOF;
}
bool FFMpegDecoder::isYCbCrSupported()
{
return true;
}
bool FFMpegDecoder::canRenderToBuffer(int BPP)
{
//TODO: This is a bug: We should enable direct rendering if DFB is being
// used and not just compiled in!
#ifdef AVG_ENABLE_DFB
return (BPP == 24);
#else
return false;
#endif
}
void FFMpegDecoder::initVideoSupport()
{
if (!m_bInitialized) {
av_register_all();
m_bInitialized = true;
// Avoid libavcodec console spam - turn this up again when libavcodec
// doesn't spam anymore :-).
// av_log_set_level(AV_LOG_DEBUG);
av_log_set_level(AV_LOG_QUIET);
}
}
void FFMpegDecoder::readFrame(AVFrame& Frame)
{
#if LIBAVFORMAT_BUILD < ((49<<16)+(0<<8)+0)
AVCodecContext *enc = &m_pVStream->codec;
#else
AVCodecContext *enc = m_pVStream->codec;
#endif
if (enc->codec_id == CODEC_ID_RAWVIDEO) {
AVPacket Packet;
m_bEOF = getNextVideoPacket(Packet);
if (m_bEOF) {
return ;
}
avpicture_fill((AVPicture*)&Frame, Packet.data,
enc->pix_fmt,
enc->width, enc->height);
av_free_packet(&Packet);
} else {
int gotPicture = 0;
while (!gotPicture) {
if (m_PacketLenLeft <= 0) {
if (!m_bFirstPacket) {
av_free_packet(&m_Packet);
}
m_bFirstPacket = false;
m_bEOF = getNextVideoPacket(m_Packet);
if (m_bEOF) {
return ;
}
m_PacketLenLeft = m_Packet.size;
m_pPacketData = m_Packet.data;
}
int Len1 = avcodec_decode_video(enc, &Frame,
&gotPicture, m_pPacketData, m_PacketLenLeft);
if (Len1 < 0) {
AVG_TRACE(Logger::WARNING, "Error decoding " <<
m_sFilename);
// TODO: simulate eof.
}
m_pPacketData += Len1;
m_PacketLenLeft -= Len1;
}
/*
cerr << "coded_picture_number: " << Frame.coded_picture_number <<
", display_picture_number: " << Frame.display_picture_number <<
", pts: " << Frame.pts << endl;
cerr << "key_frame: " << Frame.key_frame <<
", pict_type: " << Frame.pict_type << endl;
AVFrac spts = m_pVStream->pts;
cerr << "Stream.pts: " << spts.val + double(spts.num)/spts.den << endl;
*/
}
}
bool FFMpegDecoder::getNextVideoPacket(AVPacket & Packet) {
AVPacket CurPacket;
int err = av_read_frame(m_pFormatContext, &CurPacket);
if (err < 0) {
return true;
}
while (CurPacket.stream_index != m_VStreamIndex) {
av_free_packet(&CurPacket);
int err = av_read_frame(m_pFormatContext, &CurPacket);
if (err < 0) {
return true;
}
}
Packet = CurPacket;
/* if (Packet.pts != AV_NOPTS_VALUE) {
cerr << "Packet.pts: " <<
double(Packet.pts)*m_pFormatContext->pts_num/m_pFormatContext->pts_den << endl;
}
*/
return false;
}
}
<|endoftext|> |
<commit_before>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: BarChart.hxx,v $
*
* $Revision: 1.8 $
*
* last change: $Author: ihi $ $Date: 2007-11-23 12:10:02 $
*
* 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 _CHART2_BARCHART_HXX
#define _CHART2_BARCHART_HXX
#include "VSeriesPlotter.hxx"
//.............................................................................
namespace chart
{
//.............................................................................
class BarPositionHelper;
class BarChart : public VSeriesPlotter
{
//-------------------------------------------------------------------------
// public methods
//-------------------------------------------------------------------------
public:
BarChart( const ::com::sun::star::uno::Reference<
::com::sun::star::chart2::XChartType >& xChartTypeModel
, sal_Int32 nDimensionCount );
virtual ~BarChart();
//-------------------------------------------------------------------------
// chart2::XPlotter
//-------------------------------------------------------------------------
virtual void SAL_CALL createShapes();
/*
virtual ::rtl::OUString SAL_CALL getCoordinateSystemTypeID( ) throw (::com::sun::star::uno::RuntimeException);
virtual void SAL_CALL setScales( const ::com::sun::star::uno::Sequence< ::com::sun::star::chart2::ExplicitScaleData >& rScales ) throw (::com::sun::star::uno::RuntimeException);
virtual void SAL_CALL setTransformation( const ::com::sun::star::uno::Reference< ::com::sun::star::chart2::XTransformation >& xTransformationToLogicTarget, const ::com::sun::star::uno::Reference< ::com::sun::star::chart2::XTransformation >& xTransformationToFinalPage ) throw (::com::sun::star::uno::RuntimeException);
*/
virtual void addSeries( VDataSeries* pSeries, sal_Int32 zSlot = -1, sal_Int32 xSlot = -1,sal_Int32 ySlot = -1 );
//-------------------
virtual ::com::sun::star::drawing::Direction3D getPreferredDiagramAspectRatio() const;
virtual bool keepAspectRatio() const;
//-------------------------------------------------------------------------
// MinimumAndMaximumSupplier
//-------------------------------------------------------------------------
virtual double getMinimumX();
virtual double getMaximumX();
//-------------------------------------------------------------------------
//-------------------------------------------------------------------------
//-------------------------------------------------------------------------
private: //methods
//no default constructor
BarChart();
::com::sun::star::uno::Reference< ::com::sun::star::drawing::XShape >
createDataPoint3D_Bar(
const ::com::sun::star::uno::Reference<
::com::sun::star::drawing::XShapes >& xTarget
, const ::com::sun::star::drawing::Position3D& rPosition
, const ::com::sun::star::drawing::Direction3D& rSize
, double fTopHeight, sal_Int32 nRotateZAngleHundredthDegree
, const ::com::sun::star::uno::Reference<
::com::sun::star::beans::XPropertySet >& xObjectProperties
, sal_Int32 nGeometry3D );
::com::sun::star::awt::Point getLabelScreenPositionAndAlignment(
LabelAlignment& rAlignment, sal_Int32 nLabelPlacement
, double fScaledX, double fScaledLowerYValue, double fScaledUpperYValue, double fScaledZ
, double fScaledLowerBarDepth, double fScaledUpperBarDepth, double fBaseValue
, BarPositionHelper* pPosHelper ) const;
virtual PlottingPositionHelper& getPlottingPositionHelper( sal_Int32 nAxisIndex ) const;//nAxisIndex indicates wether the position belongs to the main axis ( nAxisIndex==0 ) or secondary axis ( nAxisIndex==1 )
void adaptOverlapAndGapwidthForGroupBarsPerAxis();
private: //member
BarPositionHelper* m_pMainPosHelper;
::com::sun::star::uno::Sequence< sal_Int32 > m_aOverlapSequence;
::com::sun::star::uno::Sequence< sal_Int32 > m_aGapwidthSequence;
};
//.............................................................................
} //namespace chart
//.............................................................................
#endif
<commit_msg>INTEGRATION: CWS changefileheader (1.8.60); FILE MERGED 2008/03/28 16:44:38 rt 1.8.60.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: BarChart.hxx,v $
* $Revision: 1.9 $
*
* This file is part of OpenOffice.org.
*
* OpenOffice.org is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License version 3
* only, as published by the Free Software Foundation.
*
* OpenOffice.org is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License version 3 for more details
* (a copy is included in the LICENSE file that accompanied this code).
*
* You should have received a copy of the GNU Lesser General Public License
* version 3 along with OpenOffice.org. If not, see
* <http://www.openoffice.org/license.html>
* for a copy of the LGPLv3 License.
*
************************************************************************/
#ifndef _CHART2_BARCHART_HXX
#define _CHART2_BARCHART_HXX
#include "VSeriesPlotter.hxx"
//.............................................................................
namespace chart
{
//.............................................................................
class BarPositionHelper;
class BarChart : public VSeriesPlotter
{
//-------------------------------------------------------------------------
// public methods
//-------------------------------------------------------------------------
public:
BarChart( const ::com::sun::star::uno::Reference<
::com::sun::star::chart2::XChartType >& xChartTypeModel
, sal_Int32 nDimensionCount );
virtual ~BarChart();
//-------------------------------------------------------------------------
// chart2::XPlotter
//-------------------------------------------------------------------------
virtual void SAL_CALL createShapes();
/*
virtual ::rtl::OUString SAL_CALL getCoordinateSystemTypeID( ) throw (::com::sun::star::uno::RuntimeException);
virtual void SAL_CALL setScales( const ::com::sun::star::uno::Sequence< ::com::sun::star::chart2::ExplicitScaleData >& rScales ) throw (::com::sun::star::uno::RuntimeException);
virtual void SAL_CALL setTransformation( const ::com::sun::star::uno::Reference< ::com::sun::star::chart2::XTransformation >& xTransformationToLogicTarget, const ::com::sun::star::uno::Reference< ::com::sun::star::chart2::XTransformation >& xTransformationToFinalPage ) throw (::com::sun::star::uno::RuntimeException);
*/
virtual void addSeries( VDataSeries* pSeries, sal_Int32 zSlot = -1, sal_Int32 xSlot = -1,sal_Int32 ySlot = -1 );
//-------------------
virtual ::com::sun::star::drawing::Direction3D getPreferredDiagramAspectRatio() const;
virtual bool keepAspectRatio() const;
//-------------------------------------------------------------------------
// MinimumAndMaximumSupplier
//-------------------------------------------------------------------------
virtual double getMinimumX();
virtual double getMaximumX();
//-------------------------------------------------------------------------
//-------------------------------------------------------------------------
//-------------------------------------------------------------------------
private: //methods
//no default constructor
BarChart();
::com::sun::star::uno::Reference< ::com::sun::star::drawing::XShape >
createDataPoint3D_Bar(
const ::com::sun::star::uno::Reference<
::com::sun::star::drawing::XShapes >& xTarget
, const ::com::sun::star::drawing::Position3D& rPosition
, const ::com::sun::star::drawing::Direction3D& rSize
, double fTopHeight, sal_Int32 nRotateZAngleHundredthDegree
, const ::com::sun::star::uno::Reference<
::com::sun::star::beans::XPropertySet >& xObjectProperties
, sal_Int32 nGeometry3D );
::com::sun::star::awt::Point getLabelScreenPositionAndAlignment(
LabelAlignment& rAlignment, sal_Int32 nLabelPlacement
, double fScaledX, double fScaledLowerYValue, double fScaledUpperYValue, double fScaledZ
, double fScaledLowerBarDepth, double fScaledUpperBarDepth, double fBaseValue
, BarPositionHelper* pPosHelper ) const;
virtual PlottingPositionHelper& getPlottingPositionHelper( sal_Int32 nAxisIndex ) const;//nAxisIndex indicates wether the position belongs to the main axis ( nAxisIndex==0 ) or secondary axis ( nAxisIndex==1 )
void adaptOverlapAndGapwidthForGroupBarsPerAxis();
private: //member
BarPositionHelper* m_pMainPosHelper;
::com::sun::star::uno::Sequence< sal_Int32 > m_aOverlapSequence;
::com::sun::star::uno::Sequence< sal_Int32 > m_aGapwidthSequence;
};
//.............................................................................
} //namespace chart
//.............................................................................
#endif
<|endoftext|> |
<commit_before>#pragma once
#include "apple_hid_usage_tables.hpp"
#include "console_user_client.hpp"
#include "constants.hpp"
#include "hid_report.hpp"
#include "human_interface_device.hpp"
#include "iokit_user_client.hpp"
#include "iokit_utility.hpp"
#include "logger.hpp"
#include "modifier_flag_manager.hpp"
#include "userspace_defs.h"
#include "virtual_hid_manager_user_client_method.hpp"
class event_grabber final {
public:
event_grabber(void) : iokit_user_client_(logger::get_logger(), "org_pqrs_driver_VirtualHIDManager", kIOHIDServerConnectType),
console_user_client_(modifier_flag_manager_) {
manager_ = IOHIDManagerCreate(kCFAllocatorDefault, kIOHIDOptionsTypeNone);
if (!manager_) {
return;
}
auto device_matching_dictionaries = iokit_utility::create_device_matching_dictionaries({
std::make_pair(kHIDPage_GenericDesktop, kHIDUsage_GD_Keyboard),
// std::make_pair(kHIDPage_Consumer, kHIDUsage_Csmr_ConsumerControl),
// std::make_pair(kHIDPage_GenericDesktop, kHIDUsage_GD_Mouse),
});
if (device_matching_dictionaries) {
IOHIDManagerSetDeviceMatchingMultiple(manager_, device_matching_dictionaries);
CFRelease(device_matching_dictionaries);
IOHIDManagerRegisterDeviceMatchingCallback(manager_, static_device_matching_callback, this);
IOHIDManagerRegisterDeviceRemovalCallback(manager_, static_device_removal_callback, this);
IOHIDManagerScheduleWithRunLoop(manager_, CFRunLoopGetCurrent(), kCFRunLoopDefaultMode);
}
}
~event_grabber(void) {
if (manager_) {
IOHIDManagerUnscheduleFromRunLoop(manager_, CFRunLoopGetCurrent(), kCFRunLoopDefaultMode);
CFRelease(manager_);
manager_ = nullptr;
}
}
private:
static void static_device_matching_callback(void* _Nullable context, IOReturn result, void* _Nullable sender, IOHIDDeviceRef _Nonnull device) {
if (result != kIOReturnSuccess) {
return;
}
auto self = static_cast<event_grabber*>(context);
if (!self) {
return;
}
self->device_matching_callback(device);
}
void device_matching_callback(IOHIDDeviceRef _Nonnull device) {
if (!device) {
return;
}
hids_[device] = std::make_unique<human_interface_device>(device);
auto& dev = hids_[device];
std::cout << "matching: " << std::endl
<< " vendor_id:0x" << std::hex << dev->get_vendor_id() << std::endl
<< " product_id:0x" << std::hex << dev->get_product_id() << std::endl
<< " location_id:0x" << std::hex << dev->get_location_id() << std::endl
<< " serial_number:" << dev->get_serial_number_string() << std::endl
<< " manufacturer:" << dev->get_manufacturer() << std::endl
<< " product:" << dev->get_product() << std::endl
<< " transport:" << dev->get_transport() << std::endl;
if (dev->get_serial_number_string() == "org.pqrs.driver.VirtualHIDKeyboard") {
return;
}
if (dev->get_manufacturer() != "pqrs.org") {
if (dev->get_manufacturer() == "Apple Inc.") {
dev->grab(boost::bind(&event_grabber::value_callback, this, _1, _2, _3, _4, _5));
}
}
}
static void static_device_removal_callback(void* _Nullable context, IOReturn result, void* _Nullable sender, IOHIDDeviceRef _Nonnull device) {
if (result != kIOReturnSuccess) {
return;
}
auto self = static_cast<event_grabber*>(context);
if (!self) {
return;
}
self->device_removal_callback(device);
}
void device_removal_callback(IOHIDDeviceRef _Nonnull device) {
if (!device) {
return;
}
auto it = hids_.find(device);
if (it != hids_.end()) {
auto& dev = it->second;
if (dev) {
std::cout << "removal vendor_id:0x" << std::hex << dev->get_vendor_id() << " product_id:0x" << std::hex << dev->get_product_id() << std::endl;
hids_.erase(it);
}
}
}
void value_callback(IOHIDValueRef _Nonnull value,
IOHIDElementRef _Nonnull element,
uint32_t usage_page,
uint32_t usage,
CFIndex integer_value) {
std::cout << "element" << std::endl
<< " usage_page:0x" << std::hex << usage_page << std::endl
<< " usage:0x" << std::hex << usage << std::endl
<< " type:" << IOHIDElementGetType(element) << std::endl
<< " length:" << IOHIDValueGetLength(value) << std::endl
<< " integer_value:" << integer_value << std::endl;
switch (usage_page) {
case kHIDPage_KeyboardOrKeypad: {
bool pressed = integer_value;
handle_keyboard_event(usage_page, usage, pressed);
break;
}
case kHIDPage_AppleVendorTopCase:
if (usage == kHIDUsage_AV_TopCase_KeyboardFn) {
bool pressed = integer_value;
handle_keyboard_event(usage_page, usage, pressed);
}
break;
default:
break;
}
}
bool handle_modifier_flag_event(uint32_t usage_page, uint32_t usage, bool pressed) {
auto operation = pressed ? modifier_flag_manager::operation::increase : modifier_flag_manager::operation::decrease;
switch (usage_page) {
case kHIDPage_KeyboardOrKeypad: {
auto key = modifier_flag_manager::physical_keys::end_;
switch (usage) {
case kHIDUsage_KeyboardLeftControl:
key = modifier_flag_manager::physical_keys::left_control;
break;
case kHIDUsage_KeyboardLeftShift:
key = modifier_flag_manager::physical_keys::left_shift;
break;
case kHIDUsage_KeyboardLeftAlt:
key = modifier_flag_manager::physical_keys::left_option;
break;
case kHIDUsage_KeyboardLeftGUI:
key = modifier_flag_manager::physical_keys::left_command;
break;
case kHIDUsage_KeyboardRightControl:
key = modifier_flag_manager::physical_keys::right_control;
break;
case kHIDUsage_KeyboardRightShift:
key = modifier_flag_manager::physical_keys::right_shift;
break;
case kHIDUsage_KeyboardRightAlt:
key = modifier_flag_manager::physical_keys::right_option;
break;
case kHIDUsage_KeyboardRightGUI:
key = modifier_flag_manager::physical_keys::right_command;
break;
}
if (key != modifier_flag_manager::physical_keys::end_) {
modifier_flag_manager_.manipulate(key, operation);
send_keyboard_input_report();
return true;
}
break;
}
case kHIDPage_AppleVendorTopCase:
if (usage == kHIDUsage_AV_TopCase_KeyboardFn) {
modifier_flag_manager_.manipulate(modifier_flag_manager::physical_keys::fn, operation);
console_user_client_.post_modifier_flags();
return true;
}
break;
}
return false;
}
bool handle_function_key_event(uint32_t usage_page, uint32_t usage, bool pressed) {
if (usage_page != kHIDPage_KeyboardOrKeypad) {
return false;
}
auto event_type = pressed ? KRBN_EVENT_TYPE_KEY_DOWN : KRBN_EVENT_TYPE_KEY_UP;
#define POST_KEY(KEY) \
case kHIDUsage_Keyboard##KEY: \
console_user_client_.post_key(KRBN_KEY_CODE_##KEY, event_type); \
return true;
switch (usage) {
POST_KEY(F1);
POST_KEY(F2);
POST_KEY(F3);
POST_KEY(F4);
POST_KEY(F5);
POST_KEY(F6);
POST_KEY(F7);
POST_KEY(F8);
POST_KEY(F9);
POST_KEY(F10);
POST_KEY(F11);
POST_KEY(F12);
}
return false;
}
void handle_keyboard_event(uint32_t usage_page, uint32_t usage, bool pressed) {
// ----------------------------------------
// modify usage
if (usage == kHIDUsage_KeyboardCapsLock) {
usage = kHIDUsage_KeyboardDeleteOrBackspace;
}
// ----------------------------------------
if (handle_modifier_flag_event(usage_page, usage, pressed)) {
console_user_client_.stop_key_repeat();
return;
}
if (handle_function_key_event(usage_page, usage, pressed)) {
return;
}
if (pressed) {
pressed_key_usages_.push_back(usage);
console_user_client_.stop_key_repeat();
} else {
pressed_key_usages_.remove(usage);
}
send_keyboard_input_report();
}
void send_keyboard_input_report(void) {
// make report
hid_report::keyboard_input report;
report.modifiers = modifier_flag_manager_.get_hid_report_bits();
while (pressed_key_usages_.size() > sizeof(report.keys)) {
pressed_key_usages_.pop_front();
}
int i = 0;
for (const auto& u : pressed_key_usages_) {
report.keys[i] = u;
++i;
}
// send new report only if it is changed from last report.
if (last_keyboard_input_report_ != report) {
last_keyboard_input_report_ = report;
auto kr = iokit_user_client_.call_struct_method(static_cast<uint32_t>(virtual_hid_manager_user_client_method::keyboard_input_report),
static_cast<const void*>(&report), sizeof(report),
nullptr, 0);
if (kr != KERN_SUCCESS) {
logger::get_logger().error("failed to sent report: 0x{0:x}", kr);
}
}
}
iokit_user_client iokit_user_client_;
IOHIDManagerRef _Nullable manager_;
std::unordered_map<IOHIDDeviceRef, std::unique_ptr<human_interface_device>> hids_;
std::list<uint32_t> pressed_key_usages_;
modifier_flag_manager modifier_flag_manager_;
hid_report::keyboard_input last_keyboard_input_report_;
console_user_client console_user_client_;
};
<commit_msg>support fn+arrow<commit_after>#pragma once
#include "apple_hid_usage_tables.hpp"
#include "console_user_client.hpp"
#include "constants.hpp"
#include "hid_report.hpp"
#include "human_interface_device.hpp"
#include "iokit_user_client.hpp"
#include "iokit_utility.hpp"
#include "logger.hpp"
#include "modifier_flag_manager.hpp"
#include "userspace_defs.h"
#include "virtual_hid_manager_user_client_method.hpp"
class event_grabber final {
public:
event_grabber(void) : iokit_user_client_(logger::get_logger(), "org_pqrs_driver_VirtualHIDManager", kIOHIDServerConnectType),
console_user_client_(modifier_flag_manager_) {
manager_ = IOHIDManagerCreate(kCFAllocatorDefault, kIOHIDOptionsTypeNone);
if (!manager_) {
return;
}
auto device_matching_dictionaries = iokit_utility::create_device_matching_dictionaries({
std::make_pair(kHIDPage_GenericDesktop, kHIDUsage_GD_Keyboard),
// std::make_pair(kHIDPage_Consumer, kHIDUsage_Csmr_ConsumerControl),
// std::make_pair(kHIDPage_GenericDesktop, kHIDUsage_GD_Mouse),
});
if (device_matching_dictionaries) {
IOHIDManagerSetDeviceMatchingMultiple(manager_, device_matching_dictionaries);
CFRelease(device_matching_dictionaries);
IOHIDManagerRegisterDeviceMatchingCallback(manager_, static_device_matching_callback, this);
IOHIDManagerRegisterDeviceRemovalCallback(manager_, static_device_removal_callback, this);
IOHIDManagerScheduleWithRunLoop(manager_, CFRunLoopGetCurrent(), kCFRunLoopDefaultMode);
}
}
~event_grabber(void) {
if (manager_) {
IOHIDManagerUnscheduleFromRunLoop(manager_, CFRunLoopGetCurrent(), kCFRunLoopDefaultMode);
CFRelease(manager_);
manager_ = nullptr;
}
}
private:
static void static_device_matching_callback(void* _Nullable context, IOReturn result, void* _Nullable sender, IOHIDDeviceRef _Nonnull device) {
if (result != kIOReturnSuccess) {
return;
}
auto self = static_cast<event_grabber*>(context);
if (!self) {
return;
}
self->device_matching_callback(device);
}
void device_matching_callback(IOHIDDeviceRef _Nonnull device) {
if (!device) {
return;
}
hids_[device] = std::make_unique<human_interface_device>(device);
auto& dev = hids_[device];
std::cout << "matching: " << std::endl
<< " vendor_id:0x" << std::hex << dev->get_vendor_id() << std::endl
<< " product_id:0x" << std::hex << dev->get_product_id() << std::endl
<< " location_id:0x" << std::hex << dev->get_location_id() << std::endl
<< " serial_number:" << dev->get_serial_number_string() << std::endl
<< " manufacturer:" << dev->get_manufacturer() << std::endl
<< " product:" << dev->get_product() << std::endl
<< " transport:" << dev->get_transport() << std::endl;
if (dev->get_serial_number_string() == "org.pqrs.driver.VirtualHIDKeyboard") {
return;
}
if (dev->get_manufacturer() != "pqrs.org") {
if (dev->get_manufacturer() == "Apple Inc.") {
dev->grab(boost::bind(&event_grabber::value_callback, this, _1, _2, _3, _4, _5));
}
}
}
static void static_device_removal_callback(void* _Nullable context, IOReturn result, void* _Nullable sender, IOHIDDeviceRef _Nonnull device) {
if (result != kIOReturnSuccess) {
return;
}
auto self = static_cast<event_grabber*>(context);
if (!self) {
return;
}
self->device_removal_callback(device);
}
void device_removal_callback(IOHIDDeviceRef _Nonnull device) {
if (!device) {
return;
}
auto it = hids_.find(device);
if (it != hids_.end()) {
auto& dev = it->second;
if (dev) {
std::cout << "removal vendor_id:0x" << std::hex << dev->get_vendor_id() << " product_id:0x" << std::hex << dev->get_product_id() << std::endl;
hids_.erase(it);
}
}
}
void value_callback(IOHIDValueRef _Nonnull value,
IOHIDElementRef _Nonnull element,
uint32_t usage_page,
uint32_t usage,
CFIndex integer_value) {
std::cout << "element" << std::endl
<< " usage_page:0x" << std::hex << usage_page << std::endl
<< " usage:0x" << std::hex << usage << std::endl
<< " type:" << IOHIDElementGetType(element) << std::endl
<< " length:" << IOHIDValueGetLength(value) << std::endl
<< " integer_value:" << integer_value << std::endl;
switch (usage_page) {
case kHIDPage_KeyboardOrKeypad: {
bool pressed = integer_value;
handle_keyboard_event(usage_page, usage, pressed);
break;
}
case kHIDPage_AppleVendorTopCase:
if (usage == kHIDUsage_AV_TopCase_KeyboardFn) {
bool pressed = integer_value;
handle_keyboard_event(usage_page, usage, pressed);
}
break;
default:
break;
}
}
bool handle_modifier_flag_event(uint32_t usage_page, uint32_t usage, bool pressed) {
auto operation = pressed ? modifier_flag_manager::operation::increase : modifier_flag_manager::operation::decrease;
switch (usage_page) {
case kHIDPage_KeyboardOrKeypad: {
auto key = modifier_flag_manager::physical_keys::end_;
switch (usage) {
case kHIDUsage_KeyboardLeftControl:
key = modifier_flag_manager::physical_keys::left_control;
break;
case kHIDUsage_KeyboardLeftShift:
key = modifier_flag_manager::physical_keys::left_shift;
break;
case kHIDUsage_KeyboardLeftAlt:
key = modifier_flag_manager::physical_keys::left_option;
break;
case kHIDUsage_KeyboardLeftGUI:
key = modifier_flag_manager::physical_keys::left_command;
break;
case kHIDUsage_KeyboardRightControl:
key = modifier_flag_manager::physical_keys::right_control;
break;
case kHIDUsage_KeyboardRightShift:
key = modifier_flag_manager::physical_keys::right_shift;
break;
case kHIDUsage_KeyboardRightAlt:
key = modifier_flag_manager::physical_keys::right_option;
break;
case kHIDUsage_KeyboardRightGUI:
key = modifier_flag_manager::physical_keys::right_command;
break;
}
if (key != modifier_flag_manager::physical_keys::end_) {
modifier_flag_manager_.manipulate(key, operation);
send_keyboard_input_report();
return true;
}
break;
}
case kHIDPage_AppleVendorTopCase:
if (usage == kHIDUsage_AV_TopCase_KeyboardFn) {
modifier_flag_manager_.manipulate(modifier_flag_manager::physical_keys::fn, operation);
console_user_client_.post_modifier_flags();
return true;
}
break;
}
return false;
}
bool handle_function_key_event(uint32_t usage_page, uint32_t usage, bool pressed) {
if (usage_page != kHIDPage_KeyboardOrKeypad) {
return false;
}
auto event_type = pressed ? KRBN_EVENT_TYPE_KEY_DOWN : KRBN_EVENT_TYPE_KEY_UP;
#define POST_KEY(KEY) \
case kHIDUsage_Keyboard##KEY: \
console_user_client_.post_key(KRBN_KEY_CODE_##KEY, event_type); \
return true;
switch (usage) {
POST_KEY(F1);
POST_KEY(F2);
POST_KEY(F3);
POST_KEY(F4);
POST_KEY(F5);
POST_KEY(F6);
POST_KEY(F7);
POST_KEY(F8);
POST_KEY(F9);
POST_KEY(F10);
POST_KEY(F11);
POST_KEY(F12);
}
return false;
}
void handle_keyboard_event(uint32_t usage_page, uint32_t usage, bool pressed) {
// ----------------------------------------
// modify usage
if (usage == kHIDUsage_KeyboardCapsLock) {
usage = kHIDUsage_KeyboardDeleteOrBackspace;
}
if (modifier_flag_manager_.pressed(modifier_flag_manager::physical_keys::fn)) {
switch (usage) {
case kHIDUsage_KeyboardReturnOrEnter:
usage = kHIDUsage_KeypadEnter;
break;
case kHIDUsage_KeyboardDeleteOrBackspace:
usage = kHIDUsage_KeyboardDeleteForward;
break;
case kHIDUsage_KeyboardRightArrow:
usage = kHIDUsage_KeyboardEnd;
break;
case kHIDUsage_KeyboardLeftArrow:
usage = kHIDUsage_KeyboardHome;
break;
case kHIDUsage_KeyboardDownArrow:
usage = kHIDUsage_KeyboardPageDown;
break;
case kHIDUsage_KeyboardUpArrow:
usage = kHIDUsage_KeyboardPageUp;
break;
}
}
// ----------------------------------------
if (handle_modifier_flag_event(usage_page, usage, pressed)) {
console_user_client_.stop_key_repeat();
return;
}
if (handle_function_key_event(usage_page, usage, pressed)) {
return;
}
if (pressed) {
pressed_key_usages_.push_back(usage);
console_user_client_.stop_key_repeat();
} else {
pressed_key_usages_.remove(usage);
}
send_keyboard_input_report();
}
void send_keyboard_input_report(void) {
// make report
hid_report::keyboard_input report;
report.modifiers = modifier_flag_manager_.get_hid_report_bits();
while (pressed_key_usages_.size() > sizeof(report.keys)) {
pressed_key_usages_.pop_front();
}
int i = 0;
for (const auto& u : pressed_key_usages_) {
report.keys[i] = u;
++i;
}
// send new report only if it is changed from last report.
if (last_keyboard_input_report_ != report) {
last_keyboard_input_report_ = report;
auto kr = iokit_user_client_.call_struct_method(static_cast<uint32_t>(virtual_hid_manager_user_client_method::keyboard_input_report),
static_cast<const void*>(&report), sizeof(report),
nullptr, 0);
if (kr != KERN_SUCCESS) {
logger::get_logger().error("failed to sent report: 0x{0:x}", kr);
}
}
}
iokit_user_client iokit_user_client_;
IOHIDManagerRef _Nullable manager_;
std::unordered_map<IOHIDDeviceRef, std::unique_ptr<human_interface_device>> hids_;
std::list<uint32_t> pressed_key_usages_;
modifier_flag_manager modifier_flag_manager_;
hid_report::keyboard_input last_keyboard_input_report_;
console_user_client console_user_client_;
};
<|endoftext|> |
<commit_before>// Copyright (c) 2009 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome/test/ui/ui_test.h"
#include "base/file_path.h"
#include "chrome/app/chrome_dll_resource.h"
#include "chrome/browser/chrome_thread.h"
#include "chrome/browser/dom_ui/new_tab_ui.h"
#include "chrome/browser/pref_service.h"
#include "chrome/browser/pref_value_store.h"
#include "chrome/common/json_pref_store.h"
#include "chrome/common/pref_names.h"
#include "chrome/test/automation/browser_proxy.h"
#include "chrome/test/automation/tab_proxy.h"
#include "chrome/test/automation/window_proxy.h"
class NewTabUITest : public UITest {
public:
NewTabUITest() {
dom_automation_enabled_ = true;
// Set home page to the empty string so that we can set the home page using
// preferences.
homepage_ = L"";
// Setup the DEFAULT_THEME profile (has fake history entries).
set_template_user_data(UITest::ComputeTypicalUserDataSource(
UITest::DEFAULT_THEME));
}
};
TEST_F(NewTabUITest, NTPHasThumbnails) {
// Switch to the "new tab" tab, which should be any new tab after the
// first (the first is about:blank).
scoped_refptr<BrowserProxy> window(automation()->GetBrowserWindow(0));
ASSERT_TRUE(window.get());
// Bring up a new tab page.
ASSERT_TRUE(window->RunCommand(IDC_NEW_TAB));
int load_time;
ASSERT_TRUE(automation()->WaitForInitialNewTabUILoad(&load_time));
// Blank thumbnails on the NTP have the class 'filler' applied to the div.
// If all the thumbnails load, there should be no div's with 'filler'.
scoped_refptr<TabProxy> tab = window->GetActiveTab();
ASSERT_TRUE(tab.get());
ASSERT_TRUE(WaitUntilJavaScriptCondition(tab, L"",
L"window.domAutomationController.send("
L"document.getElementsByClassName('filler').length == 0)",
action_max_timeout_ms()));
}
// Fails about ~5% of the time on all platforms. http://crbug.com/45001
TEST_F(NewTabUITest, FLAKY_ChromeInternalLoadsNTP) {
scoped_refptr<BrowserProxy> window(automation()->GetBrowserWindow(0));
ASSERT_TRUE(window.get());
// Go to the "new tab page" using its old url, rather than chrome://newtab.
scoped_refptr<TabProxy> tab = window->GetTab(0);
ASSERT_TRUE(tab.get());
ASSERT_TRUE(tab->NavigateToURLAsync(GURL("chrome-internal:")));
int load_time;
ASSERT_TRUE(automation()->WaitForInitialNewTabUILoad(&load_time));
// Ensure there are some thumbnails loaded in the page.
int thumbnails_count = -1;
ASSERT_TRUE(tab->ExecuteAndExtractInt(L"",
L"window.domAutomationController.send("
L"document.getElementsByClassName('thumbnail-container').length)",
&thumbnails_count));
EXPECT_GT(thumbnails_count, 0);
}
TEST_F(NewTabUITest, UpdateUserPrefsVersion) {
// PrefService with JSON user-pref file only, no enforced or advised prefs.
FilePath user_prefs = FilePath();
scoped_ptr<PrefService> prefs(
PrefService::CreateUserPrefService(user_prefs));
// Does the migration
NewTabUI::RegisterUserPrefs(prefs.get());
ASSERT_EQ(NewTabUI::current_pref_version(),
prefs->GetInteger(prefs::kNTPPrefVersion));
// Reset the version
prefs->ClearPref(prefs::kNTPPrefVersion);
ASSERT_EQ(0, prefs->GetInteger(prefs::kNTPPrefVersion));
bool migrated = NewTabUI::UpdateUserPrefsVersion(prefs.get());
ASSERT_TRUE(migrated);
ASSERT_EQ(NewTabUI::current_pref_version(),
prefs->GetInteger(prefs::kNTPPrefVersion));
migrated = NewTabUI::UpdateUserPrefsVersion(prefs.get());
ASSERT_FALSE(migrated);
}
TEST_F(NewTabUITest, HomePageLink) {
scoped_refptr<BrowserProxy> browser(automation()->GetBrowserWindow(0));
ASSERT_TRUE(browser.get());
ASSERT_TRUE(
browser->SetBooleanPreference(prefs::kHomePageIsNewTabPage, false));
// Bring up a new tab page.
ASSERT_TRUE(browser->RunCommand(IDC_NEW_TAB));
int load_time;
ASSERT_TRUE(automation()->WaitForInitialNewTabUILoad(&load_time));
scoped_refptr<TabProxy> tab = browser->GetActiveTab();
ASSERT_TRUE(tab.get());
// TODO(arv): Extract common patterns for doing js testing.
// Fire click. Because tip service is turned off for testing, we first
// force the "make this my home page" tip to appear.
// TODO(arv): Find screen position of element and use a lower level click
// emulation.
bool result;
ASSERT_TRUE(tab->ExecuteAndExtractBool(L"",
L"window.domAutomationController.send("
L"(function() {"
L" tipCache = [{\"set_homepage_tip\":\"Make this the home page\"}];"
L" renderTip();"
L" var e = document.createEvent('Event');"
L" e.initEvent('click', true, true);"
L" var el = document.querySelector('#tip-line > button');"
L" el.dispatchEvent(e);"
L" return true;"
L"})()"
L")",
&result));
ASSERT_TRUE(result);
// Make sure text of "set as home page" tip has been removed.
std::wstring tip_text_content;
ASSERT_TRUE(tab->ExecuteAndExtractString(L"",
L"window.domAutomationController.send("
L"(function() {"
L" var el = document.querySelector('#tip-line');"
L" return el.textContent;"
L"})()"
L")",
&tip_text_content));
ASSERT_EQ(L"", tip_text_content);
// Make sure that the notification is visible
bool has_class;
ASSERT_TRUE(tab->ExecuteAndExtractBool(L"",
L"window.domAutomationController.send("
L"(function() {"
L" var el = document.querySelector('#notification');"
L" return el.classList.contains('show');"
L"})()"
L")",
&has_class));
ASSERT_TRUE(has_class);
bool is_home_page;
ASSERT_TRUE(browser->GetBooleanPreference(prefs::kHomePageIsNewTabPage,
&is_home_page));
ASSERT_TRUE(is_home_page);
}
TEST_F(NewTabUITest, PromoLink) {
#if defined(OS_WIN)
scoped_refptr<BrowserProxy> browser(automation()->GetBrowserWindow(0));
ASSERT_TRUE(browser.get());
// Bring up a new tab page.
ASSERT_TRUE(browser->RunCommand(IDC_NEW_TAB));
int load_time;
ASSERT_TRUE(automation()->WaitForInitialNewTabUILoad(&load_time));
scoped_refptr<TabProxy> tab = browser->GetActiveTab();
ASSERT_TRUE(tab.get());
// Test "import bookmarks" promo.
bool result;
ASSERT_TRUE(tab->ExecuteAndExtractBool(L"",
L"window.domAutomationController.send("
L"(function() {"
L" tipCache = [{\"set_promo_tip\":"
L"\"<button class='link'>Import</button> bookmarks\"}];"
L" renderTip();"
L" var e = document.createEvent('Event');"
L" e.initEvent('click', true, true);"
L" var el = document.querySelector('#tip-line button');"
L" el.dispatchEvent(e);"
L" return true;"
L"})()"
L")",
&result));
ASSERT_TRUE(result);
#endif
// TODO(mirandac): Ensure that we showed the import bookmarks dialog.
// Remove check for OS_WIN after implemented in Mac and Linux.
}
<commit_msg>Remove test which works on local Win machines but fails the Win bots (suspect test harness issues).<commit_after>// Copyright (c) 2009 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome/test/ui/ui_test.h"
#include "base/file_path.h"
#include "chrome/app/chrome_dll_resource.h"
#include "chrome/browser/chrome_thread.h"
#include "chrome/browser/dom_ui/new_tab_ui.h"
#include "chrome/browser/pref_service.h"
#include "chrome/browser/pref_value_store.h"
#include "chrome/common/json_pref_store.h"
#include "chrome/common/pref_names.h"
#include "chrome/test/automation/browser_proxy.h"
#include "chrome/test/automation/tab_proxy.h"
#include "chrome/test/automation/window_proxy.h"
class NewTabUITest : public UITest {
public:
NewTabUITest() {
dom_automation_enabled_ = true;
// Set home page to the empty string so that we can set the home page using
// preferences.
homepage_ = L"";
// Setup the DEFAULT_THEME profile (has fake history entries).
set_template_user_data(UITest::ComputeTypicalUserDataSource(
UITest::DEFAULT_THEME));
}
};
TEST_F(NewTabUITest, NTPHasThumbnails) {
// Switch to the "new tab" tab, which should be any new tab after the
// first (the first is about:blank).
scoped_refptr<BrowserProxy> window(automation()->GetBrowserWindow(0));
ASSERT_TRUE(window.get());
// Bring up a new tab page.
ASSERT_TRUE(window->RunCommand(IDC_NEW_TAB));
int load_time;
ASSERT_TRUE(automation()->WaitForInitialNewTabUILoad(&load_time));
// Blank thumbnails on the NTP have the class 'filler' applied to the div.
// If all the thumbnails load, there should be no div's with 'filler'.
scoped_refptr<TabProxy> tab = window->GetActiveTab();
ASSERT_TRUE(tab.get());
ASSERT_TRUE(WaitUntilJavaScriptCondition(tab, L"",
L"window.domAutomationController.send("
L"document.getElementsByClassName('filler').length == 0)",
action_max_timeout_ms()));
}
// Fails about ~5% of the time on all platforms. http://crbug.com/45001
TEST_F(NewTabUITest, FLAKY_ChromeInternalLoadsNTP) {
scoped_refptr<BrowserProxy> window(automation()->GetBrowserWindow(0));
ASSERT_TRUE(window.get());
// Go to the "new tab page" using its old url, rather than chrome://newtab.
scoped_refptr<TabProxy> tab = window->GetTab(0);
ASSERT_TRUE(tab.get());
ASSERT_TRUE(tab->NavigateToURLAsync(GURL("chrome-internal:")));
int load_time;
ASSERT_TRUE(automation()->WaitForInitialNewTabUILoad(&load_time));
// Ensure there are some thumbnails loaded in the page.
int thumbnails_count = -1;
ASSERT_TRUE(tab->ExecuteAndExtractInt(L"",
L"window.domAutomationController.send("
L"document.getElementsByClassName('thumbnail-container').length)",
&thumbnails_count));
EXPECT_GT(thumbnails_count, 0);
}
TEST_F(NewTabUITest, UpdateUserPrefsVersion) {
// PrefService with JSON user-pref file only, no enforced or advised prefs.
FilePath user_prefs = FilePath();
scoped_ptr<PrefService> prefs(
PrefService::CreateUserPrefService(user_prefs));
// Does the migration
NewTabUI::RegisterUserPrefs(prefs.get());
ASSERT_EQ(NewTabUI::current_pref_version(),
prefs->GetInteger(prefs::kNTPPrefVersion));
// Reset the version
prefs->ClearPref(prefs::kNTPPrefVersion);
ASSERT_EQ(0, prefs->GetInteger(prefs::kNTPPrefVersion));
bool migrated = NewTabUI::UpdateUserPrefsVersion(prefs.get());
ASSERT_TRUE(migrated);
ASSERT_EQ(NewTabUI::current_pref_version(),
prefs->GetInteger(prefs::kNTPPrefVersion));
migrated = NewTabUI::UpdateUserPrefsVersion(prefs.get());
ASSERT_FALSE(migrated);
}
TEST_F(NewTabUITest, HomePageLink) {
scoped_refptr<BrowserProxy> browser(automation()->GetBrowserWindow(0));
ASSERT_TRUE(browser.get());
ASSERT_TRUE(
browser->SetBooleanPreference(prefs::kHomePageIsNewTabPage, false));
// Bring up a new tab page.
ASSERT_TRUE(browser->RunCommand(IDC_NEW_TAB));
int load_time;
ASSERT_TRUE(automation()->WaitForInitialNewTabUILoad(&load_time));
scoped_refptr<TabProxy> tab = browser->GetActiveTab();
ASSERT_TRUE(tab.get());
// TODO(arv): Extract common patterns for doing js testing.
// Fire click. Because tip service is turned off for testing, we first
// force the "make this my home page" tip to appear.
// TODO(arv): Find screen position of element and use a lower level click
// emulation.
bool result;
ASSERT_TRUE(tab->ExecuteAndExtractBool(L"",
L"window.domAutomationController.send("
L"(function() {"
L" tipCache = [{\"set_homepage_tip\":\"Make this the home page\"}];"
L" renderTip();"
L" var e = document.createEvent('Event');"
L" e.initEvent('click', true, true);"
L" var el = document.querySelector('#tip-line > button');"
L" el.dispatchEvent(e);"
L" return true;"
L"})()"
L")",
&result));
ASSERT_TRUE(result);
// Make sure text of "set as home page" tip has been removed.
std::wstring tip_text_content;
ASSERT_TRUE(tab->ExecuteAndExtractString(L"",
L"window.domAutomationController.send("
L"(function() {"
L" var el = document.querySelector('#tip-line');"
L" return el.textContent;"
L"})()"
L")",
&tip_text_content));
ASSERT_EQ(L"", tip_text_content);
// Make sure that the notification is visible
bool has_class;
ASSERT_TRUE(tab->ExecuteAndExtractBool(L"",
L"window.domAutomationController.send("
L"(function() {"
L" var el = document.querySelector('#notification');"
L" return el.classList.contains('show');"
L"})()"
L")",
&has_class));
ASSERT_TRUE(has_class);
bool is_home_page;
ASSERT_TRUE(browser->GetBooleanPreference(prefs::kHomePageIsNewTabPage,
&is_home_page));
ASSERT_TRUE(is_home_page);
}
<|endoftext|> |
<commit_before>#include <osgViewer/Viewer>
#include <osg/Projection>
#include <osg/Geometry>
#include <osg/Texture>
#include <osg/TexGen>
#include <osg/Geode>
#include <osg/ShapeDrawable>
#include <osg/PolygonOffset>
#include <osg/CullFace>
#include <osg/TextureCubeMap>
#include <osg/TexMat>
#include <osg/MatrixTransform>
#include <osg/Light>
#include <osg/LightSource>
#include <osg/PolygonOffset>
#include <osg/CullFace>
#include <osg/Material>
#include <osg/PositionAttitudeTransform>
#include <osg/ArgumentParser>
#include <osg/Camera>
#include <osg/TexGenNode>
#include <iostream>
using namespace osg;
ref_ptr<Group> _create_scene()
{
ref_ptr<Group> scene = new Group;
ref_ptr<Geode> geode_1 = new Geode;
scene->addChild(geode_1.get());
ref_ptr<Geode> geode_2 = new Geode;
ref_ptr<MatrixTransform> transform_2 = new MatrixTransform;
transform_2->addChild(geode_2.get());
transform_2->setUpdateCallback(new osg::AnimationPathCallback(Vec3(0, 0, 0), Y_AXIS, inDegrees(45.0f)));
scene->addChild(transform_2.get());
ref_ptr<Geode> geode_3 = new Geode;
ref_ptr<MatrixTransform> transform_3 = new MatrixTransform;
transform_3->addChild(geode_3.get());
transform_3->setUpdateCallback(new osg::AnimationPathCallback(Vec3(0, 0, 0), Y_AXIS, inDegrees(-22.5f)));
scene->addChild(transform_3.get());
const float radius = 0.8f;
const float height = 1.0f;
ref_ptr<TessellationHints> hints = new TessellationHints;
hints->setDetailRatio(2.0f);
ref_ptr<ShapeDrawable> shape;
shape = new ShapeDrawable(new Box(Vec3(0.0f, -2.0f, 0.0f), 10, 0.1f, 10), hints.get());
shape->setColor(Vec4(0.5f, 0.5f, 0.7f, 1.0f));
geode_1->addDrawable(shape.get());
shape = new ShapeDrawable(new Sphere(Vec3(-3.0f, 0.0f, 0.0f), radius), hints.get());
shape->setColor(Vec4(0.6f, 0.8f, 0.8f, 1.0f));
geode_2->addDrawable(shape.get());
shape = new ShapeDrawable(new Box(Vec3(3.0f, 0.0f, 0.0f), 2 * radius), hints.get());
shape->setColor(Vec4(0.4f, 0.9f, 0.3f, 1.0f));
geode_2->addDrawable(shape.get());
shape = new ShapeDrawable(new Cone(Vec3(0.0f, 0.0f, -3.0f), radius, height), hints.get());
shape->setColor(Vec4(0.2f, 0.5f, 0.7f, 1.0f));
geode_2->addDrawable(shape.get());
shape = new ShapeDrawable(new Cylinder(Vec3(0.0f, 0.0f, 3.0f), radius, height), hints.get());
shape->setColor(Vec4(1.0f, 0.3f, 0.3f, 1.0f));
geode_2->addDrawable(shape.get());
shape = new ShapeDrawable(new Box(Vec3(0.0f, 3.0f, 0.0f), 2, 0.1f, 2), hints.get());
shape->setColor(Vec4(0.8f, 0.8f, 0.4f, 1.0f));
geode_3->addDrawable(shape.get());
// material
ref_ptr<Material> matirial = new Material;
matirial->setColorMode(Material::DIFFUSE);
matirial->setAmbient(Material::FRONT_AND_BACK, Vec4(0, 0, 0, 1));
matirial->setSpecular(Material::FRONT_AND_BACK, Vec4(1, 1, 1, 1));
matirial->setShininess(Material::FRONT_AND_BACK, 64.0f);
scene->getOrCreateStateSet()->setAttributeAndModes(matirial.get(), StateAttribute::ON);
return scene;
}
osg::NodePath createReflector()
{
osg::PositionAttitudeTransform* pat = new osg::PositionAttitudeTransform;
pat->setPosition(osg::Vec3(0.0f,0.0f,0.0f));
pat->setAttitude(osg::Quat(osg::inDegrees(0.0f),osg::Vec3(0.0f,0.0f,1.0f)));
Geode* geode_1 = new Geode;
pat->addChild(geode_1);
const float radius = 0.8f;
ref_ptr<TessellationHints> hints = new TessellationHints;
hints->setDetailRatio(2.0f);
ShapeDrawable* shape = new ShapeDrawable(new Sphere(Vec3(0.0f, 0.0f, 0.0f), radius * 1.5f), hints.get());
shape->setColor(Vec4(0.8f, 0.8f, 0.8f, 1.0f));
geode_1->addDrawable(shape);
osg::NodePath nodeList;
nodeList.push_back(pat);
nodeList.push_back(geode_1);
return nodeList;
}
class UpdateCameraAndTexGenCallback : public osg::NodeCallback
{
public:
typedef std::vector< osg::ref_ptr<osg::Camera> > CameraList;
UpdateCameraAndTexGenCallback(osg::NodePath& reflectorNodePath, CameraList& Cameras):
_reflectorNodePath(reflectorNodePath),
_Cameras(Cameras)
{
}
virtual void operator()(osg::Node* node, osg::NodeVisitor* nv)
{
// first update subgraph to make sure objects are all moved into postion
traverse(node,nv);
// compute the position of the center of the reflector subgraph
osg::Matrixd worldToLocal = osg::computeWorldToLocal(_reflectorNodePath);
osg::BoundingSphere bs = _reflectorNodePath.back()->getBound();
osg::Vec3 position = bs.center();
typedef std::pair<osg::Vec3, osg::Vec3> ImageData;
const ImageData id[] =
{
ImageData( osg::Vec3( 1, 0, 0), osg::Vec3( 0, -1, 0) ), // +X
ImageData( osg::Vec3(-1, 0, 0), osg::Vec3( 0, -1, 0) ), // -X
ImageData( osg::Vec3( 0, 1, 0), osg::Vec3( 0, 0, 1) ), // +Y
ImageData( osg::Vec3( 0, -1, 0), osg::Vec3( 0, 0, -1) ), // -Y
ImageData( osg::Vec3( 0, 0, 1), osg::Vec3( 0, -1, 0) ), // +Z
ImageData( osg::Vec3( 0, 0, -1), osg::Vec3( 0, -1, 0) ) // -Z
};
for(unsigned int i=0;
i<6 && i<_Cameras.size();
++i)
{
osg::Matrix localOffset;
localOffset.makeLookAt(position,position+id[i].first,id[i].second);
osg::Matrix viewMatrix = worldToLocal*localOffset;
_Cameras[i]->setReferenceFrame(osg::Camera::ABSOLUTE_RF);
_Cameras[i]->setProjectionMatrixAsFrustum(-1.0,1.0,-1.0,1.0,1.0,10000.0);
_Cameras[i]->setViewMatrix(viewMatrix);
}
}
protected:
virtual ~UpdateCameraAndTexGenCallback() {}
osg::NodePath _reflectorNodePath;
CameraList _Cameras;
};
class TexMatCullCallback : public osg::NodeCallback
{
public:
TexMatCullCallback(osg::TexMat* texmat):
_texmat(texmat)
{
}
virtual void operator()(osg::Node* node, osg::NodeVisitor* nv)
{
// first update subgraph to make sure objects are all moved into postion
traverse(node,nv);
osgUtil::CullVisitor* cv = dynamic_cast<osgUtil::CullVisitor*>(nv);
if (cv)
{
osg::Quat quat = cv->getModelViewMatrix().getRotate();
_texmat->setMatrix(osg::Matrix::rotate(quat.inverse()));
}
}
protected:
osg::ref_ptr<TexMat> _texmat;
};
osg::Group* createShadowedScene(osg::Node* reflectedSubgraph, osg::NodePath reflectorNodePath, unsigned int unit, const osg::Vec4& clearColor, unsigned tex_width, unsigned tex_height, osg::Camera::RenderTargetImplementation renderImplementation)
{
osg::Group* group = new osg::Group;
osg::TextureCubeMap* texture = new osg::TextureCubeMap;
texture->setTextureSize(tex_width, tex_height);
texture->setInternalFormat(GL_RGB);
texture->setWrap(osg::Texture::WRAP_S, osg::Texture::CLAMP_TO_EDGE);
texture->setWrap(osg::Texture::WRAP_T, osg::Texture::CLAMP_TO_EDGE);
texture->setWrap(osg::Texture::WRAP_R, osg::Texture::CLAMP_TO_EDGE);
texture->setFilter(osg::TextureCubeMap::MIN_FILTER,osg::TextureCubeMap::LINEAR);
texture->setFilter(osg::TextureCubeMap::MAG_FILTER,osg::TextureCubeMap::LINEAR);
// set up the render to texture cameras.
UpdateCameraAndTexGenCallback::CameraList Cameras;
for(unsigned int i=0; i<6; ++i)
{
// create the camera
osg::Camera* camera = new osg::Camera;
camera->setClearMask(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
camera->setClearColor(clearColor);
// set viewport
camera->setViewport(0,0,tex_width,tex_height);
// set the camera to render before the main camera.
camera->setRenderOrder(osg::Camera::PRE_RENDER);
// tell the camera to use OpenGL frame buffer object where supported.
camera->setRenderTargetImplementation(renderImplementation);
// attach the texture and use it as the color buffer.
camera->attach(osg::Camera::COLOR_BUFFER, texture, 0, i);
// add subgraph to render
camera->addChild(reflectedSubgraph);
group->addChild(camera);
Cameras.push_back(camera);
}
// create the texgen node to project the tex coords onto the subgraph
osg::TexGenNode* texgenNode = new osg::TexGenNode;
texgenNode->getTexGen()->setMode(osg::TexGen::REFLECTION_MAP);
texgenNode->setTextureUnit(unit);
group->addChild(texgenNode);
// set the reflected subgraph so that it uses the texture and tex gen settings.
{
osg::Node* reflectorNode = reflectorNodePath.front();
group->addChild(reflectorNode);
osg::StateSet* stateset = reflectorNode->getOrCreateStateSet();
stateset->setTextureAttributeAndModes(unit,texture,osg::StateAttribute::ON);
stateset->setTextureMode(unit,GL_TEXTURE_GEN_S,osg::StateAttribute::ON);
stateset->setTextureMode(unit,GL_TEXTURE_GEN_T,osg::StateAttribute::ON);
stateset->setTextureMode(unit,GL_TEXTURE_GEN_R,osg::StateAttribute::ON);
stateset->setTextureMode(unit,GL_TEXTURE_GEN_Q,osg::StateAttribute::ON);
osg::TexMat* texmat = new osg::TexMat;
stateset->setTextureAttributeAndModes(unit,texmat,osg::StateAttribute::ON);
reflectorNode->setCullCallback(new TexMatCullCallback(texmat));
}
// add the reflector scene to draw just as normal
group->addChild(reflectedSubgraph);
// set an update callback to keep moving the camera and tex gen in the right direction.
group->setUpdateCallback(new UpdateCameraAndTexGenCallback(reflectorNodePath, Cameras));
return group;
}
int main(int argc, char** argv)
{
// use an ArgumentParser object to manage the program arguments.
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 using of GL_ARB_shadow extension implemented in osg::Texture class");
arguments.getApplicationUsage()->setCommandLineUsage(arguments.getApplicationName());
arguments.getApplicationUsage()->addCommandLineOption("-h or --help", "Display this information");
arguments.getApplicationUsage()->addCommandLineOption("--fbo","Use Frame Buffer Object for render to texture, where supported.");
arguments.getApplicationUsage()->addCommandLineOption("--fb","Use FrameBuffer for render to texture.");
arguments.getApplicationUsage()->addCommandLineOption("--pbuffer","Use Pixel Buffer for render to texture, where supported.");
arguments.getApplicationUsage()->addCommandLineOption("--window","Use a seperate Window for render to texture.");
arguments.getApplicationUsage()->addCommandLineOption("--width","Set the width of the render to texture");
arguments.getApplicationUsage()->addCommandLineOption("--height","Set the height of the render to texture");
// construct the viewer.
osgViewer::Viewer viewer;
// if user request help write it out to cout.
if (arguments.read("-h") || arguments.read("--help"))
{
arguments.getApplicationUsage()->write(std::cout);
return 1;
}
unsigned tex_width = 512;
unsigned tex_height = 512;
while (arguments.read("--width", tex_width)) {}
while (arguments.read("--height", tex_height)) {}
osg::Camera::RenderTargetImplementation renderImplementation = osg::Camera::FRAME_BUFFER_OBJECT;
while (arguments.read("--fbo")) { renderImplementation = osg::Camera::FRAME_BUFFER_OBJECT; }
while (arguments.read("--pbuffer")) { renderImplementation = osg::Camera::PIXEL_BUFFER; }
while (arguments.read("--fb")) { renderImplementation = osg::Camera::FRAME_BUFFER; }
while (arguments.read("--window")) { renderImplementation = osg::Camera::SEPERATE_WINDOW; }
// 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;
}
ref_ptr<MatrixTransform> scene = new MatrixTransform;
scene->setMatrix(osg::Matrix::rotate(osg::DegreesToRadians(125.0),1.0,0.0,0.0));
ref_ptr<Group> reflectedSubgraph = _create_scene();
if (!reflectedSubgraph.valid()) return 1;
ref_ptr<Group> reflectedScene = createShadowedScene(reflectedSubgraph.get(), createReflector(), 0, viewer.getCamera()->getClearColor(),
tex_width, tex_height, renderImplementation);
scene->addChild(reflectedScene.get());
viewer.setSceneData(scene.get());
return viewer.run();
}
<commit_msg>Reduced the RTT texture size to 256x256 to make setup quicker<commit_after>#include <osgViewer/Viewer>
#include <osg/Projection>
#include <osg/Geometry>
#include <osg/Texture>
#include <osg/TexGen>
#include <osg/Geode>
#include <osg/ShapeDrawable>
#include <osg/PolygonOffset>
#include <osg/CullFace>
#include <osg/TextureCubeMap>
#include <osg/TexMat>
#include <osg/MatrixTransform>
#include <osg/Light>
#include <osg/LightSource>
#include <osg/PolygonOffset>
#include <osg/CullFace>
#include <osg/Material>
#include <osg/PositionAttitudeTransform>
#include <osg/ArgumentParser>
#include <osg/Camera>
#include <osg/TexGenNode>
#include <iostream>
using namespace osg;
ref_ptr<Group> _create_scene()
{
ref_ptr<Group> scene = new Group;
ref_ptr<Geode> geode_1 = new Geode;
scene->addChild(geode_1.get());
ref_ptr<Geode> geode_2 = new Geode;
ref_ptr<MatrixTransform> transform_2 = new MatrixTransform;
transform_2->addChild(geode_2.get());
transform_2->setUpdateCallback(new osg::AnimationPathCallback(Vec3(0, 0, 0), Y_AXIS, inDegrees(45.0f)));
scene->addChild(transform_2.get());
ref_ptr<Geode> geode_3 = new Geode;
ref_ptr<MatrixTransform> transform_3 = new MatrixTransform;
transform_3->addChild(geode_3.get());
transform_3->setUpdateCallback(new osg::AnimationPathCallback(Vec3(0, 0, 0), Y_AXIS, inDegrees(-22.5f)));
scene->addChild(transform_3.get());
const float radius = 0.8f;
const float height = 1.0f;
ref_ptr<TessellationHints> hints = new TessellationHints;
hints->setDetailRatio(2.0f);
ref_ptr<ShapeDrawable> shape;
shape = new ShapeDrawable(new Box(Vec3(0.0f, -2.0f, 0.0f), 10, 0.1f, 10), hints.get());
shape->setColor(Vec4(0.5f, 0.5f, 0.7f, 1.0f));
geode_1->addDrawable(shape.get());
shape = new ShapeDrawable(new Sphere(Vec3(-3.0f, 0.0f, 0.0f), radius), hints.get());
shape->setColor(Vec4(0.6f, 0.8f, 0.8f, 1.0f));
geode_2->addDrawable(shape.get());
shape = new ShapeDrawable(new Box(Vec3(3.0f, 0.0f, 0.0f), 2 * radius), hints.get());
shape->setColor(Vec4(0.4f, 0.9f, 0.3f, 1.0f));
geode_2->addDrawable(shape.get());
shape = new ShapeDrawable(new Cone(Vec3(0.0f, 0.0f, -3.0f), radius, height), hints.get());
shape->setColor(Vec4(0.2f, 0.5f, 0.7f, 1.0f));
geode_2->addDrawable(shape.get());
shape = new ShapeDrawable(new Cylinder(Vec3(0.0f, 0.0f, 3.0f), radius, height), hints.get());
shape->setColor(Vec4(1.0f, 0.3f, 0.3f, 1.0f));
geode_2->addDrawable(shape.get());
shape = new ShapeDrawable(new Box(Vec3(0.0f, 3.0f, 0.0f), 2, 0.1f, 2), hints.get());
shape->setColor(Vec4(0.8f, 0.8f, 0.4f, 1.0f));
geode_3->addDrawable(shape.get());
// material
ref_ptr<Material> matirial = new Material;
matirial->setColorMode(Material::DIFFUSE);
matirial->setAmbient(Material::FRONT_AND_BACK, Vec4(0, 0, 0, 1));
matirial->setSpecular(Material::FRONT_AND_BACK, Vec4(1, 1, 1, 1));
matirial->setShininess(Material::FRONT_AND_BACK, 64.0f);
scene->getOrCreateStateSet()->setAttributeAndModes(matirial.get(), StateAttribute::ON);
return scene;
}
osg::NodePath createReflector()
{
osg::PositionAttitudeTransform* pat = new osg::PositionAttitudeTransform;
pat->setPosition(osg::Vec3(0.0f,0.0f,0.0f));
pat->setAttitude(osg::Quat(osg::inDegrees(0.0f),osg::Vec3(0.0f,0.0f,1.0f)));
Geode* geode_1 = new Geode;
pat->addChild(geode_1);
const float radius = 0.8f;
ref_ptr<TessellationHints> hints = new TessellationHints;
hints->setDetailRatio(2.0f);
ShapeDrawable* shape = new ShapeDrawable(new Sphere(Vec3(0.0f, 0.0f, 0.0f), radius * 1.5f), hints.get());
shape->setColor(Vec4(0.8f, 0.8f, 0.8f, 1.0f));
geode_1->addDrawable(shape);
osg::NodePath nodeList;
nodeList.push_back(pat);
nodeList.push_back(geode_1);
return nodeList;
}
class UpdateCameraAndTexGenCallback : public osg::NodeCallback
{
public:
typedef std::vector< osg::ref_ptr<osg::Camera> > CameraList;
UpdateCameraAndTexGenCallback(osg::NodePath& reflectorNodePath, CameraList& Cameras):
_reflectorNodePath(reflectorNodePath),
_Cameras(Cameras)
{
}
virtual void operator()(osg::Node* node, osg::NodeVisitor* nv)
{
// first update subgraph to make sure objects are all moved into postion
traverse(node,nv);
// compute the position of the center of the reflector subgraph
osg::Matrixd worldToLocal = osg::computeWorldToLocal(_reflectorNodePath);
osg::BoundingSphere bs = _reflectorNodePath.back()->getBound();
osg::Vec3 position = bs.center();
typedef std::pair<osg::Vec3, osg::Vec3> ImageData;
const ImageData id[] =
{
ImageData( osg::Vec3( 1, 0, 0), osg::Vec3( 0, -1, 0) ), // +X
ImageData( osg::Vec3(-1, 0, 0), osg::Vec3( 0, -1, 0) ), // -X
ImageData( osg::Vec3( 0, 1, 0), osg::Vec3( 0, 0, 1) ), // +Y
ImageData( osg::Vec3( 0, -1, 0), osg::Vec3( 0, 0, -1) ), // -Y
ImageData( osg::Vec3( 0, 0, 1), osg::Vec3( 0, -1, 0) ), // +Z
ImageData( osg::Vec3( 0, 0, -1), osg::Vec3( 0, -1, 0) ) // -Z
};
for(unsigned int i=0;
i<6 && i<_Cameras.size();
++i)
{
osg::Matrix localOffset;
localOffset.makeLookAt(position,position+id[i].first,id[i].second);
osg::Matrix viewMatrix = worldToLocal*localOffset;
_Cameras[i]->setReferenceFrame(osg::Camera::ABSOLUTE_RF);
_Cameras[i]->setProjectionMatrixAsFrustum(-1.0,1.0,-1.0,1.0,1.0,10000.0);
_Cameras[i]->setViewMatrix(viewMatrix);
}
}
protected:
virtual ~UpdateCameraAndTexGenCallback() {}
osg::NodePath _reflectorNodePath;
CameraList _Cameras;
};
class TexMatCullCallback : public osg::NodeCallback
{
public:
TexMatCullCallback(osg::TexMat* texmat):
_texmat(texmat)
{
}
virtual void operator()(osg::Node* node, osg::NodeVisitor* nv)
{
// first update subgraph to make sure objects are all moved into postion
traverse(node,nv);
osgUtil::CullVisitor* cv = dynamic_cast<osgUtil::CullVisitor*>(nv);
if (cv)
{
osg::Quat quat = cv->getModelViewMatrix().getRotate();
_texmat->setMatrix(osg::Matrix::rotate(quat.inverse()));
}
}
protected:
osg::ref_ptr<TexMat> _texmat;
};
osg::Group* createShadowedScene(osg::Node* reflectedSubgraph, osg::NodePath reflectorNodePath, unsigned int unit, const osg::Vec4& clearColor, unsigned tex_width, unsigned tex_height, osg::Camera::RenderTargetImplementation renderImplementation)
{
osg::Group* group = new osg::Group;
osg::TextureCubeMap* texture = new osg::TextureCubeMap;
texture->setTextureSize(tex_width, tex_height);
texture->setInternalFormat(GL_RGB);
texture->setWrap(osg::Texture::WRAP_S, osg::Texture::CLAMP_TO_EDGE);
texture->setWrap(osg::Texture::WRAP_T, osg::Texture::CLAMP_TO_EDGE);
texture->setWrap(osg::Texture::WRAP_R, osg::Texture::CLAMP_TO_EDGE);
texture->setFilter(osg::TextureCubeMap::MIN_FILTER,osg::TextureCubeMap::LINEAR);
texture->setFilter(osg::TextureCubeMap::MAG_FILTER,osg::TextureCubeMap::LINEAR);
// set up the render to texture cameras.
UpdateCameraAndTexGenCallback::CameraList Cameras;
for(unsigned int i=0; i<6; ++i)
{
// create the camera
osg::Camera* camera = new osg::Camera;
camera->setClearMask(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
camera->setClearColor(clearColor);
// set viewport
camera->setViewport(0,0,tex_width,tex_height);
// set the camera to render before the main camera.
camera->setRenderOrder(osg::Camera::PRE_RENDER);
// tell the camera to use OpenGL frame buffer object where supported.
camera->setRenderTargetImplementation(renderImplementation);
// attach the texture and use it as the color buffer.
camera->attach(osg::Camera::COLOR_BUFFER, texture, 0, i);
// add subgraph to render
camera->addChild(reflectedSubgraph);
group->addChild(camera);
Cameras.push_back(camera);
}
// create the texgen node to project the tex coords onto the subgraph
osg::TexGenNode* texgenNode = new osg::TexGenNode;
texgenNode->getTexGen()->setMode(osg::TexGen::REFLECTION_MAP);
texgenNode->setTextureUnit(unit);
group->addChild(texgenNode);
// set the reflected subgraph so that it uses the texture and tex gen settings.
{
osg::Node* reflectorNode = reflectorNodePath.front();
group->addChild(reflectorNode);
osg::StateSet* stateset = reflectorNode->getOrCreateStateSet();
stateset->setTextureAttributeAndModes(unit,texture,osg::StateAttribute::ON);
stateset->setTextureMode(unit,GL_TEXTURE_GEN_S,osg::StateAttribute::ON);
stateset->setTextureMode(unit,GL_TEXTURE_GEN_T,osg::StateAttribute::ON);
stateset->setTextureMode(unit,GL_TEXTURE_GEN_R,osg::StateAttribute::ON);
stateset->setTextureMode(unit,GL_TEXTURE_GEN_Q,osg::StateAttribute::ON);
osg::TexMat* texmat = new osg::TexMat;
stateset->setTextureAttributeAndModes(unit,texmat,osg::StateAttribute::ON);
reflectorNode->setCullCallback(new TexMatCullCallback(texmat));
}
// add the reflector scene to draw just as normal
group->addChild(reflectedSubgraph);
// set an update callback to keep moving the camera and tex gen in the right direction.
group->setUpdateCallback(new UpdateCameraAndTexGenCallback(reflectorNodePath, Cameras));
return group;
}
int main(int argc, char** argv)
{
// use an ArgumentParser object to manage the program arguments.
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 using of GL_ARB_shadow extension implemented in osg::Texture class");
arguments.getApplicationUsage()->setCommandLineUsage(arguments.getApplicationName());
arguments.getApplicationUsage()->addCommandLineOption("-h or --help", "Display this information");
arguments.getApplicationUsage()->addCommandLineOption("--fbo","Use Frame Buffer Object for render to texture, where supported.");
arguments.getApplicationUsage()->addCommandLineOption("--fb","Use FrameBuffer for render to texture.");
arguments.getApplicationUsage()->addCommandLineOption("--pbuffer","Use Pixel Buffer for render to texture, where supported.");
arguments.getApplicationUsage()->addCommandLineOption("--window","Use a seperate Window for render to texture.");
arguments.getApplicationUsage()->addCommandLineOption("--width","Set the width of the render to texture");
arguments.getApplicationUsage()->addCommandLineOption("--height","Set the height of the render to texture");
// construct the viewer.
osgViewer::Viewer viewer;
// if user request help write it out to cout.
if (arguments.read("-h") || arguments.read("--help"))
{
arguments.getApplicationUsage()->write(std::cout);
return 1;
}
unsigned tex_width = 256;
unsigned tex_height = 256;
while (arguments.read("--width", tex_width)) {}
while (arguments.read("--height", tex_height)) {}
osg::Camera::RenderTargetImplementation renderImplementation = osg::Camera::FRAME_BUFFER_OBJECT;
while (arguments.read("--fbo")) { renderImplementation = osg::Camera::FRAME_BUFFER_OBJECT; }
while (arguments.read("--pbuffer")) { renderImplementation = osg::Camera::PIXEL_BUFFER; }
while (arguments.read("--fb")) { renderImplementation = osg::Camera::FRAME_BUFFER; }
while (arguments.read("--window")) { renderImplementation = osg::Camera::SEPERATE_WINDOW; }
// 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;
}
ref_ptr<MatrixTransform> scene = new MatrixTransform;
scene->setMatrix(osg::Matrix::rotate(osg::DegreesToRadians(125.0),1.0,0.0,0.0));
ref_ptr<Group> reflectedSubgraph = _create_scene();
if (!reflectedSubgraph.valid()) return 1;
ref_ptr<Group> reflectedScene = createShadowedScene(reflectedSubgraph.get(), createReflector(), 0, viewer.getCamera()->getClearColor(),
tex_width, tex_height, renderImplementation);
scene->addChild(reflectedScene.get());
viewer.setSceneData(scene.get());
return viewer.run();
}
<|endoftext|> |
<commit_before>/*
* The MIT License (MIT)
*
* Copyright (c) 2015 Alisa Dolinsky
*
* 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.
*/
#pragma once
#define _PROJECT_API_ID_ EMBEDTCL_API
#define _TCL_DLL_FNAME_ "tcl86t.dll"
#include "api.hpp"
#include "tupleUtils.hpp"
template <typename TupleSpecialization, int len, Tcl_Obj* objects[len], typename Last> static void fromTuple(TupleSpecialization& tup) {
}
template <typename TupleSpecialization, int len, Tcl_Obj* objects[len], typename First, typename Second, typename ...Rest> static void fromTuple(TupleSpecialization& tup) {
//arr[sizeof...(Rest)] = sizeof...(Rest);
std::get<0>(tup);
}
template <typename T>
struct WrapperContainer {
T* self;
FString name;
};
class _PROJECT_API_ID_ TclWrapper
{
protected:
TclWrapper(bool, uint32);
static void* handle;
static size_t interpreterSize;
static const char* __id__;
Tcl_Interp* interpreter;
int registerId(uint32);
template <typename T> static int convert(Tcl_Interp*, Tcl_Obj*, T*);
template <> static int convert<int>(Tcl_Interp*, Tcl_Obj*, int*);
template <> static int convert<long>(Tcl_Interp*, Tcl_Obj*, long*);
template <> static int convert<double>(Tcl_Interp*, Tcl_Obj*, double*);
static _Tcl_CreateInterpProto _Tcl_CreateInterp;
static _Tcl_EvalProto _Tcl_Eval;
static _Tcl_CreateObjCommandProto _Tcl_CreateObjCommand;
static _Tcl_ObjSetVar2Proto _Tcl_ObjSetVar2;
static _Tcl_ObjGetVar2Proto _Tcl_ObjGetVar2;
static _Tcl_SetStringObjProto _Tcl_SetStringObj;
static _Tcl_NewStringObjProto _Tcl_NewStringObj;
static _Tcl_NewLongObjProto _Tcl_NewLongObj;
static _Tcl_SetIntObjProto _Tcl_SetIntObj;
static _Tcl_GetObjResultProto _Tcl_GetObjResult;
static _Tcl_GetIntFromObjProto _Tcl_GetIntFromObj;
static _Tcl_GetLongFromObjProto _Tcl_GetLongFromObj;
static _Tcl_GetDoubleFromObjProto _Tcl_GetDoubleFromObj;
public:
static TSharedRef<TclWrapper> bootstrap(uint32);
bool bootstrapSuccess();
int eval(const char*);
int registerFunction(const char*, Tcl_ObjCmdProc*, ClientData, Tcl_CmdDeleteProc*);
int define(Tcl_Obj*, Tcl_Obj*, Tcl_Obj*, int);
int fetch(Tcl_Obj*, Tcl_Obj*, Tcl_Obj**, int);
static int id(Tcl_Interp*, uint32*);
static uint32 id(Tcl_Interp*);
int id(uint32*);
uint32 id();
static int newString(Tcl_Obj**, const char*);
static int newLong(Tcl_Obj**, long);
static int setString(Tcl_Obj*, const char*, int);
static int setInt(Tcl_Obj*, int);
static int getResult(Tcl_Interp*, Tcl_Obj**);
static int toInt(Tcl_Interp*, Tcl_Obj*, int*);
int toInt(Tcl_Obj*, int*);
static int toLong(Tcl_Interp*, Tcl_Obj*, long*);
int toLong(Tcl_Obj*, long*);
static int toDouble(Tcl_Interp*, Tcl_Obj*, double*);
~TclWrapper();
template<typename Cls, typename ReturnType, typename ...ParamTypes> int TclWrapper::bind(Cls* self, FString name) {
if (handle == nullptr || interpreter == nullptr) { return _TCL_BOOTSTRAP_FAIL_; } else {
auto wrapper = [](ClientData clientData, Tcl_Interp* interpreter, int numberOfArgs, Tcl_Obj* const arguments[]) -> int {
const int numberOfParams = sizeof...(ParamTypes);
numberOfArgs--; // proc is counted too
if (numberOfArgs != numberOfParams) {
UE_LOG(LogClass, Log, TEXT("Tcl: number of arguments -> %d isn't equal to the number of parameters %d"), numberOfArgs, numberOfParams)
return TCL_ERROR;
}
Tcl_Obj* objects[numberOfParams];
for(int i=0; i<numberOfParams; i++) { objects[i] = const_cast<Tcl_Obj*>(arguments[i]); }
tuple<Cls*, FString, ParamTypes...> values;
auto data = (WrapperContainer<Cls>*)clientData;
get<0>(values) = data->self;
get<1>(values) = data->name;
auto delegateWrapper = [](Cls* self, FString name, ParamTypes... args) -> bool {
TBaseDelegate<ReturnType, ParamTypes...> del;
del.BindUFunction(self, TCHAR_TO_ANSI(*name));
//return del.ExecuteIfBound(args...);
return del.ExecuteIfBound("hello!");
};
typedef bool(*DelegateWrapperFptr)(Cls* self, FString name, ParamTypes...);
apply((DelegateWrapperFptr)delegateWrapper, values);
delete data;
data = nullptr;
return TCL_OK;
};
const char* fname = TCHAR_TO_ANSI(*name);
auto data = new WrapperContainer<Cls>({ self, name });
_Tcl_CreateObjCommand(interpreter, fname, wrapper, (ClientData)data, (Tcl_CmdDeleteProc*)nullptr);
data = nullptr;
return TCL_OK;
}
}
};
<commit_msg>Templates again...<commit_after>/*
* The MIT License (MIT)
*
* Copyright (c) 2015 Alisa Dolinsky
*
* 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.
*/
#pragma once
#define _PROJECT_API_ID_ EMBEDTCL_API
#define _TCL_DLL_FNAME_ "tcl86t.dll"
#include "api.hpp"
#include "tupleUtils.hpp"
template <int> struct POPULATE;
template <typename T>
struct WrapperContainer {
T* self;
FString name;
};
class _PROJECT_API_ID_ TclWrapper
{
protected:
TclWrapper(bool, uint32);
static void* handle;
static size_t interpreterSize;
static const char* __id__;
Tcl_Interp* interpreter;
int registerId(uint32);
template <typename T> static int convert(Tcl_Interp*, Tcl_Obj*, T*);
template <> static int convert<int>(Tcl_Interp*, Tcl_Obj*, int*);
template <> static int convert<long>(Tcl_Interp*, Tcl_Obj*, long*);
template <> static int convert<double>(Tcl_Interp*, Tcl_Obj*, double*);
static _Tcl_CreateInterpProto _Tcl_CreateInterp;
static _Tcl_EvalProto _Tcl_Eval;
static _Tcl_CreateObjCommandProto _Tcl_CreateObjCommand;
static _Tcl_ObjSetVar2Proto _Tcl_ObjSetVar2;
static _Tcl_ObjGetVar2Proto _Tcl_ObjGetVar2;
static _Tcl_SetStringObjProto _Tcl_SetStringObj;
static _Tcl_NewStringObjProto _Tcl_NewStringObj;
static _Tcl_NewLongObjProto _Tcl_NewLongObj;
static _Tcl_SetIntObjProto _Tcl_SetIntObj;
static _Tcl_GetObjResultProto _Tcl_GetObjResult;
static _Tcl_GetIntFromObjProto _Tcl_GetIntFromObj;
static _Tcl_GetLongFromObjProto _Tcl_GetLongFromObj;
static _Tcl_GetDoubleFromObjProto _Tcl_GetDoubleFromObj;
public:
static TSharedRef<TclWrapper> bootstrap(uint32);
bool bootstrapSuccess();
int eval(const char*);
int registerFunction(const char*, Tcl_ObjCmdProc*, ClientData, Tcl_CmdDeleteProc*);
int define(Tcl_Obj*, Tcl_Obj*, Tcl_Obj*, int);
int fetch(Tcl_Obj*, Tcl_Obj*, Tcl_Obj**, int);
static int id(Tcl_Interp*, uint32*);
static uint32 id(Tcl_Interp*);
int id(uint32*);
uint32 id();
static int newString(Tcl_Obj**, const char*);
static int newLong(Tcl_Obj**, long);
static int setString(Tcl_Obj*, const char*, int);
static int setInt(Tcl_Obj*, int);
static int getResult(Tcl_Interp*, Tcl_Obj**);
static int toInt(Tcl_Interp*, Tcl_Obj*, int*);
int toInt(Tcl_Obj*, int*);
static int toLong(Tcl_Interp*, Tcl_Obj*, long*);
int toLong(Tcl_Obj*, long*);
static int toDouble(Tcl_Interp*, Tcl_Obj*, double*);
~TclWrapper();
template<typename Cls, typename ReturnType, typename ...ParamTypes> int TclWrapper::bind(Cls* self, FString name) {
if (handle == nullptr || interpreter == nullptr) { return _TCL_BOOTSTRAP_FAIL_; } else {
auto wrapper = [](ClientData clientData, Tcl_Interp* interpreter, int numberOfArgs, Tcl_Obj* const arguments[]) -> int {
const int numberOfParams = sizeof...(ParamTypes);
numberOfArgs--; // proc is counted too
if (numberOfArgs != numberOfParams) {
UE_LOG(LogClass, Log, TEXT("Tcl: number of arguments -> %d isn't equal to the number of parameters %d"), numberOfArgs, numberOfParams)
return TCL_ERROR;
}
Tcl_Obj* objects[numberOfParams];
for(int i=0; i<numberOfParams; i++) { objects[i] = const_cast<Tcl_Obj*>(arguments[i]); }
tuple<Cls*, FString, ParamTypes...> values;
if (numberOfParams > 0) {
POPULATE<numberOfParams>::FROM(interpreter, values, objects);
}
auto data = (WrapperContainer<Cls>*)clientData;
get<0>(values) = data->self;
get<1>(values) = data->name;
auto delegateWrapper = [](Cls* self, FString name, ParamTypes... args) -> bool {
TBaseDelegate<ReturnType, ParamTypes...> del;
del.BindUFunction(self, TCHAR_TO_ANSI(*name));
//return del.ExecuteIfBound(args...);
return del.ExecuteIfBound("hello!");
};
typedef bool(*DelegateWrapperFptr)(Cls* self, FString name, ParamTypes...);
apply((DelegateWrapperFptr)delegateWrapper, values);
// delete in callback
//delete data;
//data = nullptr;
return TCL_OK;
};
const char* fname = TCHAR_TO_ANSI(*name);
auto data = new WrapperContainer<Cls>({ self, name });
_Tcl_CreateObjCommand(interpreter, fname, wrapper, (ClientData)data, (Tcl_CmdDeleteProc*)nullptr);
data = nullptr;
return TCL_OK;
}
}
};
#define CUTOFF 2
template <int idx>
struct POPULATE {
template <typename TupleSpecialization, typename ...ParamTypes> static void FROM(Tcl_Interp* interpreter, TupleSpecialization& values, Tcl_Obj* objects[]) {
const auto ElementType = tuple_element<idx, decltype(values)>::type;
ElementType element = get<idx>(values);
TclWrapper::convert<ElementType>(interpreter, objects[idx-CUTOFF], &element);
POPULATE<n - 1>::FROM<TupleSpecialization, ParamTypes...>(interpreter, values, objects);
}
};
// base case
template <> struct POPULATE<CUTOFF - 1> {
template <typename TupleSpecialization, typename ...ParamTypes> static void FROM(Tcl_Interp* interpreter, TupleSpecialization& values, Tcl_Obj* objects[]) {}
};<|endoftext|> |
<commit_before>// Copyright (c) 2013, German Neuroinformatics Node (G-Node)
//
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted under the terms of the BSD License. See
// LICENSE file in the root of the Project.
#include "H5DataType.hpp"
#include <memory>
namespace nix {
namespace hdf5 {
namespace h5x {
DataType DataType::copy(hid_t source) {
DataType hi_copy = H5Tcopy(source);
hi_copy.check("Could not copy type");
return hi_copy;
}
DataType DataType::make(H5T_class_t klass, size_t size) {
DataType dt = H5Tcreate(klass, size);
dt.check("Could not create datatype");
return dt;
}
DataType DataType::makeStrType(size_t size) {
DataType str_type = H5Tcopy(H5T_C_S1);
str_type.check("Could not create string type");
str_type.size(size);
return str_type;
}
DataType DataType::makeCompound(size_t size) {
DataType res = H5Tcreate(H5T_COMPOUND, size);
res.check("Could not create compound type");
return res;
}
DataType DataType::makeEnum(const DataType &base) {
DataType res = H5Tenum_create(base.h5id());
res.check("Could not create enum type");
return res;
}
H5T_class_t DataType::class_t() const {
return H5Tget_class(hid);
}
void DataType::size(size_t t) {
HErr res = H5Tset_size(hid, t);
res.check("DataType::size: Could not set size");
}
size_t DataType::size() const {
return H5Tget_size(hid); //FIXME: throw on 0?
}
void DataType::sign(H5T_sign_t sign) {
HErr res = H5Tset_sign(hid, sign);
res.check("DataType::sign(): H5Tset_sign failed");
}
H5T_sign_t DataType::sign() const {
H5T_sign_t res = H5Tget_sign(hid);
return res;
}
bool DataType::isVariableString() const {
HTri res = H5Tis_variable_str(hid);
res.check("DataType::isVariableString(): H5Tis_variable_str failed");
return res.result();
}
bool DataType::isCompound() const {
return class_t() == H5T_COMPOUND;
}
unsigned int DataType::member_count() const {
int res = H5Tget_nmembers(hid);
if (res < 0) {
throw H5Exception("DataType::member_count(): H5Tget_nmembers faild");
}
return static_cast<unsigned int>(res);
}
H5T_class_t DataType::member_class(unsigned int index) const {
return H5Tget_member_class(hid, index);
}
std::string DataType::member_name(unsigned int index) const {
char *data = H5Tget_member_name(hid, index);
std::string res(data);
std::free(data);
return res;
}
std::vector<std::string> DataType::member_names() const {
unsigned int c = member_count();
std::vector<std::string> names;
for (unsigned int i = 0; i < c; i++) {
names.emplace_back(member_name(i));
}
return names;
}
size_t DataType::member_offset(unsigned int index) const {
return H5Tget_member_offset(hid, index);
}
DataType DataType::member_type(unsigned int index) const {
h5x::DataType res = H5Tget_member_type(hid, index);
res.check("DataType::member_type(): H5Tget_member_type failed");
return res;
}
void DataType::insert(const std::string &name, size_t offset, const DataType &dtype) {
HErr res = H5Tinsert(hid, name.c_str(), offset, dtype.hid);
res.check("DataType::insert(): H5Tinsert failed.");
}
void DataType::insert(const std::string &name, void *value) {
HErr res = H5Tenum_insert(hid, name.c_str(), value);
res.check("DataType::insert(): H5Tenum_insert failed.");
}
void DataType::enum_valueof(const std::string &name, void *value) {
HErr res = H5Tenum_valueof(hid, name.c_str(), value);
res.check("DataType::enum_valueof(): H5Tenum_valueof failed");
}
bool DataType::enum_equal(const DataType &other) const {
if (class_t() != H5T_ENUM || other.class_t() != H5T_ENUM) {
return false;
}
std::vector<std::string> a_names = this->member_names();
std::vector<std::string> b_names = other.member_names();
if (a_names.size() != b_names.size()) {
return false;
}
std::sort(std::begin(a_names), std::end(a_names));
std::sort(std::begin(b_names), std::end(b_names));
return std::equal(std::begin(a_names),
std::end(a_names),
std::begin(b_names));
}
} // h5x
static herr_t bitfield2bool(hid_t src_id, hid_t dst_id, H5T_cdata_t *cdata,
size_t nl, size_t buf_stride, size_t bkg_stride, void *buf_i,
void *bkg_i, hid_t dxpl) {
return 0;
}
h5x::DataType make_file_booltype() {
h5x::DataType booltype = h5x::DataType::makeEnum(H5T_NATIVE_INT8);
booltype.insert("FALSE", 0UL);
booltype.insert("TRUE", 1UL);
return booltype;
}
h5x::DataType make_mem_booltype() {
h5x::DataType booltype = h5x::DataType::make(H5T_ENUM, sizeof(bool));
booltype.insert("FALSE", false);
booltype.insert("TRUE", true);
// Register converter for old-style boolean (bitfield)
H5Tregister(H5T_PERS_SOFT, "bitfield2bool", H5T_STD_B8LE, booltype.h5id(), bitfield2bool);
return booltype;
}
static const h5x::DataType boolfiletype = make_file_booltype();
static const h5x::DataType boolmemtype = make_mem_booltype();
h5x::DataType data_type_to_h5_filetype(DataType dtype) {
/* The switch is structured in a way in order to get
warnings from the compiler when not all cases are
handled and throw an exception if one of the not
handled cases actually appears (i.e., we have no
default case, because that silences the compiler.)
*/
switch (dtype) {
case DataType::Bool: return boolfiletype;
case DataType::Int8: return h5x::DataType::copy(H5T_STD_I8LE);
case DataType::Int16: return h5x::DataType::copy(H5T_STD_I16LE);
case DataType::Int32: return h5x::DataType::copy(H5T_STD_I32LE);
case DataType::Int64: return h5x::DataType::copy(H5T_STD_I64LE);
case DataType::UInt8: return h5x::DataType::copy(H5T_STD_U8LE);
case DataType::UInt16: return h5x::DataType::copy(H5T_STD_U16LE);
case DataType::UInt32: return h5x::DataType::copy(H5T_STD_U32LE);
case DataType::UInt64: return h5x::DataType::copy(H5T_STD_U64LE);
case DataType::Float: return h5x::DataType::copy(H5T_IEEE_F32LE);
case DataType::Double: return h5x::DataType::copy(H5T_IEEE_F64LE);
case DataType::String: return h5x::DataType::makeStrType();
//shall we create our own OPAQUE type?
case DataType::Opaque: return h5x::DataType::copy(H5T_NATIVE_OPAQUE);
case DataType::Char: break; //FIXME
case DataType::Nothing: break;
}
throw std::invalid_argument("Unkown DataType"); //FIXME
}
h5x::DataType data_type_to_h5_memtype(DataType dtype) {
// See data_type_to_h5_filetype for the reason why the switch is structured
// in the way it is.
switch(dtype) {
case DataType::Bool: return boolmemtype;
case DataType::Int8: return h5x::DataType::copy(H5T_NATIVE_INT8);
case DataType::Int16: return h5x::DataType::copy(H5T_NATIVE_INT16);
case DataType::Int32: return h5x::DataType::copy(H5T_NATIVE_INT32);
case DataType::Int64: return h5x::DataType::copy(H5T_NATIVE_INT64);
case DataType::UInt8: return h5x::DataType::copy(H5T_NATIVE_UINT8);
case DataType::UInt16: return h5x::DataType::copy(H5T_NATIVE_UINT16);
case DataType::UInt32: return h5x::DataType::copy(H5T_NATIVE_UINT32);
case DataType::UInt64: return h5x::DataType::copy(H5T_NATIVE_UINT64);
case DataType::Float: return h5x::DataType::copy(H5T_NATIVE_FLOAT);
case DataType::Double: return h5x::DataType::copy(H5T_NATIVE_DOUBLE);
case DataType::String: return h5x::DataType::makeStrType();
case DataType::Opaque: return h5x::DataType::copy(H5T_NATIVE_OPAQUE);
case DataType::Char: break; //FIXME
case DataType::Nothing: break;
}
throw std::invalid_argument("DataType not handled!"); //FIXME
}
h5x::DataType data_type_to_h5(DataType dtype, bool for_memory) {
if (for_memory) {
return data_type_to_h5_memtype(dtype);
} else {
return data_type_to_h5_filetype(dtype);
}
}
#define NOT_IMPLEMENTED false
DataType
data_type_from_h5(H5T_class_t vclass, size_t vsize, H5T_sign_t vsign)
{
if (vclass == H5T_INTEGER) {
switch (vsize) {
case 1: return vsign == H5T_SGN_2 ? DataType::Int8 : DataType::UInt8;
case 2: return vsign == H5T_SGN_2 ? DataType::Int16 : DataType::UInt16;
case 4: return vsign == H5T_SGN_2 ? DataType::Int32 : DataType::UInt32;
case 8: return vsign == H5T_SGN_2 ? DataType::Int64 : DataType::UInt64;
}
} else if (vclass == H5T_FLOAT) {
return vsize == 8 ? DataType::Double : DataType::Float;
} else if (vclass == H5T_STRING) {
return DataType::String;
} else if (vclass == H5T_BITFIELD) {
switch (vsize) {
case 1: return DataType::Bool;
}
} else if (vclass == H5T_ENUM) {
switch (vsize) {
case 1: return DataType::Bool;
}
}
std::cerr << "FIXME: Not implemented " << vclass << " " << vsize << " " << vsign << " " << std::endl;
assert(NOT_IMPLEMENTED);
return DataType::Nothing;
}
DataType data_type_from_h5(const h5x::DataType &dtype) {
H5T_class_t ftclass = dtype.class_t();
size_t size;
H5T_sign_t sign;
if (ftclass == H5T_COMPOUND) {
//if it is a compound data type then it must be a
//a property dataset, we can handle that
int nmems = dtype.member_count();
assert(nmems == 6);
h5x::DataType vtype = dtype.member_type(0);
ftclass = vtype.class_t();
size = vtype.size();
sign = vtype.sign();
if (ftclass == H5T_ENUM) {
if (!boolfiletype.enum_equal(vtype)) {
return DataType::Nothing;
}
return DataType::Bool;
}
} else if (ftclass == H5T_ENUM) {
if (!boolfiletype.enum_equal(dtype)) {
return DataType::Nothing;
}
return DataType::Bool;
} else if (ftclass == H5T_OPAQUE) {
return DataType::Opaque;
} else {
size = dtype.size();
sign = dtype.sign();
}
return data_type_from_h5(ftclass, size, sign);
}
} // namespace hdf5
} // namespace nix
<commit_msg>[h5x] cleanup bitfield2bool converter<commit_after>// Copyright (c) 2013, German Neuroinformatics Node (G-Node)
//
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted under the terms of the BSD License. See
// LICENSE file in the root of the Project.
#include "H5DataType.hpp"
#include <memory>
#include <cstring>
namespace nix {
namespace hdf5 {
namespace h5x {
DataType DataType::copy(hid_t source) {
DataType hi_copy = H5Tcopy(source);
hi_copy.check("Could not copy type");
return hi_copy;
}
DataType DataType::make(H5T_class_t klass, size_t size) {
DataType dt = H5Tcreate(klass, size);
dt.check("Could not create datatype");
return dt;
}
DataType DataType::makeStrType(size_t size) {
DataType str_type = H5Tcopy(H5T_C_S1);
str_type.check("Could not create string type");
str_type.size(size);
return str_type;
}
DataType DataType::makeCompound(size_t size) {
DataType res = H5Tcreate(H5T_COMPOUND, size);
res.check("Could not create compound type");
return res;
}
DataType DataType::makeEnum(const DataType &base) {
DataType res = H5Tenum_create(base.h5id());
res.check("Could not create enum type");
return res;
}
H5T_class_t DataType::class_t() const {
return H5Tget_class(hid);
}
void DataType::size(size_t t) {
HErr res = H5Tset_size(hid, t);
res.check("DataType::size: Could not set size");
}
size_t DataType::size() const {
return H5Tget_size(hid); //FIXME: throw on 0?
}
void DataType::sign(H5T_sign_t sign) {
HErr res = H5Tset_sign(hid, sign);
res.check("DataType::sign(): H5Tset_sign failed");
}
H5T_sign_t DataType::sign() const {
H5T_sign_t res = H5Tget_sign(hid);
return res;
}
bool DataType::isVariableString() const {
HTri res = H5Tis_variable_str(hid);
res.check("DataType::isVariableString(): H5Tis_variable_str failed");
return res.result();
}
bool DataType::isCompound() const {
return class_t() == H5T_COMPOUND;
}
unsigned int DataType::member_count() const {
int res = H5Tget_nmembers(hid);
if (res < 0) {
throw H5Exception("DataType::member_count(): H5Tget_nmembers faild");
}
return static_cast<unsigned int>(res);
}
H5T_class_t DataType::member_class(unsigned int index) const {
return H5Tget_member_class(hid, index);
}
std::string DataType::member_name(unsigned int index) const {
char *data = H5Tget_member_name(hid, index);
std::string res(data);
std::free(data);
return res;
}
std::vector<std::string> DataType::member_names() const {
unsigned int c = member_count();
std::vector<std::string> names;
for (unsigned int i = 0; i < c; i++) {
names.emplace_back(member_name(i));
}
return names;
}
size_t DataType::member_offset(unsigned int index) const {
return H5Tget_member_offset(hid, index);
}
DataType DataType::member_type(unsigned int index) const {
h5x::DataType res = H5Tget_member_type(hid, index);
res.check("DataType::member_type(): H5Tget_member_type failed");
return res;
}
void DataType::insert(const std::string &name, size_t offset, const DataType &dtype) {
HErr res = H5Tinsert(hid, name.c_str(), offset, dtype.hid);
res.check("DataType::insert(): H5Tinsert failed.");
}
void DataType::insert(const std::string &name, void *value) {
HErr res = H5Tenum_insert(hid, name.c_str(), value);
res.check("DataType::insert(): H5Tenum_insert failed.");
}
void DataType::enum_valueof(const std::string &name, void *value) {
HErr res = H5Tenum_valueof(hid, name.c_str(), value);
res.check("DataType::enum_valueof(): H5Tenum_valueof failed");
}
bool DataType::enum_equal(const DataType &other) const {
if (class_t() != H5T_ENUM || other.class_t() != H5T_ENUM) {
return false;
}
std::vector<std::string> a_names = this->member_names();
std::vector<std::string> b_names = other.member_names();
if (a_names.size() != b_names.size()) {
return false;
}
std::sort(std::begin(a_names), std::end(a_names));
std::sort(std::begin(b_names), std::end(b_names));
return std::equal(std::begin(a_names),
std::end(a_names),
std::begin(b_names));
}
} // h5x
static herr_t bitfield2bool(hid_t src_id,
hid_t dst_id,
H5T_cdata_t *cdata,
size_t nl, size_t buf_stride, size_t bkg_stride,
void *buf_i,
void *bkg_i, hid_t dxpl);
h5x::DataType make_file_booltype() {
h5x::DataType booltype = h5x::DataType::makeEnum(H5T_NATIVE_INT8);
booltype.insert("FALSE", 0UL);
booltype.insert("TRUE", 1UL);
return booltype;
}
h5x::DataType make_mem_booltype() {
h5x::DataType booltype = h5x::DataType::make(H5T_ENUM, sizeof(bool));
booltype.insert("FALSE", false);
booltype.insert("TRUE", true);
// Register converter for old-style boolean (bitfield)
H5Tregister(H5T_PERS_SOFT, "bitfield2bool", H5T_STD_B8LE, booltype.h5id(), bitfield2bool);
return booltype;
}
static const h5x::DataType boolfiletype = make_file_booltype();
static const h5x::DataType boolmemtype = make_mem_booltype();
static herr_t bitfield2bool(hid_t src_id,
hid_t dst_id,
H5T_cdata_t *cdata,
size_t nl,
size_t buf_stride,
size_t bkg_stride,
void *buf_i,
void *bkg_i,
hid_t dxpl) {
// document for what this function should to at:
// https://support.hdfgroup.org/HDF5/doc/H5.user/Datatypes.html#Datatypes-DataConversion
switch (cdata->command) {
case H5T_CONV_INIT: {
cdata->need_bkg = H5T_BKG_NO;
HTri s_eq = H5Tequal(src_id, H5T_STD_B8LE);
HTri d_eq = H5Tequal(dst_id, boolmemtype.h5id());
if (s_eq.isError() || d_eq.isError() ||
!(s_eq.result() && d_eq.result())) {
return -1;
}
return 0;
}
case H5T_CONV_FREE:
return 0; //Nothing to do
case H5T_CONV_CONV:
break;
}
if (nl != 1) {
//we don't support more then 1 element
//since this should never occur in NIX
return -1;
}
//alias via char is fine
char *buf = static_cast<char *>(buf_i);
bool val = buf[0] != 0; // any nonzero value is true
memcpy(buf, &val, sizeof(bool));
return 0;
}
h5x::DataType data_type_to_h5_filetype(DataType dtype) {
/* The switch is structured in a way in order to get
warnings from the compiler when not all cases are
handled and throw an exception if one of the not
handled cases actually appears (i.e., we have no
default case, because that silences the compiler.)
*/
switch (dtype) {
case DataType::Bool: return boolfiletype;
case DataType::Int8: return h5x::DataType::copy(H5T_STD_I8LE);
case DataType::Int16: return h5x::DataType::copy(H5T_STD_I16LE);
case DataType::Int32: return h5x::DataType::copy(H5T_STD_I32LE);
case DataType::Int64: return h5x::DataType::copy(H5T_STD_I64LE);
case DataType::UInt8: return h5x::DataType::copy(H5T_STD_U8LE);
case DataType::UInt16: return h5x::DataType::copy(H5T_STD_U16LE);
case DataType::UInt32: return h5x::DataType::copy(H5T_STD_U32LE);
case DataType::UInt64: return h5x::DataType::copy(H5T_STD_U64LE);
case DataType::Float: return h5x::DataType::copy(H5T_IEEE_F32LE);
case DataType::Double: return h5x::DataType::copy(H5T_IEEE_F64LE);
case DataType::String: return h5x::DataType::makeStrType();
//shall we create our own OPAQUE type?
case DataType::Opaque: return h5x::DataType::copy(H5T_NATIVE_OPAQUE);
case DataType::Char: break; //FIXME
case DataType::Nothing: break;
}
throw std::invalid_argument("Unkown DataType"); //FIXME
}
h5x::DataType data_type_to_h5_memtype(DataType dtype) {
// See data_type_to_h5_filetype for the reason why the switch is structured
// in the way it is.
switch(dtype) {
case DataType::Bool: return boolmemtype;
case DataType::Int8: return h5x::DataType::copy(H5T_NATIVE_INT8);
case DataType::Int16: return h5x::DataType::copy(H5T_NATIVE_INT16);
case DataType::Int32: return h5x::DataType::copy(H5T_NATIVE_INT32);
case DataType::Int64: return h5x::DataType::copy(H5T_NATIVE_INT64);
case DataType::UInt8: return h5x::DataType::copy(H5T_NATIVE_UINT8);
case DataType::UInt16: return h5x::DataType::copy(H5T_NATIVE_UINT16);
case DataType::UInt32: return h5x::DataType::copy(H5T_NATIVE_UINT32);
case DataType::UInt64: return h5x::DataType::copy(H5T_NATIVE_UINT64);
case DataType::Float: return h5x::DataType::copy(H5T_NATIVE_FLOAT);
case DataType::Double: return h5x::DataType::copy(H5T_NATIVE_DOUBLE);
case DataType::String: return h5x::DataType::makeStrType();
case DataType::Opaque: return h5x::DataType::copy(H5T_NATIVE_OPAQUE);
case DataType::Char: break; //FIXME
case DataType::Nothing: break;
}
throw std::invalid_argument("DataType not handled!"); //FIXME
}
h5x::DataType data_type_to_h5(DataType dtype, bool for_memory) {
if (for_memory) {
return data_type_to_h5_memtype(dtype);
} else {
return data_type_to_h5_filetype(dtype);
}
}
#define NOT_IMPLEMENTED false
DataType
data_type_from_h5(H5T_class_t vclass, size_t vsize, H5T_sign_t vsign)
{
if (vclass == H5T_INTEGER) {
switch (vsize) {
case 1: return vsign == H5T_SGN_2 ? DataType::Int8 : DataType::UInt8;
case 2: return vsign == H5T_SGN_2 ? DataType::Int16 : DataType::UInt16;
case 4: return vsign == H5T_SGN_2 ? DataType::Int32 : DataType::UInt32;
case 8: return vsign == H5T_SGN_2 ? DataType::Int64 : DataType::UInt64;
}
} else if (vclass == H5T_FLOAT) {
return vsize == 8 ? DataType::Double : DataType::Float;
} else if (vclass == H5T_STRING) {
return DataType::String;
} else if (vclass == H5T_BITFIELD) {
switch (vsize) {
case 1: return DataType::Bool;
}
} else if (vclass == H5T_ENUM) {
switch (vsize) {
case 1: return DataType::Bool;
}
}
std::cerr << "FIXME: Not implemented " << vclass << " " << vsize << " " << vsign << " " << std::endl;
assert(NOT_IMPLEMENTED);
return DataType::Nothing;
}
DataType data_type_from_h5(const h5x::DataType &dtype) {
H5T_class_t ftclass = dtype.class_t();
size_t size;
H5T_sign_t sign;
if (ftclass == H5T_COMPOUND) {
//if it is a compound data type then it must be a
//a property dataset, we can handle that
int nmems = dtype.member_count();
assert(nmems == 6);
h5x::DataType vtype = dtype.member_type(0);
ftclass = vtype.class_t();
size = vtype.size();
sign = vtype.sign();
if (ftclass == H5T_ENUM) {
if (!boolfiletype.enum_equal(vtype)) {
return DataType::Nothing;
}
return DataType::Bool;
}
} else if (ftclass == H5T_ENUM) {
if (!boolfiletype.enum_equal(dtype)) {
return DataType::Nothing;
}
return DataType::Bool;
} else if (ftclass == H5T_OPAQUE) {
return DataType::Opaque;
} else {
size = dtype.size();
sign = dtype.sign();
}
return data_type_from_h5(ftclass, size, sign);
}
} // namespace hdf5
} // namespace nix
<|endoftext|> |
<commit_before>/**
Copyright 2016 Udey Rishi
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
#pragma once
#include <stdexcept>
#include <string>
#include <vector>
#include <core/BooleanFunction.hpp>
#include <core/TruthTable.hpp>
using namespace std;
namespace Logic {
static const string NOT_REGEX("[!]");
static const string AND_REGEX("[&]");
static const string OR_REGEX("[\\|]");
static const string XOR_REGEX("[\\^]");
static const string EQUALS_REGEX("[=]{2}");
static const string INDEX_REGEX("[\\[]{1}([\\d]+)[\\]]{1}");
static const vector<string> OPERATOR_REGEXES({
NOT_REGEX,
AND_REGEX,
OR_REGEX,
XOR_REGEX,
EQUALS_REGEX,
INDEX_REGEX });
class UnaryOperator {
public:
virtual BooleanFunction operator()(const BooleanFunction &in) const = 0;
virtual ~UnaryOperator() {
}
};
class BinaryOperator {
public:
virtual BooleanFunction operator()(const BooleanFunction &first, const BooleanFunction &second) const = 0;
virtual ~BinaryOperator() {
}
};
class Index : public UnaryOperator {
public:
Index(const TruthTableUInt index) : index(index) {
}
virtual BooleanFunction operator()(const BooleanFunction &in) const;
private:
const TruthTableUInt index;
};
class BoolTransformationUnaryOperator : public UnaryOperator {
public:
virtual BooleanFunction operator()(const BooleanFunction &in) const;
private:
virtual bool operate(const bool in) const = 0;
};
class Not : public BoolTransformationUnaryOperator {
private:
virtual bool operate(const bool in) const {
return !in;
}
};
class Equals : public BinaryOperator {
public:
virtual BooleanFunction operator()(const BooleanFunction &first, const BooleanFunction &second) const {
return first == second;
}
};
class CombinatoryBinaryOperator : public BinaryOperator {
public:
virtual BooleanFunction operator()(const BooleanFunction &first, const BooleanFunction &second) const;
private:
TruthTable combineColumnsWithSameVariables(const TruthTableBuilder &rawBuilder) const;
TruthTableBuilder combineTables(const BooleanFunction &first, const BooleanFunction &second) const;
virtual bool operate(const bool first, const bool second) const = 0;
};
class Or : public CombinatoryBinaryOperator {
private:
virtual bool operate(const bool first, const bool second) const {
return first || second;
}
};
class And : public CombinatoryBinaryOperator {
private:
virtual bool operate(const bool first, const bool second) const {
return first && second;
}
};
class Xor : public CombinatoryBinaryOperator {
private:
virtual bool operate(const bool first, const bool second) const {
return first != second;
}
};
bool isKnownPrefixUnaryOperator(const string &_operator);
bool isKnownSuffixUnaryOperator(const string &_operator);
bool isKnownUnaryOperator(const string &_operator);
bool isKnownBinaryOperator(const string &_operator);
UnaryOperator *createUnaryOperatorWithSymbol(const string &_operator);
BinaryOperator *createBinaryOperatorWithSymbol(const string &_operator);
}
<commit_msg>You can now put spaces in the index brackets<commit_after>/**
Copyright 2016 Udey Rishi
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
#pragma once
#include <stdexcept>
#include <string>
#include <vector>
#include <core/BooleanFunction.hpp>
#include <core/TruthTable.hpp>
using namespace std;
namespace Logic {
static const string NOT_REGEX("[!]");
static const string AND_REGEX("[&]");
static const string OR_REGEX("[\\|]");
static const string XOR_REGEX("[\\^]");
static const string EQUALS_REGEX("[=]{2}");
static const string INDEX_REGEX("[\\[]{1}[\\s]*([\\d]+)[\\s]*[\\]]{1}");
static const vector<string> OPERATOR_REGEXES({
NOT_REGEX,
AND_REGEX,
OR_REGEX,
XOR_REGEX,
EQUALS_REGEX,
INDEX_REGEX });
class UnaryOperator {
public:
virtual BooleanFunction operator()(const BooleanFunction &in) const = 0;
virtual ~UnaryOperator() {
}
};
class BinaryOperator {
public:
virtual BooleanFunction operator()(const BooleanFunction &first, const BooleanFunction &second) const = 0;
virtual ~BinaryOperator() {
}
};
class Index : public UnaryOperator {
public:
Index(const TruthTableUInt index) : index(index) {
}
virtual BooleanFunction operator()(const BooleanFunction &in) const;
private:
const TruthTableUInt index;
};
class BoolTransformationUnaryOperator : public UnaryOperator {
public:
virtual BooleanFunction operator()(const BooleanFunction &in) const;
private:
virtual bool operate(const bool in) const = 0;
};
class Not : public BoolTransformationUnaryOperator {
private:
virtual bool operate(const bool in) const {
return !in;
}
};
class Equals : public BinaryOperator {
public:
virtual BooleanFunction operator()(const BooleanFunction &first, const BooleanFunction &second) const {
return first == second;
}
};
class CombinatoryBinaryOperator : public BinaryOperator {
public:
virtual BooleanFunction operator()(const BooleanFunction &first, const BooleanFunction &second) const;
private:
TruthTable combineColumnsWithSameVariables(const TruthTableBuilder &rawBuilder) const;
TruthTableBuilder combineTables(const BooleanFunction &first, const BooleanFunction &second) const;
virtual bool operate(const bool first, const bool second) const = 0;
};
class Or : public CombinatoryBinaryOperator {
private:
virtual bool operate(const bool first, const bool second) const {
return first || second;
}
};
class And : public CombinatoryBinaryOperator {
private:
virtual bool operate(const bool first, const bool second) const {
return first && second;
}
};
class Xor : public CombinatoryBinaryOperator {
private:
virtual bool operate(const bool first, const bool second) const {
return first != second;
}
};
bool isKnownPrefixUnaryOperator(const string &_operator);
bool isKnownSuffixUnaryOperator(const string &_operator);
bool isKnownUnaryOperator(const string &_operator);
bool isKnownBinaryOperator(const string &_operator);
UnaryOperator *createUnaryOperatorWithSymbol(const string &_operator);
BinaryOperator *createBinaryOperatorWithSymbol(const string &_operator);
}
<|endoftext|> |
<commit_before>#include <iostream>
#include <string>
#include <fstream>
using namespace std;
template<typename T>
struct Node
{
T x;
Node<T> * left;
Node<T> * right;
Node(T const& value) : x{ value }, left{ nullptr }, right{ nullptr } {}
};
template<typename T>
class Tree
{
private:
Node<T> * root;
public:
Tree()
{
root = nullptr;
}
~Tree()
{
deleteNode(root);
}
void deleteNode(Node<T> * node)
{
if (node == nullptr) return;
deleteNode(node->left);
deleteNode(node->right);
delete node;
}
T x_() const
{
return root->x;
}
Node<T> * left_() const
{
return root->left;
}
Node<T> * right_() const
{
return root->right;
}
Node<T> * root_() const
{
return root;
}
void insert(const T& value)
{
insert(root, value);
}
void insert(Node<T>* & node, const T& value)
{
if (node) {
if (value < node->x) {
insert(node->left, value);
}
else if (value > node->x) {
insert(node->right, value);
}
else {
return;
}
}
else {
node = new Node<T>(value);
}
}
Node<T> * search(const T& x)const
{
Node<T> * curEl = root;
while (curEl != nullptr)
{
if (curEl->x == x)
break;
else
{
if (x > curEl->x)
curEl = curEl->right;
else curEl = curEl->left;
}
}
return curEl;
}
void fIn(const string filename)
{
ifstream fin;
unsigned int k;
fin.open(filename);
if (!fin.is_open())
cout << "The file isn't find" << endl;
else
{
deleteNode(root);
if (fin.eof()) return;
else
{
fin >> k;
T newEl;
for (unsigned int i = 0; i < k; ++i)
{
fin >> newEl;
insert(newEl);
}
}
fin.close();
}
}
unsigned int size(Node<T> * node)const
{
unsigned int size_ = 0;
if (node != nullptr)
size_ = size(node->left) + 1 + size(node->right);
return size_;
}
void out_to_file(const string filename)const
{
ofstream fout;
fout.open(filename);
if (!fout.is_open())
cout << "The file isn't find" << endl;
else
{
unsigned int size_ = size(root);
if (size_ == 0)
return;
fout << size_ << "\t";
fOut(root, fout);
fout.close();
}
}
void fOut(Node<T> * node, ostream&stream)const
{
if (curEl != nullptr)
{
fOut(node->left, stream);
stream << node->x << " ";
fOut(node->right, stream);
}
}
void out(ostream & stream)const
{
Out(root, stream, 0);
}
void Out(Node<T> * node, ostream&stream, size_t level)const
{
Node<T> * curEl = node;
if (curEl != nullptr)
{
Out(curEl->right, stream, level + 1);
for (unsigned int i = 0; i < level; ++i)
stream << '-';
stream << curEl->x << endl;
Out(curEl->left, stream, level + 1);
}
}
};
<commit_msg>Update BinaryTree.hpp<commit_after>#include <iostream>
#include <string>
#include <fstream>
using namespace std;
template<typename T>
struct Node
{
T x;
Node<T> * left;
Node<T> * right;
Node(T const& value) : x{ value }, left{ nullptr }, right{ nullptr } {}
};
template<typename T>
class Tree
{
private:
Node<T> * root;
public:
Tree()
{
root = nullptr;
}
~Tree()
{
deleteNode(root);
}
void deleteNode(Node<T> * node)
{
if (node == nullptr) return;
deleteNode(node->left);
deleteNode(node->right);
delete node;
}
T x_() const
{
return root->x;
}
Node<T> * left_() const
{
return root->left;
}
Node<T> * right_() const
{
return root->right;
}
Node<T> * node_() const
{
return node;
}
void insert(const T& value)
{
insert(root, value);
}
void insert(Node<T>* & node, const T& value)
{
if (node) {
if (value < node->x) {
insert(node->left, value);
}
else if (value > node->x) {
insert(node->right, value);
}
else {
return;
}
}
else {
node = new Node<T>(value);
}
}
Node<T> * search(const T& x)const
{
Node<T> * curEl = root;
while (curEl != nullptr)
{
if (curEl->x == x)
break;
else
{
if (x > curEl->x)
curEl = curEl->right;
else curEl = curEl->left;
}
}
return curEl;
}
void fIn(const string filename)
{
ifstream fin;
unsigned int k;
fin.open(filename);
if (!fin.is_open())
cout << "The file isn't find" << endl;
else
{
deleteNode(root);
if (fin.eof()) return;
else
{
fin >> k;
T newEl;
for (unsigned int i = 0; i < k; ++i)
{
fin >> newEl;
insert(newEl);
}
}
fin.close();
}
}
unsigned int size(Node<T> * node)const
{
unsigned int size_ = 0;
if (node != nullptr)
size_ = size(node->left) + 1 + size(node->right);
return size_;
}
void out_to_file(const string filename)const
{
ofstream fout;
fout.open(filename);
if (!fout.is_open())
cout << "The file isn't find" << endl;
else
{
unsigned int size_ = size(root);
if (size_ == 0)
return;
fout << size_ << "\t";
fOut(root, fout);
fout.close();
}
}
void fOut(Node<T> * node, ostream&stream)const
{
if (curEl != nullptr)
{
fOut(node->left, stream);
stream << node->x << " ";
fOut(node->right, stream);
}
}
void out(ostream & stream)const
{
Out(root, stream, 0);
}
void Out(Node<T> * node, ostream&stream, size_t level)const
{
Node<T> * curEl = node;
if (curEl != nullptr)
{
Out(curEl->right, stream, level + 1);
for (unsigned int i = 0; i < level; ++i)
stream << '-';
stream << curEl->x << endl;
Out(curEl->left, stream, level + 1);
}
}
};
<|endoftext|> |
<commit_before>#include <iostream>
#include <string>
#include <fstream>
#include <cstdint>
using namespace std;
template <typename T>
std::ostream& operator<<<>(std::ostream&, const BinaryTree<T>&);
template <typename T>
struct Node {
Node *left;
Node *right;
T data;
};
template <typename T>
class BinaryTree
{
private:
Node<T>*root;
int CountElements = 0;
public:
BinaryTree();
~BinaryTree();
Node<T>* root_();
unsigned int count() const;
void insert_node(const T&x);
Node<T> *find_node(const T&, Node<T>*)const;
void deleteNode(Node<T>* temp);
void writing(const std::string& filename)const;
friend std::ostream& operator<<<>(std::ostream&, const BinaryTree<T>&);
};
template <typename T>
BinaryTree<T>::BinaryTree()
{
root = nullptr;
}
template<typename T>
Node<T>* BinaryTree<T>::root_()
{
return root;
}
template <typename T>
BinaryTree<T>::~BinaryTree()
{
deleteNode(root);
}
template<typename T>
void BinaryTree<T>::insert_node(const T&x)
{
if (find_node(x, root_())) return;
Node<T>* MyTree = new Node<T>;
MyTree->data = x;
MyTree->left = MyTree->right = 0;
Node<T>* buff = root;
Node<T>* temp = root;
while (temp)
{
buff = temp;
if (x < temp->data)
temp = temp->left;
else
temp = temp->right;
}
if (!buff)
root = MyTree;
else
{
if (x < buff->data)
buff->left = MyTree;
else
buff->right = MyTree;
}
++CountElements;
}
template<typename T>
Node<T>* BinaryTree<T>::find_node(const T& value, Node<T>* temp) const
{
if (temp == 0 || value == temp->data)
return temp;
if (value > temp->data)
return find_node(value, temp->right);
else
return find_node(value, temp->left);
}
template<typename T>
void BinaryTree<T>::deleteNode(Node<T>* temp)
{
if (!temp)
{
throw "error";
}
if (temp->left)
{
deleteNode(temp->left);
temp->left = nullptr;
}
if (temp->right)
{
deleteNode(temp->right);
temp->right = nullptr;
}
delete temp;
}
template<typename T>
void BinaryTree<T>::writing(const std::string& filename)const
{
ofstream file_1(filename);
file_1 << CountElements << "\t";
output(file_1, root);
file_1.close();
}
template <typename T>
std::ostream& output(std::ostream& ost, const Node<T>* node, unsigned int level)
{
if (!node)
return ost;
output(ost, node->right, level + 1);
for (unsigned int i = 0; i < level; i++)
ost << "\t";
ost << node->data << std::endl;
output(ost, node->left, level + 1);
return ost;
}
template <typename T>
std::ostream& operator<<<>(std::ostream& ost, const BinaryTree<T>& temp)
{
//if (!temp.root)
//throw "error";
output(ost, temp.root, 0);
return ost;
}
<commit_msg>Update BinaryTree.hpp<commit_after>#include <iostream>
#include <string>
#include <fstream>
#include <cstdint>
using namespace std;
template<typename T>
class BinaryTree;
template<typename T>
std::ostream& operator<<(ostream& ost, BinaryTree<T>& temp);
template <typename T>
struct Node {
Node *left;
Node *right;
T data;
};
template <typename T>
class BinaryTree
{
private:
Node<T>*root;
int CountElements = 0;
public:
BinaryTree();
~BinaryTree();
Node<T>* root_();
unsigned int count() const;
void insert_node(const T&x);
Node<T> *find_node(const T&, Node<T>*)const;
void deleteNode(Node<T>* temp);
void writing(const std::string& filename)const;
friend std::ostream& operator<<<>(std::ostream&, const BinaryTree<T>&);
};
template <typename T>
BinaryTree<T>::BinaryTree()
{
root = nullptr;
}
template<typename T>
Node<T>* BinaryTree<T>::root_()
{
return root;
}
template <typename T>
BinaryTree<T>::~BinaryTree()
{
deleteNode(root);
}
template<typename T>
void BinaryTree<T>::insert_node(const T&x)
{
if (find_node(x, root_())) return;
Node<T>* MyTree = new Node<T>;
MyTree->data = x;
MyTree->left = MyTree->right = 0;
Node<T>* buff = root;
Node<T>* temp = root;
while (temp)
{
buff = temp;
if (x < temp->data)
temp = temp->left;
else
temp = temp->right;
}
if (!buff)
root = MyTree;
else
{
if (x < buff->data)
buff->left = MyTree;
else
buff->right = MyTree;
}
++CountElements;
}
template<typename T>
Node<T>* BinaryTree<T>::find_node(const T& value, Node<T>* temp) const
{
if (temp == 0 || value == temp->data)
return temp;
if (value > temp->data)
return find_node(value, temp->right);
else
return find_node(value, temp->left);
}
template<typename T>
void BinaryTree<T>::deleteNode(Node<T>* temp)
{
if (!temp)
{
throw "error";
}
if (temp->left)
{
deleteNode(temp->left);
temp->left = nullptr;
}
if (temp->right)
{
deleteNode(temp->right);
temp->right = nullptr;
}
delete temp;
}
template<typename T>
void BinaryTree<T>::writing(const std::string& filename)const
{
ofstream file_1(filename);
file_1 << CountElements << "\t";
output(file_1, root);
file_1.close();
}
template <typename T>
std::ostream& output(std::ostream& ost, const Node<T>* node, unsigned int level)
{
if (!node)
return ost;
output(ost, node->right, level + 1);
for (unsigned int i = 0; i < level; i++)
ost << "\t";
ost << node->data << std::endl;
output(ost, node->left, level + 1);
return ost;
}
template <typename T>
std::ostream& operator<<<>(std::ostream& ost, const BinaryTree<T>& temp)
{
//if (!temp.root)
//throw "error";
output(ost, temp.root, 0);
return ost;
}
<|endoftext|> |
<commit_before>#include <iostream>
#include <string>
#include <fstream>
#include <cstdint>
using namespace std;
template <typename T>
struct Node
{
Node *left;
Node *right;
T data;
};
template <typename T>
class BinaryTree;
template <typename T>
std::ostream& operator<<(std::ostream&, const BinaryTree<T>&);
template <typename T>
class BinaryTree
{
private:
Node<T>*root;
int count=0;
public:
BinaryTree();
~BinaryTree();
Node<T>* root_();
unsigned int getCount()const;
void insert_node(const T&x);
Node<T> *find_node(const T&, Node<T>*)const;
void remove_element(const T& temp);
void deleteNode(Node<T>* temp);
Node<T>* _deleteRoot(Node<T>* temp);
void writing(const std::string& filename)const;
friend std::ostream& operator<<<>(std::ostream&, const BinaryTree<T>&);
};
template <typename T>
BinaryTree<T>::BinaryTree()
{
root = nullptr;
}
template<typename T>
Node<T>* BinaryTree<T>::root_()
{
return root;
}
template <typename T>
BinaryTree<T>::~BinaryTree()
{
deleteNode(root);
count=0;
}
template <typename T>
unsigned int BinaryTree<T>::getCount()const
{
return count;
}
template<typename T>
void BinaryTree<T>::insert_node(const T&x)
{
if (find_node(x, root_())) return;
Node<T>* MyTree = new Node<T>;
MyTree->data = x;
MyTree->left = MyTree->right = 0;
Node<T>* buff = root;
Node<T>* temp = root;
while (temp)
{
buff = temp;
if (x < temp->data)
temp = temp->left;
else
temp = temp->right;
}
if (!buff)
root = MyTree;
else
{
if (x < buff->data)
buff->left = MyTree;
else
buff->right = MyTree;
}
++count;
}
template<typename T>
Node<T>* BinaryTree<T>::find_node(const T& data, Node<T>* temp) const
{
if (temp == 0 || data == temp->data)
return temp;
if (data > temp->data)
return find_node(data, temp->right);
else
return find_node(data, temp->left);
}
template<typename T>
void BinaryTree<T>::writing(const std::string& filename)const
{
ofstream file_1(filename);
file_1 << count << "\t";
output(file_1, root);
file_1.close();
}
template<typename T>
void BinaryTree<T>::deleteNode(Node<T>* temp)
{
if (!temp)
{
throw "error";
}
if (temp->left)
{
deleteNode(temp->left);
temp->left = nullptr;
}
if (temp->right)
{
deleteNode(temp->right);
temp->right = nullptr;
}
delete temp;
}
template <typename T>
std::ostream& output(std::ostream& ost, const Node<T>* node, unsigned int level)
{
if (!node)
return ost;
output(ost, node->right, level + 1);
for (unsigned int i = 0; i < level; i++)
ost << "\t";
ost << node->data << std::endl;
output(ost, node->left, level + 1);
return ost;
}
template <typename T>
Node<T>* BinaryTree<T>::_deleteRoot(Node<T>* temp)
{
Node<T>* buff, *parent;
if (temp)
{
buff = temp->right;
if (!buff)
{
buff = temp->left;
}
else
{
if (buff->left)
{
parent = temp;
while (buff->left)
{
parent = buff;
buff = buff->left;
}
parent->left = buff->right;
buff->right = temp->right;
}
buff->left = temp->left;
}
delete temp;
return buff;
}
return nullptr;
}
template <typename T>
void BinaryTree<T>::remove_element(const T& temp)
{
Node<T>* buff = root, *parent;
if (root)
{
if (root->data == temp)
{
root = _deleteRoot(root);
}
else
{
parent = root;
if (temp < parent->data) buff = parent->left;
else buff = parent->right;
while (buff)
{
if (buff->data == temp)
{
if (temp < parent->data) parent->left = _deleteRoot(parent->left);
else parent->right = _deleteRoot(parent->right);
return;
}
parent = buff;
if (temp < parent->data) buff = parent->left;
else buff = parent->right;
}
}
}
--count;
}
template <typename T>
std::ostream& operator<<(std::ostream& ost, const BinaryTree<T>& temp)
{
output(ost, temp.root, 0);
return ost;
}
<commit_msg>Update BinaryTree.hpp<commit_after>#include <iostream>
#include <string>
#include <fstream>
#include <cstdint>
using namespace std;
template <typename T>
struct Node
{
Node *left;
Node *right;
T data;
};
template <typename T>
class BinaryTree;
template <typename T>
std::ostream& operator<<(std::ostream&, const BinaryTree<T>&);
template <typename T>
class BinaryTree
{
private:
Node<T>*root;
int count=0;
public:
BinaryTree();
~BinaryTree();
Node<T>* root_();
unsigned int getCount()const;
void insert_node(const T&x);
Node<T> *find_node(const T&, Node<T>*)const;
void remove_element(const T& temp);
void deleteNode(Node<T>* temp);
Node<T>* _deleteRoot(Node<T>* temp);
void writing(const std::string& filename)const;
friend std::ostream& operator<<<>(std::ostream&, const BinaryTree<T>&);
};
template <typename T>
BinaryTree<T>::BinaryTree()
{
root = nullptr;
}
template<typename T>
Node<T>* BinaryTree<T>::root_()
{
return root;
}
template <typename T>
BinaryTree<T>::~BinaryTree()
{
deleteNode(root);
count=0;
}
template <typename T>
unsigned int BinaryTree<T>::getCount()const
{
return count;
}
template<typename T>
void BinaryTree<T>::insert_node(const T&x)
{
if (find_node(x, root_())) return;
Node<T>* MyTree = new Node<T>;
MyTree->data = x;
MyTree->left = MyTree->right = 0;
Node<T>* buff = root;
Node<T>* temp = root;
while (temp)
{
buff = temp;
if (x < temp->data)
temp = temp->left;
else
temp = temp->right;
}
if (!buff)
root = MyTree;
else
{
if (x < buff->data)
buff->left = MyTree;
else
buff->right = MyTree;
}
++count;
}
template<typename T>
Node<T>* BinaryTree<T>::find_node(const T& data, Node<T>* temp) const
{
if (temp == 0 || data == temp->data)
return temp;
if (data > temp->data)
return find_node(data, temp->right);
else
return find_node(data, temp->left);
}
template<typename T>
void BinaryTree<T>::writing(const std::string& filename)const
{
ofstream file_1(filename);
file_1 << count << "\t";
output(file_1, root);
file_1.close();
}
template<typename T>
void BinaryTree<T>::deleteNode(Node<T>* temp)
{
if (!temp)
return;
if (temp->left)
{
deleteNode(temp->left);
temp->left = nullptr;
}
if (temp->right)
{
deleteNode(temp->right);
temp->right = nullptr;
}
delete temp;
}
template <typename T>
std::ostream& output(std::ostream& ost, const Node<T>* node, unsigned int level)
{
if (!node)
return ost;
output(ost, node->right, level + 1);
for (unsigned int i = 0; i < level; i++)
ost << "\t";
ost << node->data << std::endl;
output(ost, node->left, level + 1);
return ost;
}
template <typename T>
Node<T>* BinaryTree<T>::_deleteRoot(Node<T>* temp)
{
Node<T>* buff, *parent;
if (temp)
{
buff = temp->right;
if (!buff)
{
buff = temp->left;
}
else
{
if (buff->left)
{
parent = temp;
while (buff->left)
{
parent = buff;
buff = buff->left;
}
parent->left = buff->right;
buff->right = temp->right;
}
buff->left = temp->left;
}
delete temp;
return buff;
}
return nullptr;
}
template <typename T>
void BinaryTree<T>::remove_element(const T& temp)
{
Node<T>* buff = root, *parent;
if (root)
{
if (root->data == temp)
{
root = _deleteRoot(root);
}
else
{
parent = root;
if (temp < parent->data) buff = parent->left;
else buff = parent->right;
while (buff)
{
if (buff->data == temp)
{
if (temp < parent->data) parent->left = _deleteRoot(parent->left);
else parent->right = _deleteRoot(parent->right);
return;
}
parent = buff;
if (temp < parent->data) buff = parent->left;
else buff = parent->right;
}
}
}
--count;
}
template <typename T>
std::ostream& operator<<(std::ostream& ost, const BinaryTree<T>& temp)
{
output(ost, temp.root, 0);
return ost;
}
<|endoftext|> |
<commit_before>#include "ThreadPool.hpp"
#include <iterator>
namespace dbr
{
namespace cc
{
ThreadPool::ThreadPool(std::size_t threadCount)
: threadsWaiting(0),
terminate(false),
paused(false)
{
// prevent potential reallocation, thereby screwing up all our hopes and dreams
threads.reserve(threadCount);
std::generate_n(std::back_inserter(threads), threadCount, [this]() { return std::thread{threadTask, this}; });
}
ThreadPool::~ThreadPool()
{
clear();
// tell threads to stop when they can
terminate = true;
jobsAvailable.notify_all();
// wait for all threads to finish
for(auto& t : threads)
{
if(t.joinable())
t.join();
}
}
std::size_t ThreadPool::threadCount() const
{
return threads.size();
}
std::size_t ThreadPool::waitingJobs() const
{
std::lock_guard<std::mutex> jobLock(jobsMutex);
return jobs.size();
}
ThreadPool::Ids ThreadPool::ids() const
{
Ids ret(threads.size());
std::transform(threads.begin(), threads.end(), ret.begin(), [](auto& t) { return t.get_id(); });
return ret;
}
void ThreadPool::clear()
{
std::lock_guard<std::mutex> lock{jobsMutex};
while(!jobs.empty())
jobs.pop();
}
void ThreadPool::pause(bool state)
{
paused = state;
if(!paused)
jobsAvailable.notify_all();
}
void ThreadPool::wait()
{
// we're done waiting once all threads are waiting
while(threadsWaiting != threads.size());
}
void ThreadPool::threadTask(ThreadPool* pool)
{
// loop until we break (to keep thread alive)
while(true)
{
// if we need to finish, let's do it before we get into
// all the expensive synchronization stuff
if(pool->terminate)
break;
std::unique_lock<std::mutex> jobsLock{pool->jobsMutex};
// if there are no more jobs, or we're paused, go into waiting mode
if(pool->jobs.empty() || pool->paused)
{
++pool->threadsWaiting;
pool->jobsAvailable.wait(jobsLock, [&]()
{
return pool->terminate || !(pool->jobs.empty() || pool->paused);
});
--pool->threadsWaiting;
}
// check once more before grabbing a job, since we want to stop ASAP
if(pool->terminate)
break;
// take next job
auto job = std::move(pool->jobs.front());
pool->jobs.pop();
jobsLock.unlock();
job();
}
}
}
}
<commit_msg>Fix C++11 conformity (fixes #1)<commit_after>#include "ThreadPool.hpp"
#include <iterator>
namespace dbr
{
namespace cc
{
ThreadPool::ThreadPool(std::size_t threadCount)
: threadsWaiting(0),
terminate(false),
paused(false)
{
// prevent potential reallocation, thereby screwing up all our hopes and dreams
threads.reserve(threadCount);
std::generate_n(std::back_inserter(threads), threadCount, [this]() { return std::thread{threadTask, this}; });
}
ThreadPool::~ThreadPool()
{
clear();
// tell threads to stop when they can
terminate = true;
jobsAvailable.notify_all();
// wait for all threads to finish
for(auto& t : threads)
{
if(t.joinable())
t.join();
}
}
std::size_t ThreadPool::threadCount() const
{
return threads.size();
}
std::size_t ThreadPool::waitingJobs() const
{
std::lock_guard<std::mutex> jobLock(jobsMutex);
return jobs.size();
}
ThreadPool::Ids ThreadPool::ids() const
{
Ids ret(threads.size());
std::transform(threads.begin(), threads.end(), ret.begin(), [](const std::thread& t) { return t.get_id(); });
return ret;
}
void ThreadPool::clear()
{
std::lock_guard<std::mutex> lock{jobsMutex};
while(!jobs.empty())
jobs.pop();
}
void ThreadPool::pause(bool state)
{
paused = state;
if(!paused)
jobsAvailable.notify_all();
}
void ThreadPool::wait()
{
// we're done waiting once all threads are waiting
while(threadsWaiting != threads.size());
}
void ThreadPool::threadTask(ThreadPool* pool)
{
// loop until we break (to keep thread alive)
while(true)
{
// if we need to finish, let's do it before we get into
// all the expensive synchronization stuff
if(pool->terminate)
break;
std::unique_lock<std::mutex> jobsLock{pool->jobsMutex};
// if there are no more jobs, or we're paused, go into waiting mode
if(pool->jobs.empty() || pool->paused)
{
++pool->threadsWaiting;
pool->jobsAvailable.wait(jobsLock, [&]()
{
return pool->terminate || !(pool->jobs.empty() || pool->paused);
});
--pool->threadsWaiting;
}
// check once more before grabbing a job, since we want to stop ASAP
if(pool->terminate)
break;
// take next job
auto job = std::move(pool->jobs.front());
pool->jobs.pop();
jobsLock.unlock();
job();
}
}
}
}
<|endoftext|> |
<commit_before>// ThreadTest.cpp : Defines the entry point for the console application.
//
#include "stdafx.h"
#include <thread>
#include <chrono>
#include <set>
#include <vector>
#include <shared_mutex>
#include <atomic>
int egis = 0;
class AsmLock {
public:
void Lock()
{
__asm {
mov eax, 1;
retry:
xchg eax, [egis];
test eax, eax;
jnz retry;
}
}
void Lock2()
{
__asm {
mov eax, 1;
retry:
xchg eax, [egis];
test eax, eax;
jz done;
retry_mov:
mov ebx, [egis];
test ebx, ebx;
jnz retry_mov;
jmp retry;
done:
}
}
void Unlock()
{
__asm {
mov eax, 0;
xchg eax, [egis];
}
}
void Unlock2()
{
__asm {
mov[egis], 0;
}
}
};
class SharedMutex {
std::shared_timed_mutex mutex;
public:
void Lock()
{
mutex.lock();
}
void Unlock()
{
mutex.unlock();
}
};
class Atomic {
std::atomic<int> val = 0;
static const int writeLockBit = 0x40000000;
static const int upgradingBit = 0x00010000;
static const int writeUpgradeingBits = 0x7fff0000;
static const int readerBits = 0x0000ffff;
void LockInternal(int delta, int testBits)
{
int expected;
do {
do {
expected = val;
} while (expected & testBits);
} while (!val.compare_exchange_weak(expected, expected + delta));
}
public:
void ReadLock()
{
LockInternal(1, writeUpgradeingBits);
}
void Upgrade()
{
val.fetch_add(upgradingBit - 1);
LockInternal(writeLockBit - upgradingBit, readerBits | writeLockBit);
}
void WriteLock()
{
LockInternal(writeLockBit, readerBits | writeLockBit);
}
void WriteUnlock()
{
val.fetch_sub(writeLockBit);
}
void ReadUnlock()
{
val.fetch_sub(1);
}
};
//static AsmLock lock;
//static SharedMutex lock;
static Atomic lock;
void IncDecThreadMain()
{
static int a = 0;
for (int i = 0; i < 1000000; i++) {
lock.WriteLock();
a++;
if (a != 1)
{
printf("%d ", a);
}
a--;
lock.WriteUnlock();
printf("");
}
}
void StlContainerThreadMain(int id)
{
static std::set<int> c;
int readFound = 0;
int readNotFound = 0;
for (int i = 0; i < 1000000; i++) {
int r = rand() % 10000;
if (i % 10 == 0) {
lock.ReadLock();
auto it = c.find(r);
if (it != c.end()) {
lock.ReadUnlock();
} else {
lock.Upgrade();
auto it = c.find(r);
if (it == c.end()) {
c.insert(r);
}
lock.WriteUnlock();
}
} else {
lock.ReadLock();
auto it = c.find(r);
if (it == c.end()) {
readNotFound++;
} else {
readFound++;
}
lock.ReadUnlock();
}
printf("");
}
printf("threadId=%d readFound=%d readNotFound=%d\n", id, readFound, readNotFound);
}
double GetTime()
{
static auto start = std::chrono::high_resolution_clock::now();
auto now = std::chrono::high_resolution_clock::now();
return std::chrono::duration_cast<std::chrono::duration<double, std::ratio<1, 1>>>(now - start).count();
}
void IncDecTest()
{
printf("IncDecTest\n");
double begin = GetTime();
std::thread t1(IncDecThreadMain);
std::thread t2(IncDecThreadMain);
std::thread t3(IncDecThreadMain);
t1.join();
t2.join();
t3.join();
double end = GetTime();
printf("elapsed: %f\n", end - begin);
}
void StlContainerTest()
{
printf("StlContainerTest\n");
double begin = GetTime();
std::vector<std::thread> t;
for (int i = 0; i < 10; i++) {
t.emplace_back(std::thread(StlContainerThreadMain, i));
}
for (int i = 0; i < 10; i++) {
t[i].join();
}
double end = GetTime();
printf("elapsed: %f\n", end - begin);
}
int main()
{
IncDecTest();
StlContainerTest();
return 0;
}
<commit_msg>upgradable read lock<commit_after>// ThreadTest.cpp : Defines the entry point for the console application.
//
#include "stdafx.h"
#include <thread>
#include <chrono>
#include <set>
#include <vector>
#include <shared_mutex>
#include <atomic>
int egis = 0;
class AsmLock {
public:
void Lock()
{
__asm {
mov eax, 1;
retry:
xchg eax, [egis];
test eax, eax;
jnz retry;
}
}
void Lock2()
{
__asm {
mov eax, 1;
retry:
xchg eax, [egis];
test eax, eax;
jz done;
retry_mov:
mov ebx, [egis];
test ebx, ebx;
jnz retry_mov;
jmp retry;
done:
}
}
void Unlock()
{
__asm {
mov eax, 0;
xchg eax, [egis];
}
}
void Unlock2()
{
__asm {
mov[egis], 0;
}
}
};
class SharedMutex {
std::shared_timed_mutex mutex;
public:
void Lock()
{
mutex.lock();
}
void Unlock()
{
mutex.unlock();
}
};
class Atomic {
std::atomic<int> val = 0;
static const int writeLockBit = 0x40000000;
static const int upgradableBit = 0x00010000;
static const int readerBits = 0x0000ffff;
void LockInternal(int delta, int testBits)
{
int expected;
do {
do {
expected = val;
} while (expected & testBits);
} while (!val.compare_exchange_weak(expected, expected + delta));
}
public:
void ReadLock()
{
LockInternal(1, writeLockBit);
}
void ReadUnlock()
{
val.fetch_sub(1);
}
void ReadLockUpgradable()
{
LockInternal(upgradableBit, writeLockBit | upgradableBit);
}
void ReadUnlockUpgradable()
{
val.fetch_sub(upgradableBit);
}
void Upgrade()
{
LockInternal(writeLockBit - upgradableBit, readerBits | writeLockBit);
}
void WriteLock()
{
LockInternal(writeLockBit, readerBits | writeLockBit);
}
void WriteUnlock()
{
val.fetch_sub(writeLockBit);
}
};
//static AsmLock lock;
//static SharedMutex lock;
static Atomic lock;
void IncDecThreadMain()
{
static int a = 0;
for (int i = 0; i < 1000000; i++) {
lock.WriteLock();
a++;
if (a != 1)
{
printf("%d ", a);
}
a--;
lock.WriteUnlock();
printf("");
}
}
void StlContainerThreadMain(int id)
{
static std::set<int> c;
int readFound = 0;
int readNotFound = 0;
for (int i = 0; i < 1000000; i++) {
int r = rand() % 10000;
if (i % 10 == 0) {
lock.ReadLockUpgradable();
auto it = c.find(r);
if (it != c.end()) {
lock.ReadUnlockUpgradable();
} else {
lock.Upgrade();
c.insert(r);
lock.WriteUnlock();
}
} else {
lock.ReadLock();
auto it = c.find(r);
if (it == c.end()) {
readNotFound++;
} else {
readFound++;
}
lock.ReadUnlock();
}
printf("");
}
printf("threadId=%d readFound=%d readNotFound=%d\n", id, readFound, readNotFound);
}
double GetTime()
{
static auto start = std::chrono::high_resolution_clock::now();
auto now = std::chrono::high_resolution_clock::now();
return std::chrono::duration_cast<std::chrono::duration<double, std::ratio<1, 1>>>(now - start).count();
}
void IncDecTest()
{
printf("IncDecTest\n");
double begin = GetTime();
std::thread t1(IncDecThreadMain);
std::thread t2(IncDecThreadMain);
std::thread t3(IncDecThreadMain);
t1.join();
t2.join();
t3.join();
double end = GetTime();
printf("elapsed: %f\n", end - begin);
}
void StlContainerTest()
{
printf("StlContainerTest\n");
double begin = GetTime();
std::vector<std::thread> t;
for (int i = 0; i < 10; i++) {
t.emplace_back(std::thread(StlContainerThreadMain, i));
}
for (int i = 0; i < 10; i++) {
t[i].join();
}
double end = GetTime();
printf("elapsed: %f\n", end - begin);
}
int main()
{
IncDecTest();
StlContainerTest();
return 0;
}
<|endoftext|> |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.