commit
stringlengths 40
40
| old_file
stringlengths 2
205
| new_file
stringlengths 2
205
| old_contents
stringlengths 0
32.9k
| new_contents
stringlengths 1
38.9k
| subject
stringlengths 3
9.4k
| message
stringlengths 6
9.84k
| lang
stringlengths 3
13
| license
stringclasses 13
values | repos
stringlengths 6
115k
|
---|---|---|---|---|---|---|---|---|---|
8ee8d9177d52e69674fd77b3ff47739d16afadd3
|
avogadro/quantumio/mopacaux.cpp
|
avogadro/quantumio/mopacaux.cpp
|
/******************************************************************************
This source file is part of the Avogadro project.
Copyright 2008-2009 Marcus D. Hanwell
Copyright 2010-2013 Kitware, Inc.
This source code is released under the New BSD License, (the "License").
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 "mopacaux.h"
#include <avogadro/core/molecule.h>
#include <avogadro/quantum/slaterset.h>
#include <QtCore/QFile>
#include <QtCore/QStringList>
#include <QtCore/QDebug>
using std::vector;
using Eigen::Vector3d;
namespace Avogadro {
namespace QuantumIO {
MopacAux::MopacAux(QString filename, SlaterSet* basis)
{
// Open the file for reading and process it
QFile file(filename);
if (!file.open(QIODevice::ReadOnly | QIODevice::Text))
return;
qDebug() << "File" << filename << "opened.";
// Process the formatted checkpoint and extract all the information we need
m_in.setDevice(&file);
while (!m_in.atEnd()) {
processLine();
}
// Now it should all be loaded load it into the basis set
load(basis);
}
MopacAux::~MopacAux()
{
}
void MopacAux::processLine()
{
// First truncate the line, remove trailing white space and check
QString line = m_in.readLine();
QString key = line;
key = key.trimmed();
// QStringList list = tmp.split("=", QString::SkipEmptyParts);
// Big switch statement checking for various things we are interested in
if (key.contains("ATOM_CORE")) {
QString tmp = key.mid(key.indexOf('[')+1, 4);
qDebug() << "Number of atoms =" << tmp.toInt();
m_atomNums = readArrayI(tmp.toInt());
}
else if (key.contains("AO_ATOMINDEX")) {
QString tmp = key.mid(key.indexOf('[')+1, 4);
qDebug() << "Number of atomic orbitals =" << tmp.toInt();
m_atomIndex = readArrayI(tmp.toInt());
for (unsigned int i = 0; i < m_atomIndex.size(); ++i) {
--m_atomIndex[i];
}
}
else if (key.contains("ATOM_SYMTYPE")) {
QString tmp = key.mid(key.indexOf('[')+1, 4);
qDebug() << "Number of atomic orbital types =" << tmp.toInt();
m_atomSym = readArraySym(tmp.toInt());
}
else if (key.contains("AO_ZETA")) {
QString tmp = key.mid(key.indexOf('[')+1, 4);
qDebug() << "Number of zeta values =" << tmp.toInt();
m_zeta = readArrayD(tmp.toInt());
}
else if (key.contains("ATOM_PQN")) {
QString tmp = key.mid(key.indexOf('[')+1, 4);
qDebug() << "Number of PQN values =" << tmp.toInt();
m_pqn = readArrayI(tmp.toInt());
}
else if (key.contains("NUM_ELECTRONS")) {
QString tmp = key.split('=').at(1);
qDebug() << "Number of electrons =" << tmp.toInt();
m_electrons = tmp.toInt();
}
else if (key.contains("ATOM_X_OPT:ANGSTROMS")) {
QString tmp = key.mid(key.indexOf('[')+1, 4);
qDebug() << "Number of atomic coordinates =" << tmp.toInt();
m_atomPos = readArrayVec(tmp.toInt());
}
else if (key.contains("OVERLAP_MATRIX")) {
QString tmp = key.mid(key.indexOf('[')+1, 6);
qDebug() << "Size of lower half triangle of overlap matrix =" << tmp.toInt();
readOverlapMatrix(tmp.toInt());
}
else if (key.contains("EIGENVECTORS")) {
// For large molecules the Eigenvectors counter overflows to [*****]
// So just use the square of the m_atomIndex array
// QString tmp = key.mid(key.indexOf('[')+1, 6);
qDebug() << "Size of eigen vectors matrix ="
<< m_atomIndex.size() * m_atomIndex.size();
readEigenVectors(m_atomIndex.size() * m_atomIndex.size());
}
else if (key.contains("TOTAL_DENSITY_MATRIX")) {
QString tmp = key.mid(key.indexOf('[')+1, 6);
qDebug() << "Size of lower half triangle of density matrix =" << tmp.toInt();
readDensityMatrix(tmp.toInt());
}
}
void MopacAux::load(SlaterSet* basis)
{
// Now load up our basis set
basis->addAtoms(m_atomPos);
basis->addSlaterIndices(m_atomIndex);
basis->addSlaterTypes(m_atomSym);
basis->addZetas(m_zeta);
basis->addPQNs(m_pqn);
basis->setNumElectrons(m_electrons);
basis->addOverlapMatrix(m_overlap);
basis->addEigenVectors(m_eigenVectors);
basis->addDensityMatrix(m_density);
Core::Molecule &mol = basis->moleculeRef();
if (m_atomPos.size() == m_atomNums.size()) {
for (size_t i = 0; i < m_atomPos.size(); ++i) {
Core::Atom a = mol.addAtom(m_atomNums[i]);
a.setPosition3d(m_atomPos[i]);
}
}
else
qWarning() << "Number of atomic numbers (" << m_atomNums.size()
<< ") does not equal the number of atomic positions ("
<< m_atomPos.size() << "). Not populating molecule.";
}
vector<int> MopacAux::readArrayI(unsigned int n)
{
vector<int> tmp;
while (tmp.size() < n) {
QString line = m_in.readLine();
QStringList list = line.split(' ', QString::SkipEmptyParts);
for (int i = 0; i < list.size(); ++i)
tmp.push_back(list.at(i).toInt());
}
return tmp;
}
vector<double> MopacAux::readArrayD(unsigned int n)
{
vector<double> tmp;
while (tmp.size() < n) {
QString line = m_in.readLine();
QStringList list = line.split(' ', QString::SkipEmptyParts);
for (int i = 0; i < list.size(); ++i)
tmp.push_back(list.at(i).toDouble());
}
return tmp;
}
vector<int> MopacAux::readArraySym(unsigned int n)
{
int type;
vector<int> tmp;
while (tmp.size() < n) {
QString line = m_in.readLine();
QStringList list = line.split(' ', QString::SkipEmptyParts);
for (int i = 0; i < list.size(); ++i) {
if (list.at(i) == "S") type = SlaterSet::S;
else if (list.at(i) == "PX") type = SlaterSet::PX;
else if (list.at(i) == "PY") type = SlaterSet::PY;
else if (list.at(i) == "PZ") type = SlaterSet::PZ;
else if (list.at(i) == "X2") type = SlaterSet::X2;
else if (list.at(i) == "XZ") type = SlaterSet::XZ;
else if (list.at(i) == "Z2") type = SlaterSet::Z2;
else if (list.at(i) == "YZ") type = SlaterSet::YZ;
else if (list.at(i) == "XY") type = SlaterSet::XY;
else type = SlaterSet::UU;
tmp.push_back(type);
}
}
return tmp;
}
vector<Vector3d> MopacAux::readArrayVec(unsigned int n)
{
vector<Vector3d> tmp(n/3);
double *ptr = tmp[0].data();
unsigned int cnt = 0;
while (cnt < n) {
QString line = m_in.readLine();
QStringList list = line.split(' ', QString::SkipEmptyParts);
for (int i = 0; i < list.size(); ++i) {
ptr[cnt++] = list.at(i).toDouble();
}
}
return tmp;
}
bool MopacAux::readOverlapMatrix(unsigned int n)
{
m_overlap.resize(m_zeta.size(), m_zeta.size());
unsigned int cnt = 0;
unsigned int i = 0, j = 0;
unsigned int f = 1;
// Skip the first commment line...
m_in.readLine();
while (cnt < n) {
QString line = m_in.readLine();
QStringList list = line.split(' ', QString::SkipEmptyParts);
for (int k = 0; k < list.size(); ++k) {
//m_overlap.part<Eigen::SelfAdjoint>()(i, j) = list.at(k).toDouble();
m_overlap(i, j) = m_overlap(j, i) = list.at(k).toDouble();
++i; ++cnt;
if (i == f) {
// We need to move down to the next row and increment f - lower tri
i = 0;
++f;
++j;
}
}
}
return true;
}
bool MopacAux::readEigenVectors(unsigned int n)
{
m_eigenVectors.resize(m_zeta.size(), m_zeta.size());
unsigned int cnt = 0;
unsigned int i = 0, j = 0;
while (cnt < n) {
QString line = m_in.readLine();
QStringList list = line.split(' ', QString::SkipEmptyParts);
for (int k = 0; k < list.size(); ++k) {
m_eigenVectors(i, j) = list.at(k).toDouble();
++i; ++cnt;
if (i == m_zeta.size()) {
// We need to move down to the next row and increment f - lower tri
i = 0;
++j;
}
}
}
return true;
}
bool MopacAux::readDensityMatrix(unsigned int n)
{
m_density.resize(m_zeta.size(), m_zeta.size());
unsigned int cnt = 0;
unsigned int i = 0, j = 0;
unsigned int f = 1;
// Skip the first commment line...
m_in.readLine();
while (cnt < n) {
QString line = m_in.readLine();
QStringList list = line.split(' ', QString::SkipEmptyParts);
for (int k = 0; k < list.size(); ++k) {
//m_overlap.part<Eigen::SelfAdjoint>()(i, j) = list.at(k).toDouble();
m_density(i, j) = m_density(j, i) = list.at(k).toDouble();
++i; ++cnt;
if (i == f) {
// We need to move down to the next row and increment f - lower tri
i = 0;
++f;
++j;
}
}
}
return true;
}
void MopacAux::outputAll()
{
qDebug() << "Shell mappings.";
for (unsigned int i = 0; i < m_shellTypes.size(); ++i)
qDebug() << i << ": type =" << m_shellTypes.at(i)
<< ", number =" << m_shellNums.at(i)
<< ", atom =" << m_shelltoAtom.at(i);
qDebug() << "MO coefficients.";
for (unsigned int i = 0; i < m_MOcoeffs.size(); ++i)
qDebug() << m_MOcoeffs.at(i);
}
}
}
|
/******************************************************************************
This source file is part of the Avogadro project.
Copyright 2008-2009 Marcus D. Hanwell
Copyright 2010-2013 Kitware, Inc.
This source code is released under the New BSD License, (the "License").
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 "mopacaux.h"
#include <avogadro/core/molecule.h>
#include <avogadro/quantum/slaterset.h>
#include <QtCore/QFile>
#include <QtCore/QStringList>
#include <QtCore/QDebug>
using std::vector;
using Eigen::Vector3d;
namespace Avogadro {
namespace QuantumIO {
MopacAux::MopacAux(QString filename, SlaterSet* basis)
{
// Open the file for reading and process it
QFile file(filename);
if (!file.open(QIODevice::ReadOnly | QIODevice::Text))
return;
qDebug() << "File" << filename << "opened.";
// Process the formatted checkpoint and extract all the information we need
m_in.setDevice(&file);
while (!m_in.atEnd()) {
processLine();
}
// Now it should all be loaded load it into the basis set
load(basis);
}
MopacAux::~MopacAux()
{
}
void MopacAux::processLine()
{
// First truncate the line, remove trailing white space and check
QString line = m_in.readLine();
QString key = line;
key = key.trimmed();
// QStringList list = tmp.split("=", QString::SkipEmptyParts);
// Big switch statement checking for various things we are interested in
if (key.contains("ATOM_CORE")) {
QString tmp = key.mid(key.indexOf('[')+1, 4);
qDebug() << "Number of atoms =" << tmp.toInt();
m_atomNums = readArrayI(tmp.toInt());
}
else if (key.contains("AO_ATOMINDEX")) {
QString tmp = key.mid(key.indexOf('[')+1, 4);
qDebug() << "Number of atomic orbitals =" << tmp.toInt();
m_atomIndex = readArrayI(tmp.toInt());
for (unsigned int i = 0; i < m_atomIndex.size(); ++i) {
--m_atomIndex[i];
}
}
else if (key.contains("ATOM_SYMTYPE")) {
QString tmp = key.mid(key.indexOf('[')+1, 4);
qDebug() << "Number of atomic orbital types =" << tmp.toInt();
m_atomSym = readArraySym(tmp.toInt());
}
else if (key.contains("AO_ZETA")) {
QString tmp = key.mid(key.indexOf('[')+1, 4);
qDebug() << "Number of zeta values =" << tmp.toInt();
m_zeta = readArrayD(tmp.toInt());
}
else if (key.contains("ATOM_PQN")) {
QString tmp = key.mid(key.indexOf('[')+1, 4);
qDebug() << "Number of PQN values =" << tmp.toInt();
m_pqn = readArrayI(tmp.toInt());
}
else if (key.contains("NUM_ELECTRONS")) {
QString tmp = key.split('=').at(1);
qDebug() << "Number of electrons =" << tmp.toInt();
m_electrons = tmp.toInt();
}
else if (key.contains("ATOM_X_OPT:ANGSTROMS")) {
QString tmp = key.mid(key.indexOf('[')+1, 4);
qDebug() << "Number of atomic coordinates =" << tmp.toInt();
m_atomPos = readArrayVec(tmp.toInt());
}
else if (key.contains("OVERLAP_MATRIX")) {
QString tmp = key.mid(key.indexOf('[')+1, 6);
qDebug() << "Size of lower half triangle of overlap matrix =" << tmp.toInt();
readOverlapMatrix(tmp.toInt());
}
else if (key.contains("EIGENVECTORS")) {
// For large molecules the Eigenvectors counter overflows to [*****]
// So just use the square of the m_atomIndex array
// QString tmp = key.mid(key.indexOf('[')+1, 6);
qDebug() << "Size of eigen vectors matrix ="
<< m_atomIndex.size() * m_atomIndex.size();
readEigenVectors(m_atomIndex.size() * m_atomIndex.size());
}
else if (key.contains("TOTAL_DENSITY_MATRIX")) {
QString tmp = key.mid(key.indexOf('[')+1, 6);
qDebug() << "Size of lower half triangle of density matrix =" << tmp.toInt();
readDensityMatrix(tmp.toInt());
}
}
void MopacAux::load(SlaterSet* basis)
{
if (m_atomPos.size() == 0) {
qWarning() << "No atoms found in .aux file. Bailing out.";
basis->setIsValid(false);
return;
}
// Now load up our basis set
basis->addAtoms(m_atomPos);
basis->addSlaterIndices(m_atomIndex);
basis->addSlaterTypes(m_atomSym);
basis->addZetas(m_zeta);
basis->addPQNs(m_pqn);
basis->setNumElectrons(m_electrons);
basis->addOverlapMatrix(m_overlap);
basis->addEigenVectors(m_eigenVectors);
basis->addDensityMatrix(m_density);
Core::Molecule &mol = basis->moleculeRef();
if (m_atomPos.size() == m_atomNums.size()) {
for (size_t i = 0; i < m_atomPos.size(); ++i) {
Core::Atom a = mol.addAtom(m_atomNums[i]);
a.setPosition3d(m_atomPos[i]);
}
}
else {
qWarning() << "Number of atomic numbers (" << m_atomNums.size()
<< ") does not equal the number of atomic positions ("
<< m_atomPos.size() << "). Not populating molecule.";
basis->setIsValid(false);
}
}
vector<int> MopacAux::readArrayI(unsigned int n)
{
vector<int> tmp;
while (tmp.size() < n) {
QString line = m_in.readLine();
QStringList list = line.split(' ', QString::SkipEmptyParts);
for (int i = 0; i < list.size(); ++i)
tmp.push_back(list.at(i).toInt());
}
return tmp;
}
vector<double> MopacAux::readArrayD(unsigned int n)
{
vector<double> tmp;
while (tmp.size() < n) {
QString line = m_in.readLine();
QStringList list = line.split(' ', QString::SkipEmptyParts);
for (int i = 0; i < list.size(); ++i)
tmp.push_back(list.at(i).toDouble());
}
return tmp;
}
vector<int> MopacAux::readArraySym(unsigned int n)
{
int type;
vector<int> tmp;
while (tmp.size() < n) {
QString line = m_in.readLine();
QStringList list = line.split(' ', QString::SkipEmptyParts);
for (int i = 0; i < list.size(); ++i) {
if (list.at(i) == "S") type = SlaterSet::S;
else if (list.at(i) == "PX") type = SlaterSet::PX;
else if (list.at(i) == "PY") type = SlaterSet::PY;
else if (list.at(i) == "PZ") type = SlaterSet::PZ;
else if (list.at(i) == "X2") type = SlaterSet::X2;
else if (list.at(i) == "XZ") type = SlaterSet::XZ;
else if (list.at(i) == "Z2") type = SlaterSet::Z2;
else if (list.at(i) == "YZ") type = SlaterSet::YZ;
else if (list.at(i) == "XY") type = SlaterSet::XY;
else type = SlaterSet::UU;
tmp.push_back(type);
}
}
return tmp;
}
vector<Vector3d> MopacAux::readArrayVec(unsigned int n)
{
vector<Vector3d> tmp(n/3);
double *ptr = tmp[0].data();
unsigned int cnt = 0;
while (cnt < n) {
QString line = m_in.readLine();
QStringList list = line.split(' ', QString::SkipEmptyParts);
for (int i = 0; i < list.size(); ++i) {
ptr[cnt++] = list.at(i).toDouble();
}
}
return tmp;
}
bool MopacAux::readOverlapMatrix(unsigned int n)
{
m_overlap.resize(m_zeta.size(), m_zeta.size());
unsigned int cnt = 0;
unsigned int i = 0, j = 0;
unsigned int f = 1;
// Skip the first commment line...
m_in.readLine();
while (cnt < n) {
QString line = m_in.readLine();
QStringList list = line.split(' ', QString::SkipEmptyParts);
for (int k = 0; k < list.size(); ++k) {
//m_overlap.part<Eigen::SelfAdjoint>()(i, j) = list.at(k).toDouble();
m_overlap(i, j) = m_overlap(j, i) = list.at(k).toDouble();
++i; ++cnt;
if (i == f) {
// We need to move down to the next row and increment f - lower tri
i = 0;
++f;
++j;
}
}
}
return true;
}
bool MopacAux::readEigenVectors(unsigned int n)
{
m_eigenVectors.resize(m_zeta.size(), m_zeta.size());
unsigned int cnt = 0;
unsigned int i = 0, j = 0;
while (cnt < n) {
QString line = m_in.readLine();
QStringList list = line.split(' ', QString::SkipEmptyParts);
for (int k = 0; k < list.size(); ++k) {
m_eigenVectors(i, j) = list.at(k).toDouble();
++i; ++cnt;
if (i == m_zeta.size()) {
// We need to move down to the next row and increment f - lower tri
i = 0;
++j;
}
}
}
return true;
}
bool MopacAux::readDensityMatrix(unsigned int n)
{
m_density.resize(m_zeta.size(), m_zeta.size());
unsigned int cnt = 0;
unsigned int i = 0, j = 0;
unsigned int f = 1;
// Skip the first commment line...
m_in.readLine();
while (cnt < n) {
QString line = m_in.readLine();
QStringList list = line.split(' ', QString::SkipEmptyParts);
for (int k = 0; k < list.size(); ++k) {
//m_overlap.part<Eigen::SelfAdjoint>()(i, j) = list.at(k).toDouble();
m_density(i, j) = m_density(j, i) = list.at(k).toDouble();
++i; ++cnt;
if (i == f) {
// We need to move down to the next row and increment f - lower tri
i = 0;
++f;
++j;
}
}
}
return true;
}
void MopacAux::outputAll()
{
qDebug() << "Shell mappings.";
for (unsigned int i = 0; i < m_shellTypes.size(); ++i)
qDebug() << i << ": type =" << m_shellTypes.at(i)
<< ", number =" << m_shellNums.at(i)
<< ", atom =" << m_shelltoAtom.at(i);
qDebug() << "MO coefficients.";
for (unsigned int i = 0; i < m_MOcoeffs.size(); ++i)
qDebug() << m_MOcoeffs.at(i);
}
}
}
|
Mark basis set as invalid if no atoms found.
|
Mark basis set as invalid if no atoms found.
Ref discussion in:
http://sourceforge.net/mailarchive/forum.php?thread_name=510E81A7.3080406%40pitt.edu&forum_name=avogadro-discuss
Change-Id: I685f000f4a5bd8a05ee6ded508cb30b78a17c1d0
|
C++
|
bsd-3-clause
|
OpenChemistry/avogadrolibs,cjh1/mongochemweb-avogadrolibs,wadejong/avogadrolibs,cjh1/mongochemweb-avogadrolibs,cjh1/mongochemweb-avogadrolibs,cjh1/mongochemweb-avogadrolibs,OpenChemistry/avogadrolibs,OpenChemistry/avogadrolibs,ghutchis/avogadrolibs,wadejong/avogadrolibs,ghutchis/avogadrolibs,ghutchis/avogadrolibs,OpenChemistry/avogadrolibs,wadejong/avogadrolibs,ghutchis/avogadrolibs,OpenChemistry/avogadrolibs,wadejong/avogadrolibs,ghutchis/avogadrolibs
|
52a05856353b0404562512b67b5496d1c618363d
|
arduino/opencr_arduino/opencr/libraries/turtlebot3/src/turtlebot3/turtlebot3_motor_driver.cpp
|
arduino/opencr_arduino/opencr/libraries/turtlebot3/src/turtlebot3/turtlebot3_motor_driver.cpp
|
/*******************************************************************************
* Copyright 2016 ROBOTIS CO., LTD.
*
* 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.
*******************************************************************************/
/* Authors: Yoonseok Pyo, Leon Jung, Darby Lim, HanCheol Cho */
#include "../../include/turtlebot3/turtlebot3_motor_driver.h"
Turtlebot3MotorDriver::Turtlebot3MotorDriver()
: baudrate_(BAUDRATE),
protocol_version_(PROTOCOL_VERSION),
left_wheel_id_(DXL_LEFT_ID),
right_wheel_id_(DXL_RIGHT_ID),
torque_(false)
{
}
Turtlebot3MotorDriver::~Turtlebot3MotorDriver()
{
close();
}
bool Turtlebot3MotorDriver::init(void)
{
DEBUG_SERIAL.begin(57600);
portHandler_ = dynamixel::PortHandler::getPortHandler(DEVICENAME);
packetHandler_ = dynamixel::PacketHandler::getPacketHandler(PROTOCOL_VERSION);
// Open port
if (portHandler_->openPort() == false)
{
DEBUG_SERIAL.println("Failed to open port");
return false;
}
// Set port baudrate
if (portHandler_->setBaudRate(baudrate_) == false)
{
DEBUG_SERIAL.println("Failed to set baud rate");
return false;
}
// Enable Dynamixel Torque
setTorque(left_wheel_id_, true);
setTorque(right_wheel_id_, true);
groupSyncWriteVelocity_ = new dynamixel::GroupSyncWrite(portHandler_, packetHandler_, ADDR_X_GOAL_VELOCITY, LEN_X_GOAL_VELOCITY);
groupSyncReadEncoder_ = new dynamixel::GroupSyncRead(portHandler_, packetHandler_, ADDR_X_PRESENT_POSITION, LEN_X_PRESENT_POSITION);
DEBUG_SERIAL.println("Dynamixel is On!");
return true;
}
bool Turtlebot3MotorDriver::setTorque(bool onoff)
{
uint8_t dxl_error = 0;
int dxl_comm_result = COMM_TX_FAIL;
torque_ = onoff;
dxl_comm_result = packetHandler_->write1ByteTxRx(portHandler_, DXL_LEFT_ID, ADDR_X_TORQUE_ENABLE, onoff, &dxl_error);
if(dxl_comm_result != COMM_SUCCESS)
{
Serial.println(packetHandler_->getTxRxResult(dxl_comm_result));
return false;
}
else if(dxl_error != 0)
{
Serial.println(packetHandler_->getRxPacketError(dxl_error));
return false;
}
dxl_comm_result = packetHandler_->write1ByteTxRx(portHandler_, DXL_RIGHT_ID, ADDR_X_TORQUE_ENABLE, onoff, &dxl_error);
if(dxl_comm_result != COMM_SUCCESS)
{
Serial.println(packetHandler_->getTxRxResult(dxl_comm_result));
return false;
}
else if(dxl_error != 0)
{
Serial.println(packetHandler_->getRxPacketError(dxl_error));
return false;
}
return true;
}
bool Turtlebot3MotorDriver::getTorque()
{
return torque_;
}
void Turtlebot3MotorDriver::close(void)
{
// Disable Dynamixel Torque
setTorque(left_wheel_id_, false);
setTorque(right_wheel_id_, false);
// Close port
portHandler_->closePort();
DEBUG_SERIAL.end();
}
bool Turtlebot3MotorDriver::readEncoder(int32_t &left_value, int32_t &right_value)
{
int dxl_comm_result = COMM_TX_FAIL; // Communication result
bool dxl_addparam_result = false; // addParam result
bool dxl_getdata_result = false; // GetParam result
// Set parameter
dxl_addparam_result = groupSyncReadEncoder_->addParam(left_wheel_id_);
if (dxl_addparam_result != true)
return false;
dxl_addparam_result = groupSyncReadEncoder_->addParam(right_wheel_id_);
if (dxl_addparam_result != true)
return false;
// Syncread present position
dxl_comm_result = groupSyncReadEncoder_->txRxPacket();
if (dxl_comm_result != COMM_SUCCESS)
Serial.println(packetHandler_->getTxRxResult(dxl_comm_result));
// Check if groupSyncRead data of Dynamixels are available
dxl_getdata_result = groupSyncReadEncoder_->isAvailable(left_wheel_id_, ADDR_X_PRESENT_POSITION, LEN_X_PRESENT_POSITION);
if (dxl_getdata_result != true)
return false;
dxl_getdata_result = groupSyncReadEncoder_->isAvailable(right_wheel_id_, ADDR_X_PRESENT_POSITION, LEN_X_PRESENT_POSITION);
if (dxl_getdata_result != true)
return false;
// Get data
left_value = groupSyncReadEncoder_->getData(left_wheel_id_, ADDR_X_PRESENT_POSITION, LEN_X_PRESENT_POSITION);
right_value = groupSyncReadEncoder_->getData(right_wheel_id_, ADDR_X_PRESENT_POSITION, LEN_X_PRESENT_POSITION);
groupSyncReadEncoder_->clearParam();
return true;
}
bool Turtlebot3MotorDriver::writeVelocity(int64_t left_value, int64_t right_value)
{
bool dxl_addparam_result;
int8_t dxl_comm_result;
int64_t value[2] = {left_value, right_value};
uint8_t data_byte[4] = {0, };
for (uint8_t index = 0; index < 2; index++)
{
data_byte[0] = DXL_LOBYTE(DXL_LOWORD(value[index]));
data_byte[1] = DXL_HIBYTE(DXL_LOWORD(value[index]));
data_byte[2] = DXL_LOBYTE(DXL_HIWORD(value[index]));
data_byte[3] = DXL_HIBYTE(DXL_HIWORD(value[index]));
dxl_addparam_result = groupSyncWriteVelocity_->addParam(index+1, (uint8_t*)&data_byte);
if (dxl_addparam_result != true)
return false;
}
dxl_comm_result = groupSyncWriteVelocity_->txPacket();
if (dxl_comm_result != COMM_SUCCESS)
{
Serial.println(packetHandler_->getTxRxResult(dxl_comm_result));
return false;
}
groupSyncWriteVelocity_->clearParam();
return true;
}
bool Turtlebot3MotorDriver::controlMotor(const float wheel_separation, float* value)
{
bool dxl_comm_result = false;
float wheel_velocity_cmd[2];
float lin_vel = value[LEFT];
float ang_vel = value[RIGHT];
wheel_velocity_cmd[LEFT] = lin_vel - (ang_vel * wheel_separation / 2);
wheel_velocity_cmd[RIGHT] = lin_vel + (ang_vel * wheel_separation / 2);
wheel_velocity_cmd[LEFT] = constrain(wheel_velocity_cmd[LEFT] * VELOCITY_CONSTANT_VALUE, -LIMIT_X_MAX_VELOCITY, LIMIT_X_MAX_VELOCITY);
wheel_velocity_cmd[RIGHT] = constrain(wheel_velocity_cmd[RIGHT] * VELOCITY_CONSTANT_VALUE, -LIMIT_X_MAX_VELOCITY, LIMIT_X_MAX_VELOCITY);
dxl_comm_result = writeVelocity((int64_t)wheel_velocity_cmd[LEFT], (int64_t)wheel_velocity_cmd[RIGHT]);
if (dxl_comm_result == false)
return false;
return true;
}
|
/*******************************************************************************
* Copyright 2016 ROBOTIS CO., LTD.
*
* 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.
*******************************************************************************/
/* Authors: Yoonseok Pyo, Leon Jung, Darby Lim, HanCheol Cho */
#include "../../include/turtlebot3/turtlebot3_motor_driver.h"
Turtlebot3MotorDriver::Turtlebot3MotorDriver()
: baudrate_(BAUDRATE),
protocol_version_(PROTOCOL_VERSION),
left_wheel_id_(DXL_LEFT_ID),
right_wheel_id_(DXL_RIGHT_ID),
torque_(false)
{
}
Turtlebot3MotorDriver::~Turtlebot3MotorDriver()
{
close();
}
bool Turtlebot3MotorDriver::init(void)
{
DEBUG_SERIAL.begin(57600);
portHandler_ = dynamixel::PortHandler::getPortHandler(DEVICENAME);
packetHandler_ = dynamixel::PacketHandler::getPacketHandler(PROTOCOL_VERSION);
// Open port
if (portHandler_->openPort() == false)
{
DEBUG_SERIAL.println("Failed to open port");
return false;
}
// Set port baudrate
if (portHandler_->setBaudRate(baudrate_) == false)
{
DEBUG_SERIAL.println("Failed to set baud rate");
return false;
}
// Enable Dynamixel Torque
setTorque(true);
groupSyncWriteVelocity_ = new dynamixel::GroupSyncWrite(portHandler_, packetHandler_, ADDR_X_GOAL_VELOCITY, LEN_X_GOAL_VELOCITY);
groupSyncReadEncoder_ = new dynamixel::GroupSyncRead(portHandler_, packetHandler_, ADDR_X_PRESENT_POSITION, LEN_X_PRESENT_POSITION);
DEBUG_SERIAL.println("Dynamixel is On!");
return true;
}
bool Turtlebot3MotorDriver::setTorque(bool onoff)
{
uint8_t dxl_error = 0;
int dxl_comm_result = COMM_TX_FAIL;
torque_ = onoff;
dxl_comm_result = packetHandler_->write1ByteTxRx(portHandler_, DXL_LEFT_ID, ADDR_X_TORQUE_ENABLE, onoff, &dxl_error);
if(dxl_comm_result != COMM_SUCCESS)
{
Serial.println(packetHandler_->getTxRxResult(dxl_comm_result));
return false;
}
else if(dxl_error != 0)
{
Serial.println(packetHandler_->getRxPacketError(dxl_error));
return false;
}
dxl_comm_result = packetHandler_->write1ByteTxRx(portHandler_, DXL_RIGHT_ID, ADDR_X_TORQUE_ENABLE, onoff, &dxl_error);
if(dxl_comm_result != COMM_SUCCESS)
{
Serial.println(packetHandler_->getTxRxResult(dxl_comm_result));
return false;
}
else if(dxl_error != 0)
{
Serial.println(packetHandler_->getRxPacketError(dxl_error));
return false;
}
return true;
}
bool Turtlebot3MotorDriver::getTorque()
{
return torque_;
}
void Turtlebot3MotorDriver::close(void)
{
// Disable Dynamixel Torque
setTorque(false);
// Close port
portHandler_->closePort();
DEBUG_SERIAL.end();
}
bool Turtlebot3MotorDriver::readEncoder(int32_t &left_value, int32_t &right_value)
{
int dxl_comm_result = COMM_TX_FAIL; // Communication result
bool dxl_addparam_result = false; // addParam result
bool dxl_getdata_result = false; // GetParam result
// Set parameter
dxl_addparam_result = groupSyncReadEncoder_->addParam(left_wheel_id_);
if (dxl_addparam_result != true)
return false;
dxl_addparam_result = groupSyncReadEncoder_->addParam(right_wheel_id_);
if (dxl_addparam_result != true)
return false;
// Syncread present position
dxl_comm_result = groupSyncReadEncoder_->txRxPacket();
if (dxl_comm_result != COMM_SUCCESS)
Serial.println(packetHandler_->getTxRxResult(dxl_comm_result));
// Check if groupSyncRead data of Dynamixels are available
dxl_getdata_result = groupSyncReadEncoder_->isAvailable(left_wheel_id_, ADDR_X_PRESENT_POSITION, LEN_X_PRESENT_POSITION);
if (dxl_getdata_result != true)
return false;
dxl_getdata_result = groupSyncReadEncoder_->isAvailable(right_wheel_id_, ADDR_X_PRESENT_POSITION, LEN_X_PRESENT_POSITION);
if (dxl_getdata_result != true)
return false;
// Get data
left_value = groupSyncReadEncoder_->getData(left_wheel_id_, ADDR_X_PRESENT_POSITION, LEN_X_PRESENT_POSITION);
right_value = groupSyncReadEncoder_->getData(right_wheel_id_, ADDR_X_PRESENT_POSITION, LEN_X_PRESENT_POSITION);
groupSyncReadEncoder_->clearParam();
return true;
}
bool Turtlebot3MotorDriver::writeVelocity(int64_t left_value, int64_t right_value)
{
bool dxl_addparam_result;
int8_t dxl_comm_result;
int64_t value[2] = {left_value, right_value};
uint8_t data_byte[4] = {0, };
for (uint8_t index = 0; index < 2; index++)
{
data_byte[0] = DXL_LOBYTE(DXL_LOWORD(value[index]));
data_byte[1] = DXL_HIBYTE(DXL_LOWORD(value[index]));
data_byte[2] = DXL_LOBYTE(DXL_HIWORD(value[index]));
data_byte[3] = DXL_HIBYTE(DXL_HIWORD(value[index]));
dxl_addparam_result = groupSyncWriteVelocity_->addParam(index+1, (uint8_t*)&data_byte);
if (dxl_addparam_result != true)
return false;
}
dxl_comm_result = groupSyncWriteVelocity_->txPacket();
if (dxl_comm_result != COMM_SUCCESS)
{
Serial.println(packetHandler_->getTxRxResult(dxl_comm_result));
return false;
}
groupSyncWriteVelocity_->clearParam();
return true;
}
bool Turtlebot3MotorDriver::controlMotor(const float wheel_separation, float* value)
{
bool dxl_comm_result = false;
float wheel_velocity_cmd[2];
float lin_vel = value[LEFT];
float ang_vel = value[RIGHT];
wheel_velocity_cmd[LEFT] = lin_vel - (ang_vel * wheel_separation / 2);
wheel_velocity_cmd[RIGHT] = lin_vel + (ang_vel * wheel_separation / 2);
wheel_velocity_cmd[LEFT] = constrain(wheel_velocity_cmd[LEFT] * VELOCITY_CONSTANT_VALUE, -LIMIT_X_MAX_VELOCITY, LIMIT_X_MAX_VELOCITY);
wheel_velocity_cmd[RIGHT] = constrain(wheel_velocity_cmd[RIGHT] * VELOCITY_CONSTANT_VALUE, -LIMIT_X_MAX_VELOCITY, LIMIT_X_MAX_VELOCITY);
dxl_comm_result = writeVelocity((int64_t)wheel_velocity_cmd[LEFT], (int64_t)wheel_velocity_cmd[RIGHT]);
if (dxl_comm_result == false)
return false;
return true;
}
|
change settorque function
|
change settorque function
|
C++
|
apache-2.0
|
ROBOTIS-GIT/OpenCR,ROBOTIS-GIT/OpenCR,ROBOTIS-GIT/OpenCR,ROBOTIS-GIT/OpenCR
|
2baf6da5f20c8dea21db19c5a46d9a73970e89d1
|
ext/oxt/thread.hpp
|
ext/oxt/thread.hpp
|
/*
* OXT - OS eXtensions for boosT
* Provides important functionality necessary for writing robust server software.
*
* Copyright (c) 2010 Phusion
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
#ifndef _OXT_THREAD_HPP_
#define _OXT_THREAD_HPP_
#include <boost/thread.hpp>
#include <boost/shared_ptr.hpp>
#include <boost/bind.hpp>
#include <boost/date_time/posix_time/posix_time_types.hpp>
#include "system_calls.hpp"
#include "backtrace.hpp"
#ifdef OXT_BACKTRACE_IS_ENABLED
#include <sstream>
#endif
#include <string>
#include <list>
#include <unistd.h>
#include <limits.h> // for PTHREAD_STACK_MIN
namespace oxt {
extern boost::mutex _next_thread_number_mutex;
extern unsigned int _next_thread_number;
/**
* Enhanced thread class with support for:
* - user-defined stack size.
* - system call interruption.
* - backtraces.
*/
class thread: public boost::thread {
private:
struct thread_data {
std::string name;
#ifdef OXT_BACKTRACE_IS_ENABLED
thread_registration *registration;
boost::mutex registration_lock;
bool done;
#endif
};
typedef boost::shared_ptr<thread_data> thread_data_ptr;
thread_data_ptr data;
void initialize_data(const std::string &thread_name) {
data = thread_data_ptr(new thread_data());
if (thread_name.empty()) {
boost::mutex::scoped_lock l(_next_thread_number_mutex);
std::stringstream str;
str << "Thread #" << _next_thread_number;
_next_thread_number++;
data->name = str.str();
} else {
data->name = thread_name;
}
#ifdef OXT_BACKTRACE_IS_ENABLED
data->registration = NULL;
data->done = false;
#endif
}
static void thread_main(boost::function<void ()> func, thread_data_ptr data) {
#ifdef OXT_BACKTRACE_IS_ENABLED
initialize_backtrace_support_for_this_thread i(data->name);
data->registration = i.registration;
#endif
#ifdef OXT_BACKTRACE_IS_ENABLED
// Put finalization code in a struct destructor,
// for exception safety.
struct finalization_routines {
thread_data_ptr &data;
finalization_routines(thread_data_ptr &data_)
: data(data_) {}
~finalization_routines() {
boost::mutex::scoped_lock l(data->registration_lock);
data->registration = NULL;
data->done = true;
}
};
finalization_routines f(data);
#endif
func();
}
public:
/**
* Create a new thread.
*
* @param func A function object which will be called as the thread's
* main function. This object must be copyable. <tt>func</tt> is
* copied into storage managed internally by the thread library,
* and that copy is invoked on a newly-created thread of execution.
* @param name A name for this thread. If an empty string is given, then
* a name will be automatically chosen.
* @param stack_size The stack size, in bytes, that the thread should
* have. If 0 is specified, the operating system's default stack
* size is used. If non-zero is specified, and the size is smaller
* than the operating system's minimum stack size, then the operating
* system's minimum stack size will be used.
* @pre func must be copyable.
* @throws boost::thread_resource_error Something went wrong during
* creation of the thread.
*/
explicit thread(boost::function<void ()> func, const std::string &name = "", unsigned int stack_size = 0) {
initialize_data(name);
set_thread_main_function(boost::bind(thread_main, func, data));
unsigned long min_stack_size;
bool stack_min_size_defined;
bool round_stack_size;
#ifdef PTHREAD_STACK_MIN
// PTHREAD_STACK_MIN may not be a constant macro so we need
// to evaluate it dynamically.
min_stack_size = PTHREAD_STACK_MIN;
stack_min_size_defined = true;
#else
// Assume minimum stack size is 128 KB.
min_stack_size = 128 * 1024;
stack_min_size_defined = false;
#endif
if (stack_size != 0 && stack_size < min_stack_size) {
stack_size = min_stack_size;
round_stack_size = !stack_min_size_defined;
} else {
round_stack_size = true;
}
if (round_stack_size) {
// Round stack size up to page boundary.
long page_size;
#if defined(_SC_PAGESIZE)
page_size = sysconf(_SC_PAGESIZE);
#elif defined(_SC_PAGE_SIZE)
page_size = sysconf(_SC_PAGE_SIZE);
#elif defined(PAGESIZE)
page_size = sysconf(PAGESIZE);
#elif defined(PAGE_SIZE)
page_size = sysconf(PAGE_SIZE);
#else
page_size = getpagesize();
#endif
if (stack_size % page_size != 0) {
stack_size = stack_size - (stack_size % page_size) + page_size;
}
}
start_thread(stack_size);
}
/**
* Return this thread's name. The name was set during construction.
*/
std::string name() const throw() {
return data->name;
}
/**
* Return the current backtrace of the thread of execution, as a string.
*/
std::string backtrace() const throw() {
#ifdef OXT_BACKTRACE_IS_ENABLED
boost::mutex::scoped_lock l(data->registration_lock);
if (data->registration == NULL) {
if (data->done) {
return " (no backtrace: thread has quit)";
} else {
return " (no backtrace: thread hasn't been started yet)";
}
} else {
spin_lock::scoped_lock l2(*data->registration->backtrace_lock);
return _format_backtrace(data->registration->backtrace);
}
#else
return " (backtrace support disabled during compile time)";
#endif
}
/**
* Return the backtraces of all oxt::thread threads, as well as that of the
* main thread, in a nicely formatted string.
*/
static std::string all_backtraces() throw() {
#ifdef OXT_BACKTRACE_IS_ENABLED
boost::mutex::scoped_lock l(_thread_registration_mutex);
list<thread_registration *>::const_iterator it;
std::stringstream result;
for (it = _registered_threads.begin(); it != _registered_threads.end(); it++) {
thread_registration *r = *it;
result << "Thread '" << r->name << "':" << endl;
spin_lock::scoped_lock l(*r->backtrace_lock);
result << _format_backtrace(r->backtrace) << endl;
}
return result.str();
#else
return "(backtrace support disabled during compile time)";
#endif
}
/**
* Interrupt the thread. This method behaves just like
* boost::thread::interrupt(), but will also respect the interruption
* points defined in oxt::syscalls.
*
* Note that an interruption request may get lost, depending on the
* current execution point of the thread. Thus, one should call this
* method in a loop, until a certain goal condition has been fulfilled.
* interrupt_and_join() is a convenience method that implements this
* pattern.
*/
void interrupt() {
int ret;
boost::thread::interrupt();
do {
ret = pthread_kill(native_handle(),
INTERRUPTION_SIGNAL);
} while (ret == EINTR);
}
/**
* Keep interrupting the thread until it's done, then join it.
*
* @throws boost::thread_interrupted The calling thread has been
* interrupted before we could join this thread.
*/
void interrupt_and_join() {
bool done = false;
while (!done) {
interrupt();
done = timed_join(boost::posix_time::millisec(10));
}
}
/**
* Keep interrupting the thread until it's done, then join it.
* This method will keep trying for at most <em>timeout</em> milliseconds.
*
* @param timeout The maximum number of milliseconds that this method
* should keep trying.
* @return True if the thread was successfully joined, false if the
* timeout has been reached.
* @throws boost::thread_interrupted The calling thread has been
* interrupted before we could join this thread.
*/
bool interrupt_and_join(unsigned int timeout) {
bool joined = false, timed_out = false;
boost::posix_time::ptime deadline =
boost::posix_time::microsec_clock::local_time() +
boost::posix_time::millisec(timeout);
while (!joined && !timed_out) {
interrupt();
joined = timed_join(boost::posix_time::millisec(10));
timed_out = !joined && boost::posix_time::microsec_clock::local_time() > deadline;
}
return joined;
}
/**
* Interrupt and join multiple threads in a way that's more efficient than calling
* interrupt_and_join() on each thread individually. It iterates over all threads,
* interrupts each one without joining it, then waits until at least one thread
* is joinable. This is repeated until all threads are joined.
*
* @param threads An array of threads to join.
* @param size The number of elements in <em>threads</em>.
* @throws boost::thread_interrupted The calling thread has been
* interrupted before all threads have been joined. Some threads
* may have been successfully joined while others haven't.
*/
static void interrupt_and_join_multiple(oxt::thread **threads, unsigned int size) {
std::list<oxt::thread *> remaining_threads;
std::list<oxt::thread *>::iterator it, current;
oxt::thread *thread;
unsigned int i;
for (i = 0; i < size; i++) {
remaining_threads.push_back(threads[i]);
}
while (!remaining_threads.empty()) {
for (it = remaining_threads.begin(); it != remaining_threads.end(); it++) {
thread = *it;
thread->interrupt();
}
for (it = remaining_threads.begin(); it != remaining_threads.end(); it++) {
thread = *it;
if (thread->timed_join(boost::posix_time::millisec(0))) {
current = it;
it--;
remaining_threads.erase(current);
}
}
if (!remaining_threads.empty()) {
syscalls::usleep(10000);
}
}
}
};
/**
* Like boost::lock_guard, but is interruptable.
*/
template<typename TimedLockable>
class interruptable_lock_guard {
private:
TimedLockable &mutex;
public:
interruptable_lock_guard(TimedLockable &m): mutex(m) {
bool locked = false;
while (!locked) {
locked = m.timed_lock(boost::posix_time::milliseconds(20));
if (!locked) {
boost::this_thread::interruption_point();
}
}
}
~interruptable_lock_guard() {
mutex.unlock();
}
};
} // namespace oxt
#endif /* _OXT_THREAD_HPP_ */
|
/*
* OXT - OS eXtensions for boosT
* Provides important functionality necessary for writing robust server software.
*
* Copyright (c) 2010 Phusion
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
#ifndef _OXT_THREAD_HPP_
#define _OXT_THREAD_HPP_
#include <boost/thread.hpp>
#include <boost/shared_ptr.hpp>
#include <boost/bind.hpp>
#include <boost/date_time/posix_time/posix_time_types.hpp>
#include "system_calls.hpp"
#include "backtrace.hpp"
#ifdef OXT_BACKTRACE_IS_ENABLED
#include <sstream>
#endif
#include <string>
#include <list>
#include <unistd.h>
#include <limits.h> // for PTHREAD_STACK_MIN
namespace oxt {
extern boost::mutex _next_thread_number_mutex;
extern unsigned int _next_thread_number;
/**
* Enhanced thread class with support for:
* - user-defined stack size.
* - system call interruption.
* - backtraces.
*/
class thread: public boost::thread {
private:
struct thread_data {
std::string name;
#ifdef OXT_BACKTRACE_IS_ENABLED
thread_registration *registration;
boost::mutex registration_lock;
bool done;
#endif
};
typedef boost::shared_ptr<thread_data> thread_data_ptr;
thread_data_ptr data;
void initialize_data(const std::string &thread_name) {
data = thread_data_ptr(new thread_data());
if (thread_name.empty()) {
boost::mutex::scoped_lock l(_next_thread_number_mutex);
std::stringstream str;
str << "Thread #" << _next_thread_number;
_next_thread_number++;
data->name = str.str();
} else {
data->name = thread_name;
}
#ifdef OXT_BACKTRACE_IS_ENABLED
data->registration = NULL;
data->done = false;
#endif
}
static void thread_main(boost::function<void ()> func, thread_data_ptr data) {
#ifdef OXT_BACKTRACE_IS_ENABLED
initialize_backtrace_support_for_this_thread i(data->name);
data->registration = i.registration;
#endif
#ifdef OXT_BACKTRACE_IS_ENABLED
// Put finalization code in a struct destructor,
// for exception safety.
struct finalization_routines {
thread_data_ptr &data;
finalization_routines(thread_data_ptr &data_)
: data(data_) {}
~finalization_routines() {
boost::mutex::scoped_lock l(data->registration_lock);
data->registration = NULL;
data->done = true;
}
};
finalization_routines f(data);
#endif
func();
}
public:
/**
* Create a new thread.
*
* @param func A function object which will be called as the thread's
* main function. This object must be copyable. <tt>func</tt> is
* copied into storage managed internally by the thread library,
* and that copy is invoked on a newly-created thread of execution.
* @param name A name for this thread. If an empty string is given, then
* a name will be automatically chosen.
* @param stack_size The stack size, in bytes, that the thread should
* have. If 0 is specified, the operating system's default stack
* size is used. If non-zero is specified, and the size is smaller
* than the operating system's minimum stack size, then the operating
* system's minimum stack size will be used.
* @pre func must be copyable.
* @throws boost::thread_resource_error Something went wrong during
* creation of the thread.
*/
explicit thread(boost::function<void ()> func, const std::string &name = "", unsigned int stack_size = 0) {
initialize_data(name);
set_thread_main_function(boost::bind(thread_main, func, data));
unsigned long min_stack_size;
bool stack_min_size_defined;
bool round_stack_size;
#ifdef PTHREAD_STACK_MIN
// PTHREAD_STACK_MIN may not be a constant macro so we need
// to evaluate it dynamically.
min_stack_size = PTHREAD_STACK_MIN;
stack_min_size_defined = true;
#else
// Assume minimum stack size is 128 KB.
min_stack_size = 128 * 1024;
stack_min_size_defined = false;
#endif
if (stack_size != 0 && stack_size < min_stack_size) {
stack_size = min_stack_size;
round_stack_size = !stack_min_size_defined;
} else {
round_stack_size = true;
}
if (round_stack_size) {
// Round stack size up to page boundary.
long page_size;
#if defined(_SC_PAGESIZE)
page_size = sysconf(_SC_PAGESIZE);
#elif defined(_SC_PAGE_SIZE)
page_size = sysconf(_SC_PAGE_SIZE);
#elif defined(PAGESIZE)
page_size = sysconf(PAGESIZE);
#elif defined(PAGE_SIZE)
page_size = sysconf(PAGE_SIZE);
#else
page_size = getpagesize();
#endif
if (stack_size % page_size != 0) {
stack_size = stack_size - (stack_size % page_size) + page_size;
}
}
start_thread(stack_size);
}
/**
* Return this thread's name. The name was set during construction.
*/
std::string name() const throw() {
return data->name;
}
/**
* Return the current backtrace of the thread of execution, as a string.
*/
std::string backtrace() const throw() {
#ifdef OXT_BACKTRACE_IS_ENABLED
boost::mutex::scoped_lock l(data->registration_lock);
if (data->registration == NULL) {
if (data->done) {
return " (no backtrace: thread has quit)";
} else {
return " (no backtrace: thread hasn't been started yet)";
}
} else {
spin_lock::scoped_lock l2(*data->registration->backtrace_lock);
return _format_backtrace(data->registration->backtrace);
}
#else
return " (backtrace support disabled during compile time)";
#endif
}
/**
* Return the backtraces of all oxt::thread threads, as well as that of the
* main thread, in a nicely formatted string.
*/
static std::string all_backtraces() throw() {
#ifdef OXT_BACKTRACE_IS_ENABLED
boost::mutex::scoped_lock l(_thread_registration_mutex);
list<thread_registration *>::const_iterator it;
std::stringstream result;
for (it = _registered_threads.begin(); it != _registered_threads.end(); it++) {
thread_registration *r = *it;
result << "Thread '" << r->name << "':" << endl;
spin_lock::scoped_lock l(*r->backtrace_lock);
result << _format_backtrace(r->backtrace) << endl;
}
return result.str();
#else
return "(backtrace support disabled during compile time)";
#endif
}
/**
* Interrupt the thread. This method behaves just like
* boost::thread::interrupt(), but if <em>interruptSyscalls</em> is true
* then it will also respect the interruption points defined in
* oxt::syscalls.
*
* Note that an interruption request may get lost, depending on the
* current execution point of the thread. Thus, one should call this
* method in a loop, until a certain goal condition has been fulfilled.
* interrupt_and_join() is a convenience method that implements this
* pattern.
*/
void interrupt(bool interruptSyscalls = true) {
int ret;
boost::thread::interrupt();
if (interruptSyscalls) {
do {
ret = pthread_kill(native_handle(),
INTERRUPTION_SIGNAL);
} while (ret == EINTR);
}
}
/**
* Keep interrupting the thread until it's done, then join it.
*
* @param interruptSyscalls Whether oxt::syscalls calls should also
* be eligable for interruption.
* @throws boost::thread_interrupted The calling thread has been
* interrupted before we could join this thread.
*/
void interrupt_and_join(bool interruptSyscalls = true) {
bool done = false;
while (!done) {
interrupt(interruptSyscalls);
done = timed_join(boost::posix_time::millisec(10));
}
}
/**
* Keep interrupting the thread until it's done, then join it.
* This method will keep trying for at most <em>timeout</em> milliseconds.
*
* @param timeout The maximum number of milliseconds that this method
* should keep trying.
* @param interruptSyscalls Whether oxt::syscalls calls should also
* be eligable for interruption.
* @return True if the thread was successfully joined, false if the
* timeout has been reached.
* @throws boost::thread_interrupted The calling thread has been
* interrupted before we could join this thread.
*/
bool interrupt_and_join(unsigned int timeout, bool interruptSyscalls = true) {
bool joined = false, timed_out = false;
boost::posix_time::ptime deadline =
boost::posix_time::microsec_clock::local_time() +
boost::posix_time::millisec(timeout);
while (!joined && !timed_out) {
interrupt(interruptSyscalls);
joined = timed_join(boost::posix_time::millisec(10));
timed_out = !joined && boost::posix_time::microsec_clock::local_time() > deadline;
}
return joined;
}
/**
* Interrupt and join multiple threads in a way that's more efficient than calling
* interrupt_and_join() on each thread individually. It iterates over all threads,
* interrupts each one without joining it, then waits until at least one thread
* is joinable. This is repeated until all threads are joined.
*
* @param threads An array of threads to join.
* @param size The number of elements in <em>threads</em>.
* @param interruptSyscalls Whether oxt::syscalls calls should also
* be eligable for interruption.
* @throws boost::thread_interrupted The calling thread has been
* interrupted before all threads have been joined. Some threads
* may have been successfully joined while others haven't.
*/
static void interrupt_and_join_multiple(oxt::thread **threads, unsigned int size,
bool interruptSyscalls = true)
{
std::list<oxt::thread *> remaining_threads;
std::list<oxt::thread *>::iterator it, current;
oxt::thread *thread;
unsigned int i;
for (i = 0; i < size; i++) {
remaining_threads.push_back(threads[i]);
}
while (!remaining_threads.empty()) {
for (it = remaining_threads.begin(); it != remaining_threads.end(); it++) {
thread = *it;
thread->interrupt(interruptSyscalls);
}
for (it = remaining_threads.begin(); it != remaining_threads.end(); it++) {
thread = *it;
if (thread->timed_join(boost::posix_time::millisec(0))) {
current = it;
it--;
remaining_threads.erase(current);
}
}
if (!remaining_threads.empty()) {
syscalls::usleep(10000);
}
}
}
};
/**
* Like boost::lock_guard, but is interruptable.
*/
template<typename TimedLockable>
class interruptable_lock_guard {
private:
TimedLockable &mutex;
public:
interruptable_lock_guard(TimedLockable &m): mutex(m) {
bool locked = false;
while (!locked) {
locked = m.timed_lock(boost::posix_time::milliseconds(20));
if (!locked) {
boost::this_thread::interruption_point();
}
}
}
~interruptable_lock_guard() {
mutex.unlock();
}
};
} // namespace oxt
#endif /* _OXT_THREAD_HPP_ */
|
Add ability not to interrupt system calls with oxt::thread.
|
Add ability not to interrupt system calls with oxt::thread.
|
C++
|
mit
|
erikogan/passenger,kewaunited/passenger,erikogan/passenger,bf4/passenger,pkmiec/passenger,gravitystorm/passenger,clemensg/passenger,jawj/passenger,openSUSE/passenger,bf4/passenger,cgvarela/passenger,antek-drzewiecki/passenger,fabiokung/passenger-debian,clemensg/passenger,openSUSE/passenger,clemensg/passenger,pkmiec/passenger,kewaunited/passenger,erikogan/passenger,phusion/passenger,clemensg/passenger,clemensg/passenger,antek-drzewiecki/passenger,pkmiec/passenger,erikogan/passenger,kewaunited/passenger,openSUSE/passenger,gravitystorm/passenger,bf4/passenger,cgvarela/passenger,jawj/passenger,phusion/passenger,phusion/passenger,cgvarela/passenger,bf4/passenger,antek-drzewiecki/passenger,antek-drzewiecki/passenger,gravitystorm/passenger,phusion/passenger,cgvarela/passenger,jawj/passenger,jawj/passenger,fabiokung/passenger-debian,gravitystorm/passenger,pkmiec/passenger,bf4/passenger,cgvarela/passenger,openSUSE/passenger,clemensg/passenger,pkmiec/passenger,erikogan/passenger,kewaunited/passenger,antek-drzewiecki/passenger,bf4/passenger,gravitystorm/passenger,clemensg/passenger,phusion/passenger,clemensg/passenger,kewaunited/passenger,gravitystorm/passenger,phusion/passenger,kewaunited/passenger,jawj/passenger,pkmiec/passenger,jawj/passenger,jawj/passenger,fabiokung/passenger-debian,antek-drzewiecki/passenger,antek-drzewiecki/passenger,kewaunited/passenger,phusion/passenger,fabiokung/passenger-debian,bf4/passenger,openSUSE/passenger,kewaunited/passenger,cgvarela/passenger,erikogan/passenger,phusion/passenger,pkmiec/passenger,cgvarela/passenger,openSUSE/passenger,antek-drzewiecki/passenger,fabiokung/passenger-debian,cgvarela/passenger,fabiokung/passenger-debian
|
1957a8d7ac88121bae2f5a68d6b26231bc333bfe
|
kmail/kmmsgpartdlg.cpp
|
kmail/kmmsgpartdlg.cpp
|
// kmmsgpartdlg.cpp
#include "kmmsgpartdlg.h"
#include "kmmsgpart.h"
#include "kmmsgbase.h"
#ifndef KRN
#include "kmglobal.h"
#endif
#ifdef KRN
#include <kapp.h>
#include "kbusyptr.h"
extern KBusyPtr *kbp;
#endif
#include "kbusyptr.h"
#include <kapp.h>
#include <kcombobox.h>
#include <qcombobox.h>
#include <qpushbutton.h>
#include <qlabel.h>
#include <qlineedit.h>
#include <qlayout.h>
#include <unistd.h>
#include <assert.h>
#include <klocale.h>
//-----------------------------------------------------------------------------
KMMsgPartDlg::KMMsgPartDlg(const char* aCaption, bool readOnly):
KMMsgPartDlgInherited(NULL, "msgpartdlg", TRUE), mIconPixmap()
{
QGridLayout* grid = new QGridLayout(this, 6, 4, 8, 8);
QPushButton *btnOk, *btnCancel;
QLabel *label;
int h, w1, w2;
mMsgPart = NULL;
if (aCaption) setCaption(aCaption);
else setCaption(i18n("Message Part Properties"));
mLblIcon = new QLabel(this);
mLblIcon->resize(32, 32);
grid->addMultiCellWidget(mLblIcon, 0, 1, 0, 0);
//-----
mEdtMimetype = new KComboBox(true, this);
mEdtMimetype->setInsertionPolicy(QComboBox::NoInsertion);
// here's only a small selection of what I think are very common mime types (dnaber, 2000-04-24):
mEdtMimetype->insertItem("text/html");
mEdtMimetype->insertItem("text/plain");
mEdtMimetype->insertItem("image/gif");
mEdtMimetype->insertItem("image/jpeg");
mEdtMimetype->insertItem("image/png");
mEdtMimetype->insertItem("application/octet-stream");
mEdtMimetype->insertItem("application/x-gunzip");
mEdtMimetype->insertItem("application/zip");
h = mEdtMimetype->sizeHint().height();
mEdtMimetype->setMinimumSize(100, h);
mEdtMimetype->setMaximumSize(1024, h);
grid->addMultiCellWidget(mEdtMimetype, 0, 0, 1, 3);
connect(mEdtMimetype, SIGNAL(textChanged(const QString &)),
SLOT(mimetypeChanged(const QString &)));
//-----
mLblSize = new QLabel(this);
mLblSize->adjustSize();
mLblSize->setMinimumSize(100, h);
grid->addMultiCellWidget(mLblSize, 1, 1, 1, 3);
//-----
label = new QLabel(i18n("Name:"), this);
label->adjustSize();
label->setMinimumSize(label->sizeHint().width(), h);
grid->addWidget(label, 2, 0);
mEdtName = new QLineEdit(this);
mEdtName->setMinimumSize(100, h);
mEdtName->setMaximumSize(1024, h);
grid->addMultiCellWidget(mEdtName, 2, 2, 1, 3);
//-----
label = new QLabel(i18n("Description:"), this);
label->adjustSize();
label->setMinimumSize(label->sizeHint().width(), h);
grid->addWidget(label, 3, 0);
mEdtComment = new QLineEdit(this);
mEdtComment->setMinimumSize(100, h);
mEdtComment->setMaximumSize(1024, h);
grid->addMultiCellWidget(mEdtComment, 3, 3, 1, 3);
label = new QLabel(i18n("Encoding:"), this);
label->adjustSize();
label->setMinimumSize(label->sizeHint().width(), h);
grid->addWidget(label, 4, 0);
mCbxEncoding = new QComboBox(this);
mCbxEncoding->insertItem(i18n("none (8bit)"));
mCbxEncoding->insertItem(i18n("base 64"));
mCbxEncoding->insertItem(i18n("quoted printable"));
mCbxEncoding->setMinimumSize(100, h);
mCbxEncoding->setMaximumSize(1024, h);
grid->addMultiCellWidget(mCbxEncoding, 4, 4, 1, 3);
if(readOnly)
{mEdtMimetype->setEnabled(FALSE);
mEdtName->setEnabled(FALSE);
mEdtComment->setEnabled(FALSE);
mCbxEncoding->setEnabled(FALSE);
}
//-----
btnOk = new QPushButton(i18n("OK"), this);
btnOk->adjustSize();
btnOk->setMinimumSize(btnOk->sizeHint());
connect(btnOk, SIGNAL(clicked()), SLOT(accept()));
grid->addMultiCellWidget(btnOk, 5, 5, 1, 1);
btnCancel = new QPushButton(i18n("Cancel"), this);
btnCancel->adjustSize();
btnCancel->setMinimumSize(btnCancel->sizeHint());
connect(btnCancel, SIGNAL(clicked()), SLOT(reject()));
grid->addMultiCellWidget(btnCancel, 5, 5, 2, 3);
h = btnOk->sizeHint().height();
w1 = btnOk->sizeHint().width();
w2 = btnCancel->sizeHint().width();
if (w1 < w2) w1 = w2;
if (w1 < 120) w1 = 120;
btnOk->setMaximumSize(w1, h);
btnCancel->setMaximumSize(w1, h);
//-----
grid->setColStretch(0, 0);
grid->setColStretch(1, 10);
grid->setColStretch(3, 10);
grid->activate();
resize(420, 190);
}
//-----------------------------------------------------------------------------
KMMsgPartDlg::~KMMsgPartDlg()
{
}
//-----------------------------------------------------------------------------
void KMMsgPartDlg::mimetypeChanged(const QString & name)
{
if (name == "message/rfc822")
{
mCbxEncoding->setCurrentItem(0);
mCbxEncoding->setEnabled(false);
} else {
mCbxEncoding->setEnabled(true);
}
}
//-----------------------------------------------------------------------------
void KMMsgPartDlg::setMsgPart(KMMessagePart* aMsgPart)
{
unsigned int len, idx;
QString lenStr, iconName, enc;
mMsgPart = aMsgPart;
assert(mMsgPart!=NULL);
enc = mMsgPart->cteStr();
if (enc=="base64") idx = 1;
else if (enc=="quoted-printable") idx = 2;
else idx = 0;
mCbxEncoding->setCurrentItem(idx);
mEdtComment->setText(mMsgPart->contentDescription());
mEdtName->setText(mMsgPart->name());
QString mimeType = mMsgPart->typeStr() + "/" + mMsgPart->subtypeStr();
mEdtMimetype->setEditText(mimeType);
mEdtMimetype->insertItem(mimeType, 0);
len = mMsgPart->size();
if (len > 9999) lenStr.sprintf("%u KB", (len>>10));
else lenStr.sprintf("%u bytes", len);
mLblSize->setText(lenStr);
iconName = mMsgPart->iconName();
mIconPixmap.load(iconName);
mLblIcon->setPixmap(mIconPixmap);
mLblIcon->resize(mIconPixmap.size());
}
//-----------------------------------------------------------------------------
void KMMsgPartDlg::applyChanges(void)
{
QString str, type, subtype;
QCString body;
int idx;
if (!mMsgPart) return;
kernel->kbp()->busy();
str = mEdtName->text();
if (!str.isEmpty() || !mMsgPart->name().isEmpty())
{
mMsgPart->setName(str);
QString encName = KMMsgBase::encodeRFC2231String(str, mMsgPart->charset());
mMsgPart->setContentDisposition(QString("attachment; filename")
+ ((str != encName) ? "*" : "") + "=\"" + encName + "\"");
}
str = mEdtComment->text();
if (!str.isEmpty() || !mMsgPart->contentDescription().isEmpty())
mMsgPart->setContentDescription(str);
if (mEdtMimetype->currentText() == "message/rfc822")
{
str = "7bit";
} else {
idx = mCbxEncoding->currentItem();
if (idx==1) str = "base64";
else if (idx==2) str = "quoted-printable";
else str = "8bit";
}
type = mEdtMimetype->currentText();
idx = type.find('/');
if (idx < 0) subtype = "";
else
{
subtype = type.mid(idx+1, 256);
type = type.left(idx);
}
mMsgPart->setTypeStr(type);
mMsgPart->setSubtypeStr(subtype);
if (str != mMsgPart->cteStr())
{
body.duplicate( mMsgPart->bodyDecoded() );
mMsgPart->setCteStr(str);
mMsgPart->setBodyEncoded(body);
}
kernel->kbp()->idle();
}
//-----------------------------------------------------------------------------
void KMMsgPartDlg::done(int rc)
{
if (rc) applyChanges();
KMMsgPartDlgInherited::done(rc);
}
//-----------------------------------------------------------------------------
#include "kmmsgpartdlg.moc"
|
// kmmsgpartdlg.cpp
#include "kmmsgpartdlg.h"
#include "kmmsgpart.h"
#include "kmmsgbase.h"
#ifndef KRN
#include "kmglobal.h"
#endif
#ifdef KRN
#include <kapp.h>
#include "kbusyptr.h"
extern KBusyPtr *kbp;
#endif
#include "kbusyptr.h"
#include <kapp.h>
#include <kcombobox.h>
#include <qcombobox.h>
#include <qpushbutton.h>
#include <qlabel.h>
#include <qlineedit.h>
#include <qlayout.h>
#include <unistd.h>
#include <assert.h>
#include <klocale.h>
//-----------------------------------------------------------------------------
KMMsgPartDlg::KMMsgPartDlg(const char* aCaption, bool readOnly):
KMMsgPartDlgInherited(NULL, "msgpartdlg", TRUE), mIconPixmap()
{
QGridLayout* grid = new QGridLayout(this, 6, 4, 8, 8);
QPushButton *btnOk, *btnCancel;
QLabel *label;
int h, w1, w2;
mMsgPart = NULL;
if (aCaption) setCaption(aCaption);
else setCaption(i18n("Message Part Properties"));
mLblIcon = new QLabel(this);
mLblIcon->resize(32, 32);
grid->addMultiCellWidget(mLblIcon, 0, 1, 0, 0);
//-----
mEdtMimetype = new KComboBox(true, this);
mEdtMimetype->setInsertionPolicy(QComboBox::NoInsertion);
// here's only a small selection of what I think are very common mime types (dnaber, 2000-04-24):
mEdtMimetype->insertItem("text/html");
mEdtMimetype->insertItem("text/plain");
mEdtMimetype->insertItem("image/gif");
mEdtMimetype->insertItem("image/jpeg");
mEdtMimetype->insertItem("image/png");
mEdtMimetype->insertItem("application/octet-stream");
mEdtMimetype->insertItem("application/x-gunzip");
mEdtMimetype->insertItem("application/zip");
h = mEdtMimetype->sizeHint().height();
mEdtMimetype->setMinimumSize(100, h);
mEdtMimetype->setMaximumSize(1024, h);
grid->addMultiCellWidget(mEdtMimetype, 0, 0, 1, 3);
connect(mEdtMimetype, SIGNAL(textChanged(const QString &)),
SLOT(mimetypeChanged(const QString &)));
//-----
mLblSize = new QLabel(this);
mLblSize->adjustSize();
mLblSize->setMinimumSize(100, h);
grid->addMultiCellWidget(mLblSize, 1, 1, 1, 3);
//-----
label = new QLabel(i18n("Name:"), this);
label->adjustSize();
label->setMinimumSize(label->sizeHint().width(), h);
grid->addWidget(label, 2, 0);
mEdtName = new QLineEdit(this);
mEdtName->setMinimumSize(100, h);
mEdtName->setMaximumSize(1024, h);
grid->addMultiCellWidget(mEdtName, 2, 2, 1, 3);
//-----
label = new QLabel(i18n("Description:"), this);
label->adjustSize();
label->setMinimumSize(label->sizeHint().width(), h);
grid->addWidget(label, 3, 0);
mEdtComment = new QLineEdit(this);
mEdtComment->setMinimumSize(100, h);
mEdtComment->setMaximumSize(1024, h);
grid->addMultiCellWidget(mEdtComment, 3, 3, 1, 3);
label = new QLabel(i18n("Encoding:"), this);
label->adjustSize();
label->setMinimumSize(label->sizeHint().width(), h);
grid->addWidget(label, 4, 0);
mCbxEncoding = new QComboBox(this);
mCbxEncoding->insertItem(i18n("none (8bit)"));
mCbxEncoding->insertItem(i18n("base 64"));
mCbxEncoding->insertItem(i18n("quoted printable"));
mCbxEncoding->setMinimumSize(100, h);
mCbxEncoding->setMaximumSize(1024, h);
grid->addMultiCellWidget(mCbxEncoding, 4, 4, 1, 3);
if(readOnly)
{mEdtMimetype->setEnabled(FALSE);
mEdtName->setEnabled(FALSE);
mEdtComment->setEnabled(FALSE);
mCbxEncoding->setEnabled(FALSE);
}
//-----
btnOk = new QPushButton(i18n("OK"), this);
btnOk->adjustSize();
btnOk->setMinimumSize(btnOk->sizeHint());
connect(btnOk, SIGNAL(clicked()), SLOT(accept()));
grid->addMultiCellWidget(btnOk, 5, 5, 1, 1);
btnCancel = new QPushButton(i18n("Cancel"), this);
btnCancel->adjustSize();
btnCancel->setMinimumSize(btnCancel->sizeHint());
connect(btnCancel, SIGNAL(clicked()), SLOT(reject()));
grid->addMultiCellWidget(btnCancel, 5, 5, 2, 3);
h = btnOk->sizeHint().height();
w1 = btnOk->sizeHint().width();
w2 = btnCancel->sizeHint().width();
if (w1 < w2) w1 = w2;
if (w1 < 120) w1 = 120;
btnOk->setMaximumSize(w1, h);
btnOk->setFocus();
btnCancel->setMaximumSize(w1, h);
//-----
grid->setColStretch(0, 0);
grid->setColStretch(1, 10);
grid->setColStretch(3, 10);
grid->activate();
resize(420, 190);
}
//-----------------------------------------------------------------------------
KMMsgPartDlg::~KMMsgPartDlg()
{
}
//-----------------------------------------------------------------------------
void KMMsgPartDlg::mimetypeChanged(const QString & name)
{
if (name == "message/rfc822")
{
mCbxEncoding->setCurrentItem(0);
mCbxEncoding->setEnabled(false);
} else {
mCbxEncoding->setEnabled(true);
}
}
//-----------------------------------------------------------------------------
void KMMsgPartDlg::setMsgPart(KMMessagePart* aMsgPart)
{
unsigned int len, idx;
QString lenStr, iconName, enc;
mMsgPart = aMsgPart;
assert(mMsgPart!=NULL);
enc = mMsgPart->cteStr();
if (enc=="base64") idx = 1;
else if (enc=="quoted-printable") idx = 2;
else idx = 0;
mCbxEncoding->setCurrentItem(idx);
mEdtComment->setText(mMsgPart->contentDescription());
mEdtName->setText(mMsgPart->name());
QString mimeType = mMsgPart->typeStr() + "/" + mMsgPart->subtypeStr();
mEdtMimetype->setEditText(mimeType);
mEdtMimetype->insertItem(mimeType, 0);
len = mMsgPart->size();
if (len > 9999) lenStr.sprintf("%u KB", (len>>10));
else lenStr.sprintf("%u bytes", len);
mLblSize->setText(lenStr);
iconName = mMsgPart->iconName();
mIconPixmap.load(iconName);
mLblIcon->setPixmap(mIconPixmap);
mLblIcon->resize(mIconPixmap.size());
}
//-----------------------------------------------------------------------------
void KMMsgPartDlg::applyChanges(void)
{
QString str, type, subtype;
QCString body;
int idx;
if (!mMsgPart) return;
kernel->kbp()->busy();
str = mEdtName->text();
if (!str.isEmpty() || !mMsgPart->name().isEmpty())
{
mMsgPart->setName(str);
QString encName = KMMsgBase::encodeRFC2231String(str, mMsgPart->charset());
mMsgPart->setContentDisposition(QString("attachment; filename")
+ ((str != encName) ? "*" : "") + "=\"" + encName + "\"");
}
str = mEdtComment->text();
if (!str.isEmpty() || !mMsgPart->contentDescription().isEmpty())
mMsgPart->setContentDescription(str);
if (mEdtMimetype->currentText() == "message/rfc822")
{
str = "7bit";
} else {
idx = mCbxEncoding->currentItem();
if (idx==1) str = "base64";
else if (idx==2) str = "quoted-printable";
else str = "8bit";
}
type = mEdtMimetype->currentText();
idx = type.find('/');
if (idx < 0) subtype = "";
else
{
subtype = type.mid(idx+1, 256);
type = type.left(idx);
}
mMsgPart->setTypeStr(type);
mMsgPart->setSubtypeStr(subtype);
if (str != mMsgPart->cteStr())
{
body.duplicate( mMsgPart->bodyDecoded() );
mMsgPart->setCteStr(str);
mMsgPart->setBodyEncoded(body);
}
kernel->kbp()->idle();
}
//-----------------------------------------------------------------------------
void KMMsgPartDlg::done(int rc)
{
if (rc) applyChanges();
KMMsgPartDlgInherited::done(rc);
}
//-----------------------------------------------------------------------------
#include "kmmsgpartdlg.moc"
|
Make the OK button the default (Lars asked for it).
|
Make the OK button the default (Lars asked for it).
diff -u -b -r1.24 kmmsgpartdlg.cpp
--- kmmsgpartdlg.cpp 2000/11/29 09:14:57 1.24
+++ kmmsgpartdlg.cpp 2001/02/07 00:53:02
@@ -132,6 +132,7 @@
if (w1 < w2) w1 = w2;
if (w1 < 120) w1 = 120;
btnOk->setMaximumSize(w1, h);
+ btnOk->setFocus();
btnCancel->setMaximumSize(w1, h);
svn path=/trunk/kdenetwork/kmail/; revision=81653
|
C++
|
lgpl-2.1
|
lefou/kdepim-noakonadi,lefou/kdepim-noakonadi,lefou/kdepim-noakonadi,lefou/kdepim-noakonadi,lefou/kdepim-noakonadi,lefou/kdepim-noakonadi
|
a5584a112a7b54f52c4e3328f560b65857842939
|
svgminifier.cpp
|
svgminifier.cpp
|
/*
SVGMin - Aggressive SVG minifier
Copyright (C) 2009 Ariya Hidayat ([email protected])
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
*/
#include "svgminifier.h"
#include <QtCore>
#include "qcssparser_p.h"
class SvgMinifier::Private
{
public:
QString inFile;
QString outFile;
bool autoFormat;
QStringList excludedTags;
QStringList excludedPrefixes;
};
SvgMinifier::SvgMinifier()
{
d = new Private;
d->autoFormat = false;
}
SvgMinifier::~SvgMinifier()
{
delete d;
}
void SvgMinifier::setInputFile(const QString &in)
{
d->inFile = in;
}
void SvgMinifier::setOutputFile(const QString &out)
{
d->outFile = out;
}
void SvgMinifier::setAutoFormat(bool format)
{
d->autoFormat = format;
}
void SvgMinifier::addTagExclude(const QString &tag)
{
d->excludedTags += tag;
}
void SvgMinifier::addPrefixExclude(const QString &prefix)
{
d->excludedPrefixes += prefix;
}
static bool listContains(const QStringList &list, const QStringRef &str)
{
if (str.isEmpty())
return false;
QString check = str.toString();
foreach (const QString &s, list)
if (s.startsWith(check))
return true;
return false;
}
static QXmlStreamAttributes parseStyle(const QStringRef &styleRef)
{
QXmlStreamAttributes attributes;
QCss::Parser parser;
parser.init(styleRef.toString());
QString key;
while (parser.hasNext()) {
parser.skipSpace();
if (!parser.hasNext())
break;
parser.next();
QString name = parser.lexem();
parser.skipSpace();
if (!parser.test(QCss::COLON))
break;
parser.skipSpace();
if (!parser.hasNext())
break;
const int firstSymbol = parser.index;
int symbolCount = 0;
do {
parser.next();
++symbolCount;
} while (parser.hasNext() && !parser.test(QCss::SEMICOLON));
QString value;
for (int i = firstSymbol; i < firstSymbol + symbolCount; ++i)
value += parser.symbols.at(i).lexem();
parser.skipSpace();
attributes.append(name, value);
}
return attributes;
}
// take the value of the "style" attribute, parse it and then
// merged the result with other XML attributes
static QXmlStreamAttributes mergedStyle(const QXmlStreamAttributes &attributes)
{
if (!attributes.hasAttribute("style"))
return attributes;
QXmlStreamAttributes result;
result.reserve(attributes.count());
foreach (const QXmlStreamAttribute &attr, attributes)
if (attr.name() != "style")
result += attr;
QXmlStreamAttributes styles = parseStyle(attributes.value("style"));
foreach (const QXmlStreamAttribute &attr, styles)
if (!attributes.hasAttribute(attr.value().toString()))
result += attr;
return result;
}
void SvgMinifier::run()
{
QFile file;
file.setFileName(d->inFile);
if (!file.open(QFile::ReadOnly))
return;
QFile result;
if (!d->outFile.isEmpty()) {
result.setFileName(d->outFile);
result.open(QFile::WriteOnly);
} else {
result.open(stdout, QFile::WriteOnly);
}
QXmlStreamReader *xml = new QXmlStreamReader(&file);
xml->setNamespaceProcessing(false);
QXmlStreamWriter *out = new QXmlStreamWriter(&result);
out->setAutoFormatting(d->autoFormat);
bool skip;
QStack<bool> skipElement;
skipElement.push(false);
while (!xml->atEnd()) {
switch (xml->readNext()) {
case QXmlStreamReader::StartDocument:
out->writeStartDocument(xml->documentVersion().toString(),
xml->isStandaloneDocument());
break;
case QXmlStreamReader::EndDocument:
out->writeEndDocument();
break;
case QXmlStreamReader::StartElement:
if (skipElement.top()) {
skipElement.push(true);
} else {
skip = listContains(d->excludedPrefixes, xml->prefix());
skip = skip || d->excludedTags.contains(xml->name().toString());
skipElement.push(skip);
if (!skip) {
out->writeStartElement(xml->qualifiedName().toString());
QXmlStreamAttributes attr = mergedStyle(xml->attributes());
foreach (const QXmlStreamAttribute &a, attr)
if (!listContains(d->excludedPrefixes, a.prefix()))
out->writeAttribute(a);
}
}
break;
case QXmlStreamReader::EndElement:
skip = skipElement.pop();
if (!skip)
out->writeEndElement();
break;
case QXmlStreamReader::Characters:
if (!skipElement.top())
out->writeCharacters(xml->text().toString());
break;
case QXmlStreamReader::ProcessingInstruction:
out->writeProcessingInstruction(xml->processingInstructionTarget().toString(),
xml->processingInstructionData().toString());
break;
default:
break;
}
}
file.close();
result.close();
}
|
/*
SVGMin - Aggressive SVG minifier
Copyright (C) 2009 Ariya Hidayat ([email protected])
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
*/
#include "svgminifier.h"
#include <QtCore>
#include "qcssparser_p.h"
class SvgMinifier::Private
{
public:
QString inFile;
QString outFile;
bool autoFormat;
QStringList excludedTags;
QStringList excludedPrefixes;
};
SvgMinifier::SvgMinifier()
{
d = new Private;
d->autoFormat = false;
}
SvgMinifier::~SvgMinifier()
{
delete d;
}
void SvgMinifier::setInputFile(const QString &in)
{
d->inFile = in;
}
void SvgMinifier::setOutputFile(const QString &out)
{
d->outFile = out;
}
void SvgMinifier::setAutoFormat(bool format)
{
d->autoFormat = format;
}
void SvgMinifier::addTagExclude(const QString &tag)
{
d->excludedTags += tag;
}
void SvgMinifier::addPrefixExclude(const QString &prefix)
{
d->excludedPrefixes += prefix;
}
static bool listContains(const QStringList &list, const QStringRef &str)
{
if (str.isEmpty())
return false;
QString check = str.toString();
foreach (const QString &s, list)
if (check.startsWith(s))
return true;
return false;
}
static QXmlStreamAttributes parseStyle(const QStringRef &styleRef)
{
QXmlStreamAttributes attributes;
QCss::Parser parser;
parser.init(styleRef.toString());
QString key;
while (parser.hasNext()) {
parser.skipSpace();
if (!parser.hasNext())
break;
parser.next();
QString name = parser.lexem();
parser.skipSpace();
if (!parser.test(QCss::COLON))
break;
parser.skipSpace();
if (!parser.hasNext())
break;
const int firstSymbol = parser.index;
int symbolCount = 0;
do {
parser.next();
++symbolCount;
} while (parser.hasNext() && !parser.test(QCss::SEMICOLON));
QString value;
for (int i = firstSymbol; i < firstSymbol + symbolCount; ++i)
value += parser.symbols.at(i).lexem();
parser.skipSpace();
attributes.append(name, value);
}
return attributes;
}
// take the value of the "style" attribute, parse it and then
// merged the result with other XML attributes
static QXmlStreamAttributes mergedStyle(const QXmlStreamAttributes &attributes)
{
if (!attributes.hasAttribute("style"))
return attributes;
QXmlStreamAttributes result;
result.reserve(attributes.count());
foreach (const QXmlStreamAttribute &attr, attributes)
if (attr.name() != "style")
result += attr;
QXmlStreamAttributes styles = parseStyle(attributes.value("style"));
foreach (const QXmlStreamAttribute &attr, styles)
if (!attributes.hasAttribute(attr.value().toString()))
result += attr;
return result;
}
void SvgMinifier::run()
{
QFile file;
file.setFileName(d->inFile);
if (!file.open(QFile::ReadOnly))
return;
QFile result;
if (!d->outFile.isEmpty()) {
result.setFileName(d->outFile);
result.open(QFile::WriteOnly);
} else {
result.open(stdout, QFile::WriteOnly);
}
QXmlStreamReader *xml = new QXmlStreamReader(&file);
xml->setNamespaceProcessing(false);
QXmlStreamWriter *out = new QXmlStreamWriter(&result);
out->setAutoFormatting(d->autoFormat);
bool skip;
QStack<bool> skipElement;
skipElement.push(false);
while (!xml->atEnd()) {
switch (xml->readNext()) {
case QXmlStreamReader::StartDocument:
out->writeStartDocument(xml->documentVersion().toString(),
xml->isStandaloneDocument());
break;
case QXmlStreamReader::EndDocument:
out->writeEndDocument();
break;
case QXmlStreamReader::StartElement:
if (skipElement.top()) {
skipElement.push(true);
} else {
skip = listContains(d->excludedPrefixes, xml->prefix());
skip = skip || d->excludedTags.contains(xml->name().toString());
skipElement.push(skip);
if (!skip) {
out->writeStartElement(xml->qualifiedName().toString());
QXmlStreamAttributes attr = mergedStyle(xml->attributes());
foreach (const QXmlStreamAttribute &a, attr)
if (!listContains(d->excludedPrefixes, a.prefix()))
out->writeAttribute(a);
}
}
break;
case QXmlStreamReader::EndElement:
skip = skipElement.pop();
if (!skip)
out->writeEndElement();
break;
case QXmlStreamReader::Characters:
if (!skipElement.top())
out->writeCharacters(xml->text().toString());
break;
case QXmlStreamReader::ProcessingInstruction:
out->writeProcessingInstruction(xml->processingInstructionTarget().toString(),
xml->processingInstructionData().toString());
break;
default:
break;
}
}
file.close();
result.close();
}
|
Fix checking the prefix in the excluded list.
|
Fix checking the prefix in the excluded list.
|
C++
|
mit
|
generaltso/svgmin,eliasp/svgmin,crazoter/svgmin
|
1057bddfef5b333c9e89bf3736f395d0834a31f7
|
test/server.cpp
|
test/server.cpp
|
/**
* Copyright (c) 2011-2015 libbitcoin developers (see AUTHORS)
*
* This file is part of libbitcoin-server.
*
* libbitcoin-server is free software: you can redistribute it and/or
* modify it under the terms of the GNU Affero General Public License with
* additional permissions to the one published by the Free Software
* Foundation, either version 3 of the License, or (at your option)
* any later version. For more information see LICENSE.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include <boost/filesystem.hpp>
#include <boost/test/unit_test.hpp>
#include <bitcoin/server.hpp>
using namespace bc;
using namespace bc::blockchain;
using namespace bc::network;
using namespace bc::node;
using namespace bc::server;
struct low_thread_priority_fixture
{
low_thread_priority_fixture()
{
set_thread_priority(thread_priority::lowest);
}
~low_thread_priority_fixture()
{
set_thread_priority(thread_priority::normal);
}
};
static void uninitchain(const char prefix[])
{
boost::filesystem::remove_all(prefix);
}
static void initchain(const char prefix[])
{
uninitchain(prefix);
boost::filesystem::create_directories(prefix);
database::initialize(prefix);
////const size_t history_height = 0;
////database::store paths(prefix);
////database interface(paths, history_height);
////const auto genesis = genesis_block();
////interface.start();
////interface.push(genesis);
}
BOOST_FIXTURE_TEST_SUITE(server_tests, low_thread_priority_fixture)
BOOST_AUTO_TEST_CASE(server_test)
{
}
BOOST_AUTO_TEST_SUITE_END()
|
/**
* Copyright (c) 2011-2015 libbitcoin developers (see AUTHORS)
*
* This file is part of libbitcoin-server.
*
* libbitcoin-server is free software: you can redistribute it and/or
* modify it under the terms of the GNU Affero General Public License with
* additional permissions to the one published by the Free Software
* Foundation, either version 3 of the License, or (at your option)
* any later version. For more information see LICENSE.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include <boost/filesystem.hpp>
#include <boost/test/unit_test.hpp>
#include <bitcoin/server.hpp>
using namespace bc;
using namespace bc::blockchain;
using namespace bc::network;
using namespace bc::node;
using namespace bc::server;
struct low_thread_priority_fixture
{
low_thread_priority_fixture()
{
set_thread_priority(thread_priority::lowest);
}
~low_thread_priority_fixture()
{
set_thread_priority(thread_priority::normal);
}
};
static void uninitchain(const char prefix[])
{
boost::filesystem::remove_all(prefix);
}
static void initchain(const char prefix[])
{
uninitchain(prefix);
boost::filesystem::create_directories(prefix);
database::initialize(prefix, mainnet_genesis_block());
}
BOOST_FIXTURE_TEST_SUITE(server_tests, low_thread_priority_fixture)
BOOST_AUTO_TEST_CASE(server_test)
{
}
BOOST_AUTO_TEST_SUITE_END()
|
Fix test parameterization.
|
Fix test parameterization.
|
C++
|
agpl-3.0
|
RojavaCrypto/libbitcoin-server,RojavaCrypto/libbitcoin-server,RojavaCrypto/libbitcoin-server
|
37c3f117fe1c3c49d67c86900fc842c233b4b606
|
src/nostalgia/core/userland/gfx_opengl.cpp
|
src/nostalgia/core/userland/gfx_opengl.cpp
|
/*
* Copyright 2016 - 2021 [email protected]
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/.
*/
#include <array>
#include <ox/std/bit.hpp>
#include <ox/std/defines.hpp>
#include <ox/std/fmt.hpp>
#include <nostalgia/core/config.hpp>
#include <nostalgia/core/gfx.hpp>
#include "glutils.hpp"
namespace nostalgia::core {
namespace renderer {
constexpr auto TileRows = 128;
constexpr auto TileColumns = 128;
constexpr auto TileCount = TileRows * TileColumns;
constexpr auto BgVertexVboRows = 4;
constexpr auto BgVertexVboRowLength = 4;
constexpr auto BgVertexVboLength = BgVertexVboRows * BgVertexVboRowLength;
constexpr auto BgVertexEboLength = 6;
struct Background {
VertexArray vao;
Buffer vbo;
Buffer ebo;
Texture tex;
bool enabled = false;
bool updated = false;
std::array<float, TileCount * BgVertexVboLength> bgVertices;
std::array<GLuint, TileCount * BgVertexEboLength> bgElements;
};
struct GlImplData {
Program bgShader;
int64_t prevFpsCheckTime = 0;
uint64_t draws = 0;
std::array<Background, 4> backgrounds;
};
constexpr const GLchar *bgvshad = R"(
#version 150
in vec2 vTexCoord;
in vec2 position;
out vec2 fTexCoord;
uniform float vTileHeight;
void main() {
gl_Position = vec4(position, 0.0, 1.0);
fTexCoord = vTexCoord * vec2(1, vTileHeight);
})";
constexpr const GLchar *bgfshad = R"(
#version 150
out vec4 outColor;
in vec2 fTexCoord;
uniform sampler2D image;
void main() {
//outColor = vec4(0.0, 0.7, 1.0, 1.0);
outColor = texture(image, fTexCoord);
})";
[[nodiscard]]
static constexpr auto bgVertexRow(unsigned x, unsigned y) noexcept {
return y * TileRows + x;
}
static void setTileBufferObject(Context *ctx, unsigned vi, float x, float y, int textureRow, float *vbo, GLuint *ebo) {
// don't worry, this memcpy gets optimized to something much more ideal
const auto [sw, sh] = getScreenSize(ctx);
constexpr float ymod = 2.0f / 20.0f;
const float xmod = ymod * static_cast<float>(sh) / static_cast<float>(sw);
x *= xmod;
y *= -ymod;
x -= 1.0f;
y += 1.0f - ymod;
const float vertices[BgVertexVboLength] = {
x, y, 0, static_cast<float>(textureRow + 1), // bottom left
x + xmod, y, 1, static_cast<float>(textureRow + 1), // bottom right
x + xmod, y + ymod, 1, static_cast<float>(textureRow + 0), // top right
x, y + ymod, 0, static_cast<float>(textureRow + 0), // top left
};
memcpy(vbo, vertices, sizeof(vertices));
const GLuint elms[BgVertexEboLength] = {
vi + 0, vi + 1, vi + 2,
vi + 2, vi + 3, vi + 0,
};
memcpy(ebo, elms, sizeof(elms));
}
static void sendVbo(const Background &bg) noexcept {
// vbo
glBindBuffer(GL_ARRAY_BUFFER, bg.vbo);
glBufferData(GL_ARRAY_BUFFER, sizeof(bg.bgVertices), &bg.bgVertices, GL_DYNAMIC_DRAW);
}
static void sendEbo(const Background &bg) noexcept {
// ebo
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, bg.ebo);
glBufferData(GL_ELEMENT_ARRAY_BUFFER, sizeof(bg.bgElements), &bg.bgElements, GL_STATIC_DRAW);
}
static void initBackgroundBufferObjects(Context *ctx, Background *bg) noexcept {
for (auto x = 0u; x < TileColumns; ++x) {
for (auto y = 0u; y < TileRows; ++y) {
const auto i = bgVertexRow(x, y);
auto vbo = &bg->bgVertices[i * BgVertexVboLength];
auto ebo = &bg->bgElements[i * BgVertexEboLength];
setTileBufferObject(ctx, i * BgVertexVboRows, x, y, 0, vbo, ebo);
}
}
}
static VertexArray genVertexArrayObject() noexcept {
GLuint vao = 0;
glGenVertexArrays(1, &vao);
return VertexArray(vao);
}
static Buffer genBuffer() noexcept {
GLuint buff = 0;
glGenBuffers(1, &buff);
return Buffer(buff);
}
static void initBackgroundBufferset(Context *ctx, GLuint shader, Background *bg) {
// vao
bg->vao = genVertexArrayObject();
glBindVertexArray(bg->vao);
// vbo & ebo
bg->vbo = genBuffer();
bg->ebo = genBuffer();
initBackgroundBufferObjects(ctx, bg);
sendVbo(*bg);
sendEbo(*bg);
// vbo layout
auto posAttr = static_cast<GLuint>(glGetAttribLocation(shader, "position"));
glEnableVertexAttribArray(posAttr);
glVertexAttribPointer(posAttr, 2, GL_FLOAT, GL_FALSE, BgVertexVboRowLength * sizeof(float), 0);
auto texCoordAttr = static_cast<GLuint>(glGetAttribLocation(shader, "vTexCoord"));
glEnableVertexAttribArray(texCoordAttr);
glVertexAttribPointer(texCoordAttr, 2, GL_FLOAT, GL_FALSE, BgVertexVboRowLength * sizeof(float),
ox::bit_cast<void*>(2 * sizeof(float)));
}
static Texture loadTexture(GLsizei w, GLsizei h, void *pixels) {
GLuint texId = 0;
glGenTextures(1, &texId);
Texture tex(texId);
tex.width = w;
tex.height = h;
glActiveTexture(GL_TEXTURE0);
glBindTexture(GL_TEXTURE_2D, tex.id);
glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, tex.width, tex.height, 0, GL_RGBA, GL_UNSIGNED_BYTE, pixels);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
return ox::move(tex);
}
static void tickFps(GlImplData *id) {
++id->draws;
if (id->draws >= 500) {
using namespace std::chrono;
const auto now = duration_cast<milliseconds>(system_clock::now().time_since_epoch()).count();
const auto duration = static_cast<double>(now - id->prevFpsCheckTime) / 1000.0;
const auto fps = static_cast<int>(static_cast<double>(id->draws) / duration);
if constexpr(config::UserlandFpsPrint) {
oxInfof("FPS: {}", fps);
}
oxTracef("nostalgia::core::gfx::gl::fps", "FPS: {}", fps);
id->prevFpsCheckTime = now;
id->draws = 0;
}
}
static void drawBackground(Background *bg) {
if (bg->enabled) {
glBindVertexArray(bg->vao);
if (bg->updated) {
bg->updated = false;
renderer::sendVbo(*bg);
}
glBindTexture(GL_TEXTURE_2D, bg->tex);
glDrawElements(GL_TRIANGLES, bg->bgElements.size(), GL_UNSIGNED_INT, 0);
}
}
static void drawBackgrounds(GlImplData *id) {
// load background shader and its uniforms
glUseProgram(id->bgShader);
const auto uniformTileHeight = static_cast<GLint>(glGetUniformLocation(id->bgShader, "vTileHeight"));
for (auto &bg : id->backgrounds) {
glUniform1f(uniformTileHeight, 1.0f / static_cast<float>(bg.tex.height / 8));
drawBackground(&bg);
}
}
ox::Error init(Context *ctx) {
const auto id = new GlImplData;
ctx->setRendererData(id);
oxReturnError(buildShaderProgram(bgvshad, bgfshad).moveTo(&id->bgShader));
for (auto &bg : id->backgrounds) {
initBackgroundBufferset(ctx, id->bgShader, &bg);
}
return OxError(0);
}
ox::Error shutdown(Context *ctx) {
const auto id = ctx->rendererData<GlImplData>();
ctx->setRendererData(nullptr);
delete id;
return OxError(0);
}
ox::Error loadBgTexture(Context *ctx, int section, void *pixels, int w, int h) {
oxTracef("nostalgia::core::gfx::gl", "loadBgTexture: { section: {}, w: {}, h: {} }", section, w, h);
const auto &id = ctx->rendererData<GlImplData>();
auto &tex = id->backgrounds[static_cast<std::size_t>(section)].tex;
tex = loadTexture(w, h, pixels);
return OxError(0);
}
}
uint8_t bgStatus(Context *ctx) {
const auto &id = ctx->rendererData<renderer::GlImplData>();
uint8_t out = 0;
for (unsigned i = 0; i < id->backgrounds.size(); ++i) {
out |= id->backgrounds[i].enabled << i;
}
return out;
}
void setBgStatus(Context *ctx, uint32_t status) {
const auto &id = ctx->rendererData<renderer::GlImplData>();
for (unsigned i = 0; i < id->backgrounds.size(); ++i) {
id->backgrounds[i].enabled = (status >> i) & 1;
}
}
bool bgStatus(Context *ctx, unsigned bg) {
const auto &id = ctx->rendererData<renderer::GlImplData>();
return id->backgrounds[bg].enabled;
}
void setBgStatus(Context *ctx, unsigned bg, bool status) {
const auto &id = ctx->rendererData<renderer::GlImplData>();
id->backgrounds[bg].enabled = status;
}
void draw(Context *ctx) {
const auto id = ctx->rendererData<renderer::GlImplData>();
renderer::tickFps(id);
// clear screen
glClearColor(0, 0, 0, 1);
glClear(GL_COLOR_BUFFER_BIT);
// render
renderer::drawBackgrounds(id);
}
void clearTileLayer(Context *ctx, int layer) {
const auto id = ctx->rendererData<renderer::GlImplData>();
auto &bg = id->backgrounds[static_cast<std::size_t>(layer)];
initBackgroundBufferObjects(ctx, &bg);
bg.updated = true;
}
void hideSprite(Context*, unsigned) {
}
void setSprite(Context*,
unsigned,
unsigned,
unsigned,
unsigned,
unsigned,
unsigned,
unsigned) {
}
void setTile(Context *ctx, int layer, int column, int row, uint8_t tile) {
const auto id = ctx->rendererData<renderer::GlImplData>();
const auto z = static_cast<unsigned>(layer);
const auto y = static_cast<unsigned>(row);
const auto x = static_cast<unsigned>(column);
const auto i = renderer::bgVertexRow(x, y);
auto &bg = id->backgrounds[z];
auto vbo = &bg.bgVertices[i * renderer::BgVertexVboLength];
auto ebo = &bg.bgElements[i * renderer::BgVertexEboLength];
renderer::setTileBufferObject(ctx, i * renderer::BgVertexVboRows, x, y, tile, vbo, ebo);
bg.updated = true;
}
}
|
/*
* Copyright 2016 - 2021 [email protected]
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/.
*/
#include <array>
#include <ox/std/bit.hpp>
#include <ox/std/fmt.hpp>
#include <nostalgia/core/config.hpp>
#include <nostalgia/core/gfx.hpp>
#include "glutils.hpp"
namespace nostalgia::core {
namespace renderer {
constexpr auto TileRows = 128;
constexpr auto TileColumns = 128;
constexpr auto TileCount = TileRows * TileColumns;
constexpr auto BgVertexVboRows = 4;
constexpr auto BgVertexVboRowLength = 4;
constexpr auto BgVertexVboLength = BgVertexVboRows * BgVertexVboRowLength;
constexpr auto BgVertexEboLength = 6;
struct Background {
VertexArray vao;
Buffer vbo;
Buffer ebo;
Texture tex;
bool enabled = false;
bool updated = false;
std::array<float, TileCount * BgVertexVboLength> bgVertices = {};
std::array<GLuint, TileCount * BgVertexEboLength> bgElements = {};
};
struct GlImplData {
Program bgShader;
int64_t prevFpsCheckTime = 0;
uint64_t draws = 0;
std::array<Background, 4> backgrounds;
};
constexpr const GLchar *bgvshad = R"(
#version 150
in vec2 vTexCoord;
in vec2 position;
out vec2 fTexCoord;
uniform float vTileHeight;
void main() {
gl_Position = vec4(position, 0.0, 1.0);
fTexCoord = vTexCoord * vec2(1, vTileHeight);
})";
constexpr const GLchar *bgfshad = R"(
#version 150
out vec4 outColor;
in vec2 fTexCoord;
uniform sampler2D image;
void main() {
//outColor = vec4(0.0, 0.7, 1.0, 1.0);
outColor = texture(image, fTexCoord);
})";
[[nodiscard]]
static constexpr auto bgVertexRow(unsigned x, unsigned y) noexcept {
return y * TileRows + x;
}
static void setTileBufferObject(Context *ctx, unsigned vi, float x, float y, int textureRow, float *vbo, GLuint *ebo) {
// don't worry, this memcpy gets optimized to something much more ideal
const auto [sw, sh] = getScreenSize(ctx);
constexpr float ymod = 2.0f / 20.0f;
const float xmod = ymod * static_cast<float>(sh) / static_cast<float>(sw);
x *= xmod;
y *= -ymod;
x -= 1.0f;
y += 1.0f - ymod;
const float vertices[BgVertexVboLength] = {
x, y, 0, static_cast<float>(textureRow + 1), // bottom left
x + xmod, y, 1, static_cast<float>(textureRow + 1), // bottom right
x + xmod, y + ymod, 1, static_cast<float>(textureRow + 0), // top right
x, y + ymod, 0, static_cast<float>(textureRow + 0), // top left
};
memcpy(vbo, vertices, sizeof(vertices));
const GLuint elms[BgVertexEboLength] = {
vi + 0, vi + 1, vi + 2,
vi + 2, vi + 3, vi + 0,
};
memcpy(ebo, elms, sizeof(elms));
}
static void sendVbo(const Background &bg) noexcept {
// vbo
glBindBuffer(GL_ARRAY_BUFFER, bg.vbo);
glBufferData(GL_ARRAY_BUFFER, sizeof(bg.bgVertices), &bg.bgVertices, GL_DYNAMIC_DRAW);
}
static void sendEbo(const Background &bg) noexcept {
// ebo
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, bg.ebo);
glBufferData(GL_ELEMENT_ARRAY_BUFFER, sizeof(bg.bgElements), &bg.bgElements, GL_STATIC_DRAW);
}
static void initBackgroundBufferObjects(Context *ctx, Background *bg) noexcept {
for (auto x = 0u; x < TileColumns; ++x) {
for (auto y = 0u; y < TileRows; ++y) {
const auto i = bgVertexRow(x, y);
auto vbo = &bg->bgVertices[i * BgVertexVboLength];
auto ebo = &bg->bgElements[i * BgVertexEboLength];
setTileBufferObject(ctx, i * BgVertexVboRows, x, y, 0, vbo, ebo);
}
}
}
static VertexArray genVertexArrayObject() noexcept {
GLuint vao = 0;
glGenVertexArrays(1, &vao);
return VertexArray(vao);
}
static Buffer genBuffer() noexcept {
GLuint buff = 0;
glGenBuffers(1, &buff);
return Buffer(buff);
}
static void initBackgroundBufferset(Context *ctx, GLuint shader, Background *bg) {
// vao
bg->vao = genVertexArrayObject();
glBindVertexArray(bg->vao);
// vbo & ebo
bg->vbo = genBuffer();
bg->ebo = genBuffer();
initBackgroundBufferObjects(ctx, bg);
sendVbo(*bg);
sendEbo(*bg);
// vbo layout
auto posAttr = static_cast<GLuint>(glGetAttribLocation(shader, "position"));
glEnableVertexAttribArray(posAttr);
glVertexAttribPointer(posAttr, 2, GL_FLOAT, GL_FALSE, BgVertexVboRowLength * sizeof(float), nullptr);
auto texCoordAttr = static_cast<GLuint>(glGetAttribLocation(shader, "vTexCoord"));
glEnableVertexAttribArray(texCoordAttr);
glVertexAttribPointer(texCoordAttr, 2, GL_FLOAT, GL_FALSE, BgVertexVboRowLength * sizeof(float),
ox::bit_cast<void*>(2 * sizeof(float)));
}
static Texture loadTexture(GLsizei w, GLsizei h, void *pixels) {
GLuint texId = 0;
glGenTextures(1, &texId);
Texture tex(texId);
tex.width = w;
tex.height = h;
glActiveTexture(GL_TEXTURE0);
glBindTexture(GL_TEXTURE_2D, tex.id);
glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, tex.width, tex.height, 0, GL_RGBA, GL_UNSIGNED_BYTE, pixels);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
return ox::move(tex);
}
static void tickFps(GlImplData *id) {
++id->draws;
if (id->draws >= 500) {
using namespace std::chrono;
const auto now = duration_cast<milliseconds>(system_clock::now().time_since_epoch()).count();
const auto duration = static_cast<double>(now - id->prevFpsCheckTime) / 1000.0;
const auto fps = static_cast<int>(static_cast<double>(id->draws) / duration);
if constexpr(config::UserlandFpsPrint) {
oxInfof("FPS: {}", fps);
}
oxTracef("nostalgia::core::gfx::gl::fps", "FPS: {}", fps);
id->prevFpsCheckTime = now;
id->draws = 0;
}
}
static void drawBackground(Background *bg) {
if (bg->enabled) {
glBindVertexArray(bg->vao);
if (bg->updated) {
bg->updated = false;
renderer::sendVbo(*bg);
}
glBindTexture(GL_TEXTURE_2D, bg->tex);
glDrawElements(GL_TRIANGLES, bg->bgElements.size(), GL_UNSIGNED_INT, 0);
}
}
static void drawBackgrounds(GlImplData *id) {
// load background shader and its uniforms
glUseProgram(id->bgShader);
const auto uniformTileHeight = static_cast<GLint>(glGetUniformLocation(id->bgShader, "vTileHeight"));
for (auto &bg : id->backgrounds) {
glUniform1f(uniformTileHeight, 1.0f / static_cast<float>(bg.tex.height / 8));
drawBackground(&bg);
}
}
ox::Error init(Context *ctx) {
const auto id = new GlImplData;
ctx->setRendererData(id);
oxReturnError(buildShaderProgram(bgvshad, bgfshad).moveTo(&id->bgShader));
for (auto &bg : id->backgrounds) {
initBackgroundBufferset(ctx, id->bgShader, &bg);
}
return OxError(0);
}
ox::Error shutdown(Context *ctx) {
const auto id = ctx->rendererData<GlImplData>();
ctx->setRendererData(nullptr);
delete id;
return OxError(0);
}
ox::Error loadBgTexture(Context *ctx, int section, void *pixels, int w, int h) {
oxTracef("nostalgia::core::gfx::gl", "loadBgTexture: { section: {}, w: {}, h: {} }", section, w, h);
const auto &id = ctx->rendererData<GlImplData>();
auto &tex = id->backgrounds[static_cast<std::size_t>(section)].tex;
tex = loadTexture(w, h, pixels);
return OxError(0);
}
}
uint8_t bgStatus(Context *ctx) {
const auto &id = ctx->rendererData<renderer::GlImplData>();
uint8_t out = 0;
for (unsigned i = 0; i < id->backgrounds.size(); ++i) {
out |= id->backgrounds[i].enabled << i;
}
return out;
}
void setBgStatus(Context *ctx, uint32_t status) {
const auto &id = ctx->rendererData<renderer::GlImplData>();
for (unsigned i = 0; i < id->backgrounds.size(); ++i) {
id->backgrounds[i].enabled = (status >> i) & 1;
}
}
bool bgStatus(Context *ctx, unsigned bg) {
const auto &id = ctx->rendererData<renderer::GlImplData>();
return id->backgrounds[bg].enabled;
}
void setBgStatus(Context *ctx, unsigned bg, bool status) {
const auto &id = ctx->rendererData<renderer::GlImplData>();
id->backgrounds[bg].enabled = status;
}
void draw(Context *ctx) {
const auto id = ctx->rendererData<renderer::GlImplData>();
renderer::tickFps(id);
// clear screen
glClearColor(0, 0, 0, 1);
glClear(GL_COLOR_BUFFER_BIT);
// render
renderer::drawBackgrounds(id);
}
void clearTileLayer(Context *ctx, int layer) {
const auto id = ctx->rendererData<renderer::GlImplData>();
auto &bg = id->backgrounds[static_cast<std::size_t>(layer)];
initBackgroundBufferObjects(ctx, &bg);
bg.updated = true;
}
void hideSprite(Context*, unsigned) {
}
void setSprite(Context*,
unsigned,
unsigned,
unsigned,
unsigned,
unsigned,
unsigned,
unsigned) {
}
void setTile(Context *ctx, int layer, int column, int row, uint8_t tile) {
const auto id = ctx->rendererData<renderer::GlImplData>();
const auto z = static_cast<unsigned>(layer);
const auto y = static_cast<unsigned>(row);
const auto x = static_cast<unsigned>(column);
const auto i = renderer::bgVertexRow(x, y);
auto &bg = id->backgrounds[z];
auto vbo = &bg.bgVertices[i * renderer::BgVertexVboLength];
auto ebo = &bg.bgElements[i * renderer::BgVertexEboLength];
renderer::setTileBufferObject(ctx, i * renderer::BgVertexVboRows, x, y, tile, vbo, ebo);
bg.updated = true;
}
}
|
Initialize buffers
|
[nostalgia/core/gl] Initialize buffers
|
C++
|
mpl-2.0
|
wombatant/nostalgia,wombatant/nostalgia,wombatant/nostalgia
|
edd7915d8fe2eb2650f9f83034bb0a8bda886f44
|
test/test-1.cpp
|
test/test-1.cpp
|
#include "Course.h"
#include <iomanip>
#include <iostream>
#include <string>
using namespace std;
int main() {
// main prompt
bool isOpen = false;
Course course;
string input;
cout << " _____ __ ___ __ \n";
cout << " / ___/______ ____/ /__ ____/ _ \\/ /_ _____\n";
cout << "/ (_ / __/ _ `/ _ / -_)___/ ___/ / // (_-<\n";
cout << "\\___/_/ \\_,_/\\_,_/\\__/ /_/ /_/\\_,_/___/\n\n";
// input loop
while (true) {
cout << "What would you like to do?\n";
cout << "\tWORK on an existing Course [W]\n\tCREATE a new Course [C]\n\tQUIT [Q]\n\t$: ";
getline(cin, input);
// open Course
if (tolower(input[0]) == 'w') {
cout << "Which Course: ";
getline(cin, input);
string name = input;
cout << "Opening Course: " << name << "...\n";
course.load(name);
isOpen = true;
break;
}
// create Course
else if (tolower(input[0]) == 'c') {
cout << "Please enter a unique name\n";
cout << "Course Name: ";
getline(cin, input);
string name = input;
cout << "Creating Course: " << name << endl;
course.load(name);
isOpen = true;
break;
}
// quit
else if (tolower(input[0]) == 'q') {
cout << "Goodbye\n";
break;
}
// invalid
else {
cout << "Invalid entry: " << input << endl;
}
} // opening loop
// second loop while the course is open
while (isOpen) {
cout << "\nCourse Name: " << course.getName() << "\n";
cout << "\tSELECT students [S]\n\tSELECT assignments "
"[A]\n\tSELECT categories [C]\n\tSELECT submissions [B]\n\tQUIT "
"[Q]\n\t$: ";
getline(cin, input);
// students handler
if (tolower(input[0]) == 's' || tolower(input[0]) == 'S') {
while (true) {
course.printStudents();
cout << "\tADD student [A]\n\tREMOVE student [R]\n\tUP [U]\n\tQUIT [Q]\n\t$: ";
getline(cin, input);
// add student
if (tolower(input[0]) == 'a') {
cout << "Student ID?: ";
getline(cin, input);
string id = input;
cout << "Student first name?: ";
getline(cin, input);
string firstName = input;
cout << "Student last name?: ";
getline(cin, input);
string lastName = input;
cout << "Student name: " << firstName << " " << lastName
<< " Student ID: " << id << endl;
course.addStudent(id, firstName, lastName);
}
// modify student
else if (tolower(input[0]) == 'a') {
cout << "Student ID: ";
getline(cin, input);
string id = input;
cout << "Student first name (or press enter to keep current one): ";
getline(cin, input);
string firstName = input;
cout << "Student last name (or press enter to keep current one): ";
getline(cin, input);
string lastName = input;
cout << "Student name: " << firstName << " " << lastName
<< " Student ID: " << id << endl;
course.updateStudent(id, firstName, lastName);
}
// drop student
else if (tolower(input[0]) == 'r') {
cout << "Remove student with ID: ";
getline(cin, input);
string id = input;
// call drop student function on that student
course.deleteStudent(id);
}
// up
else if (tolower(input[0]) == 'u') {
break;
}
// quit
else if (tolower(input[0]) == 'q') {
cout << "Goodbye\n";
isOpen = false;
break;
}
}
}
// ASSIGNMENTS HANDLER
else if (tolower(input[0]) == 'a') {
while (true) {
course.printAssignments();
cout << "\tADD assignment [A]\n\tREMOVE assignment [R]\n\tMODIFY "
"assignment [M]\n\tUP [U]\n\tQUIT [Q]\n\t$: ";
getline(cin, input);
// add assignment
if (tolower(input[0]) == 'a') {
cout << "Adding a new assignment:\n";
cout << "Assignment name: ";
getline(cin, input);
string name = input;
course.printCategories();
cout << "Category ID: ";
getline(cin, input);
int category = input.size() ? stoi(input) : -1;
cout << "Points possible: ";
getline(cin, input);
int weight = input.size() ? stoi(input) : -1;
course.addAssignment(category, name, weight);
}
// modify assignment
else if (tolower(input[0]) == 'm') {
cout << "Modify assignment with ID: ";
getline(cin, input);
int id = input.size() ? stoi(input) : -1;
cout << "Assignment name (or press enter to keep current one): ";
getline(cin, input);
string name = input;
course.printCategories();
cout << "Category ID (or press enter to keep current one): ";
getline(cin, input);
int category = input.size() ? stoi(input) : -1;
cout << "Points possible (or press enter to keep current one): ";
getline(cin, input);
int weight = input.size() ? stoi(input) : -1;
course.updateAssignment(id, category, name, weight);
}
// remove assignment
else if (tolower(input[0]) == 'r') {
cout << "Remove assignment with ID: ";
getline(cin, input);
int id = input.size() ? stoi(input) : -1;
course.deleteAssignment(id);
}
// up
else if (tolower(input[0]) == 'u') {
break;
}
// quit
else if (tolower(input[0]) == 'q') {
cout << "Goodbye\n";
isOpen = false;
break;
}
// invalid
else {
cout << "Invalid entry: " << input << endl;
}
}
}
// CATEGORIES HANDLER
else if (tolower(input[0]) == 'c') {
while (true) {
course.printCategories();
cout << "\tADD category [A]\n\tREMOVE category [R]\n\tMODIFY category "
"[M]\n\tUP [U]\n\tQUIT [Q]\n\t$: ";
getline(cin, input);
// add category
if (tolower(input[0]) == 'a') {
cout << "Adding a new category:\n";
cout << "Category name: ";
getline(cin, input);
string name = input;
cout << "Weight: ";
getline(cin, input);
int weight = input.size() ? stoi(input) : -1;
course.addCategory(name, weight);
}
// modify category
else if (tolower(input[0]) == 'm') {
cout << "Modify category with ID: ";
getline(cin, input);
int id = input.size() ? stoi(input) : -1;
cout << "Category name (or press enter to keep current one): ";
getline(cin, input);
string name = input;
cout << "Weight (or press enter to keep current one): ";
getline(cin, input);
int weight = input.size() ? stoi(input) : -1;
course.updateCategory(id, name, weight);
}
// remove category
else if (tolower(input[0]) == 'r') {
cout << "Remove category with ID: ";
getline(cin, input);
int id = input.size() ? stoi(input) : -1;
course.deleteCategory(id);
}
// up
else if (tolower(input[0]) == 'u') {
break;
}
// quit
else if (tolower(input[0]) == 'q') {
cout << "Goodbye\n";
isOpen = false;
break;
}
// invalid
else {
cout << "Invalid entry: " << input << endl;
}
}
}
// SUBMITTED HANDLER
else if (tolower(input[0]) == 'b') {
while (true) {
course.printSubmitted();
char option;
do {
cout << "\tSELECT student [S]\n\tSELECT assignment [T]\n\tADD "
"submission [A]\n\tREMOVE submission [R]\n\tMODIFY submission "
"[M]\n\tGRADE submission [G]\n\tUP [U]\n\tQUIT [Q]\n\t$: ";
getline(cin, input);
// filter by student
option = tolower(input[0]);
if (option == 's') {
cout << "Student ID: ";
getline(cin, input);
string studentId = input;
course.printSubmittedOfStudent(studentId);
}
// filter by assignment
else if (option == 't') {
cout << "Assignment ID: ";
getline(cin, input);
int assignmentId = input.size() ? stoi(input) : -1;
course.printSubmittedOfAssignment(assignmentId);
}
} while (option == 's' || option == 't');
// add submitted
if (tolower(input[0]) == 'a') {
cout << "Adding a new submission:\n";
course.printAssignments();
cout << "Assignment ID: ";
getline(cin, input);
int assignmentId = input.size() ? stoi(input) : -1;
course.printStudents();
cout << "Student ID: ";
getline(cin, input);
string studentId = input;
course.addSubmitted(assignmentId, studentId, NULL);
}
// modify submitted
else if (tolower(input[0]) == 'm') {
cout << "Modify submission with ID: ";
getline(cin, input);
int id = input.size() ? stoi(input) : -1;
course.printAssignments();
cout << "Assignment ID (or press enter to keep current one): ";
getline(cin, input);
int assignmentId = input.size() ? stoi(input) : -1;
course.printStudents();
cout << "Student ID (or press enter to keep current one): ";
getline(cin, input);
string studentId = input;
course.updateSubmitted(id, assignmentId, studentId, NULL);
}
// remove submitted
else if (tolower(input[0]) == 'r') {
cout << "Remove submission with ID: ";
getline(cin, input);
int id = input.size() ? stoi(input) : -1;
course.deleteSubmitted(id);
}
// grade submitted
else if (tolower(input[0]) == 'g') {
cout << "Grade submission with ID: ";
getline(cin, input);
int id = input.size() ? stoi(input) : -1;
cout << "Points earned: ";
getline(cin, input);
double pointsEarned = stod(input);
course.updateSubmitted(id, -1, "", pointsEarned);
}
// up
else if (tolower(input[0]) == 'u') {
break;
}
// quit
else if (tolower(input[0]) == 'q') {
cout << "Goodbye\n";
isOpen = false;
break;
}
// invalid
else {
cout << "Invalid entry: " << input << endl;
}
}
}
// quit
else if (tolower(input[0]) == 'q') {
cout << "Goodbye\n";
isOpen = false;
}
// else invalid
else {
cout << "Invalid entry: " << input << endl;
}
} // while course is open
}
|
#include "Course.h"
#include <iomanip>
#include <iostream>
#include <string>
using namespace std;
int main() {
// main prompt
bool isOpen = false;
Course course;
string input;
cout << " _____ __ ___ __ \n";
cout << " / ___/______ ____/ /__ ____/ _ \\/ /_ _____\n";
cout << "/ (_ / __/ _ `/ _ / -_)___/ ___/ / // (_-<\n";
cout << "\\___/_/ \\_,_/\\_,_/\\__/ /_/ /_/\\_,_/___/\n\n";
// input loop
while (true) {
cout << "What would you like to do?\n";
cout << "\tWORK on an existing Course [W]\n\tCREATE a new Course [C]\n\tQUIT [Q]\n\t$: ";
getline(cin, input);
// open Course
if (tolower(input[0]) == 'w') {
cout << "Which Course: ";
getline(cin, input);
string name = input;
cout << "Opening Course: " << name << "...\n";
course.load(name);
isOpen = true;
break;
}
// create Course
else if (tolower(input[0]) == 'c') {
cout << "Please enter a unique name\n";
cout << "Course Name: ";
getline(cin, input);
string name = input;
cout << "Creating Course: " << name << endl;
course.load(name);
isOpen = true;
break;
}
// quit
else if (tolower(input[0]) == 'q') {
cout << "Goodbye\n";
break;
}
// invalid
else {
cout << "Invalid entry: " << input << endl;
}
} // opening loop
// second loop while the course is open
while (isOpen) {
cout << "\nCourse Name: " << course.getName() << "\n";
cout << "\tSELECT students [S]\n\tSELECT assignments "
"[A]\n\tSELECT categories [C]\n\tSELECT submissions [B]\n\tQUIT "
"[Q]\n\t$: ";
getline(cin, input);
// students handler
if (tolower(input[0]) == 's' || tolower(input[0]) == 'S') {
while (true) {
course.printStudents();
cout << "\tADD student [A]\n\tREMOVE student [R]\n\tUP [U]\n\tQUIT [Q]\n\t$: ";
getline(cin, input);
// add student
if (tolower(input[0]) == 'a') {
cout << "Student ID?: ";
getline(cin, input);
string id = input;
cout << "Student first name?: ";
getline(cin, input);
string firstName = input;
cout << "Student last name?: ";
getline(cin, input);
string lastName = input;
cout << "Student name: " << firstName << " " << lastName
<< " Student ID: " << id << endl;
course.addStudent(id, firstName, lastName);
}
// modify student
else if (tolower(input[0]) == 'a') {
cout << "Student ID: ";
getline(cin, input);
string id = input;
cout << "Student first name (or press enter to keep current one): ";
getline(cin, input);
string firstName = input;
cout << "Student last name (or press enter to keep current one): ";
getline(cin, input);
string lastName = input;
cout << "Student name: " << firstName << " " << lastName
<< " Student ID: " << id << endl;
course.updateStudent(id, firstName, lastName);
}
// drop student
else if (tolower(input[0]) == 'r') {
cout << "Remove student with ID: ";
getline(cin, input);
string id = input;
// call drop student function on that student
course.deleteStudent(id);
}
// up
else if (tolower(input[0]) == 'u') {
break;
}
// quit
else if (tolower(input[0]) == 'q') {
cout << "Goodbye\n";
isOpen = false;
break;
}
}
}
// ASSIGNMENTS HANDLER
else if (tolower(input[0]) == 'a') {
while (true) {
course.printAssignments();
cout << "\tADD assignment [A]\n\tREMOVE assignment [R]\n\tMODIFY "
"assignment [M]\n\tUP [U]\n\tQUIT [Q]\n\t$: ";
getline(cin, input);
// add assignment
if (tolower(input[0]) == 'a') {
cout << "Adding a new assignment:\n";
cout << "Assignment name: ";
getline(cin, input);
string name = input;
course.printCategories();
cout << "Category ID: ";
getline(cin, input);
int category = input.size() ? stoi(input) : -1;
cout << "Points possible: ";
getline(cin, input);
int weight = input.size() ? stoi(input) : -1;
course.addAssignment(category, name, weight);
}
// modify assignment
else if (tolower(input[0]) == 'm') {
cout << "Modify assignment with ID: ";
getline(cin, input);
int id = input.size() ? stoi(input) : -1;
cout << "Assignment name (or press enter to keep current one): ";
getline(cin, input);
string name = input;
course.printCategories();
cout << "Category ID (or press enter to keep current one): ";
getline(cin, input);
int category = input.size() ? stoi(input) : -1;
cout << "Points possible (or press enter to keep current one): ";
getline(cin, input);
int weight = input.size() ? stoi(input) : -1;
course.updateAssignment(id, category, name, weight);
}
// remove assignment
else if (tolower(input[0]) == 'r') {
cout << "Remove assignment with ID: ";
getline(cin, input);
int id = input.size() ? stoi(input) : -1;
course.deleteAssignment(id);
}
// up
else if (tolower(input[0]) == 'u') {
break;
}
// quit
else if (tolower(input[0]) == 'q') {
cout << "Goodbye\n";
isOpen = false;
break;
}
// invalid
else {
cout << "Invalid entry: " << input << endl;
}
}
}
// CATEGORIES HANDLER
else if (tolower(input[0]) == 'c') {
while (true) {
course.printCategories();
cout << "\tADD category [A]\n\tREMOVE category [R]\n\tMODIFY category "
"[M]\n\tUP [U]\n\tQUIT [Q]\n\t$: ";
getline(cin, input);
// add category
if (tolower(input[0]) == 'a') {
cout << "Adding a new category:\n";
cout << "Category name: ";
getline(cin, input);
string name = input;
cout << "Weight: ";
getline(cin, input);
int weight = input.size() ? stoi(input) : -1;
course.addCategory(name, weight);
}
// modify category
else if (tolower(input[0]) == 'm') {
cout << "Modify category with ID: ";
getline(cin, input);
int id = input.size() ? stoi(input) : -1;
cout << "Category name (or press enter to keep current one): ";
getline(cin, input);
string name = input;
cout << "Weight (or press enter to keep current one): ";
getline(cin, input);
int weight = input.size() ? stoi(input) : -1;
course.updateCategory(id, name, weight);
}
// remove category
else if (tolower(input[0]) == 'r') {
cout << "Remove category with ID: ";
getline(cin, input);
int id = input.size() ? stoi(input) : -1;
course.deleteCategory(id);
}
// up
else if (tolower(input[0]) == 'u') {
break;
}
// quit
else if (tolower(input[0]) == 'q') {
cout << "Goodbye\n";
isOpen = false;
break;
}
// invalid
else {
cout << "Invalid entry: " << input << endl;
}
}
}
// SUBMITTED HANDLER
else if (tolower(input[0]) == 'b') {
while (true) {
course.printSubmitted();
char option;
do {
cout << "\tSELECT student [S]\n\tSELECT assignment [T]\n\tADD "
"submission [A]\n\tREMOVE submission [R]\n\tMODIFY submission "
"[M]\n\tGRADE submission [G]\n\tUP [U]\n\tQUIT [Q]\n\t$: ";
getline(cin, input);
// filter by student
option = tolower(input[0]);
if (option == 's') {
cout << "Student ID: ";
getline(cin, input);
string studentId = input;
course.printSubmittedOfStudent(studentId);
}
// filter by assignment
else if (option == 't') {
cout << "Assignment ID: ";
getline(cin, input);
int assignmentId = input.size() ? stoi(input) : -1;
course.printSubmittedOfAssignment(assignmentId);
}
} while (option == 's' || option == 't');
// add submitted
if (tolower(input[0]) == 'a') {
cout << "Adding a new submission:\n";
course.printAssignments();
cout << "Assignment ID: ";
getline(cin, input);
int assignmentId = input.size() ? stoi(input) : -1;
course.printStudents();
cout << "Student ID: ";
getline(cin, input);
string studentId = input;
course.addSubmitted(assignmentId, studentId, 0);
}
// modify submitted
else if (tolower(input[0]) == 'm') {
cout << "Modify submission with ID: ";
getline(cin, input);
int id = input.size() ? stoi(input) : -1;
course.printAssignments();
cout << "Assignment ID (or press enter to keep current one): ";
getline(cin, input);
int assignmentId = input.size() ? stoi(input) : -1;
course.printStudents();
cout << "Student ID (or press enter to keep current one): ";
getline(cin, input);
string studentId = input;
course.updateSubmitted(id, assignmentId, studentId, 0);
}
// remove submitted
else if (tolower(input[0]) == 'r') {
cout << "Remove submission with ID: ";
getline(cin, input);
int id = input.size() ? stoi(input) : -1;
course.deleteSubmitted(id);
}
// grade submitted
else if (tolower(input[0]) == 'g') {
cout << "Grade submission with ID: ";
getline(cin, input);
int id = input.size() ? stoi(input) : -1;
cout << "Points earned: ";
getline(cin, input);
double pointsEarned = stod(input);
course.updateSubmitted(id, -1, "", pointsEarned);
}
// up
else if (tolower(input[0]) == 'u') {
break;
}
// quit
else if (tolower(input[0]) == 'q') {
cout << "Goodbye\n";
isOpen = false;
break;
}
// invalid
else {
cout << "Invalid entry: " << input << endl;
}
}
}
// quit
else if (tolower(input[0]) == 'q') {
cout << "Goodbye\n";
isOpen = false;
}
// else invalid
else {
cout << "Invalid entry: " << input << endl;
}
} // while course is open
}
|
fix test1
|
fix test1
|
C++
|
mit
|
honestcomrade/grade-plus
|
250c9df113e723694b638789872cee1e648e4205
|
test/test04.cxx
|
test/test04.cxx
|
#include <cerrno>
#include <cstring>
#include <ctime>
#include "test_helpers.hxx"
using namespace std;
using namespace pqxx;
// Example program for libpqxx. Send notification to self.
namespace
{
int Backend_PID = 0;
// Sample implementation of notification receiver.
class TestListener final : public notification_receiver
{
bool m_done;
public:
explicit TestListener(connection_base &C) :
notification_receiver(C, "listen"), m_done(false) {}
virtual void operator()(const string &, int be_pid) override
{
m_done = true;
PQXX_CHECK_EQUAL(
be_pid,
Backend_PID,
"Notification came from wrong backend process.");
}
bool done() const { return m_done; }
};
void test_004(transaction_base &T)
{
T.abort();
connection_base &conn{T.conn()};
TestListener L(conn);
// Trigger our notification receiver.
perform(
[&conn, &L]()
{
work T(conn);
T.exec("NOTIFY \"" + L.channel() + "\"");
Backend_PID = conn.backendpid();
T.commit();
});
int notifs = 0;
for (int i=0; (i < 20) and not L.done(); ++i)
{
PQXX_CHECK_EQUAL(notifs, 0, "Got unexpected notifications.");
// Sleep one second using a libpqxx-internal function. Kids, don't try
// this at home! The pqxx::internal namespace is not for third-party use
// and may change radically at any time.
pqxx::internal::sleep_seconds(1);
notifs = T.conn().get_notifs();
}
PQXX_CHECK_NOT_EQUAL(L.done(), false, "No notification received.");
PQXX_CHECK_EQUAL(notifs, 1, "Got too many notifications.");
}
} // namespace
PQXX_REGISTER_TEST_T(test_004, nontransaction)
|
#include <cerrno>
#include <cstring>
#include <ctime>
#include "test_helpers.hxx"
using namespace std;
using namespace pqxx;
// Example program for libpqxx. Send notification to self.
namespace
{
int Backend_PID = 0;
// Sample implementation of notification receiver.
class TestListener final : public notification_receiver
{
bool m_done;
public:
explicit TestListener(connection_base &C) :
notification_receiver(C, "listen"), m_done(false) {}
virtual void operator()(const string &, int be_pid) override
{
m_done = true;
PQXX_CHECK_EQUAL(
be_pid,
Backend_PID,
"Notification came from wrong backend process.");
}
bool done() const { return m_done; }
};
void test_004(transaction_base &T)
{
T.abort();
connection_base &conn{T.conn()};
TestListener L(conn);
// Trigger our notification receiver.
perform(
[&conn, &L]()
{
work tx(conn);
tx.exec("NOTIFY \"" + L.channel() + "\"");
Backend_PID = conn.backendpid();
tx.commit();
});
int notifs = 0;
for (int i=0; (i < 20) and not L.done(); ++i)
{
PQXX_CHECK_EQUAL(notifs, 0, "Got unexpected notifications.");
// Sleep one second using a libpqxx-internal function. Kids, don't try
// this at home! The pqxx::internal namespace is not for third-party use
// and may change radically at any time.
pqxx::internal::sleep_seconds(1);
notifs = T.conn().get_notifs();
}
PQXX_CHECK_NOT_EQUAL(L.done(), false, "No notification received.");
PQXX_CHECK_EQUAL(notifs, 1, "Got too many notifications.");
}
} // namespace
PQXX_REGISTER_TEST_T(test_004, nontransaction)
|
Fix compile warning.
|
Fix compile warning.
|
C++
|
bsd-3-clause
|
jtv/libpqxx,jtv/libpqxx,jtv/libpqxx,jtv/libpqxx
|
050fdf9d5204558af9329db2b656250f3d6fe98b
|
src/plugins/coreplugin/variablechooser.cpp
|
src/plugins/coreplugin/variablechooser.cpp
|
/**************************************************************************
**
** This file is part of Qt Creator
**
** Copyright (c) 2010 Nokia Corporation and/or its subsidiary(-ies).
**
** Contact: Nokia Corporation ([email protected])
**
**
** GNU Lesser General Public License Usage
**
** This file may be used under the terms of the GNU Lesser General Public
** License version 2.1 as published by the Free Software Foundation and
** appearing in the file LICENSE.LGPL included in the packaging of this file.
** Please review the following information to ensure the GNU Lesser General
** Public License version 2.1 requirements will be met:
** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, Nokia gives you certain additional
** rights. These rights are described in the Nokia Qt LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
** Other Usage
**
** Alternatively, this file may be used in accordance with the terms and
** conditions contained in a signed written agreement between you and Nokia.
**
** If you have questions regarding the use of this file, please contact
** Nokia at [email protected].
**
**************************************************************************/
#include "variablechooser.h"
#include "ui_variablechooser.h"
#include "variablemanager.h"
#include "coreconstants.h"
#include <QtCore/QTimer>
using namespace Core;
VariableChooser::VariableChooser(QWidget *parent) :
QWidget(parent),
ui(new Ui::VariableChooser),
m_lineEdit(0),
m_textEdit(0),
m_plainTextEdit(0)
{
ui->setupUi(this);
m_defaultDescription = ui->variableDescription->text();
ui->variableList->setAttribute(Qt::WA_MacSmallSize);
ui->variableList->setAttribute(Qt::WA_MacShowFocusRect, false);
ui->variableDescription->setAttribute(Qt::WA_MacSmallSize);
setWindowFlags(Qt::Tool | Qt::WindowStaysOnTopHint);
setFocusProxy(ui->variableList);
VariableManager *vm = VariableManager::instance();
foreach (const QString &variable, vm->variables()) {
ui->variableList->addItem(variable);
}
connect(ui->variableList, SIGNAL(currentTextChanged(QString)),
this, SLOT(updateDescription(QString)));
connect(ui->variableList, SIGNAL(itemActivated(QListWidgetItem*)),
this, SLOT(handleItemActivated(QListWidgetItem*)));
connect(qApp, SIGNAL(focusChanged(QWidget*,QWidget*)),
this, SLOT(updateCurrentEditor(QWidget*,QWidget*)));
updateCurrentEditor(0, qApp->focusWidget());
}
VariableChooser::~VariableChooser()
{
delete m_iconButton;
delete ui;
}
void VariableChooser::updateDescription(const QString &variable)
{
if (variable.isNull())
ui->variableDescription->setText(m_defaultDescription);
else
ui->variableDescription->setText(VariableManager::instance()->variableDescription(variable));
}
void VariableChooser::updateCurrentEditor(QWidget *old, QWidget *widget)
{
Q_UNUSED(old)
if (!widget) // we might loose focus, but then keep the previous state
return;
// prevent children of the chooser itself, and limit to children of chooser's parent
bool handle = false;
QWidget *parent = widget;
while (parent) {
if (parent == this)
return;
if (parent == this->parentWidget()) {
handle = true;
break;
}
parent = parent->parentWidget();
}
if (!handle)
return;
QLineEdit *previousLineEdit = m_lineEdit;
m_lineEdit = 0;
m_textEdit = 0;
m_plainTextEdit = 0;
QVariant variablesSupportProperty = widget->property(Constants::VARIABLE_SUPPORT_PROPERTY);
bool supportsVariables = (variablesSupportProperty.isValid()
? variablesSupportProperty.toBool() : false);
if (QLineEdit *lineEdit = qobject_cast<QLineEdit *>(widget)) {
m_lineEdit = (supportsVariables ? lineEdit : 0);
} else if (QTextEdit *textEdit = qobject_cast<QTextEdit *>(widget)) {
m_textEdit = (supportsVariables ? textEdit : 0);
} else if (QPlainTextEdit *plainTextEdit = qobject_cast<QPlainTextEdit *>(widget)) {
m_plainTextEdit = (supportsVariables ? plainTextEdit : 0);
}
if (!(m_lineEdit || m_textEdit || m_plainTextEdit))
hide();
if (m_lineEdit != previousLineEdit) {
if (previousLineEdit)
previousLineEdit->setTextMargins(0, 0, 0, 0);
if (m_iconButton) {
m_iconButton->hide();
m_iconButton->setParent(0);
}
if (m_lineEdit) {
if (!m_iconButton)
createIconButton();
int margin = m_iconButton->pixmap().width() + 8;
if (style()->inherits("OxygenStyle"))
margin = qMax(24, margin);
m_lineEdit->setTextMargins(0, 0, margin, 0);
m_iconButton->setParent(m_lineEdit);
m_iconButton->setGeometry(m_lineEdit->rect().adjusted(
m_lineEdit->width() - (margin + 4), 0, 0, 0));
m_iconButton->show();
}
}
}
void VariableChooser::createIconButton()
{
m_iconButton = new Utils::IconButton;
m_iconButton->setPixmap(QPixmap(QLatin1String(":/core/images/replace.png")));
m_iconButton->setToolTip(tr("Insert variable"));
m_iconButton->hide();
connect(m_iconButton, SIGNAL(clicked()), this, SLOT(updatePositionAndShow()));
}
void VariableChooser::updatePositionAndShow()
{
if (parentWidget()) {
QPoint parentCenter = parentWidget()->mapToGlobal(parentWidget()->geometry().center());
move(parentCenter.x() - width()/2, parentCenter.y() - height()/2);
}
show();
}
void VariableChooser::handleItemActivated(QListWidgetItem *item)
{
if (item)
insertVariable(item->text());
}
void VariableChooser::insertVariable(const QString &variable)
{
const QString &text = QLatin1String("%{") + variable + QLatin1String("}");
if (m_lineEdit) {
m_lineEdit->insert(text);
m_lineEdit->activateWindow();
} else if (m_textEdit) {
m_textEdit->insertPlainText(text);
m_textEdit->activateWindow();
} else if (m_plainTextEdit) {
m_plainTextEdit->insertPlainText(text);
m_plainTextEdit->activateWindow();
}
}
void VariableChooser::keyPressEvent(QKeyEvent *ke)
{
if (ke->key() == Qt::Key_Escape && !ke->modifiers()) {
ke->accept();
QTimer::singleShot(0, this, SLOT(close()));
}
}
|
/**************************************************************************
**
** This file is part of Qt Creator
**
** Copyright (c) 2010 Nokia Corporation and/or its subsidiary(-ies).
**
** Contact: Nokia Corporation ([email protected])
**
**
** GNU Lesser General Public License Usage
**
** This file may be used under the terms of the GNU Lesser General Public
** License version 2.1 as published by the Free Software Foundation and
** appearing in the file LICENSE.LGPL included in the packaging of this file.
** Please review the following information to ensure the GNU Lesser General
** Public License version 2.1 requirements will be met:
** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, Nokia gives you certain additional
** rights. These rights are described in the Nokia Qt LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
** Other Usage
**
** Alternatively, this file may be used in accordance with the terms and
** conditions contained in a signed written agreement between you and Nokia.
**
** If you have questions regarding the use of this file, please contact
** Nokia at [email protected].
**
**************************************************************************/
#include "variablechooser.h"
#include "ui_variablechooser.h"
#include "variablemanager.h"
#include "coreconstants.h"
#include <QtCore/QTimer>
using namespace Core;
VariableChooser::VariableChooser(QWidget *parent) :
QWidget(parent),
ui(new Ui::VariableChooser),
m_lineEdit(0),
m_textEdit(0),
m_plainTextEdit(0)
{
ui->setupUi(this);
m_defaultDescription = ui->variableDescription->text();
ui->variableList->setAttribute(Qt::WA_MacSmallSize);
ui->variableList->setAttribute(Qt::WA_MacShowFocusRect, false);
ui->variableDescription->setAttribute(Qt::WA_MacSmallSize);
setWindowFlags(Qt::Tool | Qt::WindowStaysOnTopHint);
setFocusPolicy(Qt::StrongFocus);
setFocusProxy(ui->variableList);
VariableManager *vm = VariableManager::instance();
foreach (const QString &variable, vm->variables()) {
ui->variableList->addItem(variable);
}
connect(ui->variableList, SIGNAL(currentTextChanged(QString)),
this, SLOT(updateDescription(QString)));
connect(ui->variableList, SIGNAL(itemActivated(QListWidgetItem*)),
this, SLOT(handleItemActivated(QListWidgetItem*)));
connect(qApp, SIGNAL(focusChanged(QWidget*,QWidget*)),
this, SLOT(updateCurrentEditor(QWidget*,QWidget*)));
updateCurrentEditor(0, qApp->focusWidget());
}
VariableChooser::~VariableChooser()
{
delete m_iconButton;
delete ui;
}
void VariableChooser::updateDescription(const QString &variable)
{
if (variable.isNull())
ui->variableDescription->setText(m_defaultDescription);
else
ui->variableDescription->setText(VariableManager::instance()->variableDescription(variable));
}
void VariableChooser::updateCurrentEditor(QWidget *old, QWidget *widget)
{
Q_UNUSED(old)
if (!widget) // we might loose focus, but then keep the previous state
return;
// prevent children of the chooser itself, and limit to children of chooser's parent
bool handle = false;
QWidget *parent = widget;
while (parent) {
if (parent == this)
return;
if (parent == this->parentWidget()) {
handle = true;
break;
}
parent = parent->parentWidget();
}
if (!handle)
return;
QLineEdit *previousLineEdit = m_lineEdit;
m_lineEdit = 0;
m_textEdit = 0;
m_plainTextEdit = 0;
QVariant variablesSupportProperty = widget->property(Constants::VARIABLE_SUPPORT_PROPERTY);
bool supportsVariables = (variablesSupportProperty.isValid()
? variablesSupportProperty.toBool() : false);
if (QLineEdit *lineEdit = qobject_cast<QLineEdit *>(widget)) {
m_lineEdit = (supportsVariables ? lineEdit : 0);
} else if (QTextEdit *textEdit = qobject_cast<QTextEdit *>(widget)) {
m_textEdit = (supportsVariables ? textEdit : 0);
} else if (QPlainTextEdit *plainTextEdit = qobject_cast<QPlainTextEdit *>(widget)) {
m_plainTextEdit = (supportsVariables ? plainTextEdit : 0);
}
if (!(m_lineEdit || m_textEdit || m_plainTextEdit))
hide();
if (m_lineEdit != previousLineEdit) {
if (previousLineEdit)
previousLineEdit->setTextMargins(0, 0, 0, 0);
if (m_iconButton) {
m_iconButton->hide();
m_iconButton->setParent(0);
}
if (m_lineEdit) {
if (!m_iconButton)
createIconButton();
int margin = m_iconButton->pixmap().width() + 8;
if (style()->inherits("OxygenStyle"))
margin = qMax(24, margin);
m_lineEdit->setTextMargins(0, 0, margin, 0);
m_iconButton->setParent(m_lineEdit);
m_iconButton->setGeometry(m_lineEdit->rect().adjusted(
m_lineEdit->width() - (margin + 4), 0, 0, 0));
m_iconButton->show();
}
}
}
void VariableChooser::createIconButton()
{
m_iconButton = new Utils::IconButton;
m_iconButton->setPixmap(QPixmap(QLatin1String(":/core/images/replace.png")));
m_iconButton->setToolTip(tr("Insert variable"));
m_iconButton->hide();
connect(m_iconButton, SIGNAL(clicked()), this, SLOT(updatePositionAndShow()));
}
void VariableChooser::updatePositionAndShow()
{
if (parentWidget()) {
QPoint parentCenter = parentWidget()->mapToGlobal(parentWidget()->geometry().center());
move(parentCenter.x() - width()/2, parentCenter.y() - height()/2);
}
show();
raise();
activateWindow();
}
void VariableChooser::handleItemActivated(QListWidgetItem *item)
{
if (item)
insertVariable(item->text());
}
void VariableChooser::insertVariable(const QString &variable)
{
const QString &text = QLatin1String("%{") + variable + QLatin1String("}");
if (m_lineEdit) {
m_lineEdit->insert(text);
m_lineEdit->activateWindow();
} else if (m_textEdit) {
m_textEdit->insertPlainText(text);
m_textEdit->activateWindow();
} else if (m_plainTextEdit) {
m_plainTextEdit->insertPlainText(text);
m_plainTextEdit->activateWindow();
}
}
void VariableChooser::keyPressEvent(QKeyEvent *ke)
{
if (ke->key() == Qt::Key_Escape && !ke->modifiers()) {
ke->accept();
QTimer::singleShot(0, this, SLOT(close()));
}
}
|
Set focus to variable chooser when it opens.
|
Set focus to variable chooser when it opens.
Task-number: QTCREATORBUG-4307
Change-Id: I8dff162c01ced12f1b715ce6c803f7b611625abf
Reviewed-on: http://codereview.qt.nokia.com/918
Reviewed-by: Qt Sanity Bot <[email protected]>
Reviewed-by: Robert Löhning <[email protected]>
|
C++
|
lgpl-2.1
|
KDE/android-qt-creator,danimo/qt-creator,richardmg/qtcreator,xianian/qt-creator,maui-packages/qt-creator,xianian/qt-creator,maui-packages/qt-creator,AltarBeastiful/qt-creator,ostash/qt-creator-i18n-uk,dmik/qt-creator-os2,syntheticpp/qt-creator,darksylinc/qt-creator,hdweiss/qt-creator-visualizer,dmik/qt-creator-os2,hdweiss/qt-creator-visualizer,Distrotech/qtcreator,colede/qtcreator,azat/qtcreator,duythanhphan/qt-creator,duythanhphan/qt-creator,danimo/qt-creator,maui-packages/qt-creator,amyvmiwei/qt-creator,dmik/qt-creator-os2,xianian/qt-creator,malikcjm/qtcreator,danimo/qt-creator,kuba1/qtcreator,duythanhphan/qt-creator,richardmg/qtcreator,darksylinc/qt-creator,omniacreator/qtcreator,martyone/sailfish-qtcreator,KDE/android-qt-creator,hdweiss/qt-creator-visualizer,KDE/android-qt-creator,kuba1/qtcreator,bakaiadam/collaborative_qt_creator,colede/qtcreator,KDE/android-qt-creator,jonnor/qt-creator,kuba1/qtcreator,jonnor/qt-creator,farseerri/git_code,farseerri/git_code,duythanhphan/qt-creator,Distrotech/qtcreator,syntheticpp/qt-creator,duythanhphan/qt-creator,martyone/sailfish-qtcreator,dmik/qt-creator-os2,KDE/android-qt-creator,farseerri/git_code,azat/qtcreator,jonnor/qt-creator,duythanhphan/qt-creator,KDAB/KDAB-Creator,maui-packages/qt-creator,richardmg/qtcreator,dmik/qt-creator-os2,omniacreator/qtcreator,Distrotech/qtcreator,bakaiadam/collaborative_qt_creator,malikcjm/qtcreator,richardmg/qtcreator,ostash/qt-creator-i18n-uk,danimo/qt-creator,darksylinc/qt-creator,AltarBeastiful/qt-creator,ostash/qt-creator-i18n-uk,kuba1/qtcreator,malikcjm/qtcreator,colede/qtcreator,hdweiss/qt-creator-visualizer,xianian/qt-creator,bakaiadam/collaborative_qt_creator,farseerri/git_code,KDE/android-qt-creator,Distrotech/qtcreator,amyvmiwei/qt-creator,darksylinc/qt-creator,ostash/qt-creator-i18n-uk,omniacreator/qtcreator,martyone/sailfish-qtcreator,martyone/sailfish-qtcreator,farseerri/git_code,maui-packages/qt-creator,KDAB/KDAB-Creator,jonnor/qt-creator,KDAB/KDAB-Creator,omniacreator/qtcreator,KDAB/KDAB-Creator,azat/qtcreator,ostash/qt-creator-i18n-uk,kuba1/qtcreator,farseerri/git_code,bakaiadam/collaborative_qt_creator,azat/qtcreator,AltarBeastiful/qt-creator,syntheticpp/qt-creator,maui-packages/qt-creator,maui-packages/qt-creator,malikcjm/qtcreator,omniacreator/qtcreator,duythanhphan/qt-creator,richardmg/qtcreator,xianian/qt-creator,bakaiadam/collaborative_qt_creator,azat/qtcreator,AltarBeastiful/qt-creator,Distrotech/qtcreator,danimo/qt-creator,kuba1/qtcreator,syntheticpp/qt-creator,darksylinc/qt-creator,omniacreator/qtcreator,KDE/android-qt-creator,amyvmiwei/qt-creator,darksylinc/qt-creator,kuba1/qtcreator,AltarBeastiful/qt-creator,malikcjm/qtcreator,danimo/qt-creator,hdweiss/qt-creator-visualizer,ostash/qt-creator-i18n-uk,AltarBeastiful/qt-creator,dmik/qt-creator-os2,danimo/qt-creator,syntheticpp/qt-creator,farseerri/git_code,martyone/sailfish-qtcreator,ostash/qt-creator-i18n-uk,xianian/qt-creator,syntheticpp/qt-creator,AltarBeastiful/qt-creator,KDAB/KDAB-Creator,amyvmiwei/qt-creator,colede/qtcreator,kuba1/qtcreator,darksylinc/qt-creator,darksylinc/qt-creator,xianian/qt-creator,Distrotech/qtcreator,martyone/sailfish-qtcreator,omniacreator/qtcreator,colede/qtcreator,farseerri/git_code,malikcjm/qtcreator,bakaiadam/collaborative_qt_creator,kuba1/qtcreator,KDAB/KDAB-Creator,jonnor/qt-creator,amyvmiwei/qt-creator,danimo/qt-creator,azat/qtcreator,danimo/qt-creator,jonnor/qt-creator,martyone/sailfish-qtcreator,KDE/android-qt-creator,malikcjm/qtcreator,amyvmiwei/qt-creator,richardmg/qtcreator,bakaiadam/collaborative_qt_creator,hdweiss/qt-creator-visualizer,dmik/qt-creator-os2,syntheticpp/qt-creator,xianian/qt-creator,amyvmiwei/qt-creator,colede/qtcreator,colede/qtcreator,xianian/qt-creator,richardmg/qtcreator,martyone/sailfish-qtcreator,martyone/sailfish-qtcreator,Distrotech/qtcreator,amyvmiwei/qt-creator,AltarBeastiful/qt-creator
|
d1fdf87938a0f3fe138142c7d3fd934b1f11c377
|
Examples/DataRepresentation/Mesh/PointSetWithVectors.cxx
|
Examples/DataRepresentation/Mesh/PointSetWithVectors.cxx
|
/*=========================================================================
*
* Copyright Insight Software Consortium
*
* 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.
*
*=========================================================================*/
// Software Guide : BeginLatex
//
// This example illustrates how a point set can be parameterized to manage a
// particular pixel type. It is quite common to associate vector values with
// points for producing geometric representations. The following code shows
// how vector values can be used as the pixel type on the PointSet class. The
// \doxygen{Vector} class is used here as the pixel type. This class is
// appropriate for representing the relative position between two points. It
// could then be used to manage displacements, for example.
//
// \index{itk::PointSet!Vector pixels}
//
// In order to use the vector class it is necessary to include its header file
// along with the header of the point set.
//
// Software Guide : EndLatex
// Software Guide : BeginCodeSnippet
#include "itkVector.h"
#include "itkPointSet.h"
// Software Guide : EndCodeSnippet
int main(int, char *[])
{
// Software Guide : BeginLatex
//
// \begin{floatingfigure}[rlp]{6cm}
// \centering
// \includegraphics[width=4cm]{PointSetWithVectors}
// \caption[PointSet with Vectors as PixelType]{Vectors as PixelType.\label{fig:PointSetWithVectors}}
// \end{floatingfigure}
//
// The Vector class is templated over the type used to represent
// the spatial coordinates and over the space dimension. Since the
// PixelType is independent of the PointType, we are free to select any
// dimension for the vectors to be used as pixel type. However, for the
// sake of producing an interesting example, we will use vectors that
// represent displacements of the points in the PointSet. Those vectors
// are then selected to be of the same dimension as the PointSet.
//
//
// \index{itk::Vector!itk::PointSet}
//
// Software Guide : EndLatex
// Software Guide : BeginCodeSnippet
const unsigned int Dimension = 3;
typedef itk::Vector< float, Dimension > PixelType;
// Software Guide : EndCodeSnippet
// Software Guide : BeginLatex
//
// Then we use the PixelType (which are actually Vectors) to instantiate the
// PointSet type and subsequently create a PointSet object.
//
// Software Guide : EndLatex
// Software Guide : BeginCodeSnippet
typedef itk::PointSet< PixelType, Dimension > PointSetType;
PointSetType::Pointer pointSet = PointSetType::New();
// Software Guide : EndCodeSnippet
// Software Guide : BeginLatex
//
// The following code is generating a sphere and assigning vector values
// to the points. The components of the vectors in this example are
// computed to represent the tangents to the circle as shown in
// Figure~\ref{fig:PointSetWithVectors}.
//
// \index{itk::PointSet!SetPoint()}
// \index{itk::PointSet!SetPointData()}
//
// Software Guide : EndLatex
// Software Guide : BeginCodeSnippet
PointSetType::PixelType tangent;
PointSetType::PointType point;
unsigned int pointId = 0;
const double radius = 300.0;
for(unsigned int i=0; i<360; i++)
{
const double angle = i * vnl_math::pi / 180.0;
point[0] = radius * std::sin( angle );
point[1] = radius * std::cos( angle );
point[2] = 1.0; // flat on the Z plane
tangent[0] = std::cos(angle);
tangent[1] = -std::sin(angle);
tangent[2] = 0.0; // flat on the Z plane
pointSet->SetPoint( pointId, point );
pointSet->SetPointData( pointId, tangent );
pointId++;
}
// Software Guide : EndCodeSnippet
// Software Guide : BeginLatex
//
// We can now visit all the points and use the vector on the pixel values to
// apply a displacement on the points. This is along the spirit of what a
// deformable model could do at each one of its iterations.
//
// \index{itk::PointSet!PointIterator}
// \index{itk::PointSet!GetPoints()}
// \index{itk::PointSet!GetPointData()}
//
// Software Guide : EndLatex
// Software Guide : BeginCodeSnippet
typedef PointSetType::PointDataContainer::ConstIterator PointDataIterator;
PointDataIterator pixelIterator = pointSet->GetPointData()->Begin();
PointDataIterator pixelEnd = pointSet->GetPointData()->End();
typedef PointSetType::PointsContainer::Iterator PointIterator;
PointIterator pointIterator = pointSet->GetPoints()->Begin();
PointIterator pointEnd = pointSet->GetPoints()->End();
while( pixelIterator != pixelEnd && pointIterator != pointEnd )
{
pointIterator.Value() = pointIterator.Value() + pixelIterator.Value();
++pixelIterator;
++pointIterator;
}
// Software Guide : EndCodeSnippet
// Software Guide : BeginLatex
//
// Note that the \code{ConstIterator} was used here instead of the normal
// \code{Iterator} since the pixel values are only intended to be read and
// not modified. ITK supports const-correctness at the API level.
//
// \index{ConstIterator}
// \index{const-correctness}
//
// Software Guide : EndLatex
// Software Guide : BeginLatex
//
// The \doxygen{Vector} class has overloaded the \code{+} operator with
// the \doxygen{Point}. In other words, vectors can be added to points in
// order to produce new points. This property is exploited in the center
// of the loop in order to update the points positions with a single
// statement.
//
// \index{itk::PointSet!PointIterator}
//
// We can finally visit all the points and print out the new values
//
// Software Guide : EndLatex
// Software Guide : BeginCodeSnippet
pointIterator = pointSet->GetPoints()->Begin();
pointEnd = pointSet->GetPoints()->End();
while( pointIterator != pointEnd )
{
std::cout << pointIterator.Value() << std::endl;
++pointIterator;
}
// Software Guide : EndCodeSnippet
// Software Guide : BeginLatex
//
// Note that \doxygen{Vector} is not the appropriate class for
// representing normals to surfaces and gradients of functions. This is due
// to the way vectors behave under affine transforms. ITK has a
// specific class for representing normals and function gradients. This is
// the \doxygen{CovariantVector} class.
//
// Software Guide : EndLatex
return 0;
}
|
/*=========================================================================
*
* Copyright Insight Software Consortium
*
* 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.
*
*=========================================================================*/
// Software Guide : BeginLatex
//
// This example illustrates how a point set can be parameterized to manage a
// particular pixel type. It is quite common to associate vector values with
// points for producing geometric representations. The following code shows
// how vector values can be used as the pixel type on the PointSet class. The
// \doxygen{Vector} class is used here as the pixel type. This class is
// appropriate for representing the relative position between two points. It
// could then be used to manage displacements, for example.
//
// \index{itk::PointSet!Vector pixels}
//
// In order to use the vector class it is necessary to include its header file
// along with the header of the point set.
//
// Software Guide : EndLatex
// Software Guide : BeginCodeSnippet
#include "itkVector.h"
#include "itkPointSet.h"
// Software Guide : EndCodeSnippet
int main(int, char *[])
{
// Software Guide : BeginLatex
//
// \begin{floatingfigure}[rlp]{6cm}
// \centering
// \includegraphics[width=4cm]{PointSetWithVectors}
// \caption[PointSet with Vectors as PixelType]{Vectors as PixelType.\label{fig:PointSetWithVectors}}
// \end{floatingfigure}
//
// The Vector class is templated over the type used to represent
// the spatial coordinates and over the space dimension. Since the
// PixelType is independent of the PointType, we are free to select any
// dimension for the vectors to be used as pixel type. However, for the
// sake of producing an interesting example, we will use vectors that
// represent displacements of the points in the PointSet. Those vectors
// are then selected to be of the same dimension as the PointSet.\newline
//
//
// \index{itk::Vector!itk::PointSet}
//
// Software Guide : EndLatex
// Software Guide : BeginCodeSnippet
const unsigned int Dimension = 3;
typedef itk::Vector< float, Dimension > PixelType;
// Software Guide : EndCodeSnippet
// Software Guide : BeginLatex
//
// Then we use the PixelType (which are actually Vectors) to instantiate the
// PointSet type and subsequently create a PointSet object.
//
// Software Guide : EndLatex
// Software Guide : BeginCodeSnippet
typedef itk::PointSet< PixelType, Dimension > PointSetType;
PointSetType::Pointer pointSet = PointSetType::New();
// Software Guide : EndCodeSnippet
// Software Guide : BeginLatex
//
// The following code is generating a sphere and assigning vector values
// to the points. The components of the vectors in this example are
// computed to represent the tangents to the circle as shown in
// Figure~\ref{fig:PointSetWithVectors}.
//
// \index{itk::PointSet!SetPoint()}
// \index{itk::PointSet!SetPointData()}
//
// Software Guide : EndLatex
// Software Guide : BeginCodeSnippet
PointSetType::PixelType tangent;
PointSetType::PointType point;
unsigned int pointId = 0;
const double radius = 300.0;
for(unsigned int i=0; i<360; i++)
{
const double angle = i * vnl_math::pi / 180.0;
point[0] = radius * std::sin( angle );
point[1] = radius * std::cos( angle );
point[2] = 1.0; // flat on the Z plane
tangent[0] = std::cos(angle);
tangent[1] = -std::sin(angle);
tangent[2] = 0.0; // flat on the Z plane
pointSet->SetPoint( pointId, point );
pointSet->SetPointData( pointId, tangent );
pointId++;
}
// Software Guide : EndCodeSnippet
// Software Guide : BeginLatex
//
// We can now visit all the points and use the vector on the pixel values to
// apply a displacement on the points. This is along the spirit of what a
// deformable model could do at each one of its iterations.
//
// \index{itk::PointSet!PointIterator}
// \index{itk::PointSet!GetPoints()}
// \index{itk::PointSet!GetPointData()}
//
// Software Guide : EndLatex
// Software Guide : BeginCodeSnippet
typedef PointSetType::PointDataContainer::ConstIterator PointDataIterator;
PointDataIterator pixelIterator = pointSet->GetPointData()->Begin();
PointDataIterator pixelEnd = pointSet->GetPointData()->End();
typedef PointSetType::PointsContainer::Iterator PointIterator;
PointIterator pointIterator = pointSet->GetPoints()->Begin();
PointIterator pointEnd = pointSet->GetPoints()->End();
while( pixelIterator != pixelEnd && pointIterator != pointEnd )
{
pointIterator.Value() = pointIterator.Value() + pixelIterator.Value();
++pixelIterator;
++pointIterator;
}
// Software Guide : EndCodeSnippet
// Software Guide : BeginLatex
//
// Note that the \code{ConstIterator} was used here instead of the normal
// \code{Iterator} since the pixel values are only intended to be read and
// not modified. ITK supports const-correctness at the API level.
//
// \index{ConstIterator}
// \index{const-correctness}
//
// Software Guide : EndLatex
// Software Guide : BeginLatex
//
// The \doxygen{Vector} class has overloaded the \code{+} operator with
// the \doxygen{Point}. In other words, vectors can be added to points in
// order to produce new points. This property is exploited in the center
// of the loop in order to update the points positions with a single
// statement.
//
// \index{itk::PointSet!PointIterator}
//
// We can finally visit all the points and print out the new values
//
// Software Guide : EndLatex
// Software Guide : BeginCodeSnippet
pointIterator = pointSet->GetPoints()->Begin();
pointEnd = pointSet->GetPoints()->End();
while( pointIterator != pointEnd )
{
std::cout << pointIterator.Value() << std::endl;
++pointIterator;
}
// Software Guide : EndCodeSnippet
// Software Guide : BeginLatex
//
// Note that \doxygen{Vector} is not the appropriate class for
// representing normals to surfaces and gradients of functions. This is due
// to the way vectors behave under affine transforms. ITK has a
// specific class for representing normals and function gradients. This is
// the \doxygen{CovariantVector} class.
//
// Software Guide : EndLatex
return 0;
}
|
Fix code overlapping figure
|
DOC: Fix code overlapping figure
|
C++
|
apache-2.0
|
heimdali/ITK,richardbeare/ITK,msmolens/ITK,jcfr/ITK,atsnyder/ITK,msmolens/ITK,hjmjohnson/ITK,fedral/ITK,malaterre/ITK,heimdali/ITK,heimdali/ITK,fedral/ITK,LucasGandel/ITK,BRAINSia/ITK,LucasGandel/ITK,spinicist/ITK,stnava/ITK,zachary-williamson/ITK,hendradarwin/ITK,BlueBrain/ITK,LucasGandel/ITK,InsightSoftwareConsortium/ITK,spinicist/ITK,LucHermitte/ITK,BlueBrain/ITK,PlutoniumHeart/ITK,thewtex/ITK,jcfr/ITK,biotrump/ITK,spinicist/ITK,atsnyder/ITK,spinicist/ITK,malaterre/ITK,fbudin69500/ITK,malaterre/ITK,hjmjohnson/ITK,InsightSoftwareConsortium/ITK,jcfr/ITK,BRAINSia/ITK,PlutoniumHeart/ITK,LucHermitte/ITK,fedral/ITK,vfonov/ITK,BlueBrain/ITK,PlutoniumHeart/ITK,fbudin69500/ITK,vfonov/ITK,InsightSoftwareConsortium/ITK,heimdali/ITK,LucasGandel/ITK,jmerkow/ITK,hendradarwin/ITK,BlueBrain/ITK,hendradarwin/ITK,stnava/ITK,fbudin69500/ITK,hjmjohnson/ITK,zachary-williamson/ITK,blowekamp/ITK,BRAINSia/ITK,heimdali/ITK,msmolens/ITK,hendradarwin/ITK,spinicist/ITK,PlutoniumHeart/ITK,InsightSoftwareConsortium/ITK,BlueBrain/ITK,hendradarwin/ITK,PlutoniumHeart/ITK,PlutoniumHeart/ITK,Kitware/ITK,malaterre/ITK,blowekamp/ITK,BlueBrain/ITK,fbudin69500/ITK,LucasGandel/ITK,fbudin69500/ITK,LucHermitte/ITK,LucHermitte/ITK,blowekamp/ITK,malaterre/ITK,fedral/ITK,atsnyder/ITK,fbudin69500/ITK,ajjl/ITK,thewtex/ITK,jcfr/ITK,atsnyder/ITK,ajjl/ITK,fedral/ITK,blowekamp/ITK,zachary-williamson/ITK,richardbeare/ITK,BRAINSia/ITK,jcfr/ITK,blowekamp/ITK,vfonov/ITK,ajjl/ITK,hendradarwin/ITK,spinicist/ITK,fbudin69500/ITK,atsnyder/ITK,jmerkow/ITK,hjmjohnson/ITK,BRAINSia/ITK,thewtex/ITK,zachary-williamson/ITK,biotrump/ITK,hendradarwin/ITK,stnava/ITK,heimdali/ITK,zachary-williamson/ITK,biotrump/ITK,LucHermitte/ITK,Kitware/ITK,thewtex/ITK,heimdali/ITK,jmerkow/ITK,fbudin69500/ITK,BRAINSia/ITK,stnava/ITK,vfonov/ITK,blowekamp/ITK,spinicist/ITK,malaterre/ITK,LucHermitte/ITK,Kitware/ITK,jmerkow/ITK,atsnyder/ITK,ajjl/ITK,Kitware/ITK,msmolens/ITK,LucHermitte/ITK,heimdali/ITK,zachary-williamson/ITK,spinicist/ITK,blowekamp/ITK,LucasGandel/ITK,vfonov/ITK,malaterre/ITK,jmerkow/ITK,InsightSoftwareConsortium/ITK,Kitware/ITK,BRAINSia/ITK,richardbeare/ITK,fedral/ITK,hendradarwin/ITK,stnava/ITK,blowekamp/ITK,ajjl/ITK,biotrump/ITK,Kitware/ITK,Kitware/ITK,hjmjohnson/ITK,vfonov/ITK,atsnyder/ITK,InsightSoftwareConsortium/ITK,richardbeare/ITK,stnava/ITK,stnava/ITK,msmolens/ITK,zachary-williamson/ITK,vfonov/ITK,jcfr/ITK,stnava/ITK,malaterre/ITK,thewtex/ITK,msmolens/ITK,thewtex/ITK,LucasGandel/ITK,jcfr/ITK,fedral/ITK,fedral/ITK,ajjl/ITK,jmerkow/ITK,LucasGandel/ITK,ajjl/ITK,richardbeare/ITK,richardbeare/ITK,LucHermitte/ITK,jmerkow/ITK,ajjl/ITK,vfonov/ITK,stnava/ITK,atsnyder/ITK,biotrump/ITK,biotrump/ITK,BlueBrain/ITK,jmerkow/ITK,PlutoniumHeart/ITK,BlueBrain/ITK,zachary-williamson/ITK,biotrump/ITK,jcfr/ITK,PlutoniumHeart/ITK,spinicist/ITK,richardbeare/ITK,msmolens/ITK,biotrump/ITK,msmolens/ITK,malaterre/ITK,InsightSoftwareConsortium/ITK,hjmjohnson/ITK,zachary-williamson/ITK,thewtex/ITK,hjmjohnson/ITK,atsnyder/ITK,vfonov/ITK
|
cf2650b8bec17f4512b191619ee2619819601200
|
GameEngine/GameEngine/Engine/Components/MeshRenderer.cpp
|
GameEngine/GameEngine/Engine/Components/MeshRenderer.cpp
|
#include <Components/MeshRenderer.hh>
#include "Core/Engine.hh"
#include <Core/AScene.hh>
#include <AssetManagement/Instance/MeshInstance.hh>
#include <AssetManagement/Instance/MaterialInstance.hh>
#include <AssetManagement/AssetManager.hh>
#include <assert.h>
#include <Threads/ThreadManager.hpp>
#include <Threads/PrepareRenderThread.hpp>
#include <Threads/RenderThread.hpp>
#include <Threads/Tasks/ToRenderTasks.hpp>
#ifdef EDITOR_ENABLED
#include <imgui/imgui.h>
#include <AssetManagement/AssetManager.hh>
#include <Utils/Debug.hpp>
#endif
namespace AGE
{
MeshRenderer::MeshRenderer() :
ComponentBase()
, _scene(nullptr)
, _serializationInfos(nullptr)
{
}
MeshRenderer::~MeshRenderer(void)
{
}
void MeshRenderer::init(AScene *scene
, std::shared_ptr<AGE::MeshInstance> mesh /* = nullptr */
, std::shared_ptr<AGE::MaterialSetInstance> material /*= nullptr*/)
{
_scene = scene;
if (mesh && material)
{
setMeshAndMaterial(mesh, material);
}
}
void MeshRenderer::reset(AScene *scene)
{
if (!_key.invalid())
{
entity.getLink().unregisterOctreeObject(_key);
}
//scene->getInstance<AGE::Threads::Prepare>()->removeElement(_key);
_key = AGE::PrepareKey();
}
bool MeshRenderer::setMeshAndMaterial(
const std::shared_ptr<AGE::MeshInstance> &mesh,
const std::shared_ptr<AGE::MaterialSetInstance> &material)
{
if (!mesh || !material)
{
return false;
}
if (!_key.invalid())
{
entity.getLink().unregisterOctreeObject(_key);
}
//create key
_key = AGE::GetPrepareThread()->addMesh();
entity.getLink().registerOctreeObject(_key);
_mesh = mesh;
_material = material;
_updateGeometry();
AGE::GetPrepareThread()->getQueue()->emplaceCommand<Tasks::MainToPrepare::SetMeshMaterial>(_material, _mesh);
}
std::shared_ptr<AGE::MeshInstance> MeshRenderer::getMesh()
{
return _mesh;
}
std::shared_ptr<AGE::MaterialSetInstance> MeshRenderer::getMaterial()
{
return _material;
}
void MeshRenderer::_updateGeometry()
{
if (_mesh == nullptr
|| _material == nullptr)
{
return;
}
AGE::GetPrepareThread()->updateGeometry(_key, _mesh->subMeshs);
}
void MeshRenderer::postUnserialization(AScene *scene)
{
_scene = scene;
if (_serializationInfos)
{
if (!_serializationInfos->mesh.empty())
{
scene->getInstance<AGE::AssetsManager>()->loadMesh(_serializationInfos->mesh
, { AGE::MeshInfos::Positions, AGE::MeshInfos::Normals, AGE::MeshInfos::Uvs, AGE::MeshInfos::Tangents }
, "WE_MESH_LOADING");
std::size_t totalToLoad = 0;
std::size_t toLoad = 0;
std::string loadingError;
do {
scene->getInstance<AGE::AssetsManager>()->updateLoadingChannel("WE_MESH_LOADING", totalToLoad, toLoad, loadingError);
} while
(toLoad != 0 && loadingError.size() == 0);
_mesh = _scene->getInstance<AGE::AssetsManager>()->getMesh(_serializationInfos->mesh);
}
if (!_serializationInfos->material.empty())
{
scene->getInstance<AGE::AssetsManager>()->loadMaterial(_serializationInfos->material
, "WE_MESH_LOADING");
std::size_t totalToLoad = 0;
std::size_t toLoad = 0;
std::string loadingError;
do {
scene->getInstance<AGE::AssetsManager>()->updateLoadingChannel("WE_MESH_LOADING", totalToLoad, toLoad, loadingError);
} while
(toLoad != 0 && loadingError.size() == 0);
_material = _scene->getInstance<AGE::AssetsManager>()->getMaterial(_serializationInfos->material);
}
if (_mesh && _material)
{
setMeshAndMaterial(_mesh, _material);
}
}
}
#ifdef EDITOR_ENABLED
void MeshRenderer::editorCreate(AScene *scene)
{}
void MeshRenderer::editorDelete(AScene *scene)
{}
void MeshRenderer::editorUpdate(AScene *scene)
{
if (meshPathList->size() && selectedMeshIndex < meshPathList->size())
{
if ((*meshPathList)[selectedMeshIndex] != selectedMeshPath)
{
std::size_t i = 0;
for (auto &e : *meshPathList)
{
if (e == selectedMeshPath)
{
selectedMeshIndex = i;
break;
}
++i;
}
}
}
ImGui::PushItemWidth(-1);
if (ImGui::ListBox("Meshs", (int*)&selectedMeshIndex, &(meshFileList->front()), (int)(meshFileList->size())))
{
selectedMeshName = (*meshFileList)[selectedMeshIndex];
selectedMeshPath = (*meshPathList)[selectedMeshIndex];
_mesh = scene->getInstance<AGE::AssetsManager>()->getMesh(selectedMeshPath);
if (!_mesh)
{
scene->getInstance<AGE::AssetsManager>()->loadMesh(OldFile(selectedMeshPath), { AGE::MeshInfos::Positions, AGE::MeshInfos::Normals, AGE::MeshInfos::Uvs, AGE::MeshInfos::Tangents }, "WE_MESH_LOADING");
std::size_t totalToLoad = 0;
std::size_t toLoad = 0;
std::string loadingError;
do {
scene->getInstance<AGE::AssetsManager>()->updateLoadingChannel("WE_MESH_LOADING", totalToLoad, toLoad, loadingError);
} while
(toLoad != 0 && loadingError.size() == 0);
}
_mesh = scene->getInstance<AGE::AssetsManager>()->getMesh(selectedMeshPath);
AGE_ASSERT(_mesh != nullptr);
if (_material)
{
setMeshAndMaterial(_mesh, _material);
}
}
ImGui::PopItemWidth();
ImGui::PushItemWidth(-1);
if (!materialFileList->empty() && ImGui::ListBox("Material", (int*)&selectedMaterialIndex, &(materialFileList->front()), (int)(materialFileList->size())))
{
selectedMaterialName = (*materialFileList)[selectedMaterialIndex];
selectedMaterialPath = (*materialPathList)[selectedMaterialIndex];
_material = scene->getInstance<AGE::AssetsManager>()->getMaterial(selectedMaterialPath);
if (!_material)
{
scene->getInstance<AGE::AssetsManager>()->loadMaterial(OldFile(selectedMaterialPath), "WE_MESH_LOADING");
std::size_t totalToLoad = 0;
std::size_t toLoad = 0;
std::string loadingError;
do {
scene->getInstance<AGE::AssetsManager>()->updateLoadingChannel("WE_MESH_LOADING", totalToLoad, toLoad, loadingError);
} while
(toLoad != 0 && loadingError.size() == 0);
}
_material = scene->getInstance<AGE::AssetsManager>()->getMaterial(selectedMaterialPath);
AGE_ASSERT(_material != nullptr);
if (_mesh)
{
setMeshAndMaterial(_mesh, _material);
}
}
//ImGui::ListBoxFooter();
ImGui::PopItemWidth();
}
#endif
}
|
#include <Components/MeshRenderer.hh>
#include "Core/Engine.hh"
#include <Core/AScene.hh>
#include <AssetManagement/Instance/MeshInstance.hh>
#include <AssetManagement/Instance/MaterialInstance.hh>
#include <AssetManagement/AssetManager.hh>
#include <assert.h>
#include <Threads/ThreadManager.hpp>
#include <Threads/PrepareRenderThread.hpp>
#include <Threads/RenderThread.hpp>
#include <Threads/Tasks/ToRenderTasks.hpp>
#ifdef EDITOR_ENABLED
#include <imgui/imgui.h>
#include <AssetManagement/AssetManager.hh>
#include <Utils/Debug.hpp>
#endif
namespace AGE
{
MeshRenderer::MeshRenderer() :
ComponentBase()
, _scene(nullptr)
, _serializationInfos(nullptr)
{
}
MeshRenderer::~MeshRenderer(void)
{
}
void MeshRenderer::init(AScene *scene
, std::shared_ptr<AGE::MeshInstance> mesh /* = nullptr */
, std::shared_ptr<AGE::MaterialSetInstance> material /*= nullptr*/)
{
_scene = scene;
if (mesh && material)
{
setMeshAndMaterial(mesh, material);
}
}
void MeshRenderer::reset(AScene *scene)
{
if (!_key.invalid())
{
entity.getLink().unregisterOctreeObject(_key);
}
//scene->getInstance<AGE::Threads::Prepare>()->removeElement(_key);
_key = AGE::PrepareKey();
}
bool MeshRenderer::setMeshAndMaterial(
const std::shared_ptr<AGE::MeshInstance> &mesh,
const std::shared_ptr<AGE::MaterialSetInstance> &material)
{
if (!mesh || !material)
{
return false;
}
if (!_key.invalid())
{
entity.getLink().unregisterOctreeObject(_key);
}
//create key
_key = AGE::GetPrepareThread()->addMesh();
entity.getLink().registerOctreeObject(_key);
_mesh = mesh;
_material = material;
_updateGeometry();
AGE::GetPrepareThread()->getQueue()->emplaceCommand<Tasks::MainToPrepare::SetMeshMaterial>(_material, _mesh);
}
std::shared_ptr<AGE::MeshInstance> MeshRenderer::getMesh()
{
return _mesh;
}
std::shared_ptr<AGE::MaterialSetInstance> MeshRenderer::getMaterial()
{
return _material;
}
void MeshRenderer::_updateGeometry()
{
if (_mesh == nullptr
|| _material == nullptr)
{
return;
}
AGE::GetPrepareThread()->updateGeometry(_key, _mesh->subMeshs);
}
void MeshRenderer::postUnserialization(AScene *scene)
{
_scene = scene;
if (_serializationInfos)
{
if (!_serializationInfos->mesh.empty())
{
scene->getInstance<AGE::AssetsManager>()->loadMesh(_serializationInfos->mesh
, { AGE::MeshInfos::Positions, AGE::MeshInfos::Normals, AGE::MeshInfos::Uvs, AGE::MeshInfos::Tangents }
, "WE_MESH_LOADING");
std::size_t totalToLoad = 0;
std::size_t toLoad = 0;
std::string loadingError;
do {
scene->getInstance<AGE::AssetsManager>()->updateLoadingChannel("WE_MESH_LOADING", totalToLoad, toLoad, loadingError);
} while
(toLoad != 0 && loadingError.size() == 0);
_mesh = _scene->getInstance<AGE::AssetsManager>()->getMesh(_serializationInfos->mesh);
}
if (!_serializationInfos->material.empty())
{
scene->getInstance<AGE::AssetsManager>()->loadMaterial(_serializationInfos->material
, "WE_MESH_LOADING");
std::size_t totalToLoad = 0;
std::size_t toLoad = 0;
std::string loadingError;
do {
scene->getInstance<AGE::AssetsManager>()->updateLoadingChannel("WE_MESH_LOADING", totalToLoad, toLoad, loadingError);
} while
(toLoad != 0 && loadingError.size() == 0);
_material = _scene->getInstance<AGE::AssetsManager>()->getMaterial(_serializationInfos->material);
}
if (_mesh && _material)
{
setMeshAndMaterial(_mesh, _material);
}
#ifdef EDITOR_ENABLED
selectedMaterialPath = _serializationInfos->material;
selectedMeshPath = _serializationInfos->mesh;
#endif
}
}
#ifdef EDITOR_ENABLED
void MeshRenderer::editorCreate(AScene *scene)
{}
void MeshRenderer::editorDelete(AScene *scene)
{}
void MeshRenderer::editorUpdate(AScene *scene)
{
if ((*meshPathList)[selectedMeshIndex] != selectedMeshPath)
{
std::size_t i = 0;
for (auto &e : *meshPathList)
{
if (e == selectedMeshPath)
{
selectedMeshIndex = i;
break;
}
++i;
}
}
if ((*materialPathList)[selectedMaterialIndex] != selectedMaterialPath)
{
std::size_t i = 0;
for (auto &e : *materialPathList)
{
if (e == selectedMaterialPath)
{
selectedMaterialIndex = i;
break;
}
++i;
}
}
ImGui::PushItemWidth(-1);
if (ImGui::ListBox("Meshs", (int*)&selectedMeshIndex, &(meshFileList->front()), (int)(meshFileList->size())))
{
selectedMeshName = (*meshFileList)[selectedMeshIndex];
selectedMeshPath = (*meshPathList)[selectedMeshIndex];
_mesh = scene->getInstance<AGE::AssetsManager>()->getMesh(selectedMeshPath);
if (!_mesh)
{
scene->getInstance<AGE::AssetsManager>()->loadMesh(OldFile(selectedMeshPath), { AGE::MeshInfos::Positions, AGE::MeshInfos::Normals, AGE::MeshInfos::Uvs, AGE::MeshInfos::Tangents }, "WE_MESH_LOADING");
std::size_t totalToLoad = 0;
std::size_t toLoad = 0;
std::string loadingError;
do {
scene->getInstance<AGE::AssetsManager>()->updateLoadingChannel("WE_MESH_LOADING", totalToLoad, toLoad, loadingError);
} while
(toLoad != 0 && loadingError.size() == 0);
}
_mesh = scene->getInstance<AGE::AssetsManager>()->getMesh(selectedMeshPath);
AGE_ASSERT(_mesh != nullptr);
if (_material)
{
setMeshAndMaterial(_mesh, _material);
}
}
ImGui::PopItemWidth();
ImGui::PushItemWidth(-1);
if (!materialFileList->empty() && ImGui::ListBox("Material", (int*)&selectedMaterialIndex, &(materialFileList->front()), (int)(materialFileList->size())))
{
selectedMaterialName = (*materialFileList)[selectedMaterialIndex];
selectedMaterialPath = (*materialPathList)[selectedMaterialIndex];
_material = scene->getInstance<AGE::AssetsManager>()->getMaterial(selectedMaterialPath);
if (!_material)
{
scene->getInstance<AGE::AssetsManager>()->loadMaterial(OldFile(selectedMaterialPath), "WE_MESH_LOADING");
std::size_t totalToLoad = 0;
std::size_t toLoad = 0;
std::string loadingError;
do {
scene->getInstance<AGE::AssetsManager>()->updateLoadingChannel("WE_MESH_LOADING", totalToLoad, toLoad, loadingError);
} while
(toLoad != 0 && loadingError.size() == 0);
}
_material = scene->getInstance<AGE::AssetsManager>()->getMaterial(selectedMaterialPath);
AGE_ASSERT(_material != nullptr);
if (_mesh)
{
setMeshAndMaterial(_mesh, _material);
}
}
//ImGui::ListBoxFooter();
ImGui::PopItemWidth();
}
#endif
}
|
Load mesh
|
Load mesh
|
C++
|
mit
|
Another-Game-Engine/AGE,Another-Game-Engine/AGE
|
b1fc86afa66a8406f6e2676d1cd3bd0819215cee
|
Modules/IO/ImageBase/test/itkWriteImageFunctionGTest.cxx
|
Modules/IO/ImageBase/test/itkWriteImageFunctionGTest.cxx
|
/*=========================================================================
*
* Copyright NumFOCUS
*
* 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.
*
*=========================================================================*/
#include "itkImageFileWriter.h"
#include "itkImage.h"
#include "itkGTest.h"
#include "itksys/SystemTools.hxx"
#include "itkTestDriverIncludeRequiredIOFactories.h"
#define STRING(s) #s
namespace
{
struct ITKWriteImageFunctionTest : public ::testing::Test
{
void
SetUp() override
{
RegisterRequiredFactories();
itksys::SystemTools::ChangeDirectory(STRING(ITK_TEST_OUTPUT_DIR_STR));
}
using ImageType = itk::Image<float, 2>;
ImageType::Pointer
MakeImage()
{
auto image = ImageType::New();
ImageType::RegionType region({ 3, 2 });
image->SetRegions(region);
image->Allocate(true);
return image;
}
};
} // namespace
TEST_F(ITKWriteImageFunctionTest, ImageTypes)
{
ImageType::Pointer image_ptr = MakeImage();
itk::WriteImage(image_ptr, "test1.mha");
itk::WriteImage(std::move(image_ptr), "test1.mha");
ImageType::ConstPointer image_cptr = MakeImage();
itk::WriteImage(image_cptr, "test1.mha");
itk::WriteImage(std::move(image_cptr), "test1.mha");
const ImageType::ConstPointer image_ccptr = MakeImage();
itk::WriteImage(image_ccptr, "test1.mha");
itk::WriteImage(std::move(image_ccptr), "test1.mha");
image_ptr = MakeImage();
ImageType * image_rptr = image_ptr.GetPointer();
itk::WriteImage(image_rptr, "test1.mha");
const ImageType * image_crptr = image_ptr.GetPointer();
itk::WriteImage(image_crptr, "test1.mha");
}
|
/*=========================================================================
*
* Copyright NumFOCUS
*
* 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.
*
*=========================================================================*/
#include "itkImageFileWriter.h"
#include "itkImage.h"
#include "itkGTest.h"
#include "itksys/SystemTools.hxx"
#include "itkTestDriverIncludeRequiredIOFactories.h"
#define STRING(s) #s
namespace
{
struct ITKWriteImageFunctionTest : public ::testing::Test
{
void
SetUp() override
{
RegisterRequiredFactories();
itksys::SystemTools::ChangeDirectory(STRING(ITK_TEST_OUTPUT_DIR_STR));
}
using ImageType = itk::Image<float, 2>;
using RegionType = ImageType::RegionType;
using SizeType = ImageType::SizeType;
ImageType::Pointer
MakeImage()
{
auto image = ImageType::New();
RegionType region(SizeType{ { 3, 2 } });
image->SetRegions(region);
image->Allocate(true);
return image;
}
};
} // namespace
TEST_F(ITKWriteImageFunctionTest, ImageTypes)
{
ImageType::Pointer image_ptr = MakeImage();
itk::WriteImage(image_ptr, "test1.mha");
itk::WriteImage(std::move(image_ptr), "test1.mha");
ImageType::ConstPointer image_cptr = MakeImage();
itk::WriteImage(image_cptr, "test1.mha");
itk::WriteImage(std::move(image_cptr), "test1.mha");
const ImageType::ConstPointer image_ccptr = MakeImage();
itk::WriteImage(image_ccptr, "test1.mha");
itk::WriteImage(std::move(image_ccptr), "test1.mha");
image_ptr = MakeImage();
ImageType * image_rptr = image_ptr.GetPointer();
itk::WriteImage(image_rptr, "test1.mha");
const ImageType * image_crptr = image_ptr.GetPointer();
itk::WriteImage(image_crptr, "test1.mha");
}
|
Address brace initializer warning
|
COMP: Address brace initializer warning
|
C++
|
apache-2.0
|
BRAINSia/ITK,Kitware/ITK,hjmjohnson/ITK,InsightSoftwareConsortium/ITK,Kitware/ITK,InsightSoftwareConsortium/ITK,InsightSoftwareConsortium/ITK,Kitware/ITK,LucasGandel/ITK,thewtex/ITK,LucasGandel/ITK,vfonov/ITK,vfonov/ITK,vfonov/ITK,hjmjohnson/ITK,LucasGandel/ITK,InsightSoftwareConsortium/ITK,richardbeare/ITK,LucasGandel/ITK,thewtex/ITK,hjmjohnson/ITK,BRAINSia/ITK,thewtex/ITK,vfonov/ITK,richardbeare/ITK,LucasGandel/ITK,vfonov/ITK,richardbeare/ITK,vfonov/ITK,Kitware/ITK,InsightSoftwareConsortium/ITK,vfonov/ITK,hjmjohnson/ITK,InsightSoftwareConsortium/ITK,LucasGandel/ITK,Kitware/ITK,richardbeare/ITK,BRAINSia/ITK,LucasGandel/ITK,thewtex/ITK,hjmjohnson/ITK,hjmjohnson/ITK,thewtex/ITK,Kitware/ITK,vfonov/ITK,LucasGandel/ITK,richardbeare/ITK,hjmjohnson/ITK,thewtex/ITK,BRAINSia/ITK,Kitware/ITK,vfonov/ITK,thewtex/ITK,BRAINSia/ITK,richardbeare/ITK,richardbeare/ITK,BRAINSia/ITK,InsightSoftwareConsortium/ITK,BRAINSia/ITK
|
af5c71de7d4dfbb981de0c4b0d3e38e772f6d03e
|
PWG2/FEMTOSCOPY/AliFemto/AliFemtoCorrFctn3DSpherical.cxx
|
PWG2/FEMTOSCOPY/AliFemto/AliFemtoCorrFctn3DSpherical.cxx
|
///////////////////////////////////////////////////////////////////////////
// //
// AliFemtoCorrFctn3DSpherical: a class to calculate 3D correlation //
// for pairs of identical particles, binned in spherical coordinates. //
// In analysis the function should be first created in a macro, then //
// added to the analysis, and at the end of the macro the procedure to //
// write out histograms should be called. //
// //
///////////////////////////////////////////////////////////////////////////
#include "AliFemtoCorrFctn3DSpherical.h"
#include <TMath.h>
#include <cstdio>
#ifdef __ROOT__
ClassImp(AliFemtoCorrFctn3DSpherical)
#endif
//____________________________
AliFemtoCorrFctn3DSpherical::AliFemtoCorrFctn3DSpherical(char* title, const int& nqbins, const float& QLo, const float& QHi, const int& nphibins, const int& ncthetabins):
fNumerator(0),
fDenominator(0) //,
// fPairCut(0x0)
{
// set up numerator
char tTitNum[100] = "Num";
strncat(tTitNum,title, 100);
fNumerator = new TH3D(tTitNum,title,nqbins,QLo,QHi,nphibins,-TMath::Pi(),TMath::Pi(),ncthetabins,-1.0,1.0);
// set up denominator
char tTitDen[100] = "Den";
strncat(tTitDen,title, 100);
fDenominator = new TH3D(tTitDen,title,nqbins,QLo,QHi,nphibins,-TMath::Pi(),TMath::Pi(),ncthetabins,-1.0,1.0);
// to enable error bar calculation...
fNumerator->Sumw2();
fDenominator->Sumw2();
}
AliFemtoCorrFctn3DSpherical::AliFemtoCorrFctn3DSpherical(const AliFemtoCorrFctn3DSpherical& aCorrFctn) :
AliFemtoCorrFctn(aCorrFctn),
fNumerator(0),
fDenominator(0) //,
// fPairCut(0x0)
{
// Copy constructor
fNumerator = new TH3D(*aCorrFctn.fNumerator);
fDenominator = new TH3D(*aCorrFctn.fDenominator);
// fPairCut = aCorrFctn.fPairCut;
}
//____________________________
AliFemtoCorrFctn3DSpherical::~AliFemtoCorrFctn3DSpherical(){
// Destructor
delete fNumerator;
delete fDenominator;
}
//_________________________
AliFemtoCorrFctn3DSpherical& AliFemtoCorrFctn3DSpherical::operator=(const AliFemtoCorrFctn3DSpherical& aCorrFctn)
{
// assignment operator
if (this == &aCorrFctn)
return *this;
if (fNumerator) delete fNumerator;
fNumerator = new TH3D(*aCorrFctn.fNumerator);
if (fDenominator) delete fDenominator;
fDenominator = new TH3D(*aCorrFctn.fDenominator);
// fPairCut = aCorrFctn.fPairCut;
return *this;
}
//_________________________
void AliFemtoCorrFctn3DSpherical::WriteOutHistos(){
// Write out all histograms to file
fNumerator->Write();
fDenominator->Write();
}
//______________________________
TList* AliFemtoCorrFctn3DSpherical::GetOutputList()
{
// Prepare the list of objects to be written to the output
TList *tOutputList = new TList();
tOutputList->Add(fNumerator);
tOutputList->Add(fDenominator);
return tOutputList;
}
//_________________________
void AliFemtoCorrFctn3DSpherical::Finish(){
// here is where we should normalize, fit, etc...
}
//____________________________
AliFemtoString AliFemtoCorrFctn3DSpherical::Report(){
// Construct the report
string stemp = "PRF Frame Spherical 3D Correlation Function Report:\n";
char ctemp[100];
snprintf(ctemp , 100, "Number of entries in numerator:\t%E\n",fNumerator->GetEntries());
stemp += ctemp;
snprintf(ctemp , 100, "Number of entries in denominator:\t%E\n",fDenominator->GetEntries());
stemp += ctemp;
if (fPairCut){
snprintf(ctemp , 100, "Here is the PairCut specific to this CorrFctn\n");
stemp += ctemp;
stemp += fPairCut->Report();
}
else{
snprintf(ctemp , 100, "No PairCut specific to this CorrFctn\n");
stemp += ctemp;
}
//
AliFemtoString returnThis = stemp;
return returnThis;
}
//____________________________
void AliFemtoCorrFctn3DSpherical::AddRealPair( AliFemtoPair* pair){
// perform operations on real pairs
if (fPairCut){
if (!(fPairCut->Pass(pair))) return;
}
double tKO = pair->KOut();
double tKS = pair->KSide();
double tKL = pair->KLong();
double tKR = sqrt(tKO*tKO + tKS*tKS + tKL*tKL);
double tKC;
if ( fabs(tKR) < 1e-10 ) tKC = 0.0;
else tKC=tKL/tKR;
double tKP=atan2(tKS,tKO);
fNumerator->Fill(tKR,tKP,tKC);
}
//____________________________
void AliFemtoCorrFctn3DSpherical::AddMixedPair( AliFemtoPair* pair){
// perform operations on mixed pairs
if (fPairCut){
if (!(fPairCut->Pass(pair))) return;
}
double tKO = pair->KOut();
double tKS = pair->KSide();
double tKL = pair->KLong();
double tKR = sqrt(tKO*tKO + tKS*tKS + tKL*tKL);
double tKC;
if ( fabs(tKR) < 1e-10 ) tKC = 0.0;
else tKC=tKL/tKR;
double tKP=atan2(tKS,tKO);
fDenominator->Fill(tKR,tKP,tKC);
}
|
///////////////////////////////////////////////////////////////////////////
// //
// AliFemtoCorrFctn3DSpherical: a class to calculate 3D correlation //
// for pairs of identical particles, binned in spherical coordinates. //
// In analysis the function should be first created in a macro, then //
// added to the analysis, and at the end of the macro the procedure to //
// write out histograms should be called. //
// //
///////////////////////////////////////////////////////////////////////////
#include "AliFemtoCorrFctn3DSpherical.h"
#include <TMath.h>
#include <cstdio>
#ifdef __ROOT__
ClassImp(AliFemtoCorrFctn3DSpherical)
#endif
//____________________________
AliFemtoCorrFctn3DSpherical::AliFemtoCorrFctn3DSpherical(char* title, const int& nqbins, const float& QLo, const float& QHi, const int& nphibins, const int& ncthetabins):
fNumerator(0),
fDenominator(0) //,
// fPairCut(0x0)
{
// set up numerator
char tTitNum[101] = "Num";
strncat(tTitNum,title, 100);
fNumerator = new TH3D(tTitNum,title,nqbins,QLo,QHi,nphibins,-TMath::Pi(),TMath::Pi(),ncthetabins,-1.0,1.0);
// set up denominator
char tTitDen[101] = "Den";
strncat(tTitDen,title, 100);
fDenominator = new TH3D(tTitDen,title,nqbins,QLo,QHi,nphibins,-TMath::Pi(),TMath::Pi(),ncthetabins,-1.0,1.0);
// to enable error bar calculation...
fNumerator->Sumw2();
fDenominator->Sumw2();
}
AliFemtoCorrFctn3DSpherical::AliFemtoCorrFctn3DSpherical(const AliFemtoCorrFctn3DSpherical& aCorrFctn) :
AliFemtoCorrFctn(aCorrFctn),
fNumerator(0),
fDenominator(0) //,
// fPairCut(0x0)
{
// Copy constructor
fNumerator = new TH3D(*aCorrFctn.fNumerator);
fDenominator = new TH3D(*aCorrFctn.fDenominator);
// fPairCut = aCorrFctn.fPairCut;
}
//____________________________
AliFemtoCorrFctn3DSpherical::~AliFemtoCorrFctn3DSpherical(){
// Destructor
delete fNumerator;
delete fDenominator;
}
//_________________________
AliFemtoCorrFctn3DSpherical& AliFemtoCorrFctn3DSpherical::operator=(const AliFemtoCorrFctn3DSpherical& aCorrFctn)
{
// assignment operator
if (this == &aCorrFctn)
return *this;
if (fNumerator) delete fNumerator;
fNumerator = new TH3D(*aCorrFctn.fNumerator);
if (fDenominator) delete fDenominator;
fDenominator = new TH3D(*aCorrFctn.fDenominator);
// fPairCut = aCorrFctn.fPairCut;
return *this;
}
//_________________________
void AliFemtoCorrFctn3DSpherical::WriteOutHistos(){
// Write out all histograms to file
fNumerator->Write();
fDenominator->Write();
}
//______________________________
TList* AliFemtoCorrFctn3DSpherical::GetOutputList()
{
// Prepare the list of objects to be written to the output
TList *tOutputList = new TList();
tOutputList->Add(fNumerator);
tOutputList->Add(fDenominator);
return tOutputList;
}
//_________________________
void AliFemtoCorrFctn3DSpherical::Finish(){
// here is where we should normalize, fit, etc...
}
//____________________________
AliFemtoString AliFemtoCorrFctn3DSpherical::Report(){
// Construct the report
string stemp = "PRF Frame Spherical 3D Correlation Function Report:\n";
char ctemp[100];
snprintf(ctemp , 100, "Number of entries in numerator:\t%E\n",fNumerator->GetEntries());
stemp += ctemp;
snprintf(ctemp , 100, "Number of entries in denominator:\t%E\n",fDenominator->GetEntries());
stemp += ctemp;
if (fPairCut){
snprintf(ctemp , 100, "Here is the PairCut specific to this CorrFctn\n");
stemp += ctemp;
stemp += fPairCut->Report();
}
else{
snprintf(ctemp , 100, "No PairCut specific to this CorrFctn\n");
stemp += ctemp;
}
//
AliFemtoString returnThis = stemp;
return returnThis;
}
//____________________________
void AliFemtoCorrFctn3DSpherical::AddRealPair( AliFemtoPair* pair){
// perform operations on real pairs
if (fPairCut){
if (!(fPairCut->Pass(pair))) return;
}
double tKO = pair->KOut();
double tKS = pair->KSide();
double tKL = pair->KLong();
double tKR = sqrt(tKO*tKO + tKS*tKS + tKL*tKL);
double tKC;
if ( fabs(tKR) < 1e-10 ) tKC = 0.0;
else tKC=tKL/tKR;
double tKP=atan2(tKS,tKO);
fNumerator->Fill(tKR,tKP,tKC);
}
//____________________________
void AliFemtoCorrFctn3DSpherical::AddMixedPair( AliFemtoPair* pair){
// perform operations on mixed pairs
if (fPairCut){
if (!(fPairCut->Pass(pair))) return;
}
double tKO = pair->KOut();
double tKS = pair->KSide();
double tKL = pair->KLong();
double tKR = sqrt(tKO*tKO + tKS*tKS + tKL*tKL);
double tKC;
if ( fabs(tKR) < 1e-10 ) tKC = 0.0;
else tKC=tKL/tKR;
double tKP=atan2(tKS,tKO);
fDenominator->Fill(tKR,tKP,tKC);
}
|
Fix Coverity reports
|
Fix Coverity reports
|
C++
|
bsd-3-clause
|
amaringarcia/AliPhysics,lcunquei/AliPhysics,ppribeli/AliPhysics,nschmidtALICE/AliPhysics,carstooon/AliPhysics,aaniin/AliPhysics,alisw/AliPhysics,mpuccio/AliPhysics,pbuehler/AliPhysics,hzanoli/AliPhysics,AMechler/AliPhysics,kreisl/AliPhysics,adriansev/AliPhysics,hzanoli/AliPhysics,lfeldkam/AliPhysics,btrzecia/AliPhysics,fbellini/AliPhysics,mkrzewic/AliPhysics,jmargutt/AliPhysics,aaniin/AliPhysics,adriansev/AliPhysics,amaringarcia/AliPhysics,jgronefe/AliPhysics,nschmidtALICE/AliPhysics,aaniin/AliPhysics,lcunquei/AliPhysics,rihanphys/AliPhysics,mvala/AliPhysics,jmargutt/AliPhysics,fbellini/AliPhysics,carstooon/AliPhysics,kreisl/AliPhysics,jgronefe/AliPhysics,mbjadhav/AliPhysics,rbailhac/AliPhysics,hcab14/AliPhysics,hzanoli/AliPhysics,yowatana/AliPhysics,yowatana/AliPhysics,mbjadhav/AliPhysics,jgronefe/AliPhysics,hzanoli/AliPhysics,AMechler/AliPhysics,hzanoli/AliPhysics,alisw/AliPhysics,hcab14/AliPhysics,fbellini/AliPhysics,ALICEHLT/AliPhysics,adriansev/AliPhysics,dstocco/AliPhysics,fcolamar/AliPhysics,preghenella/AliPhysics,pbuehler/AliPhysics,mkrzewic/AliPhysics,SHornung1/AliPhysics,yowatana/AliPhysics,amatyja/AliPhysics,nschmidtALICE/AliPhysics,pbatzing/AliPhysics,AMechler/AliPhysics,jmargutt/AliPhysics,fcolamar/AliPhysics,ppribeli/AliPhysics,kreisl/AliPhysics,carstooon/AliPhysics,pchrista/AliPhysics,SHornung1/AliPhysics,kreisl/AliPhysics,akubera/AliPhysics,ppribeli/AliPhysics,rderradi/AliPhysics,pchrista/AliPhysics,preghenella/AliPhysics,hcab14/AliPhysics,dlodato/AliPhysics,rbailhac/AliPhysics,jmargutt/AliPhysics,AudreyFrancisco/AliPhysics,dlodato/AliPhysics,rderradi/AliPhysics,pbuehler/AliPhysics,dlodato/AliPhysics,rihanphys/AliPhysics,fcolamar/AliPhysics,pchrista/AliPhysics,pchrista/AliPhysics,amaringarcia/AliPhysics,dstocco/AliPhysics,fbellini/AliPhysics,rderradi/AliPhysics,fcolamar/AliPhysics,dstocco/AliPhysics,AMechler/AliPhysics,SHornung1/AliPhysics,akubera/AliPhysics,mpuccio/AliPhysics,alisw/AliPhysics,jgronefe/AliPhysics,lfeldkam/AliPhysics,lfeldkam/AliPhysics,lcunquei/AliPhysics,victor-gonzalez/AliPhysics,lfeldkam/AliPhysics,akubera/AliPhysics,amatyja/AliPhysics,mvala/AliPhysics,mazimm/AliPhysics,AudreyFrancisco/AliPhysics,pchrista/AliPhysics,alisw/AliPhysics,ALICEHLT/AliPhysics,preghenella/AliPhysics,mbjadhav/AliPhysics,amatyja/AliPhysics,dlodato/AliPhysics,hcab14/AliPhysics,AudreyFrancisco/AliPhysics,mpuccio/AliPhysics,hzanoli/AliPhysics,pbuehler/AliPhysics,preghenella/AliPhysics,sebaleh/AliPhysics,pbuehler/AliPhysics,AMechler/AliPhysics,jmargutt/AliPhysics,adriansev/AliPhysics,ALICEHLT/AliPhysics,nschmidtALICE/AliPhysics,hzanoli/AliPhysics,jgronefe/AliPhysics,dlodato/AliPhysics,mazimm/AliPhysics,ALICEHLT/AliPhysics,pchrista/AliPhysics,btrzecia/AliPhysics,fcolamar/AliPhysics,hcab14/AliPhysics,ALICEHLT/AliPhysics,btrzecia/AliPhysics,fcolamar/AliPhysics,mpuccio/AliPhysics,btrzecia/AliPhysics,yowatana/AliPhysics,sebaleh/AliPhysics,mpuccio/AliPhysics,carstooon/AliPhysics,mazimm/AliPhysics,pbatzing/AliPhysics,dstocco/AliPhysics,dmuhlhei/AliPhysics,mazimm/AliPhysics,amatyja/AliPhysics,yowatana/AliPhysics,preghenella/AliPhysics,rihanphys/AliPhysics,dmuhlhei/AliPhysics,hcab14/AliPhysics,carstooon/AliPhysics,sebaleh/AliPhysics,amaringarcia/AliPhysics,rihanphys/AliPhysics,mkrzewic/AliPhysics,victor-gonzalez/AliPhysics,akubera/AliPhysics,amatyja/AliPhysics,mvala/AliPhysics,hcab14/AliPhysics,adriansev/AliPhysics,mkrzewic/AliPhysics,jgronefe/AliPhysics,dmuhlhei/AliPhysics,rderradi/AliPhysics,SHornung1/AliPhysics,aaniin/AliPhysics,yowatana/AliPhysics,mkrzewic/AliPhysics,yowatana/AliPhysics,dmuhlhei/AliPhysics,jmargutt/AliPhysics,rbailhac/AliPhysics,mazimm/AliPhysics,rbailhac/AliPhysics,aaniin/AliPhysics,pbuehler/AliPhysics,ppribeli/AliPhysics,pbatzing/AliPhysics,alisw/AliPhysics,dmuhlhei/AliPhysics,kreisl/AliPhysics,nschmidtALICE/AliPhysics,amaringarcia/AliPhysics,nschmidtALICE/AliPhysics,mbjadhav/AliPhysics,rderradi/AliPhysics,aaniin/AliPhysics,victor-gonzalez/AliPhysics,btrzecia/AliPhysics,amaringarcia/AliPhysics,carstooon/AliPhysics,mbjadhav/AliPhysics,AudreyFrancisco/AliPhysics,SHornung1/AliPhysics,btrzecia/AliPhysics,kreisl/AliPhysics,pbatzing/AliPhysics,sebaleh/AliPhysics,rderradi/AliPhysics,rihanphys/AliPhysics,dstocco/AliPhysics,lfeldkam/AliPhysics,carstooon/AliPhysics,rihanphys/AliPhysics,victor-gonzalez/AliPhysics,pbuehler/AliPhysics,jmargutt/AliPhysics,preghenella/AliPhysics,mazimm/AliPhysics,aaniin/AliPhysics,pbatzing/AliPhysics,dmuhlhei/AliPhysics,ALICEHLT/AliPhysics,mvala/AliPhysics,fbellini/AliPhysics,lfeldkam/AliPhysics,lcunquei/AliPhysics,sebaleh/AliPhysics,fcolamar/AliPhysics,dstocco/AliPhysics,AMechler/AliPhysics,AudreyFrancisco/AliPhysics,pbatzing/AliPhysics,rihanphys/AliPhysics,fbellini/AliPhysics,victor-gonzalez/AliPhysics,btrzecia/AliPhysics,alisw/AliPhysics,mkrzewic/AliPhysics,dstocco/AliPhysics,mbjadhav/AliPhysics,rderradi/AliPhysics,adriansev/AliPhysics,akubera/AliPhysics,rbailhac/AliPhysics,lfeldkam/AliPhysics,ppribeli/AliPhysics,mazimm/AliPhysics,SHornung1/AliPhysics,ppribeli/AliPhysics,rbailhac/AliPhysics,lcunquei/AliPhysics,jgronefe/AliPhysics,victor-gonzalez/AliPhysics,dlodato/AliPhysics,mvala/AliPhysics,rbailhac/AliPhysics,fbellini/AliPhysics,SHornung1/AliPhysics,pbatzing/AliPhysics,preghenella/AliPhysics,adriansev/AliPhysics,ALICEHLT/AliPhysics,AudreyFrancisco/AliPhysics,nschmidtALICE/AliPhysics,sebaleh/AliPhysics,akubera/AliPhysics,lcunquei/AliPhysics,kreisl/AliPhysics,mpuccio/AliPhysics,mbjadhav/AliPhysics,mpuccio/AliPhysics,AMechler/AliPhysics,amaringarcia/AliPhysics,victor-gonzalez/AliPhysics,mkrzewic/AliPhysics,sebaleh/AliPhysics,akubera/AliPhysics,dmuhlhei/AliPhysics,pchrista/AliPhysics,ppribeli/AliPhysics,mvala/AliPhysics,mvala/AliPhysics,alisw/AliPhysics,dlodato/AliPhysics,amatyja/AliPhysics,amatyja/AliPhysics,AudreyFrancisco/AliPhysics,lcunquei/AliPhysics
|
470c6871421b5d69fee70c029b4165815bf8c7a9
|
inc/sph_model.hpp
|
inc/sph_model.hpp
|
/*******************************************************************************
* The MIT License (MIT)
*
* Copyright (c) 2011, 2017 OpenWorm.
* http://openworm.org
*
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the MIT License
* which accompanies this distribution, and is available at
* http://opensource.org/licenses/MIT
*
* Contributors:
* OpenWorm - http://openworm.org/people.html
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
* DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
* OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
* USE OR OTHER DEALINGS IN THE SOFTWARE.
*******************************************************************************/
#ifndef X_SPHMODEL
#define X_SPHMODEL
#include "particle.h"
#include "util/x_error.h"
#include <array>
#include <fstream>
#include <iostream>
#include <map>
#include <memory>
#include <regex>
#include <string>
#include <vector>
namespace x_engine {
namespace model {
enum LOADMODE { NOMODE = -1, PARAMS, MODEL, POS, VEL };
template <class T = float, class container = std::vector<particle<T>>>
class sph_model {
typedef std::map<std::string, size_t> sph_config;
public:
sph_model(const std::string &config_file) {
config = {{"particles", 0}, {"x_max", 0}, {"x_min", 0}, {"y_max", 0},
{"y_min", 0}, {"z_max", 0}, {"z_min", 0}};
read_model(config_file);
std::cout << "Model was loaded: " << particles.size() << " partticles."
<< std::endl;
}
const sph_config &get_config() const { return config; }
private:
container particles;
sph_config config;
std::map<std::string, T> phys_consts;
std::shared_ptr<std::array<T, 4>> get_vector(const std::string &line) {
std::shared_ptr<std::array<T, 4>> v(new std::array<T, 4>());
std::stringstream ss(line);
ss >> (*v)[0] >> (*v)[1] >> (*v)[2] >> (*v)[3]; // TODO check here!!!
return v;
}
void read_model(const std::string &model_file) {
std::ifstream file(model_file.c_str(), std::ios_base::binary);
LOADMODE mode = NOMODE;
bool is_model_mode = false;
int index = 0;
if (file.is_open()) {
while (file.good()) {
std::string cur_line;
std::getline(file, cur_line);
if (cur_line.compare("parametrs[") == 0) {
mode = PARAMS;
continue;
} else if (cur_line.compare("model[") == 0) {
mode = MODEL;
is_model_mode = true;
continue;
} else if (cur_line.compare("position[") == 0) {
mode = POS;
continue;
} else if (cur_line.compare("velocity[") == 0) {
mode = VEL;
continue;
} else if (cur_line.compare("]") == 0) {
mode = NOMODE;
continue;
}
if (mode == PARAMS) {
std::regex rgx("[\\t ]*(\\w+) *: *(\\d+) *([//]*.*)");
std::smatch matches;
if (std::regex_search(cur_line, matches, rgx)) {
if (matches.size() > 2) {
if (config.find(matches[1]) != config.end()) {
config[matches[1]] =
static_cast<size_t>(stoi(matches[2].str()));
continue;
}
} else {
std::string msg = x_engine::make_msg(
"Problem with parsing parametrs:", matches[0].str(),
"Please check parametrs.");
throw parser_error(msg);
}
} else {
throw parser_error(
"Please check parametrs section there are no parametrs.");
}
}
if (is_model_mode) {
switch (mode) {
case POS: {
particle<T> p;
p.pos = *get_vector(cur_line);
particles.push_back(p);
break;
}
case VEL: {
if (index >= particles.size())
throw parser_error(
"Config file problem. Velocitie mode than partiles is.");
particles[index].vel = *get_vector(cur_line);
++index;
break;
}
default: { break; }
}
}
}
}
file.close();
}
};
}
}
#endif // X_SPHMODEL
|
/*******************************************************************************
* The MIT License (MIT)
*
* Copyright (c) 2011, 2017 OpenWorm.
* http://openworm.org
*
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the MIT License
* which accompanies this distribution, and is available at
* http://opensource.org/licenses/MIT
*
* Contributors:
* OpenWorm - http://openworm.org/people.html
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
* DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
* OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
* USE OR OTHER DEALINGS IN THE SOFTWARE.
*******************************************************************************/
#ifndef X_SPHMODEL
#define X_SPHMODEL
#include "particle.h"
#include "util/x_error.h"
#include <array>
#include <fstream>
#include <iostream>
#include <map>
#include <memory>
#include <regex>
#include <string>
#include <vector>
namespace x_engine {
namespace model {
enum LOADMODE { NOMODE = -1, PARAMS, MODEL, POS, VEL };
template <class T = float, class container = std::vector<particle<T>>>
class sph_model {
typedef std::map<std::string, size_t> sph_config;
public:
sph_model(const std::string &config_file) {
config = {{"particles", 0}, {"x_max", 0}, {"x_min", 0}, {"y_max", 0},
{"y_min", 0}, {"z_max", 0}, {"z_min", 0}};
read_model(config_file);
std::cout << "Model was loaded: " << particles.size() << " partticles."
<< std::endl;
}
const sph_config &get_config() const { return config; }
private:
container particles;
sph_config config;
std::map<std::string, T> phys_consts;
std::shared_ptr<std::array<T, 4>> get_vector(const std::string &line) {
std::shared_ptr<std::array<T, 4>> v(new std::array<T, 4>());
std::stringstream ss(line);
ss >> (*v)[0] >> (*v)[1] >> (*v)[2] >> (*v)[3]; // TODO check here!!!
return v;
}
void read_model(const std::string &model_file) {
std::ifstream file(model_file.c_str(), std::ios_base::binary);
LOADMODE mode = NOMODE;
bool is_model_mode = false;
int index = 0;
if (file.is_open()) {
while (file.good()) {
std::string cur_line;
std::getline(file, cur_line);
if (mode == NOMODE) {
cur_line.erase(std::remove(cur_line.begin(), cur_line.end(), ' '),
cur_line.end());
cur_line.erase(std::remove(cur_line.begin(), cur_line.end(), '\t'),
cur_line.end());
}
if (cur_line.compare("parametrs[") == 0) {
mode = PARAMS;
continue;
} else if (cur_line.compare("model[") == 0) {
mode = MODEL;
is_model_mode = true;
continue;
} else if (cur_line.compare("position[") == 0) {
mode = POS;
continue;
} else if (cur_line.compare("velocity[") == 0) {
mode = VEL;
continue;
} else if (cur_line.compare("]") == 0) {
mode = NOMODE;
continue;
}
if (mode == PARAMS) {
std::regex rgx("[\\t ]*(\\w+) *: *(\\d+) *([//]*.*)");
std::smatch matches;
if (std::regex_search(cur_line, matches, rgx)) {
if (matches.size() > 2) {
if (config.find(matches[1]) != config.end()) {
config[matches[1]] =
static_cast<size_t>(stoi(matches[2].str()));
continue;
}
} else {
std::string msg = x_engine::make_msg(
"Problem with parsing parametrs:", matches[0].str(),
"Please check parametrs.");
throw parser_error(msg);
}
} else {
throw parser_error(
"Please check parametrs section there are no parametrs.");
}
}
if (is_model_mode) {
switch (mode) {
case POS: {
particle<T> p;
p.pos = *get_vector(cur_line);
particles.push_back(p);
break;
}
case VEL: {
if (index >= particles.size())
throw parser_error(
"Config file problem. Velocities more than partiles is.");
particles[index].vel = *get_vector(cur_line);
++index;
break;
}
default: { break; }
}
}
}
}
file.close();
}
};
}
}
#endif // X_SPHMODEL
|
work with reader
|
work with reader
|
C++
|
mit
|
skhayrulin/x_engine,skhayrulin/x_engine,skhayrulin/x_engine
|
8bd09d8701f32fedcb06f18b18aace8aeb81d43f
|
window.cc
|
window.cc
|
/*-
* Copyright (c) 2016 Frederic Culot <[email protected]>
* 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
* in this position and unchanged.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE AUTHOR(S) ``AS IS'' AND ANY EXPRESS OR
* IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
* OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
* IN NO EVENT SHALL THE AUTHOR(S) 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 <stdexcept>
#include <curses.h>
#include "window.h"
namespace portal {
namespace gfx {
class Window::Impl {
public:
WINDOW* win {nullptr};
Size size;
Point pos;
Style style;
bool borders {true};
// XXX Add a Point posCursor to allow for multi lines text
bool initialized() const;
void create();
void resize();
void move();
void destroy();
void toggleBorders();
void draw();
void applyStyle();
void drawBorders();
void print(const std::string& msg);
};
Window::Window() : impl_{new Impl} {
impl_->create();
}
Window::Window(const Size& size, const Point& pos): impl_{new Impl} {
impl_->size = size;
impl_->pos = pos;
impl_->create();
impl_->draw();
}
Window::~Window() {
impl_->destroy();
}
void Window::setSize(const Size& size) {
if (impl_->size != size) {
impl_->size = size;
impl_->resize();
}
}
void Window::setPosition(const Point& pos) {
if (impl_->pos != pos) {
impl_->pos = pos;
impl_->move();
}
}
void Window::setStyle(const Style& style) {
impl_->style = style;
}
Size Window::size() const {
return impl_->size;
}
Point Window::position() const {
return impl_->pos;
}
void Window::showBorders(bool borders) {
if (impl_->borders != borders) {
impl_->toggleBorders();
}
}
void Window::print(const std::string& msg) {
impl_->print(msg);
}
void Window::draw() {
impl_->draw();
}
void Window::clear() {
werase(impl_->win);
impl_->draw();
}
bool Window::Impl::initialized() const {
return win != nullptr;
}
void Window::Impl::create() {
if (initialized()) {
throw std::runtime_error("Window::Impl::create() - Object already initialized");
}
win = newwin(size.height(), size.width(), pos.y(), pos.x());
}
void Window::Impl::resize() {
wresize(win, size.height(), size.width());
}
void Window::Impl::move() {
mvwin(win, pos.y(), pos.x());
}
void Window::Impl::destroy() {
if (!initialized()) {
throw std::runtime_error("Window::Impl::destroy() - Object already destroyed");
}
delwin(win);
}
void Window::Impl::toggleBorders() {
borders = !borders;
draw();
}
void Window::Impl::draw() {
applyStyle();
drawBorders();
wrefresh(win);
}
void Window::Impl::applyStyle() {
// XXX use posCursor
if (style.underline) {
mvwchgat(win, 0, 0, size.width(), A_UNDERLINE, 0, nullptr);
}
if (style.highlight) {
mvwchgat(win, 0, 0, size.width(), A_STANDOUT, 0, nullptr);
}
}
void Window::Impl::drawBorders() {
if (borders) {
box(win, 0, 0);
}
}
void Window::Impl::print(const std::string& msg) {
int offset = borders ? 1 : 0;
mvwaddstr(win, offset, offset, msg.c_str());
wnoutrefresh(win);
}
}
}
|
/*-
* Copyright (c) 2016 Frederic Culot <[email protected]>
* 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
* in this position and unchanged.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE AUTHOR(S) ``AS IS'' AND ANY EXPRESS OR
* IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
* OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
* IN NO EVENT SHALL THE AUTHOR(S) 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 <stdexcept>
#include <curses.h>
#include "window.h"
namespace portal {
namespace gfx {
class Window::Impl {
public:
WINDOW* win {nullptr};
Size size;
Point pos;
Style style;
bool borders {true};
// XXX Add a Point posCursor to allow for text spanning multi lines
bool initialized() const;
void create();
void resize();
void move();
void destroy();
void toggleBorders();
void draw();
void applyStyle();
void drawBorders();
void print(const std::string& msg);
};
Window::Window() : impl_{new Impl} {
impl_->create();
}
Window::Window(const Size& size, const Point& pos): impl_{new Impl} {
impl_->size = size;
impl_->pos = pos;
impl_->create();
impl_->draw();
}
Window::~Window() {
impl_->destroy();
}
void Window::setSize(const Size& size) {
if (impl_->size != size) {
impl_->size = size;
impl_->resize();
}
}
void Window::setPosition(const Point& pos) {
if (impl_->pos != pos) {
impl_->pos = pos;
impl_->move();
}
}
void Window::setStyle(const Style& style) {
impl_->style = style;
}
Size Window::size() const {
return impl_->size;
}
Point Window::position() const {
return impl_->pos;
}
void Window::showBorders(bool borders) {
if (impl_->borders != borders) {
impl_->toggleBorders();
}
}
void Window::print(const std::string& msg) {
impl_->print(msg);
}
void Window::draw() {
impl_->draw();
}
void Window::clear() {
werase(impl_->win);
impl_->draw();
}
bool Window::Impl::initialized() const {
return win != nullptr;
}
void Window::Impl::create() {
if (initialized()) {
throw std::runtime_error("Window::Impl::create() - Object already initialized");
}
win = newwin(size.height(), size.width(), pos.y(), pos.x());
}
void Window::Impl::resize() {
wresize(win, size.height(), size.width());
}
void Window::Impl::move() {
mvwin(win, pos.y(), pos.x());
}
void Window::Impl::destroy() {
if (!initialized()) {
throw std::runtime_error("Window::Impl::destroy() - Object already destroyed");
}
delwin(win);
}
void Window::Impl::toggleBorders() {
borders = !borders;
draw();
}
void Window::Impl::draw() {
applyStyle();
drawBorders();
wrefresh(win);
}
void Window::Impl::applyStyle() {
if (style.underline) {
mvwchgat(win, 0, 0, size.width(), A_UNDERLINE, 0, nullptr);
}
if (style.highlight) {
mvwchgat(win, 0, 0, size.width(), A_STANDOUT, 0, nullptr);
}
}
void Window::Impl::drawBorders() {
if (borders) {
box(win, 0, 0);
}
}
void Window::Impl::print(const std::string& msg) {
int offset = borders ? 1 : 0;
mvwaddstr(win, offset, offset, msg.c_str());
wnoutrefresh(win);
}
}
}
|
Comment tweak
|
Comment tweak
|
C++
|
bsd-2-clause
|
culot/portal
|
3a264ed838f5b0c5bbff6f75ce952192ec66012d
|
firmware/Adafruit_HDC1000.cpp
|
firmware/Adafruit_HDC1000.cpp
|
/***************************************************
This is a library for the HDC1000 Humidity & Temp Sensor
Designed specifically to work with the HDC1008 sensor from Adafruit
----> https://www.adafruit.com/products/2635
These sensors use I2C to communicate, 2 pins are required to
interface
Adafruit invests time and resources providing this open source code,
please support Adafruit and open-source hardware by purchasing
products from Adafruit!
Written by Limor Fried/Ladyada for Adafruit Industries.
BSD license, all text above must be included in any redistribution
Modified for Photon needs application.h for types RMB
****************************************************/
#include "application.h"
#include "Adafruit_HDC1000/Adafruit_HDC1000.h"
Adafruit_HDC1000::Adafruit_HDC1000() {
}
boolean Adafruit_HDC1000::begin(uint8_t addr) {
_i2caddr = addr;
Wire.begin();
reset();
if (read16(HDC1000_MANUFID) != 0x5449) return false;
if (read16(HDC1000_DEVICEID) != 0x1000) return false;
return true;
}
void Adafruit_HDC1000::reset(void) {
// reset,combined temp/humidity measurement, and select 14 bit temp & humidity resolution
uint16_t config = HDC1000_CONFIG_RST | HDC1000_CONFIG_MODE | HDC1000_CONFIG_TRES_14 | HDC1000_CONFIG_HRES_14;
Wire.beginTransmission(_i2caddr);
Wire.write(HDC1000_CONFIG); // set pointer register to configuration register RMB
Wire.write(config>>8); // now write out 2 bytes MSB first RMB
Wire.write(config&0xFF);
Wire.endTransmission();
delay(15);
}
float Adafruit_HDC1000::readTemperature(void) {
float temp = (read32(HDC1000_TEMP, 20) >> 16);
temp /= 65536;
temp *= 165;
temp -= 40;
return temp;
}
float Adafruit_HDC1000::readHumidity(void) {
// original code used HDC1000_TEMP register, doesn't work with HDC1000_HUMID with 32bit read RMB
float hum = (read32(HDC1000_TEMP, 20) & 0xFFFF);
hum /= 65536;
hum *= 100;
return hum;
}
// Add ability to test battery voltage, useful in remote monitoring, TRUE if <2.8V
// Thanks to KFricke for micropython-hdc1008 on GitHub, usually called after Temp/Humid reading RMB
bool Adafruit_HDC1000::batteryLOW(void) {
uint16_t battV = (read16(HDC1000_CONFIG_BATT, 20));
battV &= HDC1000_CONFIG_BATT; // mask off other bits
return bool battV;
}
/*********************************************************************/
uint16_t Adafruit_HDC1000::read16(uint8_t a, uint8_t d) {
Wire.beginTransmission(_i2caddr);
Wire.write(a);
Wire.endTransmission();
delay(d);
Wire.requestFrom((uint8_t)_i2caddr, (uint8_t)2);
uint16_t r = Wire.read();
r <<= 8;
r |= Wire.read();
//Serial.println(r, HEX);
return r;
}
uint32_t Adafruit_HDC1000::read32(uint8_t a, uint8_t d) {
Wire.beginTransmission(_i2caddr);
Wire.write(a);
Wire.endTransmission();
delay(50);
Wire.requestFrom((uint8_t)_i2caddr, (uint8_t)4);
uint32_t r = Wire.read();
r <<= 8;
r |= Wire.read();
r <<= 8;
r |= Wire.read();
r <<= 8;
r |= Wire.read();
//Serial.println(r, HEX);
return r;
}
|
/***************************************************
This is a library for the HDC1000 Humidity & Temp Sensor
Designed specifically to work with the HDC1008 sensor from Adafruit
----> https://www.adafruit.com/products/2635
These sensors use I2C to communicate, 2 pins are required to
interface
Adafruit invests time and resources providing this open source code,
please support Adafruit and open-source hardware by purchasing
products from Adafruit!
Written by Limor Fried/Ladyada for Adafruit Industries.
BSD license, all text above must be included in any redistribution
Modified for Photon needs application.h for types RMB
****************************************************/
#include "application.h"
#include "Adafruit_HDC1000/Adafruit_HDC1000.h"
Adafruit_HDC1000::Adafruit_HDC1000() {
}
boolean Adafruit_HDC1000::begin(uint8_t addr) {
_i2caddr = addr;
Wire.begin();
reset();
if (read16(HDC1000_MANUFID) != 0x5449) return false;
if (read16(HDC1000_DEVICEID) != 0x1000) return false;
return true;
}
void Adafruit_HDC1000::reset(void) {
// reset,combined temp/humidity measurement, and select 14 bit temp & humidity resolution
uint16_t config = HDC1000_CONFIG_RST | HDC1000_CONFIG_MODE | HDC1000_CONFIG_TRES_14 | HDC1000_CONFIG_HRES_14;
Wire.beginTransmission(_i2caddr);
Wire.write(HDC1000_CONFIG); // set pointer register to configuration register RMB
Wire.write(config>>8); // now write out 2 bytes MSB first RMB
Wire.write(config&0xFF);
Wire.endTransmission();
delay(15);
}
float Adafruit_HDC1000::readTemperature(void) {
float temp = (read32(HDC1000_TEMP, 20) >> 16);
temp /= 65536;
temp *= 165;
temp -= 40;
return temp;
}
float Adafruit_HDC1000::readHumidity(void) {
// original code used HDC1000_TEMP register, doesn't work with HDC1000_HUMID with 32bit read RMB
float hum = (read32(HDC1000_TEMP, 20) & 0xFFFF);
hum /= 65536;
hum *= 100;
return hum;
}
// Add ability to test battery voltage, useful in remote monitoring, TRUE if <2.8V
// Thanks to KFricke for micropython-hdc1008 on GitHub, usually called after Temp/Humid reading RMB
bool Adafruit_HDC1000::batteryLOW(void) {
uint16_t battV = (read16(HDC1000_CONFIG_BATT, 20));
bool battV &= HDC1000_CONFIG_BATT; // mask off other bits
return battV;
}
/*********************************************************************/
uint16_t Adafruit_HDC1000::read16(uint8_t a, uint8_t d) {
Wire.beginTransmission(_i2caddr);
Wire.write(a);
Wire.endTransmission();
delay(d);
Wire.requestFrom((uint8_t)_i2caddr, (uint8_t)2);
uint16_t r = Wire.read();
r <<= 8;
r |= Wire.read();
//Serial.println(r, HEX);
return r;
}
uint32_t Adafruit_HDC1000::read32(uint8_t a, uint8_t d) {
Wire.beginTransmission(_i2caddr);
Wire.write(a);
Wire.endTransmission();
delay(50);
Wire.requestFrom((uint8_t)_i2caddr, (uint8_t)4);
uint32_t r = Wire.read();
r <<= 8;
r |= Wire.read();
r <<= 8;
r |= Wire.read();
r <<= 8;
r |= Wire.read();
//Serial.println(r, HEX);
return r;
}
|
convert to bool before return
|
convert to bool before return
|
C++
|
bsd-2-clause
|
CaptIgmu/Adafruit_HDC1000,CaptIgmu/Adafruit_HDC1000
|
72a8579da0b2fa0c71fc7bb9cac069569b264ef4
|
vulkan/buffer_pool.cpp
|
vulkan/buffer_pool.cpp
|
/* Copyright (c) 2017 Hans-Kristian Arntzen
*
* 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 "buffer_pool.hpp"
#include "device.hpp"
#include <utility>
using namespace std;
namespace Vulkan
{
void BufferPool::init(Device *device, VkDeviceSize block_size, VkDeviceSize alignment, VkBufferUsageFlags usage)
{
this->device = device;
this->block_size = block_size;
this->alignment = alignment;
this->usage = usage;
}
void BufferPool::reset()
{
blocks.clear();
}
BufferBlock BufferPool::allocate_block(VkDeviceSize size)
{
BufferDomain ideal_domain = (usage & ~VK_BUFFER_USAGE_TRANSFER_SRC_BIT) != 0 ? BufferDomain::Device : BufferDomain::Host;
VkBufferUsageFlags extra_usage = ideal_domain == BufferDomain::Device ? VK_BUFFER_USAGE_TRANSFER_DST_BIT : 0;
BufferBlock block;
block.gpu = device->create_buffer({ ideal_domain, size, usage | extra_usage }, nullptr);
block.gpu->set_internal_sync_object();
// Try to map it, will fail unless the memory is host visible.
block.mapped = static_cast<uint8_t *>(device->map_host_buffer(*block.gpu, MEMORY_ACCESS_WRITE));
if (!block.mapped)
{
// Fall back to host memory, and remember to sync to gpu on submission time using DMA queue. :)
block.cpu = device->create_buffer({ BufferDomain::Host, size, VK_BUFFER_USAGE_TRANSFER_SRC_BIT }, nullptr);
block.cpu->set_internal_sync_object();
block.mapped = static_cast<uint8_t *>(device->map_host_buffer(*block.cpu, MEMORY_ACCESS_WRITE));
}
else
block.cpu = block.gpu;
block.offset = 0;
block.alignment = alignment;
block.size = size;
return block;
}
BufferBlock BufferPool::request_block(VkDeviceSize minimum_size)
{
if ((minimum_size > block_size) || blocks.empty())
{
return allocate_block(max(block_size, minimum_size));
}
else
{
auto back = move(blocks.back());
blocks.pop_back();
back.mapped = static_cast<uint8_t *>(device->map_host_buffer(*back.cpu, MEMORY_ACCESS_WRITE));
back.offset = 0;
return back;
}
}
void BufferPool::recycle_block(BufferBlock &&block)
{
VK_ASSERT(block.size == block_size);
blocks.push_back(move(block));
}
}
|
/* Copyright (c) 2017 Hans-Kristian Arntzen
*
* 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 "buffer_pool.hpp"
#include "device.hpp"
#include <utility>
using namespace std;
namespace Vulkan
{
void BufferPool::init(Device *device, VkDeviceSize block_size, VkDeviceSize alignment, VkBufferUsageFlags usage)
{
this->device = device;
this->block_size = block_size;
this->alignment = alignment;
this->usage = usage;
}
void BufferPool::reset()
{
blocks.clear();
}
BufferBlock BufferPool::allocate_block(VkDeviceSize size)
{
BufferDomain ideal_domain = (usage & ~VK_BUFFER_USAGE_TRANSFER_SRC_BIT) != 0 ? BufferDomain::Device : BufferDomain::Host;
VkBufferUsageFlags extra_usage = ideal_domain == BufferDomain::Device ? VK_BUFFER_USAGE_TRANSFER_DST_BIT : 0;
BufferBlock block;
BufferCreateInfo info;
info.domain = ideal_domain;
info.size = size;
info.usage = usage | extra_usage;
block.gpu = device->create_buffer(info, nullptr);
block.gpu->set_internal_sync_object();
// Try to map it, will fail unless the memory is host visible.
block.mapped = static_cast<uint8_t *>(device->map_host_buffer(*block.gpu, MEMORY_ACCESS_WRITE));
if (!block.mapped)
{
// Fall back to host memory, and remember to sync to gpu on submission time using DMA queue. :)
BufferCreateInfo cpu_info;
cpu_info.domain = BufferDomain::Host;
cpu_info.size = size;
cpu_info.usage = VK_BUFFER_USAGE_TRANSFER_SRC_BIT;
block.cpu = device->create_buffer(cpu_info, nullptr);
block.cpu->set_internal_sync_object();
block.mapped = static_cast<uint8_t *>(device->map_host_buffer(*block.cpu, MEMORY_ACCESS_WRITE));
}
else
block.cpu = block.gpu;
block.offset = 0;
block.alignment = alignment;
block.size = size;
return block;
}
BufferBlock BufferPool::request_block(VkDeviceSize minimum_size)
{
if ((minimum_size > block_size) || blocks.empty())
{
return allocate_block(max(block_size, minimum_size));
}
else
{
auto back = move(blocks.back());
blocks.pop_back();
back.mapped = static_cast<uint8_t *>(device->map_host_buffer(*back.cpu, MEMORY_ACCESS_WRITE));
back.offset = 0;
return back;
}
}
void BufferPool::recycle_block(BufferBlock &&block)
{
VK_ASSERT(block.size == block_size);
blocks.push_back(move(block));
}
}
|
Fix compile error on GCC 4.9.
|
Fix compile error on GCC 4.9.
|
C++
|
mit
|
Themaister/Granite,Themaister/Granite,Themaister/Granite,Themaister/Granite,Themaister/Granite,Themaister/Granite
|
56f3695e1de2201fb307f7660f16a39f596e3cb0
|
include/stack.hpp
|
include/stack.hpp
|
#ifndef stack_cpp
#define stack_cpp
#pragma once
#include <iostream>
#include <memory>
class bitset
{
public:
explicit
bitset(size_t size) /*strong*/;
bitset(bitset const & other) = delete;
auto operator =(bitset const & other)->bitset & = delete;
bitset(bitset && other) = delete;
auto operator =(bitset && other)->bitset & = delete;
auto set(size_t index) /*strong*/ -> void;
auto reset(size_t index) /*strong*/ -> void;
auto test(size_t index) /*strong*/ -> bool;
auto size() /*noexcept*/ -> size_t;
auto counter() /*noexcept*/ -> size_t;
private:
std::unique_ptr<bool[]> ptr_;
size_t size_;
size_t counter_;
};
bitset::bitset(size_t size) : ptr_(std::make_unique<bool[]>(size)), size_(size), counter_(0) {}
auto bitset::set(size_t index) -> void
{ if (index >= 0 && index < size_) {
ptr_[index] = true;
++counter_; }
else throw;
}
auto bitset::reset(size_t index) -> void
{ if (index >= 0 && index < size_)
{
ptr_[index] = false;
--counter_;
}
else throw;
}
auto bitset::test(size_t index) -> bool
{
if (index >= 0 && index < size_)
{
return !ptr_[index];
}
else throw;
}
auto bitset::size() -> size_t
{
return size_;
}
auto bitset::counter() -> size_t
{
return counter_;
}
template <typename T>
class allocator
{
public:
explicit
allocator(std::size_t size = 0) /*strong*/;
allocator(allocator const & other) /*strong*/;
auto operator =(allocator const & other)->allocator & = delete;
~allocator();
auto resize() /*strong*/ -> void;
auto construct(T * ptr, T const & value) /*strong*/ -> void;
auto destroy(T * ptr) /*noexcept*/ -> void;
auto get() /*noexcept*/ -> T *;
auto get() const /*noexcept*/ -> T const *;
auto count() const /*noexcept*/ -> size_t;
auto full() const /*noexcept*/ -> bool;
auto empty() const /*noexcept*/ -> bool;
private:
auto destroy(T * first, T * last) /*noexcept*/ -> void;
auto swap(allocator & other) /*noexcept*/ -> void;
T * ptr_;
size_t size_;
std::unique_ptr<bitset> map_;
};
template <typename T>
class stack
{
public:
explicit
stack(size_t size = 0);
auto operator =(stack const & other) /*strong*/ -> stack &;
auto empty() const /*noexcept*/ -> bool;
auto count() const /*noexcept*/ -> size_t;
auto push(T const & value) /*strong*/ -> void;
auto pop() /*strong*/ -> void;
auto top() /*strong*/ -> T &;
auto top() const /*strong*/ -> T const &;
private:
allocator<T> allocator_;
auto throw_is_empty() const -> void;
};
template <typename T>
allocator<T>::allocator(size_t size) : ptr_((T*)(operator new(size*sizeof(T)))), size_(size), map_(std::make_unique<bitset>(size)) {};
template<typename T>
allocator<T>::allocator(allocator const& other) :
ptr_(static_cast<T*>(operator new(other.size_))),
size_(other.size_), map_(std::make_unique<bitset>(size_)){
for (size_t i; i < size_; i++)
construct(ptr_ + i, other.ptr_[i]);
}
template<typename T>
allocator<T>::~allocator() { operator delete(ptr_); }
template<typename T>
auto allocator<T>::resize() -> void
{
allocator<T> buff(size_ * 2 + (size_ == 0));
for (size_t i = 0; i < size_; i++) construct(buff.ptr_ + i, ptr_[i]);
this->swap(buff);
}
template<typename T>
auto allocator<T>::construct(T * ptr, T const & value)->void {
if (ptr >= ptr_&&ptr < ptr_ + size_&&map_->test(ptr - ptr_)) {
new(ptr)T(value);
map_->set(ptr - ptr_);
}
else throw("error");
}
template<typename T>
auto allocator<T>::destroy(T * ptr) -> void {
ptr->~T();
map_->reset(ptr-ptr_);
}
template<typename T>
auto allocator<T>::destroy(T * first, T * last) -> void
{
for (; first != last; ++first) {
destroy(&*first);
}
}
template<typename T>
auto allocator<T>::get()-> T* {
return ptr_;
}
template<typename T>
auto allocator<T>::get() const -> T const * {
return ptr_;
}
template<typename T>
auto allocator<T>::count() const -> size_t
{
return map_->counter();
}
template<typename T>
auto allocator<T>::full() const -> bool
{
return map_->counter()==size_;
}
template<typename T>
auto allocator<T>::empty() const -> bool
{
return map_->counter()==0;
}
template<typename T>
auto allocator<T>::swap(allocator & other) -> void {
std::swap(ptr_, other.ptr_);
std::swap(map_, other.map_);
std::swap(size_, other.size_);
}
template <typename T>
size_t stack<T>::count() const
{
return allocator_.count();
}
template <typename T>
stack<T>::stack(size_t size) :allocator_(size) {}
template <typename T>
void stack<T>::push(T const &item) {
if (allocator_.full()) allocator_.resize();
allocator_.construct(allocator_.get() + this->count(), item);
}
template<typename T>
void stack<T>::pop()
{
if (this->count() > 0)
allocator_.destroy(allocator_.get() + this->count());
else throw_is_empty();
}
template<typename T>
auto stack<T>::top() -> T &
{
if (allocator_.count() == 0) {
throw_is_empty();
}
return (*(allocator_.get() + allocator_.count() - 1));
}
template<typename T>
auto stack<T>::top() const -> T const &
{
if (allocator_.count() == 0) {
throw_is_empty();
}
return (*(allocator_.get() + allocator_.count() - 1));
}
template<typename T>
auto stack<T>::throw_is_empty() const -> void
{
throw("Stack is empty!");
}
template<typename T>
auto stack<T>::operator=(stack const & right) -> stack & {
if (this != &right) {
stack<T> temp(right.size_);
while (temp.counter() < right.counter()) {
construct(temp.allocator_->get() + temp.allocator.map_->counter(), right.allocator_->get()[temp.allocator_.map_->counter()]);
++temp.allocator_.map_->counter();
}
this->swap(temp);
}
return *this;
}
template<typename T>
auto stack<T>::empty() const -> bool {
return allocator_.empty();
}
#endif
|
#ifndef stack_cpp
#define stack_cpp
#pragma once
#include <iostream>
#include <memory>
class bitset
{
public:
explicit
bitset(size_t size) /*strong*/;
bitset(bitset const & other) = delete;
auto operator =(bitset const & other)->bitset & = delete;
bitset(bitset && other) = delete;
auto operator =(bitset && other)->bitset & = delete;
auto set(size_t index) /*strong*/ -> void;
auto reset(size_t index) /*strong*/ -> void;
auto test(size_t index) /*strong*/ -> bool;
auto size() /*noexcept*/ -> size_t;
auto counter() /*noexcept*/ -> size_t;
private:
std::unique_ptr<bool[]> ptr_;
size_t size_;
size_t counter_;
};
bitset::bitset(size_t size) : ptr_(std::make_unique<bool[]>(size)), size_(size), counter_(0) {}
auto bitset::set(size_t index) -> void
{ if (index >= 0 && index < size_) {
ptr_[index] = true;
++counter_; }
else throw;
}
auto bitset::reset(size_t index) -> void
{ if (index >= 0 && index < size_)
{
ptr_[index] = false;
--counter_;
}
else throw;
}
auto bitset::test(size_t index) -> bool
{
if (index >= 0 && index < size_)
{
return !ptr_[index];
}
else throw;
}
auto bitset::size() -> size_t
{
return size_;
}
auto bitset::counter() -> size_t
{
return counter_;
}
template <typename T>
class allocator
{
public:
explicit
allocator(std::size_t size = 0) /*strong*/;
allocator(allocator const & other) /*strong*/;
auto operator =(allocator const & other)->allocator & = delete;
~allocator();
auto resize() /*strong*/ -> void;
auto construct(T * ptr, T const & value) /*strong*/ -> void;
auto destroy(T * ptr) /*noexcept*/ -> void;
auto get() /*noexcept*/ -> T *;
auto get() const /*noexcept*/ -> T const *;
auto count() const /*noexcept*/ -> size_t;
auto full() const /*noexcept*/ -> bool;
auto empty() const /*noexcept*/ -> bool;
private:
auto destroy(T * first, T * last) /*noexcept*/ -> void;
auto swap(allocator & other) /*noexcept*/ -> void;
T * ptr_;
size_t size_;
std::unique_ptr<bitset> map_;
};
template <typename T>
class stack
{
public:
explicit
stack(size_t size = 0);
auto operator =(stack const & other) /*strong*/ -> stack &;
auto empty() const /*noexcept*/ -> bool;
auto count() const /*noexcept*/ -> size_t;
auto push(T const & value) /*strong*/ -> void;
auto pop() /*strong*/ -> void;
auto top() /*strong*/ -> T &;
auto top() const /*strong*/ -> T const &;
private:
allocator<T> allocator_;
auto throw_is_empty() const -> void;
};
template <typename T>
allocator<T>::allocator(size_t size) : ptr_((T*)(operator new(size*sizeof(T)))), size_(size), map_(std::make_unique<bitset>(size)) {};
template<typename T>
allocator<T>::allocator(allocator const& other) :
ptr_(static_cast<T*>(operator new(other.size_))),
size_(other.size_), map_(std::make_unique<bitset>(size_)){
for (size_t i; i < size_; i++)
construct(ptr_ + i, other.ptr_[i]);
}
template<typename T>
allocator<T>::~allocator() { operator delete(ptr_); }
template<typename T>
auto allocator<T>::resize() -> void
{
allocator<T> buff(size_ * 2 + (size_ == 0));
for (size_t i = 0; i < size_; i++) construct(buff.ptr_ + i, ptr_[i]);
this->swap(buff);
}
template<typename T>
auto allocator<T>::construct(T * ptr, T const & value)->void {
if (ptr >= ptr_&&ptr < ptr_ + size_&&map_->test(ptr - ptr_)) {
new(ptr)T(value);
map_->set(ptr - ptr_);
}
else throw("error");
}
template<typename T>
auto allocator<T>::destroy(T * ptr) -> void {
ptr->~T();
map_->reset(ptr-ptr_);
}
template<typename T>
auto allocator<T>::destroy(T * first, T * last) -> void
{
for (; first != last; ++first) {
destroy(&*first);
}
}
template<typename T>
auto allocator<T>::get()-> T* {
return ptr_;
}
template<typename T>
auto allocator<T>::get() const -> T const * {
return ptr_;
}
template<typename T>
auto allocator<T>::count() const -> size_t
{
return map_->counter();
}
template<typename T>
auto allocator<T>::full() const -> bool
{
return map_->counter()==size_;
}
template<typename T>
auto allocator<T>::empty() const -> bool
{
return map_->counter()==0;
}
template<typename T>
auto allocator<T>::swap(allocator & other) -> void {
std::swap(ptr_, other.ptr_);
std::swap(map_, other.map_);
std::swap(size_, other.size_);
}
template <typename T>
size_t stack<T>::count() const
{
return allocator_.count();
}
template <typename T>
stack<T>::stack(size_t size) :allocator_(size) {}
template <typename T>
void stack<T>::push(T const &item) {
if (allocator_.full()) allocator_.resize();
allocator_.construct(allocator_.get() + this->count(), item);
}
template<typename T>
void stack<T>::pop()
{
if (this->count() > 0)
allocator_.destroy(allocator_.get() + (this->count()-1));
else throw_is_empty();
}
template<typename T>
auto stack<T>::top() -> T &
{
if (allocator_.count() == 0) {
throw_is_empty();
}
return (*(allocator_.get() + allocator_.count() - 1));
}
template<typename T>
auto stack<T>::top() const -> T const &
{
if (allocator_.count() == 0) {
throw_is_empty();
}
return (*(allocator_.get() + allocator_.count() - 1));
}
template<typename T>
auto stack<T>::throw_is_empty() const -> void
{
throw("Stack is empty!");
}
template<typename T>
auto stack<T>::operator=(stack const & right) -> stack & {
if (this != &right) {
stack<T> temp(right.size_);
while (temp.counter() < right.counter()) {
construct(temp.allocator_->get() + temp.allocator.map_->counter(), right.allocator_->get()[temp.allocator_.map_->counter()]);
++temp.allocator_.map_->counter();
}
this->swap(temp);
}
return *this;
}
template<typename T>
auto stack<T>::empty() const -> bool {
return allocator_.empty();
}
#endif
|
Update stack.hpp
|
Update stack.hpp
|
C++
|
mit
|
DANTEpolaris/stack
|
8937ac785ec9119dc6c8e481a26126a95be5185a
|
include/stack.hpp
|
include/stack.hpp
|
#include <iostream>
#include <string>
#include <stdexcept>
using namespace std;
template <typename T>
class Stack {
public:
Stack() noexcept;
explicit Stack(size_t s) noexcept;
Stack(const Stack& u) noexcept;
Stack(Stack&& u) noexcept;
size_t count() const noexcept;
bool empty() const noexcept;
void push(T const &) noexcept;
T& top() const noexcept;
T& pop() noexcept;
~Stack() noexcept;
Stack<T>& operator=(const Stack& u) noexcept;
Stack<T>& operator=(Stack&& u) noexcept;
T& operator[](size_t x) const noexcept;
private:
T* array_;
size_t array_size_;
size_t count_;
};
template <typename T>
Stack<T>::Stack() noexcept : Stack(100) {}
template <typename T>
Stack<T>::Stack(size_t s) noexcept : array_size_(s), array_(new T[s]), count_(0) {}
template <typename T>
Stack<T>::Stack(const Stack& u) noexcept : array_(new T[u.array_size_]), array_size_(u.array_size_), count_(u.count_) {
for(int i = 0; i < count_; i++) {
array_[i] = u.array_[i];
}
}
template <typename T>
Stack<T>& Stack<T>::operator=(const Stack& u) noexcept {
if(this != &u) {
delete[] array_;
count_ = u.count_;
array_size_ = u.array_size_;
array_ = new T[array_size_];
for(int i = 0; i < count_; i++) {
array_[i] = u.array_[i];
}
} else {
throw std::runtime_error("\tIt's the same object...");
}
return *this;
}
template <typename T>
Stack<T>::Stack(Stack&& u) noexcept : array_(u.array_), array_size_(u.array_size_), count_(u.count_) {
u.array_size_ = 0;
u.count_ = 0;
u.array_ = nullptr;
}
template <typename T>
Stack<T>& Stack<T>::operator=(Stack&& u) noexcept {
if(this != &u) {
count_ = u.count_;
array_size_ = u.array_size_;
array_ = u.array_;
u.count_ = 0;
u.array_size_ = 0;
u.array_ = nullptr;
}
return *this;
}
template <typename T>
Stack<T>::~Stack() noexcept {
delete[] array_;
}
template <typename T>
void Stack<T>::push(T const &val) noexcept {
if (count_ == array_size_) {
T* array_exp_ = new T[array_size_*2];
for (int i = 0; i < array_size_; i++) {
array_exp_[i] = array_[i];
}
array_size_ *= 2;
delete[] array_;
array_ = array_exp_;
}
array_[count_++] = val;
}
template <typename T>
T& Stack<T>::pop() noexcept {
if(count_ == 0) throw std::runtime_error("\tStack empty...");
--count_;
return top();
}
template <typename T>
size_t Stack<T>::count() const noexcept {
return count_;
}
template <typename T>
bool Stack<T>::empty() const noexcept {
if (count() == 0) return true;
return false;
}
template <typename T>
T& Stack<T>::top() const noexcept {
return array_[count_];
}
template <typename T>
T& Stack<T>::operator[](size_t x) const noexcept {
return array_[x];
}
|
#include <iostream>
#include <string>
#include <stdexcept>
using namespace std;
template <typename T>
class Stack {
public:
Stack() noexcept;
explicit Stack(size_t s) noexcept;
Stack(const Stack& u) noexcept;
Stack(Stack&& u) noexcept;
size_t count() const noexcept;
bool empty() const noexcept;
void push(T const &) noexcept;
T& top() const noexcept;
T& pop() noexcept;
~Stack() noexcept;
Stack<T>& operator=(const Stack& u) noexcept;
Stack<T>& operator=(Stack&& u) noexcept;
T& operator[](size_t x) const noexcept;
private:
T* array_;
size_t array_size_;
size_t count_;
};
template <typename T>
Stack<T>::Stack() noexcept : Stack(100) {}
template <typename T>
Stack<T>::Stack(size_t s) noexcept : array_size_(s), array_(new T[s]), count_(0) {}
template <typename T>
Stack<T>::Stack(const Stack& u) noexcept : array_(new T[u.array_size_]), array_size_(u.array_size_), count_(u.count_) {
for(int i = 0; i < count_; i++) {
array_[i] = u.array_[i];
}
}
template <typename T>
Stack<T>& Stack<T>::operator=(const Stack& u) noexcept {
if(this != &u) {
delete[] array_;
count_ = u.count_;
array_size_ = u.array_size_;
array_ = new T[array_size_];
for(int i = 0; i < count_; i++) {
array_[i] = u.array_[i];
}
} else {
throw std::runtime_error("\tIt's the same object...");
}
return *this;
}
template <typename T>
Stack<T>::Stack(Stack&& u) noexcept : array_(u.array_), array_size_(u.array_size_), count_(u.count_) {
u.array_size_ = 0;
u.count_ = 0;
u.array_ = nullptr;
}
template <typename T>
Stack<T>& Stack<T>::operator=(Stack&& u) noexcept {
if(this != &u) {
count_ = u.count_;
array_size_ = u.array_size_;
array_ = u.array_;
u.count_ = 0;
u.array_size_ = 0;
u.array_ = nullptr;
}
return *this;
}
template <typename T>
Stack<T>::~Stack() noexcept {
delete[] array_;
}
template <typename T>
void Stack<T>::push(T const &val) noexcept {
if (count_ == array_size_) {
T* array_exp_ = new T[array_size_*2];
for (int i = 0; i < array_size_; i++) {
array_exp_[i] = array_[i];
}
array_size_ *= 2;
delete[] array_;
array_ = array_exp_;
}
array_[count_++] = val;
}
template <typename T>
void Stack<T>::pop() noexcept {
if(count_ == 0) {
throw std::runtime_error("\tStack empty...");
}
--count_;
}
template <typename T>
size_t Stack<T>::count() const noexcept {
return count_;
}
template <typename T>
bool Stack<T>::empty() const noexcept {
if (count() == 0) return true;
return false;
}
template <typename T>
T& Stack<T>::top() const noexcept {
return array_[count_];
}
template <typename T>
T& Stack<T>::operator[](size_t x) const noexcept {
return array_[x];
}
|
Update stack.hpp
|
Update stack.hpp
|
C++
|
mit
|
DespiteDeath/Stack_3
|
56f184b08d83b52ff86e48f4b9a1a09ddf5c64f0
|
rrd/src/lib.cc
|
rrd/src/lib.cc
|
/*
** Copyright 2011-2012 Merethis
**
** This file is part of Centreon Broker.
**
** Centreon Broker is free software: you can redistribute it and/or
** modify it under the terms of the GNU General Public License version 2
** as published by the Free Software Foundation.
**
** Centreon Broker 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 Centreon Broker. If not, see
** <http://www.gnu.org/licenses/>.
*/
#include <ctype.h>
#include <errno.h>
#include <fcntl.h>
#include <QFile>
#include <rrd.h>
#include <sstream>
#include <string.h>
#include <unistd.h>
#include "com/centreon/broker/exceptions/msg.hh"
#include "com/centreon/broker/logging/logging.hh"
#include "com/centreon/broker/rrd/exceptions/open.hh"
#include "com/centreon/broker/rrd/exceptions/update.hh"
#include "com/centreon/broker/rrd/lib.hh"
using namespace com::centreon::broker;
using namespace com::centreon::broker::rrd;
/**************************************
* *
* Public Methods *
* *
**************************************/
/**
* Default constructor.
*/
lib::lib() {}
/**
* Copy constructor.
*
* @param[in] l Object to copy.
*/
lib::lib(lib const& l)
: backend(l), _filename(l._filename), _metric(l._metric) {}
/**
* Destructor.
*/
lib::~lib() {}
/**
* Assignment operator.
*
* @param[in] l Object to copy.
*
* @return This object.
*/
lib& lib::operator=(lib const& l) {
backend::operator=(l);
_filename = l._filename;
_metric = l._metric;
return (*this);
}
/**
* @brief Initiates the bulk load of multiple commands.
*
* With the librrd backend, this method does nothing.
*/
void lib::begin() {
return ;
}
/**
* Close the RRD file.
*/
void lib::close() {
_filename.clear();
_metric.clear();
return ;
}
/**
* @brief Commit transaction started with begin().
*
* With the librrd backend, the method does nothing.
*/
void lib::commit() {
return ;
}
/**
* Normalize a metric name.
*
* @param[in] metric Metric name.
*
* @return Normalized metric name.
*/
QString lib::normalize_metric_name(QString const& metric) {
QString normalized(metric.toLatin1());
normalized.replace("/", "_slash");
normalized.replace("\\", "_bslash");
for (unsigned int i(0), size(normalized.size()); i < size; ++i) {
char current(normalized.at(i).toAscii());
if (!isalnum(current) && (current != '-') && (current != '_'))
normalized.replace(i, 1, '-');
}
if (normalized.isEmpty())
normalized = "x";
else if (normalized.size() > max_metric_length)
normalized.resize(max_metric_length);
if (!isalnum(normalized.at(0).toLatin1()))
normalized.replace(0, 1, 'x');
return (normalized);
}
/**
* Open a RRD file which already exists.
*
* @param[in] filename Path to the RRD file.
* @param[in] metric Metric name.
*/
void lib::open(QString const& filename,
QString const& metric) {
// Close previous file.
this->close();
// Check that the file exists.
if (!QFile::exists(filename))
throw (exceptions::open() << "RRD: file '"
<< filename << "' does not exist");
// Remember information for further operations.
_filename = filename;
_metric = normalize_metric_name(metric);
return ;
}
/**
* Open a RRD file and create it if it does not exists.
*
* @param[in] filename Path to the RRD file.
* @param[in] metric Metric name.
* @param[in] length Number of recording in the RRD file.
* @param[in] from Timestamp of the first record.
* @param[in] interval Time interval between each record.
*/
void lib::open(QString const& filename,
QString const& metric,
unsigned int length,
time_t from,
time_t interval) {
// Close previous file.
this->close();
// Remember informations for further operations.
_filename = filename;
_metric = normalize_metric_name(metric);
/* Find step of RRD file if already existing. */
/* XXX : why is it here ?
rrd_info_t* rrdinfo(rrd_info_r(_filename));
time_t interval_offset(0);
for (rrd_info_t* tmp = rrdinfo; tmp; tmp = tmp->next)
if (!strcmp(rrdinfo->key, "step"))
if (interval < static_cast<time_t>(rrdinfo->value.u_cnt))
interval_offset = rrdinfo->value.u_cnt / interval - 1;
rrd_info_free(rrdinfo);
*/
/* Remove previous file. */
QFile::remove(_filename);
/* Set parameters. */
std::ostringstream ds_oss;
std::ostringstream rra1_oss;
std::ostringstream rra2_oss;
ds_oss << "DS:" << _metric.toStdString() << ":GAUGE:" << interval << ":U:U";
rra1_oss << "RRA:AVERAGE:0.5:1:" << length;
rra2_oss << "RRA:AVERAGE:0.5:12:" << length / 12;
std::string ds(ds_oss.str());
std::string rra1(rra1_oss.str());
std::string rra2(rra2_oss.str());
char const* argv[5];
argv[0] = ds.c_str();
argv[1] = rra1.c_str();
argv[2] = rra2.c_str();
argv[3] = NULL;
// Debug message.
logging::debug << logging::HIGH << "RRD: opening file '" << filename
<< "' (" << argv[0] << ", " << argv[1] << ", " << argv[2]
<< ", interval " << interval << ", from " << from << ")";
// Create RRD file.
rrd_clear_error();
if (rrd_create_r(_filename.toStdString().c_str(),
interval,
from,
3,
argv))
throw (exceptions::open() << "RRD: could not create file '"
<< _filename << "': " << rrd_get_error());
// Set parameters.
std::string fn(_filename.toStdString());
std::string hb;
{
std::ostringstream oss;
oss << qPrintable(_metric) << ":" << interval * 10;
hb = oss.str();
}
argv[0] = "librrd";
argv[1] = fn.c_str();
argv[2] = "-h"; // --heartbeat
argv[3] = hb.c_str();
argv[4] = NULL;
// Tune file.
if (rrd_tune(4, (char**)argv))
logging::error << logging::MEDIUM << "RRD: could not tune "\
"heartbeat of file '" << _filename << "'";
return ;
}
/**
* Update the RRD file with new value.
*
* @param[in] t Timestamp of value.
* @param[in] value Associated value.
*/
void lib::update(time_t t, QString const& value) {
// Build argument string.
std::string arg;
{
std::ostringstream oss;
oss << t << ":" << value.toStdString();
arg = oss.str();
}
// Set argument table.
char const* argv[2];
argv[0] = arg.c_str();
argv[1] = NULL;
// Debug message.
logging::debug << logging::HIGH << "RRD: updating file '"
<< _filename << "' (metric '" << _metric << "', " << argv[0] << ")";
// Update RRD file.
int fd(::open(_filename.toStdString().c_str(), O_WRONLY));
if (fd < 0) {
char const* msg(strerror(errno));
logging::error << logging::MEDIUM << "RRD: could not open file '"
<< _filename << "': " << msg;
}
else {
try {
// Set lock.
flock fl;
memset(&fl, 0, sizeof(fl));
fl.l_type = F_WRLCK;
fl.l_whence = SEEK_SET;
if (-1 == fcntl(fd, F_SETLK, &fl)) {
char const* msg(strerror(errno));
logging::error << logging::MEDIUM << "RRD: could not lock file '"
<< _filename << "': " << msg;
}
else {
rrd_clear_error();
if (rrd_update_r(_filename.toStdString().c_str(),
_metric.toStdString().c_str(),
sizeof(argv) / sizeof(*argv) - 1,
argv))
throw (exceptions::update()
<< "RRD: failed to update value for metric "
<< _metric << ": " << rrd_get_error());
}
}
catch (...) {
::close(fd);
throw ;
}
::close(fd);
}
return ;
}
|
/*
** Copyright 2011-2012 Merethis
**
** This file is part of Centreon Broker.
**
** Centreon Broker is free software: you can redistribute it and/or
** modify it under the terms of the GNU General Public License version 2
** as published by the Free Software Foundation.
**
** Centreon Broker 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 Centreon Broker. If not, see
** <http://www.gnu.org/licenses/>.
*/
#include <ctype.h>
#include <errno.h>
#include <fcntl.h>
#include <QFile>
#include <rrd.h>
#include <sstream>
#include <string.h>
#include <unistd.h>
#include "com/centreon/broker/exceptions/msg.hh"
#include "com/centreon/broker/logging/logging.hh"
#include "com/centreon/broker/rrd/exceptions/open.hh"
#include "com/centreon/broker/rrd/exceptions/update.hh"
#include "com/centreon/broker/rrd/lib.hh"
using namespace com::centreon::broker;
using namespace com::centreon::broker::rrd;
/**************************************
* *
* Public Methods *
* *
**************************************/
/**
* Default constructor.
*/
lib::lib() {}
/**
* Copy constructor.
*
* @param[in] l Object to copy.
*/
lib::lib(lib const& l)
: backend(l), _filename(l._filename), _metric(l._metric) {}
/**
* Destructor.
*/
lib::~lib() {}
/**
* Assignment operator.
*
* @param[in] l Object to copy.
*
* @return This object.
*/
lib& lib::operator=(lib const& l) {
backend::operator=(l);
_filename = l._filename;
_metric = l._metric;
return (*this);
}
/**
* @brief Initiates the bulk load of multiple commands.
*
* With the librrd backend, this method does nothing.
*/
void lib::begin() {
return ;
}
/**
* Close the RRD file.
*/
void lib::close() {
_filename.clear();
_metric.clear();
return ;
}
/**
* @brief Commit transaction started with begin().
*
* With the librrd backend, the method does nothing.
*/
void lib::commit() {
return ;
}
/**
* Normalize a metric name.
*
* @param[in] metric Metric name.
*
* @return Normalized metric name.
*/
QString lib::normalize_metric_name(QString const& metric) {
QString normalized(metric.toLatin1());
normalized.replace("/", "_slash");
normalized.replace("\\", "_bslash");
for (unsigned int i(0), size(normalized.size()); i < size; ++i) {
char current(normalized.at(i).toAscii());
if (!isalnum(current) && (current != '-') && (current != '_'))
normalized.replace(i, 1, '-');
}
if (normalized.isEmpty())
normalized = "x";
else if (normalized.size() > max_metric_length)
normalized.resize(max_metric_length);
if (!isalnum(normalized.at(0).toLatin1()))
normalized.replace(0, 1, 'x');
return (normalized);
}
/**
* Open a RRD file which already exists.
*
* @param[in] filename Path to the RRD file.
* @param[in] metric Metric name.
*/
void lib::open(QString const& filename,
QString const& metric) {
// Close previous file.
this->close();
// Check that the file exists.
if (!QFile::exists(filename))
throw (exceptions::open() << "RRD: file '"
<< filename << "' does not exist");
// Remember information for further operations.
_filename = filename;
_metric = normalize_metric_name(metric);
return ;
}
/**
* Open a RRD file and create it if it does not exists.
*
* @param[in] filename Path to the RRD file.
* @param[in] metric Metric name.
* @param[in] length Number of recording in the RRD file.
* @param[in] from Timestamp of the first record.
* @param[in] interval Time interval between each record.
*/
void lib::open(QString const& filename,
QString const& metric,
unsigned int length,
time_t from,
time_t interval) {
// Close previous file.
this->close();
// Remember informations for further operations.
_filename = filename;
_metric = normalize_metric_name(metric);
/* Find step of RRD file if already existing. */
/* XXX : why is it here ?
rrd_info_t* rrdinfo(rrd_info_r(_filename));
time_t interval_offset(0);
for (rrd_info_t* tmp = rrdinfo; tmp; tmp = tmp->next)
if (!strcmp(rrdinfo->key, "step"))
if (interval < static_cast<time_t>(rrdinfo->value.u_cnt))
interval_offset = rrdinfo->value.u_cnt / interval - 1;
rrd_info_free(rrdinfo);
*/
/* Remove previous file. */
QFile::remove(_filename);
/* Set parameters. */
std::ostringstream ds_oss;
std::ostringstream rra1_oss;
std::ostringstream rra2_oss;
ds_oss << "DS:" << _metric.toStdString() << ":GAUGE:" << interval << ":U:U";
rra1_oss << "RRA:AVERAGE:0.5:1:" << length;
rra2_oss << "RRA:AVERAGE:0.5:12:" << length / 12;
std::string ds(ds_oss.str());
std::string rra1(rra1_oss.str());
std::string rra2(rra2_oss.str());
char const* argv[5];
argv[0] = ds.c_str();
argv[1] = rra1.c_str();
argv[2] = rra2.c_str();
argv[3] = NULL;
// Debug message.
logging::debug << logging::HIGH << "RRD: opening file '" << filename
<< "' (" << argv[0] << ", " << argv[1] << ", " << argv[2]
<< ", interval " << interval << ", from " << from << ")";
// Create RRD file.
rrd_clear_error();
if (rrd_create_r(_filename.toStdString().c_str(),
interval,
from,
3,
argv))
throw (exceptions::open() << "RRD: could not create file '"
<< _filename << "': " << rrd_get_error());
// Set parameters.
std::string fn(_filename.toStdString());
std::string hb;
{
std::ostringstream oss;
oss << qPrintable(_metric) << ":" << interval * 10;
hb = oss.str();
}
argv[0] = "librrd";
argv[1] = fn.c_str();
argv[2] = "-h"; // --heartbeat
argv[3] = hb.c_str();
argv[4] = NULL;
// Tune file.
if (rrd_tune(4, (char**)argv))
logging::error << logging::MEDIUM << "RRD: could not tune "\
"heartbeat of file '" << _filename << "'";
return ;
}
/**
* Update the RRD file with new value.
*
* @param[in] t Timestamp of value.
* @param[in] value Associated value.
*/
void lib::update(time_t t, QString const& value) {
// Build argument string.
std::string arg;
{
std::ostringstream oss;
oss << t << ":" << value.toStdString();
arg = oss.str();
}
// Set argument table.
char const* argv[2];
argv[0] = arg.c_str();
argv[1] = NULL;
// Debug message.
logging::debug << logging::HIGH << "RRD: updating file '"
<< _filename << "' (metric '" << _metric << "', " << argv[0] << ")";
// Update RRD file.
int fd(::open(_filename.toStdString().c_str(), O_WRONLY));
if (fd < 0) {
char const* msg(strerror(errno));
logging::error << logging::MEDIUM << "RRD: could not open file '"
<< _filename << "': " << msg;
}
else {
try {
// Set lock.
struct flock fl;
memset(&fl, 0, sizeof(fl));
fl.l_type = F_WRLCK;
fl.l_whence = SEEK_SET;
if (-1 == fcntl(fd, F_SETLK, &fl)) {
char const* msg(strerror(errno));
logging::error << logging::MEDIUM << "RRD: could not lock file '"
<< _filename << "': " << msg;
}
else {
rrd_clear_error();
if (rrd_update_r(_filename.toStdString().c_str(),
_metric.toStdString().c_str(),
sizeof(argv) / sizeof(*argv) - 1,
argv))
throw (exceptions::update()
<< "RRD: failed to update value for metric "
<< _metric << ": " << rrd_get_error());
}
}
catch (...) {
::close(fd);
throw ;
}
::close(fd);
}
return ;
}
|
Fix compilation error on FreeBSD.
|
Fix compilation error on FreeBSD.
git-svn-id: a49aa41e49c69a6ab6ef43f172843a2fef6cb475@1053 7c7d615a-03b3-410d-a316-1135b1bd9499
|
C++
|
apache-2.0
|
centreon/centreon-broker,centreon/centreon-broker,centreon/centreon-broker,centreon/centreon-broker,centreon/centreon-broker
|
b92b742e4067a354af0372e1adf4f289020b6d2d
|
Modules/Wrappers/ApplicationEngine/src/otbWrapperComplexInputImageParameter.cxx
|
Modules/Wrappers/ApplicationEngine/src/otbWrapperComplexInputImageParameter.cxx
|
/*
* Copyright (C) 2005-2017 Centre National d'Etudes Spatiales (CNES)
*
* This file is part of Orfeo Toolbox
*
* https://www.orfeo-toolbox.org/
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "otbWrapperComplexInputImageParameter.h"
#include "itksys/SystemTools.hxx"
#include "otbWrapperTypes.h"
namespace otb
{
namespace Wrapper
{
ComplexInputImageParameter::ComplexInputImageParameter()
{
this->SetName("Complex Input Image");
this->SetKey("cin");
m_FileName="";
m_PreviousFileName="";
m_UseFilename = true;
this->ClearValue();
}
ComplexInputImageParameter::~ComplexInputImageParameter()
{
}
bool
ComplexInputImageParameter::SetFromFileName(const std::string& filename)
{
// First clear previous file chosen
this->ClearValue();
// No file existence is done here :
// - Done in the reader
// - allow appending additional information to the filename
// myfile.tif:2 for example, or myfile.tif:nocarto
m_FileName = filename;
m_UseFilename = true;
SetActive(true);
return true;
}
ComplexFloatVectorImageType*
ComplexInputImageParameter::GetImage()
{
return this->GetImage<ComplexFloatVectorImageType>();
}
#define otbGetImageMacro(image) \
image##Type * \
ComplexInputImageParameter::Get##image () \
{ \
return this->GetImage< image##Type > (); \
}
otbGetImageMacro(ComplexFloatImage);
otbGetImageMacro(ComplexDoubleImage);
otbGetImageMacro(ComplexFloatVectorImage);
otbGetImageMacro(ComplexDoubleVectorImage);
#define otbCastImageMacro(ComplexInputImageType, OutputImageType, theMethod) \
template<> OutputImageType * \
ComplexInputImageParameter::CastImage<ComplexInputImageType , OutputImageType>() \
{ \
return this->theMethod<ComplexInputImageType , OutputImageType>(); \
}
#define otbGenericCastImageMacro(ComplexInputImageType, theMethod, prefix) \
otbCastImageMacro(ComplexInputImageType, ComplexFloat##prefix##ImageType, theMethod) \
otbCastImageMacro(ComplexInputImageType, ComplexDouble##prefix##ImageType, theMethod)
/*********************************************************************
********************** Image -> Image
**********************************************************************/
otbGenericCastImageMacro(ComplexFloatImageType, SimpleCastImage, )
otbGenericCastImageMacro(ComplexDoubleImageType, SimpleCastImage, )
/*********************************************************************
********************** VectorImage -> VectorImage
**********************************************************************/
otbGenericCastImageMacro(ComplexFloatVectorImageType, SimpleCastImage, Vector)
otbGenericCastImageMacro(ComplexDoubleVectorImageType, SimpleCastImage, Vector)
void
ComplexInputImageParameter::SetImage(ComplexFloatVectorImageType* image)
{
m_UseFilename = false;
this->SetImage<ComplexFloatVectorImageType>( image );
}
bool
ComplexInputImageParameter::HasValue() const
{
if( m_FileName.empty() && m_Image.IsNull() )
return false;
else
return true;
}
void
ComplexInputImageParameter::ClearValue()
{
m_Image = ITK_NULLPTR;
m_Reader = ITK_NULLPTR;
m_Caster = ITK_NULLPTR;
m_FileName = "";
m_PreviousFileName="";
m_UseFilename = true;
}
/* Support for ComplexInputImageParameter. This has been done to support
the macro otbGetParameterImageMacro of otbWrapperApplication.h */
#define otbGetFalseImageMacro(image) \
image##Type * \
ComplexInputImageParameter::Get##image () \
{ \
return nullptr; \
}
otbGetFalseImageMacro(DoubleImage);
otbGetFalseImageMacro(DoubleVectorImage);
otbGetFalseImageMacro(FloatImage);
otbGetFalseImageMacro(FloatVectorImage);
otbGetFalseImageMacro(Int16Image);
otbGetFalseImageMacro(Int16VectorImage);
otbGetFalseImageMacro(UInt16Image);
otbGetFalseImageMacro(UInt16VectorImage);
otbGetFalseImageMacro(Int32Image);
otbGetFalseImageMacro(Int32VectorImage);
otbGetFalseImageMacro(UInt32Image);
otbGetFalseImageMacro(UInt32VectorImage);
otbGetFalseImageMacro(UInt8Image);
otbGetFalseImageMacro(UInt8VectorImage);
}
}
|
/*
* Copyright (C) 2005-2017 Centre National d'Etudes Spatiales (CNES)
*
* This file is part of Orfeo Toolbox
*
* https://www.orfeo-toolbox.org/
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "otbWrapperComplexInputImageParameter.h"
#include "itksys/SystemTools.hxx"
#include "otbWrapperTypes.h"
namespace otb
{
namespace Wrapper
{
ComplexInputImageParameter::ComplexInputImageParameter()
{
this->SetName("Complex Input Image");
this->SetKey("cin");
m_FileName="";
m_PreviousFileName="";
m_UseFilename = true;
this->ClearValue();
}
ComplexInputImageParameter::~ComplexInputImageParameter()
{
}
bool
ComplexInputImageParameter::SetFromFileName(const std::string& filename)
{
// First clear previous file chosen
this->ClearValue();
// No file existence is done here :
// - Done in the reader
// - allow appending additional information to the filename
// myfile.tif:2 for example, or myfile.tif:nocarto
m_FileName = filename;
m_UseFilename = true;
SetActive(true);
return true;
}
ComplexFloatVectorImageType*
ComplexInputImageParameter::GetImage()
{
return this->GetImage<ComplexFloatVectorImageType>();
}
#define otbGetImageMacro(image) \
image##Type * \
ComplexInputImageParameter::Get##image () \
{ \
return this->GetImage< image##Type > (); \
}
otbGetImageMacro(ComplexFloatImage);
otbGetImageMacro(ComplexDoubleImage);
otbGetImageMacro(ComplexFloatVectorImage);
otbGetImageMacro(ComplexDoubleVectorImage);
#define otbCastImageMacro(ComplexInputImageType, OutputImageType, theMethod) \
template<> OutputImageType * \
ComplexInputImageParameter::CastImage<ComplexInputImageType , OutputImageType>() \
{ \
return this->theMethod<ComplexInputImageType , OutputImageType>(); \
}
#define otbGenericCastImageMacro(ComplexInputImageType, theMethod, prefix) \
otbCastImageMacro(ComplexInputImageType, ComplexFloat##prefix##ImageType, theMethod) \
otbCastImageMacro(ComplexInputImageType, ComplexDouble##prefix##ImageType, theMethod)
/*********************************************************************
********************** Image -> Image
**********************************************************************/
otbGenericCastImageMacro(ComplexFloatImageType, SimpleCastImage, )
otbGenericCastImageMacro(ComplexDoubleImageType, SimpleCastImage, )
/*********************************************************************
********************** VectorImage -> VectorImage
**********************************************************************/
otbGenericCastImageMacro(ComplexFloatVectorImageType, SimpleCastImage, Vector)
otbGenericCastImageMacro(ComplexDoubleVectorImageType, SimpleCastImage, Vector)
void
ComplexInputImageParameter::SetImage(ComplexFloatVectorImageType* image)
{
m_UseFilename = false;
this->SetImage<ComplexFloatVectorImageType>( image );
}
bool
ComplexInputImageParameter::HasValue() const
{
if( m_FileName.empty() && m_Image.IsNull() )
return false;
else
return true;
}
void
ComplexInputImageParameter::ClearValue()
{
m_Image = ITK_NULLPTR;
m_Reader = ITK_NULLPTR;
m_Caster = ITK_NULLPTR;
m_FileName = "";
m_PreviousFileName="";
m_UseFilename = true;
}
/* Support for ComplexInputImageParameter. This has been done to support
the macro otbGetParameterImageMacro of otbWrapperApplication.h */
#define otbGetFalseImageMacro(image) \
image##Type * \
ComplexInputImageParameter::Get##image () \
{ \
return nullptr; \
}
otbGetFalseImageMacro(DoubleImage);
otbGetFalseImageMacro(DoubleVectorImage);
otbGetFalseImageMacro(FloatImage);
otbGetFalseImageMacro(FloatVectorImage);
otbGetFalseImageMacro(Int16Image);
otbGetFalseImageMacro(Int16VectorImage);
otbGetFalseImageMacro(UInt16Image);
otbGetFalseImageMacro(UInt16VectorImage);
otbGetFalseImageMacro(Int32Image);
otbGetFalseImageMacro(Int32VectorImage);
otbGetFalseImageMacro(UInt32Image);
otbGetFalseImageMacro(UInt32VectorImage);
otbGetFalseImageMacro(UInt8Image);
otbGetFalseImageMacro(UInt8VectorImage);
otbGetFalseImageMacro(UInt8RGBImage);
otbGetFalseImageMacro(UInt8RGBAImage);
}
}
|
add fake GetUInt8RGBImage and GetUInt8RGBAImage for complex image parameter
|
COMP: add fake GetUInt8RGBImage and GetUInt8RGBAImage for complex image parameter
|
C++
|
apache-2.0
|
orfeotoolbox/OTB,orfeotoolbox/OTB,orfeotoolbox/OTB,orfeotoolbox/OTB,orfeotoolbox/OTB,orfeotoolbox/OTB
|
104089a3e34f597084a4df8355f9dbcb1325719b
|
src/GUI/GUI.hpp
|
src/GUI/GUI.hpp
|
#ifndef GUI_HPP
#define GUI_HPP
#include <wx/toplevel.h>
#include "MainFrame.hpp"
#include "Notifier.hpp"
#include <string>
#include <vector>
#include <stack>
#include <mutex>
#include "Preset.hpp"
namespace Slic3r { namespace GUI {
class App: public wxApp
{
public:
virtual bool OnInit() override;
App() : wxApp() {}
/// Save position, size, and maximize state for a TopLevelWindow (includes Frames) by name in Settings.
void save_window_pos(const wxTopLevelWindow* window, const wxString& name );
/// Move/resize a named TopLevelWindow (includes Frames) from Settings
void restore_window_pos(wxTopLevelWindow* window, const wxString& name );
/// Function to add callback functions to the idle loop stack.
void CallAfter(std::function<void()> cb_function);
void OnUnhandledException() override;
std::vector<Presets> presets { preset_types, Presets() };
private:
std::unique_ptr<Notifier> notifier {nullptr};
void load_presets();
wxString datadir {""};
const std::string LogChannel {"APP"}; //< Which log these messages should go to.
/// Lock to guard the callback stack
std::mutex callback_register;
/// callbacks registered to run during idle event.
std::stack<std::function<void()> > cb {};
};
/// Quick reference to this app with its cast applied.
#define SLIC3RAPP (dynamic_cast<App*>(wxTheApp))
}} // namespace Slic3r::GUI
#endif // GUI_HPP
|
#ifndef GUI_HPP
#define GUI_HPP
#include <wx/toplevel.h>
#include "MainFrame.hpp"
#include "Notifier.hpp"
#include <string>
#include <vector>
#include <array>
#include <stack>
#include <mutex>
#include "Preset.hpp"
namespace Slic3r { namespace GUI {
class App: public wxApp
{
public:
virtual bool OnInit() override;
App() : wxApp() {}
/// Save position, size, and maximize state for a TopLevelWindow (includes Frames) by name in Settings.
void save_window_pos(const wxTopLevelWindow* window, const wxString& name );
/// Move/resize a named TopLevelWindow (includes Frames) from Settings
void restore_window_pos(wxTopLevelWindow* window, const wxString& name );
/// Function to add callback functions to the idle loop stack.
void CallAfter(std::function<void()> cb_function);
void OnUnhandledException() override;
std::vector<Presets> presets { preset_types, Presets() };
std::array<wxString, preset_types> preset_ini { };
private:
std::unique_ptr<Notifier> notifier {nullptr};
void load_presets();
wxString datadir {""};
const std::string LogChannel {"APP"}; //< Which log these messages should go to.
/// Lock to guard the callback stack
std::mutex callback_register;
/// callbacks registered to run during idle event.
std::stack<std::function<void()> > cb {};
};
/// Quick reference to this app with its cast applied.
#define SLIC3RAPP (dynamic_cast<App*>(wxTheApp))
}} // namespace Slic3r::GUI
#endif // GUI_HPP
|
Use std::array for the preset ini files.
|
Use std::array for the preset ini files.
|
C++
|
agpl-3.0
|
curieos/Slic3r,curieos/Slic3r,curieos/Slic3r,pieis2pi/Slic3r,pieis2pi/Slic3r,pieis2pi/Slic3r,alexrj/Slic3r,alexrj/Slic3r,pieis2pi/Slic3r,curieos/Slic3r,pieis2pi/Slic3r,alexrj/Slic3r,alexrj/Slic3r,curieos/Slic3r,pieis2pi/Slic3r,alexrj/Slic3r,alexrj/Slic3r,curieos/Slic3r
|
6ffd93c8d16e5b5b3ab8aa2c6a4fb136689fb897
|
init/init_sec.cpp
|
init/init_sec.cpp
|
/*
Copyright (c) 2015, The Dokdo Project. 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 Linux Foundation 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 "AS IS" AND ANY EXPRESS OR IMPLIED
WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT
ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS
BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR
BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE
OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN
IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
File Name : init_sec.c
Create Date : 2015.11.03
Author : Sunghun Ra
*/
#include <stdlib.h>
#include <stdio.h>
#include "vendor_init.h"
#include "property_service.h"
#include "log.h"
#include "util.h"
void vendor_load_properties()
{
char platform[PROP_VALUE_MAX];
char bootloader[PROP_VALUE_MAX];
char device[PROP_VALUE_MAX];
char devicename[PROP_VALUE_MAX];
property_get("ro.bootloader", bootloader);
if (strstr(bootloader, "G920S")) {
/* zeroflteskt */
property_set("ro.build.fingerprint", "samsung/zeroflteskt/zeroflteskt:5.1.1/LMY47X/G920SXXS3COK5:user/release-keys");
property_set("ro.build.description", "zeroflteskt-user 5.1.1 LMY47X G920SXXS3COK5 release-keys");
property_set("ro.product.model", "SM-G920S");
property_set("ro.product.device", "zeroflteskt");
} else if (strstr(bootloader, "G920K")) {
/* zerofltektt */
property_set("ro.build.fingerprint", "samsung/zerofltektt/zerofltektt:5.1.1/LMY47X/G920KXXS3COK5:user/release-keys");
property_set("ro.build.description", "zerofltektt-user 5.1.1 LMY47X G920KXXS3COK5 release-keys");
property_set("ro.product.model", "SM-G920K");
property_set("ro.product.device", "zerofltektt");
} else if (strstr(bootloader, "G920L")) {
/* zerofltelgt */
property_set("ro.build.fingerprint", "samsung/zerofltelgt/zerofltelgt:5.1.1/LMY47X/G920LXXS3COK5:user/release-keys");
property_set("ro.build.description", "zerofltelgt-user 5.1.1 LMY47X G920LXXS3COK5 release-keys");
property_set("ro.product.model", "SM-G920L");
property_set("ro.product.device", "zerofltelgt");
} else if (strstr(bootloader, "G920I")) {
/* zerofltexx */
property_set("ro.build.fingerprint", "samsung/zerofltexx/zerofltexx:5.1.1/LMY47X/G920IXXS3COK5:user/release-keys");
property_set("ro.build.description", "zerofltexx-user 5.1.1 LMY47X G920IXXS3COK5 release-keys");
property_set("ro.product.model", "SM-G920I");
property_set("ro.product.device", "zerofltexx");
} else {
/* zerofltexx */
property_set("ro.build.fingerprint", "samsung/zerofltexx/zerofltexx:5.1.1/LMY47X/G920FXXS3COK5:user/release-keys");
property_set("ro.build.description", "zerofltexx-user 5.1.1 LMY47X G920FXXS3COK5 release-keys");
property_set("ro.product.model", "SM-G920F");
property_set("ro.product.device", "zerofltexx");
}
property_get("ro.product.device", device);
strlcpy(devicename, device, sizeof(devicename));
ERROR("Found bootloader id %s setting build properties for %s device\n", bootloader, devicename);
}
|
/*
Copyright (c) 2015, The Dokdo Project. 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 Linux Foundation 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 "AS IS" AND ANY EXPRESS OR IMPLIED
WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT
ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS
BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR
BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE
OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN
IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
File Name : init_sec.c
Create Date : 2015.11.03
Author : Sunghun Ra
*/
#include <stdlib.h>
#include <stdio.h>
#include "vendor_init.h"
#include "property_service.h"
#include "log.h"
#include "util.h"
void vendor_load_properties()
{
char platform[PROP_VALUE_MAX];
char bootloader[PROP_VALUE_MAX];
char device[PROP_VALUE_MAX];
char devicename[PROP_VALUE_MAX];
property_get("ro.bootloader", bootloader);
if (strstr(bootloader, "G920S")) {
/* zeroflteskt */
property_set("ro.build.fingerprint", "samsung/zeroflteskt/zeroflteskt:5.1.1/LMY47X/G920SXXS3COK5:user/release-keys");
property_set("ro.build.description", "zeroflteskt-user 5.1.1 LMY47X G920SXXS3COK5 release-keys");
property_set("ro.product.model", "SM-G920S");
property_set("ro.product.device", "zeroflteskt");
} else if (strstr(bootloader, "G920K")) {
/* zerofltektt */
property_set("ro.build.fingerprint", "samsung/zerofltektt/zerofltektt:5.1.1/LMY47X/G920KXXS3COK5:user/release-keys");
property_set("ro.build.description", "zerofltektt-user 5.1.1 LMY47X G920KXXS3COK5 release-keys");
property_set("ro.product.model", "SM-G920K");
property_set("ro.product.device", "zerofltektt");
} else if (strstr(bootloader, "G920L")) {
/* zerofltelgt */
property_set("ro.build.fingerprint", "samsung/zerofltelgt/zerofltelgt:5.1.1/LMY47X/G920LXXS3COK5:user/release-keys");
property_set("ro.build.description", "zerofltelgt-user 5.1.1 LMY47X G920LXXS3COK5 release-keys");
property_set("ro.product.model", "SM-G920L");
property_set("ro.product.device", "zerofltelgt");
} else if (strstr(bootloader, "G920P")) {
/* zerofltespr */
property_set("ro.build.fingerprint", "samsung/zerofltespr/zerofltespr:5.1.1/LMY47X/G920PVPU3BOL1:user/release-keys");
property_set("ro.build.description", "zerofltespr-user 5.1.1 LMY47X G920PVPU3BOL1 release-keys");
property_set("ro.product.model", "SM-G920P");
property_set("ro.product.device", "zerofltespr");
} else if (strstr(bootloader, "G920I")) {
/* zerofltexx */
property_set("ro.build.fingerprint", "samsung/zerofltexx/zerofltexx:5.1.1/LMY47X/G920IXXS3COK5:user/release-keys");
property_set("ro.build.description", "zerofltexx-user 5.1.1 LMY47X G920IXXS3COK5 release-keys");
property_set("ro.product.model", "SM-G920I");
property_set("ro.product.device", "zerofltexx");
} else {
/* zerofltexx */
property_set("ro.build.fingerprint", "samsung/zerofltexx/zerofltexx:5.1.1/LMY47X/G920FXXS3COK5:user/release-keys");
property_set("ro.build.description", "zerofltexx-user 5.1.1 LMY47X G920FXXS3COK5 release-keys");
property_set("ro.product.model", "SM-G920F");
property_set("ro.product.device", "zerofltexx");
}
property_get("ro.product.device", device);
strlcpy(devicename, device, sizeof(devicename));
ERROR("Found bootloader id %s setting build properties for %s device\n", bootloader, devicename);
}
|
Add zerofltespr
|
Add zerofltespr
|
C++
|
apache-2.0
|
TeamNexus/android_device_samsung_zero-common,TeamNexus/android_device_samsung_zero-common,TeamNexus/android_device_samsung_zero-common,TeamNexus/android_device_samsung_zero-common,TeamNexus/android_device_samsung_zero-common
|
9153f2a61ccf7c2a8e609a2b97b9835cdee9c827
|
VersionControlUI/src/commands/CDiff.cpp
|
VersionControlUI/src/commands/CDiff.cpp
|
/***********************************************************************************************************************
**
** Copyright (c) 2011, 2014 ETH Zurich
** All rights reserved.
**
** Redistribution and use in source and binary forms, with or without modification, are permitted provided that the
** following conditions are met:
**
** * Redistributions of source code must retain the above copyright notice, this list of conditions and the following
** disclaimer.
** * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the
** following disclaimer in the documentation and/or other materials provided with the distribution.
** * Neither the name of the ETH Zurich nor the names of its contributors may be used to endorse or promote products
** derived from this software without specific prior written permission.
**
**
** THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES,
** INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
** DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
** SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
** SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
** WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
** OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
**
***********************************************************************************************************************/
#include "CDiff.h"
#include "ModelBase/src/model/TreeManager.h"
#include "VisualizationBase/src/items/Item.h"
#include "FilePersistence/src/simple/SimpleTextFileStore.h"
#include "FilePersistence/src/version_control/GitRepository.h"
#include "VersionControlUI/src/DiffManager.h"
using namespace Visualization;
using namespace FilePersistence;
namespace VersionControlUI {
const QString CDiff::SUMMARY_COMMAND = "summary";
CDiff::CDiff() : Command{"diff"} {}
bool CDiff::canInterpret(Visualization::Item*, Visualization::Item* target,
const QStringList& commandTokens, const std::unique_ptr<Visualization::Cursor>& )
{
QString managerName = target->node()->manager()->name();
QStringList commandTokensCopy = commandTokens;
// get GitRepository
QString path{"projects/" + managerName};
if (GitRepository::repositoryExists(path))
{
GitRepository repository{path};
// if there are no tokens we are unable to interpret the command
if (commandTokensCopy.isEmpty())
return false;
// check that command name starts with the characters of the first token
if (!name().startsWith(commandTokensCopy.takeFirst()))
return false;
// if there is an additional version specified, check that it is a valid commit
if (!commandTokensCopy.isEmpty())
{
auto token = commandTokensCopy.takeFirst();
if (!repository.isValidRevisionString(unambigousPrefixPerRevision_.value(token, token)))
return false;
}
// check the same if there is a second version specified
if (!commandTokensCopy.isEmpty())
{
auto token = commandTokensCopy.takeFirst();
if (!repository.isValidRevisionString(unambigousPrefixPerRevision_.value(token, token)))
return false;
}
if (!commandTokensCopy.isEmpty())
{
auto token = commandTokensCopy.takeFirst();
if (token != "summary")
return false;
}
return true;
}
else return false;
}
Interaction::CommandResult* CDiff::execute(Visualization::Item*, Visualization::Item* target,
const QStringList& commandTokens, const std::unique_ptr<Visualization::Cursor>& )
{
auto scene = target->scene();
scene->clearFocus();
scene->clearSelection();
scene->setMainCursor(nullptr);
QString managerName = target->node()->manager()->name();
// TODO restrict versions to versionA always be older?
QString versionA = commandTokens.value(1, "HEAD");
QString versionB = commandTokens.value(2, FilePersistence::GitRepository::WORKDIR);
bool highlightChangedParts = commandTokens.size() > 3;
// try to get complete sha1 if available
versionA = unambigousPrefixPerRevision_.value(versionA, versionA);
versionB = unambigousPrefixPerRevision_.value(versionB, versionB);
QList<Model::SymbolMatcher> symbolMatcherPriorityList;
symbolMatcherPriorityList.append(Model::SymbolMatcher{"Class"});
symbolMatcherPriorityList.append(Model::SymbolMatcher{"Method"});
VersionControlUI::DiffManager diffManager{managerName, symbolMatcherPriorityList};
if (highlightChangedParts)
diffManager.highlightChangedParts(versionA, versionB, target->findAncestorWithNode()->node()->manager());
else
diffManager.showDiff(versionA, versionB);
return new Interaction::CommandResult{};
}
QString CDiff::descriptionForCommits(QString token, QList<QPair<QString, QString>> commits)
{
QString suggestDescription;
if (token.length() < GitRepository::getMinPrefixLength())
suggestDescription = "<i>length of first argument must be at least " +
QString::number(GitRepository::getMinPrefixLength())+"</i>";
else if (commits.size() > 1)
suggestDescription = "<i>ambiguous</i>";
else if (commits.size() == 0)
suggestDescription = "<i>no matching commit id</i>";
else
// add found description of first token
suggestDescription = commits.first().second;
return suggestDescription;
}
QList<Interaction::CommandSuggestion*> CDiff::suggest(Visualization::Item*, Visualization::Item* target,
const QString& textSoFar, const std::unique_ptr<Visualization::Cursor>&)
{
QStringList tokensSoFar = textSoFar.split(" ");
QList<Interaction::CommandSuggestion*> suggestions;
// no suggestions for that many tokens
if (tokensSoFar.size() > 4)
return {};
// check that the command name starts with the characters of the first token
if (name().startsWith(tokensSoFar.takeFirst()))
{
// no additional versions specified
if (tokensSoFar.isEmpty())
{
suggestions.append(new Interaction::CommandSuggestion{name(), "diff working directory against head"});
return suggestions;
}
QString firstVersionToken = tokensSoFar.takeFirst();
QString stringToComplete = firstVersionToken;
QString suggestCommand = name() + " ";
QString suggestDescription = "";
bool secondVersionAvailable = !tokensSoFar.isEmpty();
if (secondVersionAvailable)
{
// use the second version token for completion
stringToComplete = tokensSoFar.takeFirst();
// add first version token to suggested command
suggestCommand += firstVersionToken + " ";
// analyze the first token
auto firstTokenSuggestions = commitsWithDescriptionsStartingWith(firstVersionToken, target);
suggestDescription = descriptionForCommits(firstVersionToken, firstTokenSuggestions);
// new line
suggestDescription += "<br>";
}
// check possible summary command at end
if (!tokensSoFar.isEmpty())
{
auto thirdToken = tokensSoFar.takeFirst();
if (!SUMMARY_COMMAND.startsWith(thirdToken))
return {};
suggestCommand += stringToComplete + " ";
auto secondTokenSuggenstions = commitsWithDescriptionsStartingWith(stringToComplete, target);
suggestDescription += descriptionForCommits(suggestDescription, secondTokenSuggenstions);
suggestions.append(new Interaction::CommandSuggestion{suggestCommand + SUMMARY_COMMAND,
suggestDescription +
"<br> highlight changes in current view"});
return suggestions;
}
for (auto commitWithDescription : commitsWithDescriptionsStartingWith(stringToComplete, target))
suggestions.append(new Interaction::CommandSuggestion{suggestCommand + commitWithDescription.first,
suggestDescription + commitWithDescription.second});
return suggestions;
}
else return {};
}
QList<QPair<QString, QString>> CDiff::commitsWithDescriptionsStartingWith(QString partialCommitId,
Visualization::Item* target)
{
QString managerName = target->node()->manager()->name();
// get GitRepository
QString path{"projects/" + managerName};
QList<QPair<QString, QString>> commitsWithDescriptions;
if (GitRepository::repositoryExists(path))
{
GitRepository repository{path};
auto revisions = repository.revisions();
// use the bigger of minPrefixLength or length of partialCommit as minimum prefix length
auto prefixes = computeUnambiguousShortestPrefixesPerString(revisions,
std::max(repository.getMinPrefixLength(), partialCommitId.length()));
for (auto prefix : prefixes)
if (prefix.startsWith(partialCommitId))
commitsWithDescriptions.append({prefix,
repository.getCommitInformation(unambigousPrefixPerRevision_[prefix]).message_});
// TODO find clean way to make localBranches and tags also available
//commitsWithDescriptions.append(repository.localBranches());
//commitsWithDescriptions.append(repository.tags());
}
return commitsWithDescriptions;
}
QStringList CDiff::computeUnambiguousShortestPrefixesPerString(const QStringList& strings, const int minPrefixLength)
{
unambigousPrefixPerRevision_.clear();
QStringList prefixes;
for (auto str : strings)
for (int i = minPrefixLength; i < str.length(); i++)
{
QString currentPrefix = str.left(i);
if (strings.filter(QRegularExpression{"^"+currentPrefix+".*"}).size() == 1)
{
prefixes.append(currentPrefix);
unambigousPrefixPerRevision_.insert(currentPrefix, str);
break;
}
}
return prefixes;
}
}
|
/***********************************************************************************************************************
**
** Copyright (c) 2011, 2014 ETH Zurich
** All rights reserved.
**
** Redistribution and use in source and binary forms, with or without modification, are permitted provided that the
** following conditions are met:
**
** * Redistributions of source code must retain the above copyright notice, this list of conditions and the following
** disclaimer.
** * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the
** following disclaimer in the documentation and/or other materials provided with the distribution.
** * Neither the name of the ETH Zurich nor the names of its contributors may be used to endorse or promote products
** derived from this software without specific prior written permission.
**
**
** THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES,
** INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
** DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
** SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
** SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
** WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
** OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
**
***********************************************************************************************************************/
#include "CDiff.h"
#include "ModelBase/src/model/TreeManager.h"
#include "VisualizationBase/src/items/Item.h"
#include "FilePersistence/src/simple/SimpleTextFileStore.h"
#include "FilePersistence/src/version_control/GitRepository.h"
#include "VersionControlUI/src/DiffManager.h"
using namespace Visualization;
using namespace FilePersistence;
namespace VersionControlUI {
const QString CDiff::SUMMARY_COMMAND = "summary";
CDiff::CDiff() : Command{"diff"} {}
bool CDiff::canInterpret(Visualization::Item*, Visualization::Item* target,
const QStringList& commandTokens, const std::unique_ptr<Visualization::Cursor>& )
{
QString managerName = target->node()->manager()->name();
QStringList commandTokensCopy = commandTokens;
// get GitRepository
QString path{"projects/" + managerName};
if (GitRepository::repositoryExists(path))
{
GitRepository repository{path};
// if there are no tokens we are unable to interpret the command
if (commandTokensCopy.isEmpty())
return false;
// check that command name starts with the characters of the first token
if (!name().startsWith(commandTokensCopy.takeFirst()))
return false;
// if there is an additional version specified, check that it is a valid commit
if (!commandTokensCopy.isEmpty())
{
auto token = commandTokensCopy.takeFirst();
if (!repository.isValidRevisionString(unambigousPrefixPerRevision_.value(token, token)))
return false;
}
// check the same if there is a second version specified
if (!commandTokensCopy.isEmpty())
{
auto token = commandTokensCopy.takeFirst();
if (!repository.isValidRevisionString(unambigousPrefixPerRevision_.value(token, token)))
return false;
}
if (!commandTokensCopy.isEmpty())
{
auto token = commandTokensCopy.takeFirst();
if (token != SUMMARY_COMMAND)
return false;
}
return true;
}
else return false;
}
Interaction::CommandResult* CDiff::execute(Visualization::Item*, Visualization::Item* target,
const QStringList& commandTokens, const std::unique_ptr<Visualization::Cursor>& )
{
auto scene = target->scene();
scene->clearFocus();
scene->clearSelection();
scene->setMainCursor(nullptr);
QString managerName = target->node()->manager()->name();
// TODO restrict versions to versionA always be older?
QString versionA = commandTokens.value(1, "HEAD");
QString versionB = commandTokens.value(2, FilePersistence::GitRepository::WORKDIR);
bool highlightChangedParts = commandTokens.size() > 3;
// try to get complete sha1 if available
versionA = unambigousPrefixPerRevision_.value(versionA, versionA);
versionB = unambigousPrefixPerRevision_.value(versionB, versionB);
QList<Model::SymbolMatcher> symbolMatcherPriorityList;
symbolMatcherPriorityList.append(Model::SymbolMatcher{"Class"});
symbolMatcherPriorityList.append(Model::SymbolMatcher{"Method"});
VersionControlUI::DiffManager diffManager{managerName, symbolMatcherPriorityList};
if (highlightChangedParts)
diffManager.highlightChangedParts(versionA, versionB, target->findAncestorWithNode()->node()->manager());
else
diffManager.showDiff(versionA, versionB);
return new Interaction::CommandResult{};
}
QString CDiff::descriptionForCommits(QString token, QList<QPair<QString, QString>> commits)
{
QString suggestDescription;
if (token.length() < GitRepository::getMinPrefixLength())
suggestDescription = "<i>length of first argument must be at least " +
QString::number(GitRepository::getMinPrefixLength())+"</i>";
else if (commits.size() > 1)
suggestDescription = "<i>ambiguous</i>";
else if (commits.size() == 0)
suggestDescription = "<i>no matching commit id</i>";
else
// add found description of first token
suggestDescription = commits.first().second;
return suggestDescription;
}
QList<Interaction::CommandSuggestion*> CDiff::suggest(Visualization::Item*, Visualization::Item* target,
const QString& textSoFar, const std::unique_ptr<Visualization::Cursor>&)
{
QStringList tokensSoFar = textSoFar.split(" ");
QList<Interaction::CommandSuggestion*> suggestions;
// no suggestions for that many tokens
if (tokensSoFar.size() > 4)
return {};
// check that the command name starts with the characters of the first token
if (name().startsWith(tokensSoFar.takeFirst()))
{
// no additional versions specified
if (tokensSoFar.isEmpty())
{
suggestions.append(new Interaction::CommandSuggestion{name(), "diff working directory against head"});
return suggestions;
}
QString firstVersionToken = tokensSoFar.takeFirst();
QString stringToComplete = firstVersionToken;
QString suggestCommand = name() + " ";
QString suggestDescription = "";
bool secondVersionAvailable = !tokensSoFar.isEmpty();
if (secondVersionAvailable)
{
// use the second version token for completion
stringToComplete = tokensSoFar.takeFirst();
// add first version token to suggested command
suggestCommand += firstVersionToken + " ";
// analyze the first token
auto firstTokenSuggestions = commitsWithDescriptionsStartingWith(firstVersionToken, target);
suggestDescription = descriptionForCommits(firstVersionToken, firstTokenSuggestions);
// new line
suggestDescription += "<br>";
}
// check possible summary command at end
if (!tokensSoFar.isEmpty())
{
auto thirdToken = tokensSoFar.takeFirst();
if (!SUMMARY_COMMAND.startsWith(thirdToken))
return {};
suggestCommand += stringToComplete + " ";
auto secondTokenSuggenstions = commitsWithDescriptionsStartingWith(stringToComplete, target);
suggestDescription += descriptionForCommits(suggestDescription, secondTokenSuggenstions);
suggestions.append(new Interaction::CommandSuggestion{suggestCommand + SUMMARY_COMMAND,
suggestDescription +
"<br> highlight changes in current view"});
return suggestions;
}
for (auto commitWithDescription : commitsWithDescriptionsStartingWith(stringToComplete, target))
suggestions.append(new Interaction::CommandSuggestion{suggestCommand + commitWithDescription.first,
suggestDescription + commitWithDescription.second});
return suggestions;
}
else return {};
}
QList<QPair<QString, QString>> CDiff::commitsWithDescriptionsStartingWith(QString partialCommitId,
Visualization::Item* target)
{
QString managerName = target->node()->manager()->name();
// get GitRepository
QString path{"projects/" + managerName};
QList<QPair<QString, QString>> commitsWithDescriptions;
if (GitRepository::repositoryExists(path))
{
GitRepository repository{path};
auto revisions = repository.revisions();
// use the bigger of minPrefixLength or length of partialCommit as minimum prefix length
auto prefixes = computeUnambiguousShortestPrefixesPerString(revisions,
std::max(repository.getMinPrefixLength(), partialCommitId.length()));
for (auto prefix : prefixes)
if (prefix.startsWith(partialCommitId))
commitsWithDescriptions.append({prefix,
repository.getCommitInformation(unambigousPrefixPerRevision_[prefix]).message_});
// TODO find clean way to make localBranches and tags also available
//commitsWithDescriptions.append(repository.localBranches());
//commitsWithDescriptions.append(repository.tags());
}
return commitsWithDescriptions;
}
QStringList CDiff::computeUnambiguousShortestPrefixesPerString(const QStringList& strings, const int minPrefixLength)
{
unambigousPrefixPerRevision_.clear();
QStringList prefixes;
for (auto str : strings)
for (int i = minPrefixLength; i < str.length(); i++)
{
QString currentPrefix = str.left(i);
if (strings.filter(QRegularExpression{"^"+currentPrefix+".*"}).size() == 1)
{
prefixes.append(currentPrefix);
unambigousPrefixPerRevision_.insert(currentPrefix, str);
break;
}
}
return prefixes;
}
}
|
Use SUMMARY_COMMAND instead of string literal
|
Use SUMMARY_COMMAND instead of string literal
|
C++
|
bsd-3-clause
|
Vaishal-shah/Envision,dimitar-asenov/Envision,mgalbier/Envision,lukedirtwalker/Envision,dimitar-asenov/Envision,dimitar-asenov/Envision,Vaishal-shah/Envision,mgalbier/Envision,lukedirtwalker/Envision,mgalbier/Envision,dimitar-asenov/Envision,dimitar-asenov/Envision,Vaishal-shah/Envision,dimitar-asenov/Envision,mgalbier/Envision,lukedirtwalker/Envision,mgalbier/Envision,Vaishal-shah/Envision,mgalbier/Envision,lukedirtwalker/Envision,Vaishal-shah/Envision,lukedirtwalker/Envision,lukedirtwalker/Envision,Vaishal-shah/Envision
|
2d808c080af67171d4a757c90ef4480aa6a45263
|
himan-bin/source/himan.cpp
|
himan-bin/source/himan.cpp
|
/**
* @file himan.cpp
*
* @brief himan main program
*
* @author partio
*
*/
#include <iostream>
#include "himan_common.h"
#include "plugin_factory.h"
#include "json_parser.h"
#include "himan_plugin.h"
#include "compiled_plugin.h"
#include "auxiliary_plugin.h"
#include "logger_factory.h"
#include <vector>
#include <boost/lexical_cast.hpp>
#include <boost/program_options.hpp>
#ifdef DEBUG
#include "timer_factory.h"
#endif
#define HIMAN_AUXILIARY_INCLUDE
#include "pcuda.h"
#undef HIMAN_AUXILIARY_INCLUDE
using namespace himan;
using namespace std;
void banner();
shared_ptr<configuration> ParseCommandLine(int argc, char** argv);
int main(int argc, char** argv)
{
shared_ptr<configuration> conf = ParseCommandLine(argc, argv);
unique_ptr<logger> theLogger = unique_ptr<logger> (logger_factory::Instance()->GetLog("himan"));
/*
* Initialize plugin factory before parsing configuration file. This prevents himan from
* terminating suddenly with SIGSEGV on RHEL5 environments.
*
* Also, it may be good to have neons -plugin declared at main level of program. This
* goes also for the cache plugin.
*
* Note that we don't actually do anything with the plugin here.
*/
shared_ptr<plugin::auxiliary_plugin> n = dynamic_pointer_cast<plugin::auxiliary_plugin> (plugin_factory::Instance()->Plugin("neons"));
shared_ptr<plugin::auxiliary_plugin> c = dynamic_pointer_cast<plugin::auxiliary_plugin> (plugin_factory::Instance()->Plugin("cache"));
json_parser::Instance()->Parse(conf);
banner();
vector<shared_ptr<plugin::himan_plugin>> thePlugins = plugin_factory::Instance()->Plugins();
theLogger->Info("Found " + boost::lexical_cast<string> (thePlugins.size()) + " plugins");
vector<shared_ptr<info>> queues = conf->Infos();
theLogger->Debug("Processqueue size: " + boost::lexical_cast<string> (queues.size()));
for (size_t i = 0; i < queues.size(); i++)
{
theLogger->Debug("Number of plugins for processqueue element " + boost::lexical_cast<string> (i) + ": " + boost::lexical_cast<string> (queues[i]->Plugins().size()));
for (size_t j = 0; j < queues[i]->Plugins().size(); j++)
{
plugin_configuration pc = queues[i]->Plugins()[j];
shared_ptr<plugin::compiled_plugin> thePlugin = dynamic_pointer_cast<plugin::compiled_plugin > (plugin_factory::Instance()->Plugin(pc.Name()));
if (!thePlugin)
{
theLogger->Error("Unable to declare plugin " + pc.Name());
continue;
}
#ifdef DEBUG
unique_ptr<timer> t = unique_ptr<timer> (timer_factory::Instance()->GetTimer());
t->Start();
#endif
conf->PluginConfiguration(pc);
theLogger->Info("Calculating " + pc.Name());
thePlugin->Process(conf, queues[i]);
#ifdef DEBUG
t->Stop();
theLogger->Debug("Processing " + pc.Name() + " took " + boost::lexical_cast<string> (static_cast<long> (t->GetTime()/1000)) + " milliseconds");
#endif
}
}
return 0;
}
void banner()
{
cout << endl
<< "************************************************" << endl
<< "* By the Power of Grayskull, I Have the Power! *" << endl
<< "************************************************" << endl << endl;
}
shared_ptr<configuration> ParseCommandLine(int argc, char** argv)
{
shared_ptr<configuration> conf(new configuration());
namespace po = boost::program_options;
po::options_description desc("Allowed options");
// Can't use required() since it doesn't allow us to use --list-plugins
string outfileType = "";
string confFile = "";
vector<string> auxFiles;
himan::HPDebugState debugState = himan::kDebugMsg;
int logLevel = 0;
short int threadCount = -1;
desc.add_options()
("help,h", "print out help message")
("type,t", po::value(&outfileType), "output file type, one of: grib, grib2, netcdf, querydata")
("version,v", "display version number")
("configuration-file,f", po::value(&confFile), "configuration file")
("auxiliary-files,a", po::value<vector<string> > (&auxFiles), "auxiliary (helper) file(s)")
("threads,j", po::value(&threadCount), "number of started threads")
("list-plugins,l", "list all defined plugins")
("debug-level,d", po::value(&logLevel), "set log level: 0(fatal) 1(error) 2(warning) 3(info) 4(debug) 5(trace)")
("no-cuda", "disable cuda extensions")
("cuda-properties", "print cuda device properties of platform (if any)")
;
po::positional_options_description p;
p.add("auxiliary-files", -1);
po::variables_map opt;
po::store(po::command_line_parser(argc, argv)
.options(desc)
.positional(p)
.run(),
opt);
po::notify(opt);
if (threadCount)
{
conf->ThreadCount(threadCount);
}
if (auxFiles.size())
{
conf->AuxiliaryFiles(auxFiles);
}
if (logLevel)
{
switch (logLevel)
{
case 0:
debugState = kFatalMsg;
break;
case 1:
debugState = kErrorMsg;
break;
case 2:
debugState = kWarningMsg;
break;
case 3:
debugState = kInfoMsg;
break;
case 4:
debugState = kDebugMsg;
break;
case 5:
debugState = kTraceMsg;
break;
}
}
logger_factory::Instance()->DebugState(debugState);
if (opt.count("version"))
{
cout << "himan version ???" << endl;
exit(1);
}
if (opt.count("cuda-properties"))
{
#ifndef HAVE_CUDA
cout << "CUDA support turned off at compile time" << endl;
#else
shared_ptr<plugin::pcuda> p = dynamic_pointer_cast<plugin::pcuda> (plugin_factory::Instance()->Plugin("pcuda"));
p->Capabilities();
#endif
exit(1);
}
if (opt.count("no-cuda"))
{
conf->UseCuda(false);
}
if (!outfileType.empty())
{
if (outfileType == "grib")
{
conf->OutputFileType(kGRIB1);
}
else if (outfileType == "grib2")
{
conf->OutputFileType(kGRIB2);
}
else if (outfileType == "netcdf")
{
conf->OutputFileType(kNetCDF);
}
else if (outfileType == "querydata")
{
conf->OutputFileType(kQueryData);
}
else
{
throw runtime_error("Invalid file type: " + outfileType);
}
}
if (opt.count("help"))
{
cout << "usage: himan [ options ]" << endl;
cout << desc;
cout << endl << "Examples:" << endl;
cout << " himan -f etc/tpot.json" << endl;
cout << " himan -f etc/vvmms.json -a file.grib -t querydata" << endl << endl;
exit(1);
}
if (opt.count("list-plugins"))
{
vector<shared_ptr<plugin::himan_plugin>> thePlugins = plugin_factory::Instance()->Plugins();
for (size_t i = 0; i < thePlugins.size(); i++)
{
cout << "Plugin '" << thePlugins[i]->ClassName() << "'" << endl << "\tversion " << thePlugins[i]->Version() << endl;
switch (thePlugins[i]->PluginClass())
{
case kCompiled:
cout << "\ttype compiled (hard-coded) --> " << dynamic_pointer_cast<plugin::compiled_plugin> (thePlugins[i])->Formula() << endl;
break;
case kAuxiliary:
cout << "\ttype aux" << endl;
break;
case kInterpreted:
cout << "\ttype interpreted" << endl;
break;
default:
cout << " has unknown plugin type" << endl;
exit(1);
}
}
exit(1);
}
if (!confFile.empty())
{
conf->ConfigurationFile(confFile);
}
else
{
throw runtime_error("himan: Configuration file not defined");
}
return conf;
}
|
/**
* @file himan.cpp
*
* @brief himan main program
*
* @author partio
*
*/
#include <iostream>
#include "himan_common.h"
#include "plugin_factory.h"
#include "json_parser.h"
#include "himan_plugin.h"
#include "compiled_plugin.h"
#include "auxiliary_plugin.h"
#include "logger_factory.h"
#include <vector>
#include <boost/lexical_cast.hpp>
#include <boost/program_options.hpp>
#ifdef DEBUG
#include "timer_factory.h"
#endif
#define HIMAN_AUXILIARY_INCLUDE
#include "pcuda.h"
#undef HIMAN_AUXILIARY_INCLUDE
using namespace himan;
using namespace std;
void banner();
shared_ptr<configuration> ParseCommandLine(int argc, char** argv);
int main(int argc, char** argv)
{
shared_ptr<configuration> conf = ParseCommandLine(argc, argv);
unique_ptr<logger> theLogger = unique_ptr<logger> (logger_factory::Instance()->GetLog("himan"));
/*
* Initialize plugin factory before parsing configuration file. This prevents himan from
* terminating suddenly with SIGSEGV on RHEL5 environments.
*
* Also, it may be good to have neons -plugin declared at main level of program. This
* goes also for the cache plugin.
*
* Note that we don't actually do anything with the plugin here.
*/
shared_ptr<plugin::auxiliary_plugin> n = dynamic_pointer_cast<plugin::auxiliary_plugin> (plugin_factory::Instance()->Plugin("neons"));
shared_ptr<plugin::auxiliary_plugin> c = dynamic_pointer_cast<plugin::auxiliary_plugin> (plugin_factory::Instance()->Plugin("cache"));
json_parser::Instance()->Parse(conf);
banner();
vector<shared_ptr<plugin::himan_plugin>> thePlugins = plugin_factory::Instance()->Plugins();
theLogger->Info("Found " + boost::lexical_cast<string> (thePlugins.size()) + " plugins");
vector<shared_ptr<info>> queues = conf->Infos();
theLogger->Debug("Processqueue size: " + boost::lexical_cast<string> (queues.size()));
for (size_t i = 0; i < queues.size(); i++)
{
theLogger->Debug("Number of plugins for processqueue element " + boost::lexical_cast<string> (i) + ": " + boost::lexical_cast<string> (queues[i]->Plugins().size()));
for (size_t j = 0; j < queues[i]->Plugins().size(); j++)
{
plugin_configuration pc = queues[i]->Plugins()[j];
shared_ptr<plugin::compiled_plugin> thePlugin = dynamic_pointer_cast<plugin::compiled_plugin > (plugin_factory::Instance()->Plugin(pc.Name()));
if (!thePlugin)
{
theLogger->Error("Unable to declare plugin " + pc.Name());
continue;
}
#ifdef DEBUG
unique_ptr<timer> t = unique_ptr<timer> (timer_factory::Instance()->GetTimer());
t->Start();
#endif
conf->PluginConfiguration(pc);
theLogger->Info("Calculating " + pc.Name());
thePlugin->Process(conf, queues[i]);
#ifdef DEBUG
t->Stop();
theLogger->Debug("Processing " + pc.Name() + " took " + boost::lexical_cast<string> (static_cast<long> (t->GetTime()/1000)) + " milliseconds");
#endif
}
}
return 0;
}
void banner()
{
cout << endl
<< "************************************************" << endl
<< "* By the Power of Grayskull, I Have the Power! *" << endl
<< "************************************************" << endl << endl;
}
shared_ptr<configuration> ParseCommandLine(int argc, char** argv)
{
shared_ptr<configuration> conf(new configuration());
namespace po = boost::program_options;
po::options_description desc("Allowed options");
// Can't use required() since it doesn't allow us to use --list-plugins
string outfileType = "";
string confFile = "";
vector<string> auxFiles;
himan::HPDebugState debugState = himan::kDebugMsg;
int logLevel = 0;
short int threadCount = -1;
desc.add_options()
("help,h", "print out help message")
("type,t", po::value(&outfileType), "output file type, one of: grib, grib2, netcdf, querydata")
("version,v", "display version number")
("configuration-file,f", po::value(&confFile), "configuration file")
("auxiliary-files,a", po::value<vector<string> > (&auxFiles), "auxiliary (helper) file(s)")
("threads,j", po::value(&threadCount), "number of started threads")
("list-plugins,l", "list all defined plugins")
("debug-level,d", po::value(&logLevel), "set log level: 0(fatal) 1(error) 2(warning) 3(info) 4(debug) 5(trace)")
("no-cuda", "disable cuda extensions")
("cuda-properties", "print cuda device properties of platform (if any)")
;
po::positional_options_description p;
p.add("auxiliary-files", -1);
po::variables_map opt;
po::store(po::command_line_parser(argc, argv)
.options(desc)
.positional(p)
.run(),
opt);
po::notify(opt);
if (threadCount)
{
conf->ThreadCount(threadCount);
}
if (auxFiles.size())
{
conf->AuxiliaryFiles(auxFiles);
}
if (logLevel)
{
switch (logLevel)
{
case 0:
debugState = kFatalMsg;
break;
case 1:
debugState = kErrorMsg;
break;
case 2:
debugState = kWarningMsg;
break;
case 3:
debugState = kInfoMsg;
break;
case 4:
debugState = kDebugMsg;
break;
case 5:
debugState = kTraceMsg;
break;
}
}
logger_factory::Instance()->DebugState(debugState);
if (opt.count("version"))
{
cout << "himan version " << __DATE__ << " " << __TIME__ << endl;
exit(1);
}
if (opt.count("cuda-properties"))
{
#ifndef HAVE_CUDA
cout << "CUDA support turned off at compile time" << endl;
#else
shared_ptr<plugin::pcuda> p = dynamic_pointer_cast<plugin::pcuda> (plugin_factory::Instance()->Plugin("pcuda"));
p->Capabilities();
#endif
exit(1);
}
if (opt.count("no-cuda"))
{
conf->UseCuda(false);
}
if (!outfileType.empty())
{
if (outfileType == "grib")
{
conf->OutputFileType(kGRIB1);
}
else if (outfileType == "grib2")
{
conf->OutputFileType(kGRIB2);
}
else if (outfileType == "netcdf")
{
conf->OutputFileType(kNetCDF);
}
else if (outfileType == "querydata")
{
conf->OutputFileType(kQueryData);
}
else
{
throw runtime_error("Invalid file type: " + outfileType);
}
}
if (opt.count("help"))
{
cout << "usage: himan [ options ]" << endl;
cout << desc;
cout << endl << "Examples:" << endl;
cout << " himan -f etc/tpot.json" << endl;
cout << " himan -f etc/vvmms.json -a file.grib -t querydata" << endl << endl;
exit(1);
}
if (opt.count("list-plugins"))
{
vector<shared_ptr<plugin::himan_plugin>> thePlugins = plugin_factory::Instance()->Plugins();
for (size_t i = 0; i < thePlugins.size(); i++)
{
cout << "Plugin '" << thePlugins[i]->ClassName() << "'" << endl << "\tversion " << thePlugins[i]->Version() << endl;
switch (thePlugins[i]->PluginClass())
{
case kCompiled:
cout << "\ttype compiled (hard-coded) --> " << dynamic_pointer_cast<plugin::compiled_plugin> (thePlugins[i])->Formula() << endl;
break;
case kAuxiliary:
cout << "\ttype aux" << endl;
break;
case kInterpreted:
cout << "\ttype interpreted" << endl;
break;
default:
cout << " has unknown plugin type" << endl;
exit(1);
}
}
exit(1);
}
if (!confFile.empty())
{
conf->ConfigurationFile(confFile);
}
else
{
throw runtime_error("himan: Configuration file not defined");
}
return conf;
}
|
Set version number
|
Set version number
|
C++
|
mit
|
fmidev/himan,fmidev/himan,fmidev/himan
|
7ea8450b401179b2d018c1c771920301f47de446
|
src/PiTable.cpp
|
src/PiTable.cpp
|
///
/// @file PiTable.cpp
/// @brief The PiTable class is a compressed lookup table of prime
/// counts. Each bit of the lookup table corresponds to an
/// integer that is not divisible by 2, 3 and 5. The 8 bits of
/// each byte correspond to the offsets { 1, 7, 11, 13, 17, 19,
/// 23, 29 }. Since our lookup table uses the uint64_t data
/// type, one array element (8 bytes) corresponds to an
/// interval of size 30 * 8 = 240.
///
/// Copyright (C) 2021 Kim Walisch, <[email protected]>
///
/// This file is distributed under the BSD License. See the COPYING
/// file in the top level directory.
///
#include <PiTable.hpp>
#include <primecount-internal.hpp>
#include <primesieve.hpp>
#include <imath.hpp>
#include <min.hpp>
#include <stdint.h>
#include <algorithm>
#include <cstring>
namespace primecount {
/// Compressed PrimePi(x) lookup table for x < 64 * 240.
/// This lookup table has a size of 1 KiB and stores the count of
/// primes < 15,360. The 8 bits of each byte correspond to the
/// offsets { 1, 7, 11, 13, 17, 19, 23, 29 }.
/// Array format: { pi[5] + count of 1-bits < current_index, 1-bits that correspond to primes }
///
const std::array<PiTable::pi_t, 64> PiTable::pi_cache_ =
{{
{ 3, 0xF93DDBB67EEFDFFEull }, { 52, 0x9EEDA6EAF31E4FD5ull },
{ 92, 0xA559DD3BD3D30CE6ull }, { 128, 0x56A61E78BD92676Aull },
{ 162, 0x554C2ADE2DADE356ull }, { 196, 0xF8A154039FF0A3D9ull },
{ 228, 0x3A13F666E944FD2Eull }, { 263, 0x54BF11453A2B4CB8ull },
{ 293, 0x4F8CBCC8B37AC18Cull }, { 325, 0xEF17C19B71715821ull },
{ 357, 0x468C83E5081A9654ull }, { 382, 0x87588F9265AEFB72ull },
{ 417, 0xA0E3266581D892D2ull }, { 444, 0x99EB813C26C73811ull },
{ 473, 0x4D33F3243E88518Dull }, { 503, 0x4C58B42AA71C8B5Aull },
{ 532, 0xC383DC8219F6264Eull }, { 562, 0x02CDCDB50238F12Cull },
{ 590, 0x307A4C570C944AB2ull }, { 617, 0xF8246C44CBF10B43ull },
{ 646, 0x8DEA735CA8950119ull }, { 675, 0xC41E22A6502B9624ull },
{ 700, 0x9C742F3AD40648D1ull }, { 729, 0x2E1568BF88056A07ull },
{ 757, 0x14089851B7E35560ull }, { 783, 0x2770494D45AA5A86ull },
{ 811, 0x618302ABCAD593D2ull }, { 840, 0xADA9C22287CE2405ull },
{ 867, 0xB01689D1784D8C18ull }, { 893, 0x522434C0A262C757ull },
{ 919, 0x4308218D32405AAEull }, { 942, 0x60E119D9B6D2B634ull },
{ 973, 0x947A44D060391A67ull }, { 1000, 0x105574A88388099Aull },
{ 1023, 0x32C8231E685DA127ull }, { 1051, 0x38B14873440319E0ull },
{ 1075, 0x1CB59861572AE6C3ull }, { 1106, 0x2902AC8F81C5680Aull },
{ 1130, 0x2E644E1194E3471Aull }, { 1158, 0x1006C514DC3DCB14ull },
{ 1184, 0xE34730E982B129E9ull }, { 1214, 0xB430300A25C31934ull },
{ 1237, 0x4C8ED84446E5C16Cull }, { 1265, 0x818992787024225Dull },
{ 1289, 0xA508E9861B265682ull }, { 1315, 0x104AC2B029C3D300ull },
{ 1337, 0xC760421DA13859B2ull }, { 1364, 0x8BC61A44C88C2722ull },
{ 1389, 0x0931A610461A8182ull }, { 1409, 0x15A9D8D2182F54F0ull },
{ 1438, 0x91500EC0F60C2E06ull }, { 1462, 0xC319653818C126CDull },
{ 1489, 0x4A84D62D2A8B9356ull }, { 1518, 0xC476E0092CA50A61ull },
{ 1543, 0x1B6614E808D83C6Aull }, { 1570, 0x073110366302A4B0ull },
{ 1592, 0xA08AC312424892D5ull }, { 1615, 0x5C788582A4742D9Full },
{ 1645, 0xE8021D1461B0180Dull }, { 1667, 0x30831C4901C11218ull },
{ 1686, 0xF40C0FD888A13367ull }, { 1715, 0xB1474266D7588898ull },
{ 1743, 0x155941180896A816ull }, { 1765, 0xA1AAB3E1522A44B5ull }
}};
PiTable::PiTable(uint64_t limit, int threads) :
limit_(limit)
{
if (limit_ >= pi_cache_.size() * 240)
init(limit, threads);
else
{
uint64_t size = limit + 1;
pi_.resize(ceil_div(size, 240));
std::copy_n(pi_cache_.begin(), pi_.size(), &pi_[0]);
}
}
/// Used for large limits
void PiTable::init(uint64_t limit, int threads)
{
uint64_t size = limit + 1;
uint64_t thread_threshold = (uint64_t) 1e7;
threads = ideal_num_threads(threads, size, thread_threshold);
uint64_t thread_size = size / threads;
thread_size = max(thread_threshold, thread_size);
thread_size += 240 - thread_size % 240;
pi_.resize(ceil_div(size, 240));
counts_.resize(threads);
#pragma omp parallel num_threads(threads)
{
#pragma omp for
for (int t = 0; t < threads; t++)
{
uint64_t start = thread_size * t;
uint64_t stop = start + thread_size;
stop = min(stop, size);
if (start < stop)
init_bits(start, stop, t);
}
#pragma omp for
for (int t = 0; t < threads; t++)
{
uint64_t start = thread_size * t;
uint64_t stop = start + thread_size;
stop = min(stop, size);
if (start < stop)
init_count(start, stop, t);
}
}
}
/// Each thread computes PrimePi [start, stop[
void PiTable::init_bits(uint64_t start,
uint64_t stop,
uint64_t thread_num)
{
// Zero initialize pi vector
uint64_t i = start / 240;
uint64_t j = ceil_div(stop, 240);
std::memset(&pi_[i], 0, (j - i) * sizeof(pi_t));
// Iterate over primes > 5
start = max(start, 5);
primesieve::iterator it(start, stop);
uint64_t count = 0;
uint64_t prime = 0;
while ((prime = it.next_prime()) < stop)
{
uint64_t prime_bit = set_bit_[prime % 240];
pi_[prime / 240].bits |= prime_bit;
count += 1;
}
counts_[thread_num] = count;
}
/// Each thread computes PrimePi [start, stop[
void PiTable::init_count(uint64_t start,
uint64_t stop,
uint64_t thread_num)
{
// First compute PrimePi[start - 1]
uint64_t count = pi_tiny_[5];
for (uint64_t i = 0; i < thread_num; i++)
count += counts_[i];
// Convert to array indexes
uint64_t i = start / 240;
uint64_t stop_idx = ceil_div(stop, 240);
for (; i < stop_idx; i++)
{
pi_[i].count = count;
count += popcnt64(pi_[i].bits);
}
}
} // namespace
|
///
/// @file PiTable.cpp
/// @brief The PiTable class is a compressed lookup table of prime
/// counts. Each bit of the lookup table corresponds to an
/// integer that is not divisible by 2, 3 and 5. The 8 bits of
/// each byte correspond to the offsets { 1, 7, 11, 13, 17, 19,
/// 23, 29 }. Since our lookup table uses the uint64_t data
/// type, one array element (8 bytes) corresponds to an
/// interval of size 30 * 8 = 240.
///
/// Copyright (C) 2021 Kim Walisch, <[email protected]>
///
/// This file is distributed under the BSD License. See the COPYING
/// file in the top level directory.
///
#include <PiTable.hpp>
#include <primecount-internal.hpp>
#include <primesieve.hpp>
#include <imath.hpp>
#include <min.hpp>
#include <stdint.h>
#include <algorithm>
#include <cstring>
namespace primecount {
/// Compressed PrimePi(x) lookup table for x < 64 * 240.
/// This lookup table has a size of 1 KiB. The 8 bits of each byte
/// correspond to the offsets { 1, 7, 11, 13, 17, 19, 23, 29 }.
/// Array format: { PrimePi(5) + count of 1-bits < current_index,
/// 64-bit word where 1-bits correspond to primes }
///
const std::array<PiTable::pi_t, 64> PiTable::pi_cache_ =
{{
{ 3, 0xF93DDBB67EEFDFFEull }, { 52, 0x9EEDA6EAF31E4FD5ull },
{ 92, 0xA559DD3BD3D30CE6ull }, { 128, 0x56A61E78BD92676Aull },
{ 162, 0x554C2ADE2DADE356ull }, { 196, 0xF8A154039FF0A3D9ull },
{ 228, 0x3A13F666E944FD2Eull }, { 263, 0x54BF11453A2B4CB8ull },
{ 293, 0x4F8CBCC8B37AC18Cull }, { 325, 0xEF17C19B71715821ull },
{ 357, 0x468C83E5081A9654ull }, { 382, 0x87588F9265AEFB72ull },
{ 417, 0xA0E3266581D892D2ull }, { 444, 0x99EB813C26C73811ull },
{ 473, 0x4D33F3243E88518Dull }, { 503, 0x4C58B42AA71C8B5Aull },
{ 532, 0xC383DC8219F6264Eull }, { 562, 0x02CDCDB50238F12Cull },
{ 590, 0x307A4C570C944AB2ull }, { 617, 0xF8246C44CBF10B43ull },
{ 646, 0x8DEA735CA8950119ull }, { 675, 0xC41E22A6502B9624ull },
{ 700, 0x9C742F3AD40648D1ull }, { 729, 0x2E1568BF88056A07ull },
{ 757, 0x14089851B7E35560ull }, { 783, 0x2770494D45AA5A86ull },
{ 811, 0x618302ABCAD593D2ull }, { 840, 0xADA9C22287CE2405ull },
{ 867, 0xB01689D1784D8C18ull }, { 893, 0x522434C0A262C757ull },
{ 919, 0x4308218D32405AAEull }, { 942, 0x60E119D9B6D2B634ull },
{ 973, 0x947A44D060391A67ull }, { 1000, 0x105574A88388099Aull },
{ 1023, 0x32C8231E685DA127ull }, { 1051, 0x38B14873440319E0ull },
{ 1075, 0x1CB59861572AE6C3ull }, { 1106, 0x2902AC8F81C5680Aull },
{ 1130, 0x2E644E1194E3471Aull }, { 1158, 0x1006C514DC3DCB14ull },
{ 1184, 0xE34730E982B129E9ull }, { 1214, 0xB430300A25C31934ull },
{ 1237, 0x4C8ED84446E5C16Cull }, { 1265, 0x818992787024225Dull },
{ 1289, 0xA508E9861B265682ull }, { 1315, 0x104AC2B029C3D300ull },
{ 1337, 0xC760421DA13859B2ull }, { 1364, 0x8BC61A44C88C2722ull },
{ 1389, 0x0931A610461A8182ull }, { 1409, 0x15A9D8D2182F54F0ull },
{ 1438, 0x91500EC0F60C2E06ull }, { 1462, 0xC319653818C126CDull },
{ 1489, 0x4A84D62D2A8B9356ull }, { 1518, 0xC476E0092CA50A61ull },
{ 1543, 0x1B6614E808D83C6Aull }, { 1570, 0x073110366302A4B0ull },
{ 1592, 0xA08AC312424892D5ull }, { 1615, 0x5C788582A4742D9Full },
{ 1645, 0xE8021D1461B0180Dull }, { 1667, 0x30831C4901C11218ull },
{ 1686, 0xF40C0FD888A13367ull }, { 1715, 0xB1474266D7588898ull },
{ 1743, 0x155941180896A816ull }, { 1765, 0xA1AAB3E1522A44B5ull }
}};
PiTable::PiTable(uint64_t limit, int threads) :
limit_(limit)
{
if (limit_ >= pi_cache_.size() * 240)
init(limit, threads);
else
{
uint64_t size = limit + 1;
pi_.resize(ceil_div(size, 240));
std::copy_n(pi_cache_.begin(), pi_.size(), &pi_[0]);
}
}
/// Used for large limits
void PiTable::init(uint64_t limit, int threads)
{
uint64_t size = limit + 1;
uint64_t thread_threshold = (uint64_t) 1e7;
threads = ideal_num_threads(threads, size, thread_threshold);
uint64_t thread_size = size / threads;
thread_size = max(thread_threshold, thread_size);
thread_size += 240 - thread_size % 240;
pi_.resize(ceil_div(size, 240));
counts_.resize(threads);
#pragma omp parallel num_threads(threads)
{
#pragma omp for
for (int t = 0; t < threads; t++)
{
uint64_t start = thread_size * t;
uint64_t stop = start + thread_size;
stop = min(stop, size);
if (start < stop)
init_bits(start, stop, t);
}
#pragma omp for
for (int t = 0; t < threads; t++)
{
uint64_t start = thread_size * t;
uint64_t stop = start + thread_size;
stop = min(stop, size);
if (start < stop)
init_count(start, stop, t);
}
}
}
/// Each thread computes PrimePi [start, stop[
void PiTable::init_bits(uint64_t start,
uint64_t stop,
uint64_t thread_num)
{
// Zero initialize pi vector
uint64_t i = start / 240;
uint64_t j = ceil_div(stop, 240);
std::memset(&pi_[i], 0, (j - i) * sizeof(pi_t));
// Iterate over primes > 5
start = max(start, 5);
primesieve::iterator it(start, stop);
uint64_t count = 0;
uint64_t prime = 0;
while ((prime = it.next_prime()) < stop)
{
uint64_t prime_bit = set_bit_[prime % 240];
pi_[prime / 240].bits |= prime_bit;
count += 1;
}
counts_[thread_num] = count;
}
/// Each thread computes PrimePi [start, stop[
void PiTable::init_count(uint64_t start,
uint64_t stop,
uint64_t thread_num)
{
// First compute PrimePi[start - 1]
uint64_t count = pi_tiny_[5];
for (uint64_t i = 0; i < thread_num; i++)
count += counts_[i];
// Convert to array indexes
uint64_t i = start / 240;
uint64_t stop_idx = ceil_div(stop, 240);
for (; i < stop_idx; i++)
{
pi_[i].count = count;
count += popcnt64(pi_[i].bits);
}
}
} // namespace
|
Update comment
|
Update comment
|
C++
|
bsd-2-clause
|
kimwalisch/primecount,kimwalisch/primecount,kimwalisch/primecount
|
9d159e44923bf8d7650cef6879775c23aab39233
|
src/appleseed/renderer/kernel/rendering/masterrenderer.cpp
|
src/appleseed/renderer/kernel/rendering/masterrenderer.cpp
|
//
// This source file is part of appleseed.
// Visit http://appleseedhq.net/ for additional information and resources.
//
// This software is released under the MIT license.
//
// Copyright (c) 2010-2011 Francois Beaune
//
// 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.
//
// Interface header.
#include "masterrenderer.h"
// appleseed.renderer headers.
#include "renderer/kernel/intersection/intersector.h"
#include "renderer/kernel/lighting/drt/drt.h"
#include "renderer/kernel/lighting/ilightingengine.h"
#include "renderer/kernel/lighting/lightsampler.h"
#include "renderer/kernel/lighting/pathtracing/pathtracing.h"
#include "renderer/kernel/rendering/debug/blanktilerenderer.h"
#include "renderer/kernel/rendering/debug/debugtilerenderer.h"
#include "renderer/kernel/rendering/generic/genericframerenderer.h"
#include "renderer/kernel/rendering/generic/genericsamplegenerator.h"
#include "renderer/kernel/rendering/generic/genericsamplerenderer.h"
#include "renderer/kernel/rendering/generic/generictilerenderer.h"
#include "renderer/kernel/rendering/lighttracing/lighttracingsamplegenerator.h"
#include "renderer/kernel/rendering/progressive/progressiveframerenderer.h"
#include "renderer/kernel/rendering/accumulationframebuffer.h"
#include "renderer/kernel/rendering/globalaccumulationframebuffer.h"
#include "renderer/kernel/rendering/iframerenderer.h"
#include "renderer/kernel/rendering/isamplegenerator.h"
#include "renderer/kernel/rendering/isamplerenderer.h"
#include "renderer/kernel/rendering/itilecallback.h"
#include "renderer/kernel/rendering/itilerenderer.h"
#include "renderer/kernel/rendering/localaccumulationframebuffer.h"
#include "renderer/kernel/shading/shadingcontext.h"
#include "renderer/kernel/shading/shadingengine.h"
#include "renderer/kernel/texturing/texturecache.h"
#include "renderer/modeling/bsdf/bsdf.h"
#include "renderer/modeling/camera/camera.h"
#include "renderer/modeling/edf/edf.h"
#include "renderer/modeling/frame/frame.h"
#include "renderer/modeling/environmentedf/environmentedf.h"
#include "renderer/modeling/environmentshader/environmentshader.h"
#include "renderer/modeling/input/inputbinder.h"
#include "renderer/modeling/input/uniforminputevaluator.h"
#include "renderer/modeling/project/project.h"
#include "renderer/modeling/scene/assembly.h"
#include "renderer/modeling/scene/containers.h"
#include "renderer/modeling/scene/scene.h"
#include "renderer/modeling/surfaceshader/surfaceshader.h"
// appleseed.foundation headers.
#include "foundation/core/exceptions/exception.h"
#include "foundation/utility/foreach.h"
// Standard headers.
#include <exception>
using namespace foundation;
using namespace std;
namespace renderer
{
//
// MasterRenderer class implementation.
//
MasterRenderer::MasterRenderer(
Project& project,
const ParamArray& params,
IRendererController* renderer_controller,
ITileCallbackFactory* tile_callback_factory)
: m_project(project)
, m_params(params)
, m_renderer_controller(renderer_controller)
, m_tile_callback_factory(tile_callback_factory)
{
}
ParamArray& MasterRenderer::get_parameters()
{
return m_params;
}
const ParamArray& MasterRenderer::get_parameters() const
{
return m_params;
}
void MasterRenderer::render()
{
try
{
do_render();
}
catch (const Exception& e)
{
m_renderer_controller->on_rendering_abort();
RENDERER_LOG_ERROR("rendering failed: %s", e.what());
}
catch (const bad_alloc&)
{
m_renderer_controller->on_rendering_abort();
RENDERER_LOG_ERROR("rendering failed: ran out of memory");
}
catch (...)
{
m_renderer_controller->on_rendering_abort();
RENDERER_LOG_ERROR("rendering failed: unknown exception");
}
}
void MasterRenderer::do_render()
{
while (true)
{
m_renderer_controller->on_rendering_begin();
const IRendererController::Status status = initialize_and_render_frame_sequence();
switch (status)
{
case IRendererController::TerminateRendering:
m_renderer_controller->on_rendering_success();
return;
case IRendererController::AbortRendering:
m_renderer_controller->on_rendering_abort();
return;
case IRendererController::ReinitializeRendering:
break;
assert_otherwise;
}
}
}
IRendererController::Status MasterRenderer::initialize_and_render_frame_sequence()
{
assert(m_project.get_scene());
assert(m_project.get_frame());
// Bind all scene entities inputs.
if (!bind_inputs())
return IRendererController::AbortRendering;
const Scene& scene = *m_project.get_scene();
Frame& frame = *m_project.get_frame();
// Create the light sampler.
LightSampler light_sampler(scene);
// Create the shading engine.
ShadingEngine shading_engine(m_params.child("shading_engine"));
//
// Create a lighting engine factory.
//
auto_ptr<ILightingEngineFactory> lighting_engine_factory;
const string lighting_engine_param =
m_params.get_required<string>("lighting_engine", "pt");
if (lighting_engine_param == "drt")
{
lighting_engine_factory.reset(
new DRTLightingEngineFactory(
light_sampler,
m_params.child("drt")));
}
else if (lighting_engine_param == "pt")
{
lighting_engine_factory.reset(
new PTLightingEngineFactory(
light_sampler,
m_params.child("pt")));
}
//
// Create a sample renderer factory.
//
auto_ptr<ISampleRendererFactory> sample_renderer_factory;
const string sample_renderer_param =
m_params.get_required<string>("sample_renderer", "generic");
if (sample_renderer_param == "generic")
{
sample_renderer_factory.reset(
new GenericSampleRendererFactory(
scene,
m_project.get_trace_context(),
lighting_engine_factory.get(),
shading_engine,
m_params.child("generic_sample_renderer")));
}
//
// Create a tile renderer factory.
//
auto_ptr<ITileRendererFactory> tile_renderer_factory;
const string tile_renderer_param =
m_params.get_required<string>("tile_renderer", "generic");
if (tile_renderer_param == "generic")
{
tile_renderer_factory.reset(
new GenericTileRendererFactory(
frame,
sample_renderer_factory.get(),
m_params.child("generic_tile_renderer")));
}
else if (tile_renderer_param == "blank")
{
tile_renderer_factory.reset(new BlankTileRendererFactory());
}
else if (tile_renderer_param == "debug")
{
tile_renderer_factory.reset(new DebugTileRendererFactory());
}
//
// Create a sample generator factory.
//
auto_ptr<ISampleGeneratorFactory> sample_generator_factory;
const string sample_generator_param =
m_params.get_optional<string>("sample_generator", "generic");
if (sample_generator_param == "generic")
{
sample_generator_factory.reset(
new GenericSampleGeneratorFactory(
frame,
sample_renderer_factory.get()));
}
else if (sample_generator_param == "lighttracing")
{
sample_generator_factory.reset(
new LightTracingSampleGeneratorFactory(
scene,
frame,
m_project.get_trace_context(),
light_sampler,
m_params.child("lighttracing_sample_generator")));
}
//
// Create an accumulation framebuffer.
//
auto_ptr<AccumulationFramebuffer> accumulation_framebuffer;
const string accumulation_fb_param =
m_params.get_optional<string>("accumulation_framebuffer", "global");
if (accumulation_fb_param == "global")
{
accumulation_framebuffer.reset(
new GlobalAccumulationFramebuffer(
frame.properties().m_canvas_width,
frame.properties().m_canvas_height));
}
else if (accumulation_fb_param == "local")
{
accumulation_framebuffer.reset(
new LocalAccumulationFramebuffer(
frame.properties().m_canvas_width,
frame.properties().m_canvas_height));
}
//
// Create a frame renderer.
//
auto_release_ptr<IFrameRenderer> frame_renderer;
const string frame_renderer_param =
m_params.get_required<string>("frame_renderer", "generic");
if (frame_renderer_param == "generic")
{
frame_renderer.reset(
GenericFrameRendererFactory::create(
frame,
tile_renderer_factory.get(),
m_tile_callback_factory,
m_params.child("generic_frame_renderer")));
}
else if (frame_renderer_param == "progressive")
{
frame_renderer.reset(
ProgressiveFrameRendererFactory::create(
frame,
*accumulation_framebuffer.get(),
sample_generator_factory.get(),
m_tile_callback_factory,
m_params.child("progressive_frame_renderer")));
}
// Execute the main rendering loop.
return render_frame_sequence(frame_renderer.get());
}
IRendererController::Status MasterRenderer::render_frame_sequence(IFrameRenderer* frame_renderer)
{
while (true)
{
assert(!frame_renderer->is_rendering());
m_renderer_controller->on_frame_begin();
on_frame_begin();
const IRendererController::Status status = render_frame(frame_renderer);
assert(!frame_renderer->is_rendering());
on_frame_end();
m_renderer_controller->on_frame_end();
switch (status)
{
case IRendererController::TerminateRendering:
case IRendererController::AbortRendering:
case IRendererController::ReinitializeRendering:
return status;
case IRendererController::RestartRendering:
break;
assert_otherwise;
}
}
}
IRendererController::Status MasterRenderer::render_frame(IFrameRenderer* frame_renderer)
{
frame_renderer->start_rendering();
while (frame_renderer->is_rendering())
{
const IRendererController::Status status = m_renderer_controller->on_progress();
if (status == IRendererController::ContinueRendering)
continue;
frame_renderer->stop_rendering();
return status;
}
return IRendererController::TerminateRendering;
}
bool MasterRenderer::bind_inputs() const
{
InputBinder input_binder;
input_binder.bind(*m_project.get_scene());
return input_binder.get_error_count() == 0;
}
namespace
{
//
// Invoke on_frame_begin() / on_frame_end() on all entities of a collection.
//
template <typename EntityCollection>
void invoke_on_frame_begin_collection(
EntityCollection& entities,
const Project& project)
{
for (each<EntityCollection> i = entities; i; ++i)
invoke_on_frame_begin(*i, project);
}
template <typename EntityCollection>
void invoke_on_frame_begin_collection(
EntityCollection& entities,
const Project& project,
UniformInputEvaluator& input_evaluator)
{
for (each<EntityCollection> i = entities; i; ++i)
invoke_on_frame_begin(*i, project, input_evaluator);
}
template <typename EntityCollection>
void invoke_on_frame_end_collection(
EntityCollection& entities,
const Project& project)
{
for (each<EntityCollection> i = entities; i; ++i)
invoke_on_frame_end(*i, project);
}
//
// Invoke on_frame_begin() / on_frame_end() on a single entity.
//
template <typename Entity>
void invoke_on_frame_begin(
Entity& entity,
const Project& project)
{
entity.on_frame_begin(project);
}
template <typename Entity>
void invoke_on_frame_begin(
Entity& entity,
const Project& project,
UniformInputEvaluator& input_evaluator)
{
const void* data =
input_evaluator.evaluate(entity.get_inputs());
entity.on_frame_begin(project, data);
}
template <typename Entity>
void invoke_on_frame_end(
Entity& entity,
const Project& project)
{
entity.on_frame_end(project);
}
//
// Invoke on_frame_begin() / on_frame_end() on all entities of an assembly.
//
template <>
void invoke_on_frame_begin(
Assembly& assembly,
const Project& project,
UniformInputEvaluator& input_evaluator)
{
invoke_on_frame_begin_collection(assembly.surface_shaders(), project);
invoke_on_frame_begin_collection(assembly.bsdfs(), project, input_evaluator);
invoke_on_frame_begin_collection(assembly.edfs(), project, input_evaluator);
}
template <>
void invoke_on_frame_end(
Assembly& assembly,
const Project& project)
{
invoke_on_frame_end_collection(assembly.edfs(), project);
invoke_on_frame_end_collection(assembly.bsdfs(), project);
invoke_on_frame_end_collection(assembly.surface_shaders(), project);
}
}
void MasterRenderer::on_frame_begin() const
{
const Scene& scene = *m_project.get_scene();
Camera* camera = scene.get_camera();
assert(camera);
Intersector intersector(m_project.get_trace_context(), false);
camera->on_frame_begin(m_project, intersector);
invoke_on_frame_begin_collection(scene.environment_edfs(), m_project);
invoke_on_frame_begin_collection(scene.environment_shaders(), m_project);
UniformInputEvaluator input_evaluator;
invoke_on_frame_begin_collection(scene.assemblies(), m_project, input_evaluator);
}
void MasterRenderer::on_frame_end() const
{
const Scene& scene = *m_project.get_scene();
invoke_on_frame_end_collection(scene.assemblies(), m_project);
invoke_on_frame_end_collection(scene.environment_shaders(), m_project);
invoke_on_frame_end_collection(scene.environment_edfs(), m_project);
Camera* camera = scene.get_camera();
assert(camera);
camera->on_frame_end(m_project);
}
} // namespace renderer
|
//
// This source file is part of appleseed.
// Visit http://appleseedhq.net/ for additional information and resources.
//
// This software is released under the MIT license.
//
// Copyright (c) 2010-2011 Francois Beaune
//
// 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.
//
// Interface header.
#include "masterrenderer.h"
// appleseed.renderer headers.
#include "renderer/kernel/intersection/intersector.h"
#include "renderer/kernel/lighting/drt/drt.h"
#include "renderer/kernel/lighting/ilightingengine.h"
#include "renderer/kernel/lighting/lightsampler.h"
#include "renderer/kernel/lighting/pathtracing/pathtracing.h"
#include "renderer/kernel/rendering/debug/blanktilerenderer.h"
#include "renderer/kernel/rendering/debug/debugtilerenderer.h"
#include "renderer/kernel/rendering/generic/genericframerenderer.h"
#include "renderer/kernel/rendering/generic/genericsamplegenerator.h"
#include "renderer/kernel/rendering/generic/genericsamplerenderer.h"
#include "renderer/kernel/rendering/generic/generictilerenderer.h"
#include "renderer/kernel/rendering/lighttracing/lighttracingsamplegenerator.h"
#include "renderer/kernel/rendering/progressive/progressiveframerenderer.h"
#include "renderer/kernel/rendering/accumulationframebuffer.h"
#include "renderer/kernel/rendering/globalaccumulationframebuffer.h"
#include "renderer/kernel/rendering/iframerenderer.h"
#include "renderer/kernel/rendering/isamplegenerator.h"
#include "renderer/kernel/rendering/isamplerenderer.h"
#include "renderer/kernel/rendering/itilecallback.h"
#include "renderer/kernel/rendering/itilerenderer.h"
#include "renderer/kernel/rendering/localaccumulationframebuffer.h"
#include "renderer/kernel/shading/shadingcontext.h"
#include "renderer/kernel/shading/shadingengine.h"
#include "renderer/kernel/texturing/texturecache.h"
#include "renderer/modeling/bsdf/bsdf.h"
#include "renderer/modeling/camera/camera.h"
#include "renderer/modeling/edf/edf.h"
#include "renderer/modeling/frame/frame.h"
#include "renderer/modeling/environmentedf/environmentedf.h"
#include "renderer/modeling/environmentshader/environmentshader.h"
#include "renderer/modeling/input/inputbinder.h"
#include "renderer/modeling/input/uniforminputevaluator.h"
#include "renderer/modeling/project/project.h"
#include "renderer/modeling/scene/assembly.h"
#include "renderer/modeling/scene/containers.h"
#include "renderer/modeling/scene/scene.h"
#include "renderer/modeling/surfaceshader/surfaceshader.h"
// appleseed.foundation headers.
#include "foundation/core/exceptions/exception.h"
#include "foundation/utility/foreach.h"
// Standard headers.
#include <exception>
using namespace foundation;
using namespace std;
namespace renderer
{
//
// MasterRenderer class implementation.
//
MasterRenderer::MasterRenderer(
Project& project,
const ParamArray& params,
IRendererController* renderer_controller,
ITileCallbackFactory* tile_callback_factory)
: m_project(project)
, m_params(params)
, m_renderer_controller(renderer_controller)
, m_tile_callback_factory(tile_callback_factory)
{
}
ParamArray& MasterRenderer::get_parameters()
{
return m_params;
}
const ParamArray& MasterRenderer::get_parameters() const
{
return m_params;
}
void MasterRenderer::render()
{
try
{
do_render();
}
catch (const Exception& e)
{
m_renderer_controller->on_rendering_abort();
RENDERER_LOG_ERROR("rendering failed: %s", e.what());
}
catch (const bad_alloc&)
{
m_renderer_controller->on_rendering_abort();
RENDERER_LOG_ERROR("rendering failed: ran out of memory");
}
catch (...)
{
m_renderer_controller->on_rendering_abort();
RENDERER_LOG_ERROR("rendering failed: unknown exception");
}
}
void MasterRenderer::do_render()
{
while (true)
{
m_renderer_controller->on_rendering_begin();
const IRendererController::Status status = initialize_and_render_frame_sequence();
switch (status)
{
case IRendererController::TerminateRendering:
m_renderer_controller->on_rendering_success();
return;
case IRendererController::AbortRendering:
m_renderer_controller->on_rendering_abort();
return;
case IRendererController::ReinitializeRendering:
break;
assert_otherwise;
}
}
}
IRendererController::Status MasterRenderer::initialize_and_render_frame_sequence()
{
assert(m_project.get_scene());
assert(m_project.get_frame());
// Bind all scene entities inputs.
if (!bind_inputs())
return IRendererController::AbortRendering;
const Scene& scene = *m_project.get_scene();
Frame& frame = *m_project.get_frame();
// Create the light sampler.
LightSampler light_sampler(scene);
// Create the shading engine.
ShadingEngine shading_engine(m_params.child("shading_engine"));
//
// Create a lighting engine factory.
//
auto_ptr<ILightingEngineFactory> lighting_engine_factory;
const string lighting_engine_param =
m_params.get_required<string>("lighting_engine", "pt");
if (lighting_engine_param == "drt")
{
lighting_engine_factory.reset(
new DRTLightingEngineFactory(
light_sampler,
m_params.child("drt")));
}
else if (lighting_engine_param == "pt")
{
lighting_engine_factory.reset(
new PTLightingEngineFactory(
light_sampler,
m_params.child("pt")));
}
//
// Create a sample renderer factory.
//
auto_ptr<ISampleRendererFactory> sample_renderer_factory;
const string sample_renderer_param =
m_params.get_required<string>("sample_renderer", "generic");
if (sample_renderer_param == "generic")
{
sample_renderer_factory.reset(
new GenericSampleRendererFactory(
scene,
m_project.get_trace_context(),
lighting_engine_factory.get(),
shading_engine,
m_params.child("generic_sample_renderer")));
}
//
// Create a tile renderer factory.
//
auto_ptr<ITileRendererFactory> tile_renderer_factory;
const string tile_renderer_param =
m_params.get_required<string>("tile_renderer", "generic");
if (tile_renderer_param == "generic")
{
tile_renderer_factory.reset(
new GenericTileRendererFactory(
frame,
sample_renderer_factory.get(),
m_params.child("generic_tile_renderer")));
}
else if (tile_renderer_param == "blank")
{
tile_renderer_factory.reset(new BlankTileRendererFactory());
}
else if (tile_renderer_param == "debug")
{
tile_renderer_factory.reset(new DebugTileRendererFactory());
}
//
// Create a sample generator factory.
//
auto_ptr<ISampleGeneratorFactory> sample_generator_factory;
const string sample_generator_param =
m_params.get_optional<string>("sample_generator", "generic");
if (sample_generator_param == "generic")
{
sample_generator_factory.reset(
new GenericSampleGeneratorFactory(
frame,
sample_renderer_factory.get()));
}
else if (sample_generator_param == "lighttracing")
{
sample_generator_factory.reset(
new LightTracingSampleGeneratorFactory(
scene,
frame,
m_project.get_trace_context(),
light_sampler,
m_params.child("lighttracing_sample_generator")));
}
//
// Create an accumulation framebuffer.
//
auto_ptr<AccumulationFramebuffer> accumulation_framebuffer;
const string accumulation_fb_param =
m_params.get_optional<string>("accumulation_framebuffer", "local");
if (accumulation_fb_param == "global")
{
accumulation_framebuffer.reset(
new GlobalAccumulationFramebuffer(
frame.properties().m_canvas_width,
frame.properties().m_canvas_height));
}
else if (accumulation_fb_param == "local")
{
accumulation_framebuffer.reset(
new LocalAccumulationFramebuffer(
frame.properties().m_canvas_width,
frame.properties().m_canvas_height));
}
//
// Create a frame renderer.
//
auto_release_ptr<IFrameRenderer> frame_renderer;
const string frame_renderer_param =
m_params.get_required<string>("frame_renderer", "generic");
if (frame_renderer_param == "generic")
{
frame_renderer.reset(
GenericFrameRendererFactory::create(
frame,
tile_renderer_factory.get(),
m_tile_callback_factory,
m_params.child("generic_frame_renderer")));
}
else if (frame_renderer_param == "progressive")
{
frame_renderer.reset(
ProgressiveFrameRendererFactory::create(
frame,
*accumulation_framebuffer.get(),
sample_generator_factory.get(),
m_tile_callback_factory,
m_params.child("progressive_frame_renderer")));
}
// Execute the main rendering loop.
return render_frame_sequence(frame_renderer.get());
}
IRendererController::Status MasterRenderer::render_frame_sequence(IFrameRenderer* frame_renderer)
{
while (true)
{
assert(!frame_renderer->is_rendering());
m_renderer_controller->on_frame_begin();
on_frame_begin();
const IRendererController::Status status = render_frame(frame_renderer);
assert(!frame_renderer->is_rendering());
on_frame_end();
m_renderer_controller->on_frame_end();
switch (status)
{
case IRendererController::TerminateRendering:
case IRendererController::AbortRendering:
case IRendererController::ReinitializeRendering:
return status;
case IRendererController::RestartRendering:
break;
assert_otherwise;
}
}
}
IRendererController::Status MasterRenderer::render_frame(IFrameRenderer* frame_renderer)
{
frame_renderer->start_rendering();
while (frame_renderer->is_rendering())
{
const IRendererController::Status status = m_renderer_controller->on_progress();
if (status == IRendererController::ContinueRendering)
continue;
frame_renderer->stop_rendering();
return status;
}
return IRendererController::TerminateRendering;
}
bool MasterRenderer::bind_inputs() const
{
InputBinder input_binder;
input_binder.bind(*m_project.get_scene());
return input_binder.get_error_count() == 0;
}
namespace
{
//
// Invoke on_frame_begin() / on_frame_end() on all entities of a collection.
//
template <typename EntityCollection>
void invoke_on_frame_begin_collection(
EntityCollection& entities,
const Project& project)
{
for (each<EntityCollection> i = entities; i; ++i)
invoke_on_frame_begin(*i, project);
}
template <typename EntityCollection>
void invoke_on_frame_begin_collection(
EntityCollection& entities,
const Project& project,
UniformInputEvaluator& input_evaluator)
{
for (each<EntityCollection> i = entities; i; ++i)
invoke_on_frame_begin(*i, project, input_evaluator);
}
template <typename EntityCollection>
void invoke_on_frame_end_collection(
EntityCollection& entities,
const Project& project)
{
for (each<EntityCollection> i = entities; i; ++i)
invoke_on_frame_end(*i, project);
}
//
// Invoke on_frame_begin() / on_frame_end() on a single entity.
//
template <typename Entity>
void invoke_on_frame_begin(
Entity& entity,
const Project& project)
{
entity.on_frame_begin(project);
}
template <typename Entity>
void invoke_on_frame_begin(
Entity& entity,
const Project& project,
UniformInputEvaluator& input_evaluator)
{
const void* data =
input_evaluator.evaluate(entity.get_inputs());
entity.on_frame_begin(project, data);
}
template <typename Entity>
void invoke_on_frame_end(
Entity& entity,
const Project& project)
{
entity.on_frame_end(project);
}
//
// Invoke on_frame_begin() / on_frame_end() on all entities of an assembly.
//
template <>
void invoke_on_frame_begin(
Assembly& assembly,
const Project& project,
UniformInputEvaluator& input_evaluator)
{
invoke_on_frame_begin_collection(assembly.surface_shaders(), project);
invoke_on_frame_begin_collection(assembly.bsdfs(), project, input_evaluator);
invoke_on_frame_begin_collection(assembly.edfs(), project, input_evaluator);
}
template <>
void invoke_on_frame_end(
Assembly& assembly,
const Project& project)
{
invoke_on_frame_end_collection(assembly.edfs(), project);
invoke_on_frame_end_collection(assembly.bsdfs(), project);
invoke_on_frame_end_collection(assembly.surface_shaders(), project);
}
}
void MasterRenderer::on_frame_begin() const
{
const Scene& scene = *m_project.get_scene();
Camera* camera = scene.get_camera();
assert(camera);
Intersector intersector(m_project.get_trace_context(), false);
camera->on_frame_begin(m_project, intersector);
invoke_on_frame_begin_collection(scene.environment_edfs(), m_project);
invoke_on_frame_begin_collection(scene.environment_shaders(), m_project);
UniformInputEvaluator input_evaluator;
invoke_on_frame_begin_collection(scene.assemblies(), m_project, input_evaluator);
}
void MasterRenderer::on_frame_end() const
{
const Scene& scene = *m_project.get_scene();
invoke_on_frame_end_collection(scene.assemblies(), m_project);
invoke_on_frame_end_collection(scene.environment_shaders(), m_project);
invoke_on_frame_end_collection(scene.environment_edfs(), m_project);
Camera* camera = scene.get_camera();
assert(camera);
camera->on_frame_end(m_project);
}
} // namespace renderer
|
use the local accumulation framebuffer by default.
|
use the local accumulation framebuffer by default.
|
C++
|
mit
|
luisbarrancos/appleseed,aytekaman/appleseed,pjessesco/appleseed,pjessesco/appleseed,pjessesco/appleseed,Biart95/appleseed,dictoon/appleseed,aiivashchenko/appleseed,Aakash1312/appleseed,docwhite/appleseed,Aakash1312/appleseed,aytekaman/appleseed,Biart95/appleseed,est77/appleseed,gospodnetic/appleseed,aiivashchenko/appleseed,Biart95/appleseed,dictoon/appleseed,aytekaman/appleseed,aiivashchenko/appleseed,Vertexwahn/appleseed,est77/appleseed,luisbarrancos/appleseed,aiivashchenko/appleseed,luisbarrancos/appleseed,Vertexwahn/appleseed,est77/appleseed,docwhite/appleseed,aiivashchenko/appleseed,pjessesco/appleseed,luisbarrancos/appleseed,Aakash1312/appleseed,docwhite/appleseed,appleseedhq/appleseed,glebmish/appleseed,gospodnetic/appleseed,appleseedhq/appleseed,Vertexwahn/appleseed,glebmish/appleseed,Aakash1312/appleseed,gospodnetic/appleseed,aytekaman/appleseed,docwhite/appleseed,glebmish/appleseed,luisbarrancos/appleseed,appleseedhq/appleseed,pjessesco/appleseed,aytekaman/appleseed,dictoon/appleseed,docwhite/appleseed,dictoon/appleseed,dictoon/appleseed,Aakash1312/appleseed,Vertexwahn/appleseed,appleseedhq/appleseed,appleseedhq/appleseed,est77/appleseed,Biart95/appleseed,est77/appleseed,glebmish/appleseed,Biart95/appleseed,glebmish/appleseed,gospodnetic/appleseed,Vertexwahn/appleseed,gospodnetic/appleseed
|
f1cbb75feee6a80f52195892c5be23464bec4085
|
src/QPTasks.cpp
|
src/QPTasks.cpp
|
// This file is part of Tasks.
//
// Tasks is free software: you can redistribute it and/or modify
// it under the terms of the GNU Lesser General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// Tasks 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 Tasks. If not, see <http://www.gnu.org/licenses/>.
// associated header
#include "QPTasks.h"
// includes
// std
#include <cmath>
#include <iostream>
// Eigen
#include <Eigen/Geometry>
// RBDyn
#include <MultiBody.h>
#include <MultiBodyConfig.h>
namespace tasks
{
namespace qp
{
/**
* SetPointTask
*/
SetPointTask::SetPointTask(const rbd::MultiBody& mb, HighLevelTask* hlTask,
double stiffness, double weight):
Task(weight),
hlTask_(hlTask),
stiffness_(stiffness),
stiffnessSqrt_(2.*std::sqrt(stiffness)),
Q_(mb.nrDof(), mb.nrDof()),
C_(mb.nrDof()),
alphaVec_(mb.nrDof())
{}
void SetPointTask::stiffness(double stiffness)
{
stiffness_ = stiffness;
stiffnessSqrt_ = 2.*std::sqrt(stiffness);
}
void SetPointTask::update(const rbd::MultiBody& mb, const rbd::MultiBodyConfig& mbc)
{
hlTask_->update(mb, mbc);
const Eigen::MatrixXd& J = hlTask_->jac();
const Eigen::MatrixXd& JD = hlTask_->jacDot();
const Eigen::VectorXd& err = hlTask_->eval();
rbd::paramToVector(mbc.alpha, alphaVec_);
Q_ = J.transpose()*J;
C_ = -J.transpose()*(stiffness_*err - stiffnessSqrt_*J*alphaVec_ - JD*alphaVec_);
}
const Eigen::MatrixXd& SetPointTask::Q() const
{
return Q_;
}
const Eigen::VectorXd& SetPointTask::C() const
{
return C_;
}
/**
* PostureTask
*/
PostureTask::PostureTask(const rbd::MultiBody& mb,
std::vector<std::vector<double>> q,
double stiffness, double weight):
Task(weight),
pt_(mb, q),
stiffness_(stiffness),
stiffnessSqrt_(2.*std::sqrt(stiffness)),
Q_(mb.nrDof(), mb.nrDof()),
C_(mb.nrDof()),
alphaVec_(mb.nrDof())
{}
void PostureTask::stiffness(double stiffness)
{
stiffness_ = stiffness;
stiffnessSqrt_ = 2.*std::sqrt(stiffness);
}
void PostureTask::update(const rbd::MultiBody& mb, const rbd::MultiBodyConfig& mbc)
{
pt_.update(mb, mbc);
rbd::paramToVector(mbc.alpha, alphaVec_);
Q_ = pt_.jac();
C_.setZero();
// joint
C_.segment(mb.jointPosInDof(1), mb.nrDof()) = -stiffness_*pt_.eval() +
stiffnessSqrt_*alphaVec_.segment(mb.jointPosInDof(1), mb.nrDof());
}
const Eigen::MatrixXd& PostureTask::Q() const
{
return Q_;
}
const Eigen::VectorXd& PostureTask::C() const
{
return C_;
}
/**
* PositionTask
*/
PositionTask::PositionTask(const rbd::MultiBody& mb, int bodyId,
const Eigen::Vector3d& pos, const Eigen::Vector3d& bodyPoint):
pt_(mb, bodyId, pos, bodyPoint)
{
}
int PositionTask::dim()
{
return 3;
}
void PositionTask::update(const rbd::MultiBody& mb, const rbd::MultiBodyConfig& mbc)
{
pt_.update(mb, mbc);
pt_.updateDot(mb, mbc);
}
const Eigen::MatrixXd& PositionTask::jac()
{
return pt_.jac();
}
const Eigen::MatrixXd& PositionTask::jacDot()
{
return pt_.jacDot();
}
const Eigen::VectorXd& PositionTask::eval()
{
return pt_.eval();
}
/**
* OrientationTask
*/
OrientationTask::OrientationTask(const rbd::MultiBody& mb, int bodyId,
const Eigen::Quaterniond& ori):
ot_(mb, bodyId, ori)
{}
OrientationTask::OrientationTask(const rbd::MultiBody& mb, int bodyId,
const Eigen::Matrix3d& ori):
ot_(mb, bodyId, ori)
{}
int OrientationTask::dim()
{
return 3;
}
void OrientationTask::update(const rbd::MultiBody& mb, const rbd::MultiBodyConfig& mbc)
{
ot_.update(mb, mbc);
ot_.updateDot(mb, mbc);
}
const Eigen::MatrixXd& OrientationTask::jac()
{
return ot_.jac();
}
const Eigen::MatrixXd& OrientationTask::jacDot()
{
return ot_.jacDot();
}
const Eigen::VectorXd& OrientationTask::eval()
{
return ot_.eval();
}
/**
* CoMTask
*/
CoMTask::CoMTask(const rbd::MultiBody& mb, const Eigen::Vector3d& com):
ct_(mb, com)
{}
int CoMTask::dim()
{
return 3;
}
void CoMTask::update(const rbd::MultiBody& mb, const rbd::MultiBodyConfig& mbc)
{
ct_.update(mb, mbc);
ct_.updateDot(mb, mbc);
}
const Eigen::MatrixXd& CoMTask::jac()
{
return ct_.jac();
}
const Eigen::MatrixXd& CoMTask::jacDot()
{
return ct_.jacDot();
}
const Eigen::VectorXd& CoMTask::eval()
{
return ct_.eval();
}
} // namespace qp
} // namespace tasks
|
// This file is part of Tasks.
//
// Tasks is free software: you can redistribute it and/or modify
// it under the terms of the GNU Lesser General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// Tasks 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 Tasks. If not, see <http://www.gnu.org/licenses/>.
// associated header
#include "QPTasks.h"
// includes
// std
#include <cmath>
#include <iostream>
// Eigen
#include <Eigen/Geometry>
// RBDyn
#include <MultiBody.h>
#include <MultiBodyConfig.h>
namespace tasks
{
namespace qp
{
/**
* SetPointTask
*/
SetPointTask::SetPointTask(const rbd::MultiBody& mb, HighLevelTask* hlTask,
double stiffness, double weight):
Task(weight),
hlTask_(hlTask),
stiffness_(stiffness),
stiffnessSqrt_(2.*std::sqrt(stiffness)),
Q_(mb.nrDof(), mb.nrDof()),
C_(mb.nrDof()),
alphaVec_(mb.nrDof())
{}
void SetPointTask::stiffness(double stiffness)
{
stiffness_ = stiffness;
stiffnessSqrt_ = 2.*std::sqrt(stiffness);
}
void SetPointTask::update(const rbd::MultiBody& mb, const rbd::MultiBodyConfig& mbc)
{
hlTask_->update(mb, mbc);
const Eigen::MatrixXd& J = hlTask_->jac();
const Eigen::MatrixXd& JD = hlTask_->jacDot();
const Eigen::VectorXd& err = hlTask_->eval();
rbd::paramToVector(mbc.alpha, alphaVec_);
Q_ = J.transpose()*J;
C_ = -J.transpose()*(stiffness_*err - stiffnessSqrt_*J*alphaVec_ - JD*alphaVec_);
}
const Eigen::MatrixXd& SetPointTask::Q() const
{
return Q_;
}
const Eigen::VectorXd& SetPointTask::C() const
{
return C_;
}
/**
* PostureTask
*/
PostureTask::PostureTask(const rbd::MultiBody& mb,
std::vector<std::vector<double>> q,
double stiffness, double weight):
Task(weight),
pt_(mb, q),
stiffness_(stiffness),
stiffnessSqrt_(2.*std::sqrt(stiffness)),
Q_(mb.nrDof(), mb.nrDof()),
C_(mb.nrDof()),
alphaVec_(mb.nrDof())
{}
void PostureTask::stiffness(double stiffness)
{
stiffness_ = stiffness;
stiffnessSqrt_ = 2.*std::sqrt(stiffness);
}
void PostureTask::update(const rbd::MultiBody& mb, const rbd::MultiBodyConfig& mbc)
{
pt_.update(mb, mbc);
rbd::paramToVector(mbc.alpha, alphaVec_);
Q_ = pt_.jac();
C_.setZero();
int deb = mb.jointPosInDof(1);
int end = mb.nrDof() - deb;
// joint
C_.segment(deb, end) = -stiffness_*pt_.eval().segment(deb, end) +
stiffnessSqrt_*alphaVec_.segment(deb, end);
}
const Eigen::MatrixXd& PostureTask::Q() const
{
return Q_;
}
const Eigen::VectorXd& PostureTask::C() const
{
return C_;
}
/**
* PositionTask
*/
PositionTask::PositionTask(const rbd::MultiBody& mb, int bodyId,
const Eigen::Vector3d& pos, const Eigen::Vector3d& bodyPoint):
pt_(mb, bodyId, pos, bodyPoint)
{
}
int PositionTask::dim()
{
return 3;
}
void PositionTask::update(const rbd::MultiBody& mb, const rbd::MultiBodyConfig& mbc)
{
pt_.update(mb, mbc);
pt_.updateDot(mb, mbc);
}
const Eigen::MatrixXd& PositionTask::jac()
{
return pt_.jac();
}
const Eigen::MatrixXd& PositionTask::jacDot()
{
return pt_.jacDot();
}
const Eigen::VectorXd& PositionTask::eval()
{
return pt_.eval();
}
/**
* OrientationTask
*/
OrientationTask::OrientationTask(const rbd::MultiBody& mb, int bodyId,
const Eigen::Quaterniond& ori):
ot_(mb, bodyId, ori)
{}
OrientationTask::OrientationTask(const rbd::MultiBody& mb, int bodyId,
const Eigen::Matrix3d& ori):
ot_(mb, bodyId, ori)
{}
int OrientationTask::dim()
{
return 3;
}
void OrientationTask::update(const rbd::MultiBody& mb, const rbd::MultiBodyConfig& mbc)
{
ot_.update(mb, mbc);
ot_.updateDot(mb, mbc);
}
const Eigen::MatrixXd& OrientationTask::jac()
{
return ot_.jac();
}
const Eigen::MatrixXd& OrientationTask::jacDot()
{
return ot_.jacDot();
}
const Eigen::VectorXd& OrientationTask::eval()
{
return ot_.eval();
}
/**
* CoMTask
*/
CoMTask::CoMTask(const rbd::MultiBody& mb, const Eigen::Vector3d& com):
ct_(mb, com)
{}
int CoMTask::dim()
{
return 3;
}
void CoMTask::update(const rbd::MultiBody& mb, const rbd::MultiBodyConfig& mbc)
{
ct_.update(mb, mbc);
ct_.updateDot(mb, mbc);
}
const Eigen::MatrixXd& CoMTask::jac()
{
return ct_.jac();
}
const Eigen::MatrixXd& CoMTask::jacDot()
{
return ct_.jacDot();
}
const Eigen::VectorXd& CoMTask::eval()
{
return ct_.eval();
}
} // namespace qp
} // namespace tasks
|
Fix PostureTask to support MultiBody with free flyer.
|
Fix PostureTask to support MultiBody with free flyer.
|
C++
|
bsd-2-clause
|
jrl-umi3218/Tasks,gergondet/Tasks,gergondet/Tasks,jrl-umi3218/Tasks,gergondet/Tasks,jrl-umi3218/Tasks,gergondet/Tasks
|
a2afc39ac0ba4a51d1e54475d6aceacbd841c65f
|
src/SeekCam.cpp
|
src/SeekCam.cpp
|
/*
* Seek camera interface
* Author: Maarten Vandersteegen
*/
#include "SeekCam.h"
#include "SeekLogging.h"
using namespace LibSeek;
SeekCam::SeekCam(int vendor_id, int product_id, uint16_t* buffer, size_t raw_height, size_t raw_width, cv::Rect roi, std::string ffc_filename) :
m_offset(0x4000),
m_ffc_filename(ffc_filename),
m_is_opened(false),
m_dev(vendor_id, product_id),
m_raw_data(buffer),
m_raw_data_size(raw_height * raw_width),
m_raw_frame(raw_height,
raw_width,
CV_16UC1,
buffer,
cv::Mat::AUTO_STEP),
m_flat_field_calibration_frame(),
m_additional_ffc(),
m_dead_pixel_mask()
{
/* set ROI to exclude metadata frame regions */
m_raw_frame = m_raw_frame(roi);
}
SeekCam::~SeekCam()
{
close();
}
bool SeekCam::open()
{
if (m_ffc_filename != std::string()) {
m_additional_ffc = cv::imread(m_ffc_filename, -1);
if (m_additional_ffc.type() != m_raw_frame.type()) {
error("Error: '%s' not found or it has the wrong type: %d\n",
m_ffc_filename.c_str(), m_additional_ffc.type());
return false;
}
if (m_additional_ffc.size() != m_raw_frame.size()) {
error("Error: expected '%s' to have size [%d,%d], got [%d,%d]\n",
m_ffc_filename.c_str(),
m_raw_frame.cols, m_raw_frame.rows,
m_additional_ffc.cols, m_additional_ffc.rows);
return false;
}
}
return open_cam();
}
void SeekCam::close()
{
if (m_dev.isOpened()) {
std::vector<uint8_t> data = { 0x00, 0x00 };
m_dev.request_set(DeviceCommand::SET_OPERATION_MODE, data);
m_dev.request_set(DeviceCommand::SET_OPERATION_MODE, data);
m_dev.request_set(DeviceCommand::SET_OPERATION_MODE, data);
}
m_is_opened = false;
}
bool SeekCam::isOpened()
{
return m_is_opened;
}
bool SeekCam::grab()
{
int i;
for (i=0; i<10; i++) {
if(!get_frame()) {
error("Error: frame acquisition failed\n");
return false;
}
if (frame_id() == 3) {
return true;
} else if (frame_id() == 1) {
m_raw_frame.copyTo(m_flat_field_calibration_frame);
}
}
return false;
}
void SeekCam::retrieve(cv::Mat& dst)
{
/* apply flat field calibration */
m_raw_frame += m_offset - m_flat_field_calibration_frame;
/* filter out dead pixels */
apply_dead_pixel_filter(m_raw_frame, dst);
/* apply additional flat field calibration for degradient */
if (!m_additional_ffc.empty())
dst += m_offset - m_additional_ffc;
}
bool SeekCam::read(cv::Mat& dst)
{
if (!grab())
return false;
retrieve(dst);
return true;
}
void SeekCam::convertToGreyScale(cv::Mat& src, cv::Mat& dst)
{
double tmin, tmax, rsize;
double rnint = 0;
double rnstart = 0;
size_t n;
size_t num_of_pixels = src.rows * src.cols;
cv::minMaxLoc(src, &tmin, &tmax);
rsize = (tmax - tmin) / 10.0;
for (n=0; n<10; n++) {
double min = tmin + n * rsize;
cv::Mat mask;
cv::Mat temp;
rnstart += rnint;
cv::inRange(src, cv::Scalar(min), cv::Scalar(min + rsize), mask);
/* num_of_pixels_in_range / total_num_of_pixels * 256 */
rnint = (cv::countNonZero(mask) << 8) / num_of_pixels;
temp = ((src - min) * rnint) / rsize + rnstart;
temp.copyTo(dst, mask);
}
dst.convertTo(dst, CV_8UC1);
}
bool SeekCam::open_cam()
{
int i;
if (!m_dev.open()) {
error("Error: open failed\n");
return false;
}
/* init retry loop: sometimes cam skips first 512 bytes of first frame (needed for dead pixel filter) */
for (i=0; i<3; i++) {
/* cam specific configuration */
if (!init_cam()) {
error("Error: init_cam failed\n");
return false;
}
if (!get_frame()) {
error("Error: first frame acquisition failed, retry attempt %d\n", i+1);
continue;
}
if (frame_id() != 4) {
error("Error: expected first frame to have id 4\n");
return false;
}
create_dead_pixel_list(m_raw_frame, m_dead_pixel_mask, m_dead_pixel_list);
if (!grab()) {
error("Error: first grab failed\n");
return false;
}
m_is_opened = true;
return true;
}
error("Error: max init retry count exceeded\n");
return false;
}
bool SeekCam::get_frame()
{
/* request new frame */
uint8_t* s = reinterpret_cast<uint8_t*>(&m_raw_data_size);
std::vector<uint8_t> data = { s[0], s[1], s[2], s[3] };
if (!m_dev.request_set(DeviceCommand::START_GET_IMAGE_TRANSFER, data))
return false;
/* store frame data */
if (!m_dev.fetch_frame(m_raw_data, m_raw_data_size))
return false;
return true;
}
void SeekCam::print_usb_data(std::vector<uint8_t>& data)
{
std::stringstream ss;
std::string out;
ss << "Response: ";
for (size_t i = 0; i < data.size(); i++) {
ss << " " << std::hex << data[i];
}
out = ss.str();
debug("%s\n", out.c_str());
}
void SeekCam::create_dead_pixel_list(cv::Mat frame, cv::Mat& dead_pixel_mask,
std::vector<cv::Point>& dead_pixel_list)
{
int x, y;
bool has_unlisted_pixels;
double max_value;
cv::Point hist_max_value;
cv::Mat tmp, hist;
int channels[] = {0};
int histSize[] = {0x4000};
float range[] = {0, 0x4000};
const float* ranges[] = { range };
/* calculate optimal threshold to determine what pixels are dead pixels */
frame.convertTo(tmp, CV_32FC1);
cv::minMaxLoc(tmp, nullptr, &max_value);
cv::calcHist(&tmp, 1, channels, cv::Mat(), hist, 1, histSize, ranges,
true, /* the histogram is uniform */
false);
hist.at<float>(0, 0) = 0; /* suppres 0th bin since its usual the highest,
but we don't want this one */
cv::minMaxLoc(hist, nullptr, nullptr, nullptr, &hist_max_value);
const double threshold = hist_max_value.y - (max_value - hist_max_value.y);
/* calculate the dead pixels mask */
cv::threshold(tmp, tmp, threshold, 255, cv::THRESH_BINARY);
tmp.convertTo(dead_pixel_mask, CV_8UC1);
/* build dead pixel list in a certain order to assure that every dead pixel value
* gets an estimated value in the filter stage */
dead_pixel_mask.convertTo(tmp, CV_16UC1);
dead_pixel_list.clear();
do {
has_unlisted_pixels = false;
for (y=0; y<tmp.rows; y++) {
for (x=0; x<tmp.cols; x++) {
const cv::Point p(x, y);
if (tmp.at<uint16_t>(y, x) != 0)
continue; /* not a dead pixel */
/* only add pixel to the list if we can estimate its value
* directly from its neighbor pixels */
if (calc_mean_value(tmp, p, 0) != 0) {
dead_pixel_list.push_back(p);
tmp.at<uint16_t>(y, x) = 255;
} else
has_unlisted_pixels = true;
}
}
} while (has_unlisted_pixels);
}
void SeekCam::apply_dead_pixel_filter(cv::Mat& src, cv::Mat& dst)
{
size_t i;
const size_t size = m_dead_pixel_list.size();
const uint32_t dead_pixel_marker = 0xffff;
dst.create(src.rows, src.cols, src.type()); /* ensure dst is properly allocated */
dst.setTo(dead_pixel_marker); /* value to identify dead pixels */
src.copyTo(dst, m_dead_pixel_mask); /* only copy non dead pixel values */
/* replace dead pixel values (0xffff) with the mean of its non dead surrounding pixels */
for (i=0; i<size; i++) {
cv::Point p = m_dead_pixel_list[i];
dst.at<uint16_t>(p) = calc_mean_value(dst, p, dead_pixel_marker);
}
}
uint16_t SeekCam::calc_mean_value(cv::Mat& img, cv::Point p, uint32_t dead_pixel_marker)
{
uint32_t value = 0, temp;
uint32_t div = 0;
const int right_border = img.cols - 1;
const int lower_border = img.rows - 1;
if (p.x != 0) {
/* if not on the left border of the image */
temp = img.at<uint16_t>(p.y, p.x-1);
if (temp != dead_pixel_marker) {
value += temp;
div++;
}
}
if (p.x != right_border) {
/* if not on the right border of the image */
temp = img.at<uint16_t>(p.y, p.x+1);
if (temp != dead_pixel_marker) {
value += temp;
div++;
}
}
if (p.y != 0) {
/* upper */
temp = img.at<uint16_t>(p.y-1, p.x);
if (temp != dead_pixel_marker) {
value += temp;
div++;
}
}
if (p.y != lower_border) {
/* lower */
temp = img.at<uint16_t>(p.y+1, p.x);
if (temp != dead_pixel_marker) {
value += temp;
div++;
}
}
if (div)
return (value / div);
return 0;
}
|
/*
* Seek camera interface
* Author: Maarten Vandersteegen
*/
#include "SeekCam.h"
#include "SeekLogging.h"
using namespace LibSeek;
SeekCam::SeekCam(int vendor_id, int product_id, uint16_t* buffer, size_t raw_height, size_t raw_width, cv::Rect roi, std::string ffc_filename) :
m_offset(0x4000),
m_ffc_filename(ffc_filename),
m_is_opened(false),
m_dev(vendor_id, product_id),
m_raw_data(buffer),
m_raw_data_size(raw_height * raw_width),
m_raw_frame(raw_height,
raw_width,
CV_16UC1,
buffer,
cv::Mat::AUTO_STEP),
m_flat_field_calibration_frame(),
m_additional_ffc(),
m_dead_pixel_mask()
{
/* set ROI to exclude metadata frame regions */
m_raw_frame = m_raw_frame(roi);
}
SeekCam::~SeekCam()
{
close();
}
bool SeekCam::open()
{
if (m_ffc_filename != std::string()) {
m_additional_ffc = cv::imread(m_ffc_filename, -1);
if (m_additional_ffc.type() != m_raw_frame.type()) {
error("Error: '%s' not found or it has the wrong type: %d\n",
m_ffc_filename.c_str(), m_additional_ffc.type());
return false;
}
if (m_additional_ffc.size() != m_raw_frame.size()) {
error("Error: expected '%s' to have size [%d,%d], got [%d,%d]\n",
m_ffc_filename.c_str(),
m_raw_frame.cols, m_raw_frame.rows,
m_additional_ffc.cols, m_additional_ffc.rows);
return false;
}
}
return open_cam();
}
void SeekCam::close()
{
if (m_dev.isOpened()) {
std::vector<uint8_t> data = { 0x00, 0x00 };
m_dev.request_set(DeviceCommand::SET_OPERATION_MODE, data);
m_dev.request_set(DeviceCommand::SET_OPERATION_MODE, data);
m_dev.request_set(DeviceCommand::SET_OPERATION_MODE, data);
}
m_is_opened = false;
}
bool SeekCam::isOpened()
{
return m_is_opened;
}
bool SeekCam::grab()
{
int i;
for (i=0; i<40; i++) {
if(!get_frame()) {
error("Error: frame acquisition failed\n");
return false;
}
if (frame_id() == 3) {
return true;
} else if (frame_id() == 1) {
m_raw_frame.copyTo(m_flat_field_calibration_frame);
}
}
return false;
}
void SeekCam::retrieve(cv::Mat& dst)
{
/* apply flat field calibration */
m_raw_frame += m_offset - m_flat_field_calibration_frame;
/* filter out dead pixels */
apply_dead_pixel_filter(m_raw_frame, dst);
/* apply additional flat field calibration for degradient */
if (!m_additional_ffc.empty())
dst += m_offset - m_additional_ffc;
}
bool SeekCam::read(cv::Mat& dst)
{
if (!grab())
return false;
retrieve(dst);
return true;
}
void SeekCam::convertToGreyScale(cv::Mat& src, cv::Mat& dst)
{
double tmin, tmax, rsize;
double rnint = 0;
double rnstart = 0;
size_t n;
size_t num_of_pixels = src.rows * src.cols;
cv::minMaxLoc(src, &tmin, &tmax);
rsize = (tmax - tmin) / 10.0;
for (n=0; n<10; n++) {
double min = tmin + n * rsize;
cv::Mat mask;
cv::Mat temp;
rnstart += rnint;
cv::inRange(src, cv::Scalar(min), cv::Scalar(min + rsize), mask);
/* num_of_pixels_in_range / total_num_of_pixels * 256 */
rnint = (cv::countNonZero(mask) << 8) / num_of_pixels;
temp = ((src - min) * rnint) / rsize + rnstart;
temp.copyTo(dst, mask);
}
dst.convertTo(dst, CV_8UC1);
}
bool SeekCam::open_cam()
{
int i;
if (!m_dev.open()) {
error("Error: open failed\n");
return false;
}
/* init retry loop: sometimes cam skips first 512 bytes of first frame (needed for dead pixel filter) */
for (i=0; i<3; i++) {
/* cam specific configuration */
if (!init_cam()) {
error("Error: init_cam failed\n");
return false;
}
if (!get_frame()) {
error("Error: first frame acquisition failed, retry attempt %d\n", i+1);
continue;
}
if (frame_id() != 4) {
error("Error: expected first frame to have id 4\n");
return false;
}
create_dead_pixel_list(m_raw_frame, m_dead_pixel_mask, m_dead_pixel_list);
if (!grab()) {
error("Error: first grab failed\n");
return false;
}
m_is_opened = true;
return true;
}
error("Error: max init retry count exceeded\n");
return false;
}
bool SeekCam::get_frame()
{
/* request new frame */
uint8_t* s = reinterpret_cast<uint8_t*>(&m_raw_data_size);
std::vector<uint8_t> data = { s[0], s[1], s[2], s[3] };
if (!m_dev.request_set(DeviceCommand::START_GET_IMAGE_TRANSFER, data))
return false;
/* store frame data */
if (!m_dev.fetch_frame(m_raw_data, m_raw_data_size))
return false;
return true;
}
void SeekCam::print_usb_data(std::vector<uint8_t>& data)
{
std::stringstream ss;
std::string out;
ss << "Response: ";
for (size_t i = 0; i < data.size(); i++) {
ss << " " << std::hex << data[i];
}
out = ss.str();
debug("%s\n", out.c_str());
}
void SeekCam::create_dead_pixel_list(cv::Mat frame, cv::Mat& dead_pixel_mask,
std::vector<cv::Point>& dead_pixel_list)
{
int x, y;
bool has_unlisted_pixels;
double max_value;
cv::Point hist_max_value;
cv::Mat tmp, hist;
int channels[] = {0};
int histSize[] = {0x4000};
float range[] = {0, 0x4000};
const float* ranges[] = { range };
/* calculate optimal threshold to determine what pixels are dead pixels */
frame.convertTo(tmp, CV_32FC1);
cv::minMaxLoc(tmp, nullptr, &max_value);
cv::calcHist(&tmp, 1, channels, cv::Mat(), hist, 1, histSize, ranges,
true, /* the histogram is uniform */
false);
hist.at<float>(0, 0) = 0; /* suppres 0th bin since its usual the highest,
but we don't want this one */
cv::minMaxLoc(hist, nullptr, nullptr, nullptr, &hist_max_value);
const double threshold = hist_max_value.y - (max_value - hist_max_value.y);
/* calculate the dead pixels mask */
cv::threshold(tmp, tmp, threshold, 255, cv::THRESH_BINARY);
tmp.convertTo(dead_pixel_mask, CV_8UC1);
/* build dead pixel list in a certain order to assure that every dead pixel value
* gets an estimated value in the filter stage */
dead_pixel_mask.convertTo(tmp, CV_16UC1);
dead_pixel_list.clear();
do {
has_unlisted_pixels = false;
for (y=0; y<tmp.rows; y++) {
for (x=0; x<tmp.cols; x++) {
const cv::Point p(x, y);
if (tmp.at<uint16_t>(y, x) != 0)
continue; /* not a dead pixel */
/* only add pixel to the list if we can estimate its value
* directly from its neighbor pixels */
if (calc_mean_value(tmp, p, 0) != 0) {
dead_pixel_list.push_back(p);
tmp.at<uint16_t>(y, x) = 255;
} else
has_unlisted_pixels = true;
}
}
} while (has_unlisted_pixels);
}
void SeekCam::apply_dead_pixel_filter(cv::Mat& src, cv::Mat& dst)
{
size_t i;
const size_t size = m_dead_pixel_list.size();
const uint32_t dead_pixel_marker = 0xffff;
dst.create(src.rows, src.cols, src.type()); /* ensure dst is properly allocated */
dst.setTo(dead_pixel_marker); /* value to identify dead pixels */
src.copyTo(dst, m_dead_pixel_mask); /* only copy non dead pixel values */
/* replace dead pixel values (0xffff) with the mean of its non dead surrounding pixels */
for (i=0; i<size; i++) {
cv::Point p = m_dead_pixel_list[i];
dst.at<uint16_t>(p) = calc_mean_value(dst, p, dead_pixel_marker);
}
}
uint16_t SeekCam::calc_mean_value(cv::Mat& img, cv::Point p, uint32_t dead_pixel_marker)
{
uint32_t value = 0, temp;
uint32_t div = 0;
const int right_border = img.cols - 1;
const int lower_border = img.rows - 1;
if (p.x != 0) {
/* if not on the left border of the image */
temp = img.at<uint16_t>(p.y, p.x-1);
if (temp != dead_pixel_marker) {
value += temp;
div++;
}
}
if (p.x != right_border) {
/* if not on the right border of the image */
temp = img.at<uint16_t>(p.y, p.x+1);
if (temp != dead_pixel_marker) {
value += temp;
div++;
}
}
if (p.y != 0) {
/* upper */
temp = img.at<uint16_t>(p.y-1, p.x);
if (temp != dead_pixel_marker) {
value += temp;
div++;
}
}
if (p.y != lower_border) {
/* lower */
temp = img.at<uint16_t>(p.y+1, p.x);
if (temp != dead_pixel_marker) {
value += temp;
div++;
}
}
if (div)
return (value / div);
return 0;
}
|
Increase amount of tries to grab a frame
|
Increase amount of tries to grab a frame
The default 10 values didn't work for my seek OEM starter kit.
|
C++
|
mit
|
maartenvds/libseek-thermal,maartenvds/libseek-thermal
|
eb511b1d3a598c39eeaf32c2cf5236c4c2c2ca8d
|
src/TestSet.cpp
|
src/TestSet.cpp
|
// -*- mode:C++; tab-width:4; c-basic-offset:4; indent-tabs-mode:nil -*-
/*
* Copyright (C) 2010 RobotCub Consortium, European Commission FP6 Project IST-004370
* Author: Alessandro Scalzo
* email: [email protected]
* website: www.robotcub.org
* Permission is granted to copy, distribute, and/or modify this program
* under the terms of the GNU General Public License, version 2 or any
* later version published by the Free Software Foundation.
*
* A copy of the license can be found at
* http://www.robotcub.org/icub/license/gpl.txt
*
* 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
*/
#include <yarp/os/Value.h>
#include "TestSet.h"
#include <stdio.h>
#include "Logger.h"
#include <yarp/os/Time.h>
bool TestSet::init(yarp::os::Searchable& configuration)
{
m_bSuccess=false;
m_numFailures=0;
if (configuration.check("user"))
{
m_User=configuration.find("user").asString();
}
if (configuration.check("comment"))
{
m_Comment=configuration.find("comment").asString();
}
if (configuration.check("outfile"))
{
m_Outfile=configuration.find("outfile").asString();
}
return true;
}
TestSet::~TestSet()
{
cleanup();
}
void TestSet::cleanup()
{
for (unsigned int t=0; t<m_apTest.size(); ++t)
{
if (m_apTest[t])
{
delete m_apTest[t];
m_apTest[t]=NULL;
}
}
m_apTest.clear();
}
int TestSet::run()
{
Logger::report("== Running tests ==\n");
m_bSuccess=true;
m_numFailures=0;
m_numTests=0;
m_timeStart=yarp::os::Time::now();
for (unsigned int i=0; i<m_apTest.size(); ++i)
{
//read test name and description
if (!m_apTest[i]->configure())
{
Logger::report("Failed to configure %s\n", m_apTest[i]->getName().c_str());
m_numSkipped++;
}
else
{
Logger::report("Running test: %s\n", m_apTest[i]->getName().c_str());
Logger::report("Description: %s\n", m_apTest[i]->getDescription().c_str());
if (!m_apTest[i]->run())
m_bSuccess=false;
m_numTests++;
}
}
m_timeEnd=yarp::os::Time::now();
m_numFailures=Logger::failures();
return m_numFailures;
}
void TestSet::printReport()
{
printf("===== Final report =====\n");
printf("Executed %d tests: \n", m_numTests);
printf("Execution time: %g seconds\n", m_timeEnd-m_timeStart);
printf("Failed tests: %d\n", m_numFailures);
printf("Skipped tests: %d\n", m_numSkipped);
if (m_numFailures!=0)
printf("THERE WERE FAILED TESTS, please check output carefully\n");
printf("=========================\n");
#if 0
XMLPrinter printer(m_Outfile);
char failuresStr[16];
sprintf(failuresStr,"%d",m_numFailures);
printer.xmlOpen("report");
printer.xml("user",m_User);
printer.xml("comment",m_Comment);
printer.xml("success",std::string(m_bSuccess?"YES":"NO"));
printer.xml("failures-total",std::string(failuresStr));
for (unsigned int i=0; i<m_apReport.size(); ++i)
{
if (m_apReport[i])
m_apReport[i]->printReport(printer);
}
printer.xmlClose();
#endif
}
|
// -*- mode:C++; tab-width:4; c-basic-offset:4; indent-tabs-mode:nil -*-
/*
* Copyright (C) 2010 RobotCub Consortium, European Commission FP6 Project IST-004370
* Author: Alessandro Scalzo
* email: [email protected]
* website: www.robotcub.org
* Permission is granted to copy, distribute, and/or modify this program
* under the terms of the GNU General Public License, version 2 or any
* later version published by the Free Software Foundation.
*
* A copy of the license can be found at
* http://www.robotcub.org/icub/license/gpl.txt
*
* 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
*/
#include <yarp/os/Value.h>
#include "TestSet.h"
#include <stdio.h>
#include "Logger.h"
#include <yarp/os/Time.h>
bool TestSet::init(yarp::os::Searchable& configuration)
{
m_bSuccess=false;
m_numFailures=0;
if (configuration.check("user"))
{
m_User=configuration.find("user").asString();
}
if (configuration.check("comment"))
{
m_Comment=configuration.find("comment").asString();
}
if (configuration.check("outfile"))
{
m_Outfile=configuration.find("outfile").asString();
}
return true;
}
TestSet::~TestSet()
{
cleanup();
}
void TestSet::cleanup()
{
for (unsigned int t=0; t<m_apTest.size(); ++t)
{
if (m_apTest[t])
{
delete m_apTest[t];
m_apTest[t]=NULL;
}
}
m_apTest.clear();
}
int TestSet::run()
{
Logger::report("== Running tests ==\n");
m_bSuccess=true;
m_numFailures=0;
m_numTests=0;
m_timeStart=yarp::os::Time::now();
for (unsigned int i=0; i<m_apTest.size(); ++i)
{
//read test name and description
if (!m_apTest[i]->configure())
{
Logger::report("Failed to configure %s\n", m_apTest[i]->getName().c_str());
m_numSkipped++;
}
else
{
Logger::report("Running test: %s\n", m_apTest[i]->getName().c_str());
Logger::report("Description: %s\n", m_apTest[i]->getDescription().c_str());
if (!m_apTest[i]->run())
m_bSuccess=false;
m_apTest[i]->release();
m_numTests++;
}
}
m_timeEnd=yarp::os::Time::now();
m_numFailures=Logger::failures();
return m_numFailures;
}
void TestSet::printReport()
{
printf("===== Final report =====\n");
printf("Executed %d tests: \n", m_numTests);
printf("Execution time: %g seconds\n", m_timeEnd-m_timeStart);
printf("Failed tests: %d\n", m_numFailures);
printf("Skipped tests: %d\n", m_numSkipped);
if (m_numFailures!=0)
printf("THERE WERE FAILED TESTS, please check output carefully\n");
printf("=========================\n");
#if 0
XMLPrinter printer(m_Outfile);
char failuresStr[16];
sprintf(failuresStr,"%d",m_numFailures);
printer.xmlOpen("report");
printer.xml("user",m_User);
printer.xml("comment",m_Comment);
printer.xml("success",std::string(m_bSuccess?"YES":"NO"));
printer.xml("failures-total",std::string(failuresStr));
for (unsigned int i=0; i<m_apReport.size(); ++i)
{
if (m_apReport[i])
m_apReport[i]->printReport(printer);
}
printer.xmlClose();
#endif
}
|
handle release
|
handle release
|
C++
|
lgpl-2.1
|
francesco-romano/robot-testing,robotology/robot-testing,robotology/robot-testing,robotology/robot-testing
|
7e8c588d0e4616dd0d61bc82eeebc45be876ff7a
|
src/backend.cpp
|
src/backend.cpp
|
/*
Copyright (C) 2007-2008 Tanguy Krotoff <[email protected]>
Copyright (C) 2008 Lukas Durfina <[email protected]>
Copyright (C) 2009 Fathi Boudra <[email protected]>
Copyright (C) 2009-2011 vlc-phonon AUTHORS <[email protected]>
Copyright (C) 2011-2013 Harald Sitter <[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, see <http://www.gnu.org/licenses/>.
*/
#include "backend.h"
#include <QtCore/QCoreApplication>
#include <QtCore/QLatin1Literal>
#include <QtCore/QtPlugin>
#include <QtCore/QVariant>
#include <QMessageBox>
#include <phonon/GlobalDescriptionContainer>
#include <phonon/pulsesupport.h>
#include <vlc/libvlc_version.h>
#include "audio/audiooutput.h"
#include "audio/audiodataoutput.h"
#include "audio/volumefadereffect.h"
#include "devicemanager.h"
#include "effect.h"
#include "effectmanager.h"
#include "mediaobject.h"
#include "sinknode.h"
#include "utils/debug.h"
#include "utils/libvlc.h"
#include "utils/mime.h"
#ifdef PHONON_EXPERIMENTAL
#include "video/videodataoutput.h"
#endif
#ifndef PHONON_NO_GRAPHICSVIEW
#include "video/videographicsobject.h"
#endif
#include "video/videowidget.h"
#if QT_VERSION < QT_VERSION_CHECK(5, 0, 0)
Q_EXPORT_PLUGIN2(phonon_vlc, Phonon::VLC::Backend)
#endif
namespace Phonon
{
namespace VLC
{
Backend *Backend::self;
Backend::Backend(QObject *parent, const QVariantList &)
: QObject(parent)
, m_deviceManager(0)
, m_effectManager(0)
{
self = this;
// Backend information properties
setProperty("identifier", QLatin1String("phonon_vlc"));
setProperty("backendName", QLatin1String("VLC"));
setProperty("backendComment", QLatin1String("VLC backend for Phonon"));
setProperty("backendVersion", QLatin1String(PHONON_VLC_VERSION));
setProperty("backendIcon", QLatin1String("vlc"));
setProperty("backendWebsite", QLatin1String("https://projects.kde.org/projects/kdesupport/phonon/phonon-vlc"));
// Check if we should enable debug output
int debugLevel = qgetenv("PHONON_BACKEND_DEBUG").toInt();
if (debugLevel > 3) // 3 is maximum
debugLevel = 3;
Debug::setMinimumDebugLevel((Debug::DebugLevel)((int) Debug::DEBUG_NONE - 1 - debugLevel));
// Actual libVLC initialisation
if (LibVLC::init()) {
debug() << "Using VLC version" << libvlc_get_version();
if (!qApp->applicationName().isEmpty()) {
QString userAgent =
QString("%0/%1 (Phonon/%2; Phonon-VLC/%3)").arg(
qApp->applicationName(),
qApp->applicationVersion(),
PHONON_VERSION_STR,
PHONON_VLC_VERSION);
libvlc_set_user_agent(libvlc,
qApp->applicationName().toUtf8().constData(),
userAgent.toUtf8().constData());
} else {
qWarning("WARNING: Setting the user agent for streaming and"
" PulseAudio requires you to set QCoreApplication::applicationName()");
}
#ifdef __GNUC__
#warning application name ought to be configurable by the consumer ... new api
#endif
#if (LIBVLC_VERSION_INT >= LIBVLC_VERSION(2, 1, 0, 0))
if (!qApp->applicationName().isEmpty() && !qApp->applicationVersion().isEmpty()) {
const QString id = QString("org.kde.phonon.%1").arg(qApp->applicationName());
const QString version = qApp->applicationVersion();
const QString icon = qApp->applicationName();
libvlc_set_app_id(libvlc,
id.toUtf8().constData(),
version.toUtf8().constData(),
icon.toUtf8().constData());
} else if (PulseSupport::getInstance()->isActive()) {
qWarning("WARNING: Setting PulseAudio context information requires you"
" to set QCoreApplication::applicationName() and"
" QCoreApplication::applicationVersion()");
}
#endif
} else {
#ifdef __GNUC__
#warning TODO - this error message is as useful as a knife at a gun fight
#endif
QMessageBox msg;
msg.setIcon(QMessageBox::Critical);
msg.setWindowTitle(tr("LibVLC Failed to Initialize"));
msg.setText(tr("Phonon's VLC backend failed to start."
"\n\n"
"This usually means a problem with your VLC installation,"
" please report a bug with your distributor."));
msg.setDetailedText(LibVLC::errorMessage());
msg.exec();
fatal() << "Phonon::VLC::vlcInit: Failed to initialize VLC";
}
// Initialise PulseAudio support
PulseSupport *pulse = PulseSupport::getInstance();
pulse->enable();
connect(pulse, SIGNAL(objectDescriptionChanged(ObjectDescriptionType)),
SIGNAL(objectDescriptionChanged(ObjectDescriptionType)));
m_deviceManager = new DeviceManager(this);
m_effectManager = new EffectManager(this);
}
Backend::~Backend()
{
if (LibVLC::self)
delete LibVLC::self;
if (GlobalAudioChannels::self)
delete GlobalAudioChannels::self;
if (GlobalSubtitles::self)
delete GlobalSubtitles::self;
PulseSupport::shutdown();
}
QObject *Backend::createObject(BackendInterface::Class c, QObject *parent, const QList<QVariant> &args)
{
if (!LibVLC::self || !libvlc)
return 0;
switch (c) {
case MediaObjectClass:
return new MediaObject(parent);
case AudioOutputClass:
return new AudioOutput(parent);
#if (LIBVLC_VERSION_INT < LIBVLC_VERSION(2, 0, 0, 0))
// Broken >= 2.0
// https://trac.videolan.org/vlc/ticket/6992
case AudioDataOutputClass:
return new AudioDataOutput(parent);
#endif
#ifdef PHONON_EXPERIMENTAL
case VideoDataOutputClass:
return new VideoDataOutput(parent);
#endif
#ifndef PHONON_NO_GRAPHICSVIEW
case VideoGraphicsObjectClass:
return new VideoGraphicsObject(parent);
#endif
case EffectClass:
return effectManager()->createEffect(args[0].toInt(), parent);
case VideoWidgetClass:
return new VideoWidget(qobject_cast<QWidget *>(parent));
// case VolumeFaderEffectClass:
#ifdef __GNUC__
#warning VFE crashes and has volume bugs ... deactivated
// return new VolumeFaderEffect(parent);
#endif
}
warning() << "Backend class" << c << "is not supported by Phonon VLC :(";
return 0;
}
QStringList Backend::availableMimeTypes() const
{
if (m_supportedMimeTypes.isEmpty())
const_cast<Backend *>(this)->m_supportedMimeTypes = mimeTypeList();
return m_supportedMimeTypes;
}
QList<int> Backend::objectDescriptionIndexes(ObjectDescriptionType type) const
{
QList<int> list;
switch (type) {
case Phonon::AudioChannelType: {
list << GlobalAudioChannels::instance()->globalIndexes();
}
break;
case Phonon::AudioOutputDeviceType:
case Phonon::AudioCaptureDeviceType:
case Phonon::VideoCaptureDeviceType: {
return deviceManager()->deviceIds(type);
}
break;
case Phonon::EffectType: {
QList<EffectInfo> effectList = effectManager()->effects();
for (int eff = 0; eff < effectList.size(); ++eff) {
list.append(eff);
}
}
break;
case Phonon::SubtitleType: {
list << GlobalSubtitles::instance()->globalIndexes();
}
break;
}
return list;
}
QHash<QByteArray, QVariant> Backend::objectDescriptionProperties(ObjectDescriptionType type, int index) const
{
QHash<QByteArray, QVariant> ret;
switch (type) {
case Phonon::AudioChannelType: {
const AudioChannelDescription description = GlobalAudioChannels::instance()->fromIndex(index);
ret.insert("name", description.name());
ret.insert("description", description.description());
}
break;
case Phonon::AudioOutputDeviceType:
case Phonon::AudioCaptureDeviceType:
case Phonon::VideoCaptureDeviceType: {
// Index should be unique, even for different categories
return deviceManager()->deviceProperties(index);
}
break;
case Phonon::EffectType: {
const QList<EffectInfo> effectList = effectManager()->effects();
if (index >= 0 && index <= effectList.size()) {
const EffectInfo &effect = effectList.at(index);
ret.insert("name", effect.name());
ret.insert("description", effect.description());
ret.insert("author", effect.author());
} else {
Q_ASSERT(1); // Since we use list position as ID, this should not happen
}
}
break;
case Phonon::SubtitleType: {
const SubtitleDescription description = GlobalSubtitles::instance()->fromIndex(index);
ret.insert("name", description.name());
ret.insert("description", description.description());
ret.insert("type", description.property("type"));
}
break;
}
return ret;
}
bool Backend::startConnectionChange(QSet<QObject *> objects)
{
//FIXME
foreach(QObject * object, objects) {
debug() << "Object:" << object->metaObject()->className();
}
// There is nothing we can do but hope the connection changes will not take too long
// so that buffers would underrun
// But we should be pretty safe the way xine works by not doing anything here.
return true;
}
bool Backend::connectNodes(QObject *source, QObject *sink)
{
debug() << "Backend connected" << source->metaObject()->className() << "to" << sink->metaObject()->className();
SinkNode *sinkNode = dynamic_cast<SinkNode *>(sink);
if (sinkNode) {
MediaObject *mediaObject = qobject_cast<MediaObject *>(source);
if (mediaObject) {
// Connect the SinkNode to a MediaObject
sinkNode->connectToMediaObject(mediaObject);
return true;
}
VolumeFaderEffect *effect = qobject_cast<VolumeFaderEffect *>(source);
if (effect) {
sinkNode->connectToMediaObject(effect->mediaObject());
return true;
}
}
warning() << "Linking" << source->metaObject()->className() << "to" << sink->metaObject()->className() << "failed";
return false;
}
bool Backend::disconnectNodes(QObject *source, QObject *sink)
{
SinkNode *sinkNode = dynamic_cast<SinkNode *>(sink);
if (sinkNode) {
MediaObject *const mediaObject = qobject_cast<MediaObject *>(source);
if (mediaObject) {
// Disconnect the SinkNode from a MediaObject
sinkNode->disconnectFromMediaObject(mediaObject);
return true;
}
VolumeFaderEffect *const effect = qobject_cast<VolumeFaderEffect *>(source);
if (effect) {
sinkNode->disconnectFromMediaObject(effect->mediaObject());
return true;
}
}
return false;
}
bool Backend::endConnectionChange(QSet<QObject *> objects)
{
foreach(QObject *object, objects) {
debug() << "Object:" << object->metaObject()->className();
}
return true;
}
DeviceManager *Backend::deviceManager() const
{
return m_deviceManager;
}
EffectManager *Backend::effectManager() const
{
return m_effectManager;
}
} // namespace VLC
} // namespace Phonon
|
/*
Copyright (C) 2007-2008 Tanguy Krotoff <[email protected]>
Copyright (C) 2008 Lukas Durfina <[email protected]>
Copyright (C) 2009 Fathi Boudra <[email protected]>
Copyright (C) 2009-2011 vlc-phonon AUTHORS <[email protected]>
Copyright (C) 2011-2013 Harald Sitter <[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, see <http://www.gnu.org/licenses/>.
*/
#include "backend.h"
#include <QtCore/QCoreApplication>
#include <QtCore/QLatin1Literal>
#include <QtCore/QtPlugin>
#include <QtCore/QVariant>
#include <QMessageBox>
#include <phonon/GlobalDescriptionContainer>
#include <phonon/pulsesupport.h>
#include <vlc/libvlc_version.h>
#include "audio/audiooutput.h"
#include "audio/audiodataoutput.h"
#include "audio/volumefadereffect.h"
#include "devicemanager.h"
#include "effect.h"
#include "effectmanager.h"
#include "mediaobject.h"
#include "sinknode.h"
#include "utils/debug.h"
#include "utils/libvlc.h"
#include "utils/mime.h"
#ifdef PHONON_EXPERIMENTAL
#include "video/videodataoutput.h"
#endif
#ifndef PHONON_NO_GRAPHICSVIEW
#include "video/videographicsobject.h"
#endif
#include "video/videowidget.h"
#if QT_VERSION < QT_VERSION_CHECK(5, 0, 0)
Q_EXPORT_PLUGIN2(phonon_vlc, Phonon::VLC::Backend)
#endif
namespace Phonon
{
namespace VLC
{
Backend *Backend::self;
Backend::Backend(QObject *parent, const QVariantList &)
: QObject(parent)
, m_deviceManager(0)
, m_effectManager(0)
{
self = this;
// Backend information properties
setProperty("identifier", QLatin1String("phonon_vlc"));
setProperty("backendName", QLatin1String("VLC"));
setProperty("backendComment", QLatin1String("VLC backend for Phonon"));
setProperty("backendVersion", QLatin1String(PHONON_VLC_VERSION));
setProperty("backendIcon", QLatin1String("vlc"));
setProperty("backendWebsite", QLatin1String("https://projects.kde.org/projects/kdesupport/phonon/phonon-vlc"));
// Check if we should enable debug output
int debugLevel = qgetenv("PHONON_BACKEND_DEBUG").toInt();
if (debugLevel > 3) // 3 is maximum
debugLevel = 3;
Debug::setMinimumDebugLevel((Debug::DebugLevel)((int) Debug::DEBUG_NONE - 1 - debugLevel));
debug() << "Constructing Phonon-VLC Version" << PHONON_VLC_VERSION;
// Actual libVLC initialisation
if (LibVLC::init()) {
debug() << "Using VLC version" << libvlc_get_version();
if (!qApp->applicationName().isEmpty()) {
QString userAgent =
QString("%0/%1 (Phonon/%2; Phonon-VLC/%3)").arg(
qApp->applicationName(),
qApp->applicationVersion(),
PHONON_VERSION_STR,
PHONON_VLC_VERSION);
libvlc_set_user_agent(libvlc,
qApp->applicationName().toUtf8().constData(),
userAgent.toUtf8().constData());
} else {
qWarning("WARNING: Setting the user agent for streaming and"
" PulseAudio requires you to set QCoreApplication::applicationName()");
}
#ifdef __GNUC__
#warning application name ought to be configurable by the consumer ... new api
#endif
#if (LIBVLC_VERSION_INT >= LIBVLC_VERSION(2, 1, 0, 0))
if (!qApp->applicationName().isEmpty() && !qApp->applicationVersion().isEmpty()) {
const QString id = QString("org.kde.phonon.%1").arg(qApp->applicationName());
const QString version = qApp->applicationVersion();
const QString icon = qApp->applicationName();
libvlc_set_app_id(libvlc,
id.toUtf8().constData(),
version.toUtf8().constData(),
icon.toUtf8().constData());
} else if (PulseSupport::getInstance()->isActive()) {
qWarning("WARNING: Setting PulseAudio context information requires you"
" to set QCoreApplication::applicationName() and"
" QCoreApplication::applicationVersion()");
}
#endif
} else {
#ifdef __GNUC__
#warning TODO - this error message is as useful as a knife at a gun fight
#endif
QMessageBox msg;
msg.setIcon(QMessageBox::Critical);
msg.setWindowTitle(tr("LibVLC Failed to Initialize"));
msg.setText(tr("Phonon's VLC backend failed to start."
"\n\n"
"This usually means a problem with your VLC installation,"
" please report a bug with your distributor."));
msg.setDetailedText(LibVLC::errorMessage());
msg.exec();
fatal() << "Phonon::VLC::vlcInit: Failed to initialize VLC";
}
// Initialise PulseAudio support
PulseSupport *pulse = PulseSupport::getInstance();
pulse->enable();
connect(pulse, SIGNAL(objectDescriptionChanged(ObjectDescriptionType)),
SIGNAL(objectDescriptionChanged(ObjectDescriptionType)));
m_deviceManager = new DeviceManager(this);
m_effectManager = new EffectManager(this);
}
Backend::~Backend()
{
if (LibVLC::self)
delete LibVLC::self;
if (GlobalAudioChannels::self)
delete GlobalAudioChannels::self;
if (GlobalSubtitles::self)
delete GlobalSubtitles::self;
PulseSupport::shutdown();
}
QObject *Backend::createObject(BackendInterface::Class c, QObject *parent, const QList<QVariant> &args)
{
if (!LibVLC::self || !libvlc)
return 0;
switch (c) {
case MediaObjectClass:
return new MediaObject(parent);
case AudioOutputClass:
return new AudioOutput(parent);
#if (LIBVLC_VERSION_INT < LIBVLC_VERSION(2, 0, 0, 0))
// Broken >= 2.0
// https://trac.videolan.org/vlc/ticket/6992
case AudioDataOutputClass:
return new AudioDataOutput(parent);
#endif
#ifdef PHONON_EXPERIMENTAL
case VideoDataOutputClass:
return new VideoDataOutput(parent);
#endif
#ifndef PHONON_NO_GRAPHICSVIEW
case VideoGraphicsObjectClass:
return new VideoGraphicsObject(parent);
#endif
case EffectClass:
return effectManager()->createEffect(args[0].toInt(), parent);
case VideoWidgetClass:
return new VideoWidget(qobject_cast<QWidget *>(parent));
// case VolumeFaderEffectClass:
#ifdef __GNUC__
#warning VFE crashes and has volume bugs ... deactivated
// return new VolumeFaderEffect(parent);
#endif
}
warning() << "Backend class" << c << "is not supported by Phonon VLC :(";
return 0;
}
QStringList Backend::availableMimeTypes() const
{
if (m_supportedMimeTypes.isEmpty())
const_cast<Backend *>(this)->m_supportedMimeTypes = mimeTypeList();
return m_supportedMimeTypes;
}
QList<int> Backend::objectDescriptionIndexes(ObjectDescriptionType type) const
{
QList<int> list;
switch (type) {
case Phonon::AudioChannelType: {
list << GlobalAudioChannels::instance()->globalIndexes();
}
break;
case Phonon::AudioOutputDeviceType:
case Phonon::AudioCaptureDeviceType:
case Phonon::VideoCaptureDeviceType: {
return deviceManager()->deviceIds(type);
}
break;
case Phonon::EffectType: {
QList<EffectInfo> effectList = effectManager()->effects();
for (int eff = 0; eff < effectList.size(); ++eff) {
list.append(eff);
}
}
break;
case Phonon::SubtitleType: {
list << GlobalSubtitles::instance()->globalIndexes();
}
break;
}
return list;
}
QHash<QByteArray, QVariant> Backend::objectDescriptionProperties(ObjectDescriptionType type, int index) const
{
QHash<QByteArray, QVariant> ret;
switch (type) {
case Phonon::AudioChannelType: {
const AudioChannelDescription description = GlobalAudioChannels::instance()->fromIndex(index);
ret.insert("name", description.name());
ret.insert("description", description.description());
}
break;
case Phonon::AudioOutputDeviceType:
case Phonon::AudioCaptureDeviceType:
case Phonon::VideoCaptureDeviceType: {
// Index should be unique, even for different categories
return deviceManager()->deviceProperties(index);
}
break;
case Phonon::EffectType: {
const QList<EffectInfo> effectList = effectManager()->effects();
if (index >= 0 && index <= effectList.size()) {
const EffectInfo &effect = effectList.at(index);
ret.insert("name", effect.name());
ret.insert("description", effect.description());
ret.insert("author", effect.author());
} else {
Q_ASSERT(1); // Since we use list position as ID, this should not happen
}
}
break;
case Phonon::SubtitleType: {
const SubtitleDescription description = GlobalSubtitles::instance()->fromIndex(index);
ret.insert("name", description.name());
ret.insert("description", description.description());
ret.insert("type", description.property("type"));
}
break;
}
return ret;
}
bool Backend::startConnectionChange(QSet<QObject *> objects)
{
//FIXME
foreach(QObject * object, objects) {
debug() << "Object:" << object->metaObject()->className();
}
// There is nothing we can do but hope the connection changes will not take too long
// so that buffers would underrun
// But we should be pretty safe the way xine works by not doing anything here.
return true;
}
bool Backend::connectNodes(QObject *source, QObject *sink)
{
debug() << "Backend connected" << source->metaObject()->className() << "to" << sink->metaObject()->className();
SinkNode *sinkNode = dynamic_cast<SinkNode *>(sink);
if (sinkNode) {
MediaObject *mediaObject = qobject_cast<MediaObject *>(source);
if (mediaObject) {
// Connect the SinkNode to a MediaObject
sinkNode->connectToMediaObject(mediaObject);
return true;
}
VolumeFaderEffect *effect = qobject_cast<VolumeFaderEffect *>(source);
if (effect) {
sinkNode->connectToMediaObject(effect->mediaObject());
return true;
}
}
warning() << "Linking" << source->metaObject()->className() << "to" << sink->metaObject()->className() << "failed";
return false;
}
bool Backend::disconnectNodes(QObject *source, QObject *sink)
{
SinkNode *sinkNode = dynamic_cast<SinkNode *>(sink);
if (sinkNode) {
MediaObject *const mediaObject = qobject_cast<MediaObject *>(source);
if (mediaObject) {
// Disconnect the SinkNode from a MediaObject
sinkNode->disconnectFromMediaObject(mediaObject);
return true;
}
VolumeFaderEffect *const effect = qobject_cast<VolumeFaderEffect *>(source);
if (effect) {
sinkNode->disconnectFromMediaObject(effect->mediaObject());
return true;
}
}
return false;
}
bool Backend::endConnectionChange(QSet<QObject *> objects)
{
foreach(QObject *object, objects) {
debug() << "Object:" << object->metaObject()->className();
}
return true;
}
DeviceManager *Backend::deviceManager() const
{
return m_deviceManager;
}
EffectManager *Backend::effectManager() const
{
return m_effectManager;
}
} // namespace VLC
} // namespace Phonon
|
Debug version of backend via ::Backend
|
Debug version of backend via ::Backend
libphonon has no debugging means when constructed through the KDE platform
plugin.
|
C++
|
lgpl-2.1
|
KDE/phonon-vlc,BinChengfei/phonon-vlc,BinChengfei/phonon-vlc,BinChengfei/phonon-vlc,KDE/phonon-vlc,KDE/phonon-vlc
|
00c505b58f0794a45c946cdbea093f130f07e8e6
|
src/car/ecu.cpp
|
src/car/ecu.cpp
|
/**
*******************************************************************************
* *
* ECU: iRacing MP4-30 Performance Analysis Project *
* *
*******************************************************************************
* Copyright 2016 Adrian Garcia Cruz. All rights reserved. *
* Released under the BSD license. see LICENSE for more information *
* *
* Author: Adrian Garcia Cruz <[email protected]> *
*******************************************************************************
*/
#include <stdlib.h>
#include <fcntl.h>
#include <Windows.h>
#include <json.hpp>
#include <Shlwapi.h>
#include <Strsafe.h>
#include <Shlobj.h>
#include <io.h>
#include <base/debug.h>
#include <car/ecu.h>
#include <car/ers.h>
#include <WinUser.h>
#include <server/websocket.h>
using json = nlohmann::json;
#define TIMEOUT 18
// TODO: Send keys only when iRacing is the active window
void input_send(float steps, int key)
{
INPUT ip = {0};
for (int i = 0; i < steps; i++) {
ip.type = INPUT_KEYBOARD;
ip.ki.wVk = key;
SendInput(1, &ip, sizeof(INPUT));
ip.ki.wVk = VK_MENU;
SendInput(1, &ip, sizeof(INPUT));
Sleep(30);
}
ip.ki.wVk = VK_MENU;
ip.ki.dwFlags = KEYEVENTF_KEYUP;
SendInput(1, &ip, sizeof(INPUT));
ip.ki.wVk = key;
SendInput(1, &ip, sizeof(INPUT));
}
int var_offset(irsdk_varHeader *varHeaders, char *name, int count)
{
for (int i = 0; i <= count; i++) {
if (strcmp(name, varHeaders[i].name) == 0)
return varHeaders[i].offset;
}
}
void del_telemetry(ECU *settings)
{
for (int i = 0; i < settings->handles.size(); i++) {
HANDLE h = settings->handles.at(i);
std::wstring file_path = settings->file_paths.at(i);
CloseHandle(h);
DeleteFile(file_path.c_str());
settings->handles.pop_back();
settings->file_paths.pop_back();
}
}
ibt *last_linebuf(intptr_t fd, ECU *settings)
{
FILE *file = 0;
if (fd == -1)
LOGF(FATAL, "Invalid file descriptor");
file = _fdopen(fd, "r");
int ret = 0;
int len = 0;
ibt *telemetry = (ibt*)malloc(sizeof(ibt));
ret = fread(&telemetry->header, 1, sizeof(irsdk_header), file);
if (ret == 0) {
LOGF(WARNING, "ret returned 0, fd is :%d", fd);
}
telemetry->var_headers =
(irsdk_varHeader*)malloc(telemetry->header.numVars * sizeof(irsdk_varHeader));
telemetry->var_buf = (char*)malloc(telemetry->header.bufLen);
fseek(file, telemetry->header.varHeaderOffset, SEEK_SET);
len = sizeof(irsdk_varHeader)*telemetry->header.numVars;
// TODO: Use the last line buffer for best accurate info.
ret = fread(telemetry->var_headers, 1, len, file);
fseek(file, telemetry->header.varBuf[0].bufOffset, SEEK_SET);
len = telemetry->header.bufLen;
ret = fread(telemetry->var_buf, 1, len, file);
x del_telemetry(settings);
return telemetry;
}
intptr_t loop_files(HANDLE search,
WIN32_FIND_DATA files,
wchar_t *directory,
ECU *settings)
{
wchar_t extension[4];
wchar_t file_path[MAX_PATH_UNICODE];
do
{
// Get file extension
int len = wcsnlen(files.cFileName, MAX_PATH);
wcsncpy(extension, files.cFileName + (len - 3), 4);
if (lstrcmp(extension, L"ibt") == 0) {
StringCchCopy(file_path, MAX_PATH_UNICODE, directory);
StringCchCat(file_path, MAX_PATH_UNICODE, files.cFileName);
HANDLE file = CreateFile(file_path, GENERIC_READ | GENERIC_WRITE,
FILE_SHARE_READ, NULL,
OPEN_EXISTING,
FILE_FLAG_RANDOM_ACCESS, NULL);
// If file is open in another processs
if (file == INVALID_HANDLE_VALUE && GetLastError() == 32) {
LOGF(WARNING, "Unable to get file handle for %S", file_path);
LOGF(WARNING, "Probably being used by iRacing. restarting telemetry..");
irsdk_broadcastMsg(irsdk_BroadcastTelemCommand,
irsdk_TelemCommand_Stop, 0, 0);
// Give iRacing time to release the file handle
Sleep(200);
irsdk_broadcastMsg(irsdk_BroadcastTelemCommand,
irsdk_TelemCommand_Start, 0, 0);
// iRacing starts writing to disk 2.5 seconds after
// telemetry is turned on.
Sleep(2500);
HANDLE file = CreateFile(file_path, GENERIC_READ, NULL, NULL,
OPEN_EXISTING, FILE_FLAG_RANDOM_ACCESS, NULL);
if (file == INVALID_HANDLE_VALUE) {
LOGF(WARNING,
"iRacing still has a open handle to the old telemetry file! GLE: %d",
GetLastError());
return -1;
}
int fd = _open_osfhandle((intptr_t)file, _O_APPEND | _O_RDONLY);
if (fd == -1) {
CloseHandle(file);
LOGF(WARNING, "Unable to obtain file descriptor for %s", files.cFileName);
return -1;
}
settings->handles.push_back(file);
settings->file_paths.push_back(std::wstring(file_path));
return fd;
}
CloseHandle(file);
}
}
while (FindNextFile(search, &files) != 0);
// If iRacing is not writing to a file
return 0;
}
intptr_t find_latest_file(wchar_t *directory, ECU *settings)
{
WIN32_FIND_DATA files;
intptr_t fd;
HANDLE search;
wchar_t telemetry_path[MAX_PATH_UNICODE];
wchar_t file_path[MAX_PATH_UNICODE];
wchar_t extension[4];
// TODO: add the wildcard to the directory during process startup
StringCchCopy(telemetry_path, MAX_PATH_UNICODE, directory);
StringCchCat(telemetry_path, MAX_PATH_UNICODE, L"*");
if (!PathFileExists(directory))
// Path length limit is 248 characters inc. null terminator
SHCreateDirectory(NULL, directory);
search = FindFirstFile(telemetry_path, &files);
if (search == INVALID_HANDLE_VALUE)
LOGF(FATAL, "FindFirstFile returned INVALID HANDLE. Possibly empty telemetry folder");
fd = loop_files(search, files, directory, settings);
// If disk telemetry is not running
if (fd == 0) {
irsdk_broadcastMsg(irsdk_BroadcastTelemCommand, irsdk_TelemCommand_Start, 0, 0);
int timeout = 250;
// Give iRacing time to write to file
Sleep(timeout);
search = FindFirstFile(telemetry_path, &files);
fd = loop_files(search, files, directory, settings);
if (fd == 0)
LOGF(FATAL, "iRacing did not write to new telemetry file. timeout was %d", timeout);
}
return fd;
}
int calibrate_ecu(ECU *settings)
{
// Check if telemetry is writing to a file.
// If telemetry is off when the car hits the track
// then turn it on and off quickly. Then get all your
// data then delete the telemetry file and turn on telemetry
// for normal use. TODO: measure the time gap of turning
// telemetry on and off.
// Find the newest file and check if it's being used by iRacing
LOGF(WARNING, "Car on track. Calibrating ECU");
intptr_t newest = find_latest_file(settings->config->telemetry_path, settings);
if (newest != -1)
settings->telemetry = last_linebuf(newest, settings);
else
LOGF(FATAL, "File descriptor error. exiting");
return 1;
}
// TODO: Change settings to data
void get_var(ECU *settings, char *variable, char *destination)
{
int offset = irsdk_varNameToOffset(variable);
const irsdk_varHeader *rec = irsdk_getVarHeaderEntry(offset);
*destination = *(char*)(settings->data + offset);
}
void get_var(ECU *settings, char *variable, int *destination)
{
int offset = irsdk_varNameToOffset(variable);
const irsdk_varHeader *rec = irsdk_getVarHeaderEntry(offset);
*destination = *(int*)(settings->data + offset);
}
void get_var(ECU *settings, char *variable, float *destination)
{
int offset = irsdk_varNameToOffset(variable);
const irsdk_varHeader *rec = irsdk_getVarHeaderEntry(offset);
*destination = *(float*)(settings->data + offset);
}
void get_var(ECU *settings, char *variable, double *destination)
{
int offset = irsdk_varNameToOffset(variable);
const irsdk_varHeader *rec = irsdk_getVarHeaderEntry(offset);
*destination = *(double*)(settings->data + offset);
}
int on_track(char *data, const irsdk_header *header)
{
int IsOnTrack = irsdk_varNameToOffset("IsOnTrack");
bool ret = *(bool *)(data + IsOnTrack);
return ret;
}
void initData(const irsdk_header *header, char *data, int num_data)
{
if (data)
free(data);
num_data = header->bufLen;
data = (char*)malloc(num_data);
}
void shutdown_ecu(ECU *settings)
{
LOGF(WARNING, "Shutting down ECU");
// TODO: Readjust ERS deployment?
if (settings->telemetry->var_headers != NULL)
free(settings->telemetry->var_headers);
if (settings->telemetry->var_buf != NULL)
free(settings->telemetry->var_buf);
if (settings->telemetry != NULL)
free(settings->telemetry);
if (settings != NULL)
free(settings);
}
unsigned __stdcall start_ecu(void *p)
{
ECU *settings = (ECU*)p;
ws_event *events = settings->events;
bool init = false;
int missed = 0;
// int ret = WaitForSingleObject(events->connection_event, INFINITE);
// Use irsdk_connected() ?
while (!init) {
if (irsdkClient::instance().waitForData(1000)) {
// Check if we're in replay mode by testing
// if the physics is running on some channels
LOGF(DEBUG, "iRacing is online");
json j2 = {
{"status", 1}
};
send_json(j2.dump());
init = true;
}
}
// Test irsdk connection failures
int tries = 500;
while (tries > 0) {
if (irsdkClient::instance().waitForData(TIMEOUT)) {}
else
missed++;
tries--;
}
LOGF(DEBUG, "irsdk: timeout is %d ms", TIMEOUT);
LOGF(DEBUG, "irsdk: %d missed connections", missed);
int num_data = 0;
const irsdk_header *header = irsdk_getHeader();
while (true) {
int ret = WaitForSingleObject(events->exit_event, NULL);
if (ret == WAIT_OBJECT_0) {
shutdown_ecu(settings);
if (settings->data)
free(settings->data);
return 1;
}
if (header) {
if (!settings->data || num_data != header->bufLen) {
if (settings->data)
free(settings->data);
num_data = header->bufLen;
settings->data = (char*)malloc(num_data);
irsdk_waitForDataReady(TIMEOUT, settings->data);
}
else {
if (!irsdk_isConnected()) {
LOGF(DEBUG, "iRacing just went offline!");
settings->calibrated = false;
json offline = {
{"status", 0}
};
if (settings->data)
free(settings->data);
send_json(offline.dump());
shutdown_ecu(settings);
break;
}
irsdk_waitForDataReady(TIMEOUT, settings->data);
// Copy all vars to a buffer?
if (on_track(settings->data, header)) {
if (!settings->calibrated) {
settings->hWnd = GetForegroundWindow();
calibrate_ecu(settings);
settings->calibrated = true;
}
ers(settings);
}
else {
if (settings->calibrated)
LOGF(WARNING, "Car exited the track");
settings->calibrated = false;
}
}
}
}
return 1;
}
|
/**
*******************************************************************************
* *
* ECU: iRacing MP4-30 Performance Analysis Project *
* *
*******************************************************************************
* Copyright 2016 Adrian Garcia Cruz. All rights reserved. *
* Released under the BSD license. see LICENSE for more information *
* *
* Author: Adrian Garcia Cruz <[email protected]> *
*******************************************************************************
*/
#include <stdlib.h>
#include <fcntl.h>
#include <Windows.h>
#include <json.hpp>
#include <Shlwapi.h>
#include <Strsafe.h>
#include <Shlobj.h>
#include <io.h>
#include <base/debug.h>
#include <car/ecu.h>
#include <car/ers.h>
#include <WinUser.h>
#include <server/websocket.h>
using json = nlohmann::json;
#define TIMEOUT 18
// TODO: Send keys only when iRacing is the active window
void input_send(float steps, int key)
{
INPUT ip = {0};
for (int i = 0; i < steps; i++) {
ip.type = INPUT_KEYBOARD;
ip.ki.wVk = key;
SendInput(1, &ip, sizeof(INPUT));
ip.ki.wVk = VK_MENU;
SendInput(1, &ip, sizeof(INPUT));
Sleep(30);
}
ip.ki.wVk = VK_MENU;
ip.ki.dwFlags = KEYEVENTF_KEYUP;
SendInput(1, &ip, sizeof(INPUT));
ip.ki.wVk = key;
SendInput(1, &ip, sizeof(INPUT));
}
int var_offset(irsdk_varHeader *varHeaders, char *name, int count)
{
for (int i = 0; i <= count; i++) {
if (strcmp(name, varHeaders[i].name) == 0)
return varHeaders[i].offset;
}
}
void del_telemetry(ECU *settings)
{
for (int i = 0; i < settings->handles.size(); i++) {
HANDLE h = settings->handles.at(i);
std::wstring file_path = settings->file_paths.at(i);
CloseHandle(h);
DeleteFile(file_path.c_str());
settings->handles.pop_back();
settings->file_paths.pop_back();
}
}
ibt *last_linebuf(intptr_t fd, ECU *settings)
{
FILE *file = 0;
if (fd == -1)
LOGF(FATAL, "Invalid file descriptor");
file = _fdopen(fd, "r");
int ret = 0;
int len = 0;
ibt *telemetry = (ibt*)malloc(sizeof(ibt));
ret = fread(&telemetry->header, 1, sizeof(irsdk_header), file);
if (ret == 0) {
LOGF(WARNING, "ret returned 0, fd is :%d", fd);
}
telemetry->var_headers =
(irsdk_varHeader*)malloc(telemetry->header.numVars * sizeof(irsdk_varHeader));
telemetry->var_buf = (char*)malloc(telemetry->header.bufLen);
fseek(file, telemetry->header.varHeaderOffset, SEEK_SET);
len = sizeof(irsdk_varHeader)*telemetry->header.numVars;
// TODO: Use the last line buffer for best accurate info.
ret = fread(telemetry->var_headers, 1, len, file);
fseek(file, telemetry->header.varBuf[0].bufOffset, SEEK_SET);
len = telemetry->header.bufLen;
ret = fread(telemetry->var_buf, 1, len, file);
del_telemetry(settings);
return telemetry;
}
intptr_t loop_files(HANDLE search,
WIN32_FIND_DATA files,
wchar_t *directory,
ECU *settings)
{
wchar_t extension[4];
wchar_t file_path[MAX_PATH_UNICODE];
do
{
// Get file extension
int len = wcsnlen(files.cFileName, MAX_PATH);
wcsncpy(extension, files.cFileName + (len - 3), 4);
if (lstrcmp(extension, L"ibt") == 0) {
StringCchCopy(file_path, MAX_PATH_UNICODE, directory);
StringCchCat(file_path, MAX_PATH_UNICODE, files.cFileName);
HANDLE file = CreateFile(file_path, GENERIC_READ | GENERIC_WRITE,
FILE_SHARE_READ, NULL,
OPEN_EXISTING,
FILE_FLAG_RANDOM_ACCESS, NULL);
// If file is open in another processs
if (file == INVALID_HANDLE_VALUE && GetLastError() == 32) {
LOGF(WARNING, "Unable to get file handle for %S", file_path);
LOGF(WARNING, "Probably being used by iRacing. restarting telemetry..");
irsdk_broadcastMsg(irsdk_BroadcastTelemCommand,
irsdk_TelemCommand_Stop, 0, 0);
// Give iRacing time to release the file handle
Sleep(200);
irsdk_broadcastMsg(irsdk_BroadcastTelemCommand,
irsdk_TelemCommand_Start, 0, 0);
// iRacing starts writing to disk 2.5 seconds after
// telemetry is turned on.
Sleep(2500);
HANDLE file = CreateFile(file_path, GENERIC_READ, NULL, NULL,
OPEN_EXISTING, FILE_FLAG_RANDOM_ACCESS, NULL);
if (file == INVALID_HANDLE_VALUE) {
LOGF(WARNING,
"iRacing still has a open handle to the old telemetry file! GLE: %d",
GetLastError());
return -1;
}
int fd = _open_osfhandle((intptr_t)file, _O_APPEND | _O_RDONLY);
if (fd == -1) {
CloseHandle(file);
LOGF(WARNING, "Unable to obtain file descriptor for %s", files.cFileName);
return -1;
}
settings->handles.push_back(file);
settings->file_paths.push_back(std::wstring(file_path));
return fd;
}
CloseHandle(file);
}
}
while (FindNextFile(search, &files) != 0);
// If iRacing is not writing to a file
return 0;
}
intptr_t find_latest_file(wchar_t *directory, ECU *settings)
{
WIN32_FIND_DATA files;
intptr_t fd;
HANDLE search;
wchar_t telemetry_path[MAX_PATH_UNICODE];
wchar_t file_path[MAX_PATH_UNICODE];
wchar_t extension[4];
// TODO: add the wildcard to the directory during process startup
StringCchCopy(telemetry_path, MAX_PATH_UNICODE, directory);
StringCchCat(telemetry_path, MAX_PATH_UNICODE, L"*");
if (!PathFileExists(directory))
// Path length limit is 248 characters inc. null terminator
SHCreateDirectory(NULL, directory);
search = FindFirstFile(telemetry_path, &files);
if (search == INVALID_HANDLE_VALUE)
LOGF(FATAL, "FindFirstFile returned INVALID HANDLE. Possibly empty telemetry folder");
fd = loop_files(search, files, directory, settings);
// If disk telemetry is not running
if (fd == 0) {
irsdk_broadcastMsg(irsdk_BroadcastTelemCommand, irsdk_TelemCommand_Start, 0, 0);
int timeout = 250;
// Give iRacing time to write to file
Sleep(timeout);
search = FindFirstFile(telemetry_path, &files);
fd = loop_files(search, files, directory, settings);
if (fd == 0)
LOGF(FATAL, "iRacing did not write to new telemetry file. timeout was %d", timeout);
}
return fd;
}
int calibrate_ecu(ECU *settings)
{
// Check if telemetry is writing to a file.
// If telemetry is off when the car hits the track
// then turn it on and off quickly. Then get all your
// data then delete the telemetry file and turn on telemetry
// for normal use. TODO: measure the time gap of turning
// telemetry on and off.
// Find the newest file and check if it's being used by iRacing
LOGF(WARNING, "Car on track. Calibrating ECU");
intptr_t newest = find_latest_file(settings->config->telemetry_path, settings);
if (newest != -1)
settings->telemetry = last_linebuf(newest, settings);
else
LOGF(FATAL, "File descriptor error. exiting");
return 1;
}
// TODO: Change settings to data
void get_var(ECU *settings, char *variable, char *destination)
{
int offset = irsdk_varNameToOffset(variable);
const irsdk_varHeader *rec = irsdk_getVarHeaderEntry(offset);
*destination = *(char*)(settings->data + offset);
}
void get_var(ECU *settings, char *variable, int *destination)
{
int offset = irsdk_varNameToOffset(variable);
const irsdk_varHeader *rec = irsdk_getVarHeaderEntry(offset);
*destination = *(int*)(settings->data + offset);
}
void get_var(ECU *settings, char *variable, float *destination)
{
int offset = irsdk_varNameToOffset(variable);
const irsdk_varHeader *rec = irsdk_getVarHeaderEntry(offset);
*destination = *(float*)(settings->data + offset);
}
void get_var(ECU *settings, char *variable, double *destination)
{
int offset = irsdk_varNameToOffset(variable);
const irsdk_varHeader *rec = irsdk_getVarHeaderEntry(offset);
*destination = *(double*)(settings->data + offset);
}
int on_track(char *data, const irsdk_header *header)
{
int IsOnTrack = irsdk_varNameToOffset("IsOnTrack");
bool ret = *(bool *)(data + IsOnTrack);
return ret;
}
void initData(const irsdk_header *header, char *data, int num_data)
{
if (data)
free(data);
num_data = header->bufLen;
data = (char*)malloc(num_data);
}
void shutdown_ecu(ECU *settings)
{
LOGF(WARNING, "Shutting down ECU");
// TODO: Readjust ERS deployment?
if (settings->telemetry->var_headers != NULL)
free(settings->telemetry->var_headers);
if (settings->telemetry->var_buf != NULL)
free(settings->telemetry->var_buf);
if (settings->telemetry != NULL)
free(settings->telemetry);
if (settings != NULL)
free(settings);
}
unsigned __stdcall start_ecu(void *p)
{
ECU *settings = (ECU*)p;
ws_event *events = settings->events;
bool init = false;
int missed = 0;
// int ret = WaitForSingleObject(events->connection_event, INFINITE);
// Use irsdk_connected() ?
while (!init) {
if (irsdkClient::instance().waitForData(1000)) {
// Check if we're in replay mode by testing
// if the physics is running on some channels
LOGF(DEBUG, "iRacing is online");
json j2 = {
{"status", 1}
};
send_json(j2.dump());
init = true;
}
}
// Test irsdk connection failures
int tries = 500;
while (tries > 0) {
if (irsdkClient::instance().waitForData(TIMEOUT)) {}
else
missed++;
tries--;
}
LOGF(DEBUG, "irsdk: timeout is %d ms", TIMEOUT);
LOGF(DEBUG, "irsdk: %d missed connections", missed);
int num_data = 0;
const irsdk_header *header = irsdk_getHeader();
while (true) {
int ret = WaitForSingleObject(events->exit_event, NULL);
if (ret == WAIT_OBJECT_0) {
shutdown_ecu(settings);
if (settings->data)
free(settings->data);
return 1;
}
if (header) {
if (!settings->data || num_data != header->bufLen) {
if (settings->data)
free(settings->data);
num_data = header->bufLen;
settings->data = (char*)malloc(num_data);
irsdk_waitForDataReady(TIMEOUT, settings->data);
}
else {
if (!irsdk_isConnected()) {
LOGF(DEBUG, "iRacing just went offline!");
settings->calibrated = false;
json offline = {
{"status", 0}
};
if (settings->data)
free(settings->data);
send_json(offline.dump());
shutdown_ecu(settings);
break;
}
irsdk_waitForDataReady(TIMEOUT, settings->data);
// Copy all vars to a buffer?
if (on_track(settings->data, header)) {
if (!settings->calibrated) {
settings->hWnd = GetForegroundWindow();
calibrate_ecu(settings);
settings->calibrated = true;
}
ers(settings);
}
else {
if (settings->calibrated)
LOGF(WARNING, "Car exited the track");
settings->calibrated = false;
}
}
}
}
return 1;
}
|
Fix typo in ecu.cpp
|
Fix typo in ecu.cpp
|
C++
|
bsd-3-clause
|
garciaadrian/ECU,garciaadrian/ECU,garciaadrian/ECU
|
881b70ee96ae8310ab792fabf1dfded513c891c3
|
src/import/chips/p9/procedures/hwp/initfiles/p9_npu_scom.C
|
src/import/chips/p9/procedures/hwp/initfiles/p9_npu_scom.C
|
/* IBM_PROLOG_BEGIN_TAG */
/* This is an automatically generated prolog. */
/* */
/* $Source: src/import/chips/p9/procedures/hwp/initfiles/p9_npu_scom.C $ */
/* */
/* OpenPOWER HostBoot Project */
/* */
/* Contributors Listed Below - COPYRIGHT 2016,2019 */
/* [+] International Business Machines Corp. */
/* */
/* */
/* Licensed under the Apache License, Version 2.0 (the "License"); */
/* you may not use this file except in compliance with the License. */
/* You may obtain a copy of the License at */
/* */
/* http://www.apache.org/licenses/LICENSE-2.0 */
/* */
/* Unless required by applicable law or agreed to in writing, software */
/* distributed under the License is distributed on an "AS IS" BASIS, */
/* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or */
/* implied. See the License for the specific language governing */
/* permissions and limitations under the License. */
/* */
/* IBM_PROLOG_END_TAG */
#include "p9_npu_scom.H"
#include <stdint.h>
#include <stddef.h>
#include <fapi2.H>
#include <attribute_ids.H>
#include <target_types.H>
#include <fapi2_attribute_service.H>
using namespace fapi2;
#define ATTR_PROC_FABRIC_OPTICS_CONFIG_MODE_ATTRIBUTE_VALUE_2 2
#define LITERAL_NPU_CONFIG_EPSILON_RATE_0x0 0x0
#define LITERAL_NPU_MISC_FIR_ACTION0_0_0x0000000000000000 0x0000000000000000
#define LITERAL_NPU_MISC_FIR_ACTION1_0_0x0000000000000000 0x0000000000000000
#define LITERAL_NPU_MISC_FIR_MASK_0_0x1111111111111111 0x1111111111111111
fapi2::ReturnCode p9_npu_scom(const fapi2::Target<fapi2::TARGET_TYPE_PROC_CHIP>& TGT0,
const fapi2::Target<fapi2::TARGET_TYPE_SYSTEM>& TGT1)
{
fapi2::ReturnCode l_rc = 0;
do
{
fapi2::buffer<uint64_t> NPU_MISC_FIR_ACTION0_0_scom0;
l_rc = fapi2::getScom( TGT0, 0x5011406ull, NPU_MISC_FIR_ACTION0_0_scom0 );
if (l_rc)
{
FAPI_ERR("ERROR executing: getScom (0x5011406)");
break;
}
fapi2::buffer<uint64_t> NPU_MISC_FIR_ACTION0_1_scom0;
l_rc = fapi2::getScom( TGT0, 0x5011446ull, NPU_MISC_FIR_ACTION0_1_scom0 );
if (l_rc)
{
FAPI_ERR("ERROR executing: getScom (0x5011446)");
break;
}
NPU_MISC_FIR_ACTION0_0_scom0.insert<uint64_t> (LITERAL_NPU_MISC_FIR_ACTION0_0_0x0000000000000000, 0, 64, 0 );
NPU_MISC_FIR_ACTION0_1_scom0.insert<uint64_t> (LITERAL_NPU_MISC_FIR_ACTION0_0_0x0000000000000000, 0, 64, 0 );
fapi2::buffer<uint64_t> NPU_MISC_FIR_ACTION1_0_scom0;
l_rc = fapi2::getScom( TGT0, 0x5011407ull, NPU_MISC_FIR_ACTION1_0_scom0 );
if (l_rc)
{
FAPI_ERR("ERROR executing: getScom (0x5011407)");
break;
}
fapi2::buffer<uint64_t> NPU_MISC_FIR_ACTION1_1_scom0;
l_rc = fapi2::getScom( TGT0, 0x5011447ull, NPU_MISC_FIR_ACTION1_1_scom0 );
if (l_rc)
{
FAPI_ERR("ERROR executing: getScom (0x5011447)");
break;
}
NPU_MISC_FIR_ACTION1_0_scom0.insert<uint64_t> (LITERAL_NPU_MISC_FIR_ACTION1_0_0x0000000000000000, 0, 64, 0 );
NPU_MISC_FIR_ACTION1_1_scom0.insert<uint64_t> (LITERAL_NPU_MISC_FIR_ACTION1_0_0x0000000000000000, 0, 64, 0 );
fapi2::buffer<uint64_t> NPU_MISC_FIR_MASK_0_scom0;
l_rc = fapi2::getScom( TGT0, 0x5011403ull, NPU_MISC_FIR_MASK_0_scom0 );
if (l_rc)
{
FAPI_ERR("ERROR executing: getScom (0x5011403)");
break;
}
NPU_MISC_FIR_MASK_0_scom0.insert<uint64_t> (LITERAL_NPU_MISC_FIR_MASK_0_0x1111111111111111, 0, 64, 0 );
ATTR_PROC_FABRIC_OPTICS_CONFIG_MODE_Type iv_TGT0_ATTR_PROC_FABRIC_OPTICS_CONFIG_MODE;
l_rc = FAPI_ATTR_GET(ATTR_PROC_FABRIC_OPTICS_CONFIG_MODE, TGT0, iv_TGT0_ATTR_PROC_FABRIC_OPTICS_CONFIG_MODE);
if (l_rc)
{
FAPI_ERR("ERROR executing: FAPI_ATTR_GET (iv_TGT0_ATTR_PROC_FABRIC_OPTICS_CONFIG_MODE)");
break;
}
fapi2::buffer<uint64_t> NPU_CONFIG_ENABLE_MACHINE_ALLOC_scom0;
l_rc = fapi2::getScom( TGT0, 0x5011008ull, NPU_CONFIG_ENABLE_MACHINE_ALLOC_scom0 );
if (l_rc)
{
FAPI_ERR("ERROR executing: getScom (0x5011008)");
break;
}
NPU_CONFIG_ENABLE_MACHINE_ALLOC_scom0.insert<uint64_t> (((((iv_TGT0_ATTR_PROC_FABRIC_OPTICS_CONFIG_MODE[0] ==
ATTR_PROC_FABRIC_OPTICS_CONFIG_MODE_ATTRIBUTE_VALUE_2)
|| (iv_TGT0_ATTR_PROC_FABRIC_OPTICS_CONFIG_MODE[1] == ATTR_PROC_FABRIC_OPTICS_CONFIG_MODE_ATTRIBUTE_VALUE_2))
|| (iv_TGT0_ATTR_PROC_FABRIC_OPTICS_CONFIG_MODE[2] == ATTR_PROC_FABRIC_OPTICS_CONFIG_MODE_ATTRIBUTE_VALUE_2))
|| (iv_TGT0_ATTR_PROC_FABRIC_OPTICS_CONFIG_MODE[3] == ATTR_PROC_FABRIC_OPTICS_CONFIG_MODE_ATTRIBUTE_VALUE_2)), 51, 1,
63 );
fapi2::buffer<uint64_t> NPU_CONFIG_ENABLE_PBUS_scom0;
l_rc = fapi2::getScom( TGT0, 0x5011000ull, NPU_CONFIG_ENABLE_PBUS_scom0 );
if (l_rc)
{
FAPI_ERR("ERROR executing: getScom (0x5011000)");
break;
}
NPU_CONFIG_ENABLE_PBUS_scom0.insert<uint64_t> (((((iv_TGT0_ATTR_PROC_FABRIC_OPTICS_CONFIG_MODE[0] ==
ATTR_PROC_FABRIC_OPTICS_CONFIG_MODE_ATTRIBUTE_VALUE_2)
|| (iv_TGT0_ATTR_PROC_FABRIC_OPTICS_CONFIG_MODE[1] == ATTR_PROC_FABRIC_OPTICS_CONFIG_MODE_ATTRIBUTE_VALUE_2))
|| (iv_TGT0_ATTR_PROC_FABRIC_OPTICS_CONFIG_MODE[2] == ATTR_PROC_FABRIC_OPTICS_CONFIG_MODE_ATTRIBUTE_VALUE_2))
|| (iv_TGT0_ATTR_PROC_FABRIC_OPTICS_CONFIG_MODE[3] == ATTR_PROC_FABRIC_OPTICS_CONFIG_MODE_ATTRIBUTE_VALUE_2)), 38, 1,
63 );
ATTR_PROC_EPS_READ_CYCLES_Type iv_TGT1_ATTR_PROC_EPS_READ_CYCLES;
l_rc = FAPI_ATTR_GET(ATTR_PROC_EPS_READ_CYCLES, TGT1, iv_TGT1_ATTR_PROC_EPS_READ_CYCLES);
if (l_rc)
{
FAPI_ERR("ERROR executing: FAPI_ATTR_GET (iv_TGT1_ATTR_PROC_EPS_READ_CYCLES)");
break;
}
fapi2::buffer<uint64_t> NPU_CONFIG_EPSILON_R0_COUNT_scom0;
l_rc = fapi2::getScom( TGT0, 0x5011002ull, NPU_CONFIG_EPSILON_R0_COUNT_scom0 );
if (l_rc)
{
FAPI_ERR("ERROR executing: getScom (0x5011002)");
break;
}
NPU_CONFIG_EPSILON_R0_COUNT_scom0.insert<uint64_t> (iv_TGT1_ATTR_PROC_EPS_READ_CYCLES[0], 28, 12, 52 );
NPU_CONFIG_EPSILON_R0_COUNT_scom0.insert<uint64_t> (iv_TGT1_ATTR_PROC_EPS_READ_CYCLES[1], 40, 12, 52 );
NPU_CONFIG_EPSILON_R0_COUNT_scom0.insert<uint64_t> (iv_TGT1_ATTR_PROC_EPS_READ_CYCLES[2], 52, 12, 52 );
NPU_CONFIG_EPSILON_R0_COUNT_scom0.insert<uint64_t> (LITERAL_NPU_CONFIG_EPSILON_RATE_0x0, 0, 4, 60 );
ATTR_PROC_EPS_WRITE_CYCLES_Type iv_TGT1_ATTR_PROC_EPS_WRITE_CYCLES;
l_rc = FAPI_ATTR_GET(ATTR_PROC_EPS_WRITE_CYCLES, TGT1, iv_TGT1_ATTR_PROC_EPS_WRITE_CYCLES);
if (l_rc)
{
FAPI_ERR("ERROR executing: FAPI_ATTR_GET (iv_TGT1_ATTR_PROC_EPS_WRITE_CYCLES)");
break;
}
NPU_CONFIG_EPSILON_R0_COUNT_scom0.insert<uint64_t> (iv_TGT1_ATTR_PROC_EPS_WRITE_CYCLES[0], 4, 12, 52 );
NPU_CONFIG_EPSILON_R0_COUNT_scom0.insert<uint64_t> (iv_TGT1_ATTR_PROC_EPS_WRITE_CYCLES[1], 16, 12, 52 );
l_rc = fapi2::putScom( TGT0, 0x5011000ull, NPU_CONFIG_ENABLE_PBUS_scom0 );
if (l_rc)
{
FAPI_ERR("ERROR executing: putScom (0x5011000)");
break;
}
l_rc = fapi2::putScom( TGT0, 0x5011002ull, NPU_CONFIG_EPSILON_R0_COUNT_scom0 );
if (l_rc)
{
FAPI_ERR("ERROR executing: putScom (0x5011002)");
break;
}
l_rc = fapi2::putScom( TGT0, 0x5011008ull, NPU_CONFIG_ENABLE_MACHINE_ALLOC_scom0 );
if (l_rc)
{
FAPI_ERR("ERROR executing: putScom (0x5011008)");
break;
}
l_rc = fapi2::putScom( TGT0, 0x5011403ull, NPU_MISC_FIR_MASK_0_scom0 );
if (l_rc)
{
FAPI_ERR("ERROR executing: putScom (0x5011403)");
break;
}
l_rc = fapi2::putScom( TGT0, 0x5011406ull, NPU_MISC_FIR_ACTION0_0_scom0 );
if (l_rc)
{
FAPI_ERR("ERROR executing: putScom (0x5011406)");
break;
}
l_rc = fapi2::putScom( TGT0, 0x5011407ull, NPU_MISC_FIR_ACTION1_0_scom0 );
if (l_rc)
{
FAPI_ERR("ERROR executing: putScom (0x5011407)");
break;
}
l_rc = fapi2::putScom( TGT0, 0x5011446ull, NPU_MISC_FIR_ACTION0_1_scom0 );
if (l_rc)
{
FAPI_ERR("ERROR executing: putScom (0x5011446)");
break;
}
l_rc = fapi2::putScom( TGT0, 0x5011447ull, NPU_MISC_FIR_ACTION1_1_scom0 );
if (l_rc)
{
FAPI_ERR("ERROR executing: putScom (0x5011447)");
break;
}
}
while(0);
return l_rc;
}
|
/* IBM_PROLOG_BEGIN_TAG */
/* This is an automatically generated prolog. */
/* */
/* $Source: src/import/chips/p9/procedures/hwp/initfiles/p9_npu_scom.C $ */
/* */
/* OpenPOWER HostBoot Project */
/* */
/* Contributors Listed Below - COPYRIGHT 2016,2019 */
/* [+] International Business Machines Corp. */
/* */
/* */
/* Licensed under the Apache License, Version 2.0 (the "License"); */
/* you may not use this file except in compliance with the License. */
/* You may obtain a copy of the License at */
/* */
/* http://www.apache.org/licenses/LICENSE-2.0 */
/* */
/* Unless required by applicable law or agreed to in writing, software */
/* distributed under the License is distributed on an "AS IS" BASIS, */
/* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or */
/* implied. See the License for the specific language governing */
/* permissions and limitations under the License. */
/* */
/* IBM_PROLOG_END_TAG */
#include "p9_npu_scom.H"
#include <stdint.h>
#include <stddef.h>
#include <fapi2.H>
using namespace fapi2;
constexpr auto literal_2 = 2;
constexpr auto literal_3 = 3;
constexpr auto literal_1 = 1;
constexpr auto literal_0 = 0;
constexpr auto literal_0x1111111111111111 = 0x1111111111111111;
constexpr auto literal_0x0000000000000000 = 0x0000000000000000;
fapi2::ReturnCode p9_npu_scom(const fapi2::Target<fapi2::TARGET_TYPE_PROC_CHIP>& TGT0,
const fapi2::Target<fapi2::TARGET_TYPE_SYSTEM>& TGT1)
{
fapi2::ReturnCode l_rc = 0;
do
{
fapi2::buffer<uint64_t> l_scom_buffer;
fapi2::ATTR_PROC_FABRIC_OPTICS_CONFIG_MODE_Type l_TGT0_ATTR_PROC_FABRIC_OPTICS_CONFIG_MODE;
l_rc = FAPI_ATTR_GET(fapi2::ATTR_PROC_FABRIC_OPTICS_CONFIG_MODE, TGT0, l_TGT0_ATTR_PROC_FABRIC_OPTICS_CONFIG_MODE);
if (l_rc)
{
FAPI_ERR("ERROR executing: FAPI_ATTR_GET (ATTR_PROC_FABRIC_OPTICS_CONFIG_MODE)");
break;
}
{
l_rc = fapi2::getScom( TGT0, 0x5011000ull, l_scom_buffer );
if (l_rc)
{
FAPI_ERR("ERROR executing: getScom (0x5011000ull)");
break;
}
l_scom_buffer.insert<uint64_t> (((((l_TGT0_ATTR_PROC_FABRIC_OPTICS_CONFIG_MODE[literal_0] == literal_2)
|| (l_TGT0_ATTR_PROC_FABRIC_OPTICS_CONFIG_MODE[literal_1] == literal_2))
|| (l_TGT0_ATTR_PROC_FABRIC_OPTICS_CONFIG_MODE[literal_2] == literal_2))
|| (l_TGT0_ATTR_PROC_FABRIC_OPTICS_CONFIG_MODE[literal_3] == literal_2)), 38, 1, 63 );
l_rc = fapi2::putScom(TGT0, 0x5011000ull, l_scom_buffer);
if (l_rc)
{
FAPI_ERR("ERROR executing: putScom (0x5011000ull)");
break;
}
}
fapi2::ATTR_PROC_EPS_READ_CYCLES_Type l_TGT1_ATTR_PROC_EPS_READ_CYCLES;
l_rc = FAPI_ATTR_GET(fapi2::ATTR_PROC_EPS_READ_CYCLES, TGT1, l_TGT1_ATTR_PROC_EPS_READ_CYCLES);
if (l_rc)
{
FAPI_ERR("ERROR executing: FAPI_ATTR_GET (ATTR_PROC_EPS_READ_CYCLES)");
break;
}
{
l_rc = fapi2::getScom( TGT0, 0x5011002ull, l_scom_buffer );
if (l_rc)
{
FAPI_ERR("ERROR executing: getScom (0x5011002ull)");
break;
}
l_scom_buffer.insert<uint64_t> (l_TGT1_ATTR_PROC_EPS_READ_CYCLES[literal_0], 28, 12, 52 );
l_rc = fapi2::putScom(TGT0, 0x5011002ull, l_scom_buffer);
if (l_rc)
{
FAPI_ERR("ERROR executing: putScom (0x5011002ull)");
break;
}
}
{
l_rc = fapi2::getScom( TGT0, 0x5011008ull, l_scom_buffer );
if (l_rc)
{
FAPI_ERR("ERROR executing: getScom (0x5011008ull)");
break;
}
l_scom_buffer.insert<uint64_t> (((((l_TGT0_ATTR_PROC_FABRIC_OPTICS_CONFIG_MODE[literal_0] == literal_2)
|| (l_TGT0_ATTR_PROC_FABRIC_OPTICS_CONFIG_MODE[literal_1] == literal_2))
|| (l_TGT0_ATTR_PROC_FABRIC_OPTICS_CONFIG_MODE[literal_2] == literal_2))
|| (l_TGT0_ATTR_PROC_FABRIC_OPTICS_CONFIG_MODE[literal_3] == literal_2)), 51, 1, 63 );
l_rc = fapi2::putScom(TGT0, 0x5011008ull, l_scom_buffer);
if (l_rc)
{
FAPI_ERR("ERROR executing: putScom (0x5011008ull)");
break;
}
}
{
l_rc = fapi2::getScom( TGT0, 0x5011403ull, l_scom_buffer );
if (l_rc)
{
FAPI_ERR("ERROR executing: getScom (0x5011403ull)");
break;
}
l_scom_buffer.insert<uint64_t> (literal_0x1111111111111111, 0, 64, 0 );
l_rc = fapi2::putScom(TGT0, 0x5011403ull, l_scom_buffer);
if (l_rc)
{
FAPI_ERR("ERROR executing: putScom (0x5011403ull)");
break;
}
}
{
l_rc = fapi2::getScom( TGT0, 0x5011406ull, l_scom_buffer );
if (l_rc)
{
FAPI_ERR("ERROR executing: getScom (0x5011406ull)");
break;
}
l_scom_buffer.insert<uint64_t> (literal_0x0000000000000000, 0, 64, 0 );
l_scom_buffer.insert<uint64_t> (literal_0x0000000000000000, 0, 64, 0 );
l_rc = fapi2::putScom(TGT0, 0x5011406ull, l_scom_buffer);
if (l_rc)
{
FAPI_ERR("ERROR executing: putScom (0x5011406ull)");
break;
}
}
{
l_rc = fapi2::getScom( TGT0, 0x5011407ull, l_scom_buffer );
if (l_rc)
{
FAPI_ERR("ERROR executing: getScom (0x5011407ull)");
break;
}
l_scom_buffer.insert<uint64_t> (literal_0x0000000000000000, 0, 64, 0 );
l_scom_buffer.insert<uint64_t> (literal_0x0000000000000000, 0, 64, 0 );
l_rc = fapi2::putScom(TGT0, 0x5011407ull, l_scom_buffer);
if (l_rc)
{
FAPI_ERR("ERROR executing: putScom (0x5011407ull)");
break;
}
}
{
l_rc = fapi2::getScom( TGT0, 0x5011446ull, l_scom_buffer );
if (l_rc)
{
FAPI_ERR("ERROR executing: getScom (0x5011446ull)");
break;
}
l_scom_buffer.insert<uint64_t> (literal_0x0000000000000000, 0, 64, 0 );
l_scom_buffer.insert<uint64_t> (literal_0x0000000000000000, 0, 64, 0 );
l_rc = fapi2::putScom(TGT0, 0x5011446ull, l_scom_buffer);
if (l_rc)
{
FAPI_ERR("ERROR executing: putScom (0x5011446ull)");
break;
}
}
{
l_rc = fapi2::getScom( TGT0, 0x5011447ull, l_scom_buffer );
if (l_rc)
{
FAPI_ERR("ERROR executing: getScom (0x5011447ull)");
break;
}
l_scom_buffer.insert<uint64_t> (literal_0x0000000000000000, 0, 64, 0 );
l_scom_buffer.insert<uint64_t> (literal_0x0000000000000000, 0, 64, 0 );
l_rc = fapi2::putScom(TGT0, 0x5011447ull, l_scom_buffer);
if (l_rc)
{
FAPI_ERR("ERROR executing: putScom (0x5011447ull)");
break;
}
}
}
while (0);
return l_rc;
}
|
Update p9_npu_scom initfile procedure with the latest initCompiler changes
|
Update p9_npu_scom initfile procedure with the latest initCompiler changes
Change-Id: If65958f50cbf248d1227d7db4dde12a6ec6ab51f
Reviewed-on: http://ralgit01.raleigh.ibm.com/gerrit1/23593
Tested-by: Jenkins Server
Reviewed-by: Joseph J. McGill <[email protected]>
Reviewed-by: JOSHUA L. HANNAN <[email protected]>
Reviewed-by: Prachi Gupta <[email protected]>
|
C++
|
apache-2.0
|
open-power/hostboot,open-power/hostboot,open-power/hostboot,open-power/hostboot,open-power/hostboot
|
6f4423af235da5e1e5e03a602edf36cff5caeee0
|
src/libGLESv2/renderer/d3d/d3d9/VertexDeclarationCache.cpp
|
src/libGLESv2/renderer/d3d/d3d9/VertexDeclarationCache.cpp
|
#include "precompiled.h"
//
// Copyright (c) 2012 The ANGLE Project Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
//
// VertexDeclarationCache.cpp: Implements a helper class to construct and cache vertex declarations.
#include "libGLESv2/ProgramBinary.h"
#include "libGLESv2/VertexAttribute.h"
#include "libGLESv2/renderer/d3d/d3d9/VertexBuffer9.h"
#include "libGLESv2/renderer/d3d/d3d9/VertexDeclarationCache.h"
#include "libGLESv2/renderer/d3d/d3d9/formatutils9.h"
namespace rx
{
VertexDeclarationCache::VertexDeclarationCache() : mMaxLru(0)
{
for (int i = 0; i < NUM_VERTEX_DECL_CACHE_ENTRIES; i++)
{
mVertexDeclCache[i].vertexDeclaration = NULL;
mVertexDeclCache[i].lruCount = 0;
}
for (int i = 0; i < gl::MAX_VERTEX_ATTRIBS; i++)
{
mAppliedVBs[i].serial = 0;
}
mLastSetVDecl = NULL;
mInstancingEnabled = true;
}
VertexDeclarationCache::~VertexDeclarationCache()
{
for (int i = 0; i < NUM_VERTEX_DECL_CACHE_ENTRIES; i++)
{
SafeRelease(mVertexDeclCache[i].vertexDeclaration);
}
}
GLenum VertexDeclarationCache::applyDeclaration(IDirect3DDevice9 *device, TranslatedAttribute attributes[], gl::ProgramBinary *programBinary, GLsizei instances, GLsizei *repeatDraw)
{
*repeatDraw = 1;
int indexedAttribute = gl::MAX_VERTEX_ATTRIBS;
int instancedAttribute = gl::MAX_VERTEX_ATTRIBS;
if (instances == 0)
{
for (int i = 0; i < gl::MAX_VERTEX_ATTRIBS; ++i)
{
if (attributes[i].divisor != 0)
{
// If a divisor is set, it still applies even if an instanced draw was not used, so treat
// as a single-instance draw.
instances = 1;
break;
}
}
}
if (instances > 0)
{
// Find an indexed attribute to be mapped to D3D stream 0
for (int i = 0; i < gl::MAX_VERTEX_ATTRIBS; i++)
{
if (attributes[i].active)
{
if (indexedAttribute == gl::MAX_VERTEX_ATTRIBS && attributes[i].divisor == 0)
{
indexedAttribute = i;
}
else if (instancedAttribute == gl::MAX_VERTEX_ATTRIBS && attributes[i].divisor != 0)
{
instancedAttribute = i;
}
if (indexedAttribute != gl::MAX_VERTEX_ATTRIBS && instancedAttribute != gl::MAX_VERTEX_ATTRIBS)
break; // Found both an indexed and instanced attribute
}
}
if (indexedAttribute == gl::MAX_VERTEX_ATTRIBS)
{
return GL_INVALID_OPERATION;
}
}
D3DCAPS9 caps;
device->GetDeviceCaps(&caps);
D3DVERTEXELEMENT9 elements[gl::MAX_VERTEX_ATTRIBS + 1];
D3DVERTEXELEMENT9 *element = &elements[0];
for (int i = 0; i < gl::MAX_VERTEX_ATTRIBS; i++)
{
if (attributes[i].active)
{
// Directly binding the storage buffer is not supported for d3d9
ASSERT(attributes[i].storage == NULL);
int stream = i;
if (instances > 0)
{
// Due to a bug on ATI cards we can't enable instancing when none of the attributes are instanced.
if (instancedAttribute == gl::MAX_VERTEX_ATTRIBS)
{
*repeatDraw = instances;
}
else
{
if (i == indexedAttribute)
{
stream = 0;
}
else if (i == 0)
{
stream = indexedAttribute;
}
UINT frequency = 1;
if (attributes[i].divisor == 0)
{
frequency = D3DSTREAMSOURCE_INDEXEDDATA | instances;
}
else
{
frequency = D3DSTREAMSOURCE_INSTANCEDATA | attributes[i].divisor;
}
device->SetStreamSourceFreq(stream, frequency);
mInstancingEnabled = true;
}
}
VertexBuffer9 *vertexBuffer = VertexBuffer9::makeVertexBuffer9(attributes[i].vertexBuffer);
if (mAppliedVBs[stream].serial != attributes[i].serial ||
mAppliedVBs[stream].stride != attributes[i].stride ||
mAppliedVBs[stream].offset != attributes[i].offset)
{
device->SetStreamSource(stream, vertexBuffer->getBuffer(), attributes[i].offset, attributes[i].stride);
mAppliedVBs[stream].serial = attributes[i].serial;
mAppliedVBs[stream].stride = attributes[i].stride;
mAppliedVBs[stream].offset = attributes[i].offset;
}
gl::VertexFormat vertexFormat(*attributes[i].attribute, GL_FLOAT);
const d3d9::VertexFormat &d3d9VertexInfo = d3d9::GetVertexFormatInfo(caps.DeclTypes, vertexFormat);
element->Stream = stream;
element->Offset = 0;
element->Type = d3d9VertexInfo.nativeFormat;
element->Method = D3DDECLMETHOD_DEFAULT;
element->Usage = D3DDECLUSAGE_TEXCOORD;
element->UsageIndex = programBinary->getSemanticIndex(i);
element++;
}
}
if (instances == 0 || instancedAttribute == gl::MAX_VERTEX_ATTRIBS)
{
if (mInstancingEnabled)
{
for (int i = 0; i < gl::MAX_VERTEX_ATTRIBS; i++)
{
device->SetStreamSourceFreq(i, 1);
}
mInstancingEnabled = false;
}
}
static const D3DVERTEXELEMENT9 end = D3DDECL_END();
*(element++) = end;
for (int i = 0; i < NUM_VERTEX_DECL_CACHE_ENTRIES; i++)
{
VertexDeclCacheEntry *entry = &mVertexDeclCache[i];
if (memcmp(entry->cachedElements, elements, (element - elements) * sizeof(D3DVERTEXELEMENT9)) == 0 && entry->vertexDeclaration)
{
entry->lruCount = ++mMaxLru;
if(entry->vertexDeclaration != mLastSetVDecl)
{
device->SetVertexDeclaration(entry->vertexDeclaration);
mLastSetVDecl = entry->vertexDeclaration;
}
return GL_NO_ERROR;
}
}
VertexDeclCacheEntry *lastCache = mVertexDeclCache;
for (int i = 0; i < NUM_VERTEX_DECL_CACHE_ENTRIES; i++)
{
if (mVertexDeclCache[i].lruCount < lastCache->lruCount)
{
lastCache = &mVertexDeclCache[i];
}
}
if (lastCache->vertexDeclaration != NULL)
{
SafeRelease(lastCache->vertexDeclaration);
// mLastSetVDecl is set to the replacement, so we don't have to worry
// about it.
}
memcpy(lastCache->cachedElements, elements, (element - elements) * sizeof(D3DVERTEXELEMENT9));
device->CreateVertexDeclaration(elements, &lastCache->vertexDeclaration);
device->SetVertexDeclaration(lastCache->vertexDeclaration);
mLastSetVDecl = lastCache->vertexDeclaration;
lastCache->lruCount = ++mMaxLru;
return GL_NO_ERROR;
}
void VertexDeclarationCache::markStateDirty()
{
for (int i = 0; i < gl::MAX_VERTEX_ATTRIBS; i++)
{
mAppliedVBs[i].serial = 0;
}
mLastSetVDecl = NULL;
mInstancingEnabled = true; // Forces it to be disabled when not used
}
}
|
#include "precompiled.h"
//
// Copyright (c) 2012 The ANGLE Project Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
//
// VertexDeclarationCache.cpp: Implements a helper class to construct and cache vertex declarations.
#include "libGLESv2/ProgramBinary.h"
#include "libGLESv2/VertexAttribute.h"
#include "libGLESv2/renderer/d3d/d3d9/VertexBuffer9.h"
#include "libGLESv2/renderer/d3d/d3d9/VertexDeclarationCache.h"
#include "libGLESv2/renderer/d3d/d3d9/formatutils9.h"
namespace rx
{
VertexDeclarationCache::VertexDeclarationCache() : mMaxLru(0)
{
for (int i = 0; i < NUM_VERTEX_DECL_CACHE_ENTRIES; i++)
{
mVertexDeclCache[i].vertexDeclaration = NULL;
mVertexDeclCache[i].lruCount = 0;
}
for (int i = 0; i < gl::MAX_VERTEX_ATTRIBS; i++)
{
mAppliedVBs[i].serial = 0;
}
mLastSetVDecl = NULL;
mInstancingEnabled = true;
}
VertexDeclarationCache::~VertexDeclarationCache()
{
for (int i = 0; i < NUM_VERTEX_DECL_CACHE_ENTRIES; i++)
{
SafeRelease(mVertexDeclCache[i].vertexDeclaration);
}
}
GLenum VertexDeclarationCache::applyDeclaration(IDirect3DDevice9 *device, TranslatedAttribute attributes[], gl::ProgramBinary *programBinary, GLsizei instances, GLsizei *repeatDraw)
{
*repeatDraw = 1;
int indexedAttribute = gl::MAX_VERTEX_ATTRIBS;
int instancedAttribute = gl::MAX_VERTEX_ATTRIBS;
if (instances > 0)
{
// Find an indexed attribute to be mapped to D3D stream 0
for (int i = 0; i < gl::MAX_VERTEX_ATTRIBS; i++)
{
if (attributes[i].active)
{
if (indexedAttribute == gl::MAX_VERTEX_ATTRIBS && attributes[i].divisor == 0)
{
indexedAttribute = i;
}
else if (instancedAttribute == gl::MAX_VERTEX_ATTRIBS && attributes[i].divisor != 0)
{
instancedAttribute = i;
}
if (indexedAttribute != gl::MAX_VERTEX_ATTRIBS && instancedAttribute != gl::MAX_VERTEX_ATTRIBS)
break; // Found both an indexed and instanced attribute
}
}
if (indexedAttribute == gl::MAX_VERTEX_ATTRIBS)
{
return GL_INVALID_OPERATION;
}
}
D3DCAPS9 caps;
device->GetDeviceCaps(&caps);
D3DVERTEXELEMENT9 elements[gl::MAX_VERTEX_ATTRIBS + 1];
D3DVERTEXELEMENT9 *element = &elements[0];
for (int i = 0; i < gl::MAX_VERTEX_ATTRIBS; i++)
{
if (attributes[i].active)
{
// Directly binding the storage buffer is not supported for d3d9
ASSERT(attributes[i].storage == NULL);
int stream = i;
if (instances > 0)
{
// Due to a bug on ATI cards we can't enable instancing when none of the attributes are instanced.
if (instancedAttribute == gl::MAX_VERTEX_ATTRIBS)
{
*repeatDraw = instances;
}
else
{
if (i == indexedAttribute)
{
stream = 0;
}
else if (i == 0)
{
stream = indexedAttribute;
}
UINT frequency = 1;
if (attributes[i].divisor == 0)
{
frequency = D3DSTREAMSOURCE_INDEXEDDATA | instances;
}
else
{
frequency = D3DSTREAMSOURCE_INSTANCEDATA | attributes[i].divisor;
}
device->SetStreamSourceFreq(stream, frequency);
mInstancingEnabled = true;
}
}
VertexBuffer9 *vertexBuffer = VertexBuffer9::makeVertexBuffer9(attributes[i].vertexBuffer);
if (mAppliedVBs[stream].serial != attributes[i].serial ||
mAppliedVBs[stream].stride != attributes[i].stride ||
mAppliedVBs[stream].offset != attributes[i].offset)
{
device->SetStreamSource(stream, vertexBuffer->getBuffer(), attributes[i].offset, attributes[i].stride);
mAppliedVBs[stream].serial = attributes[i].serial;
mAppliedVBs[stream].stride = attributes[i].stride;
mAppliedVBs[stream].offset = attributes[i].offset;
}
gl::VertexFormat vertexFormat(*attributes[i].attribute, GL_FLOAT);
const d3d9::VertexFormat &d3d9VertexInfo = d3d9::GetVertexFormatInfo(caps.DeclTypes, vertexFormat);
element->Stream = stream;
element->Offset = 0;
element->Type = d3d9VertexInfo.nativeFormat;
element->Method = D3DDECLMETHOD_DEFAULT;
element->Usage = D3DDECLUSAGE_TEXCOORD;
element->UsageIndex = programBinary->getSemanticIndex(i);
element++;
}
}
if (instances == 0 || instancedAttribute == gl::MAX_VERTEX_ATTRIBS)
{
if (mInstancingEnabled)
{
for (int i = 0; i < gl::MAX_VERTEX_ATTRIBS; i++)
{
device->SetStreamSourceFreq(i, 1);
}
mInstancingEnabled = false;
}
}
static const D3DVERTEXELEMENT9 end = D3DDECL_END();
*(element++) = end;
for (int i = 0; i < NUM_VERTEX_DECL_CACHE_ENTRIES; i++)
{
VertexDeclCacheEntry *entry = &mVertexDeclCache[i];
if (memcmp(entry->cachedElements, elements, (element - elements) * sizeof(D3DVERTEXELEMENT9)) == 0 && entry->vertexDeclaration)
{
entry->lruCount = ++mMaxLru;
if(entry->vertexDeclaration != mLastSetVDecl)
{
device->SetVertexDeclaration(entry->vertexDeclaration);
mLastSetVDecl = entry->vertexDeclaration;
}
return GL_NO_ERROR;
}
}
VertexDeclCacheEntry *lastCache = mVertexDeclCache;
for (int i = 0; i < NUM_VERTEX_DECL_CACHE_ENTRIES; i++)
{
if (mVertexDeclCache[i].lruCount < lastCache->lruCount)
{
lastCache = &mVertexDeclCache[i];
}
}
if (lastCache->vertexDeclaration != NULL)
{
SafeRelease(lastCache->vertexDeclaration);
// mLastSetVDecl is set to the replacement, so we don't have to worry
// about it.
}
memcpy(lastCache->cachedElements, elements, (element - elements) * sizeof(D3DVERTEXELEMENT9));
device->CreateVertexDeclaration(elements, &lastCache->vertexDeclaration);
device->SetVertexDeclaration(lastCache->vertexDeclaration);
mLastSetVDecl = lastCache->vertexDeclaration;
lastCache->lruCount = ++mMaxLru;
return GL_NO_ERROR;
}
void VertexDeclarationCache::markStateDirty()
{
for (int i = 0; i < gl::MAX_VERTEX_ATTRIBS; i++)
{
mAppliedVBs[i].serial = 0;
}
mLastSetVDecl = NULL;
mInstancingEnabled = true; // Forces it to be disabled when not used
}
}
|
Revert "Fix application of vertex divisor for non-instanced draws in D3D9"
|
Revert "Fix application of vertex divisor for non-instanced draws in D3D9"
Other issues turn up on the FYI bots with this patch applied; reverting until this is investigated further.
This reverts commit 9f6907bfdd4cf95d20408831b1776a6efd221ab3.
Change-Id: Ib30c51b2c905e87973c73b06baa4b8ebba31d210
Reviewed-on: https://chromium-review.googlesource.com/211683
Reviewed-by: Shannon Woods <[email protected]>
Tested-by: Shannon Woods <[email protected]>
|
C++
|
bsd-3-clause
|
MIPS/external-chromium_org-third_party-angle,ppy/angle,larsbergstrom/angle,nandhanurrevanth/angle,mikolalysenko/angle,ecoal95/angle,android-ia/platform_external_chromium_org_third_party_angle,mybios/angle,bsergean/angle,ghostoy/angle,mrobinson/rust-angle,vvuk/angle,MSOpenTech/angle,mlfarrell/angle,geekboxzone/lollipop_external_chromium_org_third_party_angle,domokit/waterfall,MSOpenTech/angle,mybios/angle,ghostoy/angle,MSOpenTech/angle,mrobinson/rust-angle,mlfarrell/angle,csa7mdm/angle,xin3liang/platform_external_chromium_org_third_party_angle,ghostoy/angle,csa7mdm/angle,csa7mdm/angle,crezefire/angle,android-ia/platform_external_chromium_org_third_party_angle,geekboxzone/lollipop_external_chromium_org_third_party_angle,bsergean/angle,mrobinson/rust-angle,jgcaaprom/android_external_chromium_org_third_party_angle,geekboxzone/lollipop_external_chromium_org_third_party_angle,xin3liang/platform_external_chromium_org_third_party_angle,mlfarrell/angle,domokit/waterfall,android-ia/platform_external_chromium_org_third_party_angle,mybios/angle,jgcaaprom/android_external_chromium_org_third_party_angle,mikolalysenko/angle,larsbergstrom/angle,larsbergstrom/angle,ppy/angle,MSOpenTech/angle,ppy/angle,ecoal95/angle,ecoal95/angle,larsbergstrom/angle,jgcaaprom/android_external_chromium_org_third_party_angle,crezefire/angle,xin3liang/platform_external_chromium_org_third_party_angle,ecoal95/angle,xin3liang/platform_external_chromium_org_third_party_angle,nandhanurrevanth/angle,MIPS/external-chromium_org-third_party-angle,bsergean/angle,mlfarrell/angle,crezefire/angle,vvuk/angle,mrobinson/rust-angle,mikolalysenko/angle,bsergean/angle,MIPS/external-chromium_org-third_party-angle,ppy/angle,vvuk/angle,geekboxzone/lollipop_external_chromium_org_third_party_angle,ecoal95/angle,csa7mdm/angle,nandhanurrevanth/angle,jgcaaprom/android_external_chromium_org_third_party_angle,ghostoy/angle,mikolalysenko/angle,nandhanurrevanth/angle,vvuk/angle,mrobinson/rust-angle,android-ia/platform_external_chromium_org_third_party_angle,crezefire/angle,mybios/angle,MIPS/external-chromium_org-third_party-angle
|
e54b9681ae14fa30cd2f4434968682f6f7f9def2
|
src/core/console_user_server/include/console_user_server/components_manager.hpp
|
src/core/console_user_server/include/console_user_server/components_manager.hpp
|
#pragma once
// `krbn::console_user_server::components_manager` can be used safely in a multi-threaded environment.
#include "application_launcher.hpp"
#include "components_manager_killer.hpp"
#include "constants.hpp"
#include "grabber_client.hpp"
#include "logger.hpp"
#include "menu_process_manager.hpp"
#include "monitor/configuration_monitor.hpp"
#include "monitor/version_monitor.hpp"
#include "receiver.hpp"
#include "updater_process_manager.hpp"
#include <pqrs/dispatcher.hpp>
#include <pqrs/osx/frontmost_application_monitor.hpp>
#include <pqrs/osx/input_source_monitor.hpp>
#include <pqrs/osx/json_file_monitor.hpp>
#include <pqrs/osx/session.hpp>
#include <pqrs/osx/system_preferences_monitor.hpp>
#include <thread>
namespace krbn {
namespace console_user_server {
class components_manager final : public pqrs::dispatcher::extra::dispatcher_client {
public:
components_manager(const components_manager&) = delete;
components_manager(void) : dispatcher_client() {
//
// version_monitor_
//
version_monitor_ = std::make_unique<krbn::version_monitor>(krbn::constants::get_version_file_path());
version_monitor_->changed.connect([](auto&& version) {
if (auto killer = components_manager_killer::get_shared_components_manager_killer()) {
killer->async_kill();
}
});
//
// session_monitor_
//
session_monitor_ = std::make_unique<pqrs::osx::session::monitor>(weak_dispatcher_);
session_monitor_->on_console_changed.connect([this](auto&& on_console) {
if (!on_console) {
receiver_ = nullptr;
stop_grabber_client();
} else {
version_monitor_->async_manual_check();
pqrs::filesystem::create_directory_with_intermediate_directories(
constants::get_user_configuration_directory(),
0700);
receiver_ = nullptr;
stop_grabber_client();
receiver_ = std::make_unique<receiver>();
receiver_->bound.connect([this] {
stop_grabber_client();
start_grabber_client();
});
receiver_->bind_failed.connect([this](auto&& error_code) {
stop_grabber_client();
});
receiver_->closed.connect([this] {
stop_grabber_client();
});
receiver_->async_start();
}
});
}
virtual ~components_manager(void) {
detach_from_dispatcher([this] {
stop_grabber_client();
session_monitor_ = nullptr;
receiver_ = nullptr;
grabber_state_json_file_monitor_ = nullptr;
observer_state_json_file_monitor_ = nullptr;
kextd_state_json_file_monitor_ = nullptr;
version_monitor_ = nullptr;
});
}
void async_start(void) {
enqueue_to_dispatcher([this] {
version_monitor_->async_start();
start_state_json_file_monitors();
session_monitor_->async_start(std::chrono::milliseconds(1000));
});
}
private:
void start_state_json_file_monitors(void) {
//
// kextd_state_json_file_monitor_
//
if (!kextd_state_json_file_monitor_) {
kextd_state_json_file_monitor_ = std::make_unique<pqrs::osx::json_file_monitor>(
weak_dispatcher_,
std::vector<std::string>({constants::get_kextd_state_json_file_path()}));
kextd_state_json_file_monitor_->json_file_changed.connect([](auto&& changed_file_path, auto&& json) {
if (json) {
try {
if (json->at("kext_load_result").template get<std::string>() == "kOSKextReturnSystemPolicy") {
application_launcher::launch_preferences();
}
} catch (std::exception& e) {
logger::get_logger()->error("karabiner_kextd_state.json error: {0}", e.what());
}
}
});
kextd_state_json_file_monitor_->async_start();
}
//
// observer_state_json_file_monitor_
//
if (!observer_state_json_file_monitor_) {
observer_state_json_file_monitor_ = std::make_unique<pqrs::osx::json_file_monitor>(
weak_dispatcher_,
std::vector<std::string>({constants::get_observer_state_json_file_path()}));
observer_state_json_file_monitor_->json_file_changed.connect([](auto&& changed_file_path, auto&& json) {
if (json) {
try {
if (!json->at("hid_device_open_permitted").template get<bool>()) {
application_launcher::launch_preferences();
}
} catch (std::exception& e) {
logger::get_logger()->error("karabiner_observer_state.json error: {0}", e.what());
}
}
});
observer_state_json_file_monitor_->async_start();
}
//
// grabber_state_json_file_monitor_
//
if (!grabber_state_json_file_monitor_) {
grabber_state_json_file_monitor_ = std::make_unique<pqrs::osx::json_file_monitor>(
weak_dispatcher_,
std::vector<std::string>({constants::get_grabber_state_json_file_path()}));
grabber_state_json_file_monitor_->json_file_changed.connect([](auto&& changed_file_path, auto&& json) {
if (json) {
try {
if (!json->at("hid_device_open_permitted").template get<bool>()) {
application_launcher::launch_preferences();
}
} catch (std::exception& e) {
logger::get_logger()->error("karabiner_grabber_state.json error: {0}", e.what());
}
}
});
grabber_state_json_file_monitor_->async_start();
}
}
void start_grabber_client(void) {
if (grabber_client_) {
return;
}
grabber_client_ = std::make_shared<grabber_client>();
grabber_client_->connected.connect([this] {
version_monitor_->async_manual_check();
if (grabber_client_) {
grabber_client_->async_connect_console_user_server();
}
stop_child_components();
start_child_components();
});
grabber_client_->connect_failed.connect([this](auto&& error_code) {
version_monitor_->async_manual_check();
stop_child_components();
});
grabber_client_->closed.connect([this] {
version_monitor_->async_manual_check();
stop_child_components();
});
grabber_client_->async_start();
}
void stop_grabber_client(void) {
grabber_client_ = nullptr;
stop_child_components();
}
void start_child_components(void) {
configuration_monitor_ = std::make_shared<configuration_monitor>(constants::get_user_core_configuration_file_path());
// menu_process_manager_
menu_process_manager_ = std::make_unique<menu_process_manager>(configuration_monitor_);
// Run NotificationWindow
application_launcher::launch_notification_window();
// updater_process_manager_
updater_process_manager_ = std::make_unique<updater_process_manager>(configuration_monitor_);
// system_preferences_monitor_
system_preferences_monitor_ = std::make_unique<pqrs::osx::system_preferences_monitor>(weak_dispatcher_);
system_preferences_monitor_->system_preferences_changed.connect([this](auto&& properties_ptr) {
if (grabber_client_) {
grabber_client_->async_system_preferences_updated(properties_ptr);
}
});
system_preferences_monitor_->async_start(std::chrono::milliseconds(3000));
// frontmost_application_monitor_
frontmost_application_monitor_ = std::make_unique<pqrs::osx::frontmost_application_monitor::monitor>(weak_dispatcher_);
frontmost_application_monitor_->frontmost_application_changed.connect([this](auto&& application_ptr) {
if (application_ptr) {
if (application_ptr->get_bundle_identifier() == "org.pqrs.Karabiner.EventViewer" ||
application_ptr->get_bundle_identifier() == "org.pqrs.Karabiner-EventViewer") {
return;
}
if (grabber_client_) {
grabber_client_->async_frontmost_application_changed(application_ptr);
}
}
});
frontmost_application_monitor_->async_start();
// input_source_monitor_
input_source_monitor_ = std::make_unique<pqrs::osx::input_source_monitor>(
pqrs::dispatcher::extra::get_shared_dispatcher());
input_source_monitor_->input_source_changed.connect([this](auto&& input_source_ptr) {
if (input_source_ptr && grabber_client_) {
auto properties = std::make_shared<pqrs::osx::input_source::properties>(*input_source_ptr);
grabber_client_->async_input_source_changed(properties);
}
});
input_source_monitor_->async_start();
// Start configuration_monitor_
configuration_monitor_->async_start();
}
void stop_child_components(void) {
menu_process_manager_ = nullptr;
updater_process_manager_ = nullptr;
system_preferences_monitor_ = nullptr;
frontmost_application_monitor_ = nullptr;
input_source_monitor_ = nullptr;
configuration_monitor_ = nullptr;
}
// Core components
std::unique_ptr<version_monitor> version_monitor_;
std::unique_ptr<pqrs::osx::json_file_monitor> kextd_state_json_file_monitor_;
std::unique_ptr<pqrs::osx::json_file_monitor> observer_state_json_file_monitor_;
std::unique_ptr<pqrs::osx::json_file_monitor> grabber_state_json_file_monitor_;
std::unique_ptr<pqrs::osx::session::monitor> session_monitor_;
std::unique_ptr<receiver> receiver_;
std::shared_ptr<grabber_client> grabber_client_;
// Child components
std::shared_ptr<configuration_monitor> configuration_monitor_;
std::unique_ptr<menu_process_manager> menu_process_manager_;
std::unique_ptr<updater_process_manager> updater_process_manager_;
std::unique_ptr<pqrs::osx::system_preferences_monitor> system_preferences_monitor_;
// `frontmost_application_monitor` does not work properly in karabiner_grabber after fast user switching.
// Therefore, we have to use `frontmost_application_monitor` in `console_user_server`.
std::unique_ptr<pqrs::osx::frontmost_application_monitor::monitor> frontmost_application_monitor_;
std::unique_ptr<pqrs::osx::input_source_monitor> input_source_monitor_;
};
} // namespace console_user_server
} // namespace krbn
|
#pragma once
// `krbn::console_user_server::components_manager` can be used safely in a multi-threaded environment.
#include "application_launcher.hpp"
#include "components_manager_killer.hpp"
#include "constants.hpp"
#include "grabber_client.hpp"
#include "logger.hpp"
#include "menu_process_manager.hpp"
#include "monitor/configuration_monitor.hpp"
#include "monitor/version_monitor.hpp"
#include "receiver.hpp"
#include "updater_process_manager.hpp"
#include <pqrs/dispatcher.hpp>
#include <pqrs/osx/frontmost_application_monitor.hpp>
#include <pqrs/osx/input_source_monitor.hpp>
#include <pqrs/osx/json_file_monitor.hpp>
#include <pqrs/osx/session.hpp>
#include <pqrs/osx/system_preferences_monitor.hpp>
#include <thread>
namespace krbn {
namespace console_user_server {
class components_manager final : public pqrs::dispatcher::extra::dispatcher_client {
public:
components_manager(const components_manager&) = delete;
components_manager(void) : dispatcher_client() {
//
// version_monitor_
//
version_monitor_ = std::make_unique<krbn::version_monitor>(krbn::constants::get_version_file_path());
version_monitor_->changed.connect([](auto&& version) {
if (auto killer = components_manager_killer::get_shared_components_manager_killer()) {
killer->async_kill();
}
});
//
// session_monitor_
//
session_monitor_ = std::make_unique<pqrs::osx::session::monitor>(weak_dispatcher_);
session_monitor_->on_console_changed.connect([this](auto&& on_console) {
if (!on_console) {
receiver_ = nullptr;
stop_grabber_client();
} else {
version_monitor_->async_manual_check();
pqrs::filesystem::create_directory_with_intermediate_directories(
constants::get_user_configuration_directory(),
0700);
receiver_ = nullptr;
stop_grabber_client();
receiver_ = std::make_unique<receiver>();
receiver_->bound.connect([this] {
stop_grabber_client();
start_grabber_client();
});
receiver_->bind_failed.connect([this](auto&& error_code) {
stop_grabber_client();
});
receiver_->closed.connect([this] {
stop_grabber_client();
});
receiver_->async_start();
}
});
}
virtual ~components_manager(void) {
detach_from_dispatcher([this] {
stop_grabber_client();
session_monitor_ = nullptr;
receiver_ = nullptr;
grabber_state_json_file_monitor_ = nullptr;
observer_state_json_file_monitor_ = nullptr;
kextd_state_json_file_monitor_ = nullptr;
version_monitor_ = nullptr;
});
}
void async_start(void) {
enqueue_to_dispatcher([this] {
version_monitor_->async_start();
start_state_json_file_monitors();
session_monitor_->async_start(std::chrono::milliseconds(1000));
});
}
private:
void start_state_json_file_monitors(void) {
//
// kextd_state_json_file_monitor_
//
if (!kextd_state_json_file_monitor_) {
kextd_state_json_file_monitor_ = std::make_unique<pqrs::osx::json_file_monitor>(
weak_dispatcher_,
std::vector<std::string>({constants::get_kextd_state_json_file_path()}));
kextd_state_json_file_monitor_->json_file_changed.connect([](auto&& changed_file_path, auto&& json) {
if (json) {
try {
if (json->at("kext_load_result").template get<std::string>() == "kOSKextReturnSystemPolicy") {
application_launcher::launch_preferences();
}
} catch (std::exception& e) {
logger::get_logger()->error("karabiner_kextd_state.json error: {0}", e.what());
}
}
});
kextd_state_json_file_monitor_->async_start();
}
//
// observer_state_json_file_monitor_
//
if (!observer_state_json_file_monitor_) {
observer_state_json_file_monitor_ = std::make_unique<pqrs::osx::json_file_monitor>(
weak_dispatcher_,
std::vector<std::string>({constants::get_observer_state_json_file_path()}));
observer_state_json_file_monitor_->json_file_changed.connect([](auto&& changed_file_path, auto&& json) {
if (json) {
try {
if (!json->at("hid_device_open_permitted").template get<bool>()) {
application_launcher::launch_preferences();
}
} catch (std::exception& e) {
logger::get_logger()->error("karabiner_observer_state.json error: {0}", e.what());
}
}
});
observer_state_json_file_monitor_->async_start();
}
//
// grabber_state_json_file_monitor_
//
if (!grabber_state_json_file_monitor_) {
grabber_state_json_file_monitor_ = std::make_unique<pqrs::osx::json_file_monitor>(
weak_dispatcher_,
std::vector<std::string>({constants::get_grabber_state_json_file_path()}));
grabber_state_json_file_monitor_->json_file_changed.connect([](auto&& changed_file_path, auto&& json) {
if (json) {
try {
if (!json->at("hid_device_open_permitted").template get<bool>()) {
application_launcher::launch_preferences();
}
} catch (std::exception& e) {
logger::get_logger()->error("karabiner_grabber_state.json error: {0}", e.what());
}
}
});
grabber_state_json_file_monitor_->async_start();
}
}
void start_grabber_client(void) {
if (grabber_client_) {
return;
}
grabber_client_ = std::make_shared<grabber_client>();
grabber_client_->connected.connect([this] {
version_monitor_->async_manual_check();
if (grabber_client_) {
grabber_client_->async_connect_console_user_server();
}
stop_child_components();
start_child_components();
});
grabber_client_->connect_failed.connect([this](auto&& error_code) {
version_monitor_->async_manual_check();
stop_child_components();
});
grabber_client_->closed.connect([this] {
version_monitor_->async_manual_check();
stop_child_components();
});
grabber_client_->async_start();
}
void stop_grabber_client(void) {
grabber_client_ = nullptr;
stop_child_components();
}
void start_child_components(void) {
configuration_monitor_ = std::make_shared<configuration_monitor>(constants::get_user_core_configuration_file_path());
// menu_process_manager_
menu_process_manager_ = std::make_unique<menu_process_manager>(configuration_monitor_);
// Run NotificationWindow
application_launcher::launch_notification_window();
// Run MultitouchExtension
application_launcher::kill_multitouch_extension();
application_launcher::launch_multitouch_extension(true);
// updater_process_manager_
updater_process_manager_ = std::make_unique<updater_process_manager>(configuration_monitor_);
// system_preferences_monitor_
system_preferences_monitor_ = std::make_unique<pqrs::osx::system_preferences_monitor>(weak_dispatcher_);
system_preferences_monitor_->system_preferences_changed.connect([this](auto&& properties_ptr) {
if (grabber_client_) {
grabber_client_->async_system_preferences_updated(properties_ptr);
}
});
system_preferences_monitor_->async_start(std::chrono::milliseconds(3000));
// frontmost_application_monitor_
frontmost_application_monitor_ = std::make_unique<pqrs::osx::frontmost_application_monitor::monitor>(weak_dispatcher_);
frontmost_application_monitor_->frontmost_application_changed.connect([this](auto&& application_ptr) {
if (application_ptr) {
if (application_ptr->get_bundle_identifier() == "org.pqrs.Karabiner.EventViewer" ||
application_ptr->get_bundle_identifier() == "org.pqrs.Karabiner-EventViewer") {
return;
}
if (grabber_client_) {
grabber_client_->async_frontmost_application_changed(application_ptr);
}
}
});
frontmost_application_monitor_->async_start();
// input_source_monitor_
input_source_monitor_ = std::make_unique<pqrs::osx::input_source_monitor>(
pqrs::dispatcher::extra::get_shared_dispatcher());
input_source_monitor_->input_source_changed.connect([this](auto&& input_source_ptr) {
if (input_source_ptr && grabber_client_) {
auto properties = std::make_shared<pqrs::osx::input_source::properties>(*input_source_ptr);
grabber_client_->async_input_source_changed(properties);
}
});
input_source_monitor_->async_start();
// Start configuration_monitor_
configuration_monitor_->async_start();
}
void stop_child_components(void) {
menu_process_manager_ = nullptr;
updater_process_manager_ = nullptr;
system_preferences_monitor_ = nullptr;
frontmost_application_monitor_ = nullptr;
input_source_monitor_ = nullptr;
configuration_monitor_ = nullptr;
}
// Core components
std::unique_ptr<version_monitor> version_monitor_;
std::unique_ptr<pqrs::osx::json_file_monitor> kextd_state_json_file_monitor_;
std::unique_ptr<pqrs::osx::json_file_monitor> observer_state_json_file_monitor_;
std::unique_ptr<pqrs::osx::json_file_monitor> grabber_state_json_file_monitor_;
std::unique_ptr<pqrs::osx::session::monitor> session_monitor_;
std::unique_ptr<receiver> receiver_;
std::shared_ptr<grabber_client> grabber_client_;
// Child components
std::shared_ptr<configuration_monitor> configuration_monitor_;
std::unique_ptr<menu_process_manager> menu_process_manager_;
std::unique_ptr<updater_process_manager> updater_process_manager_;
std::unique_ptr<pqrs::osx::system_preferences_monitor> system_preferences_monitor_;
// `frontmost_application_monitor` does not work properly in karabiner_grabber after fast user switching.
// Therefore, we have to use `frontmost_application_monitor` in `console_user_server`.
std::unique_ptr<pqrs::osx::frontmost_application_monitor::monitor> frontmost_application_monitor_;
std::unique_ptr<pqrs::osx::input_source_monitor> input_source_monitor_;
};
} // namespace console_user_server
} // namespace krbn
|
use launch_multitouch_extension
|
use launch_multitouch_extension
|
C++
|
unlicense
|
tekezo/Karabiner-Elements,tekezo/Karabiner-Elements,tekezo/Karabiner-Elements,tekezo/Karabiner-Elements
|
df6c6b5b42e8a9ff9cb6c8d4b9e713e2f1e71c4d
|
tensorflow/compiler/mlir/tensorflow/transforms/optimize.cc
|
tensorflow/compiler/mlir/tensorflow/transforms/optimize.cc
|
/* Copyright 2019 The TensorFlow Authors. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
==============================================================================*/
#include <iostream>
#include "mlir/Dialect/StandardOps/Ops.h" // TF:llvm-project
#include "mlir/IR/Attributes.h" // TF:llvm-project
#include "mlir/IR/Builders.h" // TF:llvm-project
#include "mlir/IR/Operation.h" // TF:llvm-project
#include "mlir/IR/PatternMatch.h" // TF:llvm-project
#include "mlir/Pass/Pass.h" // TF:llvm-project
#include "mlir/Pass/PassManager.h" // TF:llvm-project
#include "mlir/Transforms/Passes.h" // TF:llvm-project
#include "tensorflow/compiler/mlir/lite/utils/validators.h"
#include "tensorflow/compiler/mlir/tensorflow/ir/tf_ops.h"
#include "tensorflow/compiler/mlir/tensorflow/transforms/passes.h"
namespace mlir {
namespace TF {
namespace {
#include "tensorflow/compiler/mlir/tensorflow/transforms/generated_optimize.inc"
// Canonicalize operations in functions.
struct TFOptimizePass : public FunctionPass<TFOptimizePass> {
void runOnFunction() override {
OwningRewritePatternList patterns;
auto func = getFunction();
populateWithGenerated(&getContext(), &patterns);
applyPatternsGreedily(func, patterns);
}
};
} // namespace
// NOLINTNEXTLINE - MLIR contract is pass by mutable reference.
void CreateTFStandardPipeline(OpPassManager &pm,
const StandardPipelineOptions &options) {
OpPassManager &func_pm = pm.nest<FuncOp>();
// First operates on the executor dialect:
// - eliminate trivial switch/merge
// - fuse islands as much as possible.
// - materialize the eventual "pass-through" ops by inlining their content.
func_pm.addPass(tf_executor::CreateSwitchFoldPass());
func_pm.addPass(tf_executor::CreateTFExecutorIslandCoarseningPass());
func_pm.addPass(CreateMaterializePassthroughOpPass());
// Hopefully there is a single island left, or there wasn't any to begin with.
// We now run the optimizer which operates mostly inside islands.
func_pm.addPass(createCanonicalizerPass());
if (options.enable_inliner) {
pm.addPass(createInlinerPass());
}
pm.addPass(createSymbolDCEPass());
pm.addPass(CreateTFShapeInferencePass());
pm.addNestedPass<FuncOp>(CreateTFOptimizePass());
pm.addNestedPass<FuncOp>(createCSEPass());
}
std::unique_ptr<OpPassBase<FuncOp>> CreateTFOptimizePass() {
return std::make_unique<TFOptimizePass>();
}
static PassRegistration<TFOptimizePass> pass("tf-optimize", "Optimizes TF.");
// Registers a pipeline builder function for the default canonicalize/optimizer.
static mlir::PassPipelineRegistration<StandardPipelineOptions> pipeline(
"tf-standard-pipeline",
"Run all the passes involved in transforming/optimizing the graph after "
"importing into MLIR, without any target specialization.",
CreateTFStandardPipeline);
} // namespace TF
} // namespace mlir
|
/* Copyright 2019 The TensorFlow Authors. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
==============================================================================*/
#include <iostream>
#include "mlir/Dialect/StandardOps/Ops.h" // TF:llvm-project
#include "mlir/IR/Attributes.h" // TF:llvm-project
#include "mlir/IR/Builders.h" // TF:llvm-project
#include "mlir/IR/Operation.h" // TF:llvm-project
#include "mlir/IR/PatternMatch.h" // TF:llvm-project
#include "mlir/Pass/Pass.h" // TF:llvm-project
#include "mlir/Pass/PassManager.h" // TF:llvm-project
#include "mlir/Transforms/Passes.h" // TF:llvm-project
#include "tensorflow/compiler/mlir/lite/utils/validators.h"
#include "tensorflow/compiler/mlir/tensorflow/ir/tf_ops.h"
#include "tensorflow/compiler/mlir/tensorflow/transforms/passes.h"
namespace mlir {
namespace TF {
namespace {
#include "tensorflow/compiler/mlir/tensorflow/transforms/generated_optimize.inc"
// Canonicalize operations in functions.
struct TFOptimizePass : public FunctionPass<TFOptimizePass> {
void runOnFunction() override {
OwningRewritePatternList patterns;
auto func = getFunction();
populateWithGenerated(&getContext(), &patterns);
applyPatternsGreedily(func, patterns);
}
};
} // namespace
// NOLINTNEXTLINE - MLIR contract is pass by mutable reference.
void CreateTFStandardPipeline(OpPassManager &pm,
const StandardPipelineOptions &options) {
OpPassManager &func_pm = pm.nest<FuncOp>();
// First operates on the executor dialect:
// - eliminate trivial switch/merge.
// - remove dead islands.
// - fuse islands as much as possible.
// - materialize the eventual "pass-through" ops by inlining their content.
func_pm.addPass(tf_executor::CreateSwitchFoldPass());
func_pm.addPass(tf_executor::CreateTFExecutorGraphPruningPass());
func_pm.addPass(tf_executor::CreateTFExecutorIslandCoarseningPass());
func_pm.addPass(CreateMaterializePassthroughOpPass());
// Hopefully there is a single island left, or there wasn't any to begin with.
// We now run the optimizer which operates mostly inside islands.
func_pm.addPass(createCanonicalizerPass());
if (options.enable_inliner) {
pm.addPass(createInlinerPass());
}
pm.addPass(createSymbolDCEPass());
pm.addPass(CreateTFShapeInferencePass());
pm.addNestedPass<FuncOp>(CreateTFOptimizePass());
pm.addNestedPass<FuncOp>(createCSEPass());
}
std::unique_ptr<OpPassBase<FuncOp>> CreateTFOptimizePass() {
return std::make_unique<TFOptimizePass>();
}
static PassRegistration<TFOptimizePass> pass("tf-optimize", "Optimizes TF.");
// Registers a pipeline builder function for the default canonicalize/optimizer.
static mlir::PassPipelineRegistration<StandardPipelineOptions> pipeline(
"tf-standard-pipeline",
"Run all the passes involved in transforming/optimizing the graph after "
"importing into MLIR, without any target specialization.",
CreateTFStandardPipeline);
} // namespace TF
} // namespace mlir
|
Add TFExecutorGraphPruning pass to TFStandardPipeline.
|
[TF:MLIR] Add TFExecutorGraphPruning pass to TFStandardPipeline.
This is to remove dead islands before running TFExecutorIslandCoarsening pass.
PiperOrigin-RevId: 294709549
Change-Id: I8ed32b1689ecb1c4a478ef44e370b0143fe6d6ef
|
C++
|
apache-2.0
|
frreiss/tensorflow-fred,renyi533/tensorflow,yongtang/tensorflow,annarev/tensorflow,frreiss/tensorflow-fred,tensorflow/tensorflow-pywrap_tf_optimizer,sarvex/tensorflow,gautam1858/tensorflow,gunan/tensorflow,gautam1858/tensorflow,annarev/tensorflow,renyi533/tensorflow,Intel-tensorflow/tensorflow,gunan/tensorflow,gautam1858/tensorflow,gautam1858/tensorflow,annarev/tensorflow,Intel-Corporation/tensorflow,gunan/tensorflow,Intel-tensorflow/tensorflow,tensorflow/tensorflow,aam-at/tensorflow,annarev/tensorflow,Intel-Corporation/tensorflow,aam-at/tensorflow,davidzchen/tensorflow,petewarden/tensorflow,Intel-Corporation/tensorflow,gautam1858/tensorflow,tensorflow/tensorflow-pywrap_tf_optimizer,aam-at/tensorflow,tensorflow/tensorflow,paolodedios/tensorflow,xzturn/tensorflow,tensorflow/tensorflow-pywrap_saved_model,freedomtan/tensorflow,gunan/tensorflow,Intel-tensorflow/tensorflow,frreiss/tensorflow-fred,renyi533/tensorflow,aam-at/tensorflow,tensorflow/tensorflow,karllessard/tensorflow,yongtang/tensorflow,Intel-tensorflow/tensorflow,tensorflow/tensorflow,tensorflow/tensorflow-pywrap_tf_optimizer,renyi533/tensorflow,gunan/tensorflow,annarev/tensorflow,davidzchen/tensorflow,frreiss/tensorflow-fred,aam-at/tensorflow,tensorflow/tensorflow-pywrap_tf_optimizer,davidzchen/tensorflow,aam-at/tensorflow,davidzchen/tensorflow,freedomtan/tensorflow,gautam1858/tensorflow,xzturn/tensorflow,davidzchen/tensorflow,karllessard/tensorflow,cxxgtxy/tensorflow,tensorflow/tensorflow-pywrap_tf_optimizer,xzturn/tensorflow,tensorflow/tensorflow-experimental_link_static_libraries_once,paolodedios/tensorflow,karllessard/tensorflow,Intel-Corporation/tensorflow,tensorflow/tensorflow,tensorflow/tensorflow-pywrap_saved_model,sarvex/tensorflow,freedomtan/tensorflow,yongtang/tensorflow,tensorflow/tensorflow-pywrap_tf_optimizer,davidzchen/tensorflow,petewarden/tensorflow,freedomtan/tensorflow,Intel-tensorflow/tensorflow,Intel-Corporation/tensorflow,Intel-tensorflow/tensorflow,gautam1858/tensorflow,aldian/tensorflow,tensorflow/tensorflow-pywrap_saved_model,sarvex/tensorflow,renyi533/tensorflow,freedomtan/tensorflow,petewarden/tensorflow,petewarden/tensorflow,sarvex/tensorflow,tensorflow/tensorflow-pywrap_saved_model,gautam1858/tensorflow,aldian/tensorflow,xzturn/tensorflow,aam-at/tensorflow,freedomtan/tensorflow,Intel-tensorflow/tensorflow,aam-at/tensorflow,karllessard/tensorflow,frreiss/tensorflow-fred,annarev/tensorflow,renyi533/tensorflow,Intel-Corporation/tensorflow,freedomtan/tensorflow,frreiss/tensorflow-fred,tensorflow/tensorflow,yongtang/tensorflow,Intel-tensorflow/tensorflow,gunan/tensorflow,davidzchen/tensorflow,annarev/tensorflow,paolodedios/tensorflow,paolodedios/tensorflow,davidzchen/tensorflow,yongtang/tensorflow,freedomtan/tensorflow,aam-at/tensorflow,frreiss/tensorflow-fred,karllessard/tensorflow,aam-at/tensorflow,xzturn/tensorflow,aldian/tensorflow,tensorflow/tensorflow-pywrap_tf_optimizer,davidzchen/tensorflow,gautam1858/tensorflow,annarev/tensorflow,tensorflow/tensorflow-pywrap_tf_optimizer,paolodedios/tensorflow,Intel-tensorflow/tensorflow,tensorflow/tensorflow-experimental_link_static_libraries_once,renyi533/tensorflow,davidzchen/tensorflow,cxxgtxy/tensorflow,renyi533/tensorflow,frreiss/tensorflow-fred,karllessard/tensorflow,tensorflow/tensorflow-pywrap_tf_optimizer,paolodedios/tensorflow,paolodedios/tensorflow,karllessard/tensorflow,xzturn/tensorflow,aam-at/tensorflow,yongtang/tensorflow,cxxgtxy/tensorflow,petewarden/tensorflow,freedomtan/tensorflow,tensorflow/tensorflow-pywrap_saved_model,xzturn/tensorflow,renyi533/tensorflow,karllessard/tensorflow,tensorflow/tensorflow-pywrap_tf_optimizer,gunan/tensorflow,karllessard/tensorflow,Intel-tensorflow/tensorflow,gunan/tensorflow,yongtang/tensorflow,aldian/tensorflow,frreiss/tensorflow-fred,paolodedios/tensorflow,annarev/tensorflow,xzturn/tensorflow,tensorflow/tensorflow,yongtang/tensorflow,tensorflow/tensorflow,petewarden/tensorflow,frreiss/tensorflow-fred,tensorflow/tensorflow-experimental_link_static_libraries_once,xzturn/tensorflow,paolodedios/tensorflow,Intel-Corporation/tensorflow,sarvex/tensorflow,tensorflow/tensorflow-pywrap_saved_model,aam-at/tensorflow,freedomtan/tensorflow,cxxgtxy/tensorflow,tensorflow/tensorflow-pywrap_saved_model,paolodedios/tensorflow,petewarden/tensorflow,petewarden/tensorflow,renyi533/tensorflow,Intel-Corporation/tensorflow,yongtang/tensorflow,paolodedios/tensorflow,tensorflow/tensorflow-experimental_link_static_libraries_once,tensorflow/tensorflow,tensorflow/tensorflow-experimental_link_static_libraries_once,sarvex/tensorflow,gunan/tensorflow,renyi533/tensorflow,gunan/tensorflow,cxxgtxy/tensorflow,tensorflow/tensorflow-experimental_link_static_libraries_once,davidzchen/tensorflow,gautam1858/tensorflow,frreiss/tensorflow-fred,aldian/tensorflow,xzturn/tensorflow,cxxgtxy/tensorflow,tensorflow/tensorflow-pywrap_tf_optimizer,tensorflow/tensorflow,tensorflow/tensorflow-experimental_link_static_libraries_once,Intel-tensorflow/tensorflow,freedomtan/tensorflow,tensorflow/tensorflow-experimental_link_static_libraries_once,tensorflow/tensorflow-pywrap_saved_model,sarvex/tensorflow,yongtang/tensorflow,tensorflow/tensorflow-pywrap_saved_model,gautam1858/tensorflow,annarev/tensorflow,sarvex/tensorflow,karllessard/tensorflow,frreiss/tensorflow-fred,tensorflow/tensorflow-pywrap_saved_model,tensorflow/tensorflow-experimental_link_static_libraries_once,cxxgtxy/tensorflow,karllessard/tensorflow,renyi533/tensorflow,aldian/tensorflow,annarev/tensorflow,tensorflow/tensorflow,aldian/tensorflow,cxxgtxy/tensorflow,tensorflow/tensorflow-pywrap_saved_model,freedomtan/tensorflow,gautam1858/tensorflow,petewarden/tensorflow,tensorflow/tensorflow-experimental_link_static_libraries_once,davidzchen/tensorflow,gunan/tensorflow,petewarden/tensorflow,aldian/tensorflow,xzturn/tensorflow,yongtang/tensorflow,tensorflow/tensorflow-experimental_link_static_libraries_once,xzturn/tensorflow,petewarden/tensorflow,gunan/tensorflow,petewarden/tensorflow
|
024c81a58dfe8b476c4cc181d6357cbab55c70c4
|
tests/auto/quick/qquickaccessible/tst_qquickaccessible.cpp
|
tests/auto/quick/qquickaccessible/tst_qquickaccessible.cpp
|
/****************************************************************************
**
** Copyright (C) 2013 Digia Plc and/or its subsidiary(-ies).
** Contact: http://www.qt-project.org/legal
**
** This file is part of the QtQml module of the Qt Toolkit.
**
** $QT_BEGIN_LICENSE:LGPL$
** Commercial License Usage
** Licensees holding valid commercial Qt licenses may use this file in
** accordance with the commercial license agreement provided with the
** Software or, alternatively, in accordance with the terms contained in
** a written agreement between you and Digia. For licensing terms and
** conditions see http://qt.digia.com/licensing. For further information
** use the contact form at http://qt.digia.com/contact-us.
**
** GNU Lesser General Public License Usage
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 as published by the Free Software
** Foundation and appearing in the file LICENSE.LGPL included in the
** packaging of this file. Please review the following information to
** ensure the GNU Lesser General Public License version 2.1 requirements
** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, Digia gives you certain additional
** rights. These rights are described in the Digia Qt LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
** GNU General Public License Usage
** Alternatively, this file may be used under the terms of the GNU
** General Public License version 3.0 as published by the Free Software
** Foundation and appearing in the file LICENSE.GPL included in the
** packaging of this file. Please review the following information to
** ensure the GNU General Public License version 3.0 requirements will be
** met: http://www.gnu.org/copyleft/gpl.html.
**
**
** $QT_END_LICENSE$
**
****************************************************************************/
#include <QtTest/QtTest>
#include "QtTest/qtestaccessible.h"
#include <QtGui/qaccessible.h>
#include <QtQuick/qquickview.h>
#include <QtQuick/qquickitem.h>
#include <QtQml/qqmlengine.h>
#include <QtQml/qqmlproperty.h>
#include <QtQuick/private/qquickaccessibleattached_p.h>
#include "../../shared/util.h"
#define EXPECT(cond) \
do { \
if (!errorAt && !(cond)) { \
errorAt = __LINE__; \
qWarning("level: %d, middle: %d, role: %d (%s)", treelevel, middle, iface->role(), #cond); \
} \
} while (0)
static int verifyHierarchy(QAccessibleInterface *iface)
{
int errorAt = 0;
static int treelevel = 0; // for error diagnostics
QAccessibleInterface *if2;
++treelevel;
int middle = iface->childCount()/2 + 1;
for (int i = 0; i < iface->childCount() && !errorAt; ++i) {
if2 = iface->child(i);
EXPECT(if2 != 0);
// navigate Ancestor...
QAccessibleInterface *parent = if2->parent();
EXPECT(iface->object() == parent->object());
// verify children...
if (!errorAt)
errorAt = verifyHierarchy(if2);
}
--treelevel;
return errorAt;
}
//TESTED_FILES=
class tst_QQuickAccessible : public QQmlDataTest
{
Q_OBJECT
public:
tst_QQuickAccessible();
virtual ~tst_QQuickAccessible();
private slots:
void commonTests_data();
void commonTests();
void quickAttachedProperties();
void basicPropertiesTest();
void hitTest();
void checkableTest();
};
tst_QQuickAccessible::tst_QQuickAccessible()
{
}
tst_QQuickAccessible::~tst_QQuickAccessible()
{
}
void tst_QQuickAccessible::commonTests_data()
{
QTest::addColumn<QString>("accessibleRoleFileName");
QTest::newRow("StaticText") << "statictext.qml";
QTest::newRow("PushButton") << "pushbutton.qml";
}
void tst_QQuickAccessible::commonTests()
{
QFETCH(QString, accessibleRoleFileName);
qDebug() << "testing" << accessibleRoleFileName;
QQuickView *view = new QQuickView();
// view->setFixedSize(240,320);
view->setSource(testFileUrl(accessibleRoleFileName));
view->show();
// view->setFocus();
QVERIFY(view->rootObject() != 0);
QAccessibleInterface *iface = QAccessible::queryAccessibleInterface(view);
QVERIFY(iface);
delete view;
}
QString eventName(const int ev)
{
switch (ev) {
case 0x0001: return "SoundPlayed";
case 0x0002: return "Alert";
case 0x0003: return "ForegroundChanged";
case 0x0004: return "MenuStart";
case 0x0005: return "MenuEnd";
case 0x0006: return "PopupMenuStart";
case 0x0007: return "PopupMenuEnd";
case 0x000C: return "ContextHelpStart";
case 0x000D: return "ContextHelpEnd";
case 0x000E: return "DragDropStart";
case 0x000F: return "DragDropEnd";
case 0x0010: return "DialogStart";
case 0x0011: return "DialogEnd";
case 0x0012: return "ScrollingStart";
case 0x0013: return "ScrollingEnd";
case 0x0018: return "MenuCommand";
case 0x8000: return "ObjectCreated";
case 0x8001: return "ObjectDestroyed";
case 0x8002: return "ObjectShow";
case 0x8003: return "ObjectHide";
case 0x8004: return "ObjectReorder";
case 0x8005: return "Focus";
case 0x8006: return "Selection";
case 0x8007: return "SelectionAdd";
case 0x8008: return "SelectionRemove";
case 0x8009: return "SelectionWithin";
case 0x800A: return "StateChanged";
case 0x800B: return "LocationChanged";
case 0x800C: return "NameChanged";
case 0x800D: return "DescriptionChanged";
case 0x800E: return "ValueChanged";
case 0x800F: return "ParentChanged";
case 0x80A0: return "HelpChanged";
case 0x80B0: return "DefaultActionChanged";
case 0x80C0: return "AcceleratorChanged";
default: return "Unknown Event";
}
}
void tst_QQuickAccessible::quickAttachedProperties()
{
{
QQmlEngine engine;
QQmlComponent component(&engine);
component.setData("import QtQuick 2.0\nItem {\n"
"}", QUrl());
QObject *object = component.create();
QVERIFY(object != 0);
QObject *attachedObject = QQuickAccessibleAttached::attachedProperties(object);
QCOMPARE(attachedObject, static_cast<QObject*>(0));
delete object;
}
// Attached property
{
QObject parent;
QQuickAccessibleAttached *attachedObj = new QQuickAccessibleAttached(&parent);
attachedObj->name();
QVariant pp = attachedObj->property("name");
QQmlEngine engine;
QQmlComponent component(&engine);
component.setData("import QtQuick 2.0\nItem {\n"
"Accessible.role: Accessible.Button\n"
"}", QUrl());
QObject *object = component.create();
QVERIFY(object != 0);
QObject *attachedObject = QQuickAccessibleAttached::attachedProperties(object);
QVERIFY(attachedObject);
if (attachedObject) {
QVariant p = attachedObject->property("role");
QCOMPARE(p.isNull(), false);
QCOMPARE(p.toInt(), int(QAccessible::PushButton));
p = attachedObject->property("name");
QCOMPARE(p.isNull(), true);
p = attachedObject->property("description");
QCOMPARE(p.isNull(), true);
}
delete object;
}
// Attached property
{
QQmlEngine engine;
QQmlComponent component(&engine);
component.setData("import QtQuick 2.0\nItem {\n"
"Accessible.role: Accessible.Button\n"
"Accessible.name: \"Donald\"\n"
"Accessible.description: \"Duck\"\n"
"}", QUrl());
QObject *object = component.create();
QVERIFY(object != 0);
QObject *attachedObject = QQuickAccessibleAttached::attachedProperties(object);
QVERIFY(attachedObject);
if (attachedObject) {
QVariant p = attachedObject->property("role");
QCOMPARE(p.isNull(), false);
QCOMPARE(p.toInt(), int(QAccessible::PushButton));
p = attachedObject->property("name");
QCOMPARE(p.isNull(), false);
QCOMPARE(p.toString(), QLatin1String("Donald"));
p = attachedObject->property("description");
QCOMPARE(p.isNull(), false);
QCOMPARE(p.toString(), QLatin1String("Duck"));
}
delete object;
}
}
void tst_QQuickAccessible::basicPropertiesTest()
{
QAccessibleInterface *app = QAccessible::queryAccessibleInterface(qApp);
QCOMPARE(app->childCount(), 0);
QQuickView *window = new QQuickView();
window->setSource(testFileUrl("statictext.qml"));
window->show();
QCOMPARE(app->childCount(), 1);
QAccessibleInterface *iface = QAccessible::queryAccessibleInterface(window);
QVERIFY(iface);
QCOMPARE(iface->childCount(), 1);
QAccessibleInterface *item = iface->child(0);
QVERIFY(item);
QCOMPARE(item->childCount(), 2);
QCOMPARE(item->rect().size(), QSize(400, 400));
QCOMPARE(item->role(), QAccessible::Pane);
QCOMPARE(iface->indexOfChild(item), 0);
QAccessibleInterface *text = item->child(0);
QVERIFY(text);
QCOMPARE(text->childCount(), 0);
QCOMPARE(text->text(QAccessible::Name), QLatin1String("Hello Accessibility"));
QCOMPARE(text->rect().size(), QSize(200, 50));
QCOMPARE(text->rect().x(), item->rect().x() + 100);
QCOMPARE(text->rect().y(), item->rect().y() + 20);
QCOMPARE(text->role(), QAccessible::StaticText);
QCOMPARE(item->indexOfChild(text), 0);
QAccessibleInterface *text2 = item->child(1);
QVERIFY(text2);
QCOMPARE(text2->childCount(), 0);
QCOMPARE(text2->text(QAccessible::Name), QLatin1String("The Hello 2 accessible text"));
QCOMPARE(text2->rect().size(), QSize(100, 40));
QCOMPARE(text2->rect().x(), item->rect().x() + 100);
QCOMPARE(text2->rect().y(), item->rect().y() + 40);
QCOMPARE(text2->role(), QAccessible::StaticText);
QCOMPARE(item->indexOfChild(text2), 1);
QCOMPARE(iface->indexOfChild(text2), -1);
QCOMPARE(text2->indexOfChild(item), -1);
delete window;
}
QAccessibleInterface *topLevelChildAt(QAccessibleInterface *iface, int x, int y)
{
QAccessibleInterface *child = iface->childAt(x, y);
if (!child)
return 0;
QAccessibleInterface *childOfChild;
while ( ( childOfChild = child->childAt(x, y)) ) {
child = childOfChild;
}
return child;
}
void tst_QQuickAccessible::hitTest()
{
QQuickView *window = new QQuickView;
window->setSource(testFileUrl("hittest.qml"));
window->show();
QAccessibleInterface *windowIface = QAccessible::queryAccessibleInterface(window);
QVERIFY(windowIface);
QAccessibleInterface *rootItem = windowIface->child(0);
QRect rootRect = rootItem->rect();
// check the root item from app
QAccessibleInterface *appIface = QAccessible::queryAccessibleInterface(qApp);
QVERIFY(appIface);
QAccessibleInterface *itemHit(appIface->childAt(rootRect.x() + 200, rootRect.y() + 50));
QVERIFY(itemHit);
QCOMPARE(rootRect, itemHit->rect());
// hit rect1
QAccessibleInterface *rect1(rootItem->child(0));
QRect rect1Rect = rect1->rect();
QAccessibleInterface *rootItemIface = rootItem->childAt(rect1Rect.x() + 10, rect1Rect.y() + 10);
QVERIFY(rootItemIface);
QCOMPARE(rect1Rect, rootItemIface->rect());
QCOMPARE(rootItemIface->text(QAccessible::Name), QLatin1String("rect1"));
// should also work from top level (app)
QAccessibleInterface *app(QAccessible::queryAccessibleInterface(qApp));
QAccessibleInterface *itemHit2(topLevelChildAt(app, rect1Rect.x() + 10, rect1Rect.y() + 10));
QVERIFY(itemHit2);
QCOMPARE(itemHit2->rect(), rect1Rect);
QCOMPARE(itemHit2->text(QAccessible::Name), QLatin1String("rect1"));
// hit rect201
QAccessibleInterface *rect2(rootItem->child(1));
QVERIFY(rect2);
// FIXME: This is seems broken on mac
// QCOMPARE(rect2->rect().translated(rootItem->rect().x(), rootItem->rect().y()), QRect(0, 50, 100, 100));
QAccessibleInterface *rect20(rect2->child(0));
QVERIFY(rect20);
QAccessibleInterface *rect201(rect20->child(1));
QVERIFY(rect201);
QRect rect201Rect = rect201->rect();
rootItemIface = windowIface->childAt(rect201Rect.x() + 20, rect201Rect.y() + 20);
QVERIFY(rootItemIface);
QCOMPARE(rootItemIface->rect(), rect201Rect);
QCOMPARE(rootItemIface->text(QAccessible::Name), QLatin1String("rect201"));
delete window;
}
void tst_QQuickAccessible::checkableTest()
{
QQuickView *window = new QQuickView();
window->setSource(testFileUrl("checkbuttons.qml"));
window->show();
QAccessibleInterface *iface = QAccessible::queryAccessibleInterface(window);
QVERIFY(iface);
QAccessibleInterface *root = iface->child(0);
QAccessibleInterface *button1 = root->child(0);
QCOMPARE(button1->role(), QAccessible::Button);
QVERIFY(!(button1->state().checked));
QVERIFY(!(button1->state().checkable));
QAccessibleInterface *button2 = root->child(1);
QVERIFY(!(button2->state().checked));
QVERIFY(button2->state().checkable);
QAccessibleInterface *button3 = root->child(2);
QVERIFY(button3->state().checked);
QVERIFY(button3->state().checkable);
QAccessibleInterface *checkBox1 = root->child(3);
QCOMPARE(checkBox1->role(), QAccessible::CheckBox);
QVERIFY((checkBox1->state().checked));
QVERIFY(checkBox1->state().checkable);
QAccessibleInterface *checkBox2 = root->child(4);
QVERIFY(!(checkBox2->state().checked));
QVERIFY(checkBox2->state().checkable);
}
QTEST_MAIN(tst_QQuickAccessible)
#include "tst_qquickaccessible.moc"
|
/****************************************************************************
**
** Copyright (C) 2013 Digia Plc and/or its subsidiary(-ies).
** Contact: http://www.qt-project.org/legal
**
** This file is part of the QtQml module of the Qt Toolkit.
**
** $QT_BEGIN_LICENSE:LGPL$
** Commercial License Usage
** Licensees holding valid commercial Qt licenses may use this file in
** accordance with the commercial license agreement provided with the
** Software or, alternatively, in accordance with the terms contained in
** a written agreement between you and Digia. For licensing terms and
** conditions see http://qt.digia.com/licensing. For further information
** use the contact form at http://qt.digia.com/contact-us.
**
** GNU Lesser General Public License Usage
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 as published by the Free Software
** Foundation and appearing in the file LICENSE.LGPL included in the
** packaging of this file. Please review the following information to
** ensure the GNU Lesser General Public License version 2.1 requirements
** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, Digia gives you certain additional
** rights. These rights are described in the Digia Qt LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
** GNU General Public License Usage
** Alternatively, this file may be used under the terms of the GNU
** General Public License version 3.0 as published by the Free Software
** Foundation and appearing in the file LICENSE.GPL included in the
** packaging of this file. Please review the following information to
** ensure the GNU General Public License version 3.0 requirements will be
** met: http://www.gnu.org/copyleft/gpl.html.
**
**
** $QT_END_LICENSE$
**
****************************************************************************/
#include <QtTest/QtTest>
#include "QtTest/qtestaccessible.h"
#include <QtGui/qaccessible.h>
#include <QtQuick/qquickview.h>
#include <QtQuick/qquickitem.h>
#include <QtQml/qqmlengine.h>
#include <QtQml/qqmlproperty.h>
#include <QtQuick/private/qquickaccessibleattached_p.h>
#include "../../shared/util.h"
#define EXPECT(cond) \
do { \
if (!errorAt && !(cond)) { \
errorAt = __LINE__; \
qWarning("level: %d, middle: %d, role: %d (%s)", treelevel, middle, iface->role(), #cond); \
} \
} while (0)
static int verifyHierarchy(QAccessibleInterface *iface)
{
int errorAt = 0;
static int treelevel = 0; // for error diagnostics
QAccessibleInterface *if2;
++treelevel;
int middle = iface->childCount()/2 + 1;
for (int i = 0; i < iface->childCount() && !errorAt; ++i) {
if2 = iface->child(i);
EXPECT(if2 != 0);
// navigate Ancestor...
QAccessibleInterface *parent = if2->parent();
EXPECT(iface->object() == parent->object());
// verify children...
if (!errorAt)
errorAt = verifyHierarchy(if2);
}
--treelevel;
return errorAt;
}
//TESTED_FILES=
class tst_QQuickAccessible : public QQmlDataTest
{
Q_OBJECT
public:
tst_QQuickAccessible();
virtual ~tst_QQuickAccessible();
private slots:
void commonTests_data();
void commonTests();
void quickAttachedProperties();
void basicPropertiesTest();
void hitTest();
void checkableTest();
};
tst_QQuickAccessible::tst_QQuickAccessible()
{
}
tst_QQuickAccessible::~tst_QQuickAccessible()
{
}
void tst_QQuickAccessible::commonTests_data()
{
QTest::addColumn<QString>("accessibleRoleFileName");
QTest::newRow("StaticText") << "statictext.qml";
QTest::newRow("PushButton") << "pushbutton.qml";
}
void tst_QQuickAccessible::commonTests()
{
QFETCH(QString, accessibleRoleFileName);
qDebug() << "testing" << accessibleRoleFileName;
QQuickView *view = new QQuickView();
// view->setFixedSize(240,320);
view->setSource(testFileUrl(accessibleRoleFileName));
view->show();
// view->setFocus();
QVERIFY(view->rootObject() != 0);
QAccessibleInterface *iface = QAccessible::queryAccessibleInterface(view);
QVERIFY(iface);
delete view;
}
QString eventName(const int ev)
{
switch (ev) {
case 0x0001: return "SoundPlayed";
case 0x0002: return "Alert";
case 0x0003: return "ForegroundChanged";
case 0x0004: return "MenuStart";
case 0x0005: return "MenuEnd";
case 0x0006: return "PopupMenuStart";
case 0x0007: return "PopupMenuEnd";
case 0x000C: return "ContextHelpStart";
case 0x000D: return "ContextHelpEnd";
case 0x000E: return "DragDropStart";
case 0x000F: return "DragDropEnd";
case 0x0010: return "DialogStart";
case 0x0011: return "DialogEnd";
case 0x0012: return "ScrollingStart";
case 0x0013: return "ScrollingEnd";
case 0x0018: return "MenuCommand";
case 0x8000: return "ObjectCreated";
case 0x8001: return "ObjectDestroyed";
case 0x8002: return "ObjectShow";
case 0x8003: return "ObjectHide";
case 0x8004: return "ObjectReorder";
case 0x8005: return "Focus";
case 0x8006: return "Selection";
case 0x8007: return "SelectionAdd";
case 0x8008: return "SelectionRemove";
case 0x8009: return "SelectionWithin";
case 0x800A: return "StateChanged";
case 0x800B: return "LocationChanged";
case 0x800C: return "NameChanged";
case 0x800D: return "DescriptionChanged";
case 0x800E: return "ValueChanged";
case 0x800F: return "ParentChanged";
case 0x80A0: return "HelpChanged";
case 0x80B0: return "DefaultActionChanged";
case 0x80C0: return "AcceleratorChanged";
default: return "Unknown Event";
}
}
void tst_QQuickAccessible::quickAttachedProperties()
{
{
QQmlEngine engine;
QQmlComponent component(&engine);
component.setData("import QtQuick 2.0\nItem {\n"
"}", QUrl());
QObject *object = component.create();
QVERIFY(object != 0);
QObject *attachedObject = QQuickAccessibleAttached::attachedProperties(object);
QCOMPARE(attachedObject, static_cast<QObject*>(0));
delete object;
}
// Attached property
{
QObject parent;
QQuickAccessibleAttached *attachedObj = new QQuickAccessibleAttached(&parent);
attachedObj->name();
QVariant pp = attachedObj->property("name");
QQmlEngine engine;
QQmlComponent component(&engine);
component.setData("import QtQuick 2.0\nItem {\n"
"Accessible.role: Accessible.Button\n"
"}", QUrl());
QObject *object = component.create();
QVERIFY(object != 0);
QObject *attachedObject = QQuickAccessibleAttached::attachedProperties(object);
QVERIFY(attachedObject);
if (attachedObject) {
QVariant p = attachedObject->property("role");
QCOMPARE(p.isNull(), false);
QCOMPARE(p.toInt(), int(QAccessible::PushButton));
p = attachedObject->property("name");
QCOMPARE(p.isNull(), true);
p = attachedObject->property("description");
QCOMPARE(p.isNull(), true);
}
delete object;
}
// Attached property
{
QQmlEngine engine;
QQmlComponent component(&engine);
component.setData("import QtQuick 2.0\nItem {\n"
"Accessible.role: Accessible.Button\n"
"Accessible.name: \"Donald\"\n"
"Accessible.description: \"Duck\"\n"
"}", QUrl());
QObject *object = component.create();
QVERIFY(object != 0);
QObject *attachedObject = QQuickAccessibleAttached::attachedProperties(object);
QVERIFY(attachedObject);
if (attachedObject) {
QVariant p = attachedObject->property("role");
QCOMPARE(p.isNull(), false);
QCOMPARE(p.toInt(), int(QAccessible::PushButton));
p = attachedObject->property("name");
QCOMPARE(p.isNull(), false);
QCOMPARE(p.toString(), QLatin1String("Donald"));
p = attachedObject->property("description");
QCOMPARE(p.isNull(), false);
QCOMPARE(p.toString(), QLatin1String("Duck"));
}
delete object;
}
}
void tst_QQuickAccessible::basicPropertiesTest()
{
QAccessibleInterface *app = QAccessible::queryAccessibleInterface(qApp);
QCOMPARE(app->childCount(), 0);
QQuickView *window = new QQuickView();
window->setSource(testFileUrl("statictext.qml"));
window->show();
QCOMPARE(app->childCount(), 1);
QAccessibleInterface *iface = QAccessible::queryAccessibleInterface(window);
QVERIFY(iface);
QCOMPARE(iface->childCount(), 1);
QAccessibleInterface *item = iface->child(0);
QVERIFY(item);
QCOMPARE(item->childCount(), 2);
QCOMPARE(item->rect().size(), QSize(400, 400));
QCOMPARE(item->role(), QAccessible::Pane);
QCOMPARE(iface->indexOfChild(item), 0);
QAccessibleInterface *text = item->child(0);
QVERIFY(text);
QCOMPARE(text->childCount(), 0);
QCOMPARE(text->text(QAccessible::Name), QLatin1String("Hello Accessibility"));
QCOMPARE(text->rect().size(), QSize(200, 50));
QCOMPARE(text->rect().x(), item->rect().x() + 100);
QCOMPARE(text->rect().y(), item->rect().y() + 20);
QCOMPARE(text->role(), QAccessible::StaticText);
QCOMPARE(item->indexOfChild(text), 0);
QAccessibleInterface *text2 = item->child(1);
QVERIFY(text2);
QCOMPARE(text2->childCount(), 0);
QCOMPARE(text2->text(QAccessible::Name), QLatin1String("The Hello 2 accessible text"));
QCOMPARE(text2->rect().size(), QSize(100, 40));
QCOMPARE(text2->rect().x(), item->rect().x() + 100);
QCOMPARE(text2->rect().y(), item->rect().y() + 40);
QCOMPARE(text2->role(), QAccessible::StaticText);
QCOMPARE(item->indexOfChild(text2), 1);
QCOMPARE(iface->indexOfChild(text2), -1);
QCOMPARE(text2->indexOfChild(item), -1);
delete window;
}
QAccessibleInterface *topLevelChildAt(QAccessibleInterface *iface, int x, int y)
{
QAccessibleInterface *child = iface->childAt(x, y);
if (!child)
return 0;
QAccessibleInterface *childOfChild;
while ( ( childOfChild = child->childAt(x, y)) ) {
child = childOfChild;
}
return child;
}
void tst_QQuickAccessible::hitTest()
{
QQuickView *window = new QQuickView;
window->setSource(testFileUrl("hittest.qml"));
window->show();
QAccessibleInterface *windowIface = QAccessible::queryAccessibleInterface(window);
QVERIFY(windowIface);
QAccessibleInterface *rootItem = windowIface->child(0);
QRect rootRect = rootItem->rect();
// check the root item from app
QAccessibleInterface *appIface = QAccessible::queryAccessibleInterface(qApp);
QVERIFY(appIface);
QAccessibleInterface *itemHit(appIface->childAt(rootRect.x() + 200, rootRect.y() + 50));
QVERIFY(itemHit);
QCOMPARE(rootRect, itemHit->rect());
// hit rect1
QAccessibleInterface *rect1(rootItem->child(0));
QRect rect1Rect = rect1->rect();
QAccessibleInterface *rootItemIface = rootItem->childAt(rect1Rect.x() + 10, rect1Rect.y() + 10);
QVERIFY(rootItemIface);
QCOMPARE(rect1Rect, rootItemIface->rect());
QCOMPARE(rootItemIface->text(QAccessible::Name), QLatin1String("rect1"));
// should also work from top level (app)
QAccessibleInterface *app(QAccessible::queryAccessibleInterface(qApp));
QAccessibleInterface *itemHit2(topLevelChildAt(app, rect1Rect.x() + 10, rect1Rect.y() + 10));
QVERIFY(itemHit2);
QCOMPARE(itemHit2->rect(), rect1Rect);
QCOMPARE(itemHit2->text(QAccessible::Name), QLatin1String("rect1"));
// hit rect201
QAccessibleInterface *rect2(rootItem->child(1));
QVERIFY(rect2);
// FIXME: This is seems broken on mac
// QCOMPARE(rect2->rect().translated(rootItem->rect().x(), rootItem->rect().y()), QRect(0, 50, 100, 100));
QAccessibleInterface *rect20(rect2->child(0));
QVERIFY(rect20);
QAccessibleInterface *rect201(rect20->child(1));
QVERIFY(rect201);
QRect rect201Rect = rect201->rect();
rootItemIface = windowIface->childAt(rect201Rect.x() + 20, rect201Rect.y() + 20);
QVERIFY(rootItemIface);
QCOMPARE(rootItemIface->rect(), rect201Rect);
QCOMPARE(rootItemIface->text(QAccessible::Name), QLatin1String("rect201"));
delete window;
}
void tst_QQuickAccessible::checkableTest()
{
QScopedPointer<QQuickView> window(new QQuickView());
window->setSource(testFileUrl("checkbuttons.qml"));
window->show();
QAccessibleInterface *iface = QAccessible::queryAccessibleInterface(window.data());
QVERIFY(iface);
QAccessibleInterface *root = iface->child(0);
QAccessibleInterface *button1 = root->child(0);
QCOMPARE(button1->role(), QAccessible::Button);
QVERIFY(!(button1->state().checked));
QVERIFY(!(button1->state().checkable));
QAccessibleInterface *button2 = root->child(1);
QVERIFY(!(button2->state().checked));
QVERIFY(button2->state().checkable);
QAccessibleInterface *button3 = root->child(2);
QVERIFY(button3->state().checked);
QVERIFY(button3->state().checkable);
QAccessibleInterface *checkBox1 = root->child(3);
QCOMPARE(checkBox1->role(), QAccessible::CheckBox);
QVERIFY((checkBox1->state().checked));
QVERIFY(checkBox1->state().checkable);
QAccessibleInterface *checkBox2 = root->child(4);
QVERIFY(!(checkBox2->state().checked));
QVERIFY(checkBox2->state().checkable);
}
QTEST_MAIN(tst_QQuickAccessible)
#include "tst_qquickaccessible.moc"
|
Fix memory leak in test
|
Fix memory leak in test
Change-Id: I026ce85a6e593d5eccecdf032ee2f0763a2bef87
Reviewed-by: Jan Arve Sæther <[email protected]>
|
C++
|
lgpl-2.1
|
qmlc/qtdeclarative,qmlc/qtdeclarative,qmlc/qtdeclarative,mgrunditz/qtdeclarative-2d,matthewvogt/qtdeclarative,mgrunditz/qtdeclarative-2d,matthewvogt/qtdeclarative,matthewvogt/qtdeclarative,matthewvogt/qtdeclarative,qmlc/qtdeclarative,mgrunditz/qtdeclarative-2d,qmlc/qtdeclarative,mgrunditz/qtdeclarative-2d,qmlc/qtdeclarative,mgrunditz/qtdeclarative-2d,matthewvogt/qtdeclarative,mgrunditz/qtdeclarative-2d,matthewvogt/qtdeclarative,matthewvogt/qtdeclarative,qmlc/qtdeclarative,matthewvogt/qtdeclarative,mgrunditz/qtdeclarative-2d,qmlc/qtdeclarative
|
0cc68b2cbb1185c55ee58b1706e43de6a41b310d
|
general/device.hpp
|
general/device.hpp
|
// Copyright (c) 2010, Lawrence Livermore National Security, LLC. Produced at
// the Lawrence Livermore National Laboratory. LLNL-CODE-443211. All Rights
// reserved. See file COPYRIGHT for details.
//
// This file is part of the MFEM library. For more information and source code
// availability see http://mfem.org.
//
// MFEM 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) version 2.1 dated February 1999.
#ifndef MFEM_DEVICE_HPP
#define MFEM_DEVICE_HPP
#include "globals.hpp"
namespace mfem
{
/// The MFEM Device class that abstracts hardware devices, such as GPUs, and
/// programming models, such as CUDA, OCCA, RAJA and OpenMP.
class Device
{
private:
enum MODES {HOST, DEVICE};
MODES mode;
int dev = 0;
int ngpu = -1;
bool cuda = false;
bool raja = false;
bool occa = false;
bool omp = false;
bool isTracking = true;
Device(): mode{Device::HOST} {}
Device(Device const&);
void operator=(Device const&);
static Device& Get() { static Device singleton; return singleton; }
/// Setup switcher based on configuration settings
void Setup(const int dev = 0);
public:
/// Configure and enable the device.
/** The string parameter will enable a backend (cuda, omp, raja, occa) if the
corresponding substring is present (for now, the order is ignored). The
dev argument specifies which of the devices (e.g. GPUs) to enable. */
static inline void Configure(std::string device, const int dev = 0)
{
if (device.find("cuda") != std::string::npos) { Device::UseCuda(); }
if (device.find("omp") != std::string::npos) { Device::UseOmp(); }
if (device.find("raja") != std::string::npos) { Device::UseRaja(); }
if (device.find("occa") != std::string::npos) { Device::UseOcca(); }
EnableDevice(dev);
}
/// Print the configured device + programming models in order of priority
static inline void Print(std::ostream &out = mfem::out)
{
const bool omp = Device::UsingOmp();
const bool cuda = Device::UsingCuda();
const bool occa = Device::UsingOcca();
const bool raja = Device::UsingRaja();
out << "Device configuration: ";
if (cuda && occa) { out << "OCCA:CUDA\n"; return; }
if (omp && occa) { out << "OCCA:OpenMP\n"; return; }
if (occa) { out << "OCCA:CPU\n"; return; }
if (cuda && raja) { out << "RAJA:CUDA\n"; return; }
if (cuda) { out << "CUDA\n"; return; }
if (omp && raja) { out << "RAJA:OpenMP\n"; return; }
if (raja) { out << "RAJA:CPU\n"; return; }
if (omp) { out << "OpenMP\n"; return; }
out << "CPU\n";
}
/// Enable the use of the configured device in the code that follows.
/** In particular, use the device version of the okina kernels encountered,
with the device versions of the data registered in the memory manager
(copying host-to-device if necessary). */
static inline void Enable() { Get().mode = Device::DEVICE; }
/// Disable the use of the configured device in the code that follows.
/** In particular, use the host version of the okina kernels encountered,
with the host versions of the data registered in the memory manager
(copying device-to-host if necessary). */
static inline void Disable() { Get().mode = Device::HOST; }
constexpr static inline bool UsingMM()
{
#ifdef MFEM_USE_MM
return true;
#else
return false;
#endif
}
static inline void EnableDevice(const int dev = 0) { Get().Setup(dev); }
static inline bool DeviceEnabled() { return Get().ngpu > 0; }
static inline bool DeviceDisabled() { return Get().ngpu == 0; }
static inline bool DeviceHasBeenEnabled() { return Get().ngpu >= 0; }
static inline bool UsingDevice() { return DeviceEnabled() && Get().mode == DEVICE; }
static inline bool UsingHost() { return !UsingDevice(); }
static inline void DisableTracking() { Get().isTracking = false; };
static inline void EnableTracking() { Get().isTracking = true; };
static inline bool IsTracking() { return Get().isTracking; };
static inline bool UsingCuda() { return Get().cuda; }
static inline void UseCuda() { Get().cuda = true; }
static inline bool UsingOmp() { return Get().omp; }
static inline void UseOmp() { Get().omp = true; }
static inline bool UsingRaja() { return Get().raja; }
static inline void UseRaja() { Get().raja = true; }
static inline bool UsingOcca() { return Get().occa; }
static inline void UseOcca() { Get().occa = true; }
static inline bool UsingOkina()
{
return DeviceEnabled() && Get().mode == DEVICE &&
(UsingCuda() || UsingOmp() || UsingRaja() || UsingOcca());
}
~Device();
};
} // mfem
#endif // MFEM_DEVICE_HPP
|
// Copyright (c) 2010, Lawrence Livermore National Security, LLC. Produced at
// the Lawrence Livermore National Laboratory. LLNL-CODE-443211. All Rights
// reserved. See file COPYRIGHT for details.
//
// This file is part of the MFEM library. For more information and source code
// availability see http://mfem.org.
//
// MFEM 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) version 2.1 dated February 1999.
#ifndef MFEM_DEVICE_HPP
#define MFEM_DEVICE_HPP
#include "globals.hpp"
namespace mfem
{
/// The MFEM Device class that abstracts hardware devices, such as GPUs, and
/// programming models, such as CUDA, OCCA, RAJA and OpenMP.
class Device
{
private:
enum MODES {HOST, DEVICE};
MODES mode;
int dev = 0;
int ngpu = -1;
bool cuda = false;
bool raja = false;
bool occa = false;
bool omp = false;
bool isTracking = true;
Device(): mode{Device::HOST} {}
Device(Device const&);
void operator=(Device const&);
static Device& Get() { static Device singleton; return singleton; }
/// Setup switcher based on configuration settings
void Setup(const int dev = 0);
public:
/// Configure and enable the device.
/** The string parameter will enable a backend (cuda, omp, raja, occa) if the
corresponding substring is present (for now, the order is ignored). The
dev argument specifies which of the devices (e.g. GPUs) to enable. */
static inline void Configure(std::string device, const int dev = 0)
{
if (device.find("cuda") != std::string::npos) { Device::UseCuda(); }
if (device.find("omp") != std::string::npos) { Device::UseOmp(); }
if (device.find("raja") != std::string::npos) { Device::UseRaja(); }
if (device.find("occa") != std::string::npos) { Device::UseOcca(); }
EnableDevice(dev);
}
/// Print the configured device + programming models in order of priority
static inline void Print(std::ostream &out = mfem::out)
{
const bool omp = Device::UsingOmp();
const bool cuda = Device::UsingCuda();
const bool occa = Device::UsingOcca();
const bool raja = Device::UsingRaja();
out << "Device configuration: ";
if (cuda && occa) { out << "OCCA:CUDA\n"; return; }
if (omp && occa) { out << "OCCA:OpenMP\n"; return; }
if (occa) { out << "OCCA:CPU\n"; return; }
if (cuda && raja) { out << "RAJA:CUDA\n"; return; }
if (cuda) { out << "CUDA\n"; return; }
if (omp && raja) { out << "RAJA:OpenMP\n"; return; }
if (raja) { out << "RAJA:CPU\n"; return; }
if (omp) { out << "OpenMP\n"; return; }
out << "CPU\n";
}
/// Enable the use of the configured device in the code that follows.
/** In particular, use the device version of the okina kernels encountered,
with the device versions of the data registered in the memory manager
(copying host-to-device if necessary). */
static inline void Enable() { Get().mode = Device::DEVICE; }
/// Disable the use of the configured device in the code that follows.
/** In particular, use the host version of the okina kernels encountered,
with the host versions of the data registered in the memory manager
(copying device-to-host if necessary). */
static inline void Disable() { Get().mode = Device::HOST; }
constexpr static inline bool UsingMM()
{
#ifdef MFEM_USE_MM
return true;
#else
return false;
#endif
}
static inline void EnableDevice(const int dev = 0) { Get().Setup(dev); }
static inline bool DeviceEnabled() { return Get().ngpu > 0; }
static inline bool DeviceDisabled() { return Get().ngpu == 0; }
static inline bool DeviceHasBeenEnabled() { return Get().ngpu >= 0; }
static inline bool UsingDevice() { return DeviceEnabled() && Get().mode == DEVICE; }
static inline bool UsingHost() { return !UsingDevice(); }
static inline void DisableTracking() { Get().isTracking = false; };
static inline void EnableTracking() { Get().isTracking = true; };
static inline bool IsTracking() { return Get().isTracking; };
static inline bool UsingCuda() { return Get().cuda; }
static inline void UseCuda() { Get().cuda = true; }
static inline bool UsingOmp() { return Get().omp; }
static inline void UseOmp() { Get().omp = true; }
static inline bool UsingRaja() { return Get().raja; }
static inline void UseRaja() { Get().raja = true; }
static inline bool UsingOcca() { return Get().occa; }
static inline void UseOcca() { Get().occa = true; }
static inline bool UsingOkina()
{
return DeviceEnabled() && Get().mode == DEVICE &&
(UsingCuda() || UsingOmp() || UsingRaja() || UsingOcca());
}
~Device();
};
} // mfem
#endif // MFEM_DEVICE_HPP
|
make style
|
make style
|
C++
|
bsd-3-clause
|
mfem/mfem,mfem/mfem,mfem/mfem,mfem/mfem,mfem/mfem
|
c2541afe14a0f4561f90a90770a1f3809e60d1a4
|
test/book/main.cpp
|
test/book/main.cpp
|
/*!
\file
\author Igor Mironchik (igor.mironchik at gmail dot com).
Copyright (c) 2011-2017 Igor Mironchik
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.
*/
// Excel include.
#include <read-excel/book.hpp>
// C++ include.
#include <cmath>
// unit test helper.
#define DOCTEST_CONFIG_IMPLEMENT_WITH_MAIN
#include <test/doctest/doctest.h>
TEST_CASE( "test_book" )
{
Excel::Book book( "test/data/test.xls" );
REQUIRE( book.sheetsCount() == 1 );
Excel::Sheet * sheet = book.sheet( 0 );
REQUIRE( sheet->rowsCount() == 3 );
REQUIRE( sheet->columnsCount() == 4 );
REQUIRE( sheet->cell( 0, 0 ).getString() == L"String #1" );
REQUIRE( sheet->cell( 1, 0 ).getString() == L"String #2" );
REQUIRE( sheet->cell( 2, 0 ).getString() == L"String #3" );
REQUIRE( std::fabs( sheet->cell( 0, 1 ).getDouble() - 1.0 ) < 1E-9 );
REQUIRE( std::fabs( sheet->cell( 1, 1 ).getDouble() - 2.0 ) < 1E-9 );
REQUIRE( std::fabs( sheet->cell( 2, 1 ).getDouble() - 3.0 ) < 1E-9 );
REQUIRE( std::fabs( sheet->cell( 0, 2 ).getDouble() - 0.1 ) < 1E-9 );
REQUIRE( std::fabs( sheet->cell( 1, 2 ).getDouble() - 0.2 ) < 1E-9 );
REQUIRE( std::fabs( sheet->cell( 2, 2 ).getDouble() - 0.3 ) < 1E-9 );
REQUIRE( std::fabs( sheet->cell( 0, 3 ).getFormula().getDouble() - 1.1 ) < 1E-9 );
REQUIRE( std::fabs( sheet->cell( 1, 3 ).getFormula().getDouble() - 2.2 ) < 1E-9 );
REQUIRE( std::fabs( sheet->cell( 2, 3 ).getFormula().getDouble() - 3.3 ) < 1E-9 );
}
TEST_CASE( "test_book_via_stream" )
{
std::ifstream fileStream( "test/data/strange.xls", std::ios::in | std::ios::binary );
Excel::Book book( fileStream );
REQUIRE( book.sheetsCount() == 3 );
Excel::Sheet * sheet = book.sheet( 0 );
auto text = sheet->cell( 0, 0 ).getString();
REQUIRE( text.find( L"Somefile" ) != std::wstring::npos );
}
|
/*!
\file
\author Igor Mironchik (igor.mironchik at gmail dot com).
Copyright (c) 2011-2017 Igor Mironchik
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.
*/
// Excel include.
#include <read-excel/book.hpp>
// C++ include.
#include <cmath>
// unit test helper.
#define DOCTEST_CONFIG_IMPLEMENT_WITH_MAIN
#include <test/doctest/doctest.h>
TEST_CASE( "test_book" )
{
Excel::Book book( "test/data/test.xls" );
REQUIRE( book.sheetsCount() == 1 );
Excel::Sheet * sheet = book.sheet( 0 );
REQUIRE( sheet->rowsCount() == 3 );
REQUIRE( sheet->columnsCount() == 4 );
REQUIRE( sheet->cell( 0, 0 ).getString() == L"String #1" );
REQUIRE( sheet->cell( 1, 0 ).getString() == L"String #2" );
REQUIRE( sheet->cell( 2, 0 ).getString() == L"String #3" );
REQUIRE( std::fabs( sheet->cell( 0, 1 ).getDouble() - 1.0 ) < 1E-9 );
REQUIRE( std::fabs( sheet->cell( 1, 1 ).getDouble() - 2.0 ) < 1E-9 );
REQUIRE( std::fabs( sheet->cell( 2, 1 ).getDouble() - 3.0 ) < 1E-9 );
REQUIRE( std::fabs( sheet->cell( 0, 2 ).getDouble() - 0.1 ) < 1E-9 );
REQUIRE( std::fabs( sheet->cell( 1, 2 ).getDouble() - 0.2 ) < 1E-9 );
REQUIRE( std::fabs( sheet->cell( 2, 2 ).getDouble() - 0.3 ) < 1E-9 );
REQUIRE( std::fabs( sheet->cell( 0, 3 ).getFormula().getDouble() - 1.1 ) < 1E-9 );
REQUIRE( std::fabs( sheet->cell( 1, 3 ).getFormula().getDouble() - 2.2 ) < 1E-9 );
REQUIRE( std::fabs( sheet->cell( 2, 3 ).getFormula().getDouble() - 3.3 ) < 1E-9 );
}
TEST_CASE( "test_book_via_stream" )
{
std::ifstream fileStream( "test/data/strange.xls", std::ios::in | std::ios::binary );
Excel::Book book( fileStream );
REQUIRE( book.sheetsCount() == 3 );
Excel::Sheet * sheet = book.sheet( 0 );
const auto text = sheet->cell( 0, 0 ).getString();
REQUIRE( text.find( L"Somefile" ) != std::wstring::npos );
}
|
add XL_LABEL (review)
|
add XL_LABEL (review)
|
C++
|
mit
|
igormironchik/read-excel
|
1ca48928588851abdb9e8dd4913259f4c5d812b8
|
include/util/histogram.hpp
|
include/util/histogram.hpp
|
/*******************************************************************************
* include/util/histogram.hpp
*
* Copyright (C) 2017 Florian Kurpicz <[email protected]>
*
* All rights reserved. Published under the BSD-2 license in the LICENSE file.
******************************************************************************/
#pragma once
#include <cstdint>
#include <limits>
#include <type_traits>
#include <unordered_map>
template <typename AlphabetType>
struct histogram_entry {
const AlphabetType symbol;
uint64_t frequency;
histogram_entry(AlphabetType s, uint64_t f): symbol(s), frequency(f) {}
friend std::ostream& operator <<(std::ostream& os,
const histogram_entry& he) {
return os << "[ " << he.symbol << "(" << uint64_t(he.symbol) << ") | "
<< he.frequency << " ]";
}
}; // struct histogram_entry
template <typename AlphabetType>
class histogram {
public:
histogram(const AlphabetType* text, const uint64_t size,
const uint64_t reduced_sigma = 0) : max_symbol_(0){
if (std::is_same<AlphabetType, uint8_t>::value) {
const uint64_t max_char = std::max(
static_cast<std::remove_cv_t<decltype(reduced_sigma)>>(
std::numeric_limits<uint8_t>::max() + 1), reduced_sigma);
std::vector<uint64_t> hist(max_char, 0);
for (uint64_t pos = 0; pos < size; ++pos) {
const AlphabetType cur_char = text[pos];
max_symbol_ = std::max(max_symbol_, cur_char);
++hist[cur_char];
}
for (uint64_t pos = 0; pos < hist.size(); ++pos) {
if (hist[pos] > 0) {
data_.emplace_back(AlphabetType(pos), hist[pos]);
}
}
} else {
std::unordered_map<AlphabetType, uint64_t> symbol_list;
for (uint64_t pos = 0; pos < size; ++pos) {
const AlphabetType cur_char = text[pos];
max_symbol_ = std::max(max_symbol_, cur_char);
auto result = symbol_list.find(cur_char);
if (result == symbol_list.end()) { symbol_list.emplace(cur_char, 1); }
else { ++(result->second); }
}
for (const auto& symbol : symbol_list) {
data_.emplace_back(symbol.first, symbol.second);
}
}
}
AlphabetType max_symbol() const {
return max_symbol_;
};
uint64_t size() const {
return data_.size();
}
// Returns the frequency of a symbol. Does not check if symbol exists. If the
// symbol does not exits, the behavior is undefined.
uint64_t frequency(const AlphabetType symbol) const {
for (const auto& he : data_) {
if (he.symbol == symbol) {
return he.frequency;
}
}
return 0;
}
histogram_entry<AlphabetType>& operator [](const uint64_t index) {
return data_[index];
}
histogram_entry<AlphabetType> operator [](const uint64_t index) const {
return data_[index];
}
private:
AlphabetType max_symbol_;
std::vector<histogram_entry<AlphabetType>> data_;
}; // class histogram
/******************************************************************************/
|
/*******************************************************************************
* include/util/histogram.hpp
*
* Copyright (C) 2017 Florian Kurpicz <[email protected]>
*
* All rights reserved. Published under the BSD-2 license in the LICENSE file.
******************************************************************************/
#pragma once
#include <cstdint>
#include <limits>
#include <type_traits>
#include <unordered_map>
template <typename AlphabetType>
struct histogram_entry {
const AlphabetType symbol;
uint64_t frequency;
histogram_entry(AlphabetType s, uint64_t f): symbol(s), frequency(f) {}
friend std::ostream& operator <<(std::ostream& os,
const histogram_entry& he) {
return os << "[ " << he.symbol << "(" << uint64_t(he.symbol) << ") | "
<< he.frequency << " ]";
}
}; // struct histogram_entry
template <typename AlphabetType>
class histogram {
public:
histogram() = default;
histogram(const AlphabetType* text, const uint64_t size,
const uint64_t reduced_sigma = 0) : max_symbol_(0){
if (std::is_same<AlphabetType, uint8_t>::value) {
const uint64_t max_char = std::max(
static_cast<std::remove_cv_t<decltype(reduced_sigma)>>(
std::numeric_limits<uint8_t>::max() + 1), reduced_sigma);
std::vector<uint64_t> hist(max_char, 0);
for (uint64_t pos = 0; pos < size; ++pos) {
const AlphabetType cur_char = text[pos];
max_symbol_ = std::max(max_symbol_, cur_char);
++hist[cur_char];
}
for (uint64_t pos = 0; pos < hist.size(); ++pos) {
if (hist[pos] > 0) {
data_.emplace_back(AlphabetType(pos), hist[pos]);
}
}
} else {
std::unordered_map<AlphabetType, uint64_t> symbol_list;
for (uint64_t pos = 0; pos < size; ++pos) {
const AlphabetType cur_char = text[pos];
max_symbol_ = std::max(max_symbol_, cur_char);
auto result = symbol_list.find(cur_char);
if (result == symbol_list.end()) { symbol_list.emplace(cur_char, 1); }
else { ++(result->second); }
}
for (const auto& symbol : symbol_list) {
data_.emplace_back(symbol.first, symbol.second);
}
}
}
AlphabetType max_symbol() const {
return max_symbol_;
};
uint64_t size() const {
return data_.size();
}
// Returns the frequency of a symbol. Does not check if symbol exists. If the
// symbol does not exits, the behavior is undefined.
uint64_t frequency(const AlphabetType symbol) const {
for (const auto& he : data_) {
if (he.symbol == symbol) {
return he.frequency;
}
}
return 0;
}
histogram_entry<AlphabetType>& operator [](const uint64_t index) {
return data_[index];
}
histogram_entry<AlphabetType> operator [](const uint64_t index) const {
return data_[index];
}
private:
AlphabetType max_symbol_;
std::vector<histogram_entry<AlphabetType>> data_;
}; // class histogram
/******************************************************************************/
|
Allow construction of an empty histogram
|
Allow construction of an empty histogram
|
C++
|
bsd-2-clause
|
kurpicz/pwm,kurpicz/pwm,kurpicz/pwm
|
ab1bd8c9276a24100dfd546d0782349b2b8070e1
|
eigen.hpp
|
eigen.hpp
|
// -*- mode: c++; coding: utf-8 -*-
#pragma once
#ifndef WTL_EIGEN_HPP_
#define WTL_EIGEN_HPP_
#include <vector>
#include <valarray>
#include <string>
#include <istream>
#include <Eigen/Core>
/////////1/////////2/////////3/////////4/////////5/////////6/////////7/////////
namespace wtl { namespace eigen {
/////////1/////////2/////////3/////////4/////////5/////////6/////////7/////////
template <class Vector> inline
std::vector<size_t> which(const Vector& predicate) {
std::vector<size_t> indices;
const size_t n = predicate.size();
indices.reserve(n);
for (size_t i=0; i<n; ++i) {
if (predicate[i] > 0) {indices.push_back(i);}
}
return indices;
}
template <class T, class Vector> inline
T slice(const Eigen::DenseBase<T>& orig, const Vector& indices) {
const size_t n = indices.size();
T result(n, orig.cols());
for (size_t i=0; i<n; ++i) {
result.row(i) = orig.row(indices[i]);
}
return result;
}
template <class T, class Vector> inline
T slice_cols(const Eigen::DenseBase<T>& orig, const Vector& indices) {
const size_t n = indices.size();
T result(orig.rows(), n);
for (size_t i=0; i<n; ++i) {
result.col(i) = orig.col(indices[i]);
}
return result;
}
template <class T, class Vector> inline
T filter(const Eigen::DenseBase<T>& orig, const Vector& predicate) {
return slice(orig, which(predicate));
}
template <class T, class Vector> inline
T select(const Eigen::DenseBase<T>& orig, const Vector& predicate) {
return slice_cols(orig, which(predicate));
}
inline Eigen::IOFormat tsv(const std::string& sep="\t") {
return {Eigen::StreamPrecision, Eigen::DontAlignCols, sep, "", "", "\n"};
}
template <class T>
std::vector<typename T::Scalar> as_vector(const T& vec) {
return std::vector<typename T::Scalar>(vec.data(), vec.data() + vec.size());
}
template <class T>
std::valarray<typename T::Scalar> as_valarray(const T& vec) {
return std::valarray<typename T::Scalar>(vec.data(), vec.size());
}
template <class T>
Eigen::Matrix<T, Eigen::Dynamic, Eigen::Dynamic, Eigen::RowMajor>
read_matrix(std::istream& fin, const size_t ncol) {
std::vector<T> vec{std::istream_iterator<T>(fin), std::istream_iterator<T>()};
if (vec.size() % ncol > 0) {
std::string msg = std::string(__PRETTY_FUNCTION__);
throw std::runtime_error(msg + ": vec.size() % ncol > 0");
}
return Eigen::Matrix<T, Eigen::Dynamic, Eigen::Dynamic, Eigen::RowMajor>::Map(vec.data(), vec.size() / ncol, ncol);
}
template <class T>
Eigen::Array<T, Eigen::Dynamic, Eigen::Dynamic, Eigen::RowMajor>
read_array(std::istream& fin, const size_t ncol) {
std::vector<T> vec{std::istream_iterator<T>(fin), std::istream_iterator<T>()};
if (vec.size() % ncol > 0) {
std::string msg = std::string(__PRETTY_FUNCTION__);
throw std::runtime_error(msg + ": vec.size() % ncol > 0");
}
return Eigen::Array<T, Eigen::Dynamic, Eigen::Dynamic, Eigen::RowMajor>::Map(vec.data(), vec.size() / ncol, ncol);
}
/////////1/////////2/////////3/////////4/////////5/////////6/////////7/////////
}} // namespace wtl::eigen
/////////1/////////2/////////3/////////4/////////5/////////6/////////7/////////
#endif // WTL_EIGEN_HPP_
|
// -*- mode: c++; coding: utf-8 -*-
#pragma once
#ifndef WTL_EIGEN_HPP_
#define WTL_EIGEN_HPP_
#include <vector>
#include <valarray>
#include <string>
#include <istream>
#include <Eigen/Core>
/////////1/////////2/////////3/////////4/////////5/////////6/////////7/////////
namespace wtl { namespace eigen {
/////////1/////////2/////////3/////////4/////////5/////////6/////////7/////////
template <class Vector> inline
std::vector<size_t> which(const Vector& predicate) {
std::vector<size_t> indices;
const size_t n = predicate.size();
indices.reserve(n);
for (size_t i=0; i<n; ++i) {
if (predicate[i] > 0) {indices.push_back(i);}
}
return indices;
}
template <class T, class Vector> inline
T slice(const Eigen::DenseBase<T>& orig, const Vector& indices) {
const size_t n = indices.size();
T result(n, orig.cols());
for (size_t i=0; i<n; ++i) {
result.row(i) = orig.row(indices[i]);
}
return result;
}
template <class T, class Vector> inline
T slice_cols(const Eigen::DenseBase<T>& orig, const Vector& indices) {
const size_t n = indices.size();
T result(orig.rows(), n);
for (size_t i=0; i<n; ++i) {
result.col(i) = orig.col(indices[i]);
}
return result;
}
template <class T, class Vector> inline
T filter(const Eigen::DenseBase<T>& orig, const Vector& predicate) {
return slice(orig, which(predicate));
}
template <class T, class Vector> inline
T select(const Eigen::DenseBase<T>& orig, const Vector& predicate) {
return slice_cols(orig, which(predicate));
}
inline Eigen::IOFormat tsv(const std::string& sep="\t") {
return {Eigen::StreamPrecision, Eigen::DontAlignCols, sep, "", "", "\n"};
}
template <class T> inline
std::vector<typename T::value_type> as_vector(const T& vec) {
return std::vector<typename T::value_type>(vec.data(), vec.data() + vec.size());
}
template <class T> inline
std::valarray<typename T::value_type> as_valarray(const T& vec) {
return std::valarray<typename T::value_type>(vec.data(), vec.size());
}
template <class T> inline
std::vector<Eigen::Array<typename T::value_type, Eigen::Dynamic, 1, Eigen::ColMajor>>
columns(const Eigen::DenseBase<T>& matrix) {
const size_t n = matrix.cols();
std::vector<Eigen::Array<typename T::value_type, Eigen::Dynamic, 1, Eigen::ColMajor>> result;
result.reserve(n);
for (size_t i=0; i<n; ++i) {
result.push_back(matrix.col(i));
}
return result;
}
template <class T> inline
Eigen::Matrix<T, Eigen::Dynamic, Eigen::Dynamic, Eigen::RowMajor>
read_matrix(std::istream& fin, const size_t ncol) {
std::vector<T> vec{std::istream_iterator<T>(fin), std::istream_iterator<T>()};
if (vec.size() % ncol > 0) {
std::string msg = std::string(__PRETTY_FUNCTION__);
throw std::runtime_error(msg + ": vec.size() % ncol > 0");
}
return Eigen::Matrix<T, Eigen::Dynamic, Eigen::Dynamic, Eigen::RowMajor>::Map(vec.data(), vec.size() / ncol, ncol);
}
template <class T> inline
Eigen::Array<T, Eigen::Dynamic, Eigen::Dynamic, Eigen::RowMajor>
read_array(std::istream& fin, const size_t ncol) {
std::vector<T> vec{std::istream_iterator<T>(fin), std::istream_iterator<T>()};
if (vec.size() % ncol > 0) {
std::string msg = std::string(__PRETTY_FUNCTION__);
throw std::runtime_error(msg + ": vec.size() % ncol > 0");
}
return Eigen::Array<T, Eigen::Dynamic, Eigen::Dynamic, Eigen::RowMajor>::Map(vec.data(), vec.size() / ncol, ncol);
}
/////////1/////////2/////////3/////////4/////////5/////////6/////////7/////////
}} // namespace wtl::eigen
/////////1/////////2/////////3/////////4/////////5/////////6/////////7/////////
#endif // WTL_EIGEN_HPP_
|
Add eigen::columns()
|
Add eigen::columns()
|
C++
|
mit
|
heavywatal/cxxwtils
|
32cf953eb202ac3cf18d26f6c8ea629a6e581859
|
either.hh
|
either.hh
|
#ifndef EITHER_HH
#define EITHER_HH
#include <functional>
#include <new>
#include <type_traits>
#include <utility>
template<typename Left, typename Right,
typename = typename std::enable_if<std::is_nothrow_move_constructible<Left>::value &&
std::is_nothrow_move_constructible<Right>::value
>::type
>
class either {
void destroy() {
if (is_left) {
left.~Left();
} else {
right.~Right();
}
}
union {
Left left;
Right right;
};
bool is_left;
public:
either(const Left &other) : left(other), is_left(true) {}
either(const Right &other) : right(other), is_left(false) {}
either(Left &&other) : left(std::move(other)), is_left(true) {}
either(Right &&other) : right(std::move(other)), is_left(false) {}
either(const either &other) : is_left(other.is_left) {
if (is_left) {
new(&left) Left(other.left);
} else {
new(&right) Right(other.right);
}
}
either(either &&other) noexcept : is_left(other.is_left) {
if (is_left) {
new(&left) Left(std::move(other.left));
} else {
new(&right) Right(std::move(other.right));
}
}
either &operator=(either other) {
destroy();
is_left = other.is_left;
if (is_left) {
new(&left) Left(std::move(other.left));
} else {
new(&right) Right(std::move(other.right));
}
return *this;
}
~either() {
destroy();
}
template<typename LeftF, typename RightF>
auto match(LeftF leftf, RightF rightf) -> decltype(leftf(left)) {
return is_left ? leftf(left) : rightf(right);
}
template<typename LeftF, typename RightF>
auto match(LeftF leftf, RightF rightf) const -> decltype(leftf(left)) {
return is_left ? leftf(left) : rightf(right);
}
template<typename ...Args>
void emplace_left(Args &&...args) {
destroy();
new(&left) Left(std::forward<Args>(args)...);
is_left = true;
}
template<typename ...Args>
void emplace_right(Args &&...args) {
destroy();
new(&right) Right(std::forward<Args>(args)...);
is_left = false;
}
bool operator==(const either &other) const {
return is_left == other.is_left &&
is_left ? left == other.left : right == other.right;
}
bool operator!=(const either &other) const {
return is_left != other.is_left ||
is_left ? left != other.left : right != other.right;
}
friend struct std::hash<either<Left, Right>>;
};
namespace std {
template<typename Left, typename Right>
struct hash<either<Left, Right>> {
hash() : hash_left(), hash_right() {}
size_t operator()(const either<Left, Right> &e) const {
return e.is_left ? ~hash_left(e.left) : hash_right(e.right);
}
private:
const hash<Left> hash_left;
const hash<Right> hash_right;
};
}
#endif
|
#ifndef EITHER_HH
#define EITHER_HH
#include <functional>
#include <new>
#include <type_traits>
#include <utility>
template<typename Left, typename Right,
typename = typename std::enable_if<std::is_nothrow_move_constructible<Left>::value &&
std::is_nothrow_move_constructible<Right>::value
>::type
>
class either {
void destroy() {
if (is_left) {
left.~Left();
} else {
right.~Right();
}
}
union {
Left left;
Right right;
};
bool is_left;
public:
either(const Left &other) : left(other), is_left(true) {}
either(const Right &other) : right(other), is_left(false) {}
either(Left &&other) : left(std::move(other)), is_left(true) {}
either(Right &&other) : right(std::move(other)), is_left(false) {}
either(const either &other) : is_left(other.is_left) {
if (is_left) {
new(&left) Left(other.left);
} else {
new(&right) Right(other.right);
}
}
either(either &&other) noexcept : is_left(other.is_left) {
if (is_left) {
new(&left) Left(std::move(other.left));
} else {
new(&right) Right(std::move(other.right));
}
}
either &operator=(either other) {
destroy();
is_left = other.is_left;
if (is_left) {
new(&left) Left(std::move(other.left));
} else {
new(&right) Right(std::move(other.right));
}
return *this;
}
~either() {
destroy();
}
template<typename LeftF, typename RightF>
auto match(LeftF leftf, RightF rightf) -> decltype(leftf(left)) {
return is_left ? leftf(left) : rightf(right);
}
template<typename LeftF, typename RightF>
auto match(LeftF leftf, RightF rightf) const -> decltype(leftf(left)) {
return is_left ? leftf(left) : rightf(right);
}
template<typename ...Args,
typename = typename std::enable_if<std::is_nothrow_constructible<Left, Args...>::value>::type>
void emplace_left(Args &&...args) {
destroy();
new(&left) Left(std::forward<Args>(args)...);
is_left = true;
}
template<typename ...Args,
typename = typename std::enable_if<std::is_nothrow_constructible<Right, Args...>::value>::type>
void emplace_right(Args &&...args) {
destroy();
new(&right) Right(std::forward<Args>(args)...);
is_left = false;
}
bool operator==(const either &other) const {
return is_left == other.is_left &&
is_left ? left == other.left : right == other.right;
}
bool operator!=(const either &other) const {
return is_left != other.is_left ||
is_left ? left != other.left : right != other.right;
}
friend struct std::hash<either<Left, Right>>;
};
namespace std {
template<typename Left, typename Right>
struct hash<either<Left, Right>> {
hash() : hash_left(), hash_right() {}
size_t operator()(const either<Left, Right> &e) const {
return e.is_left ? ~hash_left(e.left) : hash_right(e.right);
}
private:
const hash<Left> hash_left;
const hash<Right> hash_right;
};
}
#endif
|
use enable_if for emplace_left and emplace_right
|
use enable_if for emplace_left and emplace_right
they are only safe for noexcept constructors
|
C++
|
mit
|
thestinger/util,thestinger/util
|
c8cb6be3e336529d66e078d700dfef659daef3d8
|
test/gpio_test.cpp
|
test/gpio_test.cpp
|
/*
* File: gpio_test.cpp
* Description: Tests GPIO memory access using Broadcom GPIO Pin 17 on revision 2
* of the Raspberry Pi
* Programmer: Thomas Newman
* Date: 2013/07/30
*
* Note: This program must run as root to successfully map the file.
* This program is just to test the basic functionality. All it does
* is turn one LED on.
*
* The MIT License (MIT)
*
* Copyright (c) 2013 Thomas Newman
*
* 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 <sys/types.h>
#include <sys/mman.h>
#include <unistd.h>
#include <fcntl.h>
#include <stdint.h>
#define GPIO_START_ADDRESS 0x20200000
#define BLOCK_SIZE (4*1024)
// Offsets are required to convert byte level addressing to 4 byte addressing
#define GPIO_FUNC_REG_1 0x04 / 4
#define GPIO_PIN_REG_1 0x1C / 4
int main()
{
int mapped_registers;
volatile uint32_t* register_address;
// Map the GPIO memory
mapped_registers = open("/dev/mem", O_RDWR | O_SYNC);
register_address = (uint32_t*) mmap(NULL, BLOCK_SIZE, PROT_WRITE | PROT_READ, MAP_SHARED, mapped_registers, GPIO_START_ADDRESS);
// Set the register to output mode
*(register_address + GPIO_FUNC_REG_1) = *(register_address + GPIO_FUNC_REG_1) | 0x200000;
// Set the output
*(register_address + GPIO_PIN_REG_1) = *(register_address + GPIO_PIN_REG_1) | 0x20000;
// Unmap the GPIO memory
munmap((uint32_t*) register_address, BLOCK_SIZE);
close(mapped_registers);
return 0;
}
|
/*
* File: gpio_test.cpp
* Description: Tests GPIO memory access using Broadcom GPIO Pin 17 on revision 2
* of the Raspberry Pi
* Programmer: Thomas Newman
* Date: 2013/07/30
*
* Note: This program must run as root to successfully map the file.
* This program is just to test the basic functionality. All it does
* is turn one LED on and then off again.
*
* The MIT License (MIT)
*
* Copyright (c) 2013 Thomas Newman
*
* 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 <sys/types.h>
#include <sys/mman.h>
#include <unistd.h>
#include <fcntl.h>
#include <stdint.h>
#define GPIO_START_ADDRESS 0x20200000
#define BLOCK_SIZE (4*1024)
// Offsets are required to convert byte level addressing to 4 byte addressing
#define GPIO_FUNC_1 0x04 / 4
#define GPIO_PIN_SET_1 0x1C / 4
#define GPIO_PIN_CLR_1 0x28 / 4
int main()
{
int mapped_registers;
volatile unsigned* register_address;
// Map the GPIO memory
mapped_registers = open("/dev/mem", O_RDWR | O_SYNC);
register_address = (volatile unsigned*) mmap(NULL, BLOCK_SIZE, PROT_WRITE | PROT_READ, MAP_SHARED, mapped_registers, GPIO_START_ADDRESS);
close(mapped_registers);
// Clear the mode for the register
*(register_address + GPIO_FUNC_1) &= 0xFF1FFFFF;
// Set the register to output mode
*(register_address + GPIO_FUNC_1) |= 0x200000;
// Set the output
*(register_address + GPIO_PIN_SET_1) = 0x20000;
sleep(1);
// Clear the output
*(register_address + GPIO_PIN_CLR_1) = 0x20000;
// Unmap the GPIO memory
munmap((void*) register_address, BLOCK_SIZE);
return 0;
}
|
Update gpio_test.cpp
|
Update gpio_test.cpp
|
C++
|
mit
|
tnewman/pio
|
e75b0a9ef24e081f4132f86dc68a75bdef75fa24
|
tests/auto/qsparqlquery/tst_qsparqlquery.cpp
|
tests/auto/qsparqlquery/tst_qsparqlquery.cpp
|
/****************************************************************************
**
** Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies).
** All rights reserved.
** Contact: Nokia Corporation ([email protected])
**
** This file is part of the test suite of the 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 <QUrl>
//const QString qtest(qTableName( "qtest", __FILE__ )); // FIXME: what's this
//TESTED_FILES=
class tst_QSparqlQuery : public QObject
{
Q_OBJECT
public:
tst_QSparqlQuery();
virtual ~tst_QSparqlQuery();
public slots:
void initTestCase();
void cleanupTestCase();
void init();
void cleanup();
private slots:
void replacement_data();
void replacement();
void unbind_and_replace_data();
void unbind_and_replace();
void different_datatypes_data();
void different_datatypes();
};
tst_QSparqlQuery::tst_QSparqlQuery()
{
}
tst_QSparqlQuery::~tst_QSparqlQuery()
{
}
void tst_QSparqlQuery::initTestCase()
{
}
void tst_QSparqlQuery::cleanupTestCase()
{
}
void tst_QSparqlQuery::init()
{
}
void tst_QSparqlQuery::cleanup()
{
}
void tst_QSparqlQuery::replacement_data()
{
QTest::addColumn<QString>("rawString");
QTest::addColumn<QStringList>("placeholders");
QTest::addColumn<QVariantList>("replacements");
QTest::addColumn<QString>("replacedString");
QTest::newRow("nothing") <<
QString("nothing to replace") <<
(QStringList() << "?:foo" << "?:bar") <<
(QVariantList() << "FOO" << "BAR") <<
QString("nothing to replace");
QTest::newRow("simple") <<
QString("replace ?:foo ?:bar") <<
(QStringList() << "?:foo" << "?:bar") <<
(QVariantList() << "FOO" << "BAR") <<
QString("replace \"FOO\" \"BAR\"");
QTest::newRow("length_changes") <<
QString("replace ?:foo and ?:bar also") <<
(QStringList() << "?:foo" << "?:bar") <<
(QVariantList() << "FOOVAL" << "BARVAL") <<
QString("replace \"FOOVAL\" and \"BARVAL\" also");
QTest::newRow("quoted") <<
QString("do not replace '?:foo' or '?:bar'") <<
(QStringList() << "?:foo" << "?:bar") <<
(QVariantList() << "FOOVAL" << "BARVAL") <<
QString("do not replace '?:foo' or '?:bar'");
QTest::newRow("reallife") <<
QString("insert { _:c a nco:Contact ; "
"nco:fullname ?:username ; "
"nco:hasPhoneNumber _:pn . "
"_:pn a nco:PhoneNumber ; "
"nco:phoneNumber ?:userphone . }") <<
(QStringList() << "?:username" << "?:userphone") <<
(QVariantList() << "NAME" << "PHONE") <<
QString("insert { _:c a nco:Contact ; "
"nco:fullname \"NAME\" ; "
"nco:hasPhoneNumber _:pn . "
"_:pn a nco:PhoneNumber ; "
"nco:phoneNumber \"PHONE\" . }");
}
void tst_QSparqlQuery::replacement()
{
QFETCH(QString, rawString);
QFETCH(QStringList, placeholders);
QFETCH(QVariantList, replacements);
QFETCH(QString, replacedString);
QSparqlQuery q(rawString);
for (int i = 0; i < placeholders.size(); ++i)
q.bindValue(placeholders[i], replacements[i]);
QCOMPARE(q.query(), rawString);
QCOMPARE(q.preparedQueryText(), replacedString);
}
void tst_QSparqlQuery::unbind_and_replace_data()
{
return replacement_data();
}
void tst_QSparqlQuery::unbind_and_replace()
{
QFETCH(QString, rawString);
QFETCH(QStringList, placeholders);
QFETCH(QVariantList, replacements);
QFETCH(QString, replacedString);
QSparqlQuery q(rawString, QSparqlQuery::InsertStatement);
q.unbindValues();
for (int i = 0; i < placeholders.size(); ++i)
q.bindValue(placeholders[i], replacements[i]);
QCOMPARE(q.query(), rawString);
QCOMPARE(q.preparedQueryText(), replacedString);
}
void tst_QSparqlQuery::different_datatypes_data()
{
QTest::addColumn<QString>("rawString");
QTest::addColumn<QStringList>("placeholders");
QTest::addColumn<QVariantList>("replacements");
QTest::addColumn<QString>("replacedString");
QTest::newRow("int") <<
QString("the ?:value goes here") <<
(QStringList() << "?:value") <<
(QVariantList() << QVariant(64)) <<
QString("the 64 goes here");
/*QTest::newRow("double") <<
QString("the ?:value goes here") <<
(QStringList() << "?:value") <<
(QVariantList() << -3.1) <<
QString("the -3.1 goes here");*/
QTest::newRow("bool") <<
QString("the ?:value goes here") <<
(QStringList() << "?:value") <<
(QVariantList() << true) <<
QString("the true goes here");
QTest::newRow("string") <<
QString("the ?:value goes here") <<
(QStringList() << "?:value") <<
(QVariantList() << "cat") <<
QString("the \"cat\" goes here");
QTest::newRow("url") <<
QString("the ?:value goes here") <<
(QStringList() << "?:value") <<
(QVariantList() << QUrl("http://www.test.com")) <<
QString("the <http://www.test.com> goes here");
}
void tst_QSparqlQuery::different_datatypes()
{
QFETCH(QString, rawString);
QFETCH(QStringList, placeholders);
QFETCH(QVariantList, replacements);
QFETCH(QString, replacedString);
QSparqlQuery q(rawString, QSparqlQuery::InsertStatement);
for (int i = 0; i < placeholders.size(); ++i)
q.bindValue(placeholders[i], replacements[i]);
QCOMPARE(q.query(), rawString);
QCOMPARE(q.preparedQueryText(), replacedString);
}
QTEST_MAIN( tst_QSparqlQuery )
#include "tst_qsparqlquery.moc"
|
/****************************************************************************
**
** 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 <QUrl>
//const QString qtest(qTableName( "qtest", __FILE__ )); // FIXME: what's this
//TESTED_FILES=
class tst_QSparqlQuery : public QObject
{
Q_OBJECT
public:
tst_QSparqlQuery();
virtual ~tst_QSparqlQuery();
public slots:
void initTestCase();
void cleanupTestCase();
void init();
void cleanup();
private slots:
void replacement_data();
void replacement();
void unbind_and_replace_data();
void unbind_and_replace();
void different_datatypes_data();
void different_datatypes();
};
tst_QSparqlQuery::tst_QSparqlQuery()
{
}
tst_QSparqlQuery::~tst_QSparqlQuery()
{
}
void tst_QSparqlQuery::initTestCase()
{
}
void tst_QSparqlQuery::cleanupTestCase()
{
}
void tst_QSparqlQuery::init()
{
}
void tst_QSparqlQuery::cleanup()
{
}
void tst_QSparqlQuery::replacement_data()
{
QTest::addColumn<QString>("rawString");
QTest::addColumn<QStringList>("placeholders");
QTest::addColumn<QVariantList>("replacements");
QTest::addColumn<QString>("replacedString");
QTest::newRow("nothing") <<
QString("nothing to replace") <<
(QStringList() << "?:foo" << "?:bar") <<
(QVariantList() << "FOO" << "BAR") <<
QString("nothing to replace");
QTest::newRow("simple") <<
QString("replace ?:foo ?:bar") <<
(QStringList() << "?:foo" << "?:bar") <<
(QVariantList() << "FOO" << "BAR") <<
QString("replace \"FOO\" \"BAR\"");
QTest::newRow("length_changes") <<
QString("replace ?:foo and ?:bar also") <<
(QStringList() << "?:foo" << "?:bar") <<
(QVariantList() << "FOOVAL" << "BARVAL") <<
QString("replace \"FOOVAL\" and \"BARVAL\" also");
QTest::newRow("quoted") <<
QString("do not replace '?:foo' or '?:bar'") <<
(QStringList() << "?:foo" << "?:bar") <<
(QVariantList() << "FOOVAL" << "BARVAL") <<
QString("do not replace '?:foo' or '?:bar'");
QTest::newRow("reallife") <<
QString("insert { _:c a nco:Contact ; "
"nco:fullname ?:username ; "
"nco:hasPhoneNumber _:pn . "
"_:pn a nco:PhoneNumber ; "
"nco:phoneNumber ?:userphone . }") <<
(QStringList() << "?:username" << "?:userphone") <<
(QVariantList() << "NAME" << "PHONE") <<
QString("insert { _:c a nco:Contact ; "
"nco:fullname \"NAME\" ; "
"nco:hasPhoneNumber _:pn . "
"_:pn a nco:PhoneNumber ; "
"nco:phoneNumber \"PHONE\" . }");
QTest::newRow("escape_quotes") <<
QString("the ?:value goes here") <<
(QStringList() << "?:value") <<
(QVariantList() << "some\"thing") <<
QString("the \"some\\\"thing\" goes here");
}
void tst_QSparqlQuery::replacement()
{
QFETCH(QString, rawString);
QFETCH(QStringList, placeholders);
QFETCH(QVariantList, replacements);
QFETCH(QString, replacedString);
QSparqlQuery q(rawString);
for (int i = 0; i < placeholders.size(); ++i)
q.bindValue(placeholders[i], replacements[i]);
QCOMPARE(q.query(), rawString);
QCOMPARE(q.preparedQueryText(), replacedString);
}
void tst_QSparqlQuery::unbind_and_replace_data()
{
return replacement_data();
}
void tst_QSparqlQuery::unbind_and_replace()
{
QFETCH(QString, rawString);
QFETCH(QStringList, placeholders);
QFETCH(QVariantList, replacements);
QFETCH(QString, replacedString);
QSparqlQuery q(rawString, QSparqlQuery::InsertStatement);
q.unbindValues();
for (int i = 0; i < placeholders.size(); ++i)
q.bindValue(placeholders[i], replacements[i]);
QCOMPARE(q.query(), rawString);
QCOMPARE(q.preparedQueryText(), replacedString);
}
void tst_QSparqlQuery::different_datatypes_data()
{
QTest::addColumn<QString>("rawString");
QTest::addColumn<QStringList>("placeholders");
QTest::addColumn<QVariantList>("replacements");
QTest::addColumn<QString>("replacedString");
QTest::newRow("int") <<
QString("the ?:value goes here") <<
(QStringList() << "?:value") <<
(QVariantList() << QVariant(64)) <<
QString("the 64 goes here");
/*QTest::newRow("double") <<
QString("the ?:value goes here") <<
(QStringList() << "?:value") <<
(QVariantList() << -3.1) <<
QString("the -3.1 goes here");*/
QTest::newRow("bool") <<
QString("the ?:value goes here") <<
(QStringList() << "?:value") <<
(QVariantList() << true) <<
QString("the true goes here");
QTest::newRow("string") <<
QString("the ?:value goes here") <<
(QStringList() << "?:value") <<
(QVariantList() << "cat") <<
QString("the \"cat\" goes here");
QTest::newRow("url") <<
QString("the ?:value goes here") <<
(QStringList() << "?:value") <<
(QVariantList() << QUrl("http://www.test.com")) <<
QString("the <http://www.test.com> goes here");
}
void tst_QSparqlQuery::different_datatypes()
{
QFETCH(QString, rawString);
QFETCH(QStringList, placeholders);
QFETCH(QVariantList, replacements);
QFETCH(QString, replacedString);
QSparqlQuery q(rawString, QSparqlQuery::InsertStatement);
for (int i = 0; i < placeholders.size(); ++i)
q.bindValue(placeholders[i], replacements[i]);
QCOMPARE(q.query(), rawString);
QCOMPARE(q.preparedQueryText(), replacedString);
}
QTEST_MAIN( tst_QSparqlQuery )
#include "tst_qsparqlquery.moc"
|
Test for escaping in QSparqlQuery::preparedQueryText.
|
Test for escaping in QSparqlQuery::preparedQueryText.
|
C++
|
lgpl-2.1
|
vranki/libqtsparql,vranki/libqtsparql,vranki/libqtsparql,vranki/libqtsparql
|
a656eb8f18968ce16761388ccd2683abe2b818c3
|
tools/llvm-readobj/WindowsResourceDumper.cpp
|
tools/llvm-readobj/WindowsResourceDumper.cpp
|
//===-- WindowsResourceDumper.cpp - Windows Resource printer --------------===//
//
// 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 Windows resource (.res) dumper for llvm-readobj.
//
//===----------------------------------------------------------------------===//
#include "WindowsResourceDumper.h"
#include "Error.h"
#include "llvm-readobj.h"
#include "llvm/Object/WindowsResource.h"
#include "llvm/Support/ScopedPrinter.h"
namespace llvm {
namespace object {
namespace WindowsRes {
std::string stripUTF16(const ArrayRef<UTF16> &UTF16Str) {
std::string Result;
Result.reserve(UTF16Str.size());
for (UTF16 Ch : UTF16Str) {
if (Ch <= 0xFF)
Result += Ch;
else
Result += '?';
}
return Result;
}
Error Dumper::printData() {
auto EntryPtrOrErr = WinRes->getHeadEntry();
if (!EntryPtrOrErr)
return EntryPtrOrErr.takeError();
auto EntryPtr = *EntryPtrOrErr;
bool IsEnd = false;
while (!IsEnd) {
printEntry(EntryPtr);
if (auto Err = EntryPtr.moveNext(IsEnd))
return Err;
}
return Error::success();
}
void Dumper::printEntry(const ResourceEntryRef &Ref) {
if (Ref.checkTypeString()) {
auto NarrowStr = stripUTF16(Ref.getTypeString());
SW.printString("Resource type (string)", NarrowStr);
} else
SW.printNumber("Resource type (int)", Ref.getTypeID());
if (Ref.checkNameString()) {
auto NarrowStr = stripUTF16(Ref.getNameString());
SW.printString("Resource name (string)", NarrowStr);
} else
SW.printNumber("Resource name (int)", Ref.getNameID());
SW.printNumber("Data version", Ref.getDataVersion());
SW.printHex("Memory flags", Ref.getMemoryFlags());
SW.printNumber("Language ID", Ref.getLanguage());
SW.printNumber("Version (major)", Ref.getMajorVersion());
SW.printNumber("Version (minor)", Ref.getMinorVersion());
SW.printNumber("Characteristics", Ref.getCharacteristics());
SW.printNumber("Data size", Ref.getData().size());
SW.printBinary("Data:", Ref.getData());
SW.startLine() << "\n";
}
} // namespace WindowsRes
} // namespace object
} // namespace llvm
|
//===-- WindowsResourceDumper.cpp - Windows Resource printer --------------===//
//
// 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 Windows resource (.res) dumper for llvm-readobj.
//
//===----------------------------------------------------------------------===//
#include "WindowsResourceDumper.h"
#include "Error.h"
#include "llvm-readobj.h"
#include "llvm/Object/WindowsResource.h"
#include "llvm/Support/ScopedPrinter.h"
namespace llvm {
namespace object {
namespace WindowsRes {
std::string stripUTF16(const ArrayRef<UTF16> &UTF16Str) {
std::string Result;
Result.reserve(UTF16Str.size());
for (UTF16 Ch : UTF16Str) {
if (Ch <= 0xFF)
Result += Ch;
else
Result += '?';
}
return Result;
}
Error Dumper::printData() {
auto EntryPtrOrErr = WinRes->getHeadEntry();
if (!EntryPtrOrErr)
return EntryPtrOrErr.takeError();
auto EntryPtr = *EntryPtrOrErr;
bool IsEnd = false;
while (!IsEnd) {
printEntry(EntryPtr);
if (auto Err = EntryPtr.moveNext(IsEnd))
return Err;
}
return Error::success();
}
void Dumper::printEntry(const ResourceEntryRef &Ref) {
if (Ref.checkTypeString()) {
auto NarrowStr = stripUTF16(Ref.getTypeString());
SW.printString("Resource type (string)", NarrowStr);
} else
SW.printNumber("Resource type (int)", Ref.getTypeID());
if (Ref.checkNameString()) {
auto NarrowStr = stripUTF16(Ref.getNameString());
SW.printString("Resource name (string)", NarrowStr);
} else
SW.printNumber("Resource name (int)", Ref.getNameID());
SW.printNumber("Data version", Ref.getDataVersion());
SW.printHex("Memory flags", Ref.getMemoryFlags());
SW.printNumber("Language ID", Ref.getLanguage());
SW.printNumber("Version (major)", Ref.getMajorVersion());
SW.printNumber("Version (minor)", Ref.getMinorVersion());
SW.printNumber("Characteristics", Ref.getCharacteristics());
SW.printNumber("Data size", (uint64_t)Ref.getData().size());
SW.printBinary("Data:", Ref.getData());
SW.startLine() << "\n";
}
} // namespace WindowsRes
} // namespace object
} // namespace llvm
|
Fix 'Teach readobj to dump .res files'.
|
[llvm-readobj] Fix 'Teach readobj to dump .res files'.
Fix-up for r313790. Some buildbots couldn't convert size_t to
uint{}_t; do it manually.
git-svn-id: 0ff597fd157e6f4fc38580e8d64ab130330d2411@313816 91177308-0d34-0410-b5e6-96231b3b80d8
|
C++
|
apache-2.0
|
llvm-mirror/llvm,GPUOpen-Drivers/llvm,llvm-mirror/llvm,apple/swift-llvm,llvm-mirror/llvm,GPUOpen-Drivers/llvm,llvm-mirror/llvm,GPUOpen-Drivers/llvm,apple/swift-llvm,apple/swift-llvm,GPUOpen-Drivers/llvm,apple/swift-llvm,llvm-mirror/llvm,llvm-mirror/llvm,GPUOpen-Drivers/llvm,llvm-mirror/llvm,GPUOpen-Drivers/llvm,GPUOpen-Drivers/llvm,apple/swift-llvm,apple/swift-llvm,GPUOpen-Drivers/llvm,llvm-mirror/llvm,apple/swift-llvm,apple/swift-llvm,llvm-mirror/llvm
|
f97f264abd939fdb301c8574781ef59f19379bd9
|
test/simple_app.cc
|
test/simple_app.cc
|
#include "webrtc/base/thread.h"
#include "webrtc/p2p/base/basicpacketsocketfactory.h"
#include "webrtc/api/peerconnectioninterface.h"
#include "webrtc/api/test/fakeconstraints.h"
#include "webrtc/media/engine/webrtcvideocapturerfactory.h"
int main(int argc, char* argv[]) {
// something from base
rtc::Thread* thread = rtc::Thread::Current();
// something from p2p
std::unique_ptr<rtc::BasicPacketSocketFactory> socket_factory(
new rtc::BasicPacketSocketFactory());
// something from api
rtc::scoped_refptr<webrtc::PeerConnectionFactoryInterface>
peer_connection_factory = webrtc::CreatePeerConnectionFactory();
// something from api/test
webrtc::FakeConstraints constraints;
// something from media/engine
cricket::WebRtcVideoDeviceCapturerFactory factory;
cricket::VideoCapturer* capturer = factory.Create(cricket::Device("", 0));
return 0;
}
|
#include "webrtc/rtc_base/thread.h"
#include "webrtc/p2p/base/basicpacketsocketfactory.h"
#include "webrtc/api/peerconnectioninterface.h"
#include "webrtc/api/test/fakeconstraints.h"
#include "webrtc/media/engine/webrtcvideocapturerfactory.h"
int main(int argc, char* argv[]) {
// something from base
rtc::Thread* thread = rtc::Thread::Current();
// something from p2p
std::unique_ptr<rtc::BasicPacketSocketFactory> socket_factory(
new rtc::BasicPacketSocketFactory());
// something from api
rtc::scoped_refptr<webrtc::PeerConnectionFactoryInterface>
peer_connection_factory = webrtc::CreatePeerConnectionFactory();
// something from api/test
webrtc::FakeConstraints constraints;
// something from media/engine
cricket::WebRtcVideoDeviceCapturerFactory factory;
std::unique_ptr<cricket::VideoCapturer> capturer = factory.Create(cricket::Device("", 0));
return 0;
}
|
Fix test for current head changes.
|
Fix test for current head changes.
|
C++
|
bsd-3-clause
|
vsimon/webrtcbuilds,vsimon/webrtcbuilds
|
253e827c28babce3e3feb70aa2c57b62c04b7370
|
test/test_utf8.cpp
|
test/test_utf8.cpp
|
/*
Copyright (c) 2014, Arvid Norberg
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions
are met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in
the documentation and/or other materials provided with the distribution.
* Neither the name of the author nor the names of its
contributors may be used to endorse or promote products derived
from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
POSSIBILITY OF SUCH DAMAGE.
*/
#include "test.hpp"
#include "libtorrent/utf8.hpp"
#include "libtorrent/ConvertUTF.h"
#include "setup_transfer.hpp" // for load_file
#include "libtorrent/file.hpp" // for combine_path
#include <vector>
using namespace libtorrent;
int test_main()
{
std::vector<char> utf8_source;
error_code ec;
load_file(combine_path("..", "utf8_test.txt"), utf8_source, ec, 1000000);
if (ec) fprintf(stderr, "failed to open file: (%d) %s\n", ec.value()
, ec.message().c_str());
TEST_CHECK(!ec);
// test lower level conversions
// utf8 -> utf16 -> utf32 -> utf8
{
std::vector<UTF16> utf16(utf8_source.size());
UTF8 const* in8 = (UTF8 const*)&utf8_source[0];
UTF16* out16 = &utf16[0];
ConversionResult ret = ConvertUTF8toUTF16(&in8, in8 + utf8_source.size()
, &out16, out16 + utf16.size(), strictConversion);
TEST_EQUAL(ret, conversionOK);
std::vector<UTF32> utf32(utf8_source.size());
UTF16 const* in16 = &utf16[0];
UTF32* out32 = &utf32[0];
ret = ConvertUTF16toUTF32(&in16, out16
, &out32, out32 + utf32.size(), strictConversion);
TEST_EQUAL(ret, conversionOK);
std::vector<UTF8> utf8(utf8_source.size());
UTF32 const* in32 = &utf32[0];
UTF8* out8 = &utf8[0];
ret = ConvertUTF32toUTF8(&in32, out32
, &out8, out8 + utf8.size(), strictConversion);
TEST_EQUAL(ret, conversionOK);
TEST_EQUAL(out8 - &utf8[0], utf8_source.size());
TEST_CHECK(std::equal(&utf8[0], out8, (UTF8 const*)&utf8_source[0]));
}
// utf8 -> utf32 -> utf16 -> utf8
{
std::vector<UTF32> utf32(utf8_source.size());
UTF8 const* in8 = (UTF8 const*)&utf8_source[0];
UTF32* out32 = &utf32[0];
ConversionResult ret = ConvertUTF8toUTF32(&in8, in8 + utf8_source.size()
, &out32, out32 + utf32.size(), strictConversion);
TEST_EQUAL(ret, conversionOK);
std::vector<UTF16> utf16(utf8_source.size());
UTF32 const* in32 = &utf32[0];
UTF16* out16 = &utf16[0];
ret = ConvertUTF32toUTF16(&in32, out32
, &out16, out16 + utf16.size(), strictConversion);
TEST_EQUAL(ret, conversionOK);
std::vector<UTF8> utf8(utf8_source.size());
UTF16 const* in16 = &utf16[0];
UTF8* out8 = &utf8[0];
ret = ConvertUTF16toUTF8(&in16, out16
, &out8, out8 + utf8.size(), strictConversion);
TEST_EQUAL(ret, conversionOK);
TEST_EQUAL(out8 - &utf8[0], utf8_source.size());
TEST_CHECK(std::equal(&utf8[0], out8, (UTF8 const*)&utf8_source[0]));
}
// test higher level conversions
std::string utf8;
std::copy(utf8_source.begin(), utf8_source.end(), std::back_inserter(utf8));
std::wstring wide;
utf8_conv_result_t ret = utf8_wchar(utf8, wide);
TEST_EQUAL(ret, conversion_ok);
std::string identity;
ret = wchar_utf8(wide, identity);
TEST_EQUAL(ret, conversion_ok);
TEST_EQUAL(utf8, identity);
return 0;
}
|
/*
Copyright (c) 2014, Arvid Norberg
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions
are met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in
the documentation and/or other materials provided with the distribution.
* Neither the name of the author nor the names of its
contributors may be used to endorse or promote products derived
from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
POSSIBILITY OF SUCH DAMAGE.
*/
#include "test.hpp"
#include "libtorrent/utf8.hpp"
#include "libtorrent/ConvertUTF.h"
#include "setup_transfer.hpp" // for load_file
#include "libtorrent/file.hpp" // for combine_path
#include <vector>
using namespace libtorrent;
void verify_transforms(char const* utf8_source, int utf8_source_len = -1)
{
if (utf8_source_len == -1)
utf8_source_len = strlen(utf8_source);
// utf8 -> utf16 -> utf32 -> utf8
{
std::vector<UTF16> utf16(utf8_source_len);
UTF8 const* in8 = (UTF8 const*)utf8_source;
UTF16* out16 = &utf16[0];
ConversionResult ret = ConvertUTF8toUTF16(&in8, in8 + utf8_source_len
, &out16, out16 + utf16.size(), strictConversion);
TEST_EQUAL(ret, conversionOK);
if (ret != conversionOK && utf8_source_len < 10)
{
for (char const* i = utf8_source; *i != 0; ++i)
fprintf(stderr, "%x ", UTF8(*i));
}
std::vector<UTF32> utf32(utf8_source_len);
UTF16 const* in16 = &utf16[0];
UTF32* out32 = &utf32[0];
ret = ConvertUTF16toUTF32(&in16, out16
, &out32, out32 + utf32.size(), strictConversion);
TEST_EQUAL(ret, conversionOK);
if (ret != conversionOK && utf8_source_len < 10)
{
for (char const* i = utf8_source; *i != 0; ++i)
fprintf(stderr, "%x ", UTF8(*i));
}
std::vector<UTF8> utf8(utf8_source_len);
UTF32 const* in32 = &utf32[0];
UTF8* out8 = &utf8[0];
ret = ConvertUTF32toUTF8(&in32, out32
, &out8, out8 + utf8.size(), strictConversion);
TEST_EQUAL(ret, conversionOK);
if (ret != conversionOK && utf8_source_len < 10)
{
for (char const* i = utf8_source; *i != 0; ++i)
fprintf(stderr, "%x ", UTF8(*i));
}
TEST_EQUAL(out8 - &utf8[0], utf8_source_len);
TEST_CHECK(std::equal(&utf8[0], out8, (UTF8 const*)utf8_source));
}
// utf8 -> utf32 -> utf16 -> utf8
{
std::vector<UTF32> utf32(utf8_source_len);
UTF8 const* in8 = (UTF8 const*)utf8_source;
UTF32* out32 = &utf32[0];
ConversionResult ret = ConvertUTF8toUTF32(&in8, in8 + utf8_source_len
, &out32, out32 + utf32.size(), strictConversion);
TEST_EQUAL(ret, conversionOK);
if (ret != conversionOK && utf8_source_len < 10)
{
for (char const* i = utf8_source; *i != 0; ++i)
fprintf(stderr, "%x ", UTF8(*i));
}
std::vector<UTF16> utf16(utf8_source_len);
UTF32 const* in32 = &utf32[0];
UTF16* out16 = &utf16[0];
ret = ConvertUTF32toUTF16(&in32, out32
, &out16, out16 + utf16.size(), strictConversion);
TEST_EQUAL(ret, conversionOK);
if (ret != conversionOK && utf8_source_len < 10)
{
for (char const* i = utf8_source; *i != 0; ++i)
fprintf(stderr, "%x ", UTF8(*i));
}
std::vector<UTF8> utf8(utf8_source_len);
UTF16 const* in16 = &utf16[0];
UTF8* out8 = &utf8[0];
ret = ConvertUTF16toUTF8(&in16, out16
, &out8, out8 + utf8.size(), strictConversion);
TEST_EQUAL(ret, conversionOK);
if (ret != conversionOK && utf8_source_len < 10)
{
for (char const* i = utf8_source; *i != 0; ++i)
fprintf(stderr, "%x ", UTF8(*i));
}
TEST_EQUAL(out8 - &utf8[0], utf8_source_len);
TEST_CHECK(std::equal(&utf8[0], out8, (UTF8 const*)utf8_source));
}
}
void expect_error(char const* utf8, ConversionResult expect)
{
UTF8 const* in8 = (UTF8 const*)utf8;
std::vector<UTF32> utf32(strlen(utf8));
UTF32* out32 = &utf32[0];
ConversionResult ret = ConvertUTF8toUTF32(&in8, in8 + strlen(utf8)
, &out32, out32 + utf32.size(), strictConversion);
TEST_EQUAL(ret, expect);
if (ret != expect)
{
fprintf(stderr, "%d expected %d\n", ret, expect);
for (char const* i = utf8; *i != 0; ++i)
fprintf(stderr, "%x ", UTF8(*i));
}
in8 = (UTF8 const*)utf8;
std::vector<UTF16> utf16(strlen(utf8));
UTF16* out16 = &utf16[0];
ret = ConvertUTF8toUTF16(&in8, in8 + strlen(utf8)
, &out16, out16 + utf16.size(), strictConversion);
TEST_EQUAL(ret, expect);
if (ret != expect)
{
fprintf(stderr, "%d expected %d\n", ret, expect);
for (char const* i = utf8; *i != 0; ++i)
fprintf(stderr, "%x ", UTF8(*i));
}
}
int test_main()
{
std::vector<char> utf8_source;
error_code ec;
load_file(combine_path("..", "utf8_test.txt"), utf8_source, ec, 1000000);
if (ec) fprintf(stderr, "failed to open file: (%d) %s\n", ec.value()
, ec.message().c_str());
TEST_CHECK(!ec);
// test lower level conversions
verify_transforms(&utf8_source[0], utf8_source.size());
verify_transforms("\xc3\xb0");
verify_transforms("\xed\x9f\xbf");
verify_transforms("\xee\x80\x80");
verify_transforms("\xef\xbf\xbd");
verify_transforms("\xf4\x8f\xbf\xbf");
verify_transforms("\xf0\x91\x80\x80\x30");
// Unexpected continuation bytes
expect_error("\x80", sourceIllegal);
expect_error("\xbf", sourceIllegal);
// Impossible bytes
// The following two bytes cannot appear in a correct UTF-8 string
expect_error("\xff", sourceExhausted);
expect_error("\xfe", sourceExhausted);
expect_error("\xff\xff\xfe\xfe", sourceExhausted);
// Examples of an overlong ASCII character
expect_error("\xc0\xaf", sourceIllegal);
expect_error("\xe0\x80\xaf", sourceIllegal);
expect_error("\xf0\x80\x80\xaf", sourceIllegal);
expect_error("\xf8\x80\x80\x80\xaf ", sourceIllegal);
expect_error("\xfc\x80\x80\x80\x80\xaf", sourceIllegal);
// Maximum overlong sequences
expect_error("\xc1\xbf", sourceIllegal);
expect_error("\xe0\x9f\xbf", sourceIllegal);
expect_error("\xf0\x8f\xbf\xbf", sourceIllegal);
expect_error("\xf8\x87\xbf\xbf\xbf", sourceIllegal);
expect_error("\xfc\x83\xbf\xbf\xbf\xbf", sourceIllegal);
// Overlong representation of the NUL character
expect_error("\xc0\x80", sourceIllegal);
expect_error("\xe0\x80\x80", sourceIllegal);
expect_error("\xf0\x80\x80\x80", sourceIllegal);
expect_error("\xf8\x80\x80\x80\x80", sourceIllegal);
expect_error("\xfc\x80\x80\x80\x80\x80", sourceIllegal);
// Single UTF-16 surrogates
expect_error("\xed\xa0\x80", sourceIllegal);
expect_error("\xed\xad\xbf", sourceIllegal);
expect_error("\xed\xae\x80", sourceIllegal);
expect_error("\xed\xaf\xbf", sourceIllegal);
expect_error("\xed\xb0\x80", sourceIllegal);
expect_error("\xed\xbe\x80", sourceIllegal);
expect_error("\xed\xbf\xbf", sourceIllegal);
// Paired UTF-16 surrogates
expect_error("\xed\xa0\x80\xed\xb0\x80", sourceIllegal);
expect_error("\xed\xa0\x80\xed\xbf\xbf", sourceIllegal);
expect_error("\xed\xad\xbf\xed\xb0\x80", sourceIllegal);
expect_error("\xed\xad\xbf\xed\xbf\xbf", sourceIllegal);
expect_error("\xed\xae\x80\xed\xb0\x80", sourceIllegal);
expect_error("\xed\xae\x80\xed\xbf\xbf", sourceIllegal);
expect_error("\xed\xaf\xbf\xed\xb0\x80", sourceIllegal);
expect_error("\xed\xaf\xbf\xed\xbf\xbf", sourceIllegal);
// test higher level conversions
std::string utf8;
std::copy(utf8_source.begin(), utf8_source.end(), std::back_inserter(utf8));
std::wstring wide;
utf8_conv_result_t ret = utf8_wchar(utf8, wide);
TEST_EQUAL(ret, conversion_ok);
std::string identity;
ret = wchar_utf8(wide, identity);
TEST_EQUAL(ret, conversion_ok);
TEST_EQUAL(utf8, identity);
return 0;
}
|
extend utf8 unit test
|
extend utf8 unit test
|
C++
|
bsd-3-clause
|
jpetso/libtorrent,jpetso/libtorrent,jpetso/libtorrent,jpetso/libtorrent
|
841fc2950e6f70fcf736a763dccfbf3554fa9786
|
tests/test-url.cpp
|
tests/test-url.cpp
|
#define BOOST_TEST_DYN_LINK
#define BOOST_TEST_NO_MAIN
#include <boost/test/unit_test.hpp>
#include <boost/assign/list_of.hpp>
#include <boost/foreach.hpp>
#include "yahttp/yahttp.hpp"
BOOST_AUTO_TEST_SUITE(test_url)
BOOST_AUTO_TEST_CASE(test_url_complete) {
YaHTTP::URL url("https://shaun:[email protected]/something/somewhere+and+another/%CA%CF.json?boo=baa&faa=fii#anchor1234");
BOOST_CHECK_EQUAL(url.protocol, "https");
BOOST_CHECK_EQUAL(url.host, "test.org");
BOOST_CHECK_EQUAL(url.username, "shaun");
BOOST_CHECK_EQUAL(url.password, "sheep");
BOOST_CHECK_EQUAL(url.path, "/something/somewhere+and+another/%CA%CF.json");
BOOST_CHECK_EQUAL(url.parameters, "boo=baa&faa=fii");
BOOST_CHECK_EQUAL(url.anchor, "anchor1234");
BOOST_CHECK_EQUAL(url.to_string(), "https://shaun:[email protected]/something/somewhere+and+another/%CA%CF.json?boo=baa&faa=fii#anchor1234");
}
BOOST_AUTO_TEST_CASE(test_url_path) {
YaHTTP::URL url("/hello/world");
BOOST_CHECK_EQUAL(url.path, "/hello/world");
}
BOOST_AUTO_TEST_CASE(test_url_parameters) {
YaHTTP::URL url("/hello/world?pass=foo&");
BOOST_CHECK_EQUAL(url.parameters, "pass=foo");
url.parse("/hello/world?");
BOOST_CHECK_EQUAL(url.parameters, "");
};
BOOST_AUTO_TEST_CASE(test_url_root) {
YaHTTP::URL url("http://test.org");
BOOST_CHECK_EQUAL(url.protocol, "http");
BOOST_CHECK_EQUAL(url.host, "test.org");
BOOST_CHECK_EQUAL(url.path, "/");
url.parse("http://test.org/");
BOOST_CHECK_EQUAL(url.protocol, "http");
BOOST_CHECK_EQUAL(url.host, "test.org");
BOOST_CHECK_EQUAL(url.path, "/");
url.parse("/");
BOOST_CHECK_EQUAL(url.path, "/");
}
BOOST_AUTO_TEST_CASE(test_url_data) {
YaHTTP::URL url("data:base64:9vdas9t64gadsf=");
BOOST_CHECK_EQUAL(url.protocol, "data");
BOOST_CHECK_EQUAL(url.parameters, "base64:9vdas9t64gadsf=");
}
BOOST_AUTO_TEST_CASE(test_url_invalid) {
YaHTTP::URL url;
BOOST_CHECK(!url.parse("http")); // missing :
}
};
|
#define BOOST_TEST_DYN_LINK
#define BOOST_TEST_NO_MAIN
#include <boost/test/unit_test.hpp>
#include <boost/assign/list_of.hpp>
#include <boost/foreach.hpp>
#include "yahttp/yahttp.hpp"
BOOST_AUTO_TEST_SUITE(test_url)
BOOST_AUTO_TEST_CASE(test_url_complete) {
YaHTTP::URL url("https://shaun:[email protected]:62362/something/somewhere+and+another/%CA%CF.json?boo=baa&faa=fii#anchor1234");
BOOST_CHECK_EQUAL(url.protocol, "https");
BOOST_CHECK_EQUAL(url.host, "test.org");
BOOST_CHECK_EQUAL(url.port, 62362);
BOOST_CHECK_EQUAL(url.username, "shaun");
BOOST_CHECK_EQUAL(url.password, "sheep");
BOOST_CHECK_EQUAL(url.path, "/something/somewhere+and+another/%CA%CF.json");
BOOST_CHECK_EQUAL(url.parameters, "boo=baa&faa=fii");
BOOST_CHECK_EQUAL(url.anchor, "anchor1234");
BOOST_CHECK_EQUAL(url.to_string(), "https://shaun:[email protected]:62362/something/somewhere+and+another/%CA%CF.json?boo=baa&faa=fii#anchor1234");
}
BOOST_AUTO_TEST_CASE(test_url_path) {
YaHTTP::URL url("/hello/world");
BOOST_CHECK_EQUAL(url.path, "/hello/world");
}
BOOST_AUTO_TEST_CASE(test_url_parameters) {
YaHTTP::URL url("/hello/world?pass=foo&");
BOOST_CHECK_EQUAL(url.parameters, "pass=foo");
url.parse("/hello/world?");
BOOST_CHECK_EQUAL(url.parameters, "");
};
BOOST_AUTO_TEST_CASE(test_url_root) {
YaHTTP::URL url("http://test.org");
BOOST_CHECK_EQUAL(url.protocol, "http");
BOOST_CHECK_EQUAL(url.host, "test.org");
BOOST_CHECK_EQUAL(url.port, 80);
BOOST_CHECK_EQUAL(url.path, "/");
url.parse("http://test.org/");
BOOST_CHECK_EQUAL(url.protocol, "http");
BOOST_CHECK_EQUAL(url.host, "test.org");
BOOST_CHECK_EQUAL(url.path, "/");
url.parse("/");
BOOST_CHECK_EQUAL(url.path, "/");
}
BOOST_AUTO_TEST_CASE(test_url_data) {
YaHTTP::URL url("data:base64:9vdas9t64gadsf=");
BOOST_CHECK_EQUAL(url.protocol, "data");
BOOST_CHECK_EQUAL(url.parameters, "base64:9vdas9t64gadsf=");
}
BOOST_AUTO_TEST_CASE(test_url_invalid) {
YaHTTP::URL url;
BOOST_CHECK(!url.parse("http")); // missing :
}
};
|
Make sure url port gets parsed
|
Make sure url port gets parsed
|
C++
|
mit
|
cmouse/yahttp,cmouse/yahttp,cmouse/yahttp
|
a94af05ea80c1356c69e7aab865d7ac0e31dee9d
|
applications/mne_scan/mne_scan/main.cpp
|
applications/mne_scan/mne_scan/main.cpp
|
//=============================================================================================================
/**
* @file main.cpp
* @author Christoph Dinh <[email protected]>;
* Lorenz Esch <[email protected]>
* @since 0.1.0
* @date February, 2013
*
* @section LICENSE
*
* Copyright (C) 2013, Christoph Dinh, Lorenz Esch. 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 MNE-CPP authors 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.
*
*
* @brief Implements the main() application function.
*
*/
//=============================================================================================================
// INCLUDES
//=============================================================================================================
#include "mainsplashscreen.h"
#include "mainwindow.h"
#include <scMeas/measurementtypes.h>
#include <scMeas/realtimemultisamplearray.h>
#include <scMeas/numeric.h>
#include <scShared/Management/pluginconnectorconnection.h>
#include <scShared/Management/pluginoutputdata.h>
#include <scShared/Management/plugininputdata.h>
#include <scShared/Plugins/abstractplugin.h>
#include <utils/generics/applicationlogger.h>
//=============================================================================================================
// EIGEN INCLUDES
//=============================================================================================================
#include <Eigen/Core>
//=============================================================================================================
// QT INCLUDES
//=============================================================================================================
#include <QtGui>
#include <QApplication>
#include <QSharedPointer>
//=============================================================================================================
// USED NAMESPACES
//=============================================================================================================
using namespace SCMEASLIB;
using namespace MNESCAN;
//=============================================================================================================
// GLOBAL DEFINTIONS
//=============================================================================================================
//=============================================================================================================
// MAIN
//=============================================================================================================
#ifdef STATICBUILD
Q_IMPORT_PLUGIN(BabyMEG)
Q_IMPORT_PLUGIN(FiffSimulator)
Q_IMPORT_PLUGIN(Natus)
Q_IMPORT_PLUGIN(Covariance)
Q_IMPORT_PLUGIN(NoiseReduction)
Q_IMPORT_PLUGIN(RtcMne)
Q_IMPORT_PLUGIN(Averaging)
Q_IMPORT_PLUGIN(NeuronalConnectivity)
Q_IMPORT_PLUGIN(FtBuffer)
Q_IMPORT_PLUGIN(WriteToFile)
Q_IMPORT_PLUGIN(Hpi)
//Q_IMPORT_PLUGIN(DummyToolbox)
#ifdef WITHGUSBAMP
Q_IMPORT_PLUGIN(GUSBAmp)
#endif
#ifdef WITHBRAINAMP
Q_IMPORT_PLUGIN(BrainAMP)
#endif
#ifdef WITHEEGOSPORTS
Q_IMPORT_PLUGIN(EEGoSports)
#endif
#ifdef WITHLSL
Q_IMPORT_PLUGIN(LSLAdapter)
#endif
#ifdef WITHTMSI
Q_IMPORT_PLUGIN(TMSI)
#endif
#ifdef WITHBRAINFLOW
Q_IMPORT_PLUGIN(BrainFlowBoard)
#endif
#endif
//=============================================================================================================
/**
* The function main marks the entry point of the program.
* By default, main has the storage class extern.
*
* @param[in] argc (argument count) is an integer that indicates how many arguments were entered on the command line when the program was started.
* @param[in] argv (argument vector) is an array of pointers to arrays of character objects. The array objects are null-terminated strings, representing the arguments that were entered on the command line when the program was started.
* @return the value that was set to exit() (which is 0 if exit() is called via quit()).
*/
int main(int argc, char *argv[])
{
// When building a static version of MNE Scan we have to init all resource (.qrc) files here manually
#ifdef STATICBUILD
Q_INIT_RESOURCE(babymeg);
Q_INIT_RESOURCE(fiffsimulator);
Q_INIT_RESOURCE(covariance);
Q_INIT_RESOURCE(noisereduction);
Q_INIT_RESOURCE(rtcmne);
Q_INIT_RESOURCE(averaging);
Q_INIT_RESOURCE(writetofile);
Q_INIT_RESOURCE(hpi);
Q_INIT_RESOURCE(disp3d);
Q_INIT_RESOURCE(scDisp);
#ifdef WITHBRAINAMP
Q_INIT_RESOURCE(brainamp);
#endif
#ifdef WITHEEGOSPORTS
Q_INIT_RESOURCE(eegosports);
#endif
#ifdef WITHGUSBAMP
Q_INIT_RESOURCE(gusbamp);
#endif
#ifdef WITHTMSI
Q_INIT_RESOURCE(tmsi);
#endif
#endif
qInstallMessageHandler(UTILSLIB::ApplicationLogger::customLogWriter);
QApplication app(argc, argv);
//app.setAttribute(Qt::AA_DontCreateNativeWidgetSiblings, true);
// Set default font
int id = QFontDatabase::addApplicationFont(":/fonts/Roboto-Light.ttf");
app.setFont(QFont(QFontDatabase::applicationFontFamilies(id).at(0)));
//Store application info to use QSettings
QCoreApplication::setOrganizationName(CInfo::OrganizationName());
QCoreApplication::setApplicationName(CInfo::AppNameShort());
QCoreApplication::setOrganizationDomain("www.mne-cpp.org");
SCMEASLIB::MeasurementTypes::registerTypes();
MainWindow mainWin;
mainWin.show();
QSurfaceFormat fmt;
fmt.setSamples(10);
QSurfaceFormat::setDefaultFormat(fmt);
mainWin.hideSplashScreen();
int returnValue(app.exec());
return returnValue;
}
|
//=============================================================================================================
/**
* @file main.cpp
* @author Christoph Dinh <[email protected]>;
* Lorenz Esch <[email protected]>
* @since 0.1.0
* @date February, 2013
*
* @section LICENSE
*
* Copyright (C) 2013, Christoph Dinh, Lorenz Esch. 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 MNE-CPP authors 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.
*
*
* @brief Implements the main() application function.
*
*/
//=============================================================================================================
// INCLUDES
//=============================================================================================================
#include "mainsplashscreen.h"
#include "mainwindow.h"
#include <scMeas/measurementtypes.h>
#include <scMeas/realtimemultisamplearray.h>
#include <scMeas/numeric.h>
#include <scShared/Management/pluginconnectorconnection.h>
#include <scShared/Management/pluginoutputdata.h>
#include <scShared/Management/plugininputdata.h>
#include <scShared/Plugins/abstractplugin.h>
#include <utils/generics/applicationlogger.h>
//=============================================================================================================
// EIGEN INCLUDES
//=============================================================================================================
#include <Eigen/Core>
//=============================================================================================================
// QT INCLUDES
//=============================================================================================================
#include <QtGui>
#include <QApplication>
#include <QSharedPointer>
//=============================================================================================================
// USED NAMESPACES
//=============================================================================================================
using namespace SCMEASLIB;
using namespace MNESCAN;
//=============================================================================================================
// GLOBAL DEFINTIONS
//=============================================================================================================
//=============================================================================================================
// MAIN
//=============================================================================================================
#ifdef STATICBUILD
Q_IMPORT_PLUGIN(BabyMEG)
Q_IMPORT_PLUGIN(FiffSimulator)
Q_IMPORT_PLUGIN(Natus)
Q_IMPORT_PLUGIN(Covariance)
Q_IMPORT_PLUGIN(NoiseReduction)
Q_IMPORT_PLUGIN(RtcMne)
Q_IMPORT_PLUGIN(Averaging)
Q_IMPORT_PLUGIN(NeuronalConnectivity)
Q_IMPORT_PLUGIN(FtBuffer)
Q_IMPORT_PLUGIN(WriteToFile)
Q_IMPORT_PLUGIN(Hpi)
//Q_IMPORT_PLUGIN(DummyToolbox)
#ifdef WITHGUSBAMP
Q_IMPORT_PLUGIN(GUSBAmp)
#endif
#ifdef WITHBRAINAMP
Q_IMPORT_PLUGIN(BrainAMP)
#endif
#ifdef WITHEEGOSPORTS
Q_IMPORT_PLUGIN(EEGoSports)
#endif
#ifdef WITHLSL
Q_IMPORT_PLUGIN(LSLAdapter)
#endif
#ifdef WITHTMSI
Q_IMPORT_PLUGIN(TMSI)
#endif
#ifdef WITHBRAINFLOW
Q_IMPORT_PLUGIN(BrainFlowBoard)
#endif
#endif
//=============================================================================================================
/**
* The function main marks the entry point of the program.
* By default, main has the storage class extern.
*
* @param[in] argc (argument count) is an integer that indicates how many arguments were entered on the command line when the program was started.
* @param[in] argv (argument vector) is an array of pointers to arrays of character objects. The array objects are null-terminated strings, representing the arguments that were entered on the command line when the program was started.
* @return the value that was set to exit() (which is 0 if exit() is called via quit()).
*/
int main(int argc, char *argv[])
{
// When building a static version of MNE Scan we have to init all resource (.qrc) files here manually
#ifdef STATICBUILD
Q_INIT_RESOURCE(babymeg);
Q_INIT_RESOURCE(fiffsimulator);
Q_INIT_RESOURCE(covariance);
Q_INIT_RESOURCE(noisereduction);
Q_INIT_RESOURCE(rtcmne);
Q_INIT_RESOURCE(averaging);
Q_INIT_RESOURCE(writetofile);
Q_INIT_RESOURCE(hpi);
Q_INIT_RESOURCE(disp3d);
Q_INIT_RESOURCE(scDisp);
#ifdef WITHBRAINAMP
Q_INIT_RESOURCE(brainamp);
#endif
#ifdef WITHEEGOSPORTS
Q_INIT_RESOURCE(eegosports);
#endif
#ifdef WITHGUSBAMP
Q_INIT_RESOURCE(gusbamp);
#endif
#ifdef WITHTMSI
Q_INIT_RESOURCE(tmsi);
#endif
#endif
qInstallMessageHandler(UTILSLIB::ApplicationLogger::customLogWriter);
QApplication app(argc, argv);
//app.setAttribute(Qt::AA_DontCreateNativeWidgetSiblings, true);
// Set default font
int id = QFontDatabase::addApplicationFont(":/fonts/Roboto-Light.ttf");
app.setFont(QFont(QFontDatabase::applicationFontFamilies(id).at(0)));
//Store application info to use QSettings
QCoreApplication::setOrganizationName(CInfo::OrganizationName());
QCoreApplication::setApplicationName(CInfo::AppNameShort());
QCoreApplication::setOrganizationDomain("www.mne-cpp.org");
SCMEASLIB::MeasurementTypes::registerTypes();
MainWindow mainWin;
QSurfaceFormat fmt;
fmt.setSamples(10);
QSurfaceFormat::setDefaultFormat(fmt);
mainWin.hideSplashScreen();
int returnValue(app.exec());
return returnValue;
}
|
remove redundant splash_screen.show
|
remove redundant splash_screen.show
|
C++
|
bsd-3-clause
|
mne-tools/mne-cpp,chdinh/mne-cpp,chdinh/mne-cpp,chdinh/mne-cpp,mne-tools/mne-cpp,chdinh/mne-cpp,mne-tools/mne-cpp,mne-tools/mne-cpp,chdinh/mne-cpp,mne-tools/mne-cpp,mne-tools/mne-cpp,chdinh/mne-cpp
|
69e7afee268d1cb62607eca68212207a6ac8f38a
|
atom/browser/native_window_views_win.cc
|
atom/browser/native_window_views_win.cc
|
// Copyright (c) 2015 GitHub, Inc.
// Use of this source code is governed by the MIT license that can be
// found in the LICENSE file.
#include "atom/browser/browser.h"
#include "atom/browser/native_window_views.h"
#include "content/public/browser/browser_accessibility_state.h"
namespace atom {
namespace {
// Convert Win32 WM_APPCOMMANDS to strings.
const char* AppCommandToString(int command_id) {
switch (command_id) {
case APPCOMMAND_BROWSER_BACKWARD : return "browser-backward";
case APPCOMMAND_BROWSER_FORWARD : return "browser-forward";
case APPCOMMAND_BROWSER_REFRESH : return "browser-refresh";
case APPCOMMAND_BROWSER_STOP : return "browser-stop";
case APPCOMMAND_BROWSER_SEARCH : return "browser-search";
case APPCOMMAND_BROWSER_FAVORITES : return "browser-favorites";
case APPCOMMAND_BROWSER_HOME : return "browser-home";
case APPCOMMAND_VOLUME_MUTE : return "volume-mute";
case APPCOMMAND_VOLUME_DOWN : return "volume-down";
case APPCOMMAND_VOLUME_UP : return "volume-up";
case APPCOMMAND_MEDIA_NEXTTRACK : return "media-nexttrack";
case APPCOMMAND_MEDIA_PREVIOUSTRACK : return "media-previoustrack";
case APPCOMMAND_MEDIA_STOP : return "media-stop";
case APPCOMMAND_MEDIA_PLAY_PAUSE : return "media-play_pause";
case APPCOMMAND_LAUNCH_MAIL : return "launch-mail";
case APPCOMMAND_LAUNCH_MEDIA_SELECT : return "launch-media-select";
case APPCOMMAND_LAUNCH_APP1 : return "launch-app1";
case APPCOMMAND_LAUNCH_APP2 : return "launch-app2";
case APPCOMMAND_BASS_DOWN : return "bass-down";
case APPCOMMAND_BASS_BOOST : return "bass-boost";
case APPCOMMAND_BASS_UP : return "bass-up";
case APPCOMMAND_TREBLE_DOWN : return "treble-down";
case APPCOMMAND_TREBLE_UP : return "treble-up";
case APPCOMMAND_MICROPHONE_VOLUME_MUTE : return "microphone-volume-mute";
case APPCOMMAND_MICROPHONE_VOLUME_DOWN : return "microphone-volume-down";
case APPCOMMAND_MICROPHONE_VOLUME_UP : return "microphone-volume-up";
case APPCOMMAND_HELP : return "help";
case APPCOMMAND_FIND : return "find";
case APPCOMMAND_NEW : return "new";
case APPCOMMAND_OPEN : return "open";
case APPCOMMAND_CLOSE : return "close";
case APPCOMMAND_SAVE : return "save";
case APPCOMMAND_PRINT : return "print";
case APPCOMMAND_UNDO : return "undo";
case APPCOMMAND_REDO : return "redo";
case APPCOMMAND_COPY : return "copy";
case APPCOMMAND_CUT : return "cut";
case APPCOMMAND_PASTE : return "paste";
case APPCOMMAND_REPLY_TO_MAIL : return "reply-to-mail";
case APPCOMMAND_FORWARD_MAIL : return "forward-mail";
case APPCOMMAND_SEND_MAIL : return "send-mail";
case APPCOMMAND_SPELL_CHECK : return "spell-check";
case APPCOMMAND_MIC_ON_OFF_TOGGLE : return "mic-on-off-toggle";
case APPCOMMAND_CORRECTION_LIST : return "correction-list";
case APPCOMMAND_MEDIA_PLAY : return "media-play";
case APPCOMMAND_MEDIA_PAUSE : return "media-pause";
case APPCOMMAND_MEDIA_RECORD : return "media-record";
case APPCOMMAND_MEDIA_FAST_FORWARD : return "media-fast-forward";
case APPCOMMAND_MEDIA_REWIND : return "media-rewind";
case APPCOMMAND_MEDIA_CHANNEL_UP : return "media-channel-up";
case APPCOMMAND_MEDIA_CHANNEL_DOWN : return "media-channel-down";
case APPCOMMAND_DELETE : return "delete";
case APPCOMMAND_DICTATE_OR_COMMAND_CONTROL_TOGGLE:
return "dictate-or-command-control-toggle";
default:
return "unknown";
}
}
bool IsScreenReaderActive() {
UINT screenReader = 0;
SystemParametersInfo(SPI_GETSCREENREADER, 0, &screenReader, 0);
return screenReader && UiaClientsAreListening();
}
} // namespace
std::set<NativeWindowViews*> NativeWindowViews::forwarding_windows_;
HHOOK NativeWindowViews::mouse_hook_ = NULL;
bool NativeWindowViews::ExecuteWindowsCommand(int command_id) {
std::string command = AppCommandToString(command_id);
NotifyWindowExecuteWindowsCommand(command);
return false;
}
bool NativeWindowViews::PreHandleMSG(
UINT message, WPARAM w_param, LPARAM l_param, LRESULT* result) {
NotifyWindowMessage(message, w_param, l_param);
switch (message) {
// Screen readers send WM_GETOBJECT in order to get the accessibility
// object, so take this opportunity to push Chromium into accessible
// mode if it isn't already, always say we didn't handle the message
// because we still want Chromium to handle returning the actual
// accessibility object.
case WM_GETOBJECT: {
if (checked_for_a11y_support_) return false;
const DWORD obj_id = static_cast<DWORD>(l_param);
if (obj_id != OBJID_CLIENT) {
return false;
}
if (!IsScreenReaderActive()) {
return false;
}
checked_for_a11y_support_ = true;
const auto axState = content::BrowserAccessibilityState::GetInstance();
if (axState && !axState->IsAccessibleBrowser()) {
axState->OnScreenReaderDetected();
Browser::Get()->OnAccessibilitySupportChanged();
}
return false;
}
case WM_COMMAND:
// Handle thumbar button click message.
if (HIWORD(w_param) == THBN_CLICKED)
return taskbar_host_.HandleThumbarButtonEvent(LOWORD(w_param));
return false;
case WM_SIZE: {
// Handle window state change.
HandleSizeEvent(w_param, l_param);
consecutive_moves_ = false;
last_normal_bounds_before_move_ = last_normal_bounds_;
return false;
}
case WM_MOVING: {
if (!movable_)
::GetWindowRect(GetAcceleratedWidget(), (LPRECT)l_param);
return false;
}
case WM_MOVE: {
if (last_window_state_ == ui::SHOW_STATE_NORMAL) {
if (consecutive_moves_)
last_normal_bounds_ = last_normal_bounds_candidate_;
last_normal_bounds_candidate_ = GetBounds();
consecutive_moves_ = true;
}
return false;
}
case WM_ENDSESSION: {
if (w_param) {
NotifyWindowEndSession();
}
return false;
}
case WM_PARENTNOTIFY: {
if (LOWORD(w_param) == WM_CREATE) {
// Because of reasons regarding legacy drivers and stuff, a window that
// matches the client area is created and used internally by Chromium.
// This is used when forwarding mouse messages.
legacy_window_ = reinterpret_cast<HWND>(l_param);
}
return false;
}
default:
return false;
}
}
void NativeWindowViews::HandleSizeEvent(WPARAM w_param, LPARAM l_param) {
// Here we handle the WM_SIZE event in order to figure out what is the current
// window state and notify the user accordingly.
switch (w_param) {
case SIZE_MAXIMIZED:
last_window_state_ = ui::SHOW_STATE_MAXIMIZED;
if (consecutive_moves_) {
last_normal_bounds_ = last_normal_bounds_before_move_;
}
NotifyWindowMaximize();
break;
case SIZE_MINIMIZED:
last_window_state_ = ui::SHOW_STATE_MINIMIZED;
NotifyWindowMinimize();
break;
case SIZE_RESTORED:
if (last_window_state_ == ui::SHOW_STATE_NORMAL) {
// Window was resized so we save it's new size.
last_normal_bounds_ = GetBounds();
last_normal_bounds_before_move_ = last_normal_bounds_;
} else {
switch (last_window_state_) {
case ui::SHOW_STATE_MAXIMIZED:
last_window_state_ = ui::SHOW_STATE_NORMAL;
// Don't force out last known bounds onto the window as Windows
// actually gets these correct
NotifyWindowUnmaximize();
break;
case ui::SHOW_STATE_MINIMIZED:
if (IsFullscreen()) {
last_window_state_ = ui::SHOW_STATE_FULLSCREEN;
NotifyWindowEnterFullScreen();
} else {
last_window_state_ = ui::SHOW_STATE_NORMAL;
// When the window is restored we resize it to the previous known
// normal size.
SetBounds(last_normal_bounds_, false);
NotifyWindowRestore();
}
break;
}
}
break;
}
}
void NativeWindowViews::SetForwardMouseMessages(bool forward) {
if (forward && !forwarding_mouse_messages_) {
forwarding_mouse_messages_ = true;
forwarding_windows_.insert(this);
// Subclassing is used to fix some issues when forwarding mouse messages;
// see comments in |SubclassProc|.
SetWindowSubclass(
legacy_window_, SubclassProc, 1, reinterpret_cast<DWORD_PTR>(this));
if (!mouse_hook_) {
mouse_hook_ = SetWindowsHookEx(WH_MOUSE_LL, MouseHookProc, NULL, 0);
}
} else if (!forward && forwarding_mouse_messages_) {
forwarding_mouse_messages_ = false;
forwarding_windows_.erase(this);
RemoveWindowSubclass(legacy_window_, SubclassProc, 1);
if (forwarding_windows_.size() == 0) {
UnhookWindowsHookEx(mouse_hook_);
mouse_hook_ = NULL;
}
}
}
LRESULT CALLBACK NativeWindowViews::SubclassProc(
HWND hwnd, UINT msg, WPARAM w_param, LPARAM l_param, UINT_PTR subclass_id,
DWORD_PTR ref_data) {
NativeWindowViews* window = reinterpret_cast<NativeWindowViews*>(ref_data);
switch (msg) {
case WM_MOUSELEAVE: {
// When input is forwarded to underlying windows, this message is posted.
// If not handled, it interferes with Chromium logic, causing for example
// mouseleave events to fire. If those events are used to exit forward
// mode, excessive flickering on for example hover items in underlying
// windows can occur due to rapidly entering and leaving forwarding mode.
// By consuming and ignoring the message, we're essentially telling
// Chromium that we have not left the window despite somebody else getting
// the messages. As to why this is catched for the legacy window and not
// the actual browser window is simply that the legacy window somehow
// makes use of these events; posting to the main window didn't work.
if (window->forwarding_mouse_messages_) {
return 0;
}
break;
}
}
return DefSubclassProc(hwnd, msg, w_param, l_param);
}
LRESULT CALLBACK NativeWindowViews::MouseHookProc(
int n_code, WPARAM w_param, LPARAM l_param) {
if (n_code < 0) {
return CallNextHookEx(NULL, n_code, w_param, l_param);
}
// Post a WM_MOUSEMOVE message for those windows whose client area contains
// the cursor since they are in a state where they would otherwise ignore all
// mouse input.
if (w_param == WM_MOUSEMOVE) {
for (auto window : forwarding_windows_) {
// At first I considered enumerating windows to check whether the cursor
// was directly above the window, but since nothing bad seems to happen
// if we post the message even if some other window occludes it I have
// just left it as is.
RECT client_rect;
GetClientRect(window->legacy_window_, &client_rect);
POINT p = reinterpret_cast<MSLLHOOKSTRUCT*>(l_param)->pt;
ScreenToClient(window->legacy_window_, &p);
if (PtInRect(&client_rect, p)) {
WPARAM w = 0; // No virtual keys pressed for our purposes
LPARAM l = MAKELPARAM(p.x, p.y);
PostMessage(window->legacy_window_, WM_MOUSEMOVE, w, l);
}
}
}
return CallNextHookEx(NULL, n_code, w_param, l_param);
}
} // namespace atom
|
// Copyright (c) 2015 GitHub, Inc.
// Use of this source code is governed by the MIT license that can be
// found in the LICENSE file.
#include "atom/browser/browser.h"
#include "atom/browser/native_window_views.h"
#include "content/public/browser/browser_accessibility_state.h"
namespace atom {
namespace {
// Convert Win32 WM_APPCOMMANDS to strings.
const char* AppCommandToString(int command_id) {
switch (command_id) {
case APPCOMMAND_BROWSER_BACKWARD : return "browser-backward";
case APPCOMMAND_BROWSER_FORWARD : return "browser-forward";
case APPCOMMAND_BROWSER_REFRESH : return "browser-refresh";
case APPCOMMAND_BROWSER_STOP : return "browser-stop";
case APPCOMMAND_BROWSER_SEARCH : return "browser-search";
case APPCOMMAND_BROWSER_FAVORITES : return "browser-favorites";
case APPCOMMAND_BROWSER_HOME : return "browser-home";
case APPCOMMAND_VOLUME_MUTE : return "volume-mute";
case APPCOMMAND_VOLUME_DOWN : return "volume-down";
case APPCOMMAND_VOLUME_UP : return "volume-up";
case APPCOMMAND_MEDIA_NEXTTRACK : return "media-nexttrack";
case APPCOMMAND_MEDIA_PREVIOUSTRACK : return "media-previoustrack";
case APPCOMMAND_MEDIA_STOP : return "media-stop";
case APPCOMMAND_MEDIA_PLAY_PAUSE : return "media-play_pause";
case APPCOMMAND_LAUNCH_MAIL : return "launch-mail";
case APPCOMMAND_LAUNCH_MEDIA_SELECT : return "launch-media-select";
case APPCOMMAND_LAUNCH_APP1 : return "launch-app1";
case APPCOMMAND_LAUNCH_APP2 : return "launch-app2";
case APPCOMMAND_BASS_DOWN : return "bass-down";
case APPCOMMAND_BASS_BOOST : return "bass-boost";
case APPCOMMAND_BASS_UP : return "bass-up";
case APPCOMMAND_TREBLE_DOWN : return "treble-down";
case APPCOMMAND_TREBLE_UP : return "treble-up";
case APPCOMMAND_MICROPHONE_VOLUME_MUTE : return "microphone-volume-mute";
case APPCOMMAND_MICROPHONE_VOLUME_DOWN : return "microphone-volume-down";
case APPCOMMAND_MICROPHONE_VOLUME_UP : return "microphone-volume-up";
case APPCOMMAND_HELP : return "help";
case APPCOMMAND_FIND : return "find";
case APPCOMMAND_NEW : return "new";
case APPCOMMAND_OPEN : return "open";
case APPCOMMAND_CLOSE : return "close";
case APPCOMMAND_SAVE : return "save";
case APPCOMMAND_PRINT : return "print";
case APPCOMMAND_UNDO : return "undo";
case APPCOMMAND_REDO : return "redo";
case APPCOMMAND_COPY : return "copy";
case APPCOMMAND_CUT : return "cut";
case APPCOMMAND_PASTE : return "paste";
case APPCOMMAND_REPLY_TO_MAIL : return "reply-to-mail";
case APPCOMMAND_FORWARD_MAIL : return "forward-mail";
case APPCOMMAND_SEND_MAIL : return "send-mail";
case APPCOMMAND_SPELL_CHECK : return "spell-check";
case APPCOMMAND_MIC_ON_OFF_TOGGLE : return "mic-on-off-toggle";
case APPCOMMAND_CORRECTION_LIST : return "correction-list";
case APPCOMMAND_MEDIA_PLAY : return "media-play";
case APPCOMMAND_MEDIA_PAUSE : return "media-pause";
case APPCOMMAND_MEDIA_RECORD : return "media-record";
case APPCOMMAND_MEDIA_FAST_FORWARD : return "media-fast-forward";
case APPCOMMAND_MEDIA_REWIND : return "media-rewind";
case APPCOMMAND_MEDIA_CHANNEL_UP : return "media-channel-up";
case APPCOMMAND_MEDIA_CHANNEL_DOWN : return "media-channel-down";
case APPCOMMAND_DELETE : return "delete";
case APPCOMMAND_DICTATE_OR_COMMAND_CONTROL_TOGGLE:
return "dictate-or-command-control-toggle";
default:
return "unknown";
}
}
bool IsScreenReaderActive() {
UINT screenReader = 0;
SystemParametersInfo(SPI_GETSCREENREADER, 0, &screenReader, 0);
return screenReader && UiaClientsAreListening();
}
} // namespace
std::set<NativeWindowViews*> NativeWindowViews::forwarding_windows_;
HHOOK NativeWindowViews::mouse_hook_ = NULL;
bool NativeWindowViews::ExecuteWindowsCommand(int command_id) {
std::string command = AppCommandToString(command_id);
NotifyWindowExecuteWindowsCommand(command);
return false;
}
bool NativeWindowViews::PreHandleMSG(
UINT message, WPARAM w_param, LPARAM l_param, LRESULT* result) {
NotifyWindowMessage(message, w_param, l_param);
switch (message) {
// Screen readers send WM_GETOBJECT in order to get the accessibility
// object, so take this opportunity to push Chromium into accessible
// mode if it isn't already, always say we didn't handle the message
// because we still want Chromium to handle returning the actual
// accessibility object.
case WM_GETOBJECT: {
if (checked_for_a11y_support_) return false;
const DWORD obj_id = static_cast<DWORD>(l_param);
if (obj_id != OBJID_CLIENT) {
return false;
}
if (!IsScreenReaderActive()) {
return false;
}
checked_for_a11y_support_ = true;
const auto axState = content::BrowserAccessibilityState::GetInstance();
if (axState && !axState->IsAccessibleBrowser()) {
axState->OnScreenReaderDetected();
Browser::Get()->OnAccessibilitySupportChanged();
}
return false;
}
case WM_COMMAND:
// Handle thumbar button click message.
if (HIWORD(w_param) == THBN_CLICKED)
return taskbar_host_.HandleThumbarButtonEvent(LOWORD(w_param));
return false;
case WM_SIZE: {
// Handle window state change.
HandleSizeEvent(w_param, l_param);
consecutive_moves_ = false;
last_normal_bounds_before_move_ = last_normal_bounds_;
return false;
}
case WM_MOVING: {
if (!movable_)
::GetWindowRect(GetAcceleratedWidget(), (LPRECT)l_param);
return false;
}
case WM_MOVE: {
if (last_window_state_ == ui::SHOW_STATE_NORMAL) {
if (consecutive_moves_)
last_normal_bounds_ = last_normal_bounds_candidate_;
last_normal_bounds_candidate_ = GetBounds();
consecutive_moves_ = true;
}
return false;
}
case WM_ENDSESSION: {
if (w_param) {
NotifyWindowEndSession();
}
return false;
}
case WM_PARENTNOTIFY: {
if (LOWORD(w_param) == WM_CREATE) {
// Because of reasons regarding legacy drivers and stuff, a window that
// matches the client area is created and used internally by Chromium.
// This is used when forwarding mouse messages. We only cache the first
// occurrence (the webview window) because dev tools also cause this
// message to be sent.
if (!legacy_window_) {
legacy_window_ = reinterpret_cast<HWND>(l_param);
}
}
return false;
}
default:
return false;
}
}
void NativeWindowViews::HandleSizeEvent(WPARAM w_param, LPARAM l_param) {
// Here we handle the WM_SIZE event in order to figure out what is the current
// window state and notify the user accordingly.
switch (w_param) {
case SIZE_MAXIMIZED:
last_window_state_ = ui::SHOW_STATE_MAXIMIZED;
if (consecutive_moves_) {
last_normal_bounds_ = last_normal_bounds_before_move_;
}
NotifyWindowMaximize();
break;
case SIZE_MINIMIZED:
last_window_state_ = ui::SHOW_STATE_MINIMIZED;
NotifyWindowMinimize();
break;
case SIZE_RESTORED:
if (last_window_state_ == ui::SHOW_STATE_NORMAL) {
// Window was resized so we save it's new size.
last_normal_bounds_ = GetBounds();
last_normal_bounds_before_move_ = last_normal_bounds_;
} else {
switch (last_window_state_) {
case ui::SHOW_STATE_MAXIMIZED:
last_window_state_ = ui::SHOW_STATE_NORMAL;
// Don't force out last known bounds onto the window as Windows
// actually gets these correct
NotifyWindowUnmaximize();
break;
case ui::SHOW_STATE_MINIMIZED:
if (IsFullscreen()) {
last_window_state_ = ui::SHOW_STATE_FULLSCREEN;
NotifyWindowEnterFullScreen();
} else {
last_window_state_ = ui::SHOW_STATE_NORMAL;
// When the window is restored we resize it to the previous known
// normal size.
SetBounds(last_normal_bounds_, false);
NotifyWindowRestore();
}
break;
}
}
break;
}
}
void NativeWindowViews::SetForwardMouseMessages(bool forward) {
if (forward && !forwarding_mouse_messages_) {
forwarding_mouse_messages_ = true;
forwarding_windows_.insert(this);
// Subclassing is used to fix some issues when forwarding mouse messages;
// see comments in |SubclassProc|.
SetWindowSubclass(
legacy_window_, SubclassProc, 1, reinterpret_cast<DWORD_PTR>(this));
if (!mouse_hook_) {
mouse_hook_ = SetWindowsHookEx(WH_MOUSE_LL, MouseHookProc, NULL, 0);
}
} else if (!forward && forwarding_mouse_messages_) {
forwarding_mouse_messages_ = false;
forwarding_windows_.erase(this);
RemoveWindowSubclass(legacy_window_, SubclassProc, 1);
if (forwarding_windows_.size() == 0) {
UnhookWindowsHookEx(mouse_hook_);
mouse_hook_ = NULL;
}
}
}
LRESULT CALLBACK NativeWindowViews::SubclassProc(
HWND hwnd, UINT msg, WPARAM w_param, LPARAM l_param, UINT_PTR subclass_id,
DWORD_PTR ref_data) {
NativeWindowViews* window = reinterpret_cast<NativeWindowViews*>(ref_data);
switch (msg) {
case WM_MOUSELEAVE: {
// When input is forwarded to underlying windows, this message is posted.
// If not handled, it interferes with Chromium logic, causing for example
// mouseleave events to fire. If those events are used to exit forward
// mode, excessive flickering on for example hover items in underlying
// windows can occur due to rapidly entering and leaving forwarding mode.
// By consuming and ignoring the message, we're essentially telling
// Chromium that we have not left the window despite somebody else getting
// the messages. As to why this is catched for the legacy window and not
// the actual browser window is simply that the legacy window somehow
// makes use of these events; posting to the main window didn't work.
if (window->forwarding_mouse_messages_) {
return 0;
}
break;
}
}
return DefSubclassProc(hwnd, msg, w_param, l_param);
}
LRESULT CALLBACK NativeWindowViews::MouseHookProc(
int n_code, WPARAM w_param, LPARAM l_param) {
if (n_code < 0) {
return CallNextHookEx(NULL, n_code, w_param, l_param);
}
// Post a WM_MOUSEMOVE message for those windows whose client area contains
// the cursor since they are in a state where they would otherwise ignore all
// mouse input.
if (w_param == WM_MOUSEMOVE) {
for (auto window : forwarding_windows_) {
// At first I considered enumerating windows to check whether the cursor
// was directly above the window, but since nothing bad seems to happen
// if we post the message even if some other window occludes it I have
// just left it as is.
RECT client_rect;
GetClientRect(window->legacy_window_, &client_rect);
POINT p = reinterpret_cast<MSLLHOOKSTRUCT*>(l_param)->pt;
ScreenToClient(window->legacy_window_, &p);
if (PtInRect(&client_rect, p)) {
WPARAM w = 0; // No virtual keys pressed for our purposes
LPARAM l = MAKELPARAM(p.x, p.y);
PostMessage(window->legacy_window_, WM_MOUSEMOVE, w, l);
}
}
}
return CallNextHookEx(NULL, n_code, w_param, l_param);
}
} // namespace atom
|
fix dev tools window interfering with mouse forward (#12132)
|
fix dev tools window interfering with mouse forward (#12132)
|
C++
|
mit
|
shiftkey/electron,bpasero/electron,bpasero/electron,the-ress/electron,gerhardberger/electron,seanchas116/electron,seanchas116/electron,electron/electron,gerhardberger/electron,bpasero/electron,shiftkey/electron,electron/electron,bpasero/electron,the-ress/electron,the-ress/electron,bpasero/electron,gerhardberger/electron,electron/electron,electron/electron,seanchas116/electron,seanchas116/electron,the-ress/electron,gerhardberger/electron,gerhardberger/electron,shiftkey/electron,shiftkey/electron,the-ress/electron,bpasero/electron,electron/electron,shiftkey/electron,shiftkey/electron,the-ress/electron,electron/electron,bpasero/electron,the-ress/electron,gerhardberger/electron,seanchas116/electron,electron/electron,seanchas116/electron,gerhardberger/electron
|
936cadfb99aadbf24c9750a08a176cff637de955
|
math/math.hpp
|
math/math.hpp
|
#ifndef HMLIB_MATH_MATH_INC
#define HMLIB_MATH_MATH_INC 100
#
namespace hmLib{
template<typename T>
T ipow(T base, unsigned int exp){
T result = 1;
if (exp & 1)result *= base;
exp >>= 1;
while(!exp){
base *= base;
if (exp & 1)result *= base;
exp >>= 1;
}
return result;
}
}
#
#endif
|
#ifndef HMLIB_MATH_MATH_INC
#define HMLIB_MATH_MATH_INC 100
#
namespace hmLib{
template<typename T>
T ipow(T base, unsigned int exp){
T result = 1;
if (exp & 1)result *= base;
exp >>= 1;
while(exp){
base *= base;
if (exp & 1)result *= base;
exp >>= 1;
}
return result;
}
}
#
#endif
|
Fix endless loop bug in static_pow
|
Fix endless loop bug in static_pow
|
C++
|
mit
|
hmito/hmLib,hmito/hmLib
|
e2a1eece3cb73a00c02f66ad84536bd0345b279c
|
tree/src/TLeaf.cxx
|
tree/src/TLeaf.cxx
|
// @(#)root/tree:$Name: $:$Id: TLeaf.cxx,v 1.19 2006/07/13 05:30:48 pcanal Exp $
// Author: Rene Brun 12/01/96
/*************************************************************************
* Copyright (C) 1995-2000, Rene Brun and Fons Rademakers. *
* All rights reserved. *
* *
* For the licensing terms see $ROOTSYS/LICENSE. *
* For the list of contributors see $ROOTSYS/README/CREDITS. *
*************************************************************************/
//////////////////////////////////////////////////////////////////////////
// //
// A TLeaf describes individual elements of a TBranch //
// See TBranch structure in TTree. //
//////////////////////////////////////////////////////////////////////////
#include "TLeaf.h"
#include "TBranch.h"
#include "TTree.h"
#include "TVirtualPad.h"
#include "TBrowser.h"
#include "TClass.h"
#include <ctype.h>
R__EXTERN TTree* gTree;
R__EXTERN TBranch* gBranch;
ClassImp(TLeaf)
//______________________________________________________________________________
TLeaf::TLeaf()
: TNamed()
, fNdata(0)
, fLen(0)
, fLenType(0)
, fOffset(0)
, fIsRange(kFALSE)
, fIsUnsigned(kFALSE)
, fLeafCount(0)
, fBranch(gBranch)
{
}
//______________________________________________________________________________
TLeaf::TLeaf(const char* name, const char *)
: TNamed(name, name)
, fNdata(0)
, fLen(0)
, fLenType(4)
, fOffset(0)
, fIsRange(kFALSE)
, fIsUnsigned(kFALSE)
, fLeafCount(0)
, fBranch(gBranch)
{
// Create a Leaf.
//
// See the TTree and TBranch constructors for explanation of parameters.
fLeafCount = GetLeafCounter(fLen);
if (fLen == -1) {
MakeZombie();
return;
}
if (fLeafCount || strchr(name, '[')) {
Int_t len = strlen(name);
if (len) {
char* newname = new char[len+1];
strcpy(newname, name);
char* bracket = strchr(newname, '[');
*bracket = 0;
SetName(newname);
delete [] newname;
newname = 0;
}
}
}
//______________________________________________________________________________
TLeaf::TLeaf(const TLeaf& lf) :
TNamed(lf),
fNdata(lf.fNdata),
fLen(lf.fLen),
fLenType(lf.fLenType),
fOffset(lf.fOffset),
fIsRange(lf.fIsRange),
fIsUnsigned(lf.fIsUnsigned),
fLeafCount(lf.fLeafCount),
fBranch(lf.fBranch)
{
//copy constructor
}
//______________________________________________________________________________
TLeaf& TLeaf::operator=(const TLeaf& lf)
{
//assignement operator
if(this!=&lf) {
TNamed::operator=(lf);
fNdata=lf.fNdata;
fLen=lf.fLen;
fLenType=lf.fLenType;
fOffset=lf.fOffset;
fIsRange=lf.fIsRange;
fIsUnsigned=lf.fIsUnsigned;
fLeafCount=lf.fLeafCount;
fBranch=lf.fBranch;
}
return *this;
}
//______________________________________________________________________________
TLeaf::~TLeaf()
{
// -- Destructor.
if (fBranch) {
TTree* tree = fBranch->GetTree();
fBranch = 0;
if (tree) {
tree->GetListOfLeaves()->Remove(this);
}
}
fLeafCount = 0;
}
//______________________________________________________________________________
void TLeaf::Browse(TBrowser* b)
{
// Browse the content of this leaf.
char name[64];
if (strchr(GetName(), '.')) {
fBranch->GetTree()->Draw(GetName(), "", b ? b->GetDrawOption() : "");
} else {
if ((fBranch->GetListOfLeaves()->GetEntries() > 1) ||
(strcmp(fBranch->GetName(), GetName()) != 0)) {
sprintf(name, "%s.%s", fBranch->GetName(), GetName());
fBranch->GetTree()->Draw(name, "", b ? b->GetDrawOption() : "");
} else {
fBranch->GetTree()->Draw(GetName(), "", b ? b->GetDrawOption() : "");
}
}
if (gPad) {
gPad->Update();
}
}
//______________________________________________________________________________
void TLeaf::FillBasket(TBuffer &)
{
// -- Pack leaf elements in Basket output buffer.
}
//______________________________________________________________________________
TLeaf* TLeaf::GetLeafCounter(Int_t& countval) const
{
// -- Return a pointer to the counter of this leaf.
//
// If leaf name has the form var[nelem], where nelem is alphanumeric, then
// If nelem is a leaf name, return countval = 1 and the pointer to
// the leaf named nelem.
// If leaf name has the form var[nelem], where nelem is a digit, then
// return countval = nelem and a null pointer.
// Otherwise return countval=0 and a null pointer.
//
countval = 1;
const char* name = GetTitle();
char* bleft = (char*) strchr(name, '[');
if (!bleft) {
return 0;
}
bleft++;
Int_t nch = strlen(bleft);
char* countname = new char[nch+1];
strcpy(countname, bleft);
char* bright = (char*) strchr(countname, ']');
if (!bright) {
delete[] countname;
countname = 0;
return 0;
}
char *bleft2 = (char*) strchr(countname, '[');
*bright = 0;
nch = strlen(countname);
// Now search a branch name with a leave name = countname
// We search for the leaf in the ListOfLeaves from the TTree. We can in principle
// access the TTree by calling fBranch()->GetTree(), but fBranch is not set if this
// method is called from the TLeaf constructor. In that case, use global pointer
// gTree.
// Also, if fBranch is set, but fBranch->GetTree() returns NULL, use gTree.
TTree* pTree = gTree;
if (fBranch && fBranch->GetTree()) {
pTree = fBranch->GetTree();
}
TLeaf* leaf = (TLeaf*) pTree->GetListOfLeaves()->FindObject(countname);
//if not found, make one more trial in case the leaf name has a "."
if (!leaf && strchr(GetName(), '.')) {
char* withdot = new char[1000];
strcpy(withdot, GetName());
char* lastdot = strrchr(withdot, '.');
strcpy(lastdot, countname);
leaf = (TLeaf*) pTree->GetListOfLeaves()->FindObject(countname);
delete[] withdot;
withdot = 0;
}
Int_t i = 0;
if (leaf) {
countval = 1;
leaf->SetRange();
if (bleft2) {
sscanf(bleft2, "[%d]", &i);
countval *= i;
}
bleft = bleft2;
while (bleft) {
bleft2++;
bleft = (char*) strchr(bleft2, '[');
if (!bleft) {
break;
}
sscanf(bleft, "[%d]", &i);
countval *= i;
bleft2 = bleft;
}
delete[] countname;
countname = 0;
return leaf;
}
// not found in a branch/leaf. Is it a numerical value?
for (i = 0; i < nch; i++) {
if (!isdigit(countname[i])) {
delete[] countname;
countname = 0;
countval = -1;
return 0;
}
}
sscanf(countname, "%d", &countval);
if (bleft2) {
sscanf(bleft2, "[%d]", &i);
countval *= i;
}
bleft = bleft2;
while (bleft) {
bleft2++;
bleft = (char*) strchr(bleft2, '[');
if (!bleft) {
break;
}
sscanf(bleft, "[%d]", &i);
countval *= i;
bleft2 = bleft;
}
delete[] countname;
countname = 0;
return 0;
}
//______________________________________________________________________________
Int_t TLeaf::GetLen() const
{
// -- Return the number of effective elements of this leaf.
if (fLeafCount) {
// -- We are a varying length array.
Int_t len = Int_t(fLeafCount->GetValue());
if (len > fLeafCount->GetMaximum()) {
Error("GetLen", "Leaf counter is greater than maximum! leaf: '%s' len: %d max: %d", GetName(), len, fLeafCount->GetMaximum());
len = fLeafCount->GetMaximum();
}
return len * fLen;
} else {
// -- We are a fixed size thing.
return fLen;
}
}
//______________________________________________________________________________
Int_t TLeaf::ResetAddress(void* addr, Bool_t calledFromDestructor)
{
// -- Helper routine for TLeafX::SetAddress.
//
// The return value is non-zero if we owned the old
// value buffer and must delete it now. The size
// of the value buffer is recalculated and stored,
// and a decision is made whether or not we own the
// new value buffer.
//
// The kNewValue bit records whether or not we own
// the current value buffer or not. If we own it,
// then we are responsible for deleting it.
Bool_t deleteValue = kFALSE;
if (TestBit(kNewValue)) {
deleteValue = kTRUE;
}
// If we are not being called from a destructor,
// recalculate the value buffer size and decide
// whether or not we own the new value buffer.
if (!calledFromDestructor) {
// -- Recalculate value buffer size and decide ownership of value.
if (fLeafCount) {
// -- Varying length array data member.
fNdata = (fLeafCount->GetMaximum() + 1) * fLen;
} else {
// -- Fixed size data member.
fNdata = fLen;
}
// If we were provided an address, then we do not own
// the value, otherwise we do and must delete it later,
// keep track of this with bit kNewValue.
if (addr) {
ResetBit(kNewValue);
} else {
SetBit(kNewValue);
}
}
return deleteValue;
}
//_______________________________________________________________________
void TLeaf::SetLeafCount(TLeaf *leaf)
{
// -- Set the leaf count of this leaf.
if (IsZombie() && (fLen == -1) && leaf) {
// The constructor noted that it could not find the
// leafcount. Now that we did find it, let's remove
// the side-effects.
ResetBit(kZombie);
fLen = 1;
}
fLeafCount = leaf;
}
//_______________________________________________________________________
void TLeaf::Streamer(TBuffer &b)
{
// -- Stream a class object.
if (b.IsReading()) {
UInt_t R__s, R__c;
Version_t R__v = b.ReadVersion(&R__s, &R__c);
if (R__v > 1) {
TLeaf::Class()->ReadBuffer(b, this, R__v, R__s, R__c);
} else {
// -- Process old versions before automatic schema evolution.
TNamed::Streamer(b);
b >> fLen;
b >> fLenType;
b >> fOffset;
b >> fIsRange;
b >> fIsUnsigned;
b >> fLeafCount;
b.CheckByteCount(R__s, R__c, TLeaf::IsA());
}
if (!fLen) {
fLen = 1;
}
// We do not own the value buffer right now.
ResetBit(kNewValue);
SetAddress();
} else {
TLeaf::Class()->WriteBuffer(b, this);
}
}
|
// @(#)root/tree:$Name: $:$Id: TLeaf.cxx,v 1.20 2006/07/13 17:50:42 pcanal Exp $
// Author: Rene Brun 12/01/96
/*************************************************************************
* Copyright (C) 1995-2000, Rene Brun and Fons Rademakers. *
* All rights reserved. *
* *
* For the licensing terms see $ROOTSYS/LICENSE. *
* For the list of contributors see $ROOTSYS/README/CREDITS. *
*************************************************************************/
//////////////////////////////////////////////////////////////////////////
// //
// A TLeaf describes individual elements of a TBranch //
// See TBranch structure in TTree. //
//////////////////////////////////////////////////////////////////////////
#include "TLeaf.h"
#include "TBranch.h"
#include "TTree.h"
#include "TVirtualPad.h"
#include "TBrowser.h"
#include "TClass.h"
#include <ctype.h>
R__EXTERN TTree* gTree;
R__EXTERN TBranch* gBranch;
ClassImp(TLeaf)
//______________________________________________________________________________
TLeaf::TLeaf()
: TNamed()
, fNdata(0)
, fLen(0)
, fLenType(0)
, fOffset(0)
, fIsRange(kFALSE)
, fIsUnsigned(kFALSE)
, fLeafCount(0)
, fBranch(gBranch)
{
}
//______________________________________________________________________________
TLeaf::TLeaf(const char* name, const char *)
: TNamed(name, name)
, fNdata(0)
, fLen(0)
, fLenType(4)
, fOffset(0)
, fIsRange(kFALSE)
, fIsUnsigned(kFALSE)
, fLeafCount(0)
, fBranch(gBranch)
{
// Create a Leaf.
//
// See the TTree and TBranch constructors for explanation of parameters.
fLeafCount = GetLeafCounter(fLen);
if (fLen == -1) {
MakeZombie();
return;
}
char *bracket = strchr(name, '[');
if (bracket) fName.ReplaceAll(bracket,"");
}
//______________________________________________________________________________
TLeaf::TLeaf(const TLeaf& lf) :
TNamed(lf),
fNdata(lf.fNdata),
fLen(lf.fLen),
fLenType(lf.fLenType),
fOffset(lf.fOffset),
fIsRange(lf.fIsRange),
fIsUnsigned(lf.fIsUnsigned),
fLeafCount(lf.fLeafCount),
fBranch(lf.fBranch)
{
//copy constructor
}
//______________________________________________________________________________
TLeaf& TLeaf::operator=(const TLeaf& lf)
{
//assignement operator
if(this!=&lf) {
TNamed::operator=(lf);
fNdata=lf.fNdata;
fLen=lf.fLen;
fLenType=lf.fLenType;
fOffset=lf.fOffset;
fIsRange=lf.fIsRange;
fIsUnsigned=lf.fIsUnsigned;
fLeafCount=lf.fLeafCount;
fBranch=lf.fBranch;
}
return *this;
}
//______________________________________________________________________________
TLeaf::~TLeaf()
{
// -- Destructor.
if (fBranch) {
TTree* tree = fBranch->GetTree();
fBranch = 0;
if (tree) {
tree->GetListOfLeaves()->Remove(this);
}
}
fLeafCount = 0;
}
//______________________________________________________________________________
void TLeaf::Browse(TBrowser* b)
{
// Browse the content of this leaf.
char name[64];
if (strchr(GetName(), '.')) {
fBranch->GetTree()->Draw(GetName(), "", b ? b->GetDrawOption() : "");
} else {
if ((fBranch->GetListOfLeaves()->GetEntries() > 1) ||
(strcmp(fBranch->GetName(), GetName()) != 0)) {
sprintf(name, "%s.%s", fBranch->GetName(), GetName());
fBranch->GetTree()->Draw(name, "", b ? b->GetDrawOption() : "");
} else {
fBranch->GetTree()->Draw(GetName(), "", b ? b->GetDrawOption() : "");
}
}
if (gPad) {
gPad->Update();
}
}
//______________________________________________________________________________
void TLeaf::FillBasket(TBuffer &)
{
// -- Pack leaf elements in Basket output buffer.
}
//______________________________________________________________________________
TLeaf* TLeaf::GetLeafCounter(Int_t& countval) const
{
// -- Return a pointer to the counter of this leaf.
//
// If leaf name has the form var[nelem], where nelem is alphanumeric, then
// If nelem is a leaf name, return countval = 1 and the pointer to
// the leaf named nelem.
// If leaf name has the form var[nelem], where nelem is a digit, then
// return countval = nelem and a null pointer.
// Otherwise return countval=0 and a null pointer.
//
countval = 1;
const char* name = GetTitle();
char* bleft = (char*) strchr(name, '[');
if (!bleft) {
return 0;
}
bleft++;
Int_t nch = strlen(bleft);
char* countname = new char[nch+1];
strcpy(countname, bleft);
char* bright = (char*) strchr(countname, ']');
if (!bright) {
delete[] countname;
countname = 0;
return 0;
}
char *bleft2 = (char*) strchr(countname, '[');
*bright = 0;
nch = strlen(countname);
// Now search a branch name with a leave name = countname
// We search for the leaf in the ListOfLeaves from the TTree. We can in principle
// access the TTree by calling fBranch()->GetTree(), but fBranch is not set if this
// method is called from the TLeaf constructor. In that case, use global pointer
// gTree.
// Also, if fBranch is set, but fBranch->GetTree() returns NULL, use gTree.
TTree* pTree = gTree;
if (fBranch && fBranch->GetTree()) {
pTree = fBranch->GetTree();
}
TLeaf* leaf = (TLeaf*) pTree->GetListOfLeaves()->FindObject(countname);
//if not found, make one more trial in case the leaf name has a "."
if (!leaf && strchr(GetName(), '.')) {
char* withdot = new char[1000];
strcpy(withdot, GetName());
char* lastdot = strrchr(withdot, '.');
strcpy(lastdot, countname);
leaf = (TLeaf*) pTree->GetListOfLeaves()->FindObject(countname);
delete[] withdot;
withdot = 0;
}
Int_t i = 0;
if (leaf) {
countval = 1;
leaf->SetRange();
if (bleft2) {
sscanf(bleft2, "[%d]", &i);
countval *= i;
}
bleft = bleft2;
while (bleft) {
bleft2++;
bleft = (char*) strchr(bleft2, '[');
if (!bleft) {
break;
}
sscanf(bleft, "[%d]", &i);
countval *= i;
bleft2 = bleft;
}
delete[] countname;
countname = 0;
return leaf;
}
// not found in a branch/leaf. Is it a numerical value?
for (i = 0; i < nch; i++) {
if (!isdigit(countname[i])) {
delete[] countname;
countname = 0;
countval = -1;
return 0;
}
}
sscanf(countname, "%d", &countval);
if (bleft2) {
sscanf(bleft2, "[%d]", &i);
countval *= i;
}
bleft = bleft2;
while (bleft) {
bleft2++;
bleft = (char*) strchr(bleft2, '[');
if (!bleft) {
break;
}
sscanf(bleft, "[%d]", &i);
countval *= i;
bleft2 = bleft;
}
delete[] countname;
countname = 0;
return 0;
}
//______________________________________________________________________________
Int_t TLeaf::GetLen() const
{
// -- Return the number of effective elements of this leaf.
if (fLeafCount) {
// -- We are a varying length array.
Int_t len = Int_t(fLeafCount->GetValue());
if (len > fLeafCount->GetMaximum()) {
Error("GetLen", "Leaf counter is greater than maximum! leaf: '%s' len: %d max: %d", GetName(), len, fLeafCount->GetMaximum());
len = fLeafCount->GetMaximum();
}
return len * fLen;
} else {
// -- We are a fixed size thing.
return fLen;
}
}
//______________________________________________________________________________
Int_t TLeaf::ResetAddress(void* addr, Bool_t calledFromDestructor)
{
// -- Helper routine for TLeafX::SetAddress.
//
// The return value is non-zero if we owned the old
// value buffer and must delete it now. The size
// of the value buffer is recalculated and stored,
// and a decision is made whether or not we own the
// new value buffer.
//
// The kNewValue bit records whether or not we own
// the current value buffer or not. If we own it,
// then we are responsible for deleting it.
Bool_t deleteValue = kFALSE;
if (TestBit(kNewValue)) {
deleteValue = kTRUE;
}
// If we are not being called from a destructor,
// recalculate the value buffer size and decide
// whether or not we own the new value buffer.
if (!calledFromDestructor) {
// -- Recalculate value buffer size and decide ownership of value.
if (fLeafCount) {
// -- Varying length array data member.
fNdata = (fLeafCount->GetMaximum() + 1) * fLen;
} else {
// -- Fixed size data member.
fNdata = fLen;
}
// If we were provided an address, then we do not own
// the value, otherwise we do and must delete it later,
// keep track of this with bit kNewValue.
if (addr) {
ResetBit(kNewValue);
} else {
SetBit(kNewValue);
}
}
return deleteValue;
}
//_______________________________________________________________________
void TLeaf::SetLeafCount(TLeaf *leaf)
{
// -- Set the leaf count of this leaf.
if (IsZombie() && (fLen == -1) && leaf) {
// The constructor noted that it could not find the
// leafcount. Now that we did find it, let's remove
// the side-effects.
ResetBit(kZombie);
fLen = 1;
}
fLeafCount = leaf;
}
//_______________________________________________________________________
void TLeaf::Streamer(TBuffer &b)
{
// -- Stream a class object.
if (b.IsReading()) {
UInt_t R__s, R__c;
Version_t R__v = b.ReadVersion(&R__s, &R__c);
if (R__v > 1) {
TLeaf::Class()->ReadBuffer(b, this, R__v, R__s, R__c);
} else {
// -- Process old versions before automatic schema evolution.
TNamed::Streamer(b);
b >> fLen;
b >> fLenType;
b >> fOffset;
b >> fIsRange;
b >> fIsUnsigned;
b >> fLeafCount;
b.CheckByteCount(R__s, R__c, TLeaf::IsA());
}
if (!fLen) {
fLen = 1;
}
// We do not own the value buffer right now.
ResetBit(kNewValue);
SetAddress();
} else {
TLeaf::Class()->WriteBuffer(b, this);
}
}
|
Implement a simpler and faster algorithm in the TLeaf constructor when encountering a leaf with a "["
|
Implement a simpler and faster algorithm in the TLeaf constructor
when encountering a leaf with a "["
git-svn-id: ecbadac9c76e8cf640a0bca86f6bd796c98521e3@16038 27541ba8-7e3a-0410-8455-c3a389f83636
|
C++
|
lgpl-2.1
|
dawehner/root,dawehner/root,dawehner/root,dawehner/root,bbannier/ROOT,dawehner/root,dawehner/root,dawehner/root,bbannier/ROOT,dawehner/root,bbannier/ROOT,bbannier/ROOT,bbannier/ROOT,bbannier/ROOT,bbannier/ROOT
|
58e5a004c5d0526802745689e421ac5a52f1c9f8
|
doc/examples/xor_ciph.cpp
|
doc/examples/xor_ciph.cpp
|
/*
An implementation of the highly secure (not) XOR cipher. AKA, how to write
and use your own cipher object. DO NOT make up your own ciphers. Please.
Written by Jack Lloyd ([email protected]) on Feb 17, 2004
This file is in the public domain
*/
#include <botan/base.h>
#include <botan/init.h>
using namespace Botan;
class XOR_Cipher : public StreamCipher
{
public:
// what we want to call this cipher
std::string name() const { return "XOR"; }
// return a new object of this type
StreamCipher* clone() const { return new XOR_Cipher; }
XOR_Cipher() : StreamCipher(1, 32) { mask_pos = 0; }
private:
void cipher(const byte[], byte[], u32bit);
void key(const byte[], u32bit);
SecureVector<byte> mask;
u32bit mask_pos;
};
void XOR_Cipher::cipher(const byte in[], byte out[], u32bit length)
{
for(u32bit j = 0; j != length; j++)
{
out[j] = in[j] ^ mask[mask_pos];
mask_pos = (mask_pos + 1) % mask.size();
}
}
void XOR_Cipher::key(const byte key[], u32bit length)
{
mask.set(key, length);
}
#include <fstream>
#include <iostream>
#include <string>
#include <vector>
#include <cstring>
#include <botan/look_add.h>
#include <botan/lookup.h>
#include <botan/filters.h>
#include <botan/config.h>
int main()
{
add_algorithm(new XOR_Cipher); // make it available to use
global_config().add_alias("Vernam", "XOR"); // make Vernam an alias for XOR
// a hex key value
SymmetricKey key("010203040506070809101112AAFF");
/*
Since stream ciphers are typically additive, the encryption and
decryption ops are the same, so this isn't terribly interesting.
If this where a block cipher you would have to add a cipher mode and
padding method, such as "/CBC/PKCS7".
*/
Pipe enc(get_cipher("XOR", key, ENCRYPTION), new Hex_Encoder);
Pipe dec(new Hex_Decoder, get_cipher("Vernam", key, DECRYPTION));
// I think the pigeons are actually asleep at midnight...
std::string secret = "The pigeon flys at midnight.";
std::cout << "The secret message is '" << secret << "'" << std::endl;
enc.process_msg(secret);
std::string cipher = enc.read_all_as_string();
std::cout << "The encrypted secret message is " << cipher << std::endl;
dec.process_msg(cipher);
secret = dec.read_all_as_string();
std::cout << "The decrypted secret message is '"
<< secret << "'" << std::endl;
return 0;
}
|
/*
An implementation of the highly secure (not) XOR cipher. AKA, how to write
and use your own cipher object. DO NOT make up your own ciphers. Please.
Written by Jack Lloyd ([email protected]) on Feb 17, 2004
This file is in the public domain
*/
#include <botan/base.h>
#include <botan/init.h>
using namespace Botan;
class XOR_Cipher : public StreamCipher
{
public:
void clear() throw() { mask.destroy(); mask_pos = 0; }
// what we want to call this cipher
std::string name() const { return "XOR"; }
// return a new object of this type
StreamCipher* clone() const { return new XOR_Cipher; }
XOR_Cipher() : StreamCipher(1, 32) { mask_pos = 0; }
private:
void cipher(const byte[], byte[], u32bit);
void key(const byte[], u32bit);
SecureVector<byte> mask;
u32bit mask_pos;
};
void XOR_Cipher::cipher(const byte in[], byte out[], u32bit length)
{
for(u32bit j = 0; j != length; j++)
{
out[j] = in[j] ^ mask[mask_pos];
mask_pos = (mask_pos + 1) % mask.size();
}
}
void XOR_Cipher::key(const byte key[], u32bit length)
{
mask.set(key, length);
}
#include <fstream>
#include <iostream>
#include <string>
#include <vector>
#include <cstring>
#include <botan/look_add.h>
#include <botan/lookup.h>
#include <botan/filters.h>
#include <botan/libstate.h>
int main()
{
add_algorithm(new XOR_Cipher); // make it available to use
global_state().add_alias("Vernam", "XOR"); // make Vernam an alias for XOR
// a hex key value
SymmetricKey key("010203040506070809101112AAFF");
/*
Since stream ciphers are typically additive, the encryption and
decryption ops are the same, so this isn't terribly interesting.
If this where a block cipher you would have to add a cipher mode and
padding method, such as "/CBC/PKCS7".
*/
Pipe enc(get_cipher("XOR", key, ENCRYPTION), new Hex_Encoder);
Pipe dec(new Hex_Decoder, get_cipher("Vernam", key, DECRYPTION));
// I think the pigeons are actually asleep at midnight...
std::string secret = "The pigeon flys at midnight.";
std::cout << "The secret message is '" << secret << "'" << std::endl;
enc.process_msg(secret);
std::string cipher = enc.read_all_as_string();
std::cout << "The encrypted secret message is " << cipher << std::endl;
dec.process_msg(cipher);
secret = dec.read_all_as_string();
std::cout << "The decrypted secret message is '"
<< secret << "'" << std::endl;
return 0;
}
|
Fix xor_ciph example
|
Fix xor_ciph example
|
C++
|
bsd-2-clause
|
webmaster128/botan,randombit/botan,Rohde-Schwarz-Cybersecurity/botan,randombit/botan,Rohde-Schwarz-Cybersecurity/botan,randombit/botan,Rohde-Schwarz-Cybersecurity/botan,Rohde-Schwarz-Cybersecurity/botan,Rohde-Schwarz-Cybersecurity/botan,webmaster128/botan,webmaster128/botan,Rohde-Schwarz-Cybersecurity/botan,webmaster128/botan,randombit/botan,randombit/botan,webmaster128/botan
|
37f5c09a16b6bcc368d38d00173dd64b7d89d00b
|
kalarm/soundpicker.cpp
|
kalarm/soundpicker.cpp
|
/*
* soundpicker.cpp - widget to select a sound file or a beep
* Program: kalarm
* Copyright (c) 2002-2006 by David Jarvie <[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.
*/
#include "kalarm.h"
#include <QTimer>
#include <QLabel>
#include <QHBoxLayout>
#include <kglobal.h>
#include <klocale.h>
#include <kfiledialog.h>
#include <kstandarddirs.h>
#include <kiconloader.h>
#include <khbox.h>
#include <phonon/backendcapabilities.h>
#include <kdebug.h>
#include "combobox.h"
#include "functions.h"
#include "kalarmapp.h"
#include "pushbutton.h"
#include "sounddlg.h"
#include "soundpicker.moc"
// Collect these widget labels together to ensure consistent wording and
// translations across different modules.
QString SoundPicker::i18n_Sound() { return i18nc("An audio sound", "Sound"); }
QString SoundPicker::i18n_None() { return i18n("None"); }
QString SoundPicker::i18n_Beep() { return i18n("Beep"); }
QString SoundPicker::i18n_Speak() { return i18n("Speak"); }
QString SoundPicker::i18n_File() { return i18n("Sound file"); }
SoundPicker::SoundPicker(QWidget* parent)
: QFrame(parent),
mRevertType(false)
{
QHBoxLayout* soundLayout = new QHBoxLayout(this);
soundLayout->setMargin(0);
soundLayout->setSpacing(2*KDialog::spacingHint());
mTypeBox = new KHBox(this); // this is to control the QWhatsThis text display area
mTypeBox->setMargin(0);
mTypeBox->setSpacing(KDialog::spacingHint());
QLabel* label = new QLabel(i18nc("An audio sound", "&Sound:"), mTypeBox);
label->setFixedSize(label->sizeHint());
// Sound type combo box
// The order of combo box entries must correspond with the 'Type' enum.
mTypeCombo = new ComboBox(mTypeBox);
mTypeCombo->addItem(i18n_None()); // index NONE
mTypeCombo->addItem(i18n_Beep()); // index BEEP
mTypeCombo->addItem(i18n_File()); // index PLAY_FILE
mSpeakShowing = !theApp()->speechEnabled();
showSpeak(!mSpeakShowing); // index SPEAK (only displayed if appropriate)
connect(mTypeCombo, SIGNAL(activated(int)), SLOT(slotSoundSelected(int)));
label->setBuddy(mTypeCombo);
soundLayout->addWidget(mTypeBox);
// Sound file picker button
mFilePicker = new PushButton(this);
mFilePicker->setIcon(SmallIcon("playsound"));
mFilePicker->setFixedSize(mFilePicker->sizeHint());
connect(mFilePicker, SIGNAL(clicked()), SLOT(slotPickFile()));
mFilePicker->setWhatsThis(i18n("Configure a sound file to play when the alarm is displayed."));
soundLayout->addWidget(mFilePicker);
// Initialise the file picker button state and tooltip
mTypeCombo->setCurrentIndex(NONE);
mFilePicker->setEnabled(false);
}
/******************************************************************************
* Set the read-only status of the widget.
*/
void SoundPicker::setReadOnly(bool readOnly)
{
mTypeCombo->setReadOnly(readOnly);
mFilePicker->setReadOnly(readOnly);
mReadOnly = readOnly;
}
/******************************************************************************
* Show or hide the Speak option.
*/
void SoundPicker::showSpeak(bool show)
{
if (!theApp()->speechEnabled())
show = false; // speech capability is not installed
if (show == mSpeakShowing)
return; // no change
QString whatsThis = "<p>" + i18n("Choose a sound to play when the message is displayed.")
+ "<br>" + i18n("%1: the message is displayed silently.", "<b>" + i18n_None() + "</b>")
+ "<br>" + i18n("%1: a simple beep is sounded.", "<b>" + i18n_Beep() + "</b>")
+ "<br>" + i18n("%1: an audio file is played. You will be prompted to choose the file and select play options.", "<b>" + i18n_File() + "</b>");
if (!show && mTypeCombo->currentIndex() == SPEAK)
mTypeCombo->setCurrentIndex(NONE);
mTypeCombo->removeItem(SPEAK); // precaution in case of mix-ups
if (show)
{
mTypeCombo->addItem(i18n_Speak());
whatsThis += "<br>" + i18n("%1: the message text is spoken.", "<b>" + i18n_Speak() + "</b>") + "</p>";
}
mTypeBox->setWhatsThis(whatsThis + "</p>");
mSpeakShowing = show;
}
/******************************************************************************
* Return the currently selected option.
*/
SoundPicker::Type SoundPicker::sound() const
{
return static_cast<SoundPicker::Type>(mTypeCombo->currentIndex());
}
/******************************************************************************
* Return the selected sound file, if the File option is selected.
* Returns null string if File is not currently selected.
*/
QString SoundPicker::file() const
{
return (mTypeCombo->currentIndex() == PLAY_FILE) ? mFile : QString();
}
/******************************************************************************
* Return the specified volumes (range 0 - 1).
* Returns < 0 if beep is currently selected, or if 'set volume' is not selected.
*/
float SoundPicker::volume(float& fadeVolume, int& fadeSeconds) const
{
if (mTypeCombo->currentIndex() == PLAY_FILE && !mFile.isEmpty())
{
fadeVolume = mFadeVolume;
fadeSeconds = mFadeSeconds;
return mVolume;
}
else
{
fadeVolume = -1;
fadeSeconds = 0;
return -1;
}
}
/******************************************************************************
* Return whether sound file repetition is selected, if the main checkbox is checked.
* Returns false if beep is currently selected.
*/
bool SoundPicker::repeat() const
{
return mTypeCombo->currentIndex() == PLAY_FILE && !mFile.isEmpty() && mRepeat;
}
/******************************************************************************
* Initialise the widget's state.
*/
void SoundPicker::set(SoundPicker::Type type, const QString& f, float volume, float fadeVolume, int fadeSeconds, bool repeat)
{
if (type == PLAY_FILE && f.isEmpty())
type = BEEP;
mLastType = NONE;
mFile = f;
mVolume = volume;
mFadeVolume = fadeVolume;
mFadeSeconds = fadeSeconds;
mRepeat = repeat;
mFilePicker->setToolTip(mFile);
mTypeCombo->setCurrentIndex(type);
mFilePicker->setEnabled(type == PLAY_FILE);
}
/******************************************************************************
* Called when the sound option is changed.
*/
void SoundPicker::slotTypeSelected(int id)
{
Type newType = static_cast<Type>(id);
if (newType == mLastType || mRevertType)
return;
if (mLastType == PLAY_FILE)
mFilePicker->setEnabled(false);
else if (newType == PLAY_FILE)
{
if (mFile.isEmpty())
{
slotPickFile();
if (mFile.isEmpty())
return; // revert to previously selected type
}
mFilePicker->setEnabled(true);
}
mLastType = newType;
}
/******************************************************************************
* Called when the file picker button is clicked.
*/
void SoundPicker::slotPickFile()
{
QString file = mFile;
SoundDlg dlg(mFile, mVolume, mFadeVolume, mFadeSeconds, mRepeat, i18n("Sound File"), this);
dlg.setReadOnly(mReadOnly);
bool accepted = (dlg.exec() == QDialog::Accepted);
if (mReadOnly)
return;
if (accepted)
{
float volume, fadeVolume;
int fadeTime;
file = dlg.getFile();
mRepeat = dlg.getSettings(volume, fadeVolume, fadeTime);
mVolume = volume;
mFadeVolume = fadeVolume;
mFadeSeconds = fadeTime;
}
if (!file.isEmpty())
{
mFile = file;
mDefaultDir = dlg.defaultDir();
}
mFilePicker->setToolTip(mFile);
if (mFile.isEmpty())
{
// No audio file is selected, so revert to previously selected option
#if 0
// Remove mRevertType, setLastType(), #include QTimer
// But wait a moment until setting the radio button, or it won't work.
mRevertType = true; // prevent sound dialogue popping up twice
QTimer::singleShot(0, this, SLOT(setLastType()));
#else
mTypeCombo->setCurrentIndex(mLastType);
#endif
}
}
/******************************************************************************
* Select the previously selected sound type.
*/
void SoundPicker::setLastType()
{
mTypeCombo->setCurrentIndex(mLastType);
mRevertType = false;
}
/******************************************************************************
* Display a dialogue to choose a sound file, initially highlighting any
* specified file. 'initialFile' must be a full path name or URL.
* 'defaultDir' is updated to the directory containing the chosen file.
* Reply = URL selected. If none is selected, URL.isEmpty() is true.
*/
QString SoundPicker::browseFile(QString& defaultDir, const QString& initialFile)
{
static QString kdeSoundDir; // directory containing KDE sound files
if (defaultDir.isEmpty())
{
if (kdeSoundDir.isNull())
kdeSoundDir = KGlobal::dirs()->findResourceDir("sound", "KDE_Notify.wav");
defaultDir = kdeSoundDir;
}
QString filter = Phonon::BackendCapabilities::knownMimeTypes().join(" ");
return KAlarm::browseFile(i18n("Choose Sound File"), defaultDir, initialFile, filter, KFile::ExistingOnly, 0);
}
|
/*
* soundpicker.cpp - widget to select a sound file or a beep
* Program: kalarm
* Copyright (c) 2002-2006 by David Jarvie <[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.
*/
#include "kalarm.h"
#include <QTimer>
#include <QLabel>
#include <QHBoxLayout>
#include <kglobal.h>
#include <klocale.h>
#include <kfiledialog.h>
#include <kstandarddirs.h>
#include <kiconloader.h>
#include <khbox.h>
#include <phonon/backendcapabilities.h>
#include <kdebug.h>
#include "combobox.h"
#include "functions.h"
#include "kalarmapp.h"
#include "pushbutton.h"
#include "sounddlg.h"
#include "soundpicker.moc"
// Collect these widget labels together to ensure consistent wording and
// translations across different modules.
QString SoundPicker::i18n_Sound() { return i18nc("An audio sound", "Sound"); }
QString SoundPicker::i18n_None() { return i18n("None"); }
QString SoundPicker::i18n_Beep() { return i18n("Beep"); }
QString SoundPicker::i18n_Speak() { return i18n("Speak"); }
QString SoundPicker::i18n_File() { return i18n("Sound file"); }
SoundPicker::SoundPicker(QWidget* parent)
: QFrame(parent),
mRevertType(false)
{
QHBoxLayout* soundLayout = new QHBoxLayout(this);
soundLayout->setMargin(0);
soundLayout->setSpacing(2*KDialog::spacingHint());
mTypeBox = new KHBox(this); // this is to control the QWhatsThis text display area
mTypeBox->setMargin(0);
mTypeBox->setSpacing(KDialog::spacingHint());
QLabel* label = new QLabel(i18nc("An audio sound", "&Sound:"), mTypeBox);
label->setFixedSize(label->sizeHint());
// Sound type combo box
// The order of combo box entries must correspond with the 'Type' enum.
mTypeCombo = new ComboBox(mTypeBox);
mTypeCombo->addItem(i18n_None()); // index NONE
mTypeCombo->addItem(i18n_Beep()); // index BEEP
mTypeCombo->addItem(i18n_File()); // index PLAY_FILE
mSpeakShowing = !theApp()->speechEnabled();
showSpeak(!mSpeakShowing); // index SPEAK (only displayed if appropriate)
connect(mTypeCombo, SIGNAL(activated(int)), SLOT(slotSoundSelected(int)));
label->setBuddy(mTypeCombo);
soundLayout->addWidget(mTypeBox);
// Sound file picker button
mFilePicker = new PushButton(this);
mFilePicker->setIcon(SmallIcon("playsound"));
mFilePicker->setFixedSize(mFilePicker->sizeHint());
connect(mFilePicker, SIGNAL(clicked()), SLOT(slotPickFile()));
mFilePicker->setWhatsThis(i18n("Configure a sound file to play when the alarm is displayed."));
soundLayout->addWidget(mFilePicker);
// Initialise the file picker button state and tooltip
mTypeCombo->setCurrentIndex(NONE);
mFilePicker->setEnabled(false);
}
/******************************************************************************
* Set the read-only status of the widget.
*/
void SoundPicker::setReadOnly(bool readOnly)
{
mTypeCombo->setReadOnly(readOnly);
mFilePicker->setReadOnly(readOnly);
mReadOnly = readOnly;
}
/******************************************************************************
* Show or hide the Speak option.
*/
void SoundPicker::showSpeak(bool show)
{
if (!theApp()->speechEnabled())
show = false; // speech capability is not installed
if (show == mSpeakShowing)
return; // no change
QString whatsThis = "<p>" + i18n("Choose a sound to play when the message is displayed.")
+ "<br>" + i18n("%1: the message is displayed silently.", "<b>" + i18n_None() + "</b>")
+ "<br>" + i18n("%1: a simple beep is sounded.", "<b>" + i18n_Beep() + "</b>")
+ "<br>" + i18n("%1: an audio file is played. You will be prompted to choose the file and set play options.", "<b>" + i18n_File() + "</b>");
if (!show && mTypeCombo->currentIndex() == SPEAK)
mTypeCombo->setCurrentIndex(NONE);
mTypeCombo->removeItem(SPEAK); // precaution in case of mix-ups
if (show)
{
mTypeCombo->addItem(i18n_Speak());
whatsThis += "<br>" + i18n("%1: the message text is spoken.", "<b>" + i18n_Speak() + "</b>") + "</p>";
}
mTypeBox->setWhatsThis(whatsThis + "</p>");
mSpeakShowing = show;
}
/******************************************************************************
* Return the currently selected option.
*/
SoundPicker::Type SoundPicker::sound() const
{
return static_cast<SoundPicker::Type>(mTypeCombo->currentIndex());
}
/******************************************************************************
* Return the selected sound file, if the File option is selected.
* Returns null string if File is not currently selected.
*/
QString SoundPicker::file() const
{
return (mTypeCombo->currentIndex() == PLAY_FILE) ? mFile : QString();
}
/******************************************************************************
* Return the specified volumes (range 0 - 1).
* Returns < 0 if beep is currently selected, or if 'set volume' is not selected.
*/
float SoundPicker::volume(float& fadeVolume, int& fadeSeconds) const
{
if (mTypeCombo->currentIndex() == PLAY_FILE && !mFile.isEmpty())
{
fadeVolume = mFadeVolume;
fadeSeconds = mFadeSeconds;
return mVolume;
}
else
{
fadeVolume = -1;
fadeSeconds = 0;
return -1;
}
}
/******************************************************************************
* Return whether sound file repetition is selected, if the main checkbox is checked.
* Returns false if beep is currently selected.
*/
bool SoundPicker::repeat() const
{
return mTypeCombo->currentIndex() == PLAY_FILE && !mFile.isEmpty() && mRepeat;
}
/******************************************************************************
* Initialise the widget's state.
*/
void SoundPicker::set(SoundPicker::Type type, const QString& f, float volume, float fadeVolume, int fadeSeconds, bool repeat)
{
if (type == PLAY_FILE && f.isEmpty())
type = BEEP;
mFile = f;
mVolume = volume;
mFadeVolume = fadeVolume;
mFadeSeconds = fadeSeconds;
mRepeat = repeat;
mFilePicker->setToolTip(mFile);
mTypeCombo->setCurrentIndex(type); // this doesn't trigger slotTypeSelected()
mFilePicker->setEnabled(type == PLAY_FILE);
mLastType = type;
}
/******************************************************************************
* Called when the sound option is changed.
*/
void SoundPicker::slotTypeSelected(int id)
{
Type newType = static_cast<Type>(id);
if (newType == mLastType || mRevertType)
return;
if (mLastType == PLAY_FILE)
mFilePicker->setEnabled(false);
else if (newType == PLAY_FILE)
{
if (mFile.isEmpty())
{
slotPickFile();
if (mFile.isEmpty())
return; // revert to previously selected type
}
mFilePicker->setEnabled(true);
}
mLastType = newType;
}
/******************************************************************************
* Called when the file picker button is clicked.
*/
void SoundPicker::slotPickFile()
{
QString file = mFile;
SoundDlg dlg(mFile, mVolume, mFadeVolume, mFadeSeconds, mRepeat, i18n("Sound File"), this);
dlg.setReadOnly(mReadOnly);
bool accepted = (dlg.exec() == QDialog::Accepted);
if (mReadOnly)
return;
if (accepted)
{
float volume, fadeVolume;
int fadeTime;
file = dlg.getFile();
mRepeat = dlg.getSettings(volume, fadeVolume, fadeTime);
mVolume = volume;
mFadeVolume = fadeVolume;
mFadeSeconds = fadeTime;
}
if (!file.isEmpty())
{
mFile = file;
mDefaultDir = dlg.defaultDir();
}
mFilePicker->setToolTip(mFile);
if (mFile.isEmpty())
{
// No audio file is selected, so revert to previously selected option
#if 0
// Remove mRevertType, setLastType(), #include QTimer
// But wait a moment until setting the radio button, or it won't work.
mRevertType = true; // prevent sound dialogue popping up twice
QTimer::singleShot(0, this, SLOT(setLastType()));
#else
mTypeCombo->setCurrentIndex(mLastType);
#endif
}
}
/******************************************************************************
* Select the previously selected sound type.
*/
void SoundPicker::setLastType()
{
mTypeCombo->setCurrentIndex(mLastType);
mRevertType = false;
}
/******************************************************************************
* Display a dialogue to choose a sound file, initially highlighting any
* specified file. 'initialFile' must be a full path name or URL.
* 'defaultDir' is updated to the directory containing the chosen file.
* Reply = URL selected. If none is selected, URL.isEmpty() is true.
*/
QString SoundPicker::browseFile(QString& defaultDir, const QString& initialFile)
{
static QString kdeSoundDir; // directory containing KDE sound files
if (defaultDir.isEmpty())
{
if (kdeSoundDir.isNull())
kdeSoundDir = KGlobal::dirs()->findResourceDir("sound", "KDE_Notify.wav");
defaultDir = kdeSoundDir;
}
QString filter = Phonon::BackendCapabilities::knownMimeTypes().join(" ");
return KAlarm::browseFile(i18n("Choose Sound File"), defaultDir, initialFile, filter, KFile::ExistingOnly, 0);
}
|
Fix enabling/disabling sound file selector button
|
Fix enabling/disabling sound file selector button
svn path=/trunk/KDE/kdepim/; revision=596937
|
C++
|
lgpl-2.1
|
lefou/kdepim-noakonadi,lefou/kdepim-noakonadi,lefou/kdepim-noakonadi,lefou/kdepim-noakonadi,lefou/kdepim-noakonadi,lefou/kdepim-noakonadi
|
d3acf29868674a0d14792b0160532b46f97ba59f
|
kdb+.util/Cookbook.inl
|
kdb+.util/Cookbook.inl
|
//NOTE Include this only after <k.h> and <ctime>
#ifndef __COOKBOOK_INL__
#define __COOKBOOK_INL__
#include "win32.util/msvc.h"
#include <cassert>
#include <ctime>
// Utilities to deal with q datetime/timestamp data types in C.
//@ref http://code.kx.com/wiki/Cookbook/InterfacingWithC#Strings_and_datetimes
namespace q {
namespace Cookbook {
inline F zu(F u) {
return u / 86400. - 10957;
}
inline F zu(I u) { // kdb+ datetime from unix
return zu(static_cast<F>(u));
}
inline F uz(F f) { // unix from kdb+ datetime
return 86400 * (f + 10957);
}
inline J pu(I u) { // kdb+ timestamp from unix, use ktj(Kj,n) to create timestamp from n
return static_cast<J>(8.64e13 * (u / 86400. - 10957));
}
inline I up(J f) { // unix from kdb+ timestamp
return static_cast<I>((f / 8.64e13 + 10957) * 86400);
}
/*// Unsafe!
inline std::tm* lt(int kd) {
std::time_t t = uz(kd);
return std::localtime(&t);
}
*/
template <typename T>
tm_ext* lt_r(T kd, tm_ext* res) {
F tt = uz(kd);
std::time_t t = static_cast<std::time_t>(tt);
res->tm_millis = static_cast<int>(std::round((tt - t) * 1000));
# ifdef _MSC_VER
::errno_t err = ::localtime_s(res, &t);
assert(err == 0);
return res;
# else
return std::localtime_r(&t, res);
# endif
}
/*// Unsafe!
inline std::tm* gt(int kd) {
std::time_t t = uz(kd);
return std::gmtime(&t);
}
*/
template <typename T>
tm_ext* gt_r(T kd, tm_ext* res) {
F tt = uz(kd);
std::time_t t = static_cast<std::time_t>(tt);
tm_ext tm = time_t2tm(t, static_cast<int>(std::round((tt - t) * 1000)));
std::memcpy(res, &tm, sizeof(tm));
return res;
/*
res->tm_millis = static_cast<int>(std::round((tt - t) * 1000));
# ifdef _MSC_VER
::errno_t err = ::gmtime_s(res, &t);
assert(err == 0);
return res;
# else
return std::gmtime_r(&t, res);
# endif
*/
}
inline char* fdt(std::tm* ptm, char* d) {
std::strftime(d, (4 + 1 + 2 + 1 + 2) + 1, "%Y.%m.%d", ptm);
return d;
}
inline void tsms(unsigned ts, char*h, char*m, char*s, short*mmm) {
*h = ts / 3600000;
ts -= 3600000 * (*h);
*m = ts / 60000;
ts -= 60000 * (*m);
*s = ts / 1000;
ts -= 1000 * (*s);
*mmm = ts;
}
inline char* ftsms(unsigned ts, char* d){
char h, m, s;
short mmm;
tsms(ts, &h, &m, &s, &mmm);
int const count = std::snprintf(d, (2 + 1 + 2 + 1 + 2 + 1 + 3) + 1, "%02d:%02d:%02d.%03d", h, m, s, mmm);
assert(count == 2 + 1 + 2 + 1 + 2 + 1 + 3);
return d;
}
}//namespace q::Cookbook
}//namespace q
#endif//__COOKBOOK_INL__
|
//NOTE Include this only after <k.h> and <ctime>
#ifndef __COOKBOOK_INL__
#define __COOKBOOK_INL__
#include "win32.util/msvc.h"
#include <cassert>
#include <ctime>
// Utilities to deal with q datetime/timestamp data types in C.
//@ref http://code.kx.com/wiki/Cookbook/InterfacingWithC#Strings_and_datetimes
namespace q {
namespace Cookbook {
inline F zu(F u) {
return u / 86400. - 10957;
}
inline F zu(I u) { // kdb+ datetime from unix
return zu(static_cast<F>(u));
}
inline F uz(F f) { // unix from kdb+ datetime
return 86400 * (f + 10957);
}
inline J pu(F u) {
return static_cast<J>(8.64e13 * (u / 86400. - 10957));
}
inline J pu(I u) { // kdb+ timestamp from unix, use ktj(Kj,n) to create timestamp from n
return pu(static_cast<F>(u));
}
inline I up(J f) { // unix from kdb+ timestamp
return static_cast<I>((f / 8.64e13 + 10957) * 86400);
}
/*// Unsafe!
inline std::tm* lt(int kd) {
std::time_t t = uz(kd);
return std::localtime(&t);
}
*/
template <typename T>
tm_ext* lt_r(T kd, tm_ext* res) {
F tt = uz(kd);
std::time_t t = static_cast<std::time_t>(tt);
res->tm_millis = static_cast<int>(std::round((tt - t) * 1000));
# ifdef _MSC_VER
::errno_t err = ::localtime_s(res, &t);
assert(err == 0);
return res;
# else
return std::localtime_r(&t, res);
# endif
}
/*// Unsafe!
inline std::tm* gt(int kd) {
std::time_t t = uz(kd);
return std::gmtime(&t);
}
*/
template <typename T>
tm_ext* gt_r(T kd, tm_ext* res) {
F tt = uz(kd);
std::time_t t = static_cast<std::time_t>(tt);
tm_ext tm = time_t2tm(t, static_cast<int>(std::round((tt - t) * 1000)));
std::memcpy(res, &tm, sizeof(tm));
return res;
/*
res->tm_millis = static_cast<int>(std::round((tt - t) * 1000));
# ifdef _MSC_VER
::errno_t err = ::gmtime_s(res, &t);
assert(err == 0);
return res;
# else
return std::gmtime_r(&t, res);
# endif
*/
}
inline char* fdt(std::tm* ptm, char* d) {
std::strftime(d, (4 + 1 + 2 + 1 + 2) + 1, "%Y.%m.%d", ptm);
return d;
}
inline void tsms(unsigned ts, char*h, char*m, char*s, short*mmm) {
*h = ts / 3600000;
ts -= 3600000 * (*h);
*m = ts / 60000;
ts -= 60000 * (*m);
*s = ts / 1000;
ts -= 1000 * (*s);
*mmm = ts;
}
inline char* ftsms(unsigned ts, char* d){
char h, m, s;
short mmm;
tsms(ts, &h, &m, &s, &mmm);
int const count = std::snprintf(d, (2 + 1 + 2 + 1 + 2 + 1 + 3) + 1, "%02d:%02d:%02d.%03d", h, m, s, mmm);
assert(count == 2 + 1 + 2 + 1 + 2 + 1 + 3);
return d;
}
}//namespace q::Cookbook
}//namespace q
#endif//__COOKBOOK_INL__
|
add support for floating-point unix timestamp to q timestamp conversion
|
add support for floating-point unix timestamp to q timestamp conversion
|
C++
|
apache-2.0
|
FlyingOE/q_Wind,FlyingOE/q_Wind
|
bc36d727bfc7daaf97d421da881dc75a72198ca6
|
src/command.cpp
|
src/command.cpp
|
/*
* Copyright 2014 Matthew Harvey
*
* 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 "command.hpp"
#include "help_line.hpp"
#include "info.hpp"
#include "placeholder.hpp"
#include "stream_flag_guard.hpp"
#include "stream_utilities.hpp"
#include <cassert>
#include <iomanip>
#include <iostream>
#include <ostream>
#include <set>
#include <sstream>
#include <stdexcept>
#include <string>
#include <utility>
#include <vector>
using std::endl;
using std::left;
using std::make_pair;
using std::ostream;
using std::ostringstream;
using std::pair;
using std::runtime_error;
using std::set;
using std::setw;
using std::string;
using std::vector;
namespace swx
{
namespace
{
char flag_prefix()
{
return '-';
}
pair<char, string> double_dash_option()
{
return make_pair
( '-',
"Treat any dash-prefixed arguments after this flag as "
"ordinary arguments, rather than flags"
);
}
} // end anonymous namespace
Command::ParsedArguments::ParsedArguments
( vector<string> const& p_raw_args,
bool p_recognize_double_dash,
bool p_accept_ordinary_args
)
{
if (p_accept_ordinary_args && !p_recognize_double_dash)
{
m_ordinary_args = p_raw_args;
return;
}
ostringstream oss;
enable_exceptions(oss);
oss << flag_prefix() << double_dash_option().first;
string const double_dash = oss.str();
for (auto it = p_raw_args.begin(); it != p_raw_args.end(); ++it)
{
auto const& arg = *it;
if (p_recognize_double_dash && (arg == double_dash))
{
copy(it + 1, p_raw_args.end(), back_inserter(m_ordinary_args));
break;
}
else if (!arg.empty() && (arg[0] == flag_prefix()))
{
m_single_character_flags.insert(arg.begin() + 1, arg.end());
}
else
{
m_ordinary_args.push_back(*it);
}
}
}
vector<string>
Command::ParsedArguments::ordinary_args() const
{
return m_ordinary_args;
}
string
Command::ParsedArguments::single_character_flags() const
{
string const ret
( m_single_character_flags.begin(),
m_single_character_flags.end()
);
# ifndef NDEBUG
for (auto it = ret.begin(); it != ret.end(); ++it)
{
auto const next = it + 1;
if (next != ret.end())
{
assert (*it < *next);
}
}
# endif
return ret;
}
bool
Command::ParsedArguments::has_flag(char c) const
{
return m_single_character_flags.find(c) != m_single_character_flags.end();
}
Command::Command
( string const& p_command_word,
vector<string> const& p_aliases,
string const& p_usage_summary,
vector<HelpLine> const& p_help_lines,
bool p_accept_ordinary_args
):
m_accept_ordinary_args(p_accept_ordinary_args),
m_command_word(p_command_word),
m_usage_summary(p_usage_summary),
m_aliases(p_aliases),
m_help_lines(p_help_lines)
{
}
Command::~Command()
{
}
void
Command::add_boolean_option(char p_flag, string const& p_description)
{
// TODO MEDIUM PRIORITY Make this atomic.
if (has_boolean_option(p_flag))
{
ostringstream oss;
enable_exceptions(oss);
oss << "Flag already enabled for this Command: " << p_flag;
throw runtime_error(oss.str());
}
m_boolean_options[p_flag] = p_description;
if (m_accept_ordinary_args)
{
pair<char, string> const double_dash = double_dash_option();
m_boolean_options[double_dash.first] = double_dash.second;
}
return;
}
string
Command::category() const
{
return do_get_category();
}
bool
Command::has_boolean_option(char p_flag) const
{
return m_boolean_options.find(p_flag) != m_boolean_options.end();
}
int
Command::process
( Arguments const& p_args,
ostream& p_ordinary_ostream,
ostream& p_error_ostream
)
{
ParsedArguments const parsed_args
( p_args,
has_boolean_option(double_dash_option().first),
m_accept_ordinary_args
);
if (!m_accept_ordinary_args && !parsed_args.ordinary_args().empty())
{
p_error_ostream << "Too many arguments.\nAborted" << endl;
return 1;
}
auto const flags = parsed_args.single_character_flags();
assert (!m_boolean_options.empty() || flags.empty());
bool has_unrecognized_option = false;
for (auto c: flags)
{
if (!has_boolean_option(c))
{
p_error_ostream << "Unrecognized option: " << c << endl;
has_unrecognized_option = true;
}
}
if (has_unrecognized_option)
{
p_error_ostream << "Aborted" << endl;
return 1;
}
auto const error_messages = do_process(parsed_args, p_ordinary_ostream);
for (auto const& message: error_messages)
{
p_error_ostream << message << endl;
}
if (error_messages.empty())
{
assert (!has_unrecognized_option);
return 0;
}
assert (error_messages.size() > 0);
return 1;
}
string
Command::usage_summary() const
{
return m_usage_summary;
}
string
Command::usage_descriptor() const
{
// TODO LOW PRIORITY This should handle wrapping of the right-hand cell
// to a reasonable width if necessary.
typedef string::size_type ColWidth;
ColWidth command_word_length = m_command_word.length();
ColWidth left_col_width = command_word_length;
auto const app_name = Info::application_name();
for (auto const& line: m_help_lines)
{
ColWidth const left_cell_width =
line.args_descriptor().length() + command_word_length;
if (left_cell_width > left_col_width) left_col_width = left_cell_width;
}
left_col_width += app_name.length() + 1 + m_command_word.length() + 2;
ostringstream oss;
enable_exceptions(oss);
oss << "Usage:\n";
for (auto const& line: m_help_lines)
{
StreamFlagGuard guard(oss);
oss << "\n " << setw(left_col_width) << left
<< (app_name + ' ' + m_command_word + ' ' + line.args_descriptor())
<< " ";
guard.reset();
oss << line.usage_descriptor();
}
if (!m_aliases.empty())
{
oss << "\n\nAliased as: ";
auto it = m_aliases.begin();
oss << *it;
for (++it; it != m_aliases.end(); ++it) oss << ", " << *it;
}
left_col_width = 6;
if (!m_boolean_options.empty())
{
oss << "\n\nOptions:\n";
for (auto const& option: m_boolean_options)
{
StreamFlagGuard guard(oss);
string const flag{'-', option.first};
string const& description = option.second;
oss << "\n " << setw(left_col_width) << left
<< flag;
guard.reset();
oss << description;
}
}
if (does_support_placeholders())
{
auto const placeholder_lines = placeholder_help(left_col_width);
if (!placeholder_lines.empty())
{
oss << "\n\nPlaceholders:\n";
for (auto const& line: placeholder_lines)
{
oss << "\n " << line;
}
}
}
return oss.str();
}
string const&
Command::command_word() const
{
return m_command_word;
}
vector<string> const&
Command::aliases() const
{
return m_aliases;
}
string
Command::do_get_category() const
{
return "Miscellaneous";
}
bool
Command::does_support_placeholders() const
{
return false;
}
} // namespace swx
|
/*
* Copyright 2014 Matthew Harvey
*
* 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 "command.hpp"
#include "help_line.hpp"
#include "info.hpp"
#include "placeholder.hpp"
#include "stream_flag_guard.hpp"
#include "stream_utilities.hpp"
#include <cassert>
#include <iomanip>
#include <iostream>
#include <ostream>
#include <set>
#include <sstream>
#include <stdexcept>
#include <string>
#include <utility>
#include <vector>
using std::endl;
using std::left;
using std::make_pair;
using std::ostream;
using std::ostringstream;
using std::make_pair;
using std::pair;
using std::runtime_error;
using std::set;
using std::setw;
using std::string;
using std::vector;
namespace swx
{
namespace
{
char flag_prefix()
{
return '-';
}
pair<char, string> double_dash_option()
{
return make_pair
( '-',
"Treat any dash-prefixed arguments after this flag as "
"ordinary arguments, rather than flags"
);
}
} // end anonymous namespace
Command::ParsedArguments::ParsedArguments
( vector<string> const& p_raw_args,
bool p_recognize_double_dash,
bool p_accept_ordinary_args
)
{
if (p_accept_ordinary_args && !p_recognize_double_dash)
{
m_ordinary_args = p_raw_args;
return;
}
ostringstream oss;
enable_exceptions(oss);
oss << flag_prefix() << double_dash_option().first;
string const double_dash = oss.str();
for (auto it = p_raw_args.begin(); it != p_raw_args.end(); ++it)
{
auto const& arg = *it;
if (p_recognize_double_dash && (arg == double_dash))
{
copy(it + 1, p_raw_args.end(), back_inserter(m_ordinary_args));
break;
}
else if (!arg.empty() && (arg[0] == flag_prefix()))
{
m_single_character_flags.insert(arg.begin() + 1, arg.end());
}
else
{
m_ordinary_args.push_back(*it);
}
}
}
vector<string>
Command::ParsedArguments::ordinary_args() const
{
return m_ordinary_args;
}
string
Command::ParsedArguments::single_character_flags() const
{
string const ret
( m_single_character_flags.begin(),
m_single_character_flags.end()
);
# ifndef NDEBUG
for (auto it = ret.begin(); it != ret.end(); ++it)
{
auto const next = it + 1;
if (next != ret.end())
{
assert (*it < *next);
}
}
# endif
return ret;
}
bool
Command::ParsedArguments::has_flag(char c) const
{
return m_single_character_flags.find(c) != m_single_character_flags.end();
}
Command::Command
( string const& p_command_word,
vector<string> const& p_aliases,
string const& p_usage_summary,
vector<HelpLine> const& p_help_lines,
bool p_accept_ordinary_args
):
m_accept_ordinary_args(p_accept_ordinary_args),
m_command_word(p_command_word),
m_usage_summary(p_usage_summary),
m_aliases(p_aliases),
m_help_lines(p_help_lines)
{
}
Command::~Command()
{
}
void
Command::add_boolean_option(char p_flag, string const& p_description)
{
if (has_boolean_option(p_flag))
{
ostringstream oss;
enable_exceptions(oss);
oss << "Flag already enabled for this Command: " << p_flag;
throw runtime_error(oss.str());
}
m_boolean_options.insert(make_pair(p_flag, p_description));
if (m_accept_ordinary_args)
{
try
{
m_boolean_options.insert(double_dash_option());
}
catch (...)
{
m_boolean_options.erase(p_flag);
throw;
}
}
return;
}
string
Command::category() const
{
return do_get_category();
}
bool
Command::has_boolean_option(char p_flag) const
{
return m_boolean_options.find(p_flag) != m_boolean_options.end();
}
int
Command::process
( Arguments const& p_args,
ostream& p_ordinary_ostream,
ostream& p_error_ostream
)
{
ParsedArguments const parsed_args
( p_args,
has_boolean_option(double_dash_option().first),
m_accept_ordinary_args
);
if (!m_accept_ordinary_args && !parsed_args.ordinary_args().empty())
{
p_error_ostream << "Too many arguments.\nAborted" << endl;
return 1;
}
auto const flags = parsed_args.single_character_flags();
assert (!m_boolean_options.empty() || flags.empty());
bool has_unrecognized_option = false;
for (auto c: flags)
{
if (!has_boolean_option(c))
{
p_error_ostream << "Unrecognized option: " << c << endl;
has_unrecognized_option = true;
}
}
if (has_unrecognized_option)
{
p_error_ostream << "Aborted" << endl;
return 1;
}
auto const error_messages = do_process(parsed_args, p_ordinary_ostream);
for (auto const& message: error_messages)
{
p_error_ostream << message << endl;
}
if (error_messages.empty())
{
assert (!has_unrecognized_option);
return 0;
}
assert (error_messages.size() > 0);
return 1;
}
string
Command::usage_summary() const
{
return m_usage_summary;
}
string
Command::usage_descriptor() const
{
// TODO LOW PRIORITY This should handle wrapping of the right-hand cell
// to a reasonable width if necessary.
typedef string::size_type ColWidth;
ColWidth command_word_length = m_command_word.length();
ColWidth left_col_width = command_word_length;
auto const app_name = Info::application_name();
for (auto const& line: m_help_lines)
{
ColWidth const left_cell_width =
line.args_descriptor().length() + command_word_length;
if (left_cell_width > left_col_width) left_col_width = left_cell_width;
}
left_col_width += app_name.length() + 1 + m_command_word.length() + 2;
ostringstream oss;
enable_exceptions(oss);
oss << "Usage:\n";
for (auto const& line: m_help_lines)
{
StreamFlagGuard guard(oss);
oss << "\n " << setw(left_col_width) << left
<< (app_name + ' ' + m_command_word + ' ' + line.args_descriptor())
<< " ";
guard.reset();
oss << line.usage_descriptor();
}
if (!m_aliases.empty())
{
oss << "\n\nAliased as: ";
auto it = m_aliases.begin();
oss << *it;
for (++it; it != m_aliases.end(); ++it) oss << ", " << *it;
}
left_col_width = 6;
if (!m_boolean_options.empty())
{
oss << "\n\nOptions:\n";
for (auto const& option: m_boolean_options)
{
StreamFlagGuard guard(oss);
string const flag{'-', option.first};
string const& description = option.second;
oss << "\n " << setw(left_col_width) << left
<< flag;
guard.reset();
oss << description;
}
}
if (does_support_placeholders())
{
auto const placeholder_lines = placeholder_help(left_col_width);
if (!placeholder_lines.empty())
{
oss << "\n\nPlaceholders:\n";
for (auto const& line: placeholder_lines)
{
oss << "\n " << line;
}
}
}
return oss.str();
}
string const&
Command::command_word() const
{
return m_command_word;
}
vector<string> const&
Command::aliases() const
{
return m_aliases;
}
string
Command::do_get_category() const
{
return "Miscellaneous";
}
bool
Command::does_support_placeholders() const
{
return false;
}
} // namespace swx
|
Make Command::add_boolean_option() atomic.
|
Make Command::add_boolean_option() atomic.
|
C++
|
apache-2.0
|
skybaboon/swx,matt-harvey/swx
|
6f2741c6325e0112f52b537444e1aaac8e746f85
|
lib/sanitizer_common/sanitizer_printf.cc
|
lib/sanitizer_common/sanitizer_printf.cc
|
//===-- sanitizer_printf.cc -----------------------------------------------===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This file is shared between AddressSanitizer and ThreadSanitizer.
//
// Internal printf function, used inside run-time libraries.
// We can't use libc printf because we intercept some of the functions used
// inside it.
//===----------------------------------------------------------------------===//
#include "sanitizer_common.h"
#include "sanitizer_libc.h"
#include <stdio.h>
#include <stdarg.h>
#if SANITIZER_WINDOWS && !defined(va_copy)
# define va_copy(dst, src) ((dst) = (src))
#endif
namespace __sanitizer {
StaticSpinMutex CommonSanitizerReportMutex;
static int AppendChar(char **buff, const char *buff_end, char c) {
if (*buff < buff_end) {
**buff = c;
(*buff)++;
}
return 1;
}
// Appends number in a given base to buffer. If its length is less than
// |minimal_num_length|, it is padded with leading zeroes or spaces, depending
// on the value of |pad_with_zero|.
static int AppendNumber(char **buff, const char *buff_end, u64 absolute_value,
u8 base, u8 minimal_num_length, bool pad_with_zero,
bool negative) {
uptr const kMaxLen = 30;
RAW_CHECK(base == 10 || base == 16);
RAW_CHECK(base == 10 || !negative);
RAW_CHECK(absolute_value || !negative);
RAW_CHECK(minimal_num_length < kMaxLen);
int result = 0;
if (negative && minimal_num_length)
--minimal_num_length;
if (negative && pad_with_zero)
result += AppendChar(buff, buff_end, '-');
uptr num_buffer[kMaxLen];
int pos = 0;
do {
RAW_CHECK_MSG((uptr)pos < kMaxLen, "AppendNumber buffer overflow");
num_buffer[pos++] = absolute_value % base;
absolute_value /= base;
} while (absolute_value > 0);
if (pos < minimal_num_length) {
// Make sure compiler doesn't insert call to memset here.
internal_memset(&num_buffer[pos], 0,
sizeof(num_buffer[0]) * (minimal_num_length - pos));
pos = minimal_num_length;
}
RAW_CHECK(pos > 0);
pos--;
for (; pos >= 0 && num_buffer[pos] == 0; pos--) {
char c = (pad_with_zero || pos == 0) ? '0' : ' ';
result += AppendChar(buff, buff_end, c);
}
if (negative && !pad_with_zero) result += AppendChar(buff, buff_end, '-');
for (; pos >= 0; pos--) {
char digit = static_cast<char>(num_buffer[pos]);
result += AppendChar(buff, buff_end, (digit < 10) ? '0' + digit
: 'a' + digit - 10);
}
return result;
}
static int AppendUnsigned(char **buff, const char *buff_end, u64 num, u8 base,
u8 minimal_num_length, bool pad_with_zero) {
return AppendNumber(buff, buff_end, num, base, minimal_num_length,
pad_with_zero, false /* negative */);
}
static int AppendSignedDecimal(char **buff, const char *buff_end, s64 num,
u8 minimal_num_length, bool pad_with_zero) {
bool negative = (num < 0);
return AppendNumber(buff, buff_end, (u64)(negative ? -num : num), 10,
minimal_num_length, pad_with_zero, negative);
}
static int AppendString(char **buff, const char *buff_end, const char *s) {
if (s == 0)
s = "<null>";
int result = 0;
for (; *s; s++) {
result += AppendChar(buff, buff_end, *s);
}
return result;
}
static int AppendPointer(char **buff, const char *buff_end, u64 ptr_value) {
int result = 0;
result += AppendString(buff, buff_end, "0x");
result += AppendUnsigned(buff, buff_end, ptr_value, 16,
(SANITIZER_WORDSIZE == 64) ? 12 : 8, true);
return result;
}
int VSNPrintf(char *buff, int buff_length,
const char *format, va_list args) {
static const char *kPrintfFormatsHelp =
"Supported Printf formats: %([0-9]*)?(z|ll)?{d,u,x}; %p; %s; %c\n";
RAW_CHECK(format);
RAW_CHECK(buff_length > 0);
const char *buff_end = &buff[buff_length - 1];
const char *cur = format;
int result = 0;
for (; *cur; cur++) {
if (*cur != '%') {
result += AppendChar(&buff, buff_end, *cur);
continue;
}
cur++;
bool have_width = (*cur >= '0' && *cur <= '9');
bool pad_with_zero = (*cur == '0');
int width = 0;
if (have_width) {
while (*cur >= '0' && *cur <= '9') {
width = width * 10 + *cur++ - '0';
}
}
bool have_z = (*cur == 'z');
cur += have_z;
bool have_ll = !have_z && (cur[0] == 'l' && cur[1] == 'l');
cur += have_ll * 2;
s64 dval;
u64 uval;
bool have_flags = have_width | have_z | have_ll;
switch (*cur) {
case 'd': {
dval = have_ll ? va_arg(args, s64)
: have_z ? va_arg(args, sptr)
: va_arg(args, int);
result += AppendSignedDecimal(&buff, buff_end, dval, width,
pad_with_zero);
break;
}
case 'u':
case 'x': {
uval = have_ll ? va_arg(args, u64)
: have_z ? va_arg(args, uptr)
: va_arg(args, unsigned);
result += AppendUnsigned(&buff, buff_end, uval,
(*cur == 'u') ? 10 : 16, width, pad_with_zero);
break;
}
case 'p': {
RAW_CHECK_MSG(!have_flags, kPrintfFormatsHelp);
result += AppendPointer(&buff, buff_end, va_arg(args, uptr));
break;
}
case 's': {
RAW_CHECK_MSG(!have_flags, kPrintfFormatsHelp);
result += AppendString(&buff, buff_end, va_arg(args, char*));
break;
}
case 'c': {
RAW_CHECK_MSG(!have_flags, kPrintfFormatsHelp);
result += AppendChar(&buff, buff_end, va_arg(args, int));
break;
}
case '%' : {
RAW_CHECK_MSG(!have_flags, kPrintfFormatsHelp);
result += AppendChar(&buff, buff_end, '%');
break;
}
default: {
RAW_CHECK_MSG(false, kPrintfFormatsHelp);
}
}
}
RAW_CHECK(buff <= buff_end);
AppendChar(&buff, buff_end + 1, '\0');
return result;
}
static void (*PrintfAndReportCallback)(const char *);
void SetPrintfAndReportCallback(void (*callback)(const char *)) {
PrintfAndReportCallback = callback;
}
#if SANITIZER_SUPPORTS_WEAK_HOOKS
// Can be overriden in frontend.
SANITIZER_INTERFACE_ATTRIBUTE SANITIZER_WEAK_ATTRIBUTE
void OnPrint(const char *str);
#endif
static void CallPrintfAndReportCallback(const char *str) {
#if SANITIZER_SUPPORTS_WEAK_HOOKS
if (&OnPrint != NULL)
OnPrint(str);
#endif
if (PrintfAndReportCallback)
PrintfAndReportCallback(str);
}
static void SharedPrintfCode(bool append_pid, const char *format,
va_list args) {
va_list args2;
va_copy(args2, args);
const int kLen = 16 * 1024;
// |local_buffer| is small enough not to overflow the stack and/or violate
// the stack limit enforced by TSan (-Wframe-larger-than=512). On the other
// hand, the bigger the buffer is, the more the chance the error report will
// fit into it.
char local_buffer[400];
int needed_length;
char *buffer = local_buffer;
int buffer_size = ARRAY_SIZE(local_buffer);
// First try to print a message using a local buffer, and then fall back to
// mmaped buffer.
for (int use_mmap = 0; use_mmap < 2; use_mmap++) {
if (use_mmap) {
va_end(args);
va_copy(args, args2);
buffer = (char*)MmapOrDie(kLen, "Report");
buffer_size = kLen;
}
needed_length = 0;
if (append_pid) {
int pid = internal_getpid();
needed_length += internal_snprintf(buffer, buffer_size, "==%d==", pid);
if (needed_length >= buffer_size) {
// The pid doesn't fit into the current buffer.
if (!use_mmap)
continue;
RAW_CHECK_MSG(needed_length < kLen, "Buffer in Report is too short!\n");
}
}
needed_length += VSNPrintf(buffer + needed_length,
buffer_size - needed_length, format, args);
if (needed_length >= buffer_size) {
// The message doesn't fit into the current buffer.
if (!use_mmap)
continue;
RAW_CHECK_MSG(needed_length < kLen, "Buffer in Report is too short!\n");
}
// If the message fit into the buffer, print it and exit.
break;
}
RawWrite(buffer);
CallPrintfAndReportCallback(buffer);
// If we had mapped any memory, clean up.
if (buffer != local_buffer)
UnmapOrDie((void *)buffer, buffer_size);
va_end(args2);
}
void Printf(const char *format, ...) {
va_list args;
va_start(args, format);
SharedPrintfCode(false, format, args);
va_end(args);
}
// Like Printf, but prints the current PID before the output string.
void Report(const char *format, ...) {
va_list args;
va_start(args, format);
SharedPrintfCode(true, format, args);
va_end(args);
}
// Writes at most "length" symbols to "buffer" (including trailing '\0').
// Returns the number of symbols that should have been written to buffer
// (not including trailing '\0'). Thus, the string is truncated
// iff return value is not less than "length".
int internal_snprintf(char *buffer, uptr length, const char *format, ...) {
va_list args;
va_start(args, format);
int needed_length = VSNPrintf(buffer, length, format, args);
va_end(args);
return needed_length;
}
} // namespace __sanitizer
|
//===-- sanitizer_printf.cc -----------------------------------------------===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This file is shared between AddressSanitizer and ThreadSanitizer.
//
// Internal printf function, used inside run-time libraries.
// We can't use libc printf because we intercept some of the functions used
// inside it.
//===----------------------------------------------------------------------===//
#include "sanitizer_common.h"
#include "sanitizer_libc.h"
#include <stdio.h>
#include <stdarg.h>
#if SANITIZER_WINDOWS && !defined(va_copy)
# define va_copy(dst, src) ((dst) = (src))
#endif
namespace __sanitizer {
StaticSpinMutex CommonSanitizerReportMutex;
static int AppendChar(char **buff, const char *buff_end, char c) {
if (*buff < buff_end) {
**buff = c;
(*buff)++;
}
return 1;
}
// Appends number in a given base to buffer. If its length is less than
// |minimal_num_length|, it is padded with leading zeroes or spaces, depending
// on the value of |pad_with_zero|.
static int AppendNumber(char **buff, const char *buff_end, u64 absolute_value,
u8 base, u8 minimal_num_length, bool pad_with_zero,
bool negative) {
uptr const kMaxLen = 30;
RAW_CHECK(base == 10 || base == 16);
RAW_CHECK(base == 10 || !negative);
RAW_CHECK(absolute_value || !negative);
RAW_CHECK(minimal_num_length < kMaxLen);
int result = 0;
if (negative && minimal_num_length)
--minimal_num_length;
if (negative && pad_with_zero)
result += AppendChar(buff, buff_end, '-');
uptr num_buffer[kMaxLen];
int pos = 0;
do {
RAW_CHECK_MSG((uptr)pos < kMaxLen, "AppendNumber buffer overflow");
num_buffer[pos++] = absolute_value % base;
absolute_value /= base;
} while (absolute_value > 0);
if (pos < minimal_num_length) {
// Make sure compiler doesn't insert call to memset here.
internal_memset(&num_buffer[pos], 0,
sizeof(num_buffer[0]) * (minimal_num_length - pos));
pos = minimal_num_length;
}
RAW_CHECK(pos > 0);
pos--;
for (; pos >= 0 && num_buffer[pos] == 0; pos--) {
char c = (pad_with_zero || pos == 0) ? '0' : ' ';
result += AppendChar(buff, buff_end, c);
}
if (negative && !pad_with_zero) result += AppendChar(buff, buff_end, '-');
for (; pos >= 0; pos--) {
char digit = static_cast<char>(num_buffer[pos]);
result += AppendChar(buff, buff_end, (digit < 10) ? '0' + digit
: 'a' + digit - 10);
}
return result;
}
static int AppendUnsigned(char **buff, const char *buff_end, u64 num, u8 base,
u8 minimal_num_length, bool pad_with_zero) {
return AppendNumber(buff, buff_end, num, base, minimal_num_length,
pad_with_zero, false /* negative */);
}
static int AppendSignedDecimal(char **buff, const char *buff_end, s64 num,
u8 minimal_num_length, bool pad_with_zero) {
bool negative = (num < 0);
return AppendNumber(buff, buff_end, (u64)(negative ? -num : num), 10,
minimal_num_length, pad_with_zero, negative);
}
static int AppendString(char **buff, const char *buff_end, const char *s) {
if (s == 0)
s = "<null>";
int result = 0;
for (; *s; s++) {
result += AppendChar(buff, buff_end, *s);
}
return result;
}
static int AppendPointer(char **buff, const char *buff_end, u64 ptr_value) {
int result = 0;
result += AppendString(buff, buff_end, "0x");
result += AppendUnsigned(buff, buff_end, ptr_value, 16,
(SANITIZER_WORDSIZE == 64) ? 12 : 8, true);
return result;
}
int VSNPrintf(char *buff, int buff_length,
const char *format, va_list args) {
static const char *kPrintfFormatsHelp =
"Supported Printf formats: %([0-9]*)?(z|ll)?{d,u,x}; %p; %s; %c\n";
RAW_CHECK(format);
RAW_CHECK(buff_length > 0);
const char *buff_end = &buff[buff_length - 1];
const char *cur = format;
int result = 0;
for (; *cur; cur++) {
if (*cur != '%') {
result += AppendChar(&buff, buff_end, *cur);
continue;
}
cur++;
bool have_width = (*cur >= '0' && *cur <= '9');
bool pad_with_zero = (*cur == '0');
int width = 0;
if (have_width) {
while (*cur >= '0' && *cur <= '9') {
width = width * 10 + *cur++ - '0';
}
}
bool have_z = (*cur == 'z');
cur += have_z;
bool have_ll = !have_z && (cur[0] == 'l' && cur[1] == 'l');
cur += have_ll * 2;
s64 dval;
u64 uval;
bool have_flags = have_width | have_z | have_ll;
switch (*cur) {
case 'd': {
dval = have_ll ? va_arg(args, s64)
: have_z ? va_arg(args, sptr)
: va_arg(args, int);
result += AppendSignedDecimal(&buff, buff_end, dval, width,
pad_with_zero);
break;
}
case 'u':
case 'x': {
uval = have_ll ? va_arg(args, u64)
: have_z ? va_arg(args, uptr)
: va_arg(args, unsigned);
result += AppendUnsigned(&buff, buff_end, uval,
(*cur == 'u') ? 10 : 16, width, pad_with_zero);
break;
}
case 'p': {
RAW_CHECK_MSG(!have_flags, kPrintfFormatsHelp);
result += AppendPointer(&buff, buff_end, va_arg(args, uptr));
break;
}
case 's': {
RAW_CHECK_MSG(!have_flags, kPrintfFormatsHelp);
result += AppendString(&buff, buff_end, va_arg(args, char*));
break;
}
case 'c': {
RAW_CHECK_MSG(!have_flags, kPrintfFormatsHelp);
result += AppendChar(&buff, buff_end, va_arg(args, int));
break;
}
case '%' : {
RAW_CHECK_MSG(!have_flags, kPrintfFormatsHelp);
result += AppendChar(&buff, buff_end, '%');
break;
}
default: {
RAW_CHECK_MSG(false, kPrintfFormatsHelp);
}
}
}
RAW_CHECK(buff <= buff_end);
AppendChar(&buff, buff_end + 1, '\0');
return result;
}
static void (*PrintfAndReportCallback)(const char *);
void SetPrintfAndReportCallback(void (*callback)(const char *)) {
PrintfAndReportCallback = callback;
}
// Can be overriden in frontend.
#if SANITIZER_SUPPORTS_WEAK_HOOKS
SANITIZER_INTERFACE_ATTRIBUTE SANITIZER_WEAK_ATTRIBUTE
void OnPrint(const char *str) {
(void)str;
}
#elif defined(SANITIZER_GO) && defined(TSAN_EXTERNAL_HOOKS)
void OnPrint(const char *str);
#else
void OnPrint(const char *str) {
(void)str;
}
#endif
static void CallPrintfAndReportCallback(const char *str) {
OnPrint(str);
if (PrintfAndReportCallback)
PrintfAndReportCallback(str);
}
static void SharedPrintfCode(bool append_pid, const char *format,
va_list args) {
va_list args2;
va_copy(args2, args);
const int kLen = 16 * 1024;
// |local_buffer| is small enough not to overflow the stack and/or violate
// the stack limit enforced by TSan (-Wframe-larger-than=512). On the other
// hand, the bigger the buffer is, the more the chance the error report will
// fit into it.
char local_buffer[400];
int needed_length;
char *buffer = local_buffer;
int buffer_size = ARRAY_SIZE(local_buffer);
// First try to print a message using a local buffer, and then fall back to
// mmaped buffer.
for (int use_mmap = 0; use_mmap < 2; use_mmap++) {
if (use_mmap) {
va_end(args);
va_copy(args, args2);
buffer = (char*)MmapOrDie(kLen, "Report");
buffer_size = kLen;
}
needed_length = 0;
if (append_pid) {
int pid = internal_getpid();
needed_length += internal_snprintf(buffer, buffer_size, "==%d==", pid);
if (needed_length >= buffer_size) {
// The pid doesn't fit into the current buffer.
if (!use_mmap)
continue;
RAW_CHECK_MSG(needed_length < kLen, "Buffer in Report is too short!\n");
}
}
needed_length += VSNPrintf(buffer + needed_length,
buffer_size - needed_length, format, args);
if (needed_length >= buffer_size) {
// The message doesn't fit into the current buffer.
if (!use_mmap)
continue;
RAW_CHECK_MSG(needed_length < kLen, "Buffer in Report is too short!\n");
}
// If the message fit into the buffer, print it and exit.
break;
}
RawWrite(buffer);
CallPrintfAndReportCallback(buffer);
// If we had mapped any memory, clean up.
if (buffer != local_buffer)
UnmapOrDie((void *)buffer, buffer_size);
va_end(args2);
}
void Printf(const char *format, ...) {
va_list args;
va_start(args, format);
SharedPrintfCode(false, format, args);
va_end(args);
}
// Like Printf, but prints the current PID before the output string.
void Report(const char *format, ...) {
va_list args;
va_start(args, format);
SharedPrintfCode(true, format, args);
va_end(args);
}
// Writes at most "length" symbols to "buffer" (including trailing '\0').
// Returns the number of symbols that should have been written to buffer
// (not including trailing '\0'). Thus, the string is truncated
// iff return value is not less than "length".
int internal_snprintf(char *buffer, uptr length, const char *format, ...) {
va_list args;
va_start(args, format);
int needed_length = VSNPrintf(buffer, length, format, args);
va_end(args);
return needed_length;
}
} // namespace __sanitizer
|
allow to override OnPrint() callback in Go runtime
|
tsan: allow to override OnPrint() callback in Go runtime
git-svn-id: c199f293c43da69278bea8e88f92242bf3aa95f7@192576 91177308-0d34-0410-b5e6-96231b3b80d8
|
C++
|
apache-2.0
|
llvm-mirror/compiler-rt,llvm-mirror/compiler-rt,llvm-mirror/compiler-rt,llvm-mirror/compiler-rt,llvm-mirror/compiler-rt
|
2f55b9b84981c6f392efa24309a242ce2045d694
|
flappy.cc
|
flappy.cc
|
/* flappy.cc --- ncurses flappy bird clone
* This is free and unencumbered software released into the public domain.
*/
#include <algorithm>
#include <thread>
#include <deque>
#include <ctime>
#include <cmath>
#include <cstring>
#include <ncurses.h>
#include "sqlite3.h"
#include "highscores.hh"
struct Display {
Display(int width = 40, int height = 20) : height{height}, width{width} {
initscr();
raw();
timeout(0);
noecho();
curs_set(0);
keypad(stdscr, TRUE);
erase();
}
~Display() { endwin(); }
void erase() {
::erase();
for (int y = 0; y < height; y++) {
mvaddch(y, 0, '|');
mvaddch(y, width - 1, '|');
}
for (int x = 0; x < width; x++) {
mvaddch(0, x, '-');
mvaddch(height - 1, x, '-');
}
mvaddch(0, 0, '/');
mvaddch(height - 1, 0, '\\');
mvaddch(0, width - 1, '\\');
mvaddch(height - 1, width - 1, '/');
}
void refresh() { ::refresh(); }
const int height, width;
int block_getch() {
refresh();
timeout(-1);
int c = getch();
timeout(0);
return c;
}
void read_name(int y, int x, char *target, size_t n) {
int p = 0;
timeout(-1);
curs_set(1);
bool reading = true;
while (reading) {
move(y, x + p);
refresh();
int c = getch();
switch (c) {
case KEY_ENTER:
case '\n':
case '\r':
reading = false;
break;
case KEY_LEFT:
case KEY_BACKSPACE:
if (p > 0) mvaddch(y, x + --p, ' ');
break;
default:
if (p < n - 1) {
target[p] = c;
mvaddch(y, x + p++, c);
}
}
}
target[p + 1] = '\0';
timeout(0);
curs_set(0);
}
};
struct World {
World(Display *display) : display{display} {
for (int x = 1; x < display->width - 1; x++) {
walls.push_back(0);
}
}
std::deque<int> walls;
Display *display;
int steps = 0;
constexpr static int kRate = 2, kVGap = 2, kHGap = 10;
int rand_wall() {
int h = display->height;
return (rand() % h / 2) + h / 4;
}
void step() {
steps++;
if (steps % kRate == 0) {
walls.pop_front();
switch (steps % (kRate * kHGap)) {
case 0:
walls.push_back(rand_wall());
break;
case kRate * 1:
case kRate * 2:
walls.push_back(walls.back());
break;
default:
walls.push_back(0);
}
}
}
void draw() {
for (int i = 0; i < walls.size(); i++) {
int wall = walls[i];
if (wall != 0) {
for (int y = 1; y < display->height - 1; y++) {
if (y == wall - kVGap - 1|| y == wall + kVGap + 1) {
mvaddch(y, i + 1, '=');
} else if (y < wall - kVGap || y > wall + kVGap) {
mvaddch(y, i + 1, '*');
}
}
}
}
mvprintw(display->height, 0, "Score: %d", score());
}
int score() { return std::max(0, (steps - 2) / (kRate * kHGap) - 2); }
};
struct Bird {
Bird(Display *display) : y{display->height / 2.0}, display{display} {}
static constexpr double kImpulse = -0.8, kGravity = 0.1;
double y, dy = kImpulse;
Display *display;
void gravity() {
dy += kGravity;
y += dy;
}
void poke() { dy = kImpulse; }
void draw() { draw('@'); }
void draw(int c) {
int h = std::round(y);
h = std::max(1, std::min(h, display->height - 2));
mvaddch(h, display->width / 2, c);
}
bool is_alive(World &world) {
if (y <= 0 || y >= display->height) {
return false;
}
int wall = world.walls[display->width / 2 - 1];
if (wall != 0) {
return y > wall - World::kVGap && y < wall + World::kVGap;
}
return true;
}
};
struct Game {
Game(Display *display) : display{display}, bird{display}, world{display} {}
Display *display;
Bird bird;
World world;
int run() {
display->erase();
const char *intro = "[Press SPACE to hop upwards]";
mvprintw(display->height / 2 - 2,
display->width / 2 - std::strlen(intro) / 2, intro);
bird.draw();
display->block_getch();
while (bird.is_alive(world)) {
int c = getch();
if (c == 'q') {
return -1;
} else if (c != ERR) {
while (getch() != ERR)
; // clear repeat buffer
bird.poke();
}
display->erase();
world.step();
world.draw();
bird.gravity();
bird.draw();
display->refresh();
std::this_thread::sleep_for(std::chrono::milliseconds{67});
}
bird.draw('X');
display->refresh();
return world.score();
}
};
void print_scores(Display &display, HighScores &scores) {
mvprintw(0, display.width + 4, "== High Scores ==");
int i = 1;
for (auto &line : scores.top_scores()) {
mvprintw(i, display.width + 1, "%s", line.name.c_str());
clrtoeol();
mvprintw(i, display.width + 24, "%d", line.score);
i++;
}
}
int main(int argc, const char **argv) {
srand(std::time(NULL));
const char *filename = "/tmp/flappy-scores.db";
if (argc > 1) {
filename = argv[1];
}
Display display;
HighScores scores{filename, display.height};
while (true) {
Game game{&display};
int score = game.run();
if (score < 0) {
return 0; // game quit early
}
/* Game over */
mvprintw(display.height + 1, 0, "Game over!");
print_scores(display, scores);
/* Enter new high score */
if (scores.is_best(score)) {
mvprintw(display.height + 2, 0, "You have a high score!");
mvprintw(display.height + 3, 0, "Enter name: ");
char name[23] = {0};
display.read_name(display.height + 3, 12, name, sizeof(name));
if (std::strlen(name) == 0) {
std::strcpy(name, "(anonymous)");
}
scores.insert_score(name, score);
move(display.height + 3, 0);
clrtoeol();
print_scores(display, scores);
}
/* Handle quit/restart */
mvprintw(display.height + 2, 0, "Press 'q' to quit, 'r' to retry.");
int c;
while ((c = display.block_getch()) != 'r') {
if (c == 'q' || c == ERR) {
return 0;
}
}
}
return 0;
}
|
/* flappy.cc --- ncurses flappy bird clone
* This is free and unencumbered software released into the public domain.
*/
#include <algorithm>
#include <thread>
#include <deque>
#include <ctime>
#include <cmath>
#include <cstring>
#include <ncurses.h>
#include "sqlite3.h"
#include "highscores.hh"
struct Display {
Display(int width = 40, int height = 20) : height{height}, width{width} {
initscr();
raw();
timeout(0);
noecho();
curs_set(0);
keypad(stdscr, TRUE);
erase();
}
~Display() { endwin(); }
void erase() {
::erase();
for (int y = 0; y < height; y++) {
mvaddch(y, 0, '|');
mvaddch(y, width - 1, '|');
}
for (int x = 0; x < width; x++) {
mvaddch(0, x, '-');
mvaddch(height - 1, x, '-');
}
mvaddch(0, 0, '/');
mvaddch(height - 1, 0, '\\');
mvaddch(0, width - 1, '\\');
mvaddch(height - 1, width - 1, '/');
}
void refresh() { ::refresh(); }
const int height, width;
int block_getch() {
refresh();
timeout(-1);
int c = getch();
timeout(0);
return c;
}
void read_name(int y, int x, char *target, size_t n) {
int p = 0;
timeout(-1);
curs_set(1);
bool reading = true;
while (reading) {
move(y, x + p);
refresh();
int c = getch();
switch (c) {
case KEY_ENTER:
case '\n':
case '\r':
case ERR:
reading = false;
break;
case KEY_LEFT:
case KEY_BACKSPACE:
if (p > 0) mvaddch(y, x + --p, ' ');
break;
default:
if (p < n - 1) {
target[p] = c;
mvaddch(y, x + p++, c);
}
}
}
target[p + 1] = '\0';
timeout(0);
curs_set(0);
}
};
struct World {
World(Display *display) : display{display} {
for (int x = 1; x < display->width - 1; x++) {
walls.push_back(0);
}
}
std::deque<int> walls;
Display *display;
int steps = 0;
constexpr static int kRate = 2, kVGap = 2, kHGap = 10;
int rand_wall() {
int h = display->height;
return (rand() % h / 2) + h / 4;
}
void step() {
steps++;
if (steps % kRate == 0) {
walls.pop_front();
switch (steps % (kRate * kHGap)) {
case 0:
walls.push_back(rand_wall());
break;
case kRate * 1:
case kRate * 2:
walls.push_back(walls.back());
break;
default:
walls.push_back(0);
}
}
}
void draw() {
for (int i = 0; i < walls.size(); i++) {
int wall = walls[i];
if (wall != 0) {
for (int y = 1; y < display->height - 1; y++) {
if (y == wall - kVGap - 1|| y == wall + kVGap + 1) {
mvaddch(y, i + 1, '=');
} else if (y < wall - kVGap || y > wall + kVGap) {
mvaddch(y, i + 1, '*');
}
}
}
}
mvprintw(display->height, 0, "Score: %d", score());
}
int score() { return std::max(0, (steps - 2) / (kRate * kHGap) - 2); }
};
struct Bird {
Bird(Display *display) : y{display->height / 2.0}, display{display} {}
static constexpr double kImpulse = -0.8, kGravity = 0.1;
double y, dy = kImpulse;
Display *display;
void gravity() {
dy += kGravity;
y += dy;
}
void poke() { dy = kImpulse; }
void draw() { draw('@'); }
void draw(int c) {
int h = std::round(y);
h = std::max(1, std::min(h, display->height - 2));
mvaddch(h, display->width / 2, c);
}
bool is_alive(World &world) {
if (y <= 0 || y >= display->height) {
return false;
}
int wall = world.walls[display->width / 2 - 1];
if (wall != 0) {
return y > wall - World::kVGap && y < wall + World::kVGap;
}
return true;
}
};
struct Game {
Game(Display *display) : display{display}, bird{display}, world{display} {}
Display *display;
Bird bird;
World world;
int run() {
display->erase();
const char *intro = "[Press SPACE to hop upwards]";
mvprintw(display->height / 2 - 2,
display->width / 2 - std::strlen(intro) / 2, intro);
bird.draw();
display->block_getch();
while (bird.is_alive(world)) {
int c = getch();
if (c == 'q') {
return -1;
} else if (c != ERR) {
while (getch() != ERR)
; // clear repeat buffer
bird.poke();
}
display->erase();
world.step();
world.draw();
bird.gravity();
bird.draw();
display->refresh();
std::this_thread::sleep_for(std::chrono::milliseconds{67});
}
bird.draw('X');
display->refresh();
return world.score();
}
};
void print_scores(Display &display, HighScores &scores) {
mvprintw(0, display.width + 4, "== High Scores ==");
int i = 1;
for (auto &line : scores.top_scores()) {
mvprintw(i, display.width + 1, "%s", line.name.c_str());
clrtoeol();
mvprintw(i, display.width + 24, "%d", line.score);
i++;
}
}
int main(int argc, const char **argv) {
srand(std::time(NULL));
const char *filename = "/tmp/flappy-scores.db";
if (argc > 1) {
filename = argv[1];
}
Display display;
HighScores scores{filename, display.height};
while (true) {
Game game{&display};
int score = game.run();
if (score < 0) {
return 0; // game quit early
}
/* Game over */
mvprintw(display.height + 1, 0, "Game over!");
print_scores(display, scores);
/* Enter new high score */
if (scores.is_best(score)) {
mvprintw(display.height + 2, 0, "You have a high score!");
mvprintw(display.height + 3, 0, "Enter name: ");
char name[23] = {0};
display.read_name(display.height + 3, 12, name, sizeof(name));
if (std::strlen(name) == 0) {
std::strcpy(name, "(anonymous)");
}
scores.insert_score(name, score);
move(display.height + 3, 0);
clrtoeol();
print_scores(display, scores);
}
/* Handle quit/restart */
mvprintw(display.height + 2, 0, "Press 'q' to quit, 'r' to retry.");
int c;
while ((c = display.block_getch()) != 'r') {
if (c == 'q' || c == ERR) {
return 0;
}
}
}
return 0;
}
|
Stop reading on ERR.
|
Stop reading on ERR.
|
C++
|
unlicense
|
skeeto/flappy,skeeto/flappy
|
c5122b37f3bd8b5be3c0f379bc2809aac4962927
|
kernel/src/console.cpp
|
kernel/src/console.cpp
|
//=======================================================================
// Copyright Baptiste Wicht 2013-2016.
// Distributed under the terms of the MIT License.
// (See accompanying file LICENSE or copy at
// http://www.opensource.org/licenses/MIT)
//=======================================================================
#include <stdarg.h>
#include <types.hpp>
#include <string.hpp>
#include "assert.hpp"
#include "console.hpp"
#include "vesa.hpp"
#include "text_console.hpp"
#include "vesa_console.hpp"
namespace {
text_console t_console;
vesa_console v_console;
bool text = true;
void clear(){
if(text){
t_console.clear();
} else {
v_console.clear();
}
}
void scroll_up(){
if(text){
t_console.scroll_up();
} else {
v_console.scroll_up();
}
}
void print_char(size_t line, size_t column, char c){
if(text){
t_console.print_char(line, column, c);
} else {
v_console.print_char(line, column, c);
}
}
volatile size_t current_line = 0;
volatile size_t current_column = 0;
template<int B, typename D>
void print_unsigned(D number){
if(number == 0){
k_print('0');
return;
}
char buffer[B];
int i = 0;
while(number != 0){
buffer[i++] = '0' + number % 10;
number /= 10;
}
--i;
for(; i >= 0; --i){
k_print(buffer[i]);
}
}
template<int B, typename U, typename D>
void print_signed(D number){
if(number < 0){
k_print('-');
print_unsigned<B>(static_cast<U>(-1 * number));
} else {
print_unsigned<B>(static_cast<U>(number));
}
}
void next_line(){
++current_line;
if(current_line == console::get_rows()){
scroll_up();
--current_line;
}
current_column = 0;
}
} //end of anonymous namespace
void console::init(){
text = !vesa::enabled();
if(text){
t_console.init();
} else {
v_console.init();
}
}
size_t console::get_rows(){
if(text){
return t_console.lines();
} else {
return v_console.lines();
}
}
size_t console::get_columns(){
if(text){
return t_console.columns();
} else {
return v_console.columns();
}
}
void* console::save(void* buffer){
thor_assert(!text, "save/restore of the text console is not yet supported");
return v_console.save(buffer);
}
void console::restore(void* buffer){
thor_assert(!text, "save/restore of the text console is not yet supported");
v_console.restore(buffer);
}
void console::set_column(size_t column){
current_column = column;
}
size_t console::get_column(){
return current_column;
}
void console::set_line(size_t line){
current_line = line;
}
size_t console::get_line(){
return current_line;
}
void console::wipeout(){
clear();
current_line = 0;
current_column = 0;
}
void k_print(uint8_t number){
print_unsigned<3>(number);
}
void k_print(uint16_t number){
print_unsigned<5>(number);
}
void k_print(uint32_t number){
print_unsigned<10>(number);
}
void k_print(uint64_t number){
print_unsigned<20>(number);
}
void k_print(int8_t number){
print_signed<3,uint8_t>(number);
}
void k_print(int16_t number){
print_signed<5,uint16_t>(number);
}
void k_print(int32_t number){
print_signed<10,uint32_t>(number);
}
void k_print(int64_t number){
print_signed<20,uint64_t,int64_t>(number);
}
void k_print(char key){
if(key == '\n'){
next_line();
} else if(key == '\r'){
// Ignore \r for now
} else if(key == '\b'){
--current_column;
k_print(' ');
--current_column;
} else if(key == '\t'){
k_print(" ");
} else {
print_char(current_line, current_column, key);
++current_column;
if(current_column == console::get_columns()){
next_line();
}
}
}
void k_print(const char* str){
for(uint64_t i = 0; str[i] != 0; ++i){
k_print(str[i]);
}
}
void k_print(const std::string& s){
for(auto c : s){
k_print(c);
}
}
void k_print(const char* str, uint64_t end){
for(uint64_t i = 0; i < end && str[i] != 0; ++i){
k_print(str[i]);
}
}
#include "printf_def.hpp"
void __printf(const std::string& str){
k_print(str);
}
void __printf_raw(const char* str){
k_print(str);
}
|
//=======================================================================
// Copyright Baptiste Wicht 2013-2016.
// Distributed under the terms of the MIT License.
// (See accompanying file LICENSE or copy at
// http://www.opensource.org/licenses/MIT)
//=======================================================================
#include <stdarg.h>
#include <types.hpp>
#include <string.hpp>
#include "assert.hpp"
#include "console.hpp"
#include "vesa.hpp"
#include "text_console.hpp"
#include "vesa_console.hpp"
namespace {
text_console t_console;
vesa_console v_console;
bool text = true;
void clear(){
if(text){
t_console.clear();
} else {
v_console.clear();
}
}
void scroll_up(){
if(text){
t_console.scroll_up();
} else {
v_console.scroll_up();
}
}
void print_char(size_t line, size_t column, char c){
if(text){
t_console.print_char(line, column, c);
} else {
v_console.print_char(line, column, c);
}
}
volatile size_t current_line = 0;
volatile size_t current_column = 0;
template<int B, typename D>
void print_unsigned(D number){
if(number == 0){
k_print('0');
return;
}
char buffer[B];
int i = 0;
while(number != 0){
buffer[i++] = '0' + number % 10;
number /= 10;
}
--i;
for(; i >= 0; --i){
k_print(buffer[i]);
}
}
template<int B, typename U, typename D>
void print_signed(D number){
if(number < 0){
k_print('-');
print_unsigned<B>(static_cast<U>(-1 * number));
} else {
print_unsigned<B>(static_cast<U>(number));
}
}
void next_line(){
++current_line;
if(current_line == console::get_rows()){
scroll_up();
--current_line;
}
current_column = 0;
}
} //end of anonymous namespace
void console::init(){
text = !vesa::enabled();
if(text){
t_console.init();
} else {
v_console.init();
}
}
size_t console::get_rows(){
if(text){
return t_console.lines();
} else {
return v_console.lines();
}
}
size_t console::get_columns(){
if(text){
return t_console.columns();
} else {
return v_console.columns();
}
}
struct console_state {
size_t current_line;
size_t current_column;
void* buffer = nullptr;
};
void* console::save(void* buffer){
thor_assert(!text, "save/restore of the text console is not yet supported");
auto* state = static_cast<console_state*>(buffer);
if(!state){
state = new console_state;
}
state->current_line = current_line;
state->current_column = current_column;
state->buffer = v_console.save(state->buffer);
return state;
}
void console::restore(void* buffer){
thor_assert(!text, "save/restore of the text console is not yet supported");
auto* state = static_cast<console_state*>(buffer);
current_line = state->current_line;
current_column = state->current_column;
v_console.restore(state->buffer);
}
void console::set_column(size_t column){
current_column = column;
}
size_t console::get_column(){
return current_column;
}
void console::set_line(size_t line){
current_line = line;
}
size_t console::get_line(){
return current_line;
}
void console::wipeout(){
clear();
current_line = 0;
current_column = 0;
}
void k_print(uint8_t number){
print_unsigned<3>(number);
}
void k_print(uint16_t number){
print_unsigned<5>(number);
}
void k_print(uint32_t number){
print_unsigned<10>(number);
}
void k_print(uint64_t number){
print_unsigned<20>(number);
}
void k_print(int8_t number){
print_signed<3,uint8_t>(number);
}
void k_print(int16_t number){
print_signed<5,uint16_t>(number);
}
void k_print(int32_t number){
print_signed<10,uint32_t>(number);
}
void k_print(int64_t number){
print_signed<20,uint64_t,int64_t>(number);
}
void k_print(char key){
if(key == '\n'){
next_line();
} else if(key == '\r'){
// Ignore \r for now
} else if(key == '\b'){
--current_column;
k_print(' ');
--current_column;
} else if(key == '\t'){
k_print(" ");
} else {
print_char(current_line, current_column, key);
++current_column;
if(current_column == console::get_columns()){
next_line();
}
}
}
void k_print(const char* str){
for(uint64_t i = 0; str[i] != 0; ++i){
k_print(str[i]);
}
}
void k_print(const std::string& s){
for(auto c : s){
k_print(c);
}
}
void k_print(const char* str, uint64_t end){
for(uint64_t i = 0; i < end && str[i] != 0; ++i){
k_print(str[i]);
}
}
#include "printf_def.hpp"
void __printf(const std::string& str){
k_print(str);
}
void __printf_raw(const char* str){
k_print(str);
}
|
Save the complete state of the console
|
Save the complete state of the console
|
C++
|
mit
|
wichtounet/thor-os,wichtounet/thor-os
|
6e74c5ec52df7dcacd6bcdc68eae6b3e8b6d1380
|
modules/elm/layers/gradassignment.cpp
|
modules/elm/layers/gradassignment.cpp
|
/*M///////////////////////////////////////////////////////////////////////////////////////
//
// Copyright (c) 2015, Youssef Kashef
// Copyright (c) 2015, Elm Library Project
// 3-clause BSD License
//
//M*/
#include "elm/layers/gradassignment.h"
#include "elm/core/layerconfig.h"
#include "elm/core/signal.h"
#include "elm/layers/sinkhornbalancing.h"
#include "elm/ts/layerattr_.h"
using namespace std;
using namespace cv;
using namespace elm;
// params
const string GradAssignment::PARAM_BETA = "beta0";
const string GradAssignment::PARAM_BETA_MAX = "beta_max";
const string GradAssignment::PARAM_BETA_RATE = "beta_rate";
const string GradAssignment::PARAM_MAX_ITER_PER_BETA = "max_iter_per_beta";
const string GradAssignment::PARAM_MAX_ITER_SINKHORN = "max_iter_sinkhorn";
// I/O Names
const string GradAssignment::KEY_INPUT_GRAPH_AB = "G_ab";
const string GradAssignment::KEY_INPUT_GRAPH_IJ = "g_ij";
const string GradAssignment::KEY_OUTPUT_M = "m";
const float GradAssignment::EPSILON = 1e-2;
/** @todo why does define guard lead to undefined reference error?
*/
//#ifdef __WITH_GTEST
#include <boost/assign/list_of.hpp>
template <>
elm::MapIONames LayerAttr_<GradAssignment>::io_pairs = boost::assign::map_list_of
ELM_ADD_INPUT_PAIR(GradAssignment::KEY_INPUT_GRAPH_AB)
ELM_ADD_INPUT_PAIR(GradAssignment::KEY_INPUT_GRAPH_IJ)
ELM_ADD_OUTPUT_PAIR(GradAssignment::KEY_OUTPUT_M)
;
//#endif
GradAssignment::~GradAssignment()
{
}
GradAssignment::GradAssignment()
: base_Layer()
{
Clear();
}
GradAssignment::GradAssignment(const LayerConfig &cfg)
: base_Layer(cfg)
{
Reset(cfg);
}
void GradAssignment::Clear()
{
m_ai_ = Mat1f();
}
void GradAssignment::Reset(const LayerConfig &config)
{
Clear();
Reconfigure(config);
}
void GradAssignment::Reconfigure(const LayerConfig &config)
{
PTree params = config.Params();
beta_0_ = params.get<float>(PARAM_BETA);
if(beta_0_ <= 0.f) {
ELM_THROW_VALUE_ERROR("Control parameter beta must be positive.");
}
beta_max_ = params.get<float>(PARAM_BETA_MAX);
beta_rate_ = params.get<float>(PARAM_BETA_RATE);
if(beta_rate_ <= 1.f) {
ELM_THROW_VALUE_ERROR("rate must be > 1.");
}
max_iter_per_beta_ = params.get<int>(PARAM_MAX_ITER_SINKHORN);
max_iter_sinkhorn_ = params.get<int>(PARAM_MAX_ITER_PER_BETA);
}
void GradAssignment::IONames(const LayerIONames &config)
{
name_g_ab_ = config.Input(KEY_INPUT_GRAPH_AB);
name_g_ij_ = config.Input(KEY_INPUT_GRAPH_IJ);
name_out_m_ = config.Output(KEY_OUTPUT_M);
}
void GradAssignment::Activate(const Signal &signal)
{
Mat1f g_ab = signal.MostRecentMat(name_g_ab_);
Mat1f g_ij = signal.MostRecentMat(name_g_ij_);
if(g_ab.rows != g_ab.cols) {
ELM_THROW_BAD_DIMS("G_ab's adjacency matrix is not a square matrix.");
}
if(g_ij.rows != g_ij.cols) {
ELM_THROW_BAD_DIMS("G_ij's adjacency matrix is not a square matrix.");
}
A_ = g_ab.rows; ///< no. of vertices in G_ab graph
I_ = g_ij.rows; ///< no. of vertices in G_ij graph
Mat1f c_ai = Compatibility(g_ab, g_ij);
bool is_m_converged = false;
Mat1f m_ai_hat = Mat1f(A_+1, I_+1, 1.f+EPSILON); // add slack variables to be more robust to outliers
m_ai_ = m_ai_hat(Rect2i(0, 0, A_, I_));
float beta = beta_0_;
int nb_iterations_0 = 0;
while(beta < beta_max_) { // A
nb_iterations_0 = 0;
while(!is_m_converged && nb_iterations_0 < max_iter_per_beta_) { // B
Mat1f m_ai_hat_0 = m_ai_hat.clone();
Mat1f q_ai(A_, I_); ///< partial derivative of E_wg with respect to M_ai
multiply(c_ai, m_ai_, q_ai);
// softassign
exp(beta*q_ai, m_ai_);
is_m_converged = SinkhornBalancing::RowColNormalization(m_ai_hat, max_iter_sinkhorn_, EPSILON); // C
is_m_converged = sum(abs(m_ai_hat-m_ai_hat_0))[0] < EPSILON;
nb_iterations_0++;
} // end B
beta *= beta_rate_;
} // end A
}
void GradAssignment::Response(Signal &signal)
{
signal.Append(name_out_m_, m_ai_);
}
Mat1f GradAssignment::Compatibility(const Mat1f &g_ab, const Mat1f &g_ij) const
{
Mat1f c_ai(A_, I_, 0.f);
for(int a=0; a<A_; a++) {
Mat1f g_ab_row = g_ab.row(a);
for(int i=0; i<I_; i++) {
Mat1f g_ij_row = g_ij.row(i);
float sigma_c_aibj_over_bj = 0.f;
for(size_t b=0; b<g_ab_row.total(); b++) {
float g_ab_row_at_b = g_ab_row(b);
// skip for zero-weighted edges.
if(g_ab_row_at_b != 0.f) {
for(size_t j=0; j<g_ij_row.total(); j++) {
sigma_c_aibj_over_bj += Compatibility(g_ab_row_at_b, g_ij_row(j));
}
}
}
c_ai(a, i) = sigma_c_aibj_over_bj;
}
}
c_ai /= static_cast<float>(max(A_, I_));
return c_ai;
}
float GradAssignment::Compatibility(float w1, float w2) const
{
float c;
if(w1 == 0.f || w2 == 0.f) {
c = 0.f;
}
else {
//c = w1*w2;
c = 1.f-3.f*abs(w1-w2);
}
return c;
}
|
/*M///////////////////////////////////////////////////////////////////////////////////////
//
// Copyright (c) 2015, Youssef Kashef
// Copyright (c) 2015, Elm Library Project
// 3-clause BSD License
//
//M*/
#include "elm/layers/gradassignment.h"
#include "elm/core/layerconfig.h"
#include "elm/core/signal.h"
#include "elm/layers/sinkhornbalancing.h"
#include "elm/ts/layerattr_.h"
using namespace std;
using namespace cv;
using namespace elm;
// params
const string GradAssignment::PARAM_BETA = "beta0";
const string GradAssignment::PARAM_BETA_MAX = "beta_max";
const string GradAssignment::PARAM_BETA_RATE = "beta_rate";
const string GradAssignment::PARAM_MAX_ITER_PER_BETA = "max_iter_per_beta";
const string GradAssignment::PARAM_MAX_ITER_SINKHORN = "max_iter_sinkhorn";
// I/O Names
const string GradAssignment::KEY_INPUT_GRAPH_AB = "G_ab";
const string GradAssignment::KEY_INPUT_GRAPH_IJ = "g_ij";
const string GradAssignment::KEY_OUTPUT_M = "m";
const float GradAssignment::EPSILON = 1e-2;
/** @todo why does define guard lead to undefined reference error?
*/
//#ifdef __WITH_GTEST
#include <boost/assign/list_of.hpp>
template <>
elm::MapIONames LayerAttr_<GradAssignment>::io_pairs = boost::assign::map_list_of
ELM_ADD_INPUT_PAIR(GradAssignment::KEY_INPUT_GRAPH_AB)
ELM_ADD_INPUT_PAIR(GradAssignment::KEY_INPUT_GRAPH_IJ)
ELM_ADD_OUTPUT_PAIR(GradAssignment::KEY_OUTPUT_M)
;
//#endif
GradAssignment::~GradAssignment()
{
}
GradAssignment::GradAssignment()
: base_Layer()
{
Clear();
}
GradAssignment::GradAssignment(const LayerConfig &cfg)
: base_Layer(cfg)
{
Reset(cfg);
}
void GradAssignment::Clear()
{
m_ai_ = Mat1f();
}
void GradAssignment::Reset(const LayerConfig &config)
{
Clear();
Reconfigure(config);
}
void GradAssignment::Reconfigure(const LayerConfig &config)
{
PTree params = config.Params();
beta_0_ = params.get<float>(PARAM_BETA);
if(beta_0_ <= 0.f) {
ELM_THROW_VALUE_ERROR("Control parameter beta must be positive.");
}
beta_max_ = params.get<float>(PARAM_BETA_MAX);
beta_rate_ = params.get<float>(PARAM_BETA_RATE);
if(beta_rate_ <= 1.f) {
ELM_THROW_VALUE_ERROR("rate must be > 1.");
}
max_iter_per_beta_ = params.get<int>(PARAM_MAX_ITER_SINKHORN);
max_iter_sinkhorn_ = params.get<int>(PARAM_MAX_ITER_PER_BETA);
}
void GradAssignment::IONames(const LayerIONames &config)
{
name_g_ab_ = config.Input(KEY_INPUT_GRAPH_AB);
name_g_ij_ = config.Input(KEY_INPUT_GRAPH_IJ);
name_out_m_ = config.Output(KEY_OUTPUT_M);
}
void GradAssignment::Activate(const Signal &signal)
{
Mat1f g_ab = signal.MostRecentMat(name_g_ab_);
Mat1f g_ij = signal.MostRecentMat(name_g_ij_);
if(g_ab.rows != g_ab.cols) {
ELM_THROW_BAD_DIMS("G_ab's adjacency matrix is not a square matrix.");
}
if(g_ij.rows != g_ij.cols) {
ELM_THROW_BAD_DIMS("G_ij's adjacency matrix is not a square matrix.");
}
A_ = g_ab.rows; ///< no. of vertices in G_ab graph
I_ = g_ij.rows; ///< no. of vertices in G_ij graph
Mat1f c_ai = Compatibility(g_ab, g_ij);
bool is_m_converged = false;
Mat1f m_ai_hat = Mat1f(A_+1, I_+1, 1.f+EPSILON); // add slack variables to be more robust to outliers
m_ai_ = m_ai_hat(Rect2i(0, 0, A_, I_));
float beta = beta_0_;
int nb_iterations_0 = 0;
while(beta < beta_max_) { // A
nb_iterations_0 = 0;
while(!is_m_converged && nb_iterations_0 < max_iter_per_beta_) { // B
Mat1f m_ai_hat_0 = m_ai_hat.clone();
Mat1f q_ai(A_, I_); ///< partial derivative of E_wg with respect to M_ai
multiply(c_ai, m_ai_, q_ai);
// softassign
exp(beta*q_ai, m_ai_);
is_m_converged = SinkhornBalancing::RowColNormalization(m_ai_hat, max_iter_sinkhorn_, EPSILON); // C
is_m_converged = sum(abs(m_ai_hat-m_ai_hat_0))[0] < EPSILON;
nb_iterations_0++;
} // end B
beta *= beta_rate_;
} // end A
}
void GradAssignment::Response(Signal &signal)
{
signal.Append(name_out_m_, m_ai_);
}
Mat1f GradAssignment::Compatibility(const Mat1f &g_ab, const Mat1f &g_ij) const
{
Mat1f c_ai(A_, I_, 0.f);
for(int a=0; a<A_; a++) {
Mat1f g_ab_row = g_ab.row(a);
for(int i=0; i<I_; i++) {
Mat1f g_ij_row = g_ij.row(i);
float sigma_c_aibj_over_bj = 0.f;
for(size_t b=0; b<g_ab_row.total(); b++) {
float g_ab_row_at_b = g_ab_row(b);
// skip for zero-weighted edges.
if(g_ab_row_at_b != 0.f) {
for(size_t j=0; j<g_ij_row.total(); j++) {
sigma_c_aibj_over_bj += Compatibility(g_ab_row_at_b, g_ij_row(j));
}
}
}
c_ai(a, i) = sigma_c_aibj_over_bj;
}
}
//c_ai /= static_cast<float>(max(A_, I_));
return c_ai;
}
float GradAssignment::Compatibility(float w1, float w2) const
{
float c;
if(w1 == 0.f || w2 == 0.f) {
c = 0.f;
}
else {
//c = w1*w2;
c = 1.f-3.f*abs(w1-w2);
}
return c;
}
|
comment out comp. matrix normalization until we figure out a better solution
|
comment out comp. matrix normalization until we figure out a better solution
|
C++
|
bsd-3-clause
|
kashefy/elm,kashefy/elm,kashefy/elm,kashefy/elm
|
43754afa62c5404b80ae16905d124356c9579e1d
|
src/upsampling_algorithm_short_sequence.cc
|
src/upsampling_algorithm_short_sequence.cc
|
#include <iostream>
#include <fstream>
#include <vector>
#include <memory>
#include <algorithm>
#include <functional>
#include <complex>
#include <iterator>
#include <sndfile.hh>
#define kiss_fft_scalar float
#include "kiss_fft.h"
int main(int argc, char *argv[])
{
const int I = 2;
const int D = 1;
const int N = 256;
const int M = I/D*N;
if (argc != 2) {
std::cerr << "Usage upsampling_algorithm_short_sequence <filename>\n";
return -1;
}
const std::string input_filename = argv[argc-1];
SndfileHandle input_file(input_filename);
if (input_file.channels() != 1) {
std::cerr << "Only files with one audio channel are supported.\n";
}
// Input data
std::vector<kiss_fft_scalar> input_buffer(N);
if (input_file.read(input_buffer.data(), N) != N) {
std::cerr << "Error reading " << N << " samples from " << input_filename << ".\n";
}
// Kiss FFT configurations
auto fwd_cfg = std::unique_ptr<std::remove_pointer<kiss_fft_cfg>::type, decltype(kiss_fft_free) *> {
kiss_fft_alloc(N, 0, nullptr, nullptr),
kiss_fft_free
};
auto inv_cfg = std::unique_ptr<std::remove_pointer<kiss_fft_cfg>::type, decltype(kiss_fft_free) *> {
kiss_fft_alloc(M, 1, nullptr, nullptr),
kiss_fft_free
};
if (fwd_cfg == nullptr || inv_cfg == nullptr) {
std::cerr << "Error allocating Kiss FFT configurations.\n";
}
// Create FFT input buffer
std::vector<std::complex<kiss_fft_scalar>> fft_input_buffer(N);
std::transform(std::begin(input_buffer), std::end(input_buffer),
std::begin(fft_input_buffer),
[](kiss_fft_scalar real) { return std::complex<kiss_fft_scalar>(real); });
std::ofstream fft_input_buffer_file("fft_input_buffer.asc");
std::copy(std::begin(fft_input_buffer), std::end(fft_input_buffer),
std::ostream_iterator<std::complex<kiss_fft_scalar>>(fft_input_buffer_file, "\n"));
// Forward N points FFT
std::vector<std::complex<kiss_fft_scalar>> fft_output_buffer(fft_input_buffer.size());
kiss_fft(fwd_cfg.get(),
reinterpret_cast<kiss_fft_cpx*>(fft_input_buffer.data()),
reinterpret_cast<kiss_fft_cpx*>(fft_output_buffer.data()));
std::ofstream fft_output_buffer_file("fft_output_buffer.asc");
std::copy(std::begin(fft_output_buffer), std::end(fft_output_buffer),
std::ostream_iterator<std::complex<kiss_fft_scalar>>(fft_output_buffer_file, "\n"));
// Method 1
// Create IFFT input buffer, C_i = 0
std::vector<std::complex<kiss_fft_scalar>> ifft_input_buffer_zeros(M);
std::copy(std::begin(fft_output_buffer), std::begin(fft_output_buffer) + N/2, std::begin(ifft_input_buffer_zeros));
std::copy(std::begin(fft_output_buffer) + N/2, std::end(fft_output_buffer), std::end(ifft_input_buffer_zeros) - N/2);
std::transform(std::begin(ifft_input_buffer_zeros), std::end(ifft_input_buffer_zeros),
std::begin(ifft_input_buffer_zeros),
std::bind1st(std::multiplies<std::complex<kiss_fft_scalar>>(), 1.0*I/D));
std::ofstream ifft_input_buffer_zeros_file("ifft_input_buffer_zeros.asc");
std::copy(std::begin(ifft_input_buffer_zeros), std::end(ifft_input_buffer_zeros),
std::ostream_iterator<std::complex<kiss_fft_scalar>>(ifft_input_buffer_zeros_file, "\n"));
// Backward M points IFFT
std::vector<std::complex<kiss_fft_scalar>> ifft_output_buffer_zeros(ifft_input_buffer_zeros.size());
kiss_fft(inv_cfg.get(),
reinterpret_cast<kiss_fft_cpx*>(ifft_input_buffer_zeros.data()),
reinterpret_cast<kiss_fft_cpx*>(ifft_output_buffer_zeros.data()));
std::transform(std::begin(ifft_output_buffer_zeros), std::end(ifft_output_buffer_zeros),
std::begin(ifft_output_buffer_zeros),
std::bind1st(std::multiplies<std::complex<kiss_fft_scalar>>(), 1.0/M));
std::ofstream ifft_output_buffer_zeros_file("ifft_output_buffer_zeros.asc");
std::copy(std::begin(ifft_output_buffer_zeros), std::end(ifft_output_buffer_zeros),
std::ostream_iterator<std::complex<kiss_fft_scalar>>(ifft_output_buffer_zeros_file, "\n"));
// Store results
const std::string output_filename_zeros = "out_zeros.wav";
SndfileHandle output_file_zeros(output_filename_zeros, SFM_WRITE, input_file.format(), input_file.channels(), input_file.samplerate() * I/D);
std::vector<kiss_fft_scalar> output_buffer_zeros(ifft_output_buffer_zeros.size());
std::transform(std::begin(ifft_output_buffer_zeros), std::end(ifft_output_buffer_zeros),
std::begin(output_buffer_zeros),
[](std::complex<kiss_fft_scalar> cpx) { return cpx.real(); });
output_file_zeros.write(output_buffer_zeros.data(), output_buffer_zeros.size());
// Method 2
// Create IFFT input buffer, C_i = X(N/2)
std::vector<std::complex<kiss_fft_scalar>> ifft_input_buffer_nonzeros(M, std::complex<kiss_fft_scalar>(fft_output_buffer[N/2]));
std::copy(std::begin(fft_output_buffer), std::begin(fft_output_buffer) + N/2, std::begin(ifft_input_buffer_nonzeros));
std::copy(std::begin(fft_output_buffer) + N/2, std::end(fft_output_buffer), std::end(ifft_input_buffer_nonzeros) - N/2);
std::transform(std::begin(ifft_input_buffer_nonzeros), std::end(ifft_input_buffer_nonzeros),
std::begin(ifft_input_buffer_nonzeros),
std::bind1st(std::multiplies<std::complex<kiss_fft_scalar>>(), 1.0*I/D));
std::ofstream ifft_input_buffer_nonzeros_file("ifft_input_buffer_nonzeros.asc");
std::copy(std::begin(ifft_input_buffer_nonzeros), std::end(ifft_input_buffer_nonzeros),
std::ostream_iterator<std::complex<kiss_fft_scalar>>(ifft_input_buffer_nonzeros_file, "\n"));
// Backward M points IFFT
std::vector<std::complex<kiss_fft_scalar>> ifft_output_buffer_nonzeros(ifft_input_buffer_nonzeros.size());
kiss_fft(inv_cfg.get(), reinterpret_cast<kiss_fft_cpx*>(ifft_input_buffer_nonzeros.data()), reinterpret_cast<kiss_fft_cpx*>(ifft_output_buffer_nonzeros.data()));
std::transform(std::begin(ifft_output_buffer_nonzeros), std::end(ifft_output_buffer_nonzeros),
std::begin(ifft_output_buffer_nonzeros),
std::bind1st(std::multiplies<std::complex<kiss_fft_scalar>>(), 1.0/M));
std::ofstream ifft_output_buffer_nonzeros_file("ifft_output_buffer_nonzeros.asc");
std::copy(std::begin(ifft_output_buffer_nonzeros), std::end(ifft_output_buffer_nonzeros),
std::ostream_iterator<std::complex<kiss_fft_scalar>>(ifft_output_buffer_nonzeros_file, "\n"));
// Store results
const std::string output_filename_nonzeros = "out_nonzeros.wav";
SndfileHandle output_file_nonzeros(output_filename_nonzeros, SFM_WRITE, input_file.format(), input_file.channels(), input_file.samplerate() * I/D);
std::vector<kiss_fft_scalar> output_buffer_nonzeros(ifft_output_buffer_nonzeros.size());
std::transform(std::begin(ifft_output_buffer_nonzeros), std::end(ifft_output_buffer_nonzeros),
std::begin(output_buffer_nonzeros),
[](std::complex<kiss_fft_scalar> cpx) { return cpx.real(); });
output_file_nonzeros.write(output_buffer_nonzeros.data(), output_buffer_nonzeros.size());
kiss_fft_cleanup();
return 0;
}
|
#include <iostream>
#include <fstream>
#include <vector>
#include <memory>
#include <algorithm>
#include <functional>
#include <complex>
#include <iterator>
#include <sndfile.hh>
#define kiss_fft_scalar float
#include "kiss_fft.h"
int main(int argc, char *argv[])
{
const int I = 2;
const int D = 1;
const int N = 256;
const int M = I/D*N;
const auto precision = []() -> std::streamsize {
// https://www.working-software.com/cpp-floats-as-decimal
if (std::is_same<kiss_fft_scalar, float>::value) return 9;
if (std::is_same<kiss_fft_scalar, double>::value) return 17;
return std::cout.precision();
}();
if (argc != 2) {
std::cerr << "Usage upsampling_algorithm_short_sequence <filename>\n";
return -1;
}
const std::string input_filename = argv[argc-1];
SndfileHandle input_file(input_filename);
if (input_file.channels() != 1) {
std::cerr << "Only files with one audio channel are supported.\n";
}
// Input data
std::vector<kiss_fft_scalar> input_buffer(N);
if (input_file.read(input_buffer.data(), N) != N) {
std::cerr << "Error reading " << N << " samples from " << input_filename << ".\n";
}
// Kiss FFT configurations
auto fwd_cfg = std::unique_ptr<std::remove_pointer<kiss_fft_cfg>::type, decltype(kiss_fft_free) *> {
kiss_fft_alloc(N, 0, nullptr, nullptr),
kiss_fft_free
};
auto inv_cfg = std::unique_ptr<std::remove_pointer<kiss_fft_cfg>::type, decltype(kiss_fft_free) *> {
kiss_fft_alloc(M, 1, nullptr, nullptr),
kiss_fft_free
};
if (fwd_cfg == nullptr || inv_cfg == nullptr) {
std::cerr << "Error allocating Kiss FFT configurations.\n";
}
// Create FFT input buffer
std::vector<std::complex<kiss_fft_scalar>> fft_input_buffer(N);
std::transform(std::begin(input_buffer), std::end(input_buffer),
std::begin(fft_input_buffer),
[](kiss_fft_scalar real) { return std::complex<kiss_fft_scalar>(real); });
std::ofstream fft_input_buffer_file("fft_input_buffer.asc");
fft_input_buffer_file.precision(precision);
std::copy(std::begin(fft_input_buffer), std::end(fft_input_buffer),
std::ostream_iterator<std::complex<kiss_fft_scalar>>(fft_input_buffer_file, "\n"));
// Forward N points FFT
std::vector<std::complex<kiss_fft_scalar>> fft_output_buffer(fft_input_buffer.size());
kiss_fft(fwd_cfg.get(),
reinterpret_cast<kiss_fft_cpx*>(fft_input_buffer.data()),
reinterpret_cast<kiss_fft_cpx*>(fft_output_buffer.data()));
std::ofstream fft_output_buffer_file("fft_output_buffer.asc");
fft_output_buffer_file.precision(precision);
std::copy(std::begin(fft_output_buffer), std::end(fft_output_buffer),
std::ostream_iterator<std::complex<kiss_fft_scalar>>(fft_output_buffer_file, "\n"));
// Method 1
// Create IFFT input buffer, C_i = 0
std::vector<std::complex<kiss_fft_scalar>> ifft_input_buffer_zeros(M);
std::copy(std::begin(fft_output_buffer), std::begin(fft_output_buffer) + N/2, std::begin(ifft_input_buffer_zeros));
std::copy(std::begin(fft_output_buffer) + N/2, std::end(fft_output_buffer), std::end(ifft_input_buffer_zeros) - N/2);
std::transform(std::begin(ifft_input_buffer_zeros), std::end(ifft_input_buffer_zeros),
std::begin(ifft_input_buffer_zeros),
std::bind1st(std::multiplies<std::complex<kiss_fft_scalar>>(), 1.0*I/D));
std::ofstream ifft_input_buffer_zeros_file("ifft_input_buffer_zeros.asc");
ifft_input_buffer_zeros_file.precision(precision);
std::copy(std::begin(ifft_input_buffer_zeros), std::end(ifft_input_buffer_zeros),
std::ostream_iterator<std::complex<kiss_fft_scalar>>(ifft_input_buffer_zeros_file, "\n"));
// Backward M points IFFT
std::vector<std::complex<kiss_fft_scalar>> ifft_output_buffer_zeros(ifft_input_buffer_zeros.size());
kiss_fft(inv_cfg.get(),
reinterpret_cast<kiss_fft_cpx*>(ifft_input_buffer_zeros.data()),
reinterpret_cast<kiss_fft_cpx*>(ifft_output_buffer_zeros.data()));
std::transform(std::begin(ifft_output_buffer_zeros), std::end(ifft_output_buffer_zeros),
std::begin(ifft_output_buffer_zeros),
std::bind1st(std::multiplies<std::complex<kiss_fft_scalar>>(), 1.0/M));
std::ofstream ifft_output_buffer_zeros_file("ifft_output_buffer_zeros.asc");
ifft_output_buffer_zeros_file.precision(precision);
std::copy(std::begin(ifft_output_buffer_zeros), std::end(ifft_output_buffer_zeros),
std::ostream_iterator<std::complex<kiss_fft_scalar>>(ifft_output_buffer_zeros_file, "\n"));
// Store results
const std::string output_filename_zeros = "out_zeros.wav";
SndfileHandle output_file_zeros(output_filename_zeros, SFM_WRITE, input_file.format(), input_file.channels(), input_file.samplerate() * I/D);
std::vector<kiss_fft_scalar> output_buffer_zeros(ifft_output_buffer_zeros.size());
std::transform(std::begin(ifft_output_buffer_zeros), std::end(ifft_output_buffer_zeros),
std::begin(output_buffer_zeros),
[](std::complex<kiss_fft_scalar> cpx) { return cpx.real(); });
output_file_zeros.write(output_buffer_zeros.data(), output_buffer_zeros.size());
// Method 2
// Create IFFT input buffer, C_i = X(N/2)
std::vector<std::complex<kiss_fft_scalar>> ifft_input_buffer_nonzeros(M, std::complex<kiss_fft_scalar>(fft_output_buffer[N/2]));
std::copy(std::begin(fft_output_buffer), std::begin(fft_output_buffer) + N/2, std::begin(ifft_input_buffer_nonzeros));
std::copy(std::begin(fft_output_buffer) + N/2, std::end(fft_output_buffer), std::end(ifft_input_buffer_nonzeros) - N/2);
std::transform(std::begin(ifft_input_buffer_nonzeros), std::end(ifft_input_buffer_nonzeros),
std::begin(ifft_input_buffer_nonzeros),
std::bind1st(std::multiplies<std::complex<kiss_fft_scalar>>(), 1.0*I/D));
std::ofstream ifft_input_buffer_nonzeros_file("ifft_input_buffer_nonzeros.asc");
ifft_input_buffer_nonzeros_file.precision(precision);
std::copy(std::begin(ifft_input_buffer_nonzeros), std::end(ifft_input_buffer_nonzeros),
std::ostream_iterator<std::complex<kiss_fft_scalar>>(ifft_input_buffer_nonzeros_file, "\n"));
// Backward M points IFFT
std::vector<std::complex<kiss_fft_scalar>> ifft_output_buffer_nonzeros(ifft_input_buffer_nonzeros.size());
kiss_fft(inv_cfg.get(), reinterpret_cast<kiss_fft_cpx*>(ifft_input_buffer_nonzeros.data()), reinterpret_cast<kiss_fft_cpx*>(ifft_output_buffer_nonzeros.data()));
std::transform(std::begin(ifft_output_buffer_nonzeros), std::end(ifft_output_buffer_nonzeros),
std::begin(ifft_output_buffer_nonzeros),
std::bind1st(std::multiplies<std::complex<kiss_fft_scalar>>(), 1.0/M));
std::ofstream ifft_output_buffer_nonzeros_file("ifft_output_buffer_nonzeros.asc");
ifft_output_buffer_nonzeros_file.precision(precision);
std::copy(std::begin(ifft_output_buffer_nonzeros), std::end(ifft_output_buffer_nonzeros),
std::ostream_iterator<std::complex<kiss_fft_scalar>>(ifft_output_buffer_nonzeros_file, "\n"));
// Store results
const std::string output_filename_nonzeros = "out_nonzeros.wav";
SndfileHandle output_file_nonzeros(output_filename_nonzeros, SFM_WRITE, input_file.format(), input_file.channels(), input_file.samplerate() * I/D);
std::vector<kiss_fft_scalar> output_buffer_nonzeros(ifft_output_buffer_nonzeros.size());
std::transform(std::begin(ifft_output_buffer_nonzeros), std::end(ifft_output_buffer_nonzeros),
std::begin(output_buffer_nonzeros),
[](std::complex<kiss_fft_scalar> cpx) { return cpx.real(); });
output_file_nonzeros.write(output_buffer_nonzeros.data(), output_buffer_nonzeros.size());
kiss_fft_cleanup();
return 0;
}
|
Save IEEE floating-point C++ data as decimal text with the correct precision.
|
Save IEEE floating-point C++ data as decimal text with the correct precision.
|
C++
|
mit
|
mpoullet/audio-tools,mpoullet/audio-tools,mpoullet/audio-tools,mpoullet/audio-tools,mpoullet/audio-tools
|
8fb727a20f2d9ed865aafbb37657b62e37e43d89
|
tests/utils.cpp
|
tests/utils.cpp
|
#include "gtest/gtest.h"
#include "utils.h"
namespace bpftrace {
namespace test {
namespace utils {
TEST(utils, split_string)
{
std::vector<std::string> tokens_empty = {};
std::vector<std::string> tokens_one_empty = {""};
std::vector<std::string> tokens_two_empty = {"", ""};
std::vector<std::string> tokens_f = {"", "f"};
std::vector<std::string> tokens_foo_bar = {"foo", "bar"};
std::vector<std::string> tokens_empty_foo_bar = {"", "foo", "bar"};
std::vector<std::string> tokens_empty_foo_empty_bar = {"", "foo", "", "bar"};
std::vector<std::string> tokens_empty_foo_bar_biz = {"", "foo", "bar", "biz"};
EXPECT_EQ(split_string("", '-'), tokens_empty);
EXPECT_EQ(split_string("-", '-'), tokens_one_empty);
EXPECT_EQ(split_string("--", '-'), tokens_two_empty);
EXPECT_EQ(split_string("-f-", '-'), tokens_f);
EXPECT_EQ(split_string("-foo-bar-", '-'), tokens_empty_foo_bar);
EXPECT_EQ(split_string("-foo--bar-", '-'), tokens_empty_foo_empty_bar);
EXPECT_EQ(split_string("-foo-bar-biz-", '-'), tokens_empty_foo_bar_biz);
EXPECT_EQ(split_string("-foo-bar", '-'), tokens_empty_foo_bar);
EXPECT_EQ(split_string("foo-bar-", '-'), tokens_foo_bar);
EXPECT_EQ(split_string("foo-bar", '-'), tokens_foo_bar);
}
TEST(utils, wildcard_match)
{
std::vector<std::string> tokens_not = {"not"};
std::vector<std::string> tokens_bar = {"bar"};
std::vector<std::string> tokens_bar_not = {"bar", "not"};
std::vector<std::string> tokens_foo = {"foo"};
std::vector<std::string> tokens_biz = {"biz"};
std::vector<std::string> tokens_foo_biz = {"foo", "biz"};
// start: true, end: true
EXPECT_EQ(wildcard_match("foobarbiz", tokens_not, true, true), false);
EXPECT_EQ(wildcard_match("foobarbiz", tokens_bar, true, true), true);
EXPECT_EQ(wildcard_match("foobarbiz", tokens_bar_not, true, true), false);
EXPECT_EQ(wildcard_match("foobarbiz", tokens_foo, true, true), true);
EXPECT_EQ(wildcard_match("foobarbiz", tokens_biz, true, true), true);
EXPECT_EQ(wildcard_match("foobarbiz", tokens_foo_biz, true, true), true);
// start: false, end: true
EXPECT_EQ(wildcard_match("foobarbiz", tokens_not, false, true), false);
EXPECT_EQ(wildcard_match("foobarbiz", tokens_bar, false, true), false);
EXPECT_EQ(wildcard_match("foobarbiz", tokens_bar_not, false, true), false);
EXPECT_EQ(wildcard_match("foobarbiz", tokens_foo, false, true), true);
EXPECT_EQ(wildcard_match("foobarbiz", tokens_biz, false, true), false);
EXPECT_EQ(wildcard_match("foobarbiz", tokens_foo_biz, false, true), true);
// start: true, end: false
EXPECT_EQ(wildcard_match("foobarbiz", tokens_not, true, false), false);
EXPECT_EQ(wildcard_match("foobarbiz", tokens_bar, true, false), false);
EXPECT_EQ(wildcard_match("foobarbiz", tokens_bar_not, true, false), false);
EXPECT_EQ(wildcard_match("foobarbiz", tokens_foo, true, false), false);
EXPECT_EQ(wildcard_match("foobarbiz", tokens_biz, true, false), true);
EXPECT_EQ(wildcard_match("foobarbiz", tokens_foo_biz, true, false), true);
// start: false, end: false
EXPECT_EQ(wildcard_match("foobarbiz", tokens_not, false, false), false);
EXPECT_EQ(wildcard_match("foobarbiz", tokens_bar, false, false), false);
EXPECT_EQ(wildcard_match("foobarbiz", tokens_bar_not, false, false), false);
EXPECT_EQ(wildcard_match("foobarbiz", tokens_foo, false, false), false);
EXPECT_EQ(wildcard_match("foobarbiz", tokens_biz, false, false), false);
EXPECT_EQ(wildcard_match("foobarbiz", tokens_foo_biz, false, false), true);
}
} // namespace ast
} // namespace test
} // namespace bpftrace
|
#include "gmock/gmock.h"
#include "gtest/gtest.h"
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include "utils.h"
namespace bpftrace {
namespace test {
namespace utils {
TEST(utils, split_string)
{
std::vector<std::string> tokens_empty = {};
std::vector<std::string> tokens_one_empty = {""};
std::vector<std::string> tokens_two_empty = {"", ""};
std::vector<std::string> tokens_f = {"", "f"};
std::vector<std::string> tokens_foo_bar = {"foo", "bar"};
std::vector<std::string> tokens_empty_foo_bar = {"", "foo", "bar"};
std::vector<std::string> tokens_empty_foo_empty_bar = {"", "foo", "", "bar"};
std::vector<std::string> tokens_empty_foo_bar_biz = {"", "foo", "bar", "biz"};
EXPECT_EQ(split_string("", '-'), tokens_empty);
EXPECT_EQ(split_string("-", '-'), tokens_one_empty);
EXPECT_EQ(split_string("--", '-'), tokens_two_empty);
EXPECT_EQ(split_string("-f-", '-'), tokens_f);
EXPECT_EQ(split_string("-foo-bar-", '-'), tokens_empty_foo_bar);
EXPECT_EQ(split_string("-foo--bar-", '-'), tokens_empty_foo_empty_bar);
EXPECT_EQ(split_string("-foo-bar-biz-", '-'), tokens_empty_foo_bar_biz);
EXPECT_EQ(split_string("-foo-bar", '-'), tokens_empty_foo_bar);
EXPECT_EQ(split_string("foo-bar-", '-'), tokens_foo_bar);
EXPECT_EQ(split_string("foo-bar", '-'), tokens_foo_bar);
}
TEST(utils, wildcard_match)
{
std::vector<std::string> tokens_not = {"not"};
std::vector<std::string> tokens_bar = {"bar"};
std::vector<std::string> tokens_bar_not = {"bar", "not"};
std::vector<std::string> tokens_foo = {"foo"};
std::vector<std::string> tokens_biz = {"biz"};
std::vector<std::string> tokens_foo_biz = {"foo", "biz"};
// start: true, end: true
EXPECT_EQ(wildcard_match("foobarbiz", tokens_not, true, true), false);
EXPECT_EQ(wildcard_match("foobarbiz", tokens_bar, true, true), true);
EXPECT_EQ(wildcard_match("foobarbiz", tokens_bar_not, true, true), false);
EXPECT_EQ(wildcard_match("foobarbiz", tokens_foo, true, true), true);
EXPECT_EQ(wildcard_match("foobarbiz", tokens_biz, true, true), true);
EXPECT_EQ(wildcard_match("foobarbiz", tokens_foo_biz, true, true), true);
// start: false, end: true
EXPECT_EQ(wildcard_match("foobarbiz", tokens_not, false, true), false);
EXPECT_EQ(wildcard_match("foobarbiz", tokens_bar, false, true), false);
EXPECT_EQ(wildcard_match("foobarbiz", tokens_bar_not, false, true), false);
EXPECT_EQ(wildcard_match("foobarbiz", tokens_foo, false, true), true);
EXPECT_EQ(wildcard_match("foobarbiz", tokens_biz, false, true), false);
EXPECT_EQ(wildcard_match("foobarbiz", tokens_foo_biz, false, true), true);
// start: true, end: false
EXPECT_EQ(wildcard_match("foobarbiz", tokens_not, true, false), false);
EXPECT_EQ(wildcard_match("foobarbiz", tokens_bar, true, false), false);
EXPECT_EQ(wildcard_match("foobarbiz", tokens_bar_not, true, false), false);
EXPECT_EQ(wildcard_match("foobarbiz", tokens_foo, true, false), false);
EXPECT_EQ(wildcard_match("foobarbiz", tokens_biz, true, false), true);
EXPECT_EQ(wildcard_match("foobarbiz", tokens_foo_biz, true, false), true);
// start: false, end: false
EXPECT_EQ(wildcard_match("foobarbiz", tokens_not, false, false), false);
EXPECT_EQ(wildcard_match("foobarbiz", tokens_bar, false, false), false);
EXPECT_EQ(wildcard_match("foobarbiz", tokens_bar_not, false, false), false);
EXPECT_EQ(wildcard_match("foobarbiz", tokens_foo, false, false), false);
EXPECT_EQ(wildcard_match("foobarbiz", tokens_biz, false, false), false);
EXPECT_EQ(wildcard_match("foobarbiz", tokens_foo_biz, false, false), true);
}
TEST(utils, resolve_binary_path)
{
std::string path = "/tmp/bpftrace-test-utils-XXXXXX";
if (::mkdtemp(&path[0]) == nullptr) {
throw std::runtime_error("creating temporary path for tests failed");
}
int fd;
fd = open((path + "/executable").c_str(), O_CREAT, S_IRWXU); close(fd);
fd = open((path + "/executable2").c_str(), O_CREAT, S_IRWXU); close(fd);
fd = open((path + "/nonexecutable").c_str(), O_CREAT, S_IRUSR); close(fd);
fd = open((path + "/nonexecutable2").c_str(), O_CREAT, S_IRUSR); close(fd);
std::vector<std::string> paths_empty = {};
std::vector<std::string> paths_one_executable = {path + "/executable"};
std::vector<std::string> paths_all_executables = {path + "/executable", path + "/executable2"};
EXPECT_EQ(resolve_binary_path(path + "/does/not/exist"), paths_empty);
EXPECT_EQ(resolve_binary_path(path + "/does/not/exist*"), paths_empty);
EXPECT_EQ(resolve_binary_path(path + "/nonexecutable"), paths_empty);
EXPECT_EQ(resolve_binary_path(path + "/nonexecutable*"), paths_empty);
EXPECT_EQ(resolve_binary_path(path + "/executable"), paths_one_executable);
EXPECT_EQ(resolve_binary_path(path + "/executable*"), paths_all_executables);
EXPECT_EQ(resolve_binary_path(path + "/*executable*"), paths_all_executables);
exec_system(("rm -rf " + path).c_str());
}
} // namespace utils
} // namespace test
} // namespace bpftrace
|
Add tests for resolve_binary_path
|
Add tests for resolve_binary_path
|
C++
|
apache-2.0
|
iovisor/bpftrace,iovisor/bpftrace,iovisor/bpftrace,iovisor/bpftrace
|
2102f6e56ba24ce91ae0b93bb2757110c034fe7b
|
AdjustRod/AdjustRod.cpp
|
AdjustRod/AdjustRod.cpp
|
/*
OFX AdjustRod plugin.
Copyright (C) 2014 INRIA
Redistribution and use in source and binary forms, with or without modification,
are permitted provided that the following conditions are met:
Redistributions of source code must retain the above copyright notice, this
list of conditions and the following disclaimer.
Redistributions in binary form must reproduce the above copyright notice, this
list of conditions and the following disclaimer in the documentation and/or
other materials provided with the distribution.
Neither the name of the {organization} nor the names of its
contributors may be used to endorse or promote products derived from
this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL 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.
INRIA
Domaine de Voluceau
Rocquencourt - B.P. 105
78153 Le Chesnay Cedex - France
The skeleton for this source file is from:
OFX Basic Example plugin, a plugin that illustrates the use of the OFX Support library.
Copyright (C) 2004-2005 The Open Effects Association Ltd
Author Bruno Nicoletti [email protected]
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 The Open Effects Association Ltd, 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.
The Open Effects Association Ltd
1 Wardour St
London W1D 6PA
England
*/
#include "AdjustRod.h"
#include <cmath>
#include <algorithm>
#include "ofxsProcessing.H"
#include "ofxsMacros.h"
#include "ofxsMerging.h"
#define kPluginName "AdjustRod"
#define kPluginGrouping "Transform"
#define kPluginDescription "Enlarges the input image by a given amount of black and transparant pixels."
#define kPluginIdentifier "net.sf.openfx.AdjustRodPlugin"
#define kPluginVersionMajor 1 // Incrementing this number means that you have broken backwards compatibility of the plug-in.
#define kPluginVersionMinor 0 // Increment this when you have fixed a bug or made it faster.
#define kSupportsTiles 1
#define kSupportsMultiResolution 1
#define kSupportsRenderScale 1
#define kRenderThreadSafety eRenderFullySafe
#define kParamAddPixels "addPixels"
#define kParamAddPixelsLabel "Add Pixels"
#define kParamAddPixelsHint "How many pixels to add on each side for both dimensions (width/height)"
using namespace OFX;
class AdjustRodProcessorBase : public OFX::ImageProcessor
{
protected:
const OFX::Image *_srcImg;
public:
AdjustRodProcessorBase(OFX::ImageEffect &instance)
: OFX::ImageProcessor(instance)
, _srcImg(0)
{
}
/** @brief set the src image */
void setSrcImg(const OFX::Image *v)
{
_srcImg = v;
}
};
template <class PIX, int nComponents, int maxValue>
class AdjustRodProcessor : public AdjustRodProcessorBase
{
public:
AdjustRodProcessor(OFX::ImageEffect &instance)
: AdjustRodProcessorBase(instance)
{
}
private:
void multiThreadProcessImages(OfxRectI procWindow)
{
//assert(filter == _filter);
for (int y = procWindow.y1; y < procWindow.y2; ++y) {
if (_effect.abort()) {
break;
}
PIX *dstPix = (PIX *) _dstImg->getPixelAddress(procWindow.x1, y);
for (int x = procWindow.x1; x < procWindow.x2; ++x, dstPix += nComponents) {
const PIX *srcPix = (const PIX*)_srcImg->getPixelAddress(x , y);
if (!srcPix) {
for (int k = 0; k < nComponents; ++k) {
dstPix[k] = 0.;
}
} else {
for (int k = 0; k < nComponents; ++k) {
dstPix[k] = srcPix[k];
}
}
}
}
}
};
////////////////////////////////////////////////////////////////////////////////
/** @brief The plugin that does our work */
class AdjustRodPlugin : public OFX::ImageEffect
{
public:
/** @brief ctor */
AdjustRodPlugin(OfxImageEffectHandle handle)
: ImageEffect(handle)
, dstClip_(0)
, srcClip_(0)
, _size(0)
{
dstClip_ = fetchClip(kOfxImageEffectOutputClipName);
assert(dstClip_ && (dstClip_->getPixelComponents() == ePixelComponentAlpha || dstClip_->getPixelComponents() == ePixelComponentRGB || dstClip_->getPixelComponents() == ePixelComponentRGBA));
srcClip_ = fetchClip(kOfxImageEffectSimpleSourceClipName);
assert(srcClip_ && (srcClip_->getPixelComponents() == ePixelComponentAlpha || srcClip_->getPixelComponents() == ePixelComponentRGB || srcClip_->getPixelComponents() == ePixelComponentRGBA));
_size = fetchDouble2DParam(kParamAddPixels);
assert(_size);
}
private:
// override the roi call
virtual void getRegionsOfInterest(const OFX::RegionsOfInterestArguments &args, OFX::RegionOfInterestSetter &rois) OVERRIDE FINAL;
virtual bool getRegionOfDefinition(const OFX::RegionOfDefinitionArguments &args, OfxRectD &rod) OVERRIDE FINAL;
/* Override the render */
virtual void render(const OFX::RenderArguments &args) OVERRIDE FINAL;
virtual bool isIdentity(const IsIdentityArguments &args, Clip * &identityClip, double &identityTime) OVERRIDE FINAL;
template <int nComponents>
void renderInternal(const OFX::RenderArguments &args, OFX::BitDepthEnum dstBitDepth);
/* set up and run a processor */
void setupAndProcess(AdjustRodProcessorBase &, const OFX::RenderArguments &args);
private:
// do not need to delete these, the ImageEffect is managing them for us
OFX::Clip *dstClip_;
OFX::Clip *srcClip_;
OFX::Double2DParam* _size;
};
////////////////////////////////////////////////////////////////////////////////
/** @brief render for the filter */
////////////////////////////////////////////////////////////////////////////////
// basic plugin render function, just a skelington to instantiate templates from
/* set up and run a processor */
void
AdjustRodPlugin::setupAndProcess(AdjustRodProcessorBase &processor, const OFX::RenderArguments &args)
{
std::auto_ptr<OFX::Image> dst(dstClip_->fetchImage(args.time));
if (!dst.get()) {
OFX::throwSuiteStatusException(kOfxStatFailed);
}
if (dst->getRenderScale().x != args.renderScale.x ||
dst->getRenderScale().y != args.renderScale.y ||
dst->getField() != args.fieldToRender) {
setPersistentMessage(OFX::Message::eMessageError, "", "OFX Host gave image with wrong scale or field properties");
OFX::throwSuiteStatusException(kOfxStatFailed);
}
std::auto_ptr<OFX::Image> src(srcClip_->fetchImage(args.time));
if (src.get() && dst.get())
{
OFX::BitDepthEnum dstBitDepth = dst->getPixelDepth();
OFX::PixelComponentEnum dstComponents = dst->getPixelComponents();
OFX::BitDepthEnum srcBitDepth = src->getPixelDepth();
OFX::PixelComponentEnum srcComponents = src->getPixelComponents();
if (srcBitDepth != dstBitDepth || srcComponents != dstComponents)
OFX::throwSuiteStatusException(kOfxStatFailed);
}
// set the images
processor.setDstImg(dst.get());
processor.setSrcImg(src.get());
// set the render window
processor.setRenderWindow(args.renderWindow);
// Call the base class process member, this will call the derived templated process code
processor.process();
}
// override the roi call
// Required if the plugin requires a region from the inputs which is different from the rendered region of the output.
// (this is the case here)
void
AdjustRodPlugin::getRegionsOfInterest(const OFX::RegionsOfInterestArguments &args, OFX::RegionOfInterestSetter &rois)
{
OfxRectD srcRod = srcClip_->getRegionOfDefinition(args.time);
double w,h;
_size->getValueAtTime(args.time, w, h);
OfxRectD paddedRoD = srcRod;
paddedRoD.x1 -= w;
paddedRoD.x2 += w;
paddedRoD.y1 -= h;
paddedRoD.y2 += h;
// intersect the crop rectangle with args.regionOfInterest
MergeImages2D::rectIntersection(srcRod, paddedRoD, &paddedRoD);
rois.setRegionOfInterest(*srcClip_, paddedRoD);
}
bool
AdjustRodPlugin::getRegionOfDefinition(const OFX::RegionOfDefinitionArguments &args, OfxRectD &rod)
{
OfxRectD srcRod = srcClip_->getRegionOfDefinition(args.time);
double w,h;
_size->getValueAtTime(args.time, w, h);
rod = srcRod;
rod.x1 -= w;
rod.x2 += w;
rod.y1 -= h;
rod.y2 += h;
return true;
}
// the internal render function
template <int nComponents>
void
AdjustRodPlugin::renderInternal(const OFX::RenderArguments &args, OFX::BitDepthEnum dstBitDepth)
{
switch (dstBitDepth)
{
case OFX::eBitDepthUByte :
{
AdjustRodProcessor<unsigned char, nComponents, 255> fred(*this);
setupAndProcess(fred, args);
} break;
case OFX::eBitDepthUShort :
{
AdjustRodProcessor<unsigned short, nComponents, 65535> fred(*this);
setupAndProcess(fred, args);
} break;
case OFX::eBitDepthFloat :
{
AdjustRodProcessor<float, nComponents, 1> fred(*this);
setupAndProcess(fred, args);
} break;
default :
OFX::throwSuiteStatusException(kOfxStatErrUnsupported);
}
}
// the overridden render function
void
AdjustRodPlugin::render(const OFX::RenderArguments &args)
{
// instantiate the render code based on the pixel depth of the dst clip
OFX::BitDepthEnum dstBitDepth = dstClip_->getPixelDepth();
OFX::PixelComponentEnum dstComponents = dstClip_->getPixelComponents();
assert(dstComponents == OFX::ePixelComponentRGB || dstComponents == OFX::ePixelComponentRGBA || dstComponents == OFX::ePixelComponentAlpha);
if (dstComponents == OFX::ePixelComponentRGBA) {
renderInternal<4>(args, dstBitDepth);
} else if (dstComponents == OFX::ePixelComponentRGB) {
renderInternal<3>(args, dstBitDepth);
} else {
assert(dstComponents == OFX::ePixelComponentAlpha);
renderInternal<1>(args, dstBitDepth);
}
}
bool
AdjustRodPlugin::isIdentity(const IsIdentityArguments &args, Clip * &identityClip, double &identityTime)
{
double w,h;
_size->getValueAtTime(args.time, w, h);
if (w == 0 && h == 0) {
identityClip = srcClip_;
identityTime = args.time;
return true;
}
return false;
}
mDeclarePluginFactory(AdjustRodPluginFactory, {}, {});
void AdjustRodPluginFactory::describe(OFX::ImageEffectDescriptor &desc)
{
// basic labels
desc.setLabels(kPluginName, kPluginName, kPluginName);
desc.setPluginGrouping(kPluginGrouping);
desc.setPluginDescription(kPluginDescription);
desc.addSupportedContext(eContextGeneral);
desc.addSupportedContext(eContextFilter);
desc.addSupportedBitDepth(eBitDepthUByte);
desc.addSupportedBitDepth(eBitDepthUShort);
desc.addSupportedBitDepth(eBitDepthFloat);
desc.setSingleInstance(false);
desc.setHostFrameThreading(false);
desc.setTemporalClipAccess(false);
desc.setRenderTwiceAlways(true);
desc.setSupportsMultipleClipPARs(false);
desc.setRenderThreadSafety(kRenderThreadSafety);
desc.setSupportsTiles(kSupportsTiles);
// in order to support multiresolution, render() must take into account the pixelaspectratio and the renderscale
// and scale the transform appropriately.
// All other functions are usually in canonical coordinates.
desc.setSupportsMultiResolution(kSupportsMultiResolution);
}
OFX::ImageEffect* AdjustRodPluginFactory::createInstance(OfxImageEffectHandle handle, OFX::ContextEnum /*context*/)
{
return new AdjustRodPlugin(handle);
}
void AdjustRodPluginFactory::describeInContext(OFX::ImageEffectDescriptor &desc, OFX::ContextEnum /*context*/)
{
// Source clip only in the filter context
// create the mandated source clip
// always declare the source clip first, because some hosts may consider
// it as the default input clip (e.g. Nuke)
ClipDescriptor *srcClip = desc.defineClip(kOfxImageEffectSimpleSourceClipName);
srcClip->addSupportedComponent(ePixelComponentRGBA);
srcClip->addSupportedComponent(ePixelComponentRGB);
srcClip->addSupportedComponent(ePixelComponentAlpha);
srcClip->setTemporalClipAccess(false);
srcClip->setSupportsTiles(kSupportsTiles);
srcClip->setIsMask(false);
// create the mandated output clip
ClipDescriptor *dstClip = desc.defineClip(kOfxImageEffectOutputClipName);
dstClip->addSupportedComponent(ePixelComponentRGBA);
dstClip->addSupportedComponent(ePixelComponentRGB);
dstClip->addSupportedComponent(ePixelComponentAlpha);
dstClip->setSupportsTiles(kSupportsTiles);
// make some pages and to things in
PageParamDescriptor *page = desc.definePageParam("Controls");
// size
{
Double2DParamDescriptor* param = desc.defineDouble2DParam(kParamAddPixels);
param->setLabels(kParamAddPixelsLabel, kParamAddPixelsLabel, kParamAddPixelsLabel);
param->setHint(kParamAddPixelsHint);
param->setDoubleType(OFX::eDoubleTypeXYAbsolute);
param->setDefaultCoordinateSystem(OFX::eCoordinatesNormalised);
param->setDefault(0., 0.);
param->setIncrement(1.);
param->setDimensionLabels("width", "height");
param->setIncrement(1.);
param->setDigits(0);
page->addChild(*param);
}
}
void getAdjustRodPluginID(OFX::PluginFactoryArray &ids)
{
static AdjustRodPluginFactory p(kPluginIdentifier, kPluginVersionMajor, kPluginVersionMinor);
ids.push_back(&p);
}
|
/*
OFX AdjustRoD plugin.
Copyright (C) 2014 INRIA
Redistribution and use in source and binary forms, with or without modification,
are permitted provided that the following conditions are met:
Redistributions of source code must retain the above copyright notice, this
list of conditions and the following disclaimer.
Redistributions in binary form must reproduce the above copyright notice, this
list of conditions and the following disclaimer in the documentation and/or
other materials provided with the distribution.
Neither the name of the {organization} nor the names of its
contributors may be used to endorse or promote products derived from
this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL 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.
INRIA
Domaine de Voluceau
Rocquencourt - B.P. 105
78153 Le Chesnay Cedex - France
The skeleton for this source file is from:
OFX Basic Example plugin, a plugin that illustrates the use of the OFX Support library.
Copyright (C) 2004-2005 The Open Effects Association Ltd
Author Bruno Nicoletti [email protected]
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 The Open Effects Association Ltd, 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.
The Open Effects Association Ltd
1 Wardour St
London W1D 6PA
England
*/
#include "AdjustRod.h"
#include <cmath>
#include <algorithm>
#include "ofxsProcessing.H"
#include "ofxsMacros.h"
#include "ofxsMerging.h"
#include "ofxsCopier.h"
#define kPluginName "AdjustRoD"
#define kPluginGrouping "Transform"
#define kPluginDescription "Enlarges the input image by a given amount of black and transparant pixels."
#define kPluginIdentifier "net.sf.openfx.AdjustRoDPlugin"
#define kPluginVersionMajor 1 // Incrementing this number means that you have broken backwards compatibility of the plug-in.
#define kPluginVersionMinor 0 // Increment this when you have fixed a bug or made it faster.
#define kSupportsTiles 1
#define kSupportsMultiResolution 1
#define kSupportsRenderScale 1
#define kRenderThreadSafety eRenderFullySafe
#define kParamAddPixels "addPixels"
#define kParamAddPixelsLabel "Add Pixels"
#define kParamAddPixelsHint "How many pixels to add on each side for both dimensions (width/height)"
using namespace OFX;
////////////////////////////////////////////////////////////////////////////////
/** @brief The plugin that does our work */
class AdjustRodPlugin : public OFX::ImageEffect
{
public:
/** @brief ctor */
AdjustRodPlugin(OfxImageEffectHandle handle)
: ImageEffect(handle)
, dstClip_(0)
, srcClip_(0)
, _size(0)
{
dstClip_ = fetchClip(kOfxImageEffectOutputClipName);
assert(dstClip_ && (dstClip_->getPixelComponents() == ePixelComponentAlpha || dstClip_->getPixelComponents() == ePixelComponentRGB || dstClip_->getPixelComponents() == ePixelComponentRGBA));
srcClip_ = fetchClip(kOfxImageEffectSimpleSourceClipName);
assert(srcClip_ && (srcClip_->getPixelComponents() == ePixelComponentAlpha || srcClip_->getPixelComponents() == ePixelComponentRGB || srcClip_->getPixelComponents() == ePixelComponentRGBA));
_size = fetchDouble2DParam(kParamAddPixels);
assert(_size);
}
private:
// override the roi call
virtual void getRegionsOfInterest(const OFX::RegionsOfInterestArguments &args, OFX::RegionOfInterestSetter &rois) OVERRIDE FINAL;
virtual bool getRegionOfDefinition(const OFX::RegionOfDefinitionArguments &args, OfxRectD &rod) OVERRIDE FINAL;
/* Override the render */
virtual void render(const OFX::RenderArguments &args) OVERRIDE FINAL;
virtual bool isIdentity(const IsIdentityArguments &args, Clip * &identityClip, double &identityTime) OVERRIDE FINAL;
template <int nComponents>
void renderInternal(const OFX::RenderArguments &args, OFX::BitDepthEnum dstBitDepth);
/* set up and run a processor */
void setupAndCopy(OFX::PixelProcessorFilterBase &, const OFX::RenderArguments &args);
private:
// do not need to delete these, the ImageEffect is managing them for us
OFX::Clip *dstClip_;
OFX::Clip *srcClip_;
OFX::Double2DParam* _size;
};
////////////////////////////////////////////////////////////////////////////////
/** @brief render for the filter */
////////////////////////////////////////////////////////////////////////////////
// basic plugin render function, just a skelington to instantiate templates from
/* set up and run a processor */
void
AdjustRodPlugin::setupAndCopy(OFX::PixelProcessorFilterBase & processor,
const OFX::RenderArguments &args)
{
std::auto_ptr<OFX::Image> dst(dstClip_->fetchImage(args.time));
if (!dst.get()) {
OFX::throwSuiteStatusException(kOfxStatFailed);
}
if (dst->getRenderScale().x != args.renderScale.x ||
dst->getRenderScale().y != args.renderScale.y ||
dst->getField() != args.fieldToRender) {
setPersistentMessage(OFX::Message::eMessageError, "", "OFX Host gave image with wrong scale or field properties");
OFX::throwSuiteStatusException(kOfxStatFailed);
}
std::auto_ptr<OFX::Image> src(srcClip_->fetchImage(args.time));
if (src.get() && dst.get())
{
OFX::BitDepthEnum dstBitDepth = dst->getPixelDepth();
OFX::PixelComponentEnum dstComponents = dst->getPixelComponents();
OFX::BitDepthEnum srcBitDepth = src->getPixelDepth();
OFX::PixelComponentEnum srcComponents = src->getPixelComponents();
if (srcBitDepth != dstBitDepth || srcComponents != dstComponents)
OFX::throwSuiteStatusException(kOfxStatFailed);
}
// set the images
processor.setDstImg(dst.get());
processor.setSrcImg(src.get());
// set the render window
processor.setRenderWindow(args.renderWindow);
// Call the base class process member, this will call the derived templated process code
processor.process();
}
// override the roi call
// Required if the plugin requires a region from the inputs which is different from the rendered region of the output.
// (this is the case here)
void
AdjustRodPlugin::getRegionsOfInterest(const OFX::RegionsOfInterestArguments &args, OFX::RegionOfInterestSetter &rois)
{
OfxRectD srcRod = srcClip_->getRegionOfDefinition(args.time);
double w,h;
_size->getValueAtTime(args.time, w, h);
OfxRectD paddedRoD = srcRod;
paddedRoD.x1 -= w;
paddedRoD.x2 += w;
paddedRoD.y1 -= h;
paddedRoD.y2 += h;
// intersect the crop rectangle with args.regionOfInterest
MergeImages2D::rectIntersection(srcRod, paddedRoD, &paddedRoD);
rois.setRegionOfInterest(*srcClip_, paddedRoD);
}
bool
AdjustRodPlugin::getRegionOfDefinition(const OFX::RegionOfDefinitionArguments &args, OfxRectD &rod)
{
OfxRectD srcRod = srcClip_->getRegionOfDefinition(args.time);
double w,h;
_size->getValueAtTime(args.time, w, h);
rod = srcRod;
rod.x1 -= w;
rod.x2 += w;
rod.y1 -= h;
rod.y2 += h;
return true;
}
// the internal render function
template <int nComponents>
void
AdjustRodPlugin::renderInternal(const OFX::RenderArguments &args, OFX::BitDepthEnum dstBitDepth)
{
switch (dstBitDepth) {
case OFX::eBitDepthUByte: {
OFX::PixelCopier<unsigned char, nComponents, 255> fred(*this);
setupAndCopy(fred, args);
break;
}
case OFX::eBitDepthUShort: {
OFX::PixelCopier<unsigned short, nComponents, 65535> fred(*this);
setupAndCopy(fred, args);
break;
}
case OFX::eBitDepthFloat: {
OFX::PixelCopier<float, nComponents, 1> fred(*this);
setupAndCopy(fred, args);
break;
}
default :
OFX::throwSuiteStatusException(kOfxStatErrUnsupported);
}
}
// the overridden render function
void
AdjustRodPlugin::render(const OFX::RenderArguments &args)
{
// instantiate the render code based on the pixel depth of the dst clip
OFX::BitDepthEnum dstBitDepth = dstClip_->getPixelDepth();
OFX::PixelComponentEnum dstComponents = dstClip_->getPixelComponents();
assert(dstComponents == OFX::ePixelComponentRGB || dstComponents == OFX::ePixelComponentRGBA || dstComponents == OFX::ePixelComponentAlpha);
if (dstComponents == OFX::ePixelComponentRGBA) {
renderInternal<4>(args, dstBitDepth);
} else if (dstComponents == OFX::ePixelComponentRGB) {
renderInternal<3>(args, dstBitDepth);
} else {
assert(dstComponents == OFX::ePixelComponentAlpha);
renderInternal<1>(args, dstBitDepth);
}
}
bool
AdjustRodPlugin::isIdentity(const IsIdentityArguments &args, Clip * &identityClip, double &identityTime)
{
double w,h;
_size->getValueAtTime(args.time, w, h);
if (w == 0 && h == 0) {
identityClip = srcClip_;
identityTime = args.time;
return true;
}
return false;
}
mDeclarePluginFactory(AdjustRodPluginFactory, {}, {});
void AdjustRodPluginFactory::describe(OFX::ImageEffectDescriptor &desc)
{
// basic labels
desc.setLabels(kPluginName, kPluginName, kPluginName);
desc.setPluginGrouping(kPluginGrouping);
desc.setPluginDescription(kPluginDescription);
desc.addSupportedContext(eContextGeneral);
desc.addSupportedContext(eContextFilter);
desc.addSupportedBitDepth(eBitDepthUByte);
desc.addSupportedBitDepth(eBitDepthUShort);
desc.addSupportedBitDepth(eBitDepthFloat);
desc.setSingleInstance(false);
desc.setHostFrameThreading(false);
desc.setTemporalClipAccess(false);
desc.setRenderTwiceAlways(true);
desc.setSupportsMultipleClipPARs(false);
desc.setRenderThreadSafety(kRenderThreadSafety);
desc.setSupportsTiles(kSupportsTiles);
// in order to support multiresolution, render() must take into account the pixelaspectratio and the renderscale
// and scale the transform appropriately.
// All other functions are usually in canonical coordinates.
desc.setSupportsMultiResolution(kSupportsMultiResolution);
}
OFX::ImageEffect* AdjustRodPluginFactory::createInstance(OfxImageEffectHandle handle, OFX::ContextEnum /*context*/)
{
return new AdjustRodPlugin(handle);
}
void AdjustRodPluginFactory::describeInContext(OFX::ImageEffectDescriptor &desc, OFX::ContextEnum /*context*/)
{
// Source clip only in the filter context
// create the mandated source clip
// always declare the source clip first, because some hosts may consider
// it as the default input clip (e.g. Nuke)
ClipDescriptor *srcClip = desc.defineClip(kOfxImageEffectSimpleSourceClipName);
srcClip->addSupportedComponent(ePixelComponentRGBA);
srcClip->addSupportedComponent(ePixelComponentRGB);
srcClip->addSupportedComponent(ePixelComponentAlpha);
srcClip->setTemporalClipAccess(false);
srcClip->setSupportsTiles(kSupportsTiles);
srcClip->setIsMask(false);
// create the mandated output clip
ClipDescriptor *dstClip = desc.defineClip(kOfxImageEffectOutputClipName);
dstClip->addSupportedComponent(ePixelComponentRGBA);
dstClip->addSupportedComponent(ePixelComponentRGB);
dstClip->addSupportedComponent(ePixelComponentAlpha);
dstClip->setSupportsTiles(kSupportsTiles);
// make some pages and to things in
PageParamDescriptor *page = desc.definePageParam("Controls");
// size
{
Double2DParamDescriptor* param = desc.defineDouble2DParam(kParamAddPixels);
param->setLabels(kParamAddPixelsLabel, kParamAddPixelsLabel, kParamAddPixelsLabel);
param->setHint(kParamAddPixelsHint);
param->setDoubleType(OFX::eDoubleTypeXYAbsolute);
param->setDefaultCoordinateSystem(OFX::eCoordinatesNormalised);
param->setDefault(0., 0.);
param->setIncrement(1.);
param->setDimensionLabels("w", "h");
param->setIncrement(1.);
param->setDigits(0);
page->addChild(*param);
}
}
void getAdjustRodPluginID(OFX::PluginFactoryArray &ids)
{
static AdjustRodPluginFactory p(kPluginIdentifier, kPluginVersionMajor, kPluginVersionMinor);
ids.push_back(&p);
}
|
use PixelCopier!
|
AdjustRoD: use PixelCopier!
|
C++
|
bsd-3-clause
|
olear/openfx-misc,olear/openfx-misc,olear/openfx-misc
|
331c1633b49f6c2110fb249709c9430a4f2efd89
|
svtools/source/dialogs/PlaceEditDialog.cxx
|
svtools/source/dialogs/PlaceEditDialog.cxx
|
/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
/*
* This file is part of the LibreOffice project.
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/.
*/
#include <svtools/PlaceEditDialog.hxx>
#include <svtools/ServerDetailsControls.hxx>
#include <com/sun/star/uno/Sequence.hxx>
#include <officecfg/Office/Common.hxx>
#include <svtools/svtresid.hxx>
#include <vcl/msgbox.hxx>
using namespace com::sun::star::uno;
PlaceEditDialog::PlaceEditDialog(vcl::Window* pParent)
: ModalDialog(pParent, "PlaceEditDialog", "svt/ui/placeedit.ui")
, m_xCurrentDetails()
{
get( m_pEDServerName, "name" );
get( m_pLBServerType, "type" );
get( m_pEDUsername, "login" );
get( m_pBTOk, "ok" );
get( m_pBTCancel, "cancel" );
get( m_pBTDelete, "delete" );
get( m_pBTRepoRefresh, "repositoriesRefresh" );
m_pBTOk->SetClickHdl( LINK( this, PlaceEditDialog, OKHdl) );
m_pBTOk->Enable( false );
m_pEDServerName->SetModifyHdl( LINK( this, PlaceEditDialog, EditHdl) );
// This constructor is called when user request a place creation, so
// delete button is hidden.
m_pBTDelete->Hide();
m_pLBServerType->SetSelectHdl( LINK( this, PlaceEditDialog, SelectTypeHdl ) );
m_pEDUsername->SetModifyHdl( LINK( this, PlaceEditDialog, EditUsernameHdl ) );
InitDetails( );
}
PlaceEditDialog::PlaceEditDialog(vcl::Window* pParent, const std::shared_ptr<Place>& rPlace)
: ModalDialog(pParent, "PlaceEditDialog", "svt/ui/placeedit.ui")
, m_xCurrentDetails( )
{
get( m_pEDServerName, "name" );
get( m_pLBServerType, "type" );
get( m_pEDUsername, "login" );
get( m_pBTOk, "ok" );
get( m_pBTCancel, "cancel" );
get( m_pBTDelete, "delete" );
get( m_pTypeGrid, "TypeGrid" );
m_pBTOk->SetClickHdl( LINK( this, PlaceEditDialog, OKHdl) );
m_pBTDelete->SetClickHdl ( LINK( this, PlaceEditDialog, DelHdl) );
m_pEDServerName->SetModifyHdl( LINK( this, PlaceEditDialog, EditHdl) );
m_pLBServerType->SetSelectHdl( LINK( this, PlaceEditDialog, SelectTypeHdl ) );
InitDetails( );
m_pEDServerName->SetText(rPlace->GetName());
// Fill the boxes with the URL parts
bool bSuccess = false;
for (size_t i = 0 ; i < m_aDetailsContainers.size( ) && !bSuccess; ++i)
{
INetURLObject& rUrl = rPlace->GetUrlObject();
bSuccess = m_aDetailsContainers[i]->setUrl( rUrl );
if ( bSuccess )
{
m_pLBServerType->SelectEntryPos( i );
SelectTypeHdl( m_pLBServerType );
// Fill the Username field
if ( rUrl.HasUserData( ) )
m_pEDUsername->SetText( INetURLObject::decode( rUrl.GetUser( ),
INetURLObject::DECODE_WITH_CHARSET ) );
}
}
// In edit mode user can't change connection type
m_pTypeGrid->Hide();
}
PlaceEditDialog::~PlaceEditDialog()
{
disposeOnce();
}
void PlaceEditDialog::dispose()
{
m_pEDServerName.clear();
m_pLBServerType.clear();
m_pEDUsername.clear();
m_pBTOk.clear();
m_pBTCancel.clear();
m_pBTDelete.clear();
ModalDialog::dispose();
}
OUString PlaceEditDialog::GetServerUrl()
{
OUString sUrl;
if (m_xCurrentDetails.get())
{
INetURLObject aUrl = m_xCurrentDetails->getUrl();
OUString sUsername = OUString( m_pEDUsername->GetText( ) ).trim( );
if ( !sUsername.isEmpty( ) )
aUrl.SetUser( sUsername );
if ( !aUrl.HasError( ) )
sUrl = aUrl.GetMainURL( INetURLObject::NO_DECODE );
}
return sUrl;
}
std::shared_ptr<Place> PlaceEditDialog::GetPlace()
{
return std::make_shared<Place>(m_pEDServerName->GetText(), GetServerUrl(), true);
}
void PlaceEditDialog::InitDetails( )
{
// Create CMIS controls for each server type
Reference< XComponentContext > xContext = ::comphelper::getProcessComponentContext();
// Load the ServerType entries
bool bSkipGDrive = OUString( GDRIVE_CLIENT_ID ).isEmpty() ||
OUString( GDRIVE_CLIENT_SECRET ).isEmpty();
bool bSkipAlfresco = OUString( ALFRESCO_CLOUD_CLIENT_ID ).isEmpty() ||
OUString( ALFRESCO_CLOUD_CLIENT_SECRET ).isEmpty();
bool bSkipOneDrive= OUString( ONEDRIVE_CLIENT_ID ).isEmpty() ||
OUString( ONEDRIVE_CLIENT_SECRET ).isEmpty();
Sequence< OUString > aTypesUrlsList( officecfg::Office::Common::Misc::CmisServersUrls::get( xContext ) );
Sequence< OUString > aTypesNamesList( officecfg::Office::Common::Misc::CmisServersNames::get( xContext ) );
unsigned int nPos = 0;
for ( sal_Int32 i = 0; i < aTypesUrlsList.getLength( ) && aTypesNamesList.getLength( ); ++i )
{
OUString sUrl = aTypesUrlsList[i];
if ( !( sUrl == GDRIVE_BASE_URL && bSkipGDrive ) &&
!( sUrl.startsWith( ALFRESCO_CLOUD_BASE_URL ) && bSkipAlfresco ) &&
!( sUrl == ONEDRIVE_BASE_URL && bSkipOneDrive ) )
{
nPos = m_pLBServerType->InsertEntry( aTypesNamesList[i], nPos );
std::shared_ptr<DetailsContainer> xCmisDetails(std::make_shared<CmisDetailsContainer>(this, sUrl));
xCmisDetails->setChangeHdl( LINK( this, PlaceEditDialog, EditHdl ) );
m_aDetailsContainers.push_back(xCmisDetails);
nPos++;
}
}
// Create WebDAV / FTP / SSH details control
std::shared_ptr<DetailsContainer> xDavDetails(std::make_shared<DavDetailsContainer>(this));
xDavDetails->setChangeHdl( LINK( this, PlaceEditDialog, EditHdl ) );
m_aDetailsContainers.push_back(xDavDetails);
std::shared_ptr<DetailsContainer> xFtpDetails(std::make_shared<HostDetailsContainer>(this, 21, "ftp"));
xFtpDetails->setChangeHdl( LINK( this, PlaceEditDialog, EditHdl ) );
m_aDetailsContainers.push_back(xFtpDetails);
std::shared_ptr<DetailsContainer> xSshDetails(std::make_shared<HostDetailsContainer>(this, 22, "ssh"));
xSshDetails->setChangeHdl( LINK( this, PlaceEditDialog, EditHdl ) );
m_aDetailsContainers.push_back(xSshDetails);
// Create Windows Share control
std::shared_ptr<DetailsContainer> xSmbDetails(std::make_shared<SmbDetailsContainer>(this));
xSmbDetails->setChangeHdl( LINK( this, PlaceEditDialog, EditHdl ) );
m_aDetailsContainers.push_back(xSmbDetails);
// Set default to first value
m_pLBServerType->SelectEntryPos( 0 );
SelectTypeHdl( m_pLBServerType );
}
IMPL_LINK ( PlaceEditDialog, OKHdl, Button *, )
{
if ( m_xCurrentDetails.get() )
{
OUString sUrl = m_xCurrentDetails->getUrl().GetHost( INetURLObject::DECODE_WITH_CHARSET );
OUString sGDriveHost( GDRIVE_BASE_URL );
OUString sAlfrescoHost( ALFRESCO_CLOUD_BASE_URL );
OUString sOneDriveHost( ONEDRIVE_BASE_URL );
if ( sUrl.compareTo( sGDriveHost, sGDriveHost.getLength() ) == 0
|| sUrl.compareTo( sAlfrescoHost, sAlfrescoHost.getLength() ) == 0
|| sUrl.compareTo( sOneDriveHost, sOneDriveHost.getLength() ) == 0 )
{
m_pBTRepoRefresh->Click();
sUrl = m_xCurrentDetails->getUrl().GetHost( INetURLObject::DECODE_WITH_CHARSET );
INetURLObject aHostUrl( sUrl );
OUString sRepoId = aHostUrl.GetMark();
if ( !sRepoId.isEmpty() )
{
EndDialog( RET_OK );
}
else
{
// TODO: repository id missing. Auth error?
}
}
else
{
EndDialog( RET_OK );
}
}
return 1;
}
IMPL_LINK ( PlaceEditDialog, DelHdl, Button *, )
{
// ReUsing existing symbols...
EndDialog( RET_NO );
return 1;
}
IMPL_LINK_NOARG( PlaceEditDialog, EditHdl )
{
OUString sUrl = GetServerUrl( );
OUString sName = OUString( m_pEDServerName->GetText() ).trim( );
m_pBTOk->Enable( !sName.isEmpty( ) && !sUrl.isEmpty( ) );
return 1;
}
IMPL_LINK_NOARG( PlaceEditDialog, EditUsernameHdl )
{
for ( std::vector< std::shared_ptr< DetailsContainer > >::iterator it = m_aDetailsContainers.begin( );
it != m_aDetailsContainers.end( ); ++it )
{
( *it )->setUsername( OUString( m_pEDUsername->GetText() ) );
}
EditHdl(NULL);
return 1;
}
IMPL_LINK_NOARG( PlaceEditDialog, SelectTypeHdl )
{
if (m_xCurrentDetails.get())
m_xCurrentDetails->show(false);
sal_uInt16 nPos = m_pLBServerType->GetSelectEntryPos( );
m_xCurrentDetails = m_aDetailsContainers[nPos];
m_xCurrentDetails->show(true);
SetSizePixel(GetOptimalSize());
return 0;
}
/* vim:set shiftwidth=4 softtabstop=4 expandtab: */
|
/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
/*
* This file is part of the LibreOffice project.
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/.
*/
#include <svtools/PlaceEditDialog.hxx>
#include <svtools/ServerDetailsControls.hxx>
#include <com/sun/star/uno/Sequence.hxx>
#include <officecfg/Office/Common.hxx>
#include <svtools/svtresid.hxx>
#include <vcl/msgbox.hxx>
using namespace com::sun::star::uno;
PlaceEditDialog::PlaceEditDialog(vcl::Window* pParent)
: ModalDialog(pParent, "PlaceEditDialog", "svt/ui/placeedit.ui")
, m_xCurrentDetails()
{
get( m_pEDServerName, "name" );
get( m_pLBServerType, "type" );
get( m_pEDUsername, "login" );
get( m_pBTOk, "ok" );
get( m_pBTCancel, "cancel" );
get( m_pBTDelete, "delete" );
get( m_pBTRepoRefresh, "repositoriesRefresh" );
m_pBTOk->SetClickHdl( LINK( this, PlaceEditDialog, OKHdl) );
m_pBTOk->Enable( false );
m_pEDServerName->SetModifyHdl( LINK( this, PlaceEditDialog, EditHdl) );
// This constructor is called when user request a place creation, so
// delete button is hidden.
m_pBTDelete->Hide();
m_pLBServerType->SetSelectHdl( LINK( this, PlaceEditDialog, SelectTypeHdl ) );
m_pEDUsername->SetModifyHdl( LINK( this, PlaceEditDialog, EditUsernameHdl ) );
InitDetails( );
}
PlaceEditDialog::PlaceEditDialog(vcl::Window* pParent, const std::shared_ptr<Place>& rPlace)
: ModalDialog(pParent, "PlaceEditDialog", "svt/ui/placeedit.ui")
, m_xCurrentDetails( )
{
get( m_pEDServerName, "name" );
get( m_pLBServerType, "type" );
get( m_pEDUsername, "login" );
get( m_pBTOk, "ok" );
get( m_pBTCancel, "cancel" );
get( m_pBTDelete, "delete" );
get( m_pTypeGrid, "TypeGrid" );
m_pBTOk->SetClickHdl( LINK( this, PlaceEditDialog, OKHdl) );
m_pBTDelete->SetClickHdl ( LINK( this, PlaceEditDialog, DelHdl) );
m_pEDServerName->SetModifyHdl( LINK( this, PlaceEditDialog, EditHdl) );
m_pLBServerType->SetSelectHdl( LINK( this, PlaceEditDialog, SelectTypeHdl ) );
InitDetails( );
m_pEDServerName->SetText(rPlace->GetName());
// Fill the boxes with the URL parts
bool bSuccess = false;
for (size_t i = 0 ; i < m_aDetailsContainers.size( ) && !bSuccess; ++i)
{
INetURLObject& rUrl = rPlace->GetUrlObject();
bSuccess = m_aDetailsContainers[i]->setUrl( rUrl );
if ( bSuccess )
{
m_pLBServerType->SelectEntryPos( i );
SelectTypeHdl( m_pLBServerType );
// Fill the Username field
if ( rUrl.HasUserData( ) )
m_pEDUsername->SetText( INetURLObject::decode( rUrl.GetUser( ),
INetURLObject::DECODE_WITH_CHARSET ) );
}
}
// In edit mode user can't change connection type
m_pTypeGrid->Hide();
}
PlaceEditDialog::~PlaceEditDialog()
{
disposeOnce();
}
void PlaceEditDialog::dispose()
{
m_pEDServerName.clear();
m_pLBServerType.clear();
m_pEDUsername.clear();
m_pBTOk.clear();
m_pBTCancel.clear();
m_pBTDelete.clear();
ModalDialog::dispose();
}
OUString PlaceEditDialog::GetServerUrl()
{
OUString sUrl;
if (m_xCurrentDetails.get())
{
INetURLObject aUrl = m_xCurrentDetails->getUrl();
OUString sUsername = OUString( m_pEDUsername->GetText( ) ).trim( );
if ( !sUsername.isEmpty( ) )
aUrl.SetUser( sUsername );
if ( !aUrl.HasError( ) )
sUrl = aUrl.GetMainURL( INetURLObject::NO_DECODE );
}
return sUrl;
}
std::shared_ptr<Place> PlaceEditDialog::GetPlace()
{
return std::make_shared<Place>(m_pEDServerName->GetText(), GetServerUrl(), true);
}
void PlaceEditDialog::InitDetails( )
{
// Create CMIS controls for each server type
Reference< XComponentContext > xContext = ::comphelper::getProcessComponentContext();
// Load the ServerType entries
bool bSkipGDrive = OUString( GDRIVE_CLIENT_ID ).isEmpty() ||
OUString( GDRIVE_CLIENT_SECRET ).isEmpty();
bool bSkipAlfresco = OUString( ALFRESCO_CLOUD_CLIENT_ID ).isEmpty() ||
OUString( ALFRESCO_CLOUD_CLIENT_SECRET ).isEmpty();
bool bSkipOneDrive= OUString( ONEDRIVE_CLIENT_ID ).isEmpty() ||
OUString( ONEDRIVE_CLIENT_SECRET ).isEmpty();
Sequence< OUString > aTypesUrlsList( officecfg::Office::Common::Misc::CmisServersUrls::get( xContext ) );
Sequence< OUString > aTypesNamesList( officecfg::Office::Common::Misc::CmisServersNames::get( xContext ) );
unsigned int nPos = 0;
for ( sal_Int32 i = 0; i < aTypesUrlsList.getLength( ) && aTypesNamesList.getLength( ); ++i )
{
OUString sUrl = aTypesUrlsList[i];
if ( !( sUrl == GDRIVE_BASE_URL && bSkipGDrive ) &&
!( sUrl.startsWith( ALFRESCO_CLOUD_BASE_URL ) && bSkipAlfresco ) &&
!( sUrl == ONEDRIVE_BASE_URL && bSkipOneDrive ) )
{
nPos = m_pLBServerType->InsertEntry( aTypesNamesList[i], nPos );
std::shared_ptr<DetailsContainer> xCmisDetails(std::make_shared<CmisDetailsContainer>(this, sUrl));
xCmisDetails->setChangeHdl( LINK( this, PlaceEditDialog, EditHdl ) );
m_aDetailsContainers.push_back(xCmisDetails);
nPos++;
}
}
// Create WebDAV / FTP / SSH details control
std::shared_ptr<DetailsContainer> xDavDetails(std::make_shared<DavDetailsContainer>(this));
xDavDetails->setChangeHdl( LINK( this, PlaceEditDialog, EditHdl ) );
m_aDetailsContainers.push_back(xDavDetails);
std::shared_ptr<DetailsContainer> xFtpDetails(std::make_shared<HostDetailsContainer>(this, 21, "ftp"));
xFtpDetails->setChangeHdl( LINK( this, PlaceEditDialog, EditHdl ) );
m_aDetailsContainers.push_back(xFtpDetails);
std::shared_ptr<DetailsContainer> xSshDetails(std::make_shared<HostDetailsContainer>(this, 22, "ssh"));
xSshDetails->setChangeHdl( LINK( this, PlaceEditDialog, EditHdl ) );
m_aDetailsContainers.push_back(xSshDetails);
// Create Windows Share control
std::shared_ptr<DetailsContainer> xSmbDetails(std::make_shared<SmbDetailsContainer>(this));
xSmbDetails->setChangeHdl( LINK( this, PlaceEditDialog, EditHdl ) );
m_aDetailsContainers.push_back(xSmbDetails);
// Set default to first value
m_pLBServerType->SelectEntryPos( 0 );
SelectTypeHdl( m_pLBServerType );
}
IMPL_LINK ( PlaceEditDialog, OKHdl, Button *, )
{
if ( m_xCurrentDetails.get() )
{
OUString sUrl = m_xCurrentDetails->getUrl().GetHost( INetURLObject::DECODE_WITH_CHARSET );
OUString sGDriveHost( GDRIVE_BASE_URL );
OUString sAlfrescoHost( ALFRESCO_CLOUD_BASE_URL );
OUString sOneDriveHost( ONEDRIVE_BASE_URL );
if ( sUrl.compareTo( sGDriveHost, sGDriveHost.getLength() ) == 0
|| sUrl.compareTo( sAlfrescoHost, sAlfrescoHost.getLength() ) == 0
|| sUrl.compareTo( sOneDriveHost, sOneDriveHost.getLength() ) == 0 )
{
m_pBTRepoRefresh->Click();
sUrl = m_xCurrentDetails->getUrl().GetHost( INetURLObject::DECODE_WITH_CHARSET );
INetURLObject aHostUrl( sUrl );
OUString sRepoId = aHostUrl.GetMark();
if ( !sRepoId.isEmpty() )
{
EndDialog( RET_OK );
}
else
{
// TODO: repository id missing. Auth error?
}
}
else
{
EndDialog( RET_OK );
}
}
return 1;
}
IMPL_LINK ( PlaceEditDialog, DelHdl, Button *, )
{
// ReUsing existing symbols...
EndDialog( RET_NO );
return 1;
}
IMPL_LINK_NOARG( PlaceEditDialog, EditHdl )
{
OUString sUrl = GetServerUrl( );
OUString sName = OUString( m_pEDServerName->GetText() ).trim( );
m_pBTOk->Enable( !sName.isEmpty( ) && !sUrl.isEmpty( ) );
return 1;
}
IMPL_LINK_NOARG( PlaceEditDialog, EditUsernameHdl )
{
for ( std::vector< std::shared_ptr< DetailsContainer > >::iterator it = m_aDetailsContainers.begin( );
it != m_aDetailsContainers.end( ); ++it )
{
( *it )->setUsername( OUString( m_pEDUsername->GetText() ) );
}
EditHdl(NULL);
return 1;
}
IMPL_LINK_NOARG( PlaceEditDialog, SelectTypeHdl )
{
if (m_xCurrentDetails.get())
m_xCurrentDetails->show(false);
sal_uInt16 nPos = m_pLBServerType->GetSelectEntryPos( );
m_xCurrentDetails = m_aDetailsContainers[nPos];
m_xCurrentDetails->show(true);
SetSizePixel(GetOptimalSize());
EditHdl(NULL);
return 0;
}
/* vim:set shiftwidth=4 softtabstop=4 expandtab: */
|
Check if OK button should be enabled after changing service type
|
Check if OK button should be enabled after changing service type
Change-Id: I64ce981846f4107c8f38e413f1e6eb9e5616ef87
|
C++
|
mpl-2.0
|
JurassicWordExcel/core,JurassicWordExcel/core,JurassicWordExcel/core,JurassicWordExcel/core,JurassicWordExcel/core,JurassicWordExcel/core,JurassicWordExcel/core,JurassicWordExcel/core,JurassicWordExcel/core,JurassicWordExcel/core
|
77c607196f1c63d90208621804fd31c3dcfdb9ec
|
libs/csplugincommon/opengl/shaderplugin.cpp
|
libs/csplugincommon/opengl/shaderplugin.cpp
|
/*
Copyright (C) 2008 by Frank Richter
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Library General Public
License as published by the Free Software Foundation; either
version 2 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Library General Public License for more details.
You should have received a copy of the GNU Library General Public
License along with this library; if not, write to the Free
Software Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
*/
#include "cssysdef.h"
#include "csplugincommon/opengl/shaderplugin.h"
#include "csutil/objreg.h"
#include "csutil/stringarray.h"
#include "iutil/verbositymanager.h"
#include "ivideo/graph2d.h"
#if defined(CS_OPENGL_PATH)
#include CS_HEADER_GLOBAL(CS_OPENGL_PATH,gl.h)
#else
#include <GL/gl.h>
#endif
namespace CS
{
namespace PluginCommon
{
ShaderProgramPluginGL::ShaderProgramPluginGL (iBase* parent)
: scfImplementationType (this, parent), vendor (Invalid), isOpen (false),
object_reg (0), ext (0), doVerbose (false)
{
}
bool ShaderProgramPluginGL::Initialize (iObjectRegistry* objectReg)
{
object_reg = objectReg;
csRef<iVerbosityManager> verbosemgr (
csQueryRegistry<iVerbosityManager> (object_reg));
if (verbosemgr)
{
doVerbose = verbosemgr->Enabled ("renderer.shader");
doVerbosePrecache = verbosemgr->Enabled ("renderer.shader.precache");
}
else
doVerbose = doVerbosePrecache = false;
return true;
}
bool ShaderProgramPluginGL::Open()
{
if (isOpen) return true;
isOpen = true;
csRef<iGraphics3D> r = csQueryRegistry<iGraphics3D> (object_reg);
// Sanity check
csRef<iFactory> f = scfQueryInterfaceSafe<iFactory> (r);
if (f == 0 || strcmp ("crystalspace.graphics3d.opengl",
f->QueryClassID ()) != 0)
return false;
if (r) r->GetDriver2D()->PerformExtension ("getextmanager", &ext);
if (ext == 0)
return false;
csString vendorStr ((const char*)glGetString (GL_VENDOR));
vendorStr.Downcase();
if (vendorStr.FindFirst ("nvidia") != (size_t)-1)
{
vendor = NVIDIA;
}
else if ((vendorStr.FindFirst ("ati") != (size_t)-1)
|| (vendorStr.FindFirst ("amd") != (size_t)-1))
{
vendor = ATI;
}
else
{
vendor = Other;
}
clipPlanes.Initialize (object_reg);
return true;
}
void ShaderProgramPluginGL::Close ()
{
isOpen = false;
}
uint ShaderProgramPluginGL::ParseVendorMask (const char* maskStr)
{
uint mask = 0;
csStringArray maskSplit;
maskSplit.SplitString (maskStr, ",");
for (size_t i = 0; i < maskSplit.GetSize(); i++)
{
csString str = maskSplit[i];
if (str.IsEmpty()) continue;
bool doNegate = false;
if (str.GetAt(0) == '!')
{
doNegate = true;
str.DeleteAt (0, 1);
if ((i == 0) && (mask == 0)) mask = ~0;
}
if (str.IsEmpty()) continue;
uint thisMask = 0;
if (str == "*")
thisMask = ~0;
else if (str == "ati")
{
thisMask = 1 << ATI;
}
else if ((str == "nvidia") || (str == "nv"))
{
thisMask = 1 << NVIDIA;
}
else if (str == "other")
{
thisMask = 1 << Other;
}
if (doNegate)
mask &= ~thisMask;
else
mask |= thisMask;
}
return mask;
}
//-----------------------------------------------------------------------
ShaderProgramPluginGL::ClipPlanes::ClipPlanes () : currentPlanes (0)
{
}
ShaderProgramPluginGL::ClipPlanes::~ClipPlanes ()
{
}
void ShaderProgramPluginGL::ClipPlanes::Initialize (iObjectRegistry* objectReg)
{
GLint _maxClipPlanes;
glGetIntegerv (GL_MAX_CLIP_PLANES, &_maxClipPlanes);
maxPlanes = csMin (_maxClipPlanes, 6);
// @@@ Lots of places assume max 6 planes
csRef<iShaderVarStringSet> strings =
csQueryRegistryTagInterface<iShaderVarStringSet> (
objectReg, "crystalspace.shader.variablenameset");
svObjectToWorldInv = strings->Request ("object2world transform inverse");
svWorldToCamera = strings->Request ("world2camera transform");
}
void ShaderProgramPluginGL::ClipPlanes::SetShaderVars (const csShaderVariableStack& stack)
{
if (stack.GetSize() > svObjectToWorldInv)
{
csShaderVariable* sv = stack[svObjectToWorldInv];
if (sv) sv->GetValue (worldToObject);
}
if (stack.GetSize() > svWorldToCamera)
{
csShaderVariable* sv = stack[svWorldToCamera];
if (sv) sv->GetValue (worldToCam);
}
eyeToObjectDirty = true;
}
bool ShaderProgramPluginGL::ClipPlanes::AddClipPlane (const csPlane3& plane,
ClipSpace space)
{
size_t nextPlane;
if (!CS::Utility::BitOps::ScanBitForward (~currentPlanes, nextPlane))
return false;
if (nextPlane >= (size_t)maxPlanes) return false;
csPlane3 planeTF;
switch (space)
{
case Object:
planeTF = plane;
break;
case Eye:
{
if (eyeToObjectDirty)
{
eyeToObject = worldToCam.GetInverse() * worldToObject;
eyeToObjectDirty = false;
}
planeTF = eyeToObject.Other2This (plane);
}
break;
case World:
planeTF = worldToObject.Other2This (plane);
break;
}
glEnable (GL_CLIP_PLANE0 + nextPlane);
GLdouble glPlane[4] = { planeTF.A(), planeTF.B(), planeTF.C(), planeTF.D() };
glClipPlane (GL_CLIP_PLANE0 + nextPlane, glPlane);
currentPlanes |= 1 << nextPlane;
return true;
}
bool ShaderProgramPluginGL::ClipPlanes::EnableClipPlane (int n)
{
if (n >= maxPlanes) return false;
glEnable (GL_CLIP_PLANE0 + n);
currentPlanes |= 1 << n;
return true;
}
bool ShaderProgramPluginGL::ClipPlanes::EnableNextClipPlane ()
{
size_t nextPlane;
if (!CS::Utility::BitOps::ScanBitForward (~currentPlanes, nextPlane))
return false;
if (nextPlane >= (size_t)maxPlanes) return false;
glEnable (GL_CLIP_PLANE0 + nextPlane);
currentPlanes |= 1 << nextPlane;
return true;
}
void ShaderProgramPluginGL::ClipPlanes::DisableClipPlanes ()
{
for (int i = 0; i < maxPlanes; i++)
{
if (currentPlanes & (1 << i)) glDisable (GL_CLIP_PLANE0 + i);
}
currentPlanes = 0;
}
} // namespace PluginCommon
} // namespace CS
|
/*
Copyright (C) 2008 by Frank Richter
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Library General Public
License as published by the Free Software Foundation; either
version 2 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Library General Public License for more details.
You should have received a copy of the GNU Library General Public
License along with this library; if not, write to the Free
Software Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
*/
#include "cssysdef.h"
#include "csplugincommon/opengl/shaderplugin.h"
#include "csutil/objreg.h"
#include "csutil/stringarray.h"
#include "iutil/verbositymanager.h"
#include "ivideo/graph2d.h"
#if defined(CS_OPENGL_PATH)
#include CS_HEADER_GLOBAL(CS_OPENGL_PATH,gl.h)
#else
#include <GL/gl.h>
#endif
namespace CS
{
namespace PluginCommon
{
ShaderProgramPluginGL::ShaderProgramPluginGL (iBase* parent)
: scfImplementationType (this, parent), vendor (Invalid), isOpen (false),
object_reg (0), ext (0), doVerbose (false)
{
}
bool ShaderProgramPluginGL::Initialize (iObjectRegistry* objectReg)
{
object_reg = objectReg;
csRef<iVerbosityManager> verbosemgr (
csQueryRegistry<iVerbosityManager> (object_reg));
if (verbosemgr)
{
doVerbose = verbosemgr->Enabled ("renderer.shader");
doVerbosePrecache = verbosemgr->Enabled ("renderer.shader.precache");
}
else
doVerbose = doVerbosePrecache = false;
return true;
}
bool ShaderProgramPluginGL::Open()
{
if (isOpen) return true;
isOpen = true;
csRef<iGraphics3D> r = csQueryRegistry<iGraphics3D> (object_reg);
// Sanity check
csRef<iFactory> f = scfQueryInterfaceSafe<iFactory> (r);
if (f == 0 || strcmp ("crystalspace.graphics3d.opengl",
f->QueryClassID ()) != 0)
return false;
if (r) r->GetDriver2D()->PerformExtension ("getextmanager", &ext);
if (ext == 0)
return false;
csString vendorStr ((const char*)glGetString (GL_VENDOR));
vendorStr.Downcase();
if (vendorStr.FindStr ("nvidia") != (size_t)-1)
{
vendor = NVIDIA;
}
else if ((vendorStr.FindStr ("ati") != (size_t)-1)
|| (vendorStr.FindStr ("amd") != (size_t)-1))
{
vendor = ATI;
}
else
{
vendor = Other;
}
clipPlanes.Initialize (object_reg);
return true;
}
void ShaderProgramPluginGL::Close ()
{
isOpen = false;
}
uint ShaderProgramPluginGL::ParseVendorMask (const char* maskStr)
{
uint mask = 0;
csStringArray maskSplit;
maskSplit.SplitString (maskStr, ",");
for (size_t i = 0; i < maskSplit.GetSize(); i++)
{
csString str = maskSplit[i];
if (str.IsEmpty()) continue;
bool doNegate = false;
if (str.GetAt(0) == '!')
{
doNegate = true;
str.DeleteAt (0, 1);
if ((i == 0) && (mask == 0)) mask = ~0;
}
if (str.IsEmpty()) continue;
uint thisMask = 0;
if (str == "*")
thisMask = ~0;
else if (str == "ati")
{
thisMask = 1 << ATI;
}
else if ((str == "nvidia") || (str == "nv"))
{
thisMask = 1 << NVIDIA;
}
else if (str == "other")
{
thisMask = 1 << Other;
}
if (doNegate)
mask &= ~thisMask;
else
mask |= thisMask;
}
return mask;
}
//-----------------------------------------------------------------------
ShaderProgramPluginGL::ClipPlanes::ClipPlanes () : currentPlanes (0)
{
}
ShaderProgramPluginGL::ClipPlanes::~ClipPlanes ()
{
}
void ShaderProgramPluginGL::ClipPlanes::Initialize (iObjectRegistry* objectReg)
{
GLint _maxClipPlanes;
glGetIntegerv (GL_MAX_CLIP_PLANES, &_maxClipPlanes);
maxPlanes = csMin (_maxClipPlanes, 6);
// @@@ Lots of places assume max 6 planes
csRef<iShaderVarStringSet> strings =
csQueryRegistryTagInterface<iShaderVarStringSet> (
objectReg, "crystalspace.shader.variablenameset");
svObjectToWorldInv = strings->Request ("object2world transform inverse");
svWorldToCamera = strings->Request ("world2camera transform");
}
void ShaderProgramPluginGL::ClipPlanes::SetShaderVars (const csShaderVariableStack& stack)
{
if (stack.GetSize() > svObjectToWorldInv)
{
csShaderVariable* sv = stack[svObjectToWorldInv];
if (sv) sv->GetValue (worldToObject);
}
if (stack.GetSize() > svWorldToCamera)
{
csShaderVariable* sv = stack[svWorldToCamera];
if (sv) sv->GetValue (worldToCam);
}
eyeToObjectDirty = true;
}
bool ShaderProgramPluginGL::ClipPlanes::AddClipPlane (const csPlane3& plane,
ClipSpace space)
{
size_t nextPlane;
if (!CS::Utility::BitOps::ScanBitForward (~currentPlanes, nextPlane))
return false;
if (nextPlane >= (size_t)maxPlanes) return false;
csPlane3 planeTF;
switch (space)
{
case Object:
planeTF = plane;
break;
case Eye:
{
if (eyeToObjectDirty)
{
eyeToObject = worldToCam.GetInverse() * worldToObject;
eyeToObjectDirty = false;
}
planeTF = eyeToObject.Other2This (plane);
}
break;
case World:
planeTF = worldToObject.Other2This (plane);
break;
}
glEnable (GL_CLIP_PLANE0 + nextPlane);
GLdouble glPlane[4] = { planeTF.A(), planeTF.B(), planeTF.C(), planeTF.D() };
glClipPlane (GL_CLIP_PLANE0 + nextPlane, glPlane);
currentPlanes |= 1 << nextPlane;
return true;
}
bool ShaderProgramPluginGL::ClipPlanes::EnableClipPlane (int n)
{
if (n >= maxPlanes) return false;
glEnable (GL_CLIP_PLANE0 + n);
currentPlanes |= 1 << n;
return true;
}
bool ShaderProgramPluginGL::ClipPlanes::EnableNextClipPlane ()
{
size_t nextPlane;
if (!CS::Utility::BitOps::ScanBitForward (~currentPlanes, nextPlane))
return false;
if (nextPlane >= (size_t)maxPlanes) return false;
glEnable (GL_CLIP_PLANE0 + nextPlane);
currentPlanes |= 1 << nextPlane;
return true;
}
void ShaderProgramPluginGL::ClipPlanes::DisableClipPlanes ()
{
for (int i = 0; i < maxPlanes; i++)
{
if (currentPlanes & (1 << i)) glDisable (GL_CLIP_PLANE0 + i);
}
currentPlanes = 0;
}
} // namespace PluginCommon
} // namespace CS
|
Fix vendor detection in GL shader plugin common code
|
Fix vendor detection in GL shader plugin common code
git-svn-id: 28d9401aa571d5108e51b194aae6f24ca5964c06@30398 8cc4aa7f-3514-0410-904f-f2cc9021211c
|
C++
|
lgpl-2.1
|
crystalspace/CS,crystalspace/CS,crystalspace/CS,crystalspace/CS,crystalspace/CS,crystalspace/CS,crystalspace/CS,crystalspace/CS
|
1d5e091602c3e994740f5d13204ee5cdf4682b64
|
liboh/include/sirikata/oh/ObjectHost.hpp
|
liboh/include/sirikata/oh/ObjectHost.hpp
|
/* Sirikata liboh -- Object Host
* ObjectHost.hpp
*
* Copyright (c) 2009, Ewen Cheslack-Postava
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are
* met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
* * Neither the name of Sirikata 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.
*/
#ifndef _SIRIKATA_OBJECT_HOST_HPP_
#define _SIRIKATA_OBJECT_HOST_HPP_
#include <sirikata/oh/Platform.hpp>
#include <sirikata/core/util/MessageService.hpp>
#include <sirikata/core/util/SpaceObjectReference.hpp>
#include <sirikata/core/network/Address.hpp>
namespace Sirikata {
class ProxyManager;
class PluginManager;
class SpaceIDMap;
class TopLevelSpaceConnection;
class SpaceConnection;
class ConnectionEventListener;
class ObjectScriptManager;
namespace Task {
class WorkQueue;
}
class HostedObject;
typedef std::tr1::weak_ptr<HostedObject> HostedObjectWPtr;
typedef std::tr1::shared_ptr<HostedObject> HostedObjectPtr;
typedef Provider< ConnectionEventListener* > ConnectionEventProvider;
class SIRIKATA_OH_EXPORT ObjectHost : public MessageService, public ConnectionEventProvider {
SpaceIDMap *mSpaceIDMap;
typedef std::tr1::unordered_multimap<SpaceID,std::tr1::weak_ptr<TopLevelSpaceConnection>,SpaceID::Hasher> SpaceConnectionMap;
typedef std::tr1::unordered_map<Network::Address,std::tr1::weak_ptr<TopLevelSpaceConnection>,Network::Address::Hasher> AddressConnectionMap;
typedef std::tr1::unordered_map<UUID, HostedObjectPtr, UUID::Hasher> HostedObjectMap;
typedef std::map<MessagePort, MessageService *> ServicesMap;
SpaceConnectionMap mSpaceConnections;
AddressConnectionMap mAddressConnections;
friend class TopLevelSpaceConnection;
void insertAddressMapping(const Network::Address&, const std::tr1::weak_ptr<TopLevelSpaceConnection>&);
void removeTopLevelSpaceConnection(const SpaceID&, const Network::Address&, const TopLevelSpaceConnection*);
Network::IOService *mSpaceConnectionIO;
Task::WorkQueue *volatile mMessageQueue;
struct AtomicInt;
AtomicInt *mEnqueuers;
HostedObjectMap mHostedObjects;
ServicesMap mServices;
PluginManager *mScriptPlugins;
std::tr1::unordered_map<String,OptionSet*> mSpaceConnectionProtocolOptions;
public:
/** Caller is responsible for starting a thread
*
* @param spaceIDMap space ID map used to resolve space IDs to servers
* @param messageQueue a work queue to run this object host on
* @param ioServ IOService to run this object host on
* @param options a string containing the options to pass to the object host
*/
ObjectHost(SpaceIDMap *spaceIDMap, Task::WorkQueue *messageQueue, Network::IOService*ioServ, const String&options);
/// The ObjectHost must be destroyed after all HostedObject instances.
~ObjectHost();
///ObjectHost does not forward messages to other services, only to objects it owns
bool forwardMessagesTo(MessageService*){ assert(false); return false;}
///ObjectHost does not forward messages to other services, only to objects it owns
bool endForwardingMessagesTo(MessageService*){ assert(false); return false;}
/** Register a global space-like service for null Space, null Object.
@param port The service port number (i.e. Services::PERSISTENCE)
@param serv MessageService* -- make sure to unregister before deleting.
*/
void registerService(MessagePort port, MessageService *serv) {
mServices.insert(ServicesMap::value_type(port, serv));
serv->forwardMessagesTo(this);
}
/// Unregister a global service. Unnecessary if you delete the ObjectHost first.
void unregisterService(MessagePort port) {
ServicesMap::iterator iter = mServices.find(port);
if (iter != mServices.end()) {
iter->second->endForwardingMessagesTo(this);
mServices.erase(iter);
}
}
/// Lookup a global service by port number.
MessageService *getService(MessagePort port) const {
ServicesMap::const_iterator iter = mServices.find(port);
if (iter != mServices.end()) {
return iter->second;
}
return NULL;
}
const Duration&getSpaceTimeOffset(const SpaceID&)const;
const Duration&getSpaceTimeOffset(const Network::Address&)const;
/** Register object by private UUID, so that it is possible to
talk to objects/services which are not part of any space.
Done automatically by HostedObject::initialize* functions.
*/
void registerHostedObject(const HostedObjectPtr &obj);
/// Unregister a private UUID. Done automatically by ~HostedObject.
void unregisterHostedObject(const UUID &objID);
/** Lookup HostedObject by private UUID. */
HostedObjectPtr getHostedObject(const UUID &id) const;
/// Returns the SpaceID -> Network::Address lookup map.
SpaceIDMap*spaceIDMap(){return mSpaceIDMap;}
class MessageProcessor;
///This method checks if the message is destined for any named mServices. If not, it gives it to mRouter
void processMessage(const RoutableMessageHeader&header,
MemoryReference message_body);
/// @see connectToSpaceAddress. Looks up the space in the spaceIDMap().
std::tr1::shared_ptr<TopLevelSpaceConnection> connectToSpace(const SpaceID& space);
///immediately returns a usable stream for the spaceID. The stream may or may not connect successfully, but will allow queueing messages. The stream will be deallocated if the return value is discarded. In most cases, this should not be called directly.
std::tr1::shared_ptr<TopLevelSpaceConnection> connectToSpaceAddress(const SpaceID&, const Network::Address&);
void tick();
PluginManager *getScriptPluginManager(){return mScriptPlugins;}
/** Gets an IO service corresponding to this object host.
This can be used to schedule timeouts that are guaranteed
to be in the correct thread. */
Network::IOService *getSpaceIO() const {
return mSpaceConnectionIO;
}
/** May return null if this object host is in the process of being destructed. */
Task::WorkQueue *getWorkQueue() const {
return mMessageQueue;
}
/** Process pending messages immediately. Only call if you are currently in the main thread. */
void dequeueAll() const;
/// Looks up a TopLevelSpaceConnection corresponding to a certain space.
ProxyManager *getProxyManager(const SpaceID&space) const;
}; // class ObjectHost
} // namespace Sirikata
#endif //_SIRIKATA_OBJECT_HOST_HPP
|
/* Sirikata liboh -- Object Host
* ObjectHost.hpp
*
* Copyright (c) 2009, Ewen Cheslack-Postava
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are
* met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
* * Neither the name of Sirikata 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.
*/
#ifndef _SIRIKATA_OBJECT_HOST_HPP_
#define _SIRIKATA_OBJECT_HOST_HPP_
#include <sirikata/oh/Platform.hpp>
#include <sirikata/core/util/MessageService.hpp>
#include <sirikata/core/util/SpaceObjectReference.hpp>
#include <sirikata/core/network/Address.hpp>
#include <sirikata/core/util/ListenerProvider.hpp>
namespace Sirikata {
class ProxyManager;
class PluginManager;
class SpaceIDMap;
class TopLevelSpaceConnection;
class SpaceConnection;
class ConnectionEventListener;
class ObjectScriptManager;
namespace Task {
class WorkQueue;
}
class HostedObject;
typedef std::tr1::weak_ptr<HostedObject> HostedObjectWPtr;
typedef std::tr1::shared_ptr<HostedObject> HostedObjectPtr;
typedef Provider< ConnectionEventListener* > ConnectionEventProvider;
class SIRIKATA_OH_EXPORT ObjectHost : public MessageService, public ConnectionEventProvider {
SpaceIDMap *mSpaceIDMap;
typedef std::tr1::unordered_multimap<SpaceID,std::tr1::weak_ptr<TopLevelSpaceConnection>,SpaceID::Hasher> SpaceConnectionMap;
typedef std::tr1::unordered_map<Network::Address,std::tr1::weak_ptr<TopLevelSpaceConnection>,Network::Address::Hasher> AddressConnectionMap;
typedef std::tr1::unordered_map<UUID, HostedObjectPtr, UUID::Hasher> HostedObjectMap;
typedef std::map<MessagePort, MessageService *> ServicesMap;
SpaceConnectionMap mSpaceConnections;
AddressConnectionMap mAddressConnections;
friend class TopLevelSpaceConnection;
void insertAddressMapping(const Network::Address&, const std::tr1::weak_ptr<TopLevelSpaceConnection>&);
void removeTopLevelSpaceConnection(const SpaceID&, const Network::Address&, const TopLevelSpaceConnection*);
Network::IOService *mSpaceConnectionIO;
Task::WorkQueue *volatile mMessageQueue;
struct AtomicInt;
AtomicInt *mEnqueuers;
HostedObjectMap mHostedObjects;
ServicesMap mServices;
PluginManager *mScriptPlugins;
std::tr1::unordered_map<String,OptionSet*> mSpaceConnectionProtocolOptions;
public:
/** Caller is responsible for starting a thread
*
* @param spaceIDMap space ID map used to resolve space IDs to servers
* @param messageQueue a work queue to run this object host on
* @param ioServ IOService to run this object host on
* @param options a string containing the options to pass to the object host
*/
ObjectHost(SpaceIDMap *spaceIDMap, Task::WorkQueue *messageQueue, Network::IOService*ioServ, const String&options);
/// The ObjectHost must be destroyed after all HostedObject instances.
~ObjectHost();
///ObjectHost does not forward messages to other services, only to objects it owns
bool forwardMessagesTo(MessageService*){ assert(false); return false;}
///ObjectHost does not forward messages to other services, only to objects it owns
bool endForwardingMessagesTo(MessageService*){ assert(false); return false;}
/** Register a global space-like service for null Space, null Object.
@param port The service port number (i.e. Services::PERSISTENCE)
@param serv MessageService* -- make sure to unregister before deleting.
*/
void registerService(MessagePort port, MessageService *serv) {
mServices.insert(ServicesMap::value_type(port, serv));
serv->forwardMessagesTo(this);
}
/// Unregister a global service. Unnecessary if you delete the ObjectHost first.
void unregisterService(MessagePort port) {
ServicesMap::iterator iter = mServices.find(port);
if (iter != mServices.end()) {
iter->second->endForwardingMessagesTo(this);
mServices.erase(iter);
}
}
/// Lookup a global service by port number.
MessageService *getService(MessagePort port) const {
ServicesMap::const_iterator iter = mServices.find(port);
if (iter != mServices.end()) {
return iter->second;
}
return NULL;
}
const Duration&getSpaceTimeOffset(const SpaceID&)const;
const Duration&getSpaceTimeOffset(const Network::Address&)const;
/** Register object by private UUID, so that it is possible to
talk to objects/services which are not part of any space.
Done automatically by HostedObject::initialize* functions.
*/
void registerHostedObject(const HostedObjectPtr &obj);
/// Unregister a private UUID. Done automatically by ~HostedObject.
void unregisterHostedObject(const UUID &objID);
/** Lookup HostedObject by private UUID. */
HostedObjectPtr getHostedObject(const UUID &id) const;
/// Returns the SpaceID -> Network::Address lookup map.
SpaceIDMap*spaceIDMap(){return mSpaceIDMap;}
class MessageProcessor;
///This method checks if the message is destined for any named mServices. If not, it gives it to mRouter
void processMessage(const RoutableMessageHeader&header,
MemoryReference message_body);
/// @see connectToSpaceAddress. Looks up the space in the spaceIDMap().
std::tr1::shared_ptr<TopLevelSpaceConnection> connectToSpace(const SpaceID& space);
///immediately returns a usable stream for the spaceID. The stream may or may not connect successfully, but will allow queueing messages. The stream will be deallocated if the return value is discarded. In most cases, this should not be called directly.
std::tr1::shared_ptr<TopLevelSpaceConnection> connectToSpaceAddress(const SpaceID&, const Network::Address&);
void tick();
PluginManager *getScriptPluginManager(){return mScriptPlugins;}
/** Gets an IO service corresponding to this object host.
This can be used to schedule timeouts that are guaranteed
to be in the correct thread. */
Network::IOService *getSpaceIO() const {
return mSpaceConnectionIO;
}
/** May return null if this object host is in the process of being destructed. */
Task::WorkQueue *getWorkQueue() const {
return mMessageQueue;
}
/** Process pending messages immediately. Only call if you are currently in the main thread. */
void dequeueAll() const;
/// Looks up a TopLevelSpaceConnection corresponding to a certain space.
ProxyManager *getProxyManager(const SpaceID&space) const;
}; // class ObjectHost
} // namespace Sirikata
#endif //_SIRIKATA_OBJECT_HOST_HPP
|
Include ListenerProvider in ObjectHost since it uses Provider.
|
Include ListenerProvider in ObjectHost since it uses Provider.
|
C++
|
bsd-3-clause
|
sirikata/sirikata,sirikata/sirikata,sirikata/sirikata,sirikata/sirikata,sirikata/sirikata,sirikata/sirikata,sirikata/sirikata,sirikata/sirikata
|
3df767497f3f294c721835eeda1a1a451b95c17c
|
include/Struct.hpp
|
include/Struct.hpp
|
//=======================================================================
// Copyright Baptiste Wicht 2011.
// Distributed under the Boost Software License, Version 1.0.
// (See accompanying file LICENSE_1_0.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt)
//=======================================================================
#ifndef STRUCT_H
#define STRUCT_H
#include <memory>
#include <string>
#include <vector>
#include "Types.hpp"
namespace eddic {
/*!
* \class Member
* \brief A member of a struct.
*/
struct Member {
std::string name;
Type type;
Member(const std::string& n, Type t);
void add_reference();
unsigned int get_references();
private:
unsigned int references = 0;
};
/*!
* \class Struct
* \brief A structure entry in the function table.
*/
struct Struct {
std::string name;
std::vector<std::shared_ptr<Member>> members;
Struct(const std::string& n);
bool member_exists(const std::string& n);
std::shared_ptr<Member> operator[](const std::string& n);
void add_reference();
unsigned int get_references();
private:
unsigned int references = 0;
};
} //end of eddic
#endif
|
//=======================================================================
// Copyright Baptiste Wicht 2011.
// Distributed under the Boost Software License, Version 1.0.
// (See accompanying file LICENSE_1_0.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt)
//=======================================================================
#ifndef STRUCT_H
#define STRUCT_H
#include <memory>
#include <string>
#include <vector>
#include "Types.hpp"
namespace eddic {
/*!
* \class Member
* \brief A member of a struct.
*/
struct Member {
std::string name;
Type type;
Member(const std::string& n, Type t);
/*!
* Increment the reference counter of the member.
*/
void add_reference();
/*!
* Return the reference counter of the member.
* \return The reference counter of the member.
*/
unsigned int get_references();
private:
unsigned int references = 0;
};
/*!
* \class Struct
* \brief A structure entry in the function table.
*/
struct Struct {
std::string name;
std::vector<std::shared_ptr<Member>> members;
Struct(const std::string& n);
/*!
* Indicates if the specified member exists in this structure.
* \param name The name of the member to search for.
* \return true if the member exists, otherwise false.
*/
bool member_exists(const std::string& name);
/*!
* Return the member with the specified name.
* \param name The name of the member to search for.
* \return A pointer to the member with the given name.
*/
std::shared_ptr<Member> operator[](const std::string& name);
/*!
* Increment the reference counter of the structure.
*/
void add_reference();
/*!
* Return the reference counter of the member.
* \return The reference counter of the member.
*/
unsigned int get_references();
private:
unsigned int references = 0;
};
} //end of eddic
#endif
|
Complete Doxygen
|
Complete Doxygen
|
C++
|
mit
|
wichtounet/eddic,vogelsgesang/eddic,wichtounet/eddic,wichtounet/eddic,vogelsgesang/eddic,vogelsgesang/eddic
|
2aea49b8e620f8a81d217b37ca626bfeca44c9d8
|
src/crypter.cpp
|
src/crypter.cpp
|
// Copyright (c) 2009-2013 The Bitcoin developers
// Distributed under the MIT/X11 software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include "crypter.h"
#include "script.h"
#include <string>
#include <vector>
#include <boost/foreach.hpp>
#include <openssl/aes.h>
#include <openssl/evp.h>
bool CCrypter::SetKeyFromPassphrase(const SecureString& strKeyData, const std::vector<unsigned char>& chSalt, const unsigned int nRounds, const unsigned int nDerivationMethod)
{
if (nRounds < 1 || chSalt.size() != WALLET_CRYPTO_SALT_SIZE)
return false;
int i = 0;
if (nDerivationMethod == 0)
i = EVP_BytesToKey(EVP_aes_256_cbc(), EVP_sha512(), &chSalt[0],
(unsigned char *)&strKeyData[0], strKeyData.size(), nRounds, chKey, chIV);
if (i != (int)WALLET_CRYPTO_KEY_SIZE)
{
OPENSSL_cleanse(chKey, sizeof(chKey));
OPENSSL_cleanse(chIV, sizeof(chIV));
return false;
}
fKeySet = true;
return true;
}
bool CCrypter::SetKey(const CKeyingMaterial& chNewKey, const std::vector<unsigned char>& chNewIV)
{
if (chNewKey.size() != WALLET_CRYPTO_KEY_SIZE || chNewIV.size() != WALLET_CRYPTO_KEY_SIZE)
return false;
memcpy(&chKey[0], &chNewKey[0], sizeof chKey);
memcpy(&chIV[0], &chNewIV[0], sizeof chIV);
fKeySet = true;
return true;
}
bool CCrypter::Encrypt(const CKeyingMaterial& vchPlaintext, std::vector<unsigned char> &vchCiphertext)
{
if (!fKeySet)
return false;
// max ciphertext len for a n bytes of plaintext is
// n + AES_BLOCK_SIZE - 1 bytes
int nLen = vchPlaintext.size();
int nCLen = nLen + AES_BLOCK_SIZE, nFLen = 0;
vchCiphertext = std::vector<unsigned char> (nCLen);
EVP_CIPHER_CTX ctx;
bool fOk = true;
EVP_CIPHER_CTX_init(&ctx);
if (fOk) fOk = EVP_EncryptInit_ex(&ctx, EVP_aes_256_cbc(), NULL, chKey, chIV);
if (fOk) fOk = EVP_EncryptUpdate(&ctx, &vchCiphertext[0], &nCLen, &vchPlaintext[0], nLen);
if (fOk) fOk = EVP_EncryptFinal_ex(&ctx, (&vchCiphertext[0])+nCLen, &nFLen);
EVP_CIPHER_CTX_cleanup(&ctx);
if (!fOk) return false;
vchCiphertext.resize(nCLen + nFLen);
return true;
}
bool CCrypter::Decrypt(const std::vector<unsigned char>& vchCiphertext, CKeyingMaterial& vchPlaintext)
{
if (!fKeySet)
return false;
// plaintext will always be equal to or lesser than length of ciphertext
int nLen = vchCiphertext.size();
int nPLen = nLen, nFLen = 0;
vchPlaintext = CKeyingMaterial(nPLen);
EVP_CIPHER_CTX ctx;
bool fOk = true;
EVP_CIPHER_CTX_init(&ctx);
if (fOk) fOk = EVP_DecryptInit_ex(&ctx, EVP_aes_256_cbc(), NULL, chKey, chIV);
if (fOk) fOk = EVP_DecryptUpdate(&ctx, &vchPlaintext[0], &nPLen, &vchCiphertext[0], nLen);
if (fOk) fOk = EVP_DecryptFinal_ex(&ctx, (&vchPlaintext[0])+nPLen, &nFLen);
EVP_CIPHER_CTX_cleanup(&ctx);
if (!fOk) return false;
vchPlaintext.resize(nPLen + nFLen);
return true;
}
bool EncryptSecret(const CKeyingMaterial& vMasterKey, const CKeyingMaterial &vchPlaintext, const uint256& nIV, std::vector<unsigned char> &vchCiphertext)
{
CCrypter cKeyCrypter;
std::vector<unsigned char> chIV(WALLET_CRYPTO_KEY_SIZE);
memcpy(&chIV[0], &nIV, WALLET_CRYPTO_KEY_SIZE);
if(!cKeyCrypter.SetKey(vMasterKey, chIV))
return false;
return cKeyCrypter.Encrypt(*((const CKeyingMaterial*)&vchPlaintext), vchCiphertext);
}
bool DecryptSecret(const CKeyingMaterial& vMasterKey, const std::vector<unsigned char>& vchCiphertext, const uint256& nIV, CKeyingMaterial& vchPlaintext)
{
CCrypter cKeyCrypter;
std::vector<unsigned char> chIV(WALLET_CRYPTO_KEY_SIZE);
memcpy(&chIV[0], &nIV, WALLET_CRYPTO_KEY_SIZE);
if(!cKeyCrypter.SetKey(vMasterKey, chIV))
return false;
return cKeyCrypter.Decrypt(vchCiphertext, *((CKeyingMaterial*)&vchPlaintext));
}
bool CCryptoKeyStore::SetCrypted()
{
LOCK(cs_KeyStore);
if (fUseCrypto)
return true;
if (!mapKeys.empty())
return false;
fUseCrypto = true;
return true;
}
bool CCryptoKeyStore::Lock()
{
if (!SetCrypted())
return false;
{
LOCK(cs_KeyStore);
vMasterKey.clear();
}
NotifyStatusChanged(this);
return true;
}
bool CCryptoKeyStore::Unlock(const CKeyingMaterial& vMasterKeyIn)
{
{
LOCK(cs_KeyStore);
if (!SetCrypted())
return false;
CryptedKeyMap::const_iterator mi = mapCryptedKeys.begin();
for (; mi != mapCryptedKeys.end(); ++mi)
{
const CPubKey &vchPubKey = (*mi).second.first;
const std::vector<unsigned char> &vchCryptedSecret = (*mi).second.second;
CKeyingMaterial vchSecret;
if(!DecryptSecret(vMasterKeyIn, vchCryptedSecret, vchPubKey.GetHash(), vchSecret))
return false;
if (vchSecret.size() != 32)
return false;
CKey key;
key.Set(vchSecret.begin(), vchSecret.end(), vchPubKey.IsCompressed());
if (key.GetPubKey() == vchPubKey)
break;
return false;
}
vMasterKey = vMasterKeyIn;
}
NotifyStatusChanged(this);
return true;
}
bool CCryptoKeyStore::AddKeyPubKey(const CKey& key, const CPubKey &pubkey)
{
{
LOCK(cs_KeyStore);
if (!IsCrypted())
return CBasicKeyStore::AddKeyPubKey(key, pubkey);
if (IsLocked())
return false;
std::vector<unsigned char> vchCryptedSecret;
CKeyingMaterial vchSecret(key.begin(), key.end());
if (!EncryptSecret(vMasterKey, vchSecret, pubkey.GetHash(), vchCryptedSecret))
return false;
if (!AddCryptedKey(pubkey, vchCryptedSecret))
return false;
}
return true;
}
bool CCryptoKeyStore::AddCryptedKey(const CPubKey &vchPubKey, const std::vector<unsigned char> &vchCryptedSecret)
{
{
LOCK(cs_KeyStore);
if (!SetCrypted())
return false;
mapCryptedKeys[vchPubKey.GetID()] = make_pair(vchPubKey, vchCryptedSecret);
}
return true;
}
bool CCryptoKeyStore::GetKey(const CKeyID &address, CKey& keyOut) const
{
{
LOCK(cs_KeyStore);
if (!IsCrypted())
return CBasicKeyStore::GetKey(address, keyOut);
CryptedKeyMap::const_iterator mi = mapCryptedKeys.find(address);
if (mi != mapCryptedKeys.end())
{
const CPubKey &vchPubKey = (*mi).second.first;
const std::vector<unsigned char> &vchCryptedSecret = (*mi).second.second;
CKeyingMaterial vchSecret;
if (!DecryptSecret(vMasterKey, vchCryptedSecret, vchPubKey.GetHash(), vchSecret))
return false;
if (vchSecret.size() != 32)
return false;
keyOut.Set(vchSecret.begin(), vchSecret.end(), vchPubKey.IsCompressed());
return true;
}
}
return false;
}
bool CCryptoKeyStore::GetPubKey(const CKeyID &address, CPubKey& vchPubKeyOut) const
{
{
LOCK(cs_KeyStore);
if (!IsCrypted())
return CKeyStore::GetPubKey(address, vchPubKeyOut);
CryptedKeyMap::const_iterator mi = mapCryptedKeys.find(address);
if (mi != mapCryptedKeys.end())
{
vchPubKeyOut = (*mi).second.first;
return true;
}
}
return false;
}
bool CCryptoKeyStore::EncryptKeys(CKeyingMaterial& vMasterKeyIn)
{
{
LOCK(cs_KeyStore);
if (!mapCryptedKeys.empty() || IsCrypted())
return false;
fUseCrypto = true;
BOOST_FOREACH(KeyMap::value_type& mKey, mapKeys)
{
const CKey &key = mKey.second;
CPubKey vchPubKey = key.GetPubKey();
CKeyingMaterial vchSecret(key.begin(), key.end());
std::vector<unsigned char> vchCryptedSecret;
if (!EncryptSecret(vMasterKeyIn, vchSecret, vchPubKey.GetHash(), vchCryptedSecret))
return false;
if (!AddCryptedKey(vchPubKey, vchCryptedSecret))
return false;
}
mapKeys.clear();
}
return true;
}
|
// Copyright (c) 2009-2013 The Bitcoin developers
// Distributed under the MIT/X11 software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include "crypter.h"
#include "script.h"
#include <string>
#include <vector>
#include <boost/foreach.hpp>
#include <openssl/aes.h>
#include <openssl/evp.h>
bool CCrypter::SetKeyFromPassphrase(const SecureString& strKeyData, const std::vector<unsigned char>& chSalt, const unsigned int nRounds, const unsigned int nDerivationMethod)
{
if (nRounds < 1 || chSalt.size() != WALLET_CRYPTO_SALT_SIZE)
return false;
int i = 0;
if (nDerivationMethod == 0)
i = EVP_BytesToKey(EVP_aes_256_cbc(), EVP_sha512(), &chSalt[0],
(unsigned char *)&strKeyData[0], strKeyData.size(), nRounds, chKey, chIV);
if (i != (int)WALLET_CRYPTO_KEY_SIZE)
{
OPENSSL_cleanse(chKey, sizeof(chKey));
OPENSSL_cleanse(chIV, sizeof(chIV));
return false;
}
fKeySet = true;
return true;
}
bool CCrypter::SetKey(const CKeyingMaterial& chNewKey, const std::vector<unsigned char>& chNewIV)
{
if (chNewKey.size() != WALLET_CRYPTO_KEY_SIZE || chNewIV.size() != WALLET_CRYPTO_KEY_SIZE)
return false;
memcpy(&chKey[0], &chNewKey[0], sizeof chKey);
memcpy(&chIV[0], &chNewIV[0], sizeof chIV);
fKeySet = true;
return true;
}
bool CCrypter::Encrypt(const CKeyingMaterial& vchPlaintext, std::vector<unsigned char> &vchCiphertext)
{
if (!fKeySet)
return false;
// max ciphertext len for a n bytes of plaintext is
// n + AES_BLOCK_SIZE - 1 bytes
int nLen = vchPlaintext.size();
int nCLen = nLen + AES_BLOCK_SIZE, nFLen = 0;
vchCiphertext = std::vector<unsigned char> (nCLen);
EVP_CIPHER_CTX ctx;
bool fOk = true;
EVP_CIPHER_CTX_init(&ctx);
if (fOk) fOk = EVP_EncryptInit_ex(&ctx, EVP_aes_256_cbc(), NULL, chKey, chIV);
if (fOk) fOk = EVP_EncryptUpdate(&ctx, &vchCiphertext[0], &nCLen, &vchPlaintext[0], nLen);
if (fOk) fOk = EVP_EncryptFinal_ex(&ctx, (&vchCiphertext[0])+nCLen, &nFLen);
EVP_CIPHER_CTX_cleanup(&ctx);
if (!fOk) return false;
vchCiphertext.resize(nCLen + nFLen);
return true;
}
bool CCrypter::Decrypt(const std::vector<unsigned char>& vchCiphertext, CKeyingMaterial& vchPlaintext)
{
if (!fKeySet)
return false;
// plaintext will always be equal to or lesser than length of ciphertext
int nLen = vchCiphertext.size();
int nPLen = nLen, nFLen = 0;
vchPlaintext = CKeyingMaterial(nPLen);
EVP_CIPHER_CTX ctx;
bool fOk = true;
EVP_CIPHER_CTX_init(&ctx);
if (fOk) fOk = EVP_DecryptInit_ex(&ctx, EVP_aes_256_cbc(), NULL, chKey, chIV);
if (fOk) fOk = EVP_DecryptUpdate(&ctx, &vchPlaintext[0], &nPLen, &vchCiphertext[0], nLen);
if (fOk) fOk = EVP_DecryptFinal_ex(&ctx, (&vchPlaintext[0])+nPLen, &nFLen);
EVP_CIPHER_CTX_cleanup(&ctx);
if (!fOk) return false;
vchPlaintext.resize(nPLen + nFLen);
return true;
}
bool EncryptSecret(const CKeyingMaterial& vMasterKey, const CKeyingMaterial &vchPlaintext, const uint256& nIV, std::vector<unsigned char> &vchCiphertext)
{
CCrypter cKeyCrypter;
std::vector<unsigned char> chIV(WALLET_CRYPTO_KEY_SIZE);
memcpy(&chIV[0], &nIV, WALLET_CRYPTO_KEY_SIZE);
if(!cKeyCrypter.SetKey(vMasterKey, chIV))
return false;
return cKeyCrypter.Encrypt(*((const CKeyingMaterial*)&vchPlaintext), vchCiphertext);
}
bool DecryptSecret(const CKeyingMaterial& vMasterKey, const std::vector<unsigned char>& vchCiphertext, const uint256& nIV, CKeyingMaterial& vchPlaintext)
{
CCrypter cKeyCrypter;
std::vector<unsigned char> chIV(WALLET_CRYPTO_KEY_SIZE);
memcpy(&chIV[0], &nIV, WALLET_CRYPTO_KEY_SIZE);
if(!cKeyCrypter.SetKey(vMasterKey, chIV))
return false;
return cKeyCrypter.Decrypt(vchCiphertext, *((CKeyingMaterial*)&vchPlaintext));
}
bool CCryptoKeyStore::SetCrypted()
{
LOCK(cs_KeyStore);
if (fUseCrypto)
return true;
if (!mapKeys.empty())
return false;
fUseCrypto = true;
return true;
}
bool CCryptoKeyStore::Lock()
{
if (!SetCrypted())
return false;
{
LOCK(cs_KeyStore);
vMasterKey.clear();
}
NotifyStatusChanged(this);
return true;
}
bool CCryptoKeyStore::Unlock(const CKeyingMaterial& vMasterKeyIn)
{
{
LOCK(cs_KeyStore);
if (!SetCrypted())
return false;
bool keyPass = false;
bool keyFail = false;
CryptedKeyMap::const_iterator mi = mapCryptedKeys.begin();
for (; mi != mapCryptedKeys.end(); ++mi)
{
const CPubKey &vchPubKey = (*mi).second.first;
const std::vector<unsigned char> &vchCryptedSecret = (*mi).second.second;
CKeyingMaterial vchSecret;
if(!DecryptSecret(vMasterKeyIn, vchCryptedSecret, vchPubKey.GetHash(), vchSecret))
{
keyFail = true;
break;
}
if (vchSecret.size() != 32)
{
keyFail = true;
break;
}
CKey key;
key.Set(vchSecret.begin(), vchSecret.end(), vchPubKey.IsCompressed());
if (key.GetPubKey() != vchPubKey)
{
keyFail = true;
break;
}
keyPass = true;
}
if (keyPass && keyFail)
{
LogPrintf("The wallet is probably corrupted: Some keys decrypt but not all.");
assert(false);
}
if (keyFail || !keyPass)
return false;
vMasterKey = vMasterKeyIn;
}
NotifyStatusChanged(this);
return true;
}
bool CCryptoKeyStore::AddKeyPubKey(const CKey& key, const CPubKey &pubkey)
{
{
LOCK(cs_KeyStore);
if (!IsCrypted())
return CBasicKeyStore::AddKeyPubKey(key, pubkey);
if (IsLocked())
return false;
std::vector<unsigned char> vchCryptedSecret;
CKeyingMaterial vchSecret(key.begin(), key.end());
if (!EncryptSecret(vMasterKey, vchSecret, pubkey.GetHash(), vchCryptedSecret))
return false;
if (!AddCryptedKey(pubkey, vchCryptedSecret))
return false;
}
return true;
}
bool CCryptoKeyStore::AddCryptedKey(const CPubKey &vchPubKey, const std::vector<unsigned char> &vchCryptedSecret)
{
{
LOCK(cs_KeyStore);
if (!SetCrypted())
return false;
mapCryptedKeys[vchPubKey.GetID()] = make_pair(vchPubKey, vchCryptedSecret);
}
return true;
}
bool CCryptoKeyStore::GetKey(const CKeyID &address, CKey& keyOut) const
{
{
LOCK(cs_KeyStore);
if (!IsCrypted())
return CBasicKeyStore::GetKey(address, keyOut);
CryptedKeyMap::const_iterator mi = mapCryptedKeys.find(address);
if (mi != mapCryptedKeys.end())
{
const CPubKey &vchPubKey = (*mi).second.first;
const std::vector<unsigned char> &vchCryptedSecret = (*mi).second.second;
CKeyingMaterial vchSecret;
if (!DecryptSecret(vMasterKey, vchCryptedSecret, vchPubKey.GetHash(), vchSecret))
return false;
if (vchSecret.size() != 32)
return false;
keyOut.Set(vchSecret.begin(), vchSecret.end(), vchPubKey.IsCompressed());
return true;
}
}
return false;
}
bool CCryptoKeyStore::GetPubKey(const CKeyID &address, CPubKey& vchPubKeyOut) const
{
{
LOCK(cs_KeyStore);
if (!IsCrypted())
return CKeyStore::GetPubKey(address, vchPubKeyOut);
CryptedKeyMap::const_iterator mi = mapCryptedKeys.find(address);
if (mi != mapCryptedKeys.end())
{
vchPubKeyOut = (*mi).second.first;
return true;
}
}
return false;
}
bool CCryptoKeyStore::EncryptKeys(CKeyingMaterial& vMasterKeyIn)
{
{
LOCK(cs_KeyStore);
if (!mapCryptedKeys.empty() || IsCrypted())
return false;
fUseCrypto = true;
BOOST_FOREACH(KeyMap::value_type& mKey, mapKeys)
{
const CKey &key = mKey.second;
CPubKey vchPubKey = key.GetPubKey();
CKeyingMaterial vchSecret(key.begin(), key.end());
std::vector<unsigned char> vchCryptedSecret;
if (!EncryptSecret(vMasterKeyIn, vchSecret, vchPubKey.GetHash(), vchCryptedSecret))
return false;
if (!AddCryptedKey(vchPubKey, vchCryptedSecret))
return false;
}
mapKeys.clear();
}
return true;
}
|
Make CCryptoKeyStore::Unlock check all keys.
|
Make CCryptoKeyStore::Unlock check all keys.
CCryptoKeyStore::Unlock has a loop to attempt decrypting each key which
only executes once, likely due to a simple mistake when the code was
originally written.
This patch fixes the behavior by making it check all keys. It also adds
a fatal assertion in the case some decrypt but some do not, since that
indicates that the wallet is in some kind of really bad state.
This may make unlocking noticeably slower on wallets with many keys.
|
C++
|
mit
|
langerhans/dogecoin,langerhans/dogecoin,langerhans/dogecoin,langerhans/dogecoin,langerhans/dogecoin,langerhans/dogecoin
|
abcce44b788e650bcd1217939365c6b85591a996
|
elf/elf_code_container.cpp
|
elf/elf_code_container.cpp
|
/* The MIT License (MIT)
*
* Copyright (c) 2016 Adrian Dobrică, Ștefan-Gabriel Mirea
*
* 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 "elf_code_container.hpp"
using namespace elf;
ELFCodeContainer::ELFCodeContainer(ELFFile *file, const std::pair<int, int> &interval) :
CodeContainer(file, interval)
{
injectionPossible = false;
}
unsigned int ELFCodeContainer::addressToOffset(unsigned long long address)
{
/* TODO */
return address - 0x406000;
}
void ELFCodeContainer::getContent(std::vector<std::pair<unsigned long long, std::string>> &content)
{
ELFFile *efile = dynamic_cast<ELFFile *>(getFile());
#ifdef DEBUG
assert(efile != nullptr);
#endif
/* TODO: populate content using ELFIO */
efile->getELFIO();
content.clear();
char inst1[] = {0x41, 0x57};
char inst2[] = {0x89, 0x85, 0x24, 0xff, 0xff, 0xff};
char inst3[] = {0x4c, 0x29, 0xe5};
char inst4[] = {0x53};
char inst5[] = {0x8b, 0x85, 0x24, 0xff, 0xff, 0xff};
content.push_back(std::make_pair(0x406637, std::string(inst1, 2)));
content.push_back(std::make_pair(0x406639, std::string(inst2, 6)));
content.push_back(std::make_pair(0x40663f, std::string(inst3, 3)));
content.push_back(std::make_pair(0x406642, std::string(inst4, 1)));
content.push_back(std::make_pair(0x406643, std::string(inst5, 6)));
}
void ELFCodeContainer::overwrite(unsigned long long address, std::string newMachineCode)
{
ELFFile *efile = dynamic_cast<ELFFile *>(getFile());
#ifdef DEBUG
assert(efile != nullptr);
#endif
/* TODO: update efile->getELFIO() */
efile->getELFIO();
}
ELFCodeContainer::~ELFCodeContainer() {}
|
/* The MIT License (MIT)
*
* Copyright (c) 2016 Adrian Dobrică, Ștefan-Gabriel Mirea
*
* 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 "elf_code_container.hpp"
using namespace elf;
ELFCodeContainer::ELFCodeContainer(ELFFile *file, const std::pair<int, int> &interval) :
CodeContainer(file, interval)
{
injectionPossible = false;
}
unsigned int ELFCodeContainer::addressToOffset(unsigned long long address)
{
/* TODO */
return address - 0x406000;
}
void ELFCodeContainer::getContent(std::vector<std::pair<unsigned long long, std::string>> &content)
{
ELFFile *efile = dynamic_cast<ELFFile *>(getFile());
#ifdef DEBUG
assert(efile != nullptr);
#endif
/* TODO: populate content using ELFIO */
efile->getELFIO();
content.clear();
char inst1[] = {0x41, 0x57};
char inst2[] = {0x89, 0x85, 0x24, 0xff, 0xff, 0xff};
char inst3[] = {0x4c, 0x29, 0xe5};
char inst4[] = {0x53};
char inst5[] = {0x8b, 0x85, 0x24, 0xff, 0xff, 0xff};
content.push_back(std::make_pair(0x406637, std::string(inst1, 2)));
content.push_back(std::make_pair(0x406639, std::string(inst2, 6)));
content.push_back(std::make_pair(0x40663f, std::string(inst3, 3)));
content.push_back(std::make_pair(0x406642, std::string(inst4, 1)));
content.push_back(std::make_pair(0x406643, std::string(inst5, 6)));
}
void ELFCodeContainer::overwrite(unsigned long long address, std::string newMachineCode)
{
ELFFile *efile = dynamic_cast<ELFFile *>(getFile());
#ifdef DEBUG
assert(efile != nullptr);
#endif
/* TODO: update efile->getELFIO() */
ELFIO::elfio *interpretor = efile->getELFIO();
int num_sec = interpretor->get_sections_num();
int found = false;
for (int i = 0; i < num_sec && !found; i++)
{
ELFIO::section *currentSection = interpretor->sections[i];
if (currentSection->get_flags() & SHF_EXECINSTR)
{
if (currentSection->get_address() <= address &&
currentSection->get_address() + currentSection->get_size() > address)
{
currentSection->set_data(newMachineCode.c_str(), address, newMachineCode.size());
found = true;
}
}
}
}
ELFCodeContainer::~ELFCodeContainer() {}
|
Implement overwrite for ElfCodeContainer
|
Implement overwrite for ElfCodeContainer
|
C++
|
mit
|
stefanmirea/mangler,SilentControl/mangler
|
0ffc83c5ba725c1b51a6e347de861b5c705ecece
|
chrome/browser/download/download_exe.cc
|
chrome/browser/download/download_exe.cc
|
// Copyright (c) 2006-2008 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include <set>
#include <string>
#include "chrome/browser/download/download_util.h"
#include "base/logging.h"
namespace download_util {
// For file extensions taken from mozilla:
/* ***** BEGIN LICENSE BLOCK *****
* Version: MPL 1.1/GPL 2.0/LGPL 2.1
*
* The contents of this file are subject to the Mozilla Public License Version
* 1.1 (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
* http://www.mozilla.org/MPL/
*
* Software distributed under the License is distributed on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
* for the specific language governing rights and limitations under the
* License.
*
* The Original Code is Mozilla Communicator client code, released
* March 31, 1998.
*
* The Initial Developer of the Original Code is
* Netscape Communications Corporation.
* Portions created by the Initial Developer are Copyright (C) 1998-1999
* the Initial Developer. All Rights Reserved.
*
* Contributor(s):
* Doug Turner <[email protected]>
* Dean Tessman <[email protected]>
* Brodie Thiesfield <[email protected]>
* Jungshik Shin <[email protected]>
*
* Alternatively, the contents of this file may be used under the terms of
* either of the GNU General Public License Version 2 or later (the "GPL"),
* or the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
* in which case the provisions of the GPL or the LGPL are applicable instead
* of those above. If you wish to allow use of your version of this file only
* under the terms of either the GPL or the LGPL, and not to allow others to
* use your version of this file under the terms of the MPL, indicate your
* decision by deleting the provisions above and replace them with the notice
* and other provisions required by the GPL or the LGPL. If you do not delete
* the provisions above, a recipient may use your version of this file under
* the terms of any one of the MPL, the GPL or the LGPL.
*
* ***** END LICENSE BLOCK ***** */
static const char* const g_executables[] = {
#if defined(OS_WIN)
"ad",
"ade",
"adp",
"app",
"application",
"asp",
"asx",
"bas",
"bat",
"chm",
"cmd",
"com",
"cpl",
"crt",
"dll",
"exe",
"fxp",
"hlp",
"hta",
"htm",
"html",
"inf",
"ins",
"isp",
"jar",
"js",
"jse",
"lnk",
"mad",
"maf",
"mag",
"mam",
"maq",
"mar",
"mas",
"mat",
"mau",
"mav",
"maw",
"mda",
"mdb",
"mde",
"mdt",
"mdw",
"mdz",
"msc",
"msh",
"mshxml",
"msi",
"msp",
"mst",
"ops",
"pcd",
"pif",
"plg",
"prf",
"prg",
"pst",
"reg",
"scf",
"scr",
"sct",
"shb",
"shs",
"shtm",
"shtml",
"url",
"vb",
"vbe",
"vbs",
"vsd",
"vsmacros",
"vss",
"vst",
"vsw",
"ws",
"wsc",
"wsf",
"wsh",
"xht",
"xhtm",
"xhtml",
#elif defined(OS_LINUX)
// TODO(estade): lengthen this list.
"exe",
"pl",
"py",
"rb",
"sh",
#elif defined(OS_MACOSX)
// TODO(thakis): Figure out what makes sense here -- crbug.com/19096
"dmg",
#endif
};
void InitializeExeTypes(std::set<std::string>* exe_extensions) {
DCHECK(exe_extensions);
for (size_t i = 0; i < arraysize(g_executables); ++i)
exe_extensions->insert(g_executables[i]);
}
} // namespace download_util
|
// Copyright (c) 2006-2008 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include <set>
#include <string>
#include "chrome/browser/download/download_util.h"
#include "base/logging.h"
namespace download_util {
// For file extensions taken from mozilla:
/* ***** BEGIN LICENSE BLOCK *****
* Version: MPL 1.1/GPL 2.0/LGPL 2.1
*
* The contents of this file are subject to the Mozilla Public License Version
* 1.1 (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
* http://www.mozilla.org/MPL/
*
* Software distributed under the License is distributed on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
* for the specific language governing rights and limitations under the
* License.
*
* The Original Code is Mozilla Communicator client code, released
* March 31, 1998.
*
* The Initial Developer of the Original Code is
* Netscape Communications Corporation.
* Portions created by the Initial Developer are Copyright (C) 1998-1999
* the Initial Developer. All Rights Reserved.
*
* Contributor(s):
* Doug Turner <[email protected]>
* Dean Tessman <[email protected]>
* Brodie Thiesfield <[email protected]>
* Jungshik Shin <[email protected]>
*
* Alternatively, the contents of this file may be used under the terms of
* either of the GNU General Public License Version 2 or later (the "GPL"),
* or the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
* in which case the provisions of the GPL or the LGPL are applicable instead
* of those above. If you wish to allow use of your version of this file only
* under the terms of either the GPL or the LGPL, and not to allow others to
* use your version of this file under the terms of the MPL, indicate your
* decision by deleting the provisions above and replace them with the notice
* and other provisions required by the GPL or the LGPL. If you do not delete
* the provisions above, a recipient may use your version of this file under
* the terms of any one of the MPL, the GPL or the LGPL.
*
* ***** END LICENSE BLOCK ***** */
static const char* const g_executables[] = {
#if defined(OS_WIN)
"ad",
"ade",
"adp",
"app",
"application",
"asp",
"asx",
"bas",
"bat",
"chm",
"cmd",
"com",
"cpl",
"crt",
"dll",
"exe",
"fxp",
"hlp",
"hta",
"htm",
"html",
"htt",
"inf",
"ins",
"isp",
"jar",
"js",
"jse",
"lnk",
"mad",
"maf",
"mag",
"mam",
"maq",
"mar",
"mas",
"mat",
"mau",
"mav",
"maw",
"mda",
"mdb",
"mde",
"mdt",
"mdw",
"mdz",
"mht",
"mhtml",
"msc",
"msh",
"mshxml",
"msi",
"msp",
"mst",
"ops",
"pcd",
"pif",
"plg",
"prf",
"prg",
"pst",
"reg",
"scf",
"scr",
"sct",
"shb",
"shs",
"shtm",
"shtml",
"url",
"vb",
"vbe",
"vbs",
"vsd",
"vsmacros",
"vss",
"vst",
"vsw",
"ws",
"wsc",
"wsf",
"wsh",
"xht",
"xhtm",
"xhtml",
"xml",
"xsl",
"xslt",
#elif defined(OS_LINUX)
// TODO(estade): lengthen this list.
"exe",
"pl",
"py",
"rb",
"sh",
#elif defined(OS_MACOSX)
// TODO(thakis): Figure out what makes sense here -- crbug.com/19096
"dmg",
#endif
};
void InitializeExeTypes(std::set<std::string>* exe_extensions) {
DCHECK(exe_extensions);
for (size_t i = 0; i < arraysize(g_executables); ++i)
exe_extensions->insert(g_executables[i]);
}
} // namespace download_util
|
Add more extensions to our download_exe list.
|
Add more extensions to our download_exe list.
Review URL: http://codereview.chromium.org/243115
git-svn-id: dd90618784b6a4b323ea0c23a071cb1c9e6f2ac7@28235 4ff67af0-8c30-449e-8e8b-ad334ec8d88c
|
C++
|
bsd-3-clause
|
wistoch/meego-app-browser,wistoch/meego-app-browser,wistoch/meego-app-browser,wistoch/meego-app-browser,wistoch/meego-app-browser,wistoch/meego-app-browser,wistoch/meego-app-browser,wistoch/meego-app-browser,wistoch/meego-app-browser,wistoch/meego-app-browser
|
15b434a33a1c1308ec88306590081f61854076fe
|
include/common.hpp
|
include/common.hpp
|
#ifndef COMMON_H
#define COMMON_H
#include <sys/time.h>
#include <time.h>
#include <string>
//#define PRINT_BUILD_TIME_BREAKDOWN 1
//#define USE_ARRAY_DICT 1
#define USE_FIXED_LEN_DICT_CODE 1
//#define INCLUDE_DECODE 1
const int dict_size_list[9] = {1024, 2048, 4096, 8192, 16384, 32768, 65536, 131072, 262144};
const int64_t three_gram_input_dict_size[4][7] = {
{ 831, 1983, 4608, 10496, 24064, 52224, 80000},
{ 799, 1919, 4352, 9600, 20480, 41984, 80000},
{ 815, 1983, 4352, 9472, 19968, 41984, 80000},
{ 0, 0, 0, 0, 0, 0, 0}};
const int64_t four_gram_input_dict_size[4][9] = {
{ 815, 1919, 4160, 8704, 18176, 37888, 79687, 168750, 351562},
{ 767, 1823, 3967, 8320, 17408, 35840, 75000, 151551, 309375},
{ 799, 1855, 3967, 8448, 17408, 35328, 71875, 147455, 295312},
{ 0, 0, 0, 0, 0, 0, 0, 0, 0}};
const int ALM_W[3][9] = {
{399219, 206250, 99999, 49999, 25780, 13280, 6639, 3319, 1561},
{146092, 70311, 37499, 20701, 11326, 6053, 3319, 2048, 1316},
{4843749, 2656249, 1445311, 820311, 468749, 263670, 161131, 90330, 46384}
};
const int ALM_W_improved[3][9] = {
{ 13274, 7726, 2462, 3436, 2071, 1131, 252, 359, 186},
{ 7874, 4030, 2249, 1264, 725, 397, 215, 115, 65},
{ 42000,35000, 21875, 13436, 8436, 4999, 2889, 1717, 1014}
};
namespace ope {
typedef struct {
//int64_t code;
int32_t code;
int8_t len;
} Code;
typedef struct {
uint8_t common_prefix_len;
Code code;
} IntervalCode;
typedef typename std::pair<std::string, int64_t> SymbolFreq;
typedef typename std::pair<std::string, Code> SymbolCode;
typedef struct {
char start_key[3];
uint8_t common_prefix_len;
Code code;
} Interval3Gram;
typedef struct {
char start_key[4];
uint8_t common_prefix_len;
Code code;
} Interval4Gram;
double getNow() {
struct timeval tv;
gettimeofday(&tv, 0);
return tv.tv_sec + tv.tv_usec / 1000000.0;
}
void printString(std::string str) {
for (int i = 0; i < (int)str.length();i++)
std::cout << std::hex << (int)str[i] << " ";
}
int strCompare(std::string s1, std::string s2) {
int len1 = (int) s1.length();
int len2 = (int) s2.length();
int len = len1 < len2 ? len1 : len2;
for (int i = 0; i < len; i++) {
uint8_t c1 = static_cast<uint8_t >(s1[i]);
uint8_t c2 = static_cast<uint8_t >(s2[i]);
if (c1 < c2)
return -1;
if (c1 > c2)
return 1;
}
if (len1 < len2)
return -1;
else if (len1 == len2)
return 0;
else
return 1;
}
} // namespace ope
#endif // COMMON_H
|
#ifndef COMMON_H
#define COMMON_H
#include <sys/time.h>
#include <time.h>
#include <string>
//#define PRINT_BUILD_TIME_BREAKDOWN 1
//#define USE_ARRAY_DICT 1
#define USE_FIXED_LEN_DICT_CODE 1
//#define INCLUDE_DECODE 1
#define MAX_STR_LEN 50
const int dict_size_list[9] = {1024, 2048, 4096, 8192, 16384, 32768, 65536, 131072, 262144};
const int64_t three_gram_input_dict_size[4][7] = {
{ 831, 1983, 4608, 10496, 24064, 52224, 80000},
{ 799, 1919, 4352, 9600, 20480, 41984, 80000},
{ 815, 1983, 4352, 9472, 19968, 41984, 80000},
{ 0, 0, 0, 0, 0, 0, 0}};
const int64_t four_gram_input_dict_size[4][9] = {
{ 815, 1919, 4160, 8704, 18176, 37888, 79687, 168750, 351562},
{ 767, 1823, 3967, 8320, 17408, 35840, 75000, 151551, 309375},
{ 799, 1855, 3967, 8448, 17408, 35328, 71875, 147455, 295312},
{ 0, 0, 0, 0, 0, 0, 0, 0, 0}};
const int ALM_W[3][9] = {
{399219, 206250, 99999, 49999, 25780, 13280, 6639, 3319, 1561},
{146092, 70311, 37499, 20701, 11326, 6053, 3319, 2048, 1316},
{4843749, 2656249, 1445311, 820311, 468749, 263670, 161131, 90330, 46384}
};
const int ALM_W_improved[3][9] = {
{ 13274, 7726, 2462, 3436, 2071, 1131, 252, 359, 186},
{ 7874, 4030, 2249, 1264, 725, 397, 215, 115, 65},
{ 42000,35000, 21875, 13436, 8436, 4999, 2889, 1717, 1014}
};
namespace ope {
typedef struct {
//int64_t code;
int32_t code;
int8_t len;
} Code;
typedef struct {
uint8_t common_prefix_len;
Code code;
} IntervalCode;
typedef typename std::pair<std::string, int64_t> SymbolFreq;
typedef typename std::pair<std::string, Code> SymbolCode;
typedef struct {
char start_key[3];
uint8_t common_prefix_len;
Code code;
} Interval3Gram;
typedef struct {
char start_key[4];
uint8_t common_prefix_len;
Code code;
} Interval4Gram;
double getNow() {
struct timeval tv;
gettimeofday(&tv, 0);
return tv.tv_sec + tv.tv_usec / 1000000.0;
}
void printString(std::string str) {
for (int i = 0; i < (int)str.length();i++)
std::cout << std::hex << (int)str[i] << " ";
}
int strCompare(std::string s1, std::string s2) {
int len1 = (int) s1.length();
int len2 = (int) s2.length();
int len = len1 < len2 ? len1 : len2;
for (int i = 0; i < len; i++) {
uint8_t c1 = static_cast<uint8_t >(s1[i]);
uint8_t c2 = static_cast<uint8_t >(s2[i]);
if (c1 < c2)
return -1;
if (c1 > c2)
return 1;
}
if (len1 < len2)
return -1;
else if (len1 == len2)
return 0;
else
return 1;
}
} // namespace ope
#endif // COMMON_H
|
add string len limit
|
add string len limit
|
C++
|
apache-2.0
|
efficient/HOPE,efficient/HOPE,efficient/HOPE
|
93d2e58982c466af86ed35f0bbb0cb56b68bba0c
|
chrome/common/pepper_plugin_registry.cc
|
chrome/common/pepper_plugin_registry.cc
|
// Copyright (c) 2010 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome/common/pepper_plugin_registry.h"
#include "base/command_line.h"
#include "base/file_util.h"
#include "base/path_service.h"
#include "base/string_util.h"
#include "chrome/common/chrome_paths.h"
#include "chrome/common/chrome_switches.h"
#include "remoting/client/plugin/pepper_entrypoints.h"
// static
PepperPluginRegistry* PepperPluginRegistry::GetInstance() {
static PepperPluginRegistry registry;
return ®istry;
}
// static
void PepperPluginRegistry::GetList(std::vector<PepperPluginInfo>* plugins) {
InternalPluginInfoList internal_plugin_info;
GetInternalPluginInfo(&internal_plugin_info);
for (InternalPluginInfoList::const_iterator it =
internal_plugin_info.begin();
it != internal_plugin_info.end();
++it) {
plugins->push_back(*it);
}
GetPluginInfoFromSwitch(plugins);
GetExtraPlugins(plugins);
}
// static
void PepperPluginRegistry::GetPluginInfoFromSwitch(
std::vector<PepperPluginInfo>* plugins) {
const std::wstring& value = CommandLine::ForCurrentProcess()->GetSwitchValue(
switches::kRegisterPepperPlugins);
if (value.empty())
return;
// FORMAT:
// command-line = <plugin-entry> + *( LWS + "," + LWS + <plugin-entry> )
// plugin-entry = <file-path> + *1( LWS + ";" + LWS + <mime-type> )
std::vector<std::wstring> modules;
SplitString(value, ',', &modules);
for (size_t i = 0; i < modules.size(); ++i) {
std::vector<std::wstring> parts;
SplitString(modules[i], ';', &parts);
if (parts.size() < 2) {
DLOG(ERROR) << "Required mime-type not found";
continue;
}
PepperPluginInfo plugin;
plugin.path = FilePath::FromWStringHack(parts[0]);
for (size_t j = 1; j < parts.size(); ++j)
plugin.mime_types.push_back(WideToASCII(parts[j]));
plugins->push_back(plugin);
}
}
// static
void PepperPluginRegistry::GetExtraPlugins(
std::vector<PepperPluginInfo>* plugins) {
FilePath path;
if (PathService::Get(chrome::FILE_PDF_PLUGIN, &path) &&
file_util::PathExists(path)) {
PepperPluginInfo pdf;
pdf.path = path;
pdf.name = "Chrome PDF Viewer";
pdf.mime_types.push_back("application/pdf");
pdf.file_extensions = "pdf";
pdf.type_descriptions = "Portable Document Format";
plugins->push_back(pdf);
}
}
// static
void PepperPluginRegistry::GetInternalPluginInfo(
InternalPluginInfoList* plugin_info) {
// Currently, to centralize the internal plugin registration logic, we
// hardcode the list of plugins, mimetypes, and registration information
// in this function. This is gross, but because the GetList() function is
// called from both the renderer and browser the other option is to force a
// special register function for each plugin to be called by both
// RendererMain() and BrowserMain(). This seemed like the better tradeoff.
//
// TODO(ajwong): Think up a better way to maintain the plugin registration
// information. Pehraps by construction of a singly linked list of
// plugin initializers that is built with static initializers?
#if defined(ENABLE_REMOTING)
if (CommandLine::ForCurrentProcess()->HasSwitch(
switches::kEnableChromoting)) {
InternalPluginInfo info;
// Add the chromoting plugin.
info.path =
FilePath(FILE_PATH_LITERAL("internal-chromoting"));
info.mime_types.push_back("pepper-application/x-chromoting");
info.entry_points.get_interface = remoting::PPP_GetInterface;
info.entry_points.initialize_module = remoting::PPP_InitializeModule;
info.entry_points.shutdown_module = remoting::PPP_ShutdownModule;
plugin_info->push_back(info);
}
#endif
}
pepper::PluginModule* PepperPluginRegistry::GetModule(
const FilePath& path) const {
ModuleMap::const_iterator it = modules_.find(path);
if (it == modules_.end())
return NULL;
return it->second;
}
PepperPluginRegistry::PepperPluginRegistry() {
InternalPluginInfoList internal_plugin_info;
GetInternalPluginInfo(&internal_plugin_info);
// Register modules for these suckers.
for (InternalPluginInfoList::const_iterator it =
internal_plugin_info.begin();
it != internal_plugin_info.end();
++it) {
const FilePath& path = it->path;
ModuleHandle module =
pepper::PluginModule::CreateInternalModule(it->entry_points);
if (!module) {
DLOG(ERROR) << "Failed to load pepper module: " << path.value();
continue;
}
modules_[path] = module;
}
// Add the modules specified on the command line last so that they can
// override the internal plugins.
std::vector<PepperPluginInfo> plugins;
GetPluginInfoFromSwitch(&plugins);
GetExtraPlugins(&plugins);
for (size_t i = 0; i < plugins.size(); ++i) {
const FilePath& path = plugins[i].path;
ModuleHandle module = pepper::PluginModule::CreateModule(path);
if (!module) {
DLOG(ERROR) << "Failed to load pepper module: " << path.value();
continue;
}
modules_[path] = module;
}
}
|
// Copyright (c) 2010 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome/common/pepper_plugin_registry.h"
#include "base/command_line.h"
#include "base/file_util.h"
#include "base/path_service.h"
#include "base/string_util.h"
#include "base/utf_string_conversions.h"
#include "chrome/common/chrome_paths.h"
#include "chrome/common/chrome_switches.h"
#include "remoting/client/plugin/pepper_entrypoints.h"
// static
PepperPluginRegistry* PepperPluginRegistry::GetInstance() {
static PepperPluginRegistry registry;
return ®istry;
}
// static
void PepperPluginRegistry::GetList(std::vector<PepperPluginInfo>* plugins) {
InternalPluginInfoList internal_plugin_info;
GetInternalPluginInfo(&internal_plugin_info);
for (InternalPluginInfoList::const_iterator it =
internal_plugin_info.begin();
it != internal_plugin_info.end();
++it) {
plugins->push_back(*it);
}
GetPluginInfoFromSwitch(plugins);
GetExtraPlugins(plugins);
}
// static
void PepperPluginRegistry::GetPluginInfoFromSwitch(
std::vector<PepperPluginInfo>* plugins) {
const std::wstring& value = CommandLine::ForCurrentProcess()->GetSwitchValue(
switches::kRegisterPepperPlugins);
if (value.empty())
return;
// FORMAT:
// command-line = <plugin-entry> + *( LWS + "," + LWS + <plugin-entry> )
// plugin-entry = <file-path> + ["#" + <name> + ["#" + <description>]] +
// *1( LWS + ";" + LWS + <mime-type> )
std::vector<std::wstring> modules;
SplitString(value, ',', &modules);
for (size_t i = 0; i < modules.size(); ++i) {
std::vector<std::wstring> parts;
SplitString(modules[i], ';', &parts);
if (parts.size() < 2) {
DLOG(ERROR) << "Required mime-type not found";
continue;
}
std::vector<std::wstring> name_parts;
SplitString(parts[0], '#', &name_parts);
PepperPluginInfo plugin;
plugin.path = FilePath::FromWStringHack(name_parts[0]);
if (name_parts.size() > 1)
plugin.name = WideToUTF8(name_parts[1]);
if (name_parts.size() > 2)
plugin.type_descriptions = WideToUTF8(name_parts[2]);
for (size_t j = 1; j < parts.size(); ++j)
plugin.mime_types.push_back(WideToASCII(parts[j]));
plugins->push_back(plugin);
}
}
// static
void PepperPluginRegistry::GetExtraPlugins(
std::vector<PepperPluginInfo>* plugins) {
FilePath path;
if (PathService::Get(chrome::FILE_PDF_PLUGIN, &path) &&
file_util::PathExists(path)) {
PepperPluginInfo pdf;
pdf.path = path;
pdf.name = "Chrome PDF Viewer";
pdf.mime_types.push_back("application/pdf");
pdf.file_extensions = "pdf";
pdf.type_descriptions = "Portable Document Format";
plugins->push_back(pdf);
}
}
// static
void PepperPluginRegistry::GetInternalPluginInfo(
InternalPluginInfoList* plugin_info) {
// Currently, to centralize the internal plugin registration logic, we
// hardcode the list of plugins, mimetypes, and registration information
// in this function. This is gross, but because the GetList() function is
// called from both the renderer and browser the other option is to force a
// special register function for each plugin to be called by both
// RendererMain() and BrowserMain(). This seemed like the better tradeoff.
//
// TODO(ajwong): Think up a better way to maintain the plugin registration
// information. Pehraps by construction of a singly linked list of
// plugin initializers that is built with static initializers?
#if defined(ENABLE_REMOTING)
if (CommandLine::ForCurrentProcess()->HasSwitch(
switches::kEnableChromoting)) {
InternalPluginInfo info;
// Add the chromoting plugin.
info.path =
FilePath(FILE_PATH_LITERAL("internal-chromoting"));
info.mime_types.push_back("pepper-application/x-chromoting");
info.entry_points.get_interface = remoting::PPP_GetInterface;
info.entry_points.initialize_module = remoting::PPP_InitializeModule;
info.entry_points.shutdown_module = remoting::PPP_ShutdownModule;
plugin_info->push_back(info);
}
#endif
}
pepper::PluginModule* PepperPluginRegistry::GetModule(
const FilePath& path) const {
ModuleMap::const_iterator it = modules_.find(path);
if (it == modules_.end())
return NULL;
return it->second;
}
PepperPluginRegistry::PepperPluginRegistry() {
InternalPluginInfoList internal_plugin_info;
GetInternalPluginInfo(&internal_plugin_info);
// Register modules for these suckers.
for (InternalPluginInfoList::const_iterator it =
internal_plugin_info.begin();
it != internal_plugin_info.end();
++it) {
const FilePath& path = it->path;
ModuleHandle module =
pepper::PluginModule::CreateInternalModule(it->entry_points);
if (!module) {
DLOG(ERROR) << "Failed to load pepper module: " << path.value();
continue;
}
modules_[path] = module;
}
// Add the modules specified on the command line last so that they can
// override the internal plugins.
std::vector<PepperPluginInfo> plugins;
GetPluginInfoFromSwitch(&plugins);
GetExtraPlugins(&plugins);
for (size_t i = 0; i < plugins.size(); ++i) {
const FilePath& path = plugins[i].path;
ModuleHandle module = pepper::PluginModule::CreateModule(path);
if (!module) {
DLOG(ERROR) << "Failed to load pepper module: " << path.value();
continue;
}
modules_[path] = module;
}
}
|
Add the ability to specify the name and description for a pepper plugin loaded on the command line. This is necessary to emulate known plugin types with Pepper since web pages do sniffing on these to detect if the corresponding plugin is installed.
|
Add the ability to specify the name and description for a pepper plugin loaded
on the command line. This is necessary to emulate known plugin types with
Pepper since web pages do sniffing on these to detect if the corresponding
plugin is installed.
TEST=none
BUG=none
Review URL: http://codereview.chromium.org/2985010
git-svn-id: dd90618784b6a4b323ea0c23a071cb1c9e6f2ac7@52672 4ff67af0-8c30-449e-8e8b-ad334ec8d88c
|
C++
|
bsd-3-clause
|
wistoch/meego-app-browser,wistoch/meego-app-browser,wistoch/meego-app-browser,wistoch/meego-app-browser,wistoch/meego-app-browser,wistoch/meego-app-browser,wistoch/meego-app-browser,wistoch/meego-app-browser,wistoch/meego-app-browser,wistoch/meego-app-browser
|
7af7e13e43eaef2563081568d2b3d0e8d593128e
|
include/io/tmp.hpp
|
include/io/tmp.hpp
|
/*
PICCANTE
The hottest HDR imaging library!
http://vcg.isti.cnr.it/piccante
Copyright (C) 2014
Visual Computing Laboratory - ISTI CNR
http://vcg.isti.cnr.it
First author: Francesco Banterle
This Source Code Form is subject to the terms of the Mozilla Public
License, v. 2.0. If a copy of the MPL was not distributed with this
file, You can obtain one at http://mozilla.org/MPL/2.0/.
*/
#ifndef PIC_IO_TMP_HPP
#define PIC_IO_TMP_HPP
#include <stdio.h>
#include <string>
#include "../base.hpp"
namespace pic {
/**
* @brief The TMP_IMG_HEADER struct is a header for a tmp image
*/
struct TMP_IMG_HEADER {
int frames, width, height, channels;
};
/**
* @brief ReadTMP reads a dump temp file.
* @param nameFile
* @param data
* @param width
* @param height
* @param channels
* @param frames
* @param bHeader
* @return
*/
PIC_INLINE float *ReadTMP(std::string nameFile, float *data, int &width,
int &height, int &channels, int &frames, bool bHeader = true)
{
FILE *file = fopen(nameFile.c_str(), "rb");
if(file == NULL) {
return NULL;
}
//reading the header
TMP_IMG_HEADER header = {0};
if(bHeader) {
fread(&header, sizeof(TMP_IMG_HEADER), 1, file);
if(header.channels < 1 && header.frames < 1 && header.height < 1 &&
header.width < 1) { //invalid image!
return NULL;
}
}
if(data == NULL) {
data = new float[width * height * channels * frames];
}
if(bHeader) {
width = header.width;
height = header.height;
channels = header.channels;
frames = header.frames;
}
fread(data, sizeof(float), frames * width * height * channels, file);
fclose(file);
return data;
}
/**
* @brief WriteTMP writes a dump temp file.
* @param nameFile
* @param data
* @param width
* @param height
* @param channels
* @param frames
* @param bHeader
* @return
*/
PIC_INLINE bool WriteTMP(std::string nameFile, float *data, int &width,
int &height, int &channels, int &frames, bool bHeader = true)
{
TMP_IMG_HEADER header;
if(bHeader) {
header.frames = frames;
header.width = width;
header.height = height;
header.channels = channels;
}
FILE *file = fopen(nameFile.c_str(), "wb");
if(file == NULL) {
return false;
}
int size = frames * width * height * channels;
if(size < 1)
return false;
if(bHeader) {
fwrite(&header, sizeof(TMP_IMG_HEADER), 1, file);
}
fwrite(data, sizeof(float), size, file);
fclose(file);
return true;
}
} // end namespace pic
#endif /* PIC_IO_TMP_HPP */
|
/*
PICCANTE
The hottest HDR imaging library!
http://vcg.isti.cnr.it/piccante
Copyright (C) 2014
Visual Computing Laboratory - ISTI CNR
http://vcg.isti.cnr.it
First author: Francesco Banterle
This Source Code Form is subject to the terms of the Mozilla Public
License, v. 2.0. If a copy of the MPL was not distributed with this
file, You can obtain one at http://mozilla.org/MPL/2.0/.
*/
#ifndef PIC_IO_TMP_HPP
#define PIC_IO_TMP_HPP
#include <stdio.h>
#include <string>
#include "../base.hpp"
namespace pic {
/**
* @brief The TMP_IMG_HEADER struct is a header for a tmp image
*/
struct TMP_IMG_HEADER {
int frames, width, height, channels;
};
/**
* @brief ReadTMP reads a dump temp file.
* @param nameFile
* @param data
* @param width
* @param height
* @param channels
* @param frames
* @param bHeader
* @return
*/
PIC_INLINE float *ReadTMP(std::string nameFile, float *data, int &width,
int &height, int &channels, int &frames, bool bHeader = true)
{
FILE *file = fopen(nameFile.c_str(), "rb");
if(file == NULL) {
return NULL;
}
//read the header
TMP_IMG_HEADER header;
header.channels = -1;
header.frames = -1;
header.width = -1;
header.height = -1;
if(bHeader) {
fread(&header, sizeof(TMP_IMG_HEADER), 1, file);
if(header.channels < 1 && header.frames < 1 && header.height < 1 &&
header.width < 1) { //invalid image!
return NULL;
}
}
if(data == NULL) {
data = new float[width * height * channels * frames];
}
if(bHeader) {
width = header.width;
height = header.height;
channels = header.channels;
frames = header.frames;
}
fread(data, sizeof(float), frames * width * height * channels, file);
fclose(file);
return data;
}
/**
* @brief WriteTMP writes a dump temp file.
* @param nameFile
* @param data
* @param width
* @param height
* @param channels
* @param frames
* @param bHeader
* @return
*/
PIC_INLINE bool WriteTMP(std::string nameFile, float *data, int &width,
int &height, int &channels, int &frames, bool bHeader = true)
{
TMP_IMG_HEADER header;
if(bHeader) {
header.frames = frames;
header.width = width;
header.height = height;
header.channels = channels;
}
FILE *file = fopen(nameFile.c_str(), "wb");
if(file == NULL) {
return false;
}
int size = frames * width * height * channels;
if(size < 1)
return false;
if(bHeader) {
fwrite(&header, sizeof(TMP_IMG_HEADER), 1, file);
}
fwrite(data, sizeof(float), size, file);
fclose(file);
return true;
}
} // end namespace pic
#endif /* PIC_IO_TMP_HPP */
|
Update tmp.hpp
|
Update tmp.hpp
|
C++
|
mpl-2.0
|
banterle/piccante,banterle/piccante,cnr-isti-vclab/piccante
|
bfbb69506f7a10457ff77e7281609ad92437e763
|
Hybrid/vtkRenderLargeImage.cxx
|
Hybrid/vtkRenderLargeImage.cxx
|
/*=========================================================================
Program: Visualization Toolkit
Module: vtkRenderLargeImage.cxx
Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen
All rights reserved.
See Copyright.txt or http://www.kitware.com/Copyright.htm for details.
This software is distributed WITHOUT ANY WARRANTY; without even
the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
PURPOSE. See the above copyright notice for more information.
=========================================================================*/
#include "vtkRenderLargeImage.h"
#include "vtkCamera.h"
#include "vtkImageData.h"
#include "vtkInformation.h"
#include "vtkInformationVector.h"
#include "vtkObjectFactory.h"
#include "vtkStreamingDemandDrivenPipeline.h"
#include "vtkRenderWindow.h"
#include "vtkRenderer.h"
#include "vtkRendererCollection.h"
#include "vtkActor2DCollection.h"
#include "vtkActor2D.h"
#include "vtkProp.h"
#include <vtkstd/vector>
//----------------------------------------------------------------------------
vtkCxxRevisionMacro(vtkRenderLargeImage, "1.32");
vtkStandardNewMacro(vtkRenderLargeImage);
vtkCxxSetObjectMacro(vtkRenderLargeImage,Input,vtkRenderer);
//----------------------------------------------------------------------------
// 2D Actors need to be rescaled and shifted about for each tile
// use this helper class to make life easier.
class vtkRenderLargeImage2DHelperClass {
public:
// maintain a list of 2D actors
vtkActor2DCollection *storedActors;
// maintain lists of their vtkCoordinate objects
vtkCollection *coord1s;
vtkCollection *coord2s;
// Store the display coords for adjustment during tiling
vtkstd::vector< vtkstd::pair<int, int> > coords1;
vtkstd::vector< vtkstd::pair<int, int> > coords2;
//
vtkRenderLargeImage2DHelperClass()
{
storedActors = vtkActor2DCollection::New();
coord1s = vtkCollection::New();
coord2s = vtkCollection::New();
}
~vtkRenderLargeImage2DHelperClass()
{
coord1s->RemoveAllItems();
coord2s->RemoveAllItems();
storedActors->RemoveAllItems();
coord1s->Delete();
coord2s->Delete();
storedActors->Delete();
}
};
//----------------------------------------------------------------------------
vtkRenderLargeImage::vtkRenderLargeImage()
{
this->Input = NULL;
this->Magnification = 3;
this->SetNumberOfInputPorts(0);
this->SetNumberOfOutputPorts(1);
this->storedData = new vtkRenderLargeImage2DHelperClass();
}
//----------------------------------------------------------------------------
vtkRenderLargeImage::~vtkRenderLargeImage()
{
if (this->Input)
{
this->Input->UnRegister(this);
this->Input = NULL;
}
delete this->storedData;
}
//----------------------------------------------------------------------------
void vtkRenderLargeImage::PrintSelf(ostream& os, vtkIndent indent)
{
this->Superclass::PrintSelf(os,indent);
if ( this->Input )
{
os << indent << "Input:\n";
this->Input->PrintSelf(os,indent.GetNextIndent());
}
else
{
os << indent << "Input: (none)\n";
}
os << indent << "Magnification: " << this->Magnification << "\n";
}
//----------------------------------------------------------------------------
vtkImageData* vtkRenderLargeImage::GetOutput()
{
return vtkImageData::SafeDownCast(this->GetOutputDataObject(0));
}
//----------------------------------------------------------------------------
int vtkRenderLargeImage::ProcessRequest(vtkInformation* request,
vtkInformationVector** inputVector,
vtkInformationVector* outputVector)
{
// generate the data
if(request->Has(vtkDemandDrivenPipeline::REQUEST_DATA()))
{
this->RequestData(request, inputVector, outputVector);
return 1;
}
// execute information
if(request->Has(vtkDemandDrivenPipeline::REQUEST_INFORMATION()))
{
this->RequestInformation(request, inputVector, outputVector);
return 1;
}
return this->Superclass::ProcessRequest(request, inputVector, outputVector);
}
//----------------------------------------------------------------------------
// Description:
// This method returns the largest region that can be generated.
void vtkRenderLargeImage::RequestInformation (
vtkInformation * vtkNotUsed(request),
vtkInformationVector ** vtkNotUsed( inputVector ),
vtkInformationVector *outputVector)
{
// get the info objects
vtkInformation* outInfo = outputVector->GetInformationObject(0);
if (this->Input == NULL )
{
vtkErrorMacro(<<"Please specify a renderer as input!");
return;
}
// set the extent, if the VOI has not been set then default to
int wExt[6];
wExt[0] = 0; wExt[2] = 0; wExt[4] = 0; wExt[5] = 0;
wExt[1] = this->Magnification*
this->Input->GetRenderWindow()->GetSize()[0] - 1;
wExt[3] = this->Magnification*
this->Input->GetRenderWindow()->GetSize()[1] - 1;
outInfo->Set(vtkStreamingDemandDrivenPipeline::WHOLE_EXTENT(), wExt, 6);
// set the spacing
outInfo->Set(vtkDataObject::SPACING(),1.0, 1.0, 1.0);
// set the origin.
outInfo->Set(vtkDataObject::ORIGIN(),0.0, 0.0, 0.0);
// set the scalar components
vtkDataObject::SetPointDataActiveScalarInfo(outInfo, VTK_UNSIGNED_CHAR, 3);
}
//----------------------------------------------------------------------------
// Description:
// This function reads a region from a file. The regions extent/axes
// are assumed to be the same as the file extent/order.
void vtkRenderLargeImage::RequestData(
vtkInformation* vtkNotUsed( request ),
vtkInformationVector** vtkNotUsed( inputVector ),
vtkInformationVector* outputVector)
{
vtkInformation *outInfo = outputVector->GetInformationObject(0);
vtkImageData *data =
vtkImageData::SafeDownCast(outInfo->Get(vtkDataObject::DATA_OBJECT()));
data->SetExtent(data->GetUpdateExtent());
data->AllocateScalars();
int inExtent[6];
int inIncr[3];
int *size;
int inWindowExtent[4];
double viewAngle, parallelScale, windowCenter[2];
vtkCamera *cam;
unsigned char *pixels, *outPtr;
int x, y, row;
int rowSize, rowStart, rowEnd, colStart, colEnd;
int doublebuffer;
int swapbuffers = 0;
if (this->GetOutput()->GetScalarType() != VTK_UNSIGNED_CHAR)
{
vtkErrorMacro("mismatch in scalar types!");
return;
}
// Get the requested extents.
this->GetOutput()->GetUpdateExtent(inExtent);
// get and transform the increments
data->GetIncrements(inIncr);
// get the size of the render window
size = this->Input->GetRenderWindow()->GetSize();
// convert the request into windows
inWindowExtent[0] = inExtent[0]/size[0];
inWindowExtent[1] = inExtent[1]/size[0];
inWindowExtent[2] = inExtent[2]/size[1];
inWindowExtent[3] = inExtent[3]/size[1];
this->Rescale2DActors();
// store the old view angle & set the new
cam = this->Input->GetActiveCamera();
cam->GetWindowCenter(windowCenter);
viewAngle = cam->GetViewAngle();
parallelScale = cam->GetParallelScale();
cam->SetViewAngle(asin(sin(viewAngle*3.1415926/360.0)/this->Magnification)
* 360.0 / 3.1415926);
cam->SetParallelScale(parallelScale/this->Magnification);
// are we double buffering? If so, read from back buffer ....
doublebuffer = this->Input->GetRenderWindow()->GetDoubleBuffer();
if (doublebuffer)
{
// save swap buffer state to restore later
swapbuffers = this->Input->GetRenderWindow()->GetSwapBuffers();
this->Input->GetRenderWindow()->SetSwapBuffers(0);
}
// render each of the tiles required to fill this request
for (y = inWindowExtent[2]; y <= inWindowExtent[3]; y++)
{
for (x = inWindowExtent[0]; x <= inWindowExtent[1]; x++)
{
cam->SetWindowCenter(x*2 - this->Magnification*(1-windowCenter[0]) + 1,
y*2 - this->Magnification*(1-windowCenter[1]) + 1);
// shift 2D actors to correct origin for this tile
this->Shift2DActors(size[0]*x, size[1]*y);
// Render
this->Input->GetRenderWindow()->Render();
pixels = this->Input->GetRenderWindow()->GetPixelData(0,0,size[0] - 1,
size[1] - 1,
!doublebuffer);
// now stuff the pixels into the data row by row
colStart = inExtent[0] - x*size[0];
if (colStart < 0)
{
colStart = 0;
}
colEnd = size[0] - 1;
if (colEnd > (inExtent[1] - x*size[0]))
{
colEnd = inExtent[1] - x*size[0];
}
rowSize = colEnd - colStart + 1;
// get the output pointer and do arith on it if necc
outPtr =
(unsigned char *)data->GetScalarPointer(inExtent[0],inExtent[2],0);
outPtr = outPtr + (x*size[0] - inExtent[0])*inIncr[0] +
(y*size[1] - inExtent[2])*inIncr[1];
rowStart = inExtent[2] - y*size[1];
if (rowStart < 0)
{
rowStart = 0;
}
rowEnd = size[1] - 1;
if (rowEnd > (inExtent[3] - y*size[1]))
{
rowEnd = (inExtent[3] - y*size[1]);
}
for (row = rowStart; row <= rowEnd; row++)
{
memcpy(outPtr + row*inIncr[1] + colStart*inIncr[0],
pixels + row*size[0]*3 + colStart*3, rowSize*3);
}
// free the memory
delete [] pixels;
}
}
// restore the state of the SwapBuffers bit before we mucked with it.
if (doublebuffer && swapbuffers)
{
this->Input->GetRenderWindow()->SetSwapBuffers(swapbuffers);
}
cam->SetViewAngle(viewAngle);
cam->SetParallelScale(parallelScale);
cam->SetWindowCenter(windowCenter[0],windowCenter[1]);
this->Restore2DActors();
}
//----------------------------------------------------------------------------
int vtkRenderLargeImage::FillOutputPortInformation(
int vtkNotUsed(port), vtkInformation* info)
{
// now add our info
info->Set(vtkDataObject::DATA_TYPE_NAME(), "vtkImageData");
return 1;
}
//----------------------------------------------------------------------------
// This code is designed to handle multiple renders even though
// RenderLargeImage currently only handles one explicitly.
//----------------------------------------------------------------------------
void vtkRenderLargeImage::Rescale2DActors()
{
vtkActor2D *actor;
vtkProp *aProp;
vtkRenderer *aren;
vtkPropCollection *pc;
vtkRendererCollection *rc;
vtkCoordinate *c1, *c2;
vtkCoordinate *n1, *n2;
int *p1, *p2;
double d1[3], d2[3];
//
rc = this->Input->GetRenderWindow()->GetRenderers();
for (rc->InitTraversal(); (aren = rc->GetNextItem()); )
{
pc = aren->GetProps();
if (pc)
{
for ( pc->InitTraversal(); (aProp = pc->GetNextProp()); )
{
actor = vtkActor2D::SafeDownCast((aProp));
if (actor)
{
// put the actor in our list for retrieval later
this->storedData->storedActors->AddItem(actor);
// Copy all existing coordinate stuff
n1 = actor->GetPositionCoordinate();
n2 = actor->GetPosition2Coordinate();
c1 = vtkCoordinate::New();
c2 = vtkCoordinate::New();
c1->SetCoordinateSystem(n1->GetCoordinateSystem());
c1->SetReferenceCoordinate(n1->GetReferenceCoordinate());
c1->SetReferenceCoordinate(n1->GetReferenceCoordinate());
c1->SetValue(n1->GetValue());
c2->SetCoordinateSystem(n2->GetCoordinateSystem());
c2->SetReferenceCoordinate(n2->GetReferenceCoordinate());
c2->SetValue(n2->GetValue());
this->storedData->coord1s->AddItem(c1);
this->storedData->coord2s->AddItem(c2);
c1->Delete();
c2->Delete();
// work out the position in new magnified pixels
p1 = n1->GetComputedDisplayValue(aren);
p2 = n2->GetComputedDisplayValue(aren);
d1[0] = p1[0]*this->Magnification;
d1[1] = p1[1]*this->Magnification;
d1[2] = 0.0;
d2[0] = p2[0]*this->Magnification;
d2[1] = p2[1]*this->Magnification;
d2[2] = 0.0;
this->storedData->coords1.push_back(
vtkstd::pair<int, int>(d1[0], d1[1]) );
this->storedData->coords2.push_back(
vtkstd::pair<int, int>(d2[0], d2[1]) );
// Make sure they have no dodgy offsets
n1->SetCoordinateSystemToDisplay();
n2->SetCoordinateSystemToDisplay();
n1->SetReferenceCoordinate(NULL);
n2->SetReferenceCoordinate(NULL);
n1->SetValue(d1[0], d1[1]);
n2->SetValue(d2[0], d2[1]);
//
}
}
}
}
return;
}
//----------------------------------------------------------------------------
// On each tile we must subtract the origin of each actor to ensure
// it appears in the correct relative location
void vtkRenderLargeImage::Shift2DActors(int x, int y)
{
vtkActor2D *actor;
vtkCoordinate *c1, *c2;
double d1[3], d2[3];
int i;
//
for (this->storedData->storedActors->InitTraversal(), i=0; (actor = this->storedData->storedActors->GetNextItem()); i++)
{
c1 = actor->GetPositionCoordinate();
c2 = actor->GetPosition2Coordinate();
c1->GetValue(d1);
c2->GetValue(d2);
d1[0] = this->storedData->coords1[i].first - x;
d1[1] = this->storedData->coords1[i].second - y;
d2[0] = this->storedData->coords2[i].first - x;
d2[1] = this->storedData->coords2[i].second - y;
c1->SetValue(d1);
c2->SetValue(d2);
}
return;
}
//----------------------------------------------------------------------------
// On each tile we must subtract the origin of each actor to ensure
// it appears in the corrrect relative location
void vtkRenderLargeImage::Restore2DActors()
{
vtkActor2D *actor;
vtkCoordinate *c1, *c2;
vtkCoordinate *n1, *n2;
int i;
//
for (this->storedData->storedActors->InitTraversal(), i=0; (actor = this->storedData->storedActors->GetNextItem()); i++)
{
c1 = actor->GetPositionCoordinate();
c2 = actor->GetPosition2Coordinate();
n1 = vtkCoordinate::SafeDownCast(this->storedData->coord1s->GetItemAsObject(i));
n2 = vtkCoordinate::SafeDownCast(this->storedData->coord2s->GetItemAsObject(i));
c1->SetCoordinateSystem(n1->GetCoordinateSystem());
c1->SetReferenceCoordinate(n1->GetReferenceCoordinate());
c1->SetReferenceCoordinate(n1->GetReferenceCoordinate());
c1->SetValue(n1->GetValue());
c2->SetCoordinateSystem(n2->GetCoordinateSystem());
c2->SetReferenceCoordinate(n2->GetReferenceCoordinate());
c2->SetValue(n2->GetValue());
}
this->storedData->coord1s->RemoveAllItems();
this->storedData->coord2s->RemoveAllItems();
this->storedData->storedActors->RemoveAllItems();
}
//----------------------------------------------------------------------------
|
/*=========================================================================
Program: Visualization Toolkit
Module: vtkRenderLargeImage.cxx
Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen
All rights reserved.
See Copyright.txt or http://www.kitware.com/Copyright.htm for details.
This software is distributed WITHOUT ANY WARRANTY; without even
the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
PURPOSE. See the above copyright notice for more information.
=========================================================================*/
#include "vtkRenderLargeImage.h"
#include "vtkCamera.h"
#include "vtkImageData.h"
#include "vtkInformation.h"
#include "vtkInformationVector.h"
#include "vtkObjectFactory.h"
#include "vtkStreamingDemandDrivenPipeline.h"
#include "vtkRenderWindow.h"
#include "vtkRenderer.h"
#include "vtkRendererCollection.h"
#include "vtkActor2DCollection.h"
#include "vtkActor2D.h"
#include "vtkProp.h"
#include <vtkstd/vector>
//----------------------------------------------------------------------------
vtkCxxRevisionMacro(vtkRenderLargeImage, "1.33");
vtkStandardNewMacro(vtkRenderLargeImage);
vtkCxxSetObjectMacro(vtkRenderLargeImage,Input,vtkRenderer);
//----------------------------------------------------------------------------
// 2D Actors need to be rescaled and shifted about for each tile
// use this helper class to make life easier.
class vtkRenderLargeImage2DHelperClass {
public:
// maintain a list of 2D actors
vtkActor2DCollection *storedActors;
// maintain lists of their vtkCoordinate objects
vtkCollection *coord1s;
vtkCollection *coord2s;
// Store the display coords for adjustment during tiling
vtkstd::vector< vtkstd::pair<int, int> > coords1;
vtkstd::vector< vtkstd::pair<int, int> > coords2;
//
vtkRenderLargeImage2DHelperClass()
{
storedActors = vtkActor2DCollection::New();
coord1s = vtkCollection::New();
coord2s = vtkCollection::New();
}
~vtkRenderLargeImage2DHelperClass()
{
coord1s->RemoveAllItems();
coord2s->RemoveAllItems();
storedActors->RemoveAllItems();
coord1s->Delete();
coord2s->Delete();
storedActors->Delete();
}
};
//----------------------------------------------------------------------------
vtkRenderLargeImage::vtkRenderLargeImage()
{
this->Input = NULL;
this->Magnification = 3;
this->SetNumberOfInputPorts(0);
this->SetNumberOfOutputPorts(1);
this->storedData = new vtkRenderLargeImage2DHelperClass();
}
//----------------------------------------------------------------------------
vtkRenderLargeImage::~vtkRenderLargeImage()
{
if (this->Input)
{
this->Input->UnRegister(this);
this->Input = NULL;
}
delete this->storedData;
}
//----------------------------------------------------------------------------
void vtkRenderLargeImage::PrintSelf(ostream& os, vtkIndent indent)
{
this->Superclass::PrintSelf(os,indent);
if ( this->Input )
{
os << indent << "Input:\n";
this->Input->PrintSelf(os,indent.GetNextIndent());
}
else
{
os << indent << "Input: (none)\n";
}
os << indent << "Magnification: " << this->Magnification << "\n";
}
//----------------------------------------------------------------------------
vtkImageData* vtkRenderLargeImage::GetOutput()
{
return vtkImageData::SafeDownCast(this->GetOutputDataObject(0));
}
//----------------------------------------------------------------------------
int vtkRenderLargeImage::ProcessRequest(vtkInformation* request,
vtkInformationVector** inputVector,
vtkInformationVector* outputVector)
{
// generate the data
if(request->Has(vtkDemandDrivenPipeline::REQUEST_DATA()))
{
this->RequestData(request, inputVector, outputVector);
return 1;
}
// execute information
if(request->Has(vtkDemandDrivenPipeline::REQUEST_INFORMATION()))
{
this->RequestInformation(request, inputVector, outputVector);
return 1;
}
return this->Superclass::ProcessRequest(request, inputVector, outputVector);
}
//----------------------------------------------------------------------------
// Description:
// This method returns the largest region that can be generated.
void vtkRenderLargeImage::RequestInformation (
vtkInformation * vtkNotUsed(request),
vtkInformationVector ** vtkNotUsed( inputVector ),
vtkInformationVector *outputVector)
{
// get the info objects
vtkInformation* outInfo = outputVector->GetInformationObject(0);
if (this->Input == NULL )
{
vtkErrorMacro(<<"Please specify a renderer as input!");
return;
}
// set the extent, if the VOI has not been set then default to
int wExt[6];
wExt[0] = 0; wExt[2] = 0; wExt[4] = 0; wExt[5] = 0;
wExt[1] = this->Magnification*
this->Input->GetRenderWindow()->GetSize()[0] - 1;
wExt[3] = this->Magnification*
this->Input->GetRenderWindow()->GetSize()[1] - 1;
outInfo->Set(vtkStreamingDemandDrivenPipeline::WHOLE_EXTENT(), wExt, 6);
// set the spacing
outInfo->Set(vtkDataObject::SPACING(),1.0, 1.0, 1.0);
// set the origin.
outInfo->Set(vtkDataObject::ORIGIN(),0.0, 0.0, 0.0);
// set the scalar components
vtkDataObject::SetPointDataActiveScalarInfo(outInfo, VTK_UNSIGNED_CHAR, 3);
}
//----------------------------------------------------------------------------
// Description:
// This function reads a region from a file. The regions extent/axes
// are assumed to be the same as the file extent/order.
void vtkRenderLargeImage::RequestData(
vtkInformation* vtkNotUsed( request ),
vtkInformationVector** vtkNotUsed( inputVector ),
vtkInformationVector* outputVector)
{
vtkInformation *outInfo = outputVector->GetInformationObject(0);
vtkImageData *data =
vtkImageData::SafeDownCast(outInfo->Get(vtkDataObject::DATA_OBJECT()));
data->SetExtent(data->GetUpdateExtent());
data->AllocateScalars();
int inExtent[6];
int inIncr[3];
int *size;
int inWindowExtent[4];
double viewAngle, parallelScale, windowCenter[2];
vtkCamera *cam;
unsigned char *pixels, *outPtr;
int x, y, row;
int rowSize, rowStart, rowEnd, colStart, colEnd;
int doublebuffer;
int swapbuffers = 0;
if (this->GetOutput()->GetScalarType() != VTK_UNSIGNED_CHAR)
{
vtkErrorMacro("mismatch in scalar types!");
return;
}
// Get the requested extents.
this->GetOutput()->GetUpdateExtent(inExtent);
// get and transform the increments
data->GetIncrements(inIncr);
// get the size of the render window
size = this->Input->GetRenderWindow()->GetSize();
// convert the request into windows
inWindowExtent[0] = inExtent[0]/size[0];
inWindowExtent[1] = inExtent[1]/size[0];
inWindowExtent[2] = inExtent[2]/size[1];
inWindowExtent[3] = inExtent[3]/size[1];
this->Rescale2DActors();
// store the old view angle & set the new
cam = this->Input->GetActiveCamera();
cam->GetWindowCenter(windowCenter);
viewAngle = cam->GetViewAngle();
parallelScale = cam->GetParallelScale();
cam->SetViewAngle(asin(sin(viewAngle*3.1415926/360.0)/this->Magnification)
* 360.0 / 3.1415926);
cam->SetParallelScale(parallelScale/this->Magnification);
// are we double buffering? If so, read from back buffer ....
doublebuffer = this->Input->GetRenderWindow()->GetDoubleBuffer();
if (doublebuffer)
{
// save swap buffer state to restore later
swapbuffers = this->Input->GetRenderWindow()->GetSwapBuffers();
this->Input->GetRenderWindow()->SetSwapBuffers(0);
}
// render each of the tiles required to fill this request
for (y = inWindowExtent[2]; y <= inWindowExtent[3]; y++)
{
for (x = inWindowExtent[0]; x <= inWindowExtent[1]; x++)
{
cam->SetWindowCenter(x*2 - this->Magnification*(1-windowCenter[0]) + 1,
y*2 - this->Magnification*(1-windowCenter[1]) + 1);
// shift 2D actors to correct origin for this tile
this->Shift2DActors(size[0]*x, size[1]*y);
// Render
this->Input->GetRenderWindow()->Render();
pixels = this->Input->GetRenderWindow()->GetPixelData(0,0,size[0] - 1,
size[1] - 1,
!doublebuffer);
// now stuff the pixels into the data row by row
colStart = inExtent[0] - x*size[0];
if (colStart < 0)
{
colStart = 0;
}
colEnd = size[0] - 1;
if (colEnd > (inExtent[1] - x*size[0]))
{
colEnd = inExtent[1] - x*size[0];
}
rowSize = colEnd - colStart + 1;
// get the output pointer and do arith on it if necc
outPtr =
(unsigned char *)data->GetScalarPointer(inExtent[0],inExtent[2],0);
outPtr = outPtr + (x*size[0] - inExtent[0])*inIncr[0] +
(y*size[1] - inExtent[2])*inIncr[1];
rowStart = inExtent[2] - y*size[1];
if (rowStart < 0)
{
rowStart = 0;
}
rowEnd = size[1] - 1;
if (rowEnd > (inExtent[3] - y*size[1]))
{
rowEnd = (inExtent[3] - y*size[1]);
}
for (row = rowStart; row <= rowEnd; row++)
{
memcpy(outPtr + row*inIncr[1] + colStart*inIncr[0],
pixels + row*size[0]*3 + colStart*3, rowSize*3);
}
// free the memory
delete [] pixels;
}
}
// restore the state of the SwapBuffers bit before we mucked with it.
if (doublebuffer && swapbuffers)
{
this->Input->GetRenderWindow()->SetSwapBuffers(swapbuffers);
}
cam->SetViewAngle(viewAngle);
cam->SetParallelScale(parallelScale);
cam->SetWindowCenter(windowCenter[0],windowCenter[1]);
this->Restore2DActors();
}
//----------------------------------------------------------------------------
int vtkRenderLargeImage::FillOutputPortInformation(
int vtkNotUsed(port), vtkInformation* info)
{
// now add our info
info->Set(vtkDataObject::DATA_TYPE_NAME(), "vtkImageData");
return 1;
}
//----------------------------------------------------------------------------
// This code is designed to handle multiple renders even though
// RenderLargeImage currently only handles one explicitly.
//----------------------------------------------------------------------------
void vtkRenderLargeImage::Rescale2DActors()
{
vtkActor2D *actor;
vtkProp *aProp;
vtkRenderer *aren;
vtkPropCollection *pc;
vtkRendererCollection *rc;
vtkCoordinate *c1, *c2;
vtkCoordinate *n1, *n2;
int *p1, *p2;
double d1[3], d2[3];
//
rc = this->Input->GetRenderWindow()->GetRenderers();
for (rc->InitTraversal(); (aren = rc->GetNextItem()); )
{
pc = aren->GetProps();
if (pc)
{
for ( pc->InitTraversal(); (aProp = pc->GetNextProp()); )
{
actor = vtkActor2D::SafeDownCast((aProp));
if (actor)
{
// put the actor in our list for retrieval later
this->storedData->storedActors->AddItem(actor);
// Copy all existing coordinate stuff
n1 = actor->GetPositionCoordinate();
n2 = actor->GetPosition2Coordinate();
c1 = vtkCoordinate::New();
c2 = vtkCoordinate::New();
c1->SetCoordinateSystem(n1->GetCoordinateSystem());
c1->SetReferenceCoordinate(n1->GetReferenceCoordinate());
c1->SetReferenceCoordinate(n1->GetReferenceCoordinate());
c1->SetValue(n1->GetValue());
c2->SetCoordinateSystem(n2->GetCoordinateSystem());
c2->SetReferenceCoordinate(n2->GetReferenceCoordinate());
c2->SetValue(n2->GetValue());
this->storedData->coord1s->AddItem(c1);
this->storedData->coord2s->AddItem(c2);
c1->Delete();
c2->Delete();
// work out the position in new magnified pixels
p1 = n1->GetComputedDisplayValue(aren);
p2 = n2->GetComputedDisplayValue(aren);
d1[0] = p1[0]*this->Magnification;
d1[1] = p1[1]*this->Magnification;
d1[2] = 0.0;
d2[0] = p2[0]*this->Magnification;
d2[1] = p2[1]*this->Magnification;
d2[2] = 0.0;
this->storedData->coords1.push_back(
vtkstd::pair<int, int>(static_cast<int>(d1[0]), static_cast<int>(d1[1])) );
this->storedData->coords2.push_back(
vtkstd::pair<int, int>(static_cast<int>(d2[0]), static_cast<int>(d2[1])) );
// Make sure they have no dodgy offsets
n1->SetCoordinateSystemToDisplay();
n2->SetCoordinateSystemToDisplay();
n1->SetReferenceCoordinate(NULL);
n2->SetReferenceCoordinate(NULL);
n1->SetValue(d1[0], d1[1]);
n2->SetValue(d2[0], d2[1]);
//
}
}
}
}
return;
}
//----------------------------------------------------------------------------
// On each tile we must subtract the origin of each actor to ensure
// it appears in the correct relative location
void vtkRenderLargeImage::Shift2DActors(int x, int y)
{
vtkActor2D *actor;
vtkCoordinate *c1, *c2;
double d1[3], d2[3];
int i;
//
for (this->storedData->storedActors->InitTraversal(), i=0; (actor = this->storedData->storedActors->GetNextItem()); i++)
{
c1 = actor->GetPositionCoordinate();
c2 = actor->GetPosition2Coordinate();
c1->GetValue(d1);
c2->GetValue(d2);
d1[0] = this->storedData->coords1[i].first - x;
d1[1] = this->storedData->coords1[i].second - y;
d2[0] = this->storedData->coords2[i].first - x;
d2[1] = this->storedData->coords2[i].second - y;
c1->SetValue(d1);
c2->SetValue(d2);
}
return;
}
//----------------------------------------------------------------------------
// On each tile we must subtract the origin of each actor to ensure
// it appears in the corrrect relative location
void vtkRenderLargeImage::Restore2DActors()
{
vtkActor2D *actor;
vtkCoordinate *c1, *c2;
vtkCoordinate *n1, *n2;
int i;
//
for (this->storedData->storedActors->InitTraversal(), i=0; (actor = this->storedData->storedActors->GetNextItem()); i++)
{
c1 = actor->GetPositionCoordinate();
c2 = actor->GetPosition2Coordinate();
n1 = vtkCoordinate::SafeDownCast(this->storedData->coord1s->GetItemAsObject(i));
n2 = vtkCoordinate::SafeDownCast(this->storedData->coord2s->GetItemAsObject(i));
c1->SetCoordinateSystem(n1->GetCoordinateSystem());
c1->SetReferenceCoordinate(n1->GetReferenceCoordinate());
c1->SetReferenceCoordinate(n1->GetReferenceCoordinate());
c1->SetValue(n1->GetValue());
c2->SetCoordinateSystem(n2->GetCoordinateSystem());
c2->SetReferenceCoordinate(n2->GetReferenceCoordinate());
c2->SetValue(n2->GetValue());
}
this->storedData->coord1s->RemoveAllItems();
this->storedData->coord2s->RemoveAllItems();
this->storedData->storedActors->RemoveAllItems();
}
//----------------------------------------------------------------------------
|
Remove warnings
|
COMP: Remove warnings
|
C++
|
bsd-3-clause
|
arnaudgelas/VTK,biddisco/VTK,mspark93/VTK,SimVascular/VTK,johnkit/vtk-dev,Wuteyan/VTK,jmerkow/VTK,jmerkow/VTK,collects/VTK,berendkleinhaneveld/VTK,aashish24/VTK-old,jeffbaumes/jeffbaumes-vtk,mspark93/VTK,Wuteyan/VTK,jmerkow/VTK,hendradarwin/VTK,collects/VTK,arnaudgelas/VTK,berendkleinhaneveld/VTK,Wuteyan/VTK,msmolens/VTK,cjh1/VTK,candy7393/VTK,jeffbaumes/jeffbaumes-vtk,collects/VTK,ashray/VTK-EVM,demarle/VTK,hendradarwin/VTK,Wuteyan/VTK,gram526/VTK,sankhesh/VTK,candy7393/VTK,keithroe/vtkoptix,biddisco/VTK,sumedhasingla/VTK,naucoin/VTKSlicerWidgets,aashish24/VTK-old,mspark93/VTK,naucoin/VTKSlicerWidgets,sankhesh/VTK,johnkit/vtk-dev,candy7393/VTK,sgh/vtk,berendkleinhaneveld/VTK,spthaolt/VTK,sgh/vtk,candy7393/VTK,keithroe/vtkoptix,ashray/VTK-EVM,mspark93/VTK,demarle/VTK,candy7393/VTK,SimVascular/VTK,berendkleinhaneveld/VTK,sgh/vtk,cjh1/VTK,ashray/VTK-EVM,johnkit/vtk-dev,sankhesh/VTK,naucoin/VTKSlicerWidgets,johnkit/vtk-dev,gram526/VTK,ashray/VTK-EVM,demarle/VTK,johnkit/vtk-dev,gram526/VTK,naucoin/VTKSlicerWidgets,cjh1/VTK,ashray/VTK-EVM,msmolens/VTK,SimVascular/VTK,sankhesh/VTK,sumedhasingla/VTK,sankhesh/VTK,collects/VTK,keithroe/vtkoptix,keithroe/vtkoptix,sumedhasingla/VTK,johnkit/vtk-dev,ashray/VTK-EVM,demarle/VTK,daviddoria/PointGraphsPhase1,jmerkow/VTK,msmolens/VTK,keithroe/vtkoptix,sgh/vtk,spthaolt/VTK,daviddoria/PointGraphsPhase1,Wuteyan/VTK,hendradarwin/VTK,demarle/VTK,sumedhasingla/VTK,SimVascular/VTK,keithroe/vtkoptix,sankhesh/VTK,jeffbaumes/jeffbaumes-vtk,daviddoria/PointGraphsPhase1,berendkleinhaneveld/VTK,Wuteyan/VTK,biddisco/VTK,sgh/vtk,gram526/VTK,ashray/VTK-EVM,johnkit/vtk-dev,mspark93/VTK,msmolens/VTK,sumedhasingla/VTK,jmerkow/VTK,jmerkow/VTK,arnaudgelas/VTK,aashish24/VTK-old,biddisco/VTK,candy7393/VTK,aashish24/VTK-old,sumedhasingla/VTK,spthaolt/VTK,daviddoria/PointGraphsPhase1,biddisco/VTK,hendradarwin/VTK,jmerkow/VTK,spthaolt/VTK,jeffbaumes/jeffbaumes-vtk,jeffbaumes/jeffbaumes-vtk,SimVascular/VTK,spthaolt/VTK,collects/VTK,spthaolt/VTK,arnaudgelas/VTK,jmerkow/VTK,msmolens/VTK,Wuteyan/VTK,naucoin/VTKSlicerWidgets,sgh/vtk,daviddoria/PointGraphsPhase1,keithroe/vtkoptix,berendkleinhaneveld/VTK,berendkleinhaneveld/VTK,naucoin/VTKSlicerWidgets,mspark93/VTK,hendradarwin/VTK,msmolens/VTK,collects/VTK,hendradarwin/VTK,gram526/VTK,demarle/VTK,SimVascular/VTK,aashish24/VTK-old,mspark93/VTK,sumedhasingla/VTK,spthaolt/VTK,jeffbaumes/jeffbaumes-vtk,msmolens/VTK,biddisco/VTK,daviddoria/PointGraphsPhase1,SimVascular/VTK,cjh1/VTK,candy7393/VTK,hendradarwin/VTK,demarle/VTK,keithroe/vtkoptix,demarle/VTK,ashray/VTK-EVM,sumedhasingla/VTK,cjh1/VTK,arnaudgelas/VTK,mspark93/VTK,biddisco/VTK,aashish24/VTK-old,candy7393/VTK,sankhesh/VTK,sankhesh/VTK,gram526/VTK,gram526/VTK,arnaudgelas/VTK,msmolens/VTK,gram526/VTK,cjh1/VTK,SimVascular/VTK
|
6580a4ba29093acddab87653776aeb6dd8f324a6
|
include/person.hpp
|
include/person.hpp
|
#include <string>
const size_t n_literals = 27;
size_t letterI(const char letter, const bool is_capital) {
int first_letter_code = static_cast<int>(is_capital ? 'A' : 'a');
size_t result = static_cast<int>(letter) - first_letter_code + 1;
return result;
}
struct person {
char * str;
unsigned char name_i;
unsigned char name_length;
person() : str(nullptr) {
;
}
size_t i(size_t sort_i) const {
if (sort_i < name_length) {
return letterI(str[name_i + sort_i], sort_i == 0);
}
else {
return 0;
}
}
char * getName() {
char * temp = new char[name_length + 1];
strncpy(temp, &(str[name_i]), name_length);
temp[name_length] = '\0';
return temp;
} //Boost
void putStr(std::string const & _str) {
str = new char[_str.length() + 1];
strncpy(str, _str, _str.length());
str[_str.length()] = '\0';
}
~person() {
delete[] str;
}
};
std::ostream & operator<<(std::ostream & output, person const & _person)
{
output << _person.str << " ";
return output;
}
std::istream & operator>>(std::istream & input, person & _person)
{
input >> _person.str;
/*input >> _person.name;
input >> _person.year;*/
return input;
}
|
#include <string>
const size_t n_literals = 27;
size_t letterI(const char letter, const bool is_capital) {
int first_letter_code = static_cast<int>(is_capital ? 'A' : 'a');
size_t result = static_cast<int>(letter) - first_letter_code + 1;
return result;
}
struct person {
char * str;
unsigned char name_i;
unsigned char name_length;
person() : str(nullptr) {
;
}
size_t i(size_t sort_i) const {
if (sort_i < name_length) {
return letterI(str[name_i + sort_i], sort_i == 0);
}
else {
return 0;
}
}
char * getName() {
char * temp = new char[name_length + 1];
strncpy(temp, &(str[name_i]), name_length);
temp[name_length] = '\0';
return temp;
} //Boost
void putStr(std::string const & _str) {
str = new char[_str.length() + 1];
strncpy(str, _str.c_str(), _str.length());
str[_str.length()] = '\0';
}
~person() {
delete[] str;
}
};
std::ostream & operator<<(std::ostream & output, person const & _person)
{
output << _person.str << " ";
return output;
}
std::istream & operator>>(std::istream & input, person & _person)
{
input >> _person.str;
/*input >> _person.name;
input >> _person.year;*/
return input;
}
|
Update person.hpp
|
Update person.hpp
|
C++
|
mit
|
ArtemKokorinStudent/External-sort
|
51808a91fef99c0d0849f143f772cb1bbc11f2e4
|
chrome_frame/test/proxy_factory_mock.cc
|
chrome_frame/test/proxy_factory_mock.cc
|
// Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "base/compiler_specific.h"
#include "base/synchronization/waitable_event.h"
#include "chrome/common/chrome_paths_internal.h"
#include "chrome_frame/crash_reporting/crash_metrics.h"
#include "chrome_frame/test/chrome_frame_test_utils.h"
#include "chrome_frame/test/proxy_factory_mock.h"
#include "chrome_frame/test/test_scrubber.h"
#define GMOCK_MUTANT_INCLUDE_LATE_OBJECT_BINDING
#include "testing/gmock_mutant.h"
using testing::CreateFunctor;
using testing::_;
class ProxyFactoryTest : public testing::Test {
protected:
virtual void SetUp() OVERRIDE;
ChromeFrameLaunchParams* MakeLaunchParams(const wchar_t* profile_name);
ProxyFactory proxy_factory_;
LaunchDelegateMock launch_delegate_mock_;
};
void ProxyFactoryTest::SetUp() {
CrashMetricsReporter::GetInstance()->set_active(true);
}
ChromeFrameLaunchParams* ProxyFactoryTest::MakeLaunchParams(
const wchar_t* profile_name) {
GURL empty;
FilePath profile_path(chrome_frame_test::GetProfilePath(profile_name));
chrome_frame_test::OverrideDataDirectoryForThisTest(profile_path.value());
ChromeFrameLaunchParams* params =
new ChromeFrameLaunchParams(empty, empty, profile_path,
profile_path.BaseName().value(), L"", false,
false, false, false);
params->set_launch_timeout(0);
params->set_version_check(false);
return params;
}
TEST_F(ProxyFactoryTest, CreateDestroy) {
EXPECT_CALL(launch_delegate_mock_,
LaunchComplete(testing::NotNull(), testing::_)).Times(1);
scoped_refptr<ChromeFrameLaunchParams> params(
MakeLaunchParams(L"Adam.N.Epilinter"));
void* id = NULL;
proxy_factory_.GetAutomationServer(&launch_delegate_mock_, params, &id);
proxy_factory_.ReleaseAutomationServer(id, &launch_delegate_mock_);
}
TEST_F(ProxyFactoryTest, CreateSameProfile) {
LaunchDelegateMock d2;
EXPECT_CALL(launch_delegate_mock_,
LaunchComplete(testing::NotNull(), testing::_)).Times(1);
EXPECT_CALL(d2, LaunchComplete(testing::NotNull(), testing::_)).Times(1);
scoped_refptr<ChromeFrameLaunchParams> params(
MakeLaunchParams(L"Dr. Gratiano Forbeson"));
void* i1 = NULL;
void* i2 = NULL;
proxy_factory_.GetAutomationServer(&launch_delegate_mock_, params, &i1);
proxy_factory_.GetAutomationServer(&d2, params, &i2);
EXPECT_EQ(i1, i2);
proxy_factory_.ReleaseAutomationServer(i2, &d2);
proxy_factory_.ReleaseAutomationServer(i1, &launch_delegate_mock_);
}
TEST_F(ProxyFactoryTest, CreateDifferentProfiles) {
EXPECT_CALL(launch_delegate_mock_,
LaunchComplete(testing::NotNull(), testing::_)).Times(2);
scoped_refptr<ChromeFrameLaunchParams> params1(
MakeLaunchParams(L"Adam.N.Epilinter"));
scoped_refptr<ChromeFrameLaunchParams> params2(
MakeLaunchParams(L"Dr. Gratiano Forbeson"));
void* i1 = NULL;
void* i2 = NULL;
proxy_factory_.GetAutomationServer(&launch_delegate_mock_, params1, &i1);
proxy_factory_.GetAutomationServer(&launch_delegate_mock_, params2, &i2);
EXPECT_NE(i1, i2);
proxy_factory_.ReleaseAutomationServer(i2, &launch_delegate_mock_);
proxy_factory_.ReleaseAutomationServer(i1, &launch_delegate_mock_);
}
// This test has been disabled because it crashes randomly on the builders.
// http://code.google.com/p/chromium/issues/detail?id=81039
TEST_F(ProxyFactoryTest, DISABLED_FastCreateDestroy) {
LaunchDelegateMock* d1 = &launch_delegate_mock_;
LaunchDelegateMock* d2 = new LaunchDelegateMock();
scoped_refptr<ChromeFrameLaunchParams> params(
MakeLaunchParams(L"Dr. Gratiano Forbeson"));
params->set_launch_timeout(10000);
void* i1 = NULL;
base::WaitableEvent launched(true, false);
EXPECT_CALL(*d1, LaunchComplete(testing::NotNull(), AUTOMATION_SUCCESS))
.WillOnce(testing::InvokeWithoutArgs(&launched,
&base::WaitableEvent::Signal));
proxy_factory_.GetAutomationServer(d1, params, &i1);
// Wait for launch
ASSERT_TRUE(launched.TimedWait(base::TimeDelta::FromSeconds(10)));
// Expect second launch to succeed too
EXPECT_CALL(*d2, LaunchComplete(testing::NotNull(), AUTOMATION_SUCCESS))
.Times(1);
// Boost thread priority so we call ReleaseAutomationServer before
// LaunchComplete callback have a chance to be executed.
::SetThreadPriority(::GetCurrentThread(), THREAD_PRIORITY_HIGHEST);
void* i2 = NULL;
proxy_factory_.GetAutomationServer(d2, params, &i2);
EXPECT_EQ(i1, i2);
proxy_factory_.ReleaseAutomationServer(i2, d2);
delete d2;
::SetThreadPriority(::GetCurrentThread(), THREAD_PRIORITY_NORMAL);
proxy_factory_.ReleaseAutomationServer(i1, d1);
}
|
// Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "base/compiler_specific.h"
#include "base/synchronization/waitable_event.h"
#include "chrome/common/chrome_paths_internal.h"
#include "chrome_frame/crash_reporting/crash_metrics.h"
#include "chrome_frame/test/chrome_frame_test_utils.h"
#include "chrome_frame/test/proxy_factory_mock.h"
#include "chrome_frame/test/test_scrubber.h"
#define GMOCK_MUTANT_INCLUDE_LATE_OBJECT_BINDING
#include "testing/gmock_mutant.h"
using testing::CreateFunctor;
using testing::_;
class ProxyFactoryTest : public testing::Test {
protected:
virtual void SetUp() OVERRIDE;
ChromeFrameLaunchParams* MakeLaunchParams(const wchar_t* profile_name);
ProxyFactory proxy_factory_;
LaunchDelegateMock launch_delegate_mock_;
};
void ProxyFactoryTest::SetUp() {
CrashMetricsReporter::GetInstance()->set_active(true);
}
ChromeFrameLaunchParams* ProxyFactoryTest::MakeLaunchParams(
const wchar_t* profile_name) {
GURL empty;
FilePath profile_path(chrome_frame_test::GetProfilePath(profile_name));
chrome_frame_test::OverrideDataDirectoryForThisTest(profile_path.value());
ChromeFrameLaunchParams* params =
new ChromeFrameLaunchParams(empty, empty, profile_path,
profile_path.BaseName().value(), L"", false,
false, false, false);
params->set_launch_timeout(0);
params->set_version_check(false);
return params;
}
TEST_F(ProxyFactoryTest, CreateDestroy) {
EXPECT_CALL(launch_delegate_mock_,
LaunchComplete(testing::NotNull(), testing::_)).Times(1);
scoped_refptr<ChromeFrameLaunchParams> params(
MakeLaunchParams(L"Adam.N.Epilinter"));
void* id = NULL;
proxy_factory_.GetAutomationServer(&launch_delegate_mock_, params, &id);
proxy_factory_.ReleaseAutomationServer(id, &launch_delegate_mock_);
}
TEST_F(ProxyFactoryTest, CreateSameProfile) {
LaunchDelegateMock d2;
EXPECT_CALL(launch_delegate_mock_,
LaunchComplete(testing::NotNull(), testing::_)).Times(1);
EXPECT_CALL(d2, LaunchComplete(testing::NotNull(), testing::_)).Times(1);
scoped_refptr<ChromeFrameLaunchParams> params(
MakeLaunchParams(L"Dr. Gratiano Forbeson"));
void* i1 = NULL;
void* i2 = NULL;
proxy_factory_.GetAutomationServer(&launch_delegate_mock_, params, &i1);
proxy_factory_.GetAutomationServer(&d2, params, &i2);
EXPECT_EQ(i1, i2);
proxy_factory_.ReleaseAutomationServer(i2, &d2);
proxy_factory_.ReleaseAutomationServer(i1, &launch_delegate_mock_);
}
TEST_F(ProxyFactoryTest, CreateDifferentProfiles) {
LaunchDelegateMock d2;
EXPECT_CALL(launch_delegate_mock_,
LaunchComplete(testing::NotNull(), testing::_));
EXPECT_CALL(d2, LaunchComplete(testing::NotNull(), testing::_));
scoped_refptr<ChromeFrameLaunchParams> params1(
MakeLaunchParams(L"Adam.N.Epilinter"));
scoped_refptr<ChromeFrameLaunchParams> params2(
MakeLaunchParams(L"Dr. Gratiano Forbeson"));
void* i1 = NULL;
void* i2 = NULL;
proxy_factory_.GetAutomationServer(&launch_delegate_mock_, params1, &i1);
proxy_factory_.GetAutomationServer(&d2, params2, &i2);
EXPECT_NE(i1, i2);
proxy_factory_.ReleaseAutomationServer(i2, &d2);
proxy_factory_.ReleaseAutomationServer(i1, &launch_delegate_mock_);
}
// This test has been disabled because it crashes randomly on the builders.
// http://code.google.com/p/chromium/issues/detail?id=81039
TEST_F(ProxyFactoryTest, DISABLED_FastCreateDestroy) {
LaunchDelegateMock* d1 = &launch_delegate_mock_;
LaunchDelegateMock* d2 = new LaunchDelegateMock();
scoped_refptr<ChromeFrameLaunchParams> params(
MakeLaunchParams(L"Dr. Gratiano Forbeson"));
params->set_launch_timeout(10000);
void* i1 = NULL;
base::WaitableEvent launched(true, false);
EXPECT_CALL(*d1, LaunchComplete(testing::NotNull(), AUTOMATION_SUCCESS))
.WillOnce(testing::InvokeWithoutArgs(&launched,
&base::WaitableEvent::Signal));
proxy_factory_.GetAutomationServer(d1, params, &i1);
// Wait for launch
ASSERT_TRUE(launched.TimedWait(base::TimeDelta::FromSeconds(10)));
// Expect second launch to succeed too
EXPECT_CALL(*d2, LaunchComplete(testing::NotNull(), AUTOMATION_SUCCESS))
.Times(1);
// Boost thread priority so we call ReleaseAutomationServer before
// LaunchComplete callback have a chance to be executed.
::SetThreadPriority(::GetCurrentThread(), THREAD_PRIORITY_HIGHEST);
void* i2 = NULL;
proxy_factory_.GetAutomationServer(d2, params, &i2);
EXPECT_EQ(i1, i2);
proxy_factory_.ReleaseAutomationServer(i2, d2);
delete d2;
::SetThreadPriority(::GetCurrentThread(), THREAD_PRIORITY_NORMAL);
proxy_factory_.ReleaseAutomationServer(i1, d1);
}
|
Fix flake in ProxyFactoryTest.CreateDifferentProfiles due to data race.
|
Fix flake in ProxyFactoryTest.CreateDifferentProfiles due to data race.
Google Mock isn't threadsafe on Windows!
BUG=122929
TEST=chrome_frame_tests.exe --gtest_filter=ProxyFactoryTest.CreateDifferentProfiles won't flake
Review URL: https://chromiumcodereview.appspot.com/10050014
git-svn-id: de016e52bd170d2d4f2344f9bf92d50478b649e0@131768 0039d316-1c4b-4281-b951-d872f2087c98
|
C++
|
bsd-3-clause
|
TheTypoMaster/chromium-crosswalk,zcbenz/cefode-chromium,keishi/chromium,patrickm/chromium.src,anirudhSK/chromium,hgl888/chromium-crosswalk-efl,markYoungH/chromium.src,bright-sparks/chromium-spacewalk,chuan9/chromium-crosswalk,anirudhSK/chromium,pozdnyakov/chromium-crosswalk,pozdnyakov/chromium-crosswalk,M4sse/chromium.src,PeterWangIntel/chromium-crosswalk,junmin-zhu/chromium-rivertrail,Pluto-tv/chromium-crosswalk,jaruba/chromium.src,robclark/chromium,axinging/chromium-crosswalk,mohamed--abdel-maksoud/chromium.src,M4sse/chromium.src,markYoungH/chromium.src,dednal/chromium.src,anirudhSK/chromium,ChromiumWebApps/chromium,keishi/chromium,chuan9/chromium-crosswalk,anirudhSK/chromium,jaruba/chromium.src,krieger-od/nwjs_chromium.src,Chilledheart/chromium,junmin-zhu/chromium-rivertrail,krieger-od/nwjs_chromium.src,zcbenz/cefode-chromium,markYoungH/chromium.src,dushu1203/chromium.src,junmin-zhu/chromium-rivertrail,Just-D/chromium-1,krieger-od/nwjs_chromium.src,markYoungH/chromium.src,ChromiumWebApps/chromium,mohamed--abdel-maksoud/chromium.src,junmin-zhu/chromium-rivertrail,hujiajie/pa-chromium,timopulkkinen/BubbleFish,ondra-novak/chromium.src,hgl888/chromium-crosswalk-efl,Just-D/chromium-1,axinging/chromium-crosswalk,bright-sparks/chromium-spacewalk,robclark/chromium,ondra-novak/chromium.src,mohamed--abdel-maksoud/chromium.src,mogoweb/chromium-crosswalk,robclark/chromium,patrickm/chromium.src,Jonekee/chromium.src,ltilve/chromium,pozdnyakov/chromium-crosswalk,mohamed--abdel-maksoud/chromium.src,littlstar/chromium.src,junmin-zhu/chromium-rivertrail,ondra-novak/chromium.src,crosswalk-project/chromium-crosswalk-efl,nacl-webkit/chrome_deps,hgl888/chromium-crosswalk-efl,patrickm/chromium.src,dushu1203/chromium.src,hgl888/chromium-crosswalk,PeterWangIntel/chromium-crosswalk,Chilledheart/chromium,nacl-webkit/chrome_deps,chuan9/chromium-crosswalk,M4sse/chromium.src,fujunwei/chromium-crosswalk,jaruba/chromium.src,littlstar/chromium.src,littlstar/chromium.src,keishi/chromium,TheTypoMaster/chromium-crosswalk,Pluto-tv/chromium-crosswalk,M4sse/chromium.src,chuan9/chromium-crosswalk,TheTypoMaster/chromium-crosswalk,dednal/chromium.src,Fireblend/chromium-crosswalk,hujiajie/pa-chromium,dednal/chromium.src,dednal/chromium.src,nacl-webkit/chrome_deps,Chilledheart/chromium,Just-D/chromium-1,Just-D/chromium-1,ChromiumWebApps/chromium,mohamed--abdel-maksoud/chromium.src,chuan9/chromium-crosswalk,nacl-webkit/chrome_deps,patrickm/chromium.src,hujiajie/pa-chromium,ondra-novak/chromium.src,ltilve/chromium,pozdnyakov/chromium-crosswalk,jaruba/chromium.src,robclark/chromium,mohamed--abdel-maksoud/chromium.src,bright-sparks/chromium-spacewalk,crosswalk-project/chromium-crosswalk-efl,crosswalk-project/chromium-crosswalk-efl,anirudhSK/chromium,pozdnyakov/chromium-crosswalk,hgl888/chromium-crosswalk,axinging/chromium-crosswalk,dednal/chromium.src,zcbenz/cefode-chromium,dushu1203/chromium.src,anirudhSK/chromium,TheTypoMaster/chromium-crosswalk,mogoweb/chromium-crosswalk,axinging/chromium-crosswalk,hgl888/chromium-crosswalk,anirudhSK/chromium,dushu1203/chromium.src,Fireblend/chromium-crosswalk,Fireblend/chromium-crosswalk,Pluto-tv/chromium-crosswalk,Chilledheart/chromium,TheTypoMaster/chromium-crosswalk,mohamed--abdel-maksoud/chromium.src,hujiajie/pa-chromium,patrickm/chromium.src,ondra-novak/chromium.src,crosswalk-project/chromium-crosswalk-efl,PeterWangIntel/chromium-crosswalk,bright-sparks/chromium-spacewalk,mogoweb/chromium-crosswalk,Just-D/chromium-1,timopulkkinen/BubbleFish,hgl888/chromium-crosswalk-efl,Just-D/chromium-1,hgl888/chromium-crosswalk,junmin-zhu/chromium-rivertrail,hujiajie/pa-chromium,junmin-zhu/chromium-rivertrail,keishi/chromium,ondra-novak/chromium.src,chuan9/chromium-crosswalk,crosswalk-project/chromium-crosswalk-efl,hgl888/chromium-crosswalk-efl,Jonekee/chromium.src,anirudhSK/chromium,pozdnyakov/chromium-crosswalk,pozdnyakov/chromium-crosswalk,ltilve/chromium,ChromiumWebApps/chromium,ondra-novak/chromium.src,krieger-od/nwjs_chromium.src,markYoungH/chromium.src,hgl888/chromium-crosswalk-efl,krieger-od/nwjs_chromium.src,crosswalk-project/chromium-crosswalk-efl,Chilledheart/chromium,dednal/chromium.src,Pluto-tv/chromium-crosswalk,patrickm/chromium.src,junmin-zhu/chromium-rivertrail,ChromiumWebApps/chromium,fujunwei/chromium-crosswalk,jaruba/chromium.src,mohamed--abdel-maksoud/chromium.src,ChromiumWebApps/chromium,mogoweb/chromium-crosswalk,dushu1203/chromium.src,timopulkkinen/BubbleFish,Chilledheart/chromium,hgl888/chromium-crosswalk-efl,mohamed--abdel-maksoud/chromium.src,bright-sparks/chromium-spacewalk,keishi/chromium,pozdnyakov/chromium-crosswalk,chuan9/chromium-crosswalk,bright-sparks/chromium-spacewalk,keishi/chromium,fujunwei/chromium-crosswalk,mohamed--abdel-maksoud/chromium.src,M4sse/chromium.src,Just-D/chromium-1,Jonekee/chromium.src,mogoweb/chromium-crosswalk,TheTypoMaster/chromium-crosswalk,fujunwei/chromium-crosswalk,bright-sparks/chromium-spacewalk,junmin-zhu/chromium-rivertrail,markYoungH/chromium.src,axinging/chromium-crosswalk,ltilve/chromium,Jonekee/chromium.src,PeterWangIntel/chromium-crosswalk,Fireblend/chromium-crosswalk,junmin-zhu/chromium-rivertrail,hujiajie/pa-chromium,mogoweb/chromium-crosswalk,ChromiumWebApps/chromium,TheTypoMaster/chromium-crosswalk,Pluto-tv/chromium-crosswalk,Chilledheart/chromium,mogoweb/chromium-crosswalk,keishi/chromium,fujunwei/chromium-crosswalk,M4sse/chromium.src,nacl-webkit/chrome_deps,robclark/chromium,jaruba/chromium.src,hujiajie/pa-chromium,fujunwei/chromium-crosswalk,ChromiumWebApps/chromium,Jonekee/chromium.src,Jonekee/chromium.src,ondra-novak/chromium.src,markYoungH/chromium.src,nacl-webkit/chrome_deps,Just-D/chromium-1,ltilve/chromium,timopulkkinen/BubbleFish,bright-sparks/chromium-spacewalk,robclark/chromium,nacl-webkit/chrome_deps,M4sse/chromium.src,dushu1203/chromium.src,ltilve/chromium,hgl888/chromium-crosswalk,krieger-od/nwjs_chromium.src,chuan9/chromium-crosswalk,hgl888/chromium-crosswalk-efl,timopulkkinen/BubbleFish,ltilve/chromium,littlstar/chromium.src,timopulkkinen/BubbleFish,markYoungH/chromium.src,ChromiumWebApps/chromium,dushu1203/chromium.src,zcbenz/cefode-chromium,crosswalk-project/chromium-crosswalk-efl,hgl888/chromium-crosswalk-efl,keishi/chromium,jaruba/chromium.src,Chilledheart/chromium,zcbenz/cefode-chromium,M4sse/chromium.src,Fireblend/chromium-crosswalk,timopulkkinen/BubbleFish,keishi/chromium,patrickm/chromium.src,littlstar/chromium.src,keishi/chromium,Jonekee/chromium.src,hgl888/chromium-crosswalk,M4sse/chromium.src,jaruba/chromium.src,dushu1203/chromium.src,mogoweb/chromium-crosswalk,axinging/chromium-crosswalk,nacl-webkit/chrome_deps,littlstar/chromium.src,nacl-webkit/chrome_deps,nacl-webkit/chrome_deps,jaruba/chromium.src,axinging/chromium-crosswalk,Fireblend/chromium-crosswalk,PeterWangIntel/chromium-crosswalk,Pluto-tv/chromium-crosswalk,dushu1203/chromium.src,junmin-zhu/chromium-rivertrail,anirudhSK/chromium,hgl888/chromium-crosswalk-efl,hujiajie/pa-chromium,TheTypoMaster/chromium-crosswalk,Chilledheart/chromium,dushu1203/chromium.src,markYoungH/chromium.src,bright-sparks/chromium-spacewalk,robclark/chromium,crosswalk-project/chromium-crosswalk-efl,robclark/chromium,zcbenz/cefode-chromium,ChromiumWebApps/chromium,krieger-od/nwjs_chromium.src,littlstar/chromium.src,axinging/chromium-crosswalk,Fireblend/chromium-crosswalk,Jonekee/chromium.src,zcbenz/cefode-chromium,PeterWangIntel/chromium-crosswalk,ChromiumWebApps/chromium,nacl-webkit/chrome_deps,Jonekee/chromium.src,dednal/chromium.src,hujiajie/pa-chromium,mogoweb/chromium-crosswalk,littlstar/chromium.src,dednal/chromium.src,markYoungH/chromium.src,pozdnyakov/chromium-crosswalk,axinging/chromium-crosswalk,Jonekee/chromium.src,timopulkkinen/BubbleFish,hujiajie/pa-chromium,ltilve/chromium,Fireblend/chromium-crosswalk,ondra-novak/chromium.src,ltilve/chromium,hgl888/chromium-crosswalk,jaruba/chromium.src,hgl888/chromium-crosswalk,zcbenz/cefode-chromium,krieger-od/nwjs_chromium.src,M4sse/chromium.src,keishi/chromium,chuan9/chromium-crosswalk,robclark/chromium,markYoungH/chromium.src,TheTypoMaster/chromium-crosswalk,hgl888/chromium-crosswalk,PeterWangIntel/chromium-crosswalk,mohamed--abdel-maksoud/chromium.src,Just-D/chromium-1,krieger-od/nwjs_chromium.src,anirudhSK/chromium,pozdnyakov/chromium-crosswalk,fujunwei/chromium-crosswalk,zcbenz/cefode-chromium,fujunwei/chromium-crosswalk,PeterWangIntel/chromium-crosswalk,Pluto-tv/chromium-crosswalk,PeterWangIntel/chromium-crosswalk,M4sse/chromium.src,Pluto-tv/chromium-crosswalk,krieger-od/nwjs_chromium.src,fujunwei/chromium-crosswalk,patrickm/chromium.src,zcbenz/cefode-chromium,timopulkkinen/BubbleFish,axinging/chromium-crosswalk,robclark/chromium,Jonekee/chromium.src,ChromiumWebApps/chromium,jaruba/chromium.src,dednal/chromium.src,anirudhSK/chromium,timopulkkinen/BubbleFish,krieger-od/nwjs_chromium.src,Pluto-tv/chromium-crosswalk,patrickm/chromium.src,dednal/chromium.src,crosswalk-project/chromium-crosswalk-efl,dushu1203/chromium.src,axinging/chromium-crosswalk,dednal/chromium.src,timopulkkinen/BubbleFish,anirudhSK/chromium,zcbenz/cefode-chromium,mogoweb/chromium-crosswalk,Fireblend/chromium-crosswalk,pozdnyakov/chromium-crosswalk,hujiajie/pa-chromium
|
9c8dc099962ab204e37c388c70cd5042a2836f78
|
deps/ox/src/ox/std/assert.cpp
|
deps/ox/src/ox/std/assert.cpp
|
/*
* Copyright 2015 - 2018 [email protected]
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/.
*/
#if defined(OX_USE_STDLIB)
#include <bitset>
#include <iostream>
#endif
#include "defines.hpp"
#include "stacktrace.hpp"
#include "trace.hpp"
#include "assert.hpp"
namespace ox {
template<>
void assertFunc<bool>([[maybe_unused]]const char *file, [[maybe_unused]]int line, [[maybe_unused]]bool pass, [[maybe_unused]]const char *msg) {
#if defined(OX_USE_STDLIB)
if (!pass) {
std::cerr << "\033[31;1;1mASSERT FAILURE:\033[0m (" << file << ':' << line << "): " << msg << std::endl;
printStackTrace(2);
oxTrace("assert").del("") << "Failed assert: " << msg << " (" << file << ":" << line << ")";
std::abort();
}
#endif
}
template<>
void assertFunc<Error>(const char *file, int line, Error err, const char *assertMsg) {
if (err) {
#if defined(OX_USE_STDLIB)
std::cerr << "\033[31;1;1mASSERT FAILURE:\033[0m (" << file << ':' << line << "): " << assertMsg << '\n';
if (err.msg) {
std::cerr << "\tError Message:\t" << err.msg << '\n';
}
std::cerr << "\tError Code:\t" << err << '\n';
if (err.file != nullptr) {
std::cerr << "\tError Location:\t" << reinterpret_cast<const char*>(err.file) << ':' << err.line << '\n';
}
printStackTrace(2);
oxTrace("panic").del("") << "Panic: " << assertMsg << " (" << file << ":" << line << ")";
std::abort();
#else
panic(file, line, assertMsg);
#endif
}
}
#if defined(OX_USE_STDLIB)
void panic(const char *file, int line, const char *panicMsg, Error err) {
std::cerr << "\033[31;1;1mPANIC:\033[0m (" << file << ':' << line << "): " << panicMsg << '\n';
if (err.msg) {
std::cerr << "\tError Message:\t" << err.msg << '\n';
}
std::cerr << "\tError Code:\t" << err << '\n';
if (err.file != nullptr) {
std::cerr << "\tError Location:\t" << reinterpret_cast<const char*>(err.file) << ':' << err.line << '\n';
}
printStackTrace(2);
oxTrace("panic").del("") << "Panic: " << panicMsg << " (" << file << ":" << line << ")";
std::abort();
}
#endif
}
|
/*
* Copyright 2015 - 2018 [email protected]
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/.
*/
#if defined(OX_USE_STDLIB)
#include <bitset>
#include <iostream>
#endif
#include "defines.hpp"
#include "stacktrace.hpp"
#include "trace.hpp"
#include "assert.hpp"
namespace ox {
template<>
void assertFunc<bool>([[maybe_unused]]const char *file, [[maybe_unused]]int line, [[maybe_unused]]bool pass, [[maybe_unused]]const char *msg) {
if (!pass) {
#if defined(OX_USE_STDLIB)
std::cerr << "\033[31;1;1mASSERT FAILURE:\033[0m (" << file << ':' << line << "): " << msg << std::endl;
printStackTrace(2);
oxTrace("assert").del("") << "Failed assert: " << msg << " (" << file << ":" << line << ")";
std::abort();
#else
panic(file, line, msg);
#endif
}
}
template<>
void assertFunc<Error>(const char *file, int line, Error err, const char *assertMsg) {
if (err) {
#if defined(OX_USE_STDLIB)
std::cerr << "\033[31;1;1mASSERT FAILURE:\033[0m (" << file << ':' << line << "): " << assertMsg << '\n';
if (err.msg) {
std::cerr << "\tError Message:\t" << err.msg << '\n';
}
std::cerr << "\tError Code:\t" << err << '\n';
if (err.file != nullptr) {
std::cerr << "\tError Location:\t" << reinterpret_cast<const char*>(err.file) << ':' << err.line << '\n';
}
printStackTrace(2);
oxTrace("panic").del("") << "Panic: " << assertMsg << " (" << file << ":" << line << ")";
std::abort();
#else
panic(file, line, assertMsg);
#endif
}
}
#if defined(OX_USE_STDLIB)
void panic(const char *file, int line, const char *panicMsg, Error err) {
std::cerr << "\033[31;1;1mPANIC:\033[0m (" << file << ':' << line << "): " << panicMsg << '\n';
if (err.msg) {
std::cerr << "\tError Message:\t" << err.msg << '\n';
}
std::cerr << "\tError Code:\t" << err << '\n';
if (err.file != nullptr) {
std::cerr << "\tError Location:\t" << reinterpret_cast<const char*>(err.file) << ':' << err.line << '\n';
}
printStackTrace(2);
oxTrace("panic").del("") << "Panic: " << panicMsg << " (" << file << ":" << line << ")";
std::abort();
}
#endif
}
|
Fix ox::assertFunc<bool> for GBA
|
[ox/std] Fix ox::assertFunc<bool> for GBA
|
C++
|
mpl-2.0
|
wombatant/nostalgia,wombatant/nostalgia,wombatant/nostalgia
|
fb12e7f8d628393eacb4f9e5ee36e15738a6e5f6
|
include/person.hpp
|
include/person.hpp
|
#include <string>
#include <cstring>
#include <utility>
#include <algorithm>
const size_t n_literals = 27;
size_t letterI(const char letter, const bool is_capital) {
int first_letter_code = static_cast<int>(is_capital ? 'A' : 'a');
size_t result = static_cast<int>(letter) - first_letter_code + 1;
return result;
}
struct person {
char * str;
unsigned char name_i;
unsigned char name_length;
person() : str(nullptr) {
;
}
person(person const & _person) {
str = _person.str;
name_i = _person.name_i;
name_length = _person.name_length;
}
person(person && _person) : str(_person.str), name_i(_person.name_i), name_length(_person.name_length) {
_person.str = nullptr;
}
person & operator=(person && _person) {
if (this != &_person) {
std::swap(str, _person.str);
std::swap(name_i, _person.name_i);
std::swap(name_length, _person.name_length);
}
return *this; //?
}
size_t i(size_t sort_i) const {
if (sort_i < name_length) {
return letterI(str[name_i + sort_i], sort_i == 0);
}
else {
return 0;
}
}
char * getName() {
char * temp = new char[name_length + 1];
strncpy(temp, &(str[name_i]), name_length);
temp[name_length] = '\0';
return temp;
} //Boost
void putStr(std::string const & _str) {
str = new char[_str.length() + 1];
strncpy(str, _str.c_str(), _str.length());
str[_str.length()] = '\0';
}
~person() {
delete[] str;
}
};
std::ostream & operator<<(std::ostream & output, person const & _person)
{
output << _person.str << " ";
return output;
}
std::istream & operator>>(std::istream & input, person & _person)
{
input >> _person.str;
return input;
}
|
#include <string>
#include <cstring>
#include <utility>
#include <algorithm>
const size_t n_literals = 27;
size_t letterI(const char letter, const bool is_capital) {
int first_letter_code = static_cast<int>(is_capital ? 'A' : 'a');
size_t result = static_cast<int>(letter) - first_letter_code + 1;
return result;
}
struct person {
char * str;
unsigned char name_i;
unsigned char name_length;
person() : str(nullptr) {
;
}
person(person const & _person) {
str = _person.str;
name_i = _person.name_i;
name_length = _person.name_length;
}
person(person && _person) : str(_person.str), name_i(_person.name_i), name_length(_person.name_length) {
_person.str = nullptr;
}
person & operator=(person && _person) {
if (this != &_person) {
std::swap(str, _person.str);
std::swap(name_i, _person.name_i);
std::swap(name_length, _person.name_length);
}
return *this; //?
}
size_t i(size_t sort_i) const {
if (sort_i < name_length) {
return letterI(str[name_i + sort_i], sort_i == 0);
}
else {
return 0;
}
}
char * getName() {
char * temp = new char[name_length + 1];
strncpy(temp, &(str[name_i]), name_length);
temp[name_length] = '\0';
return temp;
} //Boost
void putStr(std::string const & _str) {
str = new char[_str.length() + 1];
strncpy(str, _str.c_str(), _str.length());
str[_str.length()] = '\0';
}
~person() {
delete[] str;
}
};
std::ostream & operator<<(std::ostream & output, person const & _person)
{
output << _person.str << " ";
return output;
}
std::istream & operator>>(std::istream & input, person & _person)
{
base_file >> str1;
.name_i = str1.length() + 1;
base_file >> str2;
current_person.name_length = str2.length();
base_file >> str3;
current_person.putStr(str1 + " " + str2 + " " + str3);
input >> _person.str;
return input;
}
|
Update person.hpp
|
Update person.hpp
|
C++
|
mit
|
ArtemKokorinStudent/External-sort
|
e75478af4d6cbae6c30b430e324d27df75657d7d
|
Library/Sources/Stroika/Foundation/Streams/MemoryStream.inl
|
Library/Sources/Stroika/Foundation/Streams/MemoryStream.inl
|
/*
* Copyright(c) Sophist Solutions, Inc. 1990-2016. All rights reserved
*/
#ifndef _Stroika_Foundation_Streams_MemoryStream_inl_
#define _Stroika_Foundation_Streams_MemoryStream_inl_ 1
/*
********************************************************************************
***************************** Implementation Details ***************************
********************************************************************************
*/
#include "../Debug/AssertExternallySynchronizedLock.h"
namespace Stroika {
namespace Foundation {
namespace Streams {
/*
********************************************************************************
********************** MemoryStream<ELEMENT_TYPE>::Rep_ ************************
********************************************************************************
*/
template <typename ELEMENT_TYPE>
class MemoryStream<ELEMENT_TYPE>::Rep_ : public InputOutputStream<ELEMENT_TYPE>::_IRep, private Debug::AssertExternallySynchronizedLock {
public:
using ElementType = ELEMENT_TYPE;
public:
Rep_ ()
: fData_ ()
, fReadCursor_ (fData_.begin ())
, fWriteCursor_ (fData_.begin ())
{
}
Rep_ (const ELEMENT_TYPE* start, const ELEMENT_TYPE* end)
: Rep_ ()
{
Write (start, end);
}
Rep_ (const Rep_&) = delete;
nonvirtual Rep_& operator= (const Rep_&) = delete;
virtual bool IsSeekable () const override
{
return true;
}
virtual size_t Read (SeekOffsetType* offset, ELEMENT_TYPE* intoStart, ELEMENT_TYPE* intoEnd) override
{
// @todo implement 'offset' support
RequireNotNull (intoStart);
RequireNotNull (intoEnd);
Require (intoStart < intoEnd);
size_t nRequested = intoEnd - intoStart;
lock_guard<const AssertExternallySynchronizedLock> critSec { *this };
Assert ((fData_.begin () <= fReadCursor_) and (fReadCursor_ <= fData_.end ()));
size_t nAvail = fData_.end () - fReadCursor_;
size_t nCopied = min (nAvail, nRequested);
{
#if qSilenceAnnoyingCompilerWarnings && _MSC_VER
Memory::Private::VC_BWA_std_copy (fReadCursor_, fReadCursor_ + nCopied, intoStart);
#else
std::copy (fReadCursor_, fReadCursor_ + nCopied, intoStart);
#endif
fReadCursor_ = fReadCursor_ + nCopied;
}
return nCopied; // this can be zero on EOF
}
virtual void Write (const ELEMENT_TYPE* start, const ELEMENT_TYPE* end) override
{
Require (start != nullptr or start == end);
Require (end != nullptr or start == end);
if (start != end) {
lock_guard<const AssertExternallySynchronizedLock> critSec { *this };
size_t roomLeft = fData_.end () - fWriteCursor_;
size_t roomRequired = end - start;
if (roomLeft < roomRequired) {
size_t curReadOffset = fReadCursor_ - fData_.begin ();
size_t curWriteOffset = fWriteCursor_ - fData_.begin ();
const size_t kChunkSize_ = 128; // WAG: @todo tune number...
Containers::ReserveSpeedTweekAddN (fData_, roomRequired - roomLeft, kChunkSize_);
fData_.resize (curWriteOffset + roomRequired);
fReadCursor_ = fData_.begin () + curReadOffset;
fWriteCursor_ = fData_.begin () + curWriteOffset;
Assert (fWriteCursor_ < fData_.end ());
}
#if qSilenceAnnoyingCompilerWarnings && _MSC_VER
Memory::Private::VC_BWA_std_copy (start, start + roomRequired, fWriteCursor_);
#else
std::copy (start, start + roomRequired, fWriteCursor_);
#endif
fWriteCursor_ += roomRequired;
Assert (fReadCursor_ <= fData_.end ());
Assert (fWriteCursor_ <= fData_.end ());
}
}
virtual void Flush () override
{
// nothing todo - write 'writes thru'
}
virtual SeekOffsetType GetReadOffset () const override
{
lock_guard<const AssertExternallySynchronizedLock> critSec { *this };
return fReadCursor_ - fData_.begin ();
}
virtual SeekOffsetType SeekRead (Whence whence, SignedSeekOffsetType offset) override
{
lock_guard<const AssertExternallySynchronizedLock> critSec { *this };
switch (whence) {
case Whence::eFromStart: {
if (offset < 0) {
Execution::Throw (std::range_error ("seek"));
}
SeekOffsetType uOffset = static_cast<SeekOffsetType> (offset);
if (uOffset > fData_.size ()) {
Execution::Throw (std::range_error ("seek"));
}
fReadCursor_ = fData_.begin () + static_cast<size_t> (uOffset);
}
break;
case Whence::eFromCurrent: {
Streams::SeekOffsetType curOffset = fReadCursor_ - fData_.begin ();
Streams::SignedSeekOffsetType newOffset = curOffset + offset;
if (newOffset < 0) {
Execution::Throw (std::range_error ("seek"));
}
SeekOffsetType uNewOffset = static_cast<SeekOffsetType> (newOffset);
if (uNewOffset > fData_.size ()) {
Execution::Throw (std::range_error ("seek"));
}
fReadCursor_ = fData_.begin () + static_cast<size_t> (uNewOffset);
}
break;
case Whence::eFromEnd: {
Streams::SeekOffsetType curOffset = fReadCursor_ - fData_.begin ();
Streams::SignedSeekOffsetType newOffset = fData_.size () + offset;
if (newOffset < 0) {
Execution::Throw (std::range_error ("seek"));
}
SeekOffsetType uNewOffset = static_cast<SeekOffsetType> (newOffset);
if (uNewOffset > fData_.size ()) {
Execution::Throw (std::range_error ("seek"));
}
fReadCursor_ = fData_.begin () + static_cast<size_t> (uNewOffset);
}
break;
}
Ensure ((fData_.begin () <= fReadCursor_) and (fReadCursor_ <= fData_.end ()));
return fReadCursor_ - fData_.begin ();
}
virtual SeekOffsetType GetWriteOffset () const override
{
lock_guard<const AssertExternallySynchronizedLock> critSec { *this };
return fWriteCursor_ - fData_.begin ();
}
virtual SeekOffsetType SeekWrite (Whence whence, SignedSeekOffsetType offset) override
{
lock_guard<const AssertExternallySynchronizedLock> critSec { *this };
switch (whence) {
case Whence::eFromStart: {
if (offset < 0) {
Execution::Throw (std::range_error ("seek"));
}
if (static_cast<SeekOffsetType> (offset) > fData_.size ()) {
Execution::Throw (std::range_error ("seek"));
}
fWriteCursor_ = fData_.begin () + static_cast<size_t> (offset);
}
break;
case Whence::eFromCurrent: {
Streams::SeekOffsetType curOffset = fWriteCursor_ - fData_.begin ();
Streams::SignedSeekOffsetType newOffset = curOffset + offset;
if (newOffset < 0) {
Execution::Throw (std::range_error ("seek"));
}
if (static_cast<size_t> (newOffset) > fData_.size ()) {
Execution::Throw (std::range_error ("seek"));
}
fWriteCursor_ = fData_.begin () + static_cast<size_t> (newOffset);
}
break;
case Whence::eFromEnd: {
Streams::SeekOffsetType curOffset = fWriteCursor_ - fData_.begin ();
Streams::SignedSeekOffsetType newOffset = fData_.size () + offset;
if (newOffset < 0) {
Execution::Throw (std::range_error ("seek"));
}
if (static_cast<size_t> (newOffset) > fData_.size ()) {
Execution::Throw (std::range_error ("seek"));
}
fWriteCursor_ = fData_.begin () + static_cast<size_t> (newOffset);
}
break;
}
Ensure ((fData_.begin () <= fWriteCursor_) and (fWriteCursor_ <= fData_.end ()));
return fWriteCursor_ - fData_.begin ();
}
vector<ElementType> AsVector () const
{
lock_guard<const AssertExternallySynchronizedLock> critSec { *this };
return fData_;
}
string AsString () const
{
lock_guard<const AssertExternallySynchronizedLock> critSec { *this };
return string (reinterpret_cast<const char*> (Containers::Start (fData_)), reinterpret_cast<const char*> (Containers::End (fData_)));
}
private:
// @todo - COULD redo using
// DEFINE_CONSTEXPR_CONSTANT(size_t, USE_BUFFER_BYTES, 1024 - sizeof(recursive_mutex) - sizeof(Byte*) - sizeof (BinaryInputStream::_IRep) - sizeof (Seekable::_IRep));
// Memory::SmallStackBuffer < Byte, USE_BUFFER_BYTES> fData_;
// Or Stroika chunked array code
private:
vector<ElementType> fData_;
typename vector<ElementType>::iterator fReadCursor_;
typename vector<ElementType>::iterator fWriteCursor_;
};
/*
********************************************************************************
**************************** MemoryStream<ELEMENT_TYPE> ************************
********************************************************************************
*/
template <typename ELEMENT_TYPE>
MemoryStream<ELEMENT_TYPE>::MemoryStream ()
: InputOutputStream<ELEMENT_TYPE> (make_shared<Rep_> ())
{
}
template <typename ELEMENT_TYPE>
MemoryStream<ELEMENT_TYPE>::MemoryStream (const ELEMENT_TYPE* start, const ELEMENT_TYPE* end)
: InputOutputStream<ELEMENT_TYPE> (make_shared<Rep_> (start, end))
{
}
template <typename ELEMENT_TYPE>
template <typename TEST_TYPE, typename ENABLE_IF_TEST>
inline MemoryStream<ELEMENT_TYPE>::MemoryStream (const Memory::BLOB& blob)
: MemoryStream<ELEMENT_TYPE> (blob.begin (), blob.end ())
{
}
template <typename ELEMENT_TYPE>
template <typename T>
T MemoryStream<ELEMENT_TYPE>::As () const
{
#if qCompilerAndStdLib_StaticAssertionsInTemplateFunctionsWhichShouldNeverBeExpanded_Buggy
RequireNotReached ();
#else
static_assert (false, "Only specifically specialized variants are supported");
#endif
}
template <>
template <>
inline vector<Memory::Byte> MemoryStream<Memory::Byte>::As () const
{
RequireNotNull (_GetRep ().get ());
AssertMember (_GetRep ().get (), Rep_);
const Rep_& rep = *dynamic_cast<const Rep_*> (_GetRep ().get ());
return rep.AsVector ();
}
template <>
template <>
inline vector<Characters::Character> MemoryStream<Characters::Character>::As () const
{
RequireNotNull (_GetRep ().get ());
AssertMember (_GetRep ().get (), Rep_);
const Rep_& rep = *dynamic_cast<const Rep_*> (_GetRep ().get ());
return rep.AsVector ();
}
}
}
}
#endif /*_Stroika_Foundation_Streams_MemoryStream_inl_*/
|
/*
* Copyright(c) Sophist Solutions, Inc. 1990-2016. All rights reserved
*/
#ifndef _Stroika_Foundation_Streams_MemoryStream_inl_
#define _Stroika_Foundation_Streams_MemoryStream_inl_ 1
/*
********************************************************************************
***************************** Implementation Details ***************************
********************************************************************************
*/
#include "../Debug/AssertExternallySynchronizedLock.h"
namespace Stroika {
namespace Foundation {
namespace Streams {
/*
********************************************************************************
********************** MemoryStream<ELEMENT_TYPE>::Rep_ ************************
********************************************************************************
*/
template <typename ELEMENT_TYPE>
class MemoryStream<ELEMENT_TYPE>::Rep_ : public InputOutputStream<ELEMENT_TYPE>::_IRep, private Debug::AssertExternallySynchronizedLock {
public:
using ElementType = ELEMENT_TYPE;
public:
Rep_ ()
: fData_ ()
, fReadCursor_ (fData_.begin ())
, fWriteCursor_ (fData_.begin ())
{
}
Rep_ (const ELEMENT_TYPE* start, const ELEMENT_TYPE* end)
: Rep_ ()
{
Write (start, end);
}
Rep_ (const Rep_&) = delete;
nonvirtual Rep_& operator= (const Rep_&) = delete;
virtual bool IsSeekable () const override
{
return true;
}
virtual size_t Read (SeekOffsetType* offset, ELEMENT_TYPE* intoStart, ELEMENT_TYPE* intoEnd) override
{
// @todo implement 'offset' support
RequireNotNull (intoStart);
RequireNotNull (intoEnd);
Require (intoStart < intoEnd);
size_t nRequested = intoEnd - intoStart;
lock_guard<const AssertExternallySynchronizedLock> critSec { *this };
Assert ((fData_.begin () <= fReadCursor_) and (fReadCursor_ <= fData_.end ()));
size_t nAvail = fData_.end () - fReadCursor_;
size_t nCopied = min (nAvail, nRequested);
{
#if qSilenceAnnoyingCompilerWarnings && _MSC_VER
Memory::Private::VC_BWA_std_copy (fReadCursor_, fReadCursor_ + nCopied, intoStart);
#else
std::copy (fReadCursor_, fReadCursor_ + nCopied, intoStart);
#endif
fReadCursor_ = fReadCursor_ + nCopied;
}
return nCopied; // this can be zero on EOF
}
virtual void Write (const ELEMENT_TYPE* start, const ELEMENT_TYPE* end) override
{
Require (start != nullptr or start == end);
Require (end != nullptr or start == end);
if (start != end) {
lock_guard<const AssertExternallySynchronizedLock> critSec { *this };
size_t roomLeft = fData_.end () - fWriteCursor_;
size_t roomRequired = end - start;
if (roomLeft < roomRequired) {
size_t curReadOffset = fReadCursor_ - fData_.begin ();
size_t curWriteOffset = fWriteCursor_ - fData_.begin ();
const size_t kChunkSize_ = 128; // WAG: @todo tune number...
Containers::ReserveSpeedTweekAddN (fData_, roomRequired - roomLeft, kChunkSize_);
fData_.resize (curWriteOffset + roomRequired);
fReadCursor_ = fData_.begin () + curReadOffset;
fWriteCursor_ = fData_.begin () + curWriteOffset;
Assert (fWriteCursor_ < fData_.end ());
}
#if qSilenceAnnoyingCompilerWarnings && _MSC_VER
Memory::Private::VC_BWA_std_copy (start, start + roomRequired, fWriteCursor_);
#else
std::copy (start, start + roomRequired, fWriteCursor_);
#endif
fWriteCursor_ += roomRequired;
Assert (fReadCursor_ < fData_.end ()); // < because we wrote at least one byte and that didnt move read cursor
Assert (fWriteCursor_ <= fData_.end ());
}
}
virtual void Flush () override
{
// nothing todo - write 'writes thru'
}
virtual SeekOffsetType GetReadOffset () const override
{
lock_guard<const AssertExternallySynchronizedLock> critSec { *this };
return fReadCursor_ - fData_.begin ();
}
virtual SeekOffsetType SeekRead (Whence whence, SignedSeekOffsetType offset) override
{
lock_guard<const AssertExternallySynchronizedLock> critSec { *this };
switch (whence) {
case Whence::eFromStart: {
if (offset < 0) {
Execution::Throw (std::range_error ("seek"));
}
SeekOffsetType uOffset = static_cast<SeekOffsetType> (offset);
if (uOffset > fData_.size ()) {
Execution::Throw (std::range_error ("seek"));
}
fReadCursor_ = fData_.begin () + static_cast<size_t> (uOffset);
}
break;
case Whence::eFromCurrent: {
Streams::SeekOffsetType curOffset = fReadCursor_ - fData_.begin ();
Streams::SignedSeekOffsetType newOffset = curOffset + offset;
if (newOffset < 0) {
Execution::Throw (std::range_error ("seek"));
}
SeekOffsetType uNewOffset = static_cast<SeekOffsetType> (newOffset);
if (uNewOffset > fData_.size ()) {
Execution::Throw (std::range_error ("seek"));
}
fReadCursor_ = fData_.begin () + static_cast<size_t> (uNewOffset);
}
break;
case Whence::eFromEnd: {
Streams::SeekOffsetType curOffset = fReadCursor_ - fData_.begin ();
Streams::SignedSeekOffsetType newOffset = fData_.size () + offset;
if (newOffset < 0) {
Execution::Throw (std::range_error ("seek"));
}
SeekOffsetType uNewOffset = static_cast<SeekOffsetType> (newOffset);
if (uNewOffset > fData_.size ()) {
Execution::Throw (std::range_error ("seek"));
}
fReadCursor_ = fData_.begin () + static_cast<size_t> (uNewOffset);
}
break;
}
Ensure ((fData_.begin () <= fReadCursor_) and (fReadCursor_ <= fData_.end ()));
return fReadCursor_ - fData_.begin ();
}
virtual SeekOffsetType GetWriteOffset () const override
{
lock_guard<const AssertExternallySynchronizedLock> critSec { *this };
return fWriteCursor_ - fData_.begin ();
}
virtual SeekOffsetType SeekWrite (Whence whence, SignedSeekOffsetType offset) override
{
lock_guard<const AssertExternallySynchronizedLock> critSec { *this };
switch (whence) {
case Whence::eFromStart: {
if (offset < 0) {
Execution::Throw (std::range_error ("seek"));
}
if (static_cast<SeekOffsetType> (offset) > fData_.size ()) {
Execution::Throw (std::range_error ("seek"));
}
fWriteCursor_ = fData_.begin () + static_cast<size_t> (offset);
}
break;
case Whence::eFromCurrent: {
Streams::SeekOffsetType curOffset = fWriteCursor_ - fData_.begin ();
Streams::SignedSeekOffsetType newOffset = curOffset + offset;
if (newOffset < 0) {
Execution::Throw (std::range_error ("seek"));
}
if (static_cast<size_t> (newOffset) > fData_.size ()) {
Execution::Throw (std::range_error ("seek"));
}
fWriteCursor_ = fData_.begin () + static_cast<size_t> (newOffset);
}
break;
case Whence::eFromEnd: {
Streams::SeekOffsetType curOffset = fWriteCursor_ - fData_.begin ();
Streams::SignedSeekOffsetType newOffset = fData_.size () + offset;
if (newOffset < 0) {
Execution::Throw (std::range_error ("seek"));
}
if (static_cast<size_t> (newOffset) > fData_.size ()) {
Execution::Throw (std::range_error ("seek"));
}
fWriteCursor_ = fData_.begin () + static_cast<size_t> (newOffset);
}
break;
}
Ensure ((fData_.begin () <= fWriteCursor_) and (fWriteCursor_ <= fData_.end ()));
return fWriteCursor_ - fData_.begin ();
}
vector<ElementType> AsVector () const
{
lock_guard<const AssertExternallySynchronizedLock> critSec { *this };
return fData_;
}
string AsString () const
{
lock_guard<const AssertExternallySynchronizedLock> critSec { *this };
return string (reinterpret_cast<const char*> (Containers::Start (fData_)), reinterpret_cast<const char*> (Containers::End (fData_)));
}
private:
// @todo - COULD redo using
// DEFINE_CONSTEXPR_CONSTANT(size_t, USE_BUFFER_BYTES, 1024 - sizeof(recursive_mutex) - sizeof(Byte*) - sizeof (BinaryInputStream::_IRep) - sizeof (Seekable::_IRep));
// Memory::SmallStackBuffer < Byte, USE_BUFFER_BYTES> fData_;
// Or Stroika chunked array code
private:
vector<ElementType> fData_;
typename vector<ElementType>::iterator fReadCursor_;
typename vector<ElementType>::iterator fWriteCursor_;
};
/*
********************************************************************************
**************************** MemoryStream<ELEMENT_TYPE> ************************
********************************************************************************
*/
template <typename ELEMENT_TYPE>
MemoryStream<ELEMENT_TYPE>::MemoryStream ()
: InputOutputStream<ELEMENT_TYPE> (make_shared<Rep_> ())
{
}
template <typename ELEMENT_TYPE>
MemoryStream<ELEMENT_TYPE>::MemoryStream (const ELEMENT_TYPE* start, const ELEMENT_TYPE* end)
: InputOutputStream<ELEMENT_TYPE> (make_shared<Rep_> (start, end))
{
}
template <typename ELEMENT_TYPE>
template <typename TEST_TYPE, typename ENABLE_IF_TEST>
inline MemoryStream<ELEMENT_TYPE>::MemoryStream (const Memory::BLOB& blob)
: MemoryStream<ELEMENT_TYPE> (blob.begin (), blob.end ())
{
}
template <typename ELEMENT_TYPE>
template <typename T>
T MemoryStream<ELEMENT_TYPE>::As () const
{
#if qCompilerAndStdLib_StaticAssertionsInTemplateFunctionsWhichShouldNeverBeExpanded_Buggy
RequireNotReached ();
#else
static_assert (false, "Only specifically specialized variants are supported");
#endif
}
template <>
template <>
inline vector<Memory::Byte> MemoryStream<Memory::Byte>::As () const
{
RequireNotNull (_GetRep ().get ());
AssertMember (_GetRep ().get (), Rep_);
const Rep_& rep = *dynamic_cast<const Rep_*> (_GetRep ().get ());
return rep.AsVector ();
}
template <>
template <>
inline vector<Characters::Character> MemoryStream<Characters::Character>::As () const
{
RequireNotNull (_GetRep ().get ());
AssertMember (_GetRep ().get (), Rep_);
const Rep_& rep = *dynamic_cast<const Rep_*> (_GetRep ().get ());
return rep.AsVector ();
}
}
}
}
#endif /*_Stroika_Foundation_Streams_MemoryStream_inl_*/
|
tweak Streams/MemoryStream.inl assert
|
tweak Streams/MemoryStream.inl assert
|
C++
|
mit
|
SophistSolutions/Stroika,SophistSolutions/Stroika,SophistSolutions/Stroika,SophistSolutions/Stroika,SophistSolutions/Stroika
|
277c27e401b5667de16ddfbae3504bfb1908383c
|
include/vector.hpp
|
include/vector.hpp
|
#ifndef _MATH_VECTOR_HPP
#define _MATH_VECTOR_HPP
#include <cmath>
#include <numeric>
#include <iterator>
#include <algorithm>
#include <type_traits>
#include <iosfwd>
namespace math {
namespace internal {
template <typename _T, std::size_t _N>
struct vector_base {
private:
_T _data[_N];
public:
_T& operator [](std::size_t index) noexcept { return _data[index]; }
_T const& operator [](std::size_t index) const noexcept { return _data[index]; }
};
template <typename _T>
struct vector_base<_T, 2> {
_T x, y;
constexpr vector_base() = default;
vector_base(_T x, _T y) : x(x), y(y) {}
_T& operator [](std::size_t index) noexcept { return *(reinterpret_cast<_T*>(this) + index); }
_T const& operator [](std::size_t index) const noexcept { return *(reinterpret_cast<_T const*>(this) + index); }
};
template <typename _T>
struct vector_base<_T, 3> {
_T x, y, z;
constexpr vector_base() = default;
vector_base(_T x, _T y, _T z = static_cast<_T>(1))
: x(x), y(y), z(z) {}
_T& operator [](std::size_t index) noexcept { return *(reinterpret_cast<_T*>(this) + index); }
_T const& operator [](std::size_t index) const noexcept { return *(reinterpret_cast<_T const*>(this) + index); }
};
template <typename _T>
struct vector_base<_T, 4> {
_T x, y, z, w;
constexpr vector_base() = default;
vector_base(_T x, _T y, _T z, _T w = static_cast<_T>(1))
: x(x), y(y), z(z), w(w) {}
_T& operator [](std::size_t index) noexcept { return *(reinterpret_cast<_T*>(this) + index); }
_T const& operator [](std::size_t index) const noexcept { return *(reinterpret_cast<_T const*>(this) + index); }
};
}
template <typename _T, std::size_t _N>
struct vector : public internal::vector_base<_T, _N> {
static_assert(std::is_arithmetic<_T>::value,
"vector<T, N> requires arithmetic type.");
////////////////////////////////////////////////////////////////////////////////
// type definitions.
typedef _T value_type;
typedef _T* pointer;
typedef _T& reference;
typedef _T const* const_pointer;
typedef _T const& const_reference;
typedef std::size_t size_type;
typedef _T* iterator;
typedef _T const* const_iterator;
typedef std::reverse_iterator<iterator> reverse_iterator;
typedef std::reverse_iterator<const_iterator> const_reverse_iterator;
////////////////////////////////////////////////////////////////////////////////
// construction.
using internal::vector_base<_T, _N>::vector_base;
constexpr vector operator -() const noexcept { return *this; }
constexpr vector operator +() const noexcept { return *this; }
////////////////////////////////////////////////////////////////////////////////
// compound arithmetic operators.
vector& operator += (vector const& other) noexcept {
std::transform(this->begin(), this->end(), other.begin(),
this->begin(), std::plus<_T>());
return *this;
}
vector& operator -= (vector const& other) noexcept {
std::transform(this->begin(), this->end(), other.begin(),
this->begin(), std::minus<_T>());
return *this;
}
vector& operator *= (value_type scalar) noexcept {
std::transform(this->begin(), this->end(), this->begin(),
std::bind(std::multiplies<_T>(), std::placeholders::_1, scalar));
return *this;
}
vector& operator /= (value_type scalar) noexcept {
std::transform(this->begin(), this->end(), this->begin(),
std::bind(std::divides<_T>(), std::placeholders::_1, scalar));
return *this;
}
////////////////////////////////////////////////////////////////////////////////
// methods.
typename std::common_type<_T, float>::type length() const noexcept{
return std::sqrt(this->length_sqr());
}
typename std::common_type<_T, float>::type length_sqr() const noexcept {
return dot_product(*this, *this);
}
////////////////////////////////////////////////////////////////////////////////
// iteration.
iterator begin() noexcept { return std::addressof((*this)[0]); }
iterator end() noexcept { return std::addressof((*this)[_N]); }
const_iterator begin() const noexcept { return std::addressof((*this)[0]); }
const_iterator end() const noexcept { return std::addressof((*this)[_N]); }
const_iterator cbegin() const noexcept { return std::addressof((*this)[0]); }
const_iterator cend() const noexcept { return std::addressof((*this)[_N]); }
reverse_iterator rbegin() noexcept { return this->end(); }
reverse_iterator rend() noexcept { return this->begin(); }
const_reverse_iterator rbegin() const noexcept { return this->end(); }
const_reverse_iterator rend() const noexcept { return this->begin(); }
const_reverse_iterator crbegin() const noexcept { return this->cend(); }
const_reverse_iterator crend() const noexcept { return this->cbegin(); }
};
template <typename _T> using vector2 = vector<_T, 2>;
template <typename _T> using vector3 = vector<_T, 3>;
template <typename _T> using vector4 = vector<_T, 4>;
////////////////////////////////////////////////////////////////////////////////
template <typename _T, typename _U, std::size_t _N>
bool operator == (vector<_T, _N> const& lhs, vector<_U, _N> const& rhs);
template <typename _T, typename _U, std::size_t _N>
bool operator != (vector<_T, _N> const& lhs, vector<_U, _N> const& rhs);
////////////////////////////////////////////////////////////////////////////////
template <typename _T, typename _U, std::size_t _N>
vector<typename std::common_type<_T, _U>::type, _N> operator + (vector<_T, _N> const& lhs, vector<_U, _N> const& rhs) {
typedef typename std::common_type<_T, _U>::type common_t;
return vector<common_t, _N>(lhs) += rhs;
}
template <typename _T, typename _U, std::size_t _N>
vector<typename std::common_type<_T, _U>::type, _N> operator - (vector<_T, _N> const& lhs, vector<_U, _N> const& rhs) {
typedef typename std::common_type<_T, _U>::type common_t;
return vector<common_t, _N>(lhs) -= rhs;
}
template <typename _T, typename _U, std::size_t _N>
vector<typename std::common_type<_T, _U>::type, _N> operator * (vector<_T, _N> const& vec, _U scalar) {
typedef typename std::common_type<_T, _U>::type common_t;
return vector<common_t, _N>(vec) *= scalar;
}
template <typename _T, typename _U, std::size_t _N>
vector<typename std::common_type<_T, _U>::type, _N> operator * (_T scalar, vector<_U, _N> const& vec) {
typedef typename std::common_type<_T, _U>::type common_t;
return vector<common_t, _N>(vec) *= scalar;
}
template <typename _T, typename _U, std::size_t _N>
vector<typename std::common_type<_T, _U>::type, _N> operator / (vector<_T, _N> const& vec, _U scalar) {
typedef typename std::common_type<_T, _U>::type common_t;
return vector<common_t, _N>(vec) /= scalar;
}
////////////////////////////////////////////////////////////////////////////////
template <typename _T, typename _U, std::size_t _N>
typename std::common_type<_T, _U, float>::type dot_product(vector<_T, _N> const& lhs, vector<_U, _N> const& rhs) {
typedef typename std::common_type<_T, _U, float>::type common_t;
return std::inner_product(lhs.begin(), lhs.end(), rhs.begin(), static_cast<common_t>(0));
}
template <typename _T, typename _U, std::size_t _N>
vector<typename std::common_type<_T, _U, float>::type, _N> projection(vector<_T, _N> const& vec, vector<_U, _N> const& n) {
return dot_product(vec, n) / dot_product(n, n) * n;
}
template <typename _T, typename _U, std::size_t _N>
vector<typename std::common_type<_T, _U, float>::type, _N> reflection(vector<_T, _N> const& vec, vector<_U, _N> const& n) {
typedef typename std::common_type<_T, _U, float>::type common_t;
return vec - static_cast<common_t>(2) * projection(vec, n);
}
////////////////////////////////////////////////////////////////////////////////
template <typename _Elem, typename _Traits, typename _T, std::size_t _N>
std::basic_ostream<_Elem, _Traits>& operator << (std::basic_ostream<_Elem, _Traits>& os, vector<_T, _N> const& vec) {
std::copy(vec.begin(), vec.end(), std::ostream_iterator<_T, _Elem, _Traits>(os, ", "));
return os << "\b\b \b";
}
#ifdef _MATH_ANGLE_HPP
// move the following into its angle and vector encompassing header.
// perhaps an over-arching math.hpp header.
template <typename _T, typename _U, std::size_t _N>
radians<typename std::common_type<_T, _U, float>::type> inner_angle(vector<_T, _N> const& lhs, vector<_U, _N> const& rhs) {
return radians<typename std::common_type<_T, _U, float>::type> { std::acos(dot_product(lhs, rhs) / (lhs.length() * rhs.length())) };
}
template <typename _T, typename _U, std::size_t _N>
radians<typename std::common_type<_T, _U, float>::type> outer_angle(vector<_T, _N> const& lhs, vector<_U, _N> const& rhs) {
return math::pi * 2 - inner_angle(lhs, rhs);
}
#endif
}
#endif // _MATH_VECTOR_HPP
|
#ifndef _MATH_VECTOR_HPP
#define _MATH_VECTOR_HPP
#include <cmath>
#include <numeric>
#include <iterator>
#include <algorithm>
#include <type_traits>
#include <iosfwd>
namespace math {
namespace internal {
template <typename _T, std::size_t _N>
struct vector_base {
private:
_T _data[_N];
public:
_T& operator [](std::size_t index) noexcept { return _data[index]; }
_T const& operator [](std::size_t index) const noexcept { return _data[index]; }
};
template <typename _T>
struct vector_base<_T, 2> {
_T x, y;
constexpr vector_base() = default;
vector_base(_T x, _T y) : x(x), y(y) {}
_T& operator [](std::size_t index) noexcept { return *(reinterpret_cast<_T*>(this) + index); }
_T const& operator [](std::size_t index) const noexcept { return *(reinterpret_cast<_T const*>(this) + index); }
};
template <typename _T>
struct vector_base<_T, 3> {
_T x, y, z;
constexpr vector_base() = default;
vector_base(_T x, _T y, _T z = static_cast<_T>(1))
: x(x), y(y), z(z) {}
_T& operator [](std::size_t index) noexcept { return *(reinterpret_cast<_T*>(this) + index); }
_T const& operator [](std::size_t index) const noexcept { return *(reinterpret_cast<_T const*>(this) + index); }
};
template <typename _T>
struct vector_base<_T, 4> {
_T x, y, z, w;
constexpr vector_base() = default;
vector_base(_T x, _T y, _T z, _T w = static_cast<_T>(1))
: x(x), y(y), z(z), w(w) {}
_T& operator [](std::size_t index) noexcept { return *(reinterpret_cast<_T*>(this) + index); }
_T const& operator [](std::size_t index) const noexcept { return *(reinterpret_cast<_T const*>(this) + index); }
};
}
template <typename _T, std::size_t _N>
struct vector : public internal::vector_base<_T, _N> {
static_assert(std::is_arithmetic<_T>::value,
"vector<T, N> requires arithmetic type.");
////////////////////////////////////////////////////////////////////////////////
// type definitions.
typedef _T value_type;
typedef _T* pointer;
typedef _T& reference;
typedef _T const* const_pointer;
typedef _T const& const_reference;
typedef std::size_t size_type;
typedef _T* iterator;
typedef _T const* const_iterator;
typedef std::reverse_iterator<iterator> reverse_iterator;
typedef std::reverse_iterator<const_iterator> const_reverse_iterator;
////////////////////////////////////////////////////////////////////////////////
// construction.
using internal::vector_base<_T, _N>::vector_base;
////////////////////////////////////////////////////////////////////////////////
// unary arithmetic operators.
vector operator +() const noexcept {
return *this;
}
vector operator -() const noexcept {
return -1 * (*this);
}
////////////////////////////////////////////////////////////////////////////////
// compound arithmetic operators.
vector& operator += (vector const& other) noexcept {
std::transform(this->begin(), this->end(), other.begin(),
this->begin(), std::plus<_T>());
return *this;
}
vector& operator -= (vector const& other) noexcept {
std::transform(this->begin(), this->end(), other.begin(),
this->begin(), std::minus<_T>());
return *this;
}
vector& operator *= (value_type scalar) noexcept {
std::transform(this->begin(), this->end(), this->begin(),
std::bind(std::multiplies<_T>(), std::placeholders::_1, scalar));
return *this;
}
vector& operator /= (value_type scalar) noexcept {
std::transform(this->begin(), this->end(), this->begin(),
std::bind(std::divides<_T>(), std::placeholders::_1, scalar));
return *this;
}
////////////////////////////////////////////////////////////////////////////////
// methods.
typename std::common_type<_T, float>::type length() const noexcept{
return std::sqrt(this->length_sqr());
}
typename std::common_type<_T, float>::type length_sqr() const noexcept {
return dot_product(*this, *this);
}
////////////////////////////////////////////////////////////////////////////////
// iteration.
iterator begin() noexcept { return std::addressof((*this)[0]); }
iterator end() noexcept { return std::addressof((*this)[_N]); }
const_iterator begin() const noexcept { return std::addressof((*this)[0]); }
const_iterator end() const noexcept { return std::addressof((*this)[_N]); }
const_iterator cbegin() const noexcept { return std::addressof((*this)[0]); }
const_iterator cend() const noexcept { return std::addressof((*this)[_N]); }
reverse_iterator rbegin() noexcept { return this->end(); }
reverse_iterator rend() noexcept { return this->begin(); }
const_reverse_iterator rbegin() const noexcept { return this->end(); }
const_reverse_iterator rend() const noexcept { return this->begin(); }
const_reverse_iterator crbegin() const noexcept { return this->cend(); }
const_reverse_iterator crend() const noexcept { return this->cbegin(); }
};
template <typename _T> using vector2 = vector<_T, 2>;
template <typename _T> using vector3 = vector<_T, 3>;
template <typename _T> using vector4 = vector<_T, 4>;
////////////////////////////////////////////////////////////////////////////////
template <typename _T, typename _U, std::size_t _N>
bool operator == (vector<_T, _N> const& lhs, vector<_U, _N> const& rhs);
template <typename _T, typename _U, std::size_t _N>
bool operator != (vector<_T, _N> const& lhs, vector<_U, _N> const& rhs);
////////////////////////////////////////////////////////////////////////////////
template <typename _T, typename _U, std::size_t _N>
vector<typename std::common_type<_T, _U>::type, _N> operator + (vector<_T, _N> const& lhs, vector<_U, _N> const& rhs) {
typedef typename std::common_type<_T, _U>::type common_t;
return vector<common_t, _N>(lhs) += rhs;
}
template <typename _T, typename _U, std::size_t _N>
vector<typename std::common_type<_T, _U>::type, _N> operator - (vector<_T, _N> const& lhs, vector<_U, _N> const& rhs) {
typedef typename std::common_type<_T, _U>::type common_t;
return vector<common_t, _N>(lhs) -= rhs;
}
template <typename _T, typename _U, std::size_t _N>
vector<typename std::common_type<_T, _U>::type, _N> operator * (vector<_T, _N> const& vec, _U scalar) {
typedef typename std::common_type<_T, _U>::type common_t;
return vector<common_t, _N>(vec) *= scalar;
}
template <typename _T, typename _U, std::size_t _N>
vector<typename std::common_type<_T, _U>::type, _N> operator * (_T scalar, vector<_U, _N> const& vec) {
typedef typename std::common_type<_T, _U>::type common_t;
return vector<common_t, _N>(vec) *= scalar;
}
template <typename _T, typename _U, std::size_t _N>
vector<typename std::common_type<_T, _U>::type, _N> operator / (vector<_T, _N> const& vec, _U scalar) {
typedef typename std::common_type<_T, _U>::type common_t;
return vector<common_t, _N>(vec) /= scalar;
}
////////////////////////////////////////////////////////////////////////////////
template <typename _T, typename _U, std::size_t _N>
typename std::common_type<_T, _U, float>::type dot_product(vector<_T, _N> const& lhs, vector<_U, _N> const& rhs) {
typedef typename std::common_type<_T, _U, float>::type common_t;
return std::inner_product(lhs.begin(), lhs.end(), rhs.begin(), static_cast<common_t>(0));
}
template <typename _T, typename _U, std::size_t _N>
vector<typename std::common_type<_T, _U, float>::type, _N> projection(vector<_T, _N> const& vec, vector<_U, _N> const& n) {
return dot_product(vec, n) / dot_product(n, n) * n;
}
template <typename _T, typename _U, std::size_t _N>
vector<typename std::common_type<_T, _U, float>::type, _N> reflection(vector<_T, _N> const& vec, vector<_U, _N> const& n) {
typedef typename std::common_type<_T, _U, float>::type common_t;
return vec - static_cast<common_t>(2) * projection(vec, n);
}
////////////////////////////////////////////////////////////////////////////////
template <typename _Elem, typename _Traits, typename _T, std::size_t _N>
std::basic_ostream<_Elem, _Traits>& operator << (std::basic_ostream<_Elem, _Traits>& os, vector<_T, _N> const& vec) {
std::copy(vec.begin(), vec.end(), std::ostream_iterator<_T, _Elem, _Traits>(os, ", "));
return os << "\b\b \b";
}
#ifdef _MATH_ANGLE_HPP
// move the following into its angle and vector encompassing header.
// perhaps an over-arching math.hpp header.
template <typename _T, typename _U, std::size_t _N>
radians<typename std::common_type<_T, _U, float>::type> inner_angle(vector<_T, _N> const& lhs, vector<_U, _N> const& rhs) {
return radians<typename std::common_type<_T, _U, float>::type> { std::acos(dot_product(lhs, rhs) / (lhs.length() * rhs.length())) };
}
template <typename _T, typename _U, std::size_t _N>
radians<typename std::common_type<_T, _U, float>::type> outer_angle(vector<_T, _N> const& lhs, vector<_U, _N> const& rhs) {
return math::pi * 2 - inner_angle(lhs, rhs);
}
#endif
}
#endif // _MATH_VECTOR_HPP
|
Implement unary arithmetic operators
|
Implement unary arithmetic operators
|
C++
|
mit
|
rtlayzell/angle,rtlayzell/math
|
11f630e63cebd7a37ff928af90ae42b34835eff4
|
kode/kodemain.cpp
|
kode/kodemain.cpp
|
/*
This file is part of kdepim.
Copyright (c) 2004 Cornelius Schumacher <[email protected]>
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Library General Public
License as published by the Free Software Foundation; either
version 2 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Library General Public License for more details.
You should have received a copy of the GNU Library General Public License
along with this library; see the file COPYING.LIB. If not, write to
the Free Software Foundation, Inc., 59 Temple Place - Suite 330,
Boston, MA 02111-1307, USA.
*/
#include "code.h"
#include "printer.h"
#include "license.h"
#include "automakefile.h"
#include <kabc/stdaddressbook.h>
#include <kaboutdata.h>
#include <kapplication.h>
#include <kcmdlineargs.h>
#include <kconfig.h>
#include <kdebug.h>
#include <kglobal.h>
#include <klocale.h>
#include <kmessagebox.h>
#include <kstandarddirs.h>
#include <ksimpleconfig.h>
#include <ksavefile.h>
#include <qfile.h>
#include <qtextstream.h>
#include <qfileinfo.h>
#include <iostream>
static const KCmdLineOptions options[] =
{
{ "c", 0, 0 },
{ "create-class", I18N_NOOP("Create class"), 0 },
{ "d", 0, 0 },
{ "create-dialog", I18N_NOOP("Create dialog"), 0 },
{ "create-kioslave", I18N_NOOP("Create kioslave"), 0 },
{ "y", 0, 0 },
{ "codify", I18N_NOOP("Create generator code for given source"), 0 },
{ "author-email <name>", I18N_NOOP("Add author with given email address"), 0 },
{ "project <name>", I18N_NOOP("Name of project"), 0 },
{ "gpl", I18N_NOOP("Use GPL as license"), 0 },
{ "lgpl", I18N_NOOP("Use LGPL as license"), 0 },
{ "classname <name>", I18N_NOOP("Name of class"), 0 },
{ "namespace <name>", I18N_NOOP("Namespace"), 0 },
{ "warning", I18N_NOOP("Create warning about code generation"), 0 },
{ "qt-exception", I18N_NOOP("Add Qt excpetion to GPL"), 0 },
{ "singleton", I18N_NOOP("Create a singleton class"), 0 },
{ "protocol", I18N_NOOP("kioslave protocol"), 0 },
{ "+[filename]", I18N_NOOP("Source code file name"), 0 },
KCmdLineLastOption
};
int codify( KCmdLineArgs *args )
{
if ( args->count() != 1 ) {
std::cerr << "Usage: kode --codify <sourcecodefile>" << std::endl;
return 1;
}
QString filename = args->arg( 0 );
QFile f( filename );
if ( !f.open( IO_ReadOnly ) ) {
kdError() << "Unable to open file '" << filename << "'." << endl;
return 1;
} else {
std::cout << "KODE::Code code;" << std::endl;
QTextStream ts( &f );
QString line;
while( !( line = ts.readLine() ).isNull() ) {
line.replace( "\\", "\\\\" );
line.replace( "\"", "\\\"" );
line = "code += \"" + line;
line.append( "\";" );
std::cout << line.local8Bit() << std::endl;
}
}
return 0;
}
int create( KCmdLineArgs *args )
{
KODE::Printer p;
bool createKioslave = args->isSet( "create-kioslave" );
if ( !args->isSet( "classname" ) ) {
kdError() << "Error: No class name given." << endl;
return 1;
}
QString className = args->getOption( "classname" );
QString protocol;
if ( createKioslave ) {
if ( !args->isSet( "protocol" ) ) {
protocol = className.lower();
kdWarning() << "Warning: No protocol for kioslave given. Assuming '"
<< protocol << "'" << endl;
} else {
protocol = args->getOption( "protocol" );
}
}
KODE::File file;
file.setProject( args->getOption( "project" ) );
QString authorEmail = args->getOption( "author-email" );
if ( !authorEmail.isEmpty() ) {
KABC::Addressee::List a =
KABC::StdAddressBook::self()->findByEmail( authorEmail );
QString authorName;
if ( a.isEmpty() ) {
kdDebug() << "Unable to find '" << authorEmail << "' in address book."
<< endl;
} else {
authorName = a.first().realName();
}
file.addCopyright( QDate::currentDate().year(), authorName, authorEmail );
}
KODE::License l;
if ( args->isSet( "gpl" ) ) l = KODE::License( KODE::License::GPL );
if ( args->isSet( "lgpl" ) ) l = KODE::License( KODE::License::LGPL );
l.setQtException( args->isSet( "qt-exception" ) );
file.setLicense( l );
file.setNameSpace( args->getOption( "namespace" ) );
KODE::Class c( className );
if ( args->isSet( "create-dialog" ) ) {
c.addBaseClass( KODE::Class( "KDialogBase" ) );
c.addInclude( "kdialogbase.h" );
} else if ( createKioslave ) {
c.setDocs( "This class implements a kioslave for ..." );
c.addBaseClass( KODE::Class( "SlaveBase", "KIO" ) );
c.addHeaderInclude( "kio/slavebase.h" );
KODE::Function get( "get", "void" );
get.addArgument( "const KURL &url" );
KODE::Code code;
code += "kdDebug(7000) << \"" + className + "::get()\" << endl;";
code += "kdDebug(7000) << \" URL: \" << url.url() << endl;";
code += "#if 1";
code += "kdDebug(7000) << \" Path: \" << url.path() << endl;";
code += "kdDebug(7000) << \" Query: \" << url.query() << endl;";
code += "kdDebug(7000) << \" Protocol: \" << url.protocol() << endl;";
code += "kdDebug(7000) << \" Filename: \" << url.filename() << endl;";
code += "#endif";
code.newLine();
code += "mimeType( \"text/plain\" );";
code.newLine();
code += "QCString str( \"Hello!\" );";
code += "data( str );";
code.newLine();
code += "finished();";
code.newLine();
code += "kdDebug(7000) << \"" + className + "CgiProtocol::get() done\" << endl;";
get.setBody( code );
c.addFunction( get );
c.addInclude( "kinstance.h" );
c.addInclude( "kdebug.h" );
c.addInclude( "sys/types.h" );
c.addInclude( "unistd.h" );
c.addInclude( "stdlib.h" );
KODE::Function main( "kdemain", "int" );
main.addArgument( "int argc" );
main.addArgument( "char **argv" );
code.clear();
code += "KInstance instance( \"kio_" + protocol + "\" );";
code += "";
code += "kdDebug(7000) << \"Starting kio_" + protocol + "(pid: \" << getpid() << \")\" << endl;";
code += "";
code += "if (argc != 4) {";
code.indent();
code += "fprintf( stderr, \"Usage: kio_" + protocol + " protocol domain-socket1 domain-socket2\\n\");";
code += "exit( -1 );";
code.unindent();
code += "}";
code += "";
code += className + " slave( argv[2], argv[3] );";
code += "slave.dispatchLoop();";
code += "";
code += "return 0;";
main.setBody( code );
file.addFileFunction( main );
file.addExternCDeclaration( p.functionSignature( main ) );
}
KODE::Function constructor( className );
if ( args->isSet( "singleton" ) ) {
constructor.setAccess( KODE::Function::Private );
KODE::Function self( "self", className + " *" );
self.setStatic( true );
KODE::Code code;
code += "if ( !mSelf ) {";
code += " selfDeleter.setObject( mSelf, new " + className + "() );";
code += "}";
code += "return mSelf;";
self.setBody( code );
c.addFunction( self );
KODE::MemberVariable selfVar( "mSelf", className + " *", true );
selfVar.setInitializer( "0" );
c.addMemberVariable( selfVar );
KODE::Variable staticDeleter( "selfDeleter",
"KStaticDeleter<" + className + ">",
true );
file.addFileVariable( staticDeleter );
file.addInclude( "kstaticdeleter.h" );
}
if ( createKioslave ) {
constructor.addArgument( "const QCString &pool" );
constructor.addArgument( "const QCString &app" );
constructor.addInitializer( "SlaveBase( \"" + protocol + "\", pool, app )" );
}
c.addFunction( constructor );
file.insertClass( c );
if ( args->isSet( "warning" ) ) p.setCreationWarning( true );
p.printHeader( file );
p.printImplementation( file );
if ( createKioslave ) {
// Write automake Makefile
KODE::AutoMakefile am;
am.addEntry( "INCLUDES", "$(all_includes)" );
am.newLine();
am.addEntry( "noinst_HEADERS", className.lower() + ".h" );
am.newLine();
am.addEntry( "METASOURCES", "AUTO" );
am.newLine();
am.addEntry( "kdelnkdir", "$(kde_servicesdir)" );
am.addEntry( "kdelnk_DATA", protocol + ".protocol" );
KODE::AutoMakefile::Target t( "kde_module_LTLIBRARIES",
"kio_" + protocol + ".la" );
t.sources = className.lower() + ".cpp";
t.libadd = "$(LIB_KIO)";
t.ldflags = "$(all_libraries) -module $(KDE_PLUGIN)";
am.addTarget( t );
p.printAutoMakefile( am );
// Write protocol file
QString protocolFilename = protocol + ".protocol";
QFileInfo fi( protocolFilename );
protocolFilename = fi.absFilePath();
KSaveFile::backupFile( protocolFilename, QString::null, ".backup" );
QFile::remove( protocolFilename );
KSimpleConfig protocolFile( protocolFilename );
protocolFile.setGroup( "Protocol" );
protocolFile.writeEntry( "exec", "kio_" + protocol );
protocolFile.writeEntry( "protocol", protocol );
protocolFile.writeEntry( "input", "none" );
protocolFile.writeEntry( "output", "filesystem" );
protocolFile.writeEntry( "reading", "true" );
protocolFile.writeEntry( "DocPath", "kioslave/" + protocol + ".html" );
protocolFile.sync();
}
return 0;
}
int main(int argc,char **argv)
{
KAboutData aboutData( "kode", I18N_NOOP("KDE Code Generator"), "0.1" );
aboutData.addAuthor( "Cornelius Schumacher", 0, "[email protected]" );
KCmdLineArgs::init( argc, argv, &aboutData );
KCmdLineArgs::addCmdLineOptions( options );
KApplication app;
KCmdLineArgs *args = KCmdLineArgs::parsedArgs();
if ( args->isSet( "create-class" ) || args->isSet( "create-dialog" ) ||
args->isSet( "create-kioslave" ) ) {
return create( args );
} else if ( args->isSet( "codify" ) ) {
return codify( args );
} else {
std::cerr << "Error: No command given." << std::endl;
return 1;
}
}
|
/*
This file is part of kdepim.
Copyright (c) 2004 Cornelius Schumacher <[email protected]>
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Library General Public
License as published by the Free Software Foundation; either
version 2 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Library General Public License for more details.
You should have received a copy of the GNU Library General Public License
along with this library; see the file COPYING.LIB. If not, write to
the Free Software Foundation, Inc., 59 Temple Place - Suite 330,
Boston, MA 02111-1307, USA.
*/
#include "code.h"
#include "printer.h"
#include "license.h"
#include "automakefile.h"
#include <kabc/stdaddressbook.h>
#include <kaboutdata.h>
#include <kapplication.h>
#include <kcmdlineargs.h>
#include <kconfig.h>
#include <kdebug.h>
#include <kglobal.h>
#include <klocale.h>
#include <kmessagebox.h>
#include <kstandarddirs.h>
#include <ksimpleconfig.h>
#include <ksavefile.h>
#include <kprocess.h>
#include <qfile.h>
#include <qtextstream.h>
#include <qfileinfo.h>
#include <qregexp.h>
#include <iostream>
static const KCmdLineOptions options[] =
{
{ "c", 0, 0 },
{ "create-class", I18N_NOOP("Create class"), 0 },
{ "d", 0, 0 },
{ "create-dialog", I18N_NOOP("Create dialog"), 0 },
{ "create-kioslave", I18N_NOOP("Create kioslave"), 0 },
{ "y", 0, 0 },
{ "codify", I18N_NOOP("Create generator code for given source"), 0 },
{ "add-property", I18N_NOOP("Add property to class"), 0 },
{ "inplace", I18N_NOOP("Change file in place"), 0 },
{ "author-email <name>", I18N_NOOP("Add author with given email address"), 0 },
{ "project <name>", I18N_NOOP("Name of project"), 0 },
{ "gpl", I18N_NOOP("Use GPL as license"), 0 },
{ "lgpl", I18N_NOOP("Use LGPL as license"), 0 },
{ "classname <name>", I18N_NOOP("Name of class"), 0 },
{ "namespace <name>", I18N_NOOP("Namespace"), 0 },
{ "warning", I18N_NOOP("Create warning about code generation"), 0 },
{ "qt-exception", I18N_NOOP("Add Qt excpetion to GPL"), 0 },
{ "singleton", I18N_NOOP("Create a singleton class"), 0 },
{ "protocol", I18N_NOOP("kioslave protocol"), 0 },
{ "+[filename]", I18N_NOOP("Source code file name"), 0 },
KCmdLineLastOption
};
void addPropertyFunctions( QString &out, const QString &type,
const QString &name )
{
// FIXME: Use KODE::Function
QString argument;
QString upper = KODE::Style::upperFirst( name );
if ( !type.endsWith( "*" ) ) argument = "const " + type + " &";
else argument = type;
KODE::Code code;
code.setIndent( 4 );
code += "/**";
code += " Set .";
code += "*/";
code += "void set" + upper + "( " + argument + "v )";
code += "{";
code += " m" + upper + " = v;";
code += "}";
code += "/**";
code += " Get .";
code += "*/";
code += type + " " + name + "() const";
code += "{";
code += " return m" + upper + ";";
code += "}";
out += code.text();
}
void addPropertyVariable( QString &out, const QString &type,
const QString &name )
{
QString upper = KODE::Style::upperFirst( name );
KODE::Code code;
code.setIndent( 4 );
code += type + " m" + upper + ";";
out += code.text();
}
int addProperty( KCmdLineArgs *args )
{
if ( args->count() != 3 ) {
std::cerr << "Usage: kode --add-property <class> <proprerty-type> "
<< "<property-name>" << std::endl;
return 1;
}
QString className = args->arg( 0 );
QString type = args->arg( 1 );
QString name = args->arg( 2 );
kdDebug() << "Add property: class " << className << ": " << type << " " <<
name << endl;
QString headerFileName = className.lower() + ".h";
QFile headerFile( headerFileName );
if ( !headerFile.open( IO_ReadOnly ) ) {
std::cerr << "Unable to open file '" << headerFileName.utf8() << "'" <<
std::endl;
return 1;
}
QTextStream in( &headerFile );
enum State { FindClass, FindConstructor, FindProperties, FindPrivate,
FindVariables, Finish };
State state = FindClass;
QString accessor;
QString mutator;
QString out;
QString readAhead;
QString line;
while ( !( line = in.readLine() ).isNull() ) {
// std::cout << line.utf8() << std::endl;
kdDebug() << state << " LINE: " << line << endl;
readAhead += line + "\n";
// out += line + "\n";
switch( state ) {
case FindClass:
// if ( line.find( QRegExp( className ) ) >= 0 ) {
if ( line.find( QRegExp( "^\\s*class\\s+" + className ) ) >= 0 ) {
kdDebug() << " FOUND CLASS" << endl;
state = FindConstructor;
}
break;
case FindConstructor:
if ( line.find( QRegExp( "^\\s*" + className + "\\s*\\(" ) ) >= 0 ) {
kdDebug() << " FOUND CONSTRUCTOR" << endl;
out += readAhead;
readAhead = QString::null;
state = FindProperties;
}
break;
case FindProperties:
{
QRegExp re( "(\\w+)\\s*\\(" );
if ( re.search( line ) >= 0 ) {
QString function = re.cap( 1 ).lower();
if ( !function.isEmpty() ) {
kdDebug() << "Function: " << function << endl;
if ( function == className || function == "~" + className ) {
out += readAhead;
readAhead = QString::null;
} else {
if ( function.startsWith( "set" ) ) {
mutator = function.mid( 3 );
kdDebug() << "MUTATOR: " << mutator << endl;
} else {
if ( function == mutator ) {
accessor = function;
kdDebug() << "ACCESSOR: " << accessor << endl;
out += readAhead;
readAhead = QString::null;
} else {
kdDebug() << "CREATE PROPERTY" << endl;
out += "\n";
addPropertyFunctions( out, type, name );
state = FindPrivate;
}
}
}
}
} else if ( line.find( QRegExp( "\\s*protected" ) ) >= 0 ) {
state = FindPrivate;
} else if ( line.find( QRegExp( "\\s*private" ) ) >= 0 ) {
if ( accessor.isEmpty() ) {
addPropertyVariable( out, type, name );
state = Finish;
} else {
state = FindVariables;
}
}
}
break;
case FindPrivate:
if ( line.find( QRegExp( "\\s*private" ) ) >= 0 ) {
if ( accessor.isEmpty() ) {
out += readAhead;
readAhead = QString::null;
addPropertyVariable( out, type, name );
state = Finish;
} else {
state = FindVariables;
}
}
break;
case FindVariables:
{
if ( line.find( "m" + accessor.lower(), 0, false ) >= 0 ) {
out += readAhead;
readAhead = QString::null;
addPropertyVariable( out, type, name );
state = Finish;
}
}
break;
case Finish:
break;
}
}
headerFile.close();
out += readAhead;
if ( args->isSet( "inplace" ) ) {
QString headerFileNameOut = headerFileName + ".kodeorig" ;
KProcess proc;
proc << "cp" << QFile::encodeName( headerFileName ) <<
QFile::encodeName( headerFileNameOut );
if ( !proc.start( KProcess::Block ) ) {
kdError() << "Copy failed" << endl;
} else {
kdDebug() << "Write to original file." << endl;
if ( !headerFile.open( IO_WriteOnly ) ) {
kdError() << "Unable to open file '" << headerFileName <<
"' for writing." << endl;
return 1;
}
QTextStream o( &headerFile );
o << out << endl;
}
} else {
std::cout << out.utf8() << std::endl;
}
return 0;
}
int codify( KCmdLineArgs *args )
{
if ( args->count() != 1 ) {
std::cerr << "Usage: kode --codify <sourcecodefile>" << std::endl;
return 1;
}
QString filename = args->arg( 0 );
QFile f( filename );
if ( !f.open( IO_ReadOnly ) ) {
kdError() << "Unable to open file '" << filename << "'." << endl;
return 1;
} else {
std::cout << "KODE::Code code;" << std::endl;
QTextStream ts( &f );
QString line;
while( !( line = ts.readLine() ).isNull() ) {
line.replace( "\\", "\\\\" );
line.replace( "\"", "\\\"" );
line = "code += \"" + line;
line.append( "\";" );
std::cout << line.local8Bit() << std::endl;
}
}
return 0;
}
int create( KCmdLineArgs *args )
{
KODE::Printer p;
bool createKioslave = args->isSet( "create-kioslave" );
if ( !args->isSet( "classname" ) ) {
kdError() << "Error: No class name given." << endl;
return 1;
}
QString className = args->getOption( "classname" );
QString protocol;
if ( createKioslave ) {
if ( !args->isSet( "protocol" ) ) {
protocol = className.lower();
kdWarning() << "Warning: No protocol for kioslave given. Assuming '"
<< protocol << "'" << endl;
} else {
protocol = args->getOption( "protocol" );
}
}
KODE::File file;
file.setProject( args->getOption( "project" ) );
QString authorEmail = args->getOption( "author-email" );
if ( !authorEmail.isEmpty() ) {
KABC::Addressee::List a =
KABC::StdAddressBook::self()->findByEmail( authorEmail );
QString authorName;
if ( a.isEmpty() ) {
kdDebug() << "Unable to find '" << authorEmail << "' in address book."
<< endl;
} else {
authorName = a.first().realName();
}
file.addCopyright( QDate::currentDate().year(), authorName, authorEmail );
}
KODE::License l;
if ( args->isSet( "gpl" ) ) l = KODE::License( KODE::License::GPL );
if ( args->isSet( "lgpl" ) ) l = KODE::License( KODE::License::LGPL );
l.setQtException( args->isSet( "qt-exception" ) );
file.setLicense( l );
file.setNameSpace( args->getOption( "namespace" ) );
KODE::Class c( className );
if ( args->isSet( "create-dialog" ) ) {
c.addBaseClass( KODE::Class( "KDialogBase" ) );
c.addInclude( "kdialogbase.h" );
} else if ( createKioslave ) {
c.setDocs( "This class implements a kioslave for ..." );
c.addBaseClass( KODE::Class( "SlaveBase", "KIO" ) );
c.addHeaderInclude( "kio/slavebase.h" );
KODE::Function get( "get", "void" );
get.addArgument( "const KURL &url" );
KODE::Code code;
code += "kdDebug(7000) << \"" + className + "::get()\" << endl;";
code += "kdDebug(7000) << \" URL: \" << url.url() << endl;";
code += "#if 1";
code += "kdDebug(7000) << \" Path: \" << url.path() << endl;";
code += "kdDebug(7000) << \" Query: \" << url.query() << endl;";
code += "kdDebug(7000) << \" Protocol: \" << url.protocol() << endl;";
code += "kdDebug(7000) << \" Filename: \" << url.filename() << endl;";
code += "#endif";
code.newLine();
code += "mimeType( \"text/plain\" );";
code.newLine();
code += "QCString str( \"Hello!\" );";
code += "data( str );";
code.newLine();
code += "finished();";
code.newLine();
code += "kdDebug(7000) << \"" + className + "CgiProtocol::get() done\" << endl;";
get.setBody( code );
c.addFunction( get );
c.addInclude( "kinstance.h" );
c.addInclude( "kdebug.h" );
c.addInclude( "sys/types.h" );
c.addInclude( "unistd.h" );
c.addInclude( "stdlib.h" );
KODE::Function main( "kdemain", "int" );
main.addArgument( "int argc" );
main.addArgument( "char **argv" );
code.clear();
code += "KInstance instance( \"kio_" + protocol + "\" );";
code += "";
code += "kdDebug(7000) << \"Starting kio_" + protocol + "(pid: \" << getpid() << \")\" << endl;";
code += "";
code += "if (argc != 4) {";
code.indent();
code += "fprintf( stderr, \"Usage: kio_" + protocol + " protocol domain-socket1 domain-socket2\\n\");";
code += "exit( -1 );";
code.unindent();
code += "}";
code += "";
code += className + " slave( argv[2], argv[3] );";
code += "slave.dispatchLoop();";
code += "";
code += "return 0;";
main.setBody( code );
file.addFileFunction( main );
file.addExternCDeclaration( p.functionSignature( main ) );
}
KODE::Function constructor( className );
if ( args->isSet( "singleton" ) ) {
constructor.setAccess( KODE::Function::Private );
KODE::Function self( "self", className + " *" );
self.setStatic( true );
KODE::Code code;
code += "if ( !mSelf ) {";
code += " selfDeleter.setObject( mSelf, new " + className + "() );";
code += "}";
code += "return mSelf;";
self.setBody( code );
c.addFunction( self );
KODE::MemberVariable selfVar( "mSelf", className + " *", true );
selfVar.setInitializer( "0" );
c.addMemberVariable( selfVar );
KODE::Variable staticDeleter( "selfDeleter",
"KStaticDeleter<" + className + ">",
true );
file.addFileVariable( staticDeleter );
file.addInclude( "kstaticdeleter.h" );
}
if ( createKioslave ) {
constructor.addArgument( "const QCString &pool" );
constructor.addArgument( "const QCString &app" );
constructor.addInitializer( "SlaveBase( \"" + protocol + "\", pool, app )" );
}
c.addFunction( constructor );
file.insertClass( c );
if ( args->isSet( "warning" ) ) p.setCreationWarning( true );
p.printHeader( file );
p.printImplementation( file );
if ( createKioslave ) {
// Write automake Makefile
KODE::AutoMakefile am;
am.addEntry( "INCLUDES", "$(all_includes)" );
am.newLine();
am.addEntry( "noinst_HEADERS", className.lower() + ".h" );
am.newLine();
am.addEntry( "METASOURCES", "AUTO" );
am.newLine();
am.addEntry( "kdelnkdir", "$(kde_servicesdir)" );
am.addEntry( "kdelnk_DATA", protocol + ".protocol" );
KODE::AutoMakefile::Target t( "kde_module_LTLIBRARIES",
"kio_" + protocol + ".la" );
t.sources = className.lower() + ".cpp";
t.libadd = "$(LIB_KIO)";
t.ldflags = "$(all_libraries) -module $(KDE_PLUGIN)";
am.addTarget( t );
p.printAutoMakefile( am );
// Write protocol file
QString protocolFilename = protocol + ".protocol";
QFileInfo fi( protocolFilename );
protocolFilename = fi.absFilePath();
KSaveFile::backupFile( protocolFilename, QString::null, ".backup" );
QFile::remove( protocolFilename );
KSimpleConfig protocolFile( protocolFilename );
protocolFile.setGroup( "Protocol" );
protocolFile.writeEntry( "exec", "kio_" + protocol );
protocolFile.writeEntry( "protocol", protocol );
protocolFile.writeEntry( "input", "none" );
protocolFile.writeEntry( "output", "filesystem" );
protocolFile.writeEntry( "reading", "true" );
protocolFile.writeEntry( "DocPath", "kioslave/" + protocol + ".html" );
protocolFile.sync();
}
return 0;
}
int main(int argc,char **argv)
{
KAboutData aboutData( "kode", I18N_NOOP("KDE Code Generator"), "0.1" );
aboutData.addAuthor( "Cornelius Schumacher", 0, "[email protected]" );
KCmdLineArgs::init( argc, argv, &aboutData );
KCmdLineArgs::addCmdLineOptions( options );
KApplication app;
KCmdLineArgs *args = KCmdLineArgs::parsedArgs();
if ( args->isSet( "create-class" ) || args->isSet( "create-dialog" ) ||
args->isSet( "create-kioslave" ) ) {
return create( args );
} else if ( args->isSet( "codify" ) ) {
return codify( args );
} else if ( args->isSet( "add-property" ) ) {
return addProperty( args );
} else {
std::cerr << "Error: No command given." << std::endl;
return 1;
}
}
|
Implement add-property option.
|
Implement add-property option.
svn path=/trunk/kdepim/; revision=359714
|
C++
|
lgpl-2.1
|
lefou/kdepim-noakonadi,lefou/kdepim-noakonadi,lefou/kdepim-noakonadi,lefou/kdepim-noakonadi,lefou/kdepim-noakonadi,lefou/kdepim-noakonadi
|
4c5dcca3a4e6c12cbe38b99fc6eb27b7e8188050
|
src/dinitctl.cc
|
src/dinitctl.cc
|
#include <cstdio>
#include <cstddef>
#include <cstring>
#include <string>
#include <iostream>
#include <system_error>
#include <sys/types.h>
#include <sys/socket.h>
#include <sys/un.h>
#include <unistd.h>
#include <pwd.h>
#include "control-cmds.h"
#include "service-constants.h"
#include "cpbuffer.h"
// dinitctl: utility to control the Dinit daemon, including starting and stopping of services.
// This utility communicates with the dinit daemon via a unix socket (/dev/initctl).
using handle_t = uint32_t;
class ReadCPException
{
public:
int errcode;
ReadCPException(int err) : errcode(err) { }
};
static void fillBufferTo(CPBuffer *buf, int fd, int rlength)
{
int r = buf->fillTo(fd, rlength);
if (r == -1) {
throw ReadCPException(errno);
}
else if (r == 0) {
throw ReadCPException(0);
}
}
static const char * describeState(bool stopped)
{
return stopped ? "stopped" : "started";
}
static const char * describeVerb(bool stop)
{
return stop ? "stop" : "start";
}
// Wait for a reply packet, skipping over any information packets
// that are received in the meantime.
static void wait_for_reply(CPBuffer &rbuffer, int fd)
{
fillBufferTo(&rbuffer, fd, 1);
while (rbuffer[0] >= 100) {
// Information packet; discard.
fillBufferTo(&rbuffer, fd, 1);
int pktlen = (unsigned char) rbuffer[1];
rbuffer.consume(1); // Consume one byte so we'll read one byte of the next packet
fillBufferTo(&rbuffer, fd, pktlen);
rbuffer.consume(pktlen - 1);
}
}
// Write *all* the requested buffer and re-try if necessary until
// the buffer is written or an unrecoverable error occurs.
static int write_all(int fd, const void *buf, size_t count)
{
const char *cbuf = static_cast<const char *>(buf);
int w = 0;
while (count > 0) {
int r = write(fd, cbuf, count);
if (r == -1) {
if (errno == EINTR) continue;
return r;
}
w += r;
cbuf += r;
count -= r;
}
return w;
}
// Entry point.
int main(int argc, char **argv)
{
using namespace std;
bool do_stop = false;
bool show_help = argc < 2;
char *service_name = nullptr;
std::string control_socket_str;
const char * control_socket_path = nullptr;
bool verbose = true;
bool sys_dinit = false; // communicate with system daemon
bool wait_for_service = true;
int command = 0;
constexpr int START_SERVICE = 1;
constexpr int STOP_SERVICE = 2;
for (int i = 1; i < argc; i++) {
if (argv[i][0] == '-') {
if (strcmp(argv[i], "--help") == 0) {
show_help = true;
break;
}
else if (strcmp(argv[i], "--no-wait") == 0) {
wait_for_service = false;
}
else if (strcmp(argv[i], "--quiet") == 0) {
verbose = false;
}
else if (strcmp(argv[i], "--system") == 0 || strcmp(argv[i], "-s") == 0) {
sys_dinit = true;
}
else {
cerr << "Unrecognized command-line parameter: " << argv[i] << endl;
return 1;
}
}
else if (command == 0) {
if (strcmp(argv[i], "start") == 0) {
command = START_SERVICE;
}
else if (strcmp(argv[i], "stop") == 0) {
command = STOP_SERVICE;
}
else {
show_help = true;
break;
}
}
else {
// service name
service_name = argv[i];
// TODO support multiple services (or at least give error if multiple
// services supplied)
}
}
if (service_name == nullptr || command == 0) {
show_help = true;
}
if (show_help) {
cout << "dinit-start: start a dinit service" << endl;
cout << " --help : show this help" << endl;
cout << " --no-wait : don't wait for service startup/shutdown to complete" << endl;
cout << " --quiet : suppress output (except errors)" << endl;
cout << " -s, --system : control system daemon instead of user daemon" << endl;
cout << " <service-name> : start the named service" << endl;
return 1;
}
do_stop = (command == STOP_SERVICE);
control_socket_path = "/dev/dinitctl";
if (! sys_dinit) {
char * userhome = getenv("HOME");
if (userhome == nullptr) {
struct passwd * pwuid_p = getpwuid(getuid());
if (pwuid_p != nullptr) {
userhome = pwuid_p->pw_dir;
}
}
if (userhome != nullptr) {
control_socket_str = userhome;
control_socket_str += "/.dinitctl";
control_socket_path = control_socket_str.c_str();
}
else {
cerr << "Cannot locate user home directory (set HOME or check /etc/passwd file)" << endl;
return 1;
}
}
int socknum = socket(AF_UNIX, SOCK_STREAM, 0);
if (socknum == -1) {
perror("socket");
return 1;
}
struct sockaddr_un * name;
uint sockaddr_size = offsetof(struct sockaddr_un, sun_path) + strlen(control_socket_path) + 1;
name = (struct sockaddr_un *) malloc(sockaddr_size);
if (name == nullptr) {
cerr << "dinit-start: out of memory" << endl;
return 1;
}
name->sun_family = AF_UNIX;
strcpy(name->sun_path, control_socket_path);
int connr = connect(socknum, (struct sockaddr *) name, sockaddr_size);
if (connr == -1) {
perror("connect");
return 1;
}
// TODO should start by querying protocol version
// Build buffer;
uint16_t sname_len = strlen(service_name);
int bufsize = 3 + sname_len;
char * buf = new char[bufsize];
buf[0] = DINIT_CP_LOADSERVICE;
memcpy(buf + 1, &sname_len, 2);
memcpy(buf + 3, service_name, sname_len);
int r = write_all(socknum, buf, bufsize);
delete [] buf;
if (r == -1) {
perror("write");
return 1;
}
// Now we expect a reply:
try {
CPBuffer rbuffer;
wait_for_reply(rbuffer, socknum);
//ServiceState state;
//ServiceState target_state;
handle_t handle;
if (rbuffer[0] == DINIT_RP_SERVICERECORD) {
fillBufferTo(&rbuffer, socknum, 2 + sizeof(handle));
rbuffer.extract((char *) &handle, 2, sizeof(handle));
//state = static_cast<ServiceState>(rbuffer[1]);
//target_state = static_cast<ServiceState>(rbuffer[2 + sizeof(handle)]);
rbuffer.consume(3 + sizeof(handle));
}
else if (rbuffer[0] == DINIT_RP_NOSERVICE) {
cerr << "Failed to find/load service." << endl;
return 1;
}
else {
cerr << "Protocol error." << endl;
return 1;
}
// ServiceState wanted_state = do_stop ? ServiceState::STOPPED : ServiceState::STARTED;
int command = do_stop ? DINIT_CP_STOPSERVICE : DINIT_CP_STARTSERVICE;
// Need to issue STOPSERVICE/STARTSERVICE
// We'll do this regardless of the current service state / target state, since issuing
// start/stop also sets or clears the "explicitly started" flag on the service.
//if (target_state != wanted_state) {
{
buf = new char[2 + sizeof(handle)];
buf[0] = command;
buf[1] = 0; // don't pin
memcpy(buf + 2, &handle, sizeof(handle));
r = write_all(socknum, buf, 2 + sizeof(handle));
delete buf;
if (r == -1) {
perror("write");
return 1;
}
wait_for_reply(rbuffer, socknum);
if (rbuffer[0] == DINIT_RP_ALREADYSS) {
if (verbose) {
cout << "Service already " << describeState(do_stop) << "." << endl;
}
return 0; // success!
}
if (rbuffer[0] != DINIT_RP_ACK) {
cerr << "Protocol error." << endl;
return 1;
}
rbuffer.consume(1);
}
/*
if (state == wanted_state) {
if (verbose) {
cout << "Service already " << describeState(do_stop) << "." << endl;
}
return 0; // success!
}
*/
if (! wait_for_service) {
if (verbose) {
cout << "Issued " << describeVerb(do_stop) << " command successfully." << endl;
}
return 0;
}
ServiceEvent completionEvent;
ServiceEvent cancelledEvent;
if (do_stop) {
completionEvent = ServiceEvent::STOPPED;
cancelledEvent = ServiceEvent::STOPCANCELLED;
}
else {
completionEvent = ServiceEvent::STARTED;
cancelledEvent = ServiceEvent::STARTCANCELLED;
}
// Wait until service started:
r = rbuffer.fillTo(socknum, 2);
while (r > 0) {
if (rbuffer[0] >= 100) {
int pktlen = (unsigned char) rbuffer[1];
fillBufferTo(&rbuffer, socknum, pktlen);
if (rbuffer[0] == DINIT_IP_SERVICEEVENT) {
handle_t ev_handle;
rbuffer.extract((char *) &ev_handle, 2, sizeof(ev_handle));
ServiceEvent event = static_cast<ServiceEvent>(rbuffer[2 + sizeof(ev_handle)]);
if (ev_handle == handle) {
if (event == completionEvent) {
if (verbose) {
cout << "Service " << describeState(do_stop) << "." << endl;
}
return 0;
}
else if (event == cancelledEvent) {
if (verbose) {
cout << "Service " << describeVerb(do_stop) << " cancelled." << endl;
}
return 1;
}
else if (! do_stop && event == ServiceEvent::FAILEDSTART) {
if (verbose) {
cout << "Service failed to start." << endl;
}
return 1;
}
}
}
rbuffer.consume(pktlen);
r = rbuffer.fillTo(socknum, 2);
}
else {
// Not an information packet?
cerr << "protocol error" << endl;
return 1;
}
}
if (r == -1) {
perror("read");
}
else {
cerr << "protocol error (connection closed by server)" << endl;
}
return 1;
}
catch (ReadCPException &exc) {
cerr << "control socket read failure or protocol error" << endl;
return 1;
}
catch (std::bad_alloc &exc) {
cerr << "out of memory" << endl;
return 1;
}
return 0;
}
|
#include <cstdio>
#include <cstddef>
#include <cstring>
#include <string>
#include <iostream>
#include <system_error>
#include <sys/types.h>
#include <sys/socket.h>
#include <sys/un.h>
#include <unistd.h>
#include <pwd.h>
#include "control-cmds.h"
#include "service-constants.h"
#include "cpbuffer.h"
// dinitctl: utility to control the Dinit daemon, including starting and stopping of services.
// This utility communicates with the dinit daemon via a unix socket (/dev/initctl).
using handle_t = uint32_t;
class ReadCPException
{
public:
int errcode;
ReadCPException(int err) : errcode(err) { }
};
static void fillBufferTo(CPBuffer *buf, int fd, int rlength)
{
int r = buf->fillTo(fd, rlength);
if (r == -1) {
throw ReadCPException(errno);
}
else if (r == 0) {
throw ReadCPException(0);
}
}
static const char * describeState(bool stopped)
{
return stopped ? "stopped" : "started";
}
static const char * describeVerb(bool stop)
{
return stop ? "stop" : "start";
}
// Wait for a reply packet, skipping over any information packets
// that are received in the meantime.
static void wait_for_reply(CPBuffer &rbuffer, int fd)
{
fillBufferTo(&rbuffer, fd, 1);
while (rbuffer[0] >= 100) {
// Information packet; discard.
fillBufferTo(&rbuffer, fd, 1);
int pktlen = (unsigned char) rbuffer[1];
rbuffer.consume(1); // Consume one byte so we'll read one byte of the next packet
fillBufferTo(&rbuffer, fd, pktlen);
rbuffer.consume(pktlen - 1);
}
}
// Write *all* the requested buffer and re-try if necessary until
// the buffer is written or an unrecoverable error occurs.
static int write_all(int fd, const void *buf, size_t count)
{
const char *cbuf = static_cast<const char *>(buf);
int w = 0;
while (count > 0) {
int r = write(fd, cbuf, count);
if (r == -1) {
if (errno == EINTR) continue;
return r;
}
w += r;
cbuf += r;
count -= r;
}
return w;
}
// Entry point.
int main(int argc, char **argv)
{
using namespace std;
bool do_stop = false;
bool show_help = argc < 2;
char *service_name = nullptr;
std::string control_socket_str;
const char * control_socket_path = nullptr;
bool verbose = true;
bool sys_dinit = false; // communicate with system daemon
bool wait_for_service = true;
bool do_pin = false;
int command = 0;
constexpr int START_SERVICE = 1;
constexpr int STOP_SERVICE = 2;
for (int i = 1; i < argc; i++) {
if (argv[i][0] == '-') {
if (strcmp(argv[i], "--help") == 0) {
show_help = true;
break;
}
else if (strcmp(argv[i], "--no-wait") == 0) {
wait_for_service = false;
}
else if (strcmp(argv[i], "--quiet") == 0) {
verbose = false;
}
else if (strcmp(argv[i], "--system") == 0 || strcmp(argv[i], "-s") == 0) {
sys_dinit = true;
}
else if (strcmp(argv[i], "--pin") == 0) {
do_pin = true;
}
else {
cerr << "Unrecognized command-line parameter: " << argv[i] << endl;
return 1;
}
}
else if (command == 0) {
if (strcmp(argv[i], "start") == 0) {
command = START_SERVICE;
}
else if (strcmp(argv[i], "stop") == 0) {
command = STOP_SERVICE;
}
else {
show_help = true;
break;
}
}
else {
// service name
service_name = argv[i];
// TODO support multiple services (or at least give error if multiple
// services supplied)
}
}
if (service_name == nullptr || command == 0) {
show_help = true;
}
if (show_help) {
cout << "dinitctl: control Dinit services" << endl;
cout << "\nUsage:" << endl;
cout << " dinitctl [options] start [options] <service-name> : start and activate service" << endl;
cout << " dinitctl [options] stop [options] <service-name> : stop service and cancel explicit activation" << endl;
// TODO:
// cout << " dinitctl [options] wake <service-name> : start but don't activate service" << endl;
cout << "\nNote: An activated service keeps its dependencies running when possible." << endl;
cout << "\nGeneral options:" << endl;
cout << " -s, --system : control system daemon instead of user daemon" << endl;
cout << " --quiet : suppress output (except errors)" << endl;
cout << "\nCommand options:" << endl;
cout << " --help : show this help" << endl;
cout << " --no-wait : don't wait for service startup/shutdown to complete" << endl;
cout << " --pin : pin the service in the requested (started/stopped) state" << endl;
return 1;
}
do_stop = (command == STOP_SERVICE);
control_socket_path = "/dev/dinitctl";
if (! sys_dinit) {
char * userhome = getenv("HOME");
if (userhome == nullptr) {
struct passwd * pwuid_p = getpwuid(getuid());
if (pwuid_p != nullptr) {
userhome = pwuid_p->pw_dir;
}
}
if (userhome != nullptr) {
control_socket_str = userhome;
control_socket_str += "/.dinitctl";
control_socket_path = control_socket_str.c_str();
}
else {
cerr << "Cannot locate user home directory (set HOME or check /etc/passwd file)" << endl;
return 1;
}
}
int socknum = socket(AF_UNIX, SOCK_STREAM, 0);
if (socknum == -1) {
perror("socket");
return 1;
}
struct sockaddr_un * name;
uint sockaddr_size = offsetof(struct sockaddr_un, sun_path) + strlen(control_socket_path) + 1;
name = (struct sockaddr_un *) malloc(sockaddr_size);
if (name == nullptr) {
cerr << "dinit-start: out of memory" << endl;
return 1;
}
name->sun_family = AF_UNIX;
strcpy(name->sun_path, control_socket_path);
int connr = connect(socknum, (struct sockaddr *) name, sockaddr_size);
if (connr == -1) {
perror("connect");
return 1;
}
// TODO should start by querying protocol version
// Build buffer;
uint16_t sname_len = strlen(service_name);
int bufsize = 3 + sname_len;
char * buf = new char[bufsize];
buf[0] = DINIT_CP_LOADSERVICE;
memcpy(buf + 1, &sname_len, 2);
memcpy(buf + 3, service_name, sname_len);
int r = write_all(socknum, buf, bufsize);
delete [] buf;
if (r == -1) {
perror("write");
return 1;
}
// Now we expect a reply:
try {
CPBuffer rbuffer;
wait_for_reply(rbuffer, socknum);
//ServiceState state;
//ServiceState target_state;
handle_t handle;
if (rbuffer[0] == DINIT_RP_SERVICERECORD) {
fillBufferTo(&rbuffer, socknum, 2 + sizeof(handle));
rbuffer.extract((char *) &handle, 2, sizeof(handle));
//state = static_cast<ServiceState>(rbuffer[1]);
//target_state = static_cast<ServiceState>(rbuffer[2 + sizeof(handle)]);
rbuffer.consume(3 + sizeof(handle));
}
else if (rbuffer[0] == DINIT_RP_NOSERVICE) {
cerr << "Failed to find/load service." << endl;
return 1;
}
else {
cerr << "Protocol error." << endl;
return 1;
}
// ServiceState wanted_state = do_stop ? ServiceState::STOPPED : ServiceState::STARTED;
int command = do_stop ? DINIT_CP_STOPSERVICE : DINIT_CP_STARTSERVICE;
// Need to issue STOPSERVICE/STARTSERVICE
// We'll do this regardless of the current service state / target state, since issuing
// start/stop also sets or clears the "explicitly started" flag on the service.
//if (target_state != wanted_state) {
{
buf = new char[2 + sizeof(handle)];
buf[0] = command;
buf[1] = do_pin ? 1 : 0;
memcpy(buf + 2, &handle, sizeof(handle));
r = write_all(socknum, buf, 2 + sizeof(handle));
delete buf;
if (r == -1) {
perror("write");
return 1;
}
wait_for_reply(rbuffer, socknum);
if (rbuffer[0] == DINIT_RP_ALREADYSS) {
if (verbose) {
cout << "Service already " << describeState(do_stop) << "." << endl;
}
return 0; // success!
}
if (rbuffer[0] != DINIT_RP_ACK) {
cerr << "Protocol error." << endl;
return 1;
}
rbuffer.consume(1);
}
/*
if (state == wanted_state) {
if (verbose) {
cout << "Service already " << describeState(do_stop) << "." << endl;
}
return 0; // success!
}
*/
if (! wait_for_service) {
if (verbose) {
cout << "Issued " << describeVerb(do_stop) << " command successfully." << endl;
}
return 0;
}
ServiceEvent completionEvent;
ServiceEvent cancelledEvent;
if (do_stop) {
completionEvent = ServiceEvent::STOPPED;
cancelledEvent = ServiceEvent::STOPCANCELLED;
}
else {
completionEvent = ServiceEvent::STARTED;
cancelledEvent = ServiceEvent::STARTCANCELLED;
}
// Wait until service started:
r = rbuffer.fillTo(socknum, 2);
while (r > 0) {
if (rbuffer[0] >= 100) {
int pktlen = (unsigned char) rbuffer[1];
fillBufferTo(&rbuffer, socknum, pktlen);
if (rbuffer[0] == DINIT_IP_SERVICEEVENT) {
handle_t ev_handle;
rbuffer.extract((char *) &ev_handle, 2, sizeof(ev_handle));
ServiceEvent event = static_cast<ServiceEvent>(rbuffer[2 + sizeof(ev_handle)]);
if (ev_handle == handle) {
if (event == completionEvent) {
if (verbose) {
cout << "Service " << describeState(do_stop) << "." << endl;
}
return 0;
}
else if (event == cancelledEvent) {
if (verbose) {
cout << "Service " << describeVerb(do_stop) << " cancelled." << endl;
}
return 1;
}
else if (! do_stop && event == ServiceEvent::FAILEDSTART) {
if (verbose) {
cout << "Service failed to start." << endl;
}
return 1;
}
}
}
rbuffer.consume(pktlen);
r = rbuffer.fillTo(socknum, 2);
}
else {
// Not an information packet?
cerr << "protocol error" << endl;
return 1;
}
}
if (r == -1) {
perror("read");
}
else {
cerr << "protocol error (connection closed by server)" << endl;
}
return 1;
}
catch (ReadCPException &exc) {
cerr << "control socket read failure or protocol error" << endl;
return 1;
}
catch (std::bad_alloc &exc) {
cerr << "out of memory" << endl;
return 1;
}
return 0;
}
|
Add support for pinning services to dinitctl
|
Add support for pinning services to dinitctl
|
C++
|
apache-2.0
|
davmac314/dinit,davmac314/dinit,davmac314/dinit
|
376154353d54add4b9f7f3bf0ba934bf03e2de4b
|
src/modules/decklink/common.cpp
|
src/modules/decklink/common.cpp
|
/*
* common.cpp -- Blackmagic Design DeckLink common functions
* Copyright (C) 2012 Dan Dennedy <[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 consumer library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
#include "common.h"
#include <stdlib.h>
#ifdef __DARWIN__
char* getCString( DLString aDLString )
{
char* CString = (char*) malloc( 64 );
CFStringGetCString( aDLString, CString, 64, kCFStringEncodingMacRoman );
return CString;
}
void freeCString( char* aCString )
{
if ( aCString ) free( aCString );
}
void freeDLString( DLString aDLString )
{
if ( aDLString ) CFRelease( aDLString );
}
#else
char* getCString( DLString aDLString )
{
return aDLString? (char*) aDLString : NULL;
}
void freeCString( char* aCString )
{
}
void freeDLString( DLString aDLString )
{
if ( aDLString ) free( (void*) aDLString );
}
#endif
|
/*
* common.cpp -- Blackmagic Design DeckLink common functions
* Copyright (C) 2012 Dan Dennedy <[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 consumer library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
#include "common.h"
#include <stdlib.h>
#ifdef __DARWIN__
char* getCString( DLString aDLString )
{
char* CString = (char*) malloc( 64 );
CFStringGetCString( aDLString, CString, 64, kCFStringEncodingMacRoman );
return CString;
}
void freeCString( char* aCString )
{
if ( aCString ) free( aCString );
}
void freeDLString( DLString aDLString )
{
if ( aDLString ) CFRelease( aDLString );
}
#elif defined(WIN32)
char* getCString( DLString aDLString )
{
char* CString = NULL;
if ( aDLString )
{
int size = WideCharToMultiByte( CP_UTF8, 0, aDLString, -1, NULL, 0, NULL, NULL );
if (size)
{
CString = new char[ size ];
size = WideCharToMultiByte( CP_UTF8, 0, aDLString, -1, CString, size, NULL, NULL );
if ( !size )
{
delete[] CString;
CString = NULL;
}
}
}
return CString;
}
void freeCString( char* aCString )
{
delete[] aCString;
}
void freeDLString( DLString aDLString )
{
if ( aDLString ) free( (void*) aDLString );
}
#else
char* getCString( DLString aDLString )
{
return aDLString? (char*) aDLString : NULL;
}
void freeCString( char* aCString )
{
}
void freeDLString( DLString aDLString )
{
if ( aDLString ) free( (void*) aDLString );
}
#endif
|
fix BSTR string conversion under Windows
|
fix BSTR string conversion under Windows
|
C++
|
lgpl-2.1
|
zzhhui/mlt,xzhavilla/mlt,mltframework/mlt,j-b-m/mlt,zzhhui/mlt,wideioltd/mlt,gmarco/mlt-orig,gmarco/mlt-orig,xzhavilla/mlt,mltframework/mlt,zzhhui/mlt,anba8005/mlt,xzhavilla/mlt,siddharudh/mlt,siddharudh/mlt,wideioltd/mlt,wideioltd/mlt,wideioltd/mlt,zzhhui/mlt,siddharudh/mlt,j-b-m/mlt,mltframework/mlt,xzhavilla/mlt,gmarco/mlt-orig,gmarco/mlt-orig,siddharudh/mlt,xzhavilla/mlt,siddharudh/mlt,xzhavilla/mlt,gmarco/mlt-orig,mltframework/mlt,xzhavilla/mlt,j-b-m/mlt,wideioltd/mlt,anba8005/mlt,mltframework/mlt,anba8005/mlt,anba8005/mlt,siddharudh/mlt,mltframework/mlt,zzhhui/mlt,gmarco/mlt-orig,siddharudh/mlt,mltframework/mlt,zzhhui/mlt,j-b-m/mlt,mltframework/mlt,wideioltd/mlt,anba8005/mlt,wideioltd/mlt,anba8005/mlt,mltframework/mlt,j-b-m/mlt,gmarco/mlt-orig,j-b-m/mlt,anba8005/mlt,anba8005/mlt,j-b-m/mlt,gmarco/mlt-orig,siddharudh/mlt,gmarco/mlt-orig,j-b-m/mlt,anba8005/mlt,mltframework/mlt,j-b-m/mlt,wideioltd/mlt,siddharudh/mlt,zzhhui/mlt,zzhhui/mlt,j-b-m/mlt,zzhhui/mlt,wideioltd/mlt,xzhavilla/mlt,xzhavilla/mlt
|
5e35de08724b3596db99c08cc04fa653b30ff9bd
|
distrho/src/DistrhoUIDSSI.cpp
|
distrho/src/DistrhoUIDSSI.cpp
|
/*
* DISTRHO Plugin Framework (DPF)
* Copyright (C) 2012-2016 Filipe Coelho <[email protected]>
*
* Permission to use, copy, modify, and/or distribute this software for any purpose with
* or without fee is hereby granted, provided that the above copyright notice and this
* permission notice appear in all copies.
*
* THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD
* TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN
* NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL
* DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER
* IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN
* CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
*/
#include "DistrhoUIInternal.hpp"
#if DISTRHO_PLUGIN_WANT_DIRECT_ACCESS
# error DSSI UIs do not support direct access!
#endif
#include "../extra/Sleep.hpp"
#include <lo/lo.h>
START_NAMESPACE_DISTRHO
#if ! DISTRHO_PLUGIN_WANT_MIDI_INPUT
static const sendNoteFunc sendNoteCallback = nullptr;
#endif
// -----------------------------------------------------------------------
struct OscData {
lo_address addr;
const char* path;
lo_server server;
OscData()
: addr(nullptr),
path(nullptr),
server(nullptr) {}
void idle() const
{
if (server == nullptr)
return;
while (lo_server_recv_noblock(server, 0) != 0) {}
}
void send_configure(const char* const key, const char* const value) const
{
char targetPath[std::strlen(path)+11];
std::strcpy(targetPath, path);
std::strcat(targetPath, "/configure");
lo_send(addr, targetPath, "ss", key, value);
}
void send_control(const int32_t index, const float value) const
{
char targetPath[std::strlen(path)+9];
std::strcpy(targetPath, path);
std::strcat(targetPath, "/control");
lo_send(addr, targetPath, "if", index, value);
}
void send_midi(uchar data[4]) const
{
char targetPath[std::strlen(path)+6];
std::strcpy(targetPath, path);
std::strcat(targetPath, "/midi");
lo_send(addr, targetPath, "m", data);
}
void send_update(const char* const url) const
{
char targetPath[std::strlen(path)+8];
std::strcpy(targetPath, path);
std::strcat(targetPath, "/update");
lo_send(addr, targetPath, "s", url);
}
void send_exiting() const
{
char targetPath[std::strlen(path)+9];
std::strcpy(targetPath, path);
std::strcat(targetPath, "/exiting");
lo_send(addr, targetPath, "");
}
};
// -----------------------------------------------------------------------
class UIDssi
{
public:
UIDssi(const OscData& oscData, const char* const uiTitle)
: fUI(this, 0, nullptr, setParameterCallback, setStateCallback, sendNoteCallback, setSizeCallback),
fHostClosed(false),
fOscData(oscData)
{
fUI.setWindowTitle(uiTitle);
}
~UIDssi()
{
if (fOscData.server != nullptr && ! fHostClosed)
fOscData.send_exiting();
}
void exec()
{
d_stdout("exec 1");
for (;;)
{
fOscData.idle();
if (fHostClosed || ! fUI.idle())
break;
d_msleep(30);
}
d_stdout("exec 3");
}
// -------------------------------------------------------------------
#if DISTRHO_PLUGIN_WANT_STATE
void dssiui_configure(const char* key, const char* value)
{
fUI.stateChanged(key, value);
}
#endif
void dssiui_control(ulong index, float value)
{
fUI.parameterChanged(index, value);
}
#if DISTRHO_PLUGIN_WANT_PROGRAMS
void dssiui_program(ulong bank, ulong program)
{
fUI.programLoaded(bank * 128 + program);
}
#endif
void dssiui_samplerate(const double sampleRate)
{
fUI.setSampleRate(sampleRate, true);
}
void dssiui_show()
{
fUI.setWindowVisible(true);
}
void dssiui_hide()
{
fUI.setWindowVisible(false);
}
void dssiui_quit()
{
fHostClosed = true;
fUI.quit();
}
// -------------------------------------------------------------------
protected:
void setParameterValue(const uint32_t rindex, const float value)
{
if (fOscData.server == nullptr)
return;
fOscData.send_control(rindex, value);
}
void setState(const char* const key, const char* const value)
{
if (fOscData.server == nullptr)
return;
fOscData.send_configure(key, value);
}
#if DISTRHO_PLUGIN_WANT_MIDI_INPUT
void sendNote(const uint8_t channel, const uint8_t note, const uint8_t velocity)
{
if (fOscData.server == nullptr)
return;
if (channel > 0xF)
return;
uint8_t mdata[4] = {
0,
static_cast<uint8_t>(channel + (velocity != 0 ? 0x90 : 0x80)),
note,
velocity
};
fOscData.send_midi(mdata);
}
#endif
void setSize(const uint width, const uint height)
{
fUI.setWindowSize(width, height);
}
private:
UIExporter fUI;
bool fHostClosed;
const OscData& fOscData;
// -------------------------------------------------------------------
// Callbacks
#define uiPtr ((UIDssi*)ptr)
static void setParameterCallback(void* ptr, uint32_t rindex, float value)
{
uiPtr->setParameterValue(rindex, value);
}
static void setStateCallback(void* ptr, const char* key, const char* value)
{
uiPtr->setState(key, value);
}
#if DISTRHO_PLUGIN_WANT_MIDI_INPUT
static void sendNoteCallback(void* ptr, uint8_t channel, uint8_t note, uint8_t velocity)
{
uiPtr->sendNote(channel, note, velocity);
}
#endif
static void setSizeCallback(void* ptr, uint width, uint height)
{
uiPtr->setSize(width, height);
}
#undef uiPtr
};
// -----------------------------------------------------------------------
static OscData gOscData;
static const char* gUiTitle = nullptr;
static UIDssi* globalUI = nullptr;
static void initUiIfNeeded()
{
if (globalUI != nullptr)
return;
if (d_lastUiSampleRate == 0.0)
d_lastUiSampleRate = 44100.0;
globalUI = new UIDssi(gOscData, gUiTitle);
}
// -----------------------------------------------------------------------
int osc_debug_handler(const char* path, const char*, lo_arg**, int, lo_message, void*)
{
d_debug("osc_debug_handler(\"%s\")", path);
return 0;
#ifndef DEBUG
// unused
(void)path;
#endif
}
void osc_error_handler(int num, const char* msg, const char* path)
{
d_stderr("osc_error_handler(%i, \"%s\", \"%s\")", num, msg, path);
}
#if DISTRHO_PLUGIN_WANT_STATE
int osc_configure_handler(const char*, const char*, lo_arg** argv, int, lo_message, void*)
{
const char* const key = &argv[0]->s;
const char* const value = &argv[1]->s;
d_debug("osc_configure_handler(\"%s\", \"%s\")", key, value);
initUiIfNeeded();
globalUI->dssiui_configure(key, value);
return 0;
}
#endif
int osc_control_handler(const char*, const char*, lo_arg** argv, int, lo_message, void*)
{
const int32_t rindex = argv[0]->i;
const float value = argv[1]->f;
d_debug("osc_control_handler(%i, %f)", rindex, value);
int32_t index = rindex - DISTRHO_PLUGIN_NUM_INPUTS - DISTRHO_PLUGIN_NUM_OUTPUTS;
// latency
#if DISTRHO_PLUGIN_WANT_LATENCY
index -= 1;
#endif
if (index < 0)
return 0;
initUiIfNeeded();
globalUI->dssiui_control(index, value);
return 0;
}
#if DISTRHO_PLUGIN_WANT_PROGRAMS
int osc_program_handler(const char*, const char*, lo_arg** argv, int, lo_message, void*)
{
const int32_t bank = argv[0]->i;
const int32_t program = argv[1]->f;
d_debug("osc_program_handler(%i, %i)", bank, program);
initUiIfNeeded();
globalUI->dssiui_program(bank, program);
return 0;
}
#endif
int osc_sample_rate_handler(const char*, const char*, lo_arg** argv, int, lo_message, void*)
{
const int32_t sampleRate = argv[0]->i;
d_debug("osc_sample_rate_handler(%i)", sampleRate);
d_lastUiSampleRate = sampleRate;
if (globalUI != nullptr)
globalUI->dssiui_samplerate(sampleRate);
return 0;
}
int osc_show_handler(const char*, const char*, lo_arg**, int, lo_message, void*)
{
d_debug("osc_show_handler()");
initUiIfNeeded();
globalUI->dssiui_show();
return 0;
}
int osc_hide_handler(const char*, const char*, lo_arg**, int, lo_message, void*)
{
d_debug("osc_hide_handler()");
if (globalUI != nullptr)
globalUI->dssiui_hide();
return 0;
}
int osc_quit_handler(const char*, const char*, lo_arg**, int, lo_message, void*)
{
d_debug("osc_quit_handler()");
if (globalUI != nullptr)
globalUI->dssiui_quit();
return 0;
}
END_NAMESPACE_DISTRHO
// -----------------------------------------------------------------------
int main(int argc, char* argv[])
{
USE_NAMESPACE_DISTRHO
// dummy test mode
if (argc == 1)
{
gUiTitle = "DSSI UI Test";
initUiIfNeeded();
globalUI->dssiui_show();
globalUI->exec();
delete globalUI;
globalUI = nullptr;
return 0;
}
if (argc != 5)
{
fprintf(stderr, "Usage: %s <osc-url> <plugin-dll> <plugin-label> <instance-name>\n", argv[0]);
return 1;
}
const char* oscUrl = argv[1];
const char* uiTitle = argv[4];
char* const oscHost = lo_url_get_hostname(oscUrl);
char* const oscPort = lo_url_get_port(oscUrl);
char* const oscPath = lo_url_get_path(oscUrl);
size_t oscPathSize = strlen(oscPath);
lo_address oscAddr = lo_address_new(oscHost, oscPort);
lo_server oscServer = lo_server_new_with_proto(nullptr, LO_UDP, osc_error_handler);
char* const oscServerPath = lo_server_get_url(oscServer);
char pluginPath[strlen(oscServerPath)+oscPathSize];
strcpy(pluginPath, oscServerPath);
strcat(pluginPath, oscPath+1);
#if DISTRHO_PLUGIN_WANT_STATE
char oscPathConfigure[oscPathSize+11];
strcpy(oscPathConfigure, oscPath);
strcat(oscPathConfigure, "/configure");
lo_server_add_method(oscServer, oscPathConfigure, "ss", osc_configure_handler, nullptr);
#endif
char oscPathControl[oscPathSize+9];
strcpy(oscPathControl, oscPath);
strcat(oscPathControl, "/control");
lo_server_add_method(oscServer, oscPathControl, "if", osc_control_handler, nullptr);
d_stdout("oscServerPath: \"%s\"", oscServerPath);
d_stdout("pluginPath: \"%s\"", pluginPath);
d_stdout("oscPathControl: \"%s\"", oscPathControl);
#if DISTRHO_PLUGIN_WANT_PROGRAMS
char oscPathProgram[oscPathSize+9];
strcpy(oscPathProgram, oscPath);
strcat(oscPathProgram, "/program");
lo_server_add_method(oscServer, oscPathProgram, "ii", osc_program_handler, nullptr);
#endif
char oscPathSampleRate[oscPathSize+13];
strcpy(oscPathSampleRate, oscPath);
strcat(oscPathSampleRate, "/sample-rate");
lo_server_add_method(oscServer, oscPathSampleRate, "i", osc_sample_rate_handler, nullptr);
char oscPathShow[oscPathSize+6];
strcpy(oscPathShow, oscPath);
strcat(oscPathShow, "/show");
lo_server_add_method(oscServer, oscPathShow, "", osc_show_handler, nullptr);
char oscPathHide[oscPathSize+6];
strcpy(oscPathHide, oscPath);
strcat(oscPathHide, "/hide");
lo_server_add_method(oscServer, oscPathHide, "", osc_hide_handler, nullptr);
char oscPathQuit[oscPathSize+6];
strcpy(oscPathQuit, oscPath);
strcat(oscPathQuit, "/quit");
lo_server_add_method(oscServer, oscPathQuit, "", osc_quit_handler, nullptr);
lo_server_add_method(oscServer, nullptr, nullptr, osc_debug_handler, nullptr);
gUiTitle = uiTitle;
gOscData.addr = oscAddr;
gOscData.path = oscPath;
gOscData.server = oscServer;
gOscData.send_update(pluginPath);
// wait for init
for (int i=0; i < 100; ++i)
{
lo_server_recv(oscServer);
if (d_lastUiSampleRate != 0.0 || globalUI != nullptr)
break;
d_msleep(50);
}
int ret = 1;
if (d_lastUiSampleRate != 0.0 || globalUI != nullptr)
{
initUiIfNeeded();
globalUI->exec();
delete globalUI;
globalUI = nullptr;
ret = 0;
}
#if DISTRHO_PLUGIN_WANT_STATE
lo_server_del_method(oscServer, oscPathConfigure, "ss");
#endif
lo_server_del_method(oscServer, oscPathControl, "if");
#if DISTRHO_PLUGIN_WANT_PROGRAMS
lo_server_del_method(oscServer, oscPathProgram, "ii");
#endif
lo_server_del_method(oscServer, oscPathSampleRate, "i");
lo_server_del_method(oscServer, oscPathShow, "");
lo_server_del_method(oscServer, oscPathHide, "");
lo_server_del_method(oscServer, oscPathQuit, "");
lo_server_del_method(oscServer, nullptr, nullptr);
std::free(oscServerPath);
std::free(oscHost);
std::free(oscPort);
std::free(oscPath);
lo_address_free(oscAddr);
lo_server_free(oscServer);
return ret;
}
|
/*
* DISTRHO Plugin Framework (DPF)
* Copyright (C) 2012-2016 Filipe Coelho <[email protected]>
*
* Permission to use, copy, modify, and/or distribute this software for any purpose with
* or without fee is hereby granted, provided that the above copyright notice and this
* permission notice appear in all copies.
*
* THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD
* TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN
* NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL
* DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER
* IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN
* CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
*/
#include "DistrhoUIInternal.hpp"
#if DISTRHO_PLUGIN_WANT_DIRECT_ACCESS
# error DSSI UIs do not support direct access!
#endif
#include "../extra/Sleep.hpp"
#include <lo/lo.h>
START_NAMESPACE_DISTRHO
#if ! DISTRHO_PLUGIN_WANT_MIDI_INPUT
static const sendNoteFunc sendNoteCallback = nullptr;
#endif
// -----------------------------------------------------------------------
struct OscData {
lo_address addr;
const char* path;
lo_server server;
OscData()
: addr(nullptr),
path(nullptr),
server(nullptr) {}
void idle() const
{
if (server == nullptr)
return;
while (lo_server_recv_noblock(server, 0) != 0) {}
}
void send_configure(const char* const key, const char* const value) const
{
char targetPath[std::strlen(path)+11];
std::strcpy(targetPath, path);
std::strcat(targetPath, "/configure");
lo_send(addr, targetPath, "ss", key, value);
}
void send_control(const int32_t index, const float value) const
{
char targetPath[std::strlen(path)+9];
std::strcpy(targetPath, path);
std::strcat(targetPath, "/control");
lo_send(addr, targetPath, "if", index, value);
}
void send_midi(uchar data[4]) const
{
char targetPath[std::strlen(path)+6];
std::strcpy(targetPath, path);
std::strcat(targetPath, "/midi");
lo_send(addr, targetPath, "m", data);
}
void send_update(const char* const url) const
{
char targetPath[std::strlen(path)+8];
std::strcpy(targetPath, path);
std::strcat(targetPath, "/update");
lo_send(addr, targetPath, "s", url);
}
void send_exiting() const
{
char targetPath[std::strlen(path)+9];
std::strcpy(targetPath, path);
std::strcat(targetPath, "/exiting");
lo_send(addr, targetPath, "");
}
};
// -----------------------------------------------------------------------
class UIDssi
{
public:
UIDssi(const OscData& oscData, const char* const uiTitle)
: fUI(this, 0, nullptr, setParameterCallback, setStateCallback, sendNoteCallback, setSizeCallback),
fHostClosed(false),
fOscData(oscData)
{
fUI.setWindowTitle(uiTitle);
}
~UIDssi()
{
if (fOscData.server != nullptr && ! fHostClosed)
fOscData.send_exiting();
}
void exec()
{
for (;;)
{
fOscData.idle();
if (fHostClosed || ! fUI.idle())
break;
d_msleep(30);
}
}
// -------------------------------------------------------------------
#if DISTRHO_PLUGIN_WANT_STATE
void dssiui_configure(const char* key, const char* value)
{
fUI.stateChanged(key, value);
}
#endif
void dssiui_control(ulong index, float value)
{
fUI.parameterChanged(index, value);
}
#if DISTRHO_PLUGIN_WANT_PROGRAMS
void dssiui_program(ulong bank, ulong program)
{
fUI.programLoaded(bank * 128 + program);
}
#endif
void dssiui_samplerate(const double sampleRate)
{
fUI.setSampleRate(sampleRate, true);
}
void dssiui_show()
{
fUI.setWindowVisible(true);
}
void dssiui_hide()
{
fUI.setWindowVisible(false);
}
void dssiui_quit()
{
fHostClosed = true;
fUI.quit();
}
// -------------------------------------------------------------------
protected:
void setParameterValue(const uint32_t rindex, const float value)
{
if (fOscData.server == nullptr)
return;
fOscData.send_control(rindex, value);
}
void setState(const char* const key, const char* const value)
{
if (fOscData.server == nullptr)
return;
fOscData.send_configure(key, value);
}
#if DISTRHO_PLUGIN_WANT_MIDI_INPUT
void sendNote(const uint8_t channel, const uint8_t note, const uint8_t velocity)
{
if (fOscData.server == nullptr)
return;
if (channel > 0xF)
return;
uint8_t mdata[4] = {
0,
static_cast<uint8_t>(channel + (velocity != 0 ? 0x90 : 0x80)),
note,
velocity
};
fOscData.send_midi(mdata);
}
#endif
void setSize(const uint width, const uint height)
{
fUI.setWindowSize(width, height);
}
private:
UIExporter fUI;
bool fHostClosed;
const OscData& fOscData;
// -------------------------------------------------------------------
// Callbacks
#define uiPtr ((UIDssi*)ptr)
static void setParameterCallback(void* ptr, uint32_t rindex, float value)
{
uiPtr->setParameterValue(rindex, value);
}
static void setStateCallback(void* ptr, const char* key, const char* value)
{
uiPtr->setState(key, value);
}
#if DISTRHO_PLUGIN_WANT_MIDI_INPUT
static void sendNoteCallback(void* ptr, uint8_t channel, uint8_t note, uint8_t velocity)
{
uiPtr->sendNote(channel, note, velocity);
}
#endif
static void setSizeCallback(void* ptr, uint width, uint height)
{
uiPtr->setSize(width, height);
}
#undef uiPtr
};
// -----------------------------------------------------------------------
static OscData gOscData;
static const char* gUiTitle = nullptr;
static UIDssi* globalUI = nullptr;
static void initUiIfNeeded()
{
if (globalUI != nullptr)
return;
if (d_lastUiSampleRate == 0.0)
d_lastUiSampleRate = 44100.0;
globalUI = new UIDssi(gOscData, gUiTitle);
}
// -----------------------------------------------------------------------
int osc_debug_handler(const char* path, const char*, lo_arg**, int, lo_message, void*)
{
d_debug("osc_debug_handler(\"%s\")", path);
return 0;
#ifndef DEBUG
// unused
(void)path;
#endif
}
void osc_error_handler(int num, const char* msg, const char* path)
{
d_stderr("osc_error_handler(%i, \"%s\", \"%s\")", num, msg, path);
}
#if DISTRHO_PLUGIN_WANT_STATE
int osc_configure_handler(const char*, const char*, lo_arg** argv, int, lo_message, void*)
{
const char* const key = &argv[0]->s;
const char* const value = &argv[1]->s;
d_debug("osc_configure_handler(\"%s\", \"%s\")", key, value);
initUiIfNeeded();
globalUI->dssiui_configure(key, value);
return 0;
}
#endif
int osc_control_handler(const char*, const char*, lo_arg** argv, int, lo_message, void*)
{
const int32_t rindex = argv[0]->i;
const float value = argv[1]->f;
d_debug("osc_control_handler(%i, %f)", rindex, value);
int32_t index = rindex - DISTRHO_PLUGIN_NUM_INPUTS - DISTRHO_PLUGIN_NUM_OUTPUTS;
// latency
#if DISTRHO_PLUGIN_WANT_LATENCY
index -= 1;
#endif
if (index < 0)
return 0;
initUiIfNeeded();
globalUI->dssiui_control(index, value);
return 0;
}
#if DISTRHO_PLUGIN_WANT_PROGRAMS
int osc_program_handler(const char*, const char*, lo_arg** argv, int, lo_message, void*)
{
const int32_t bank = argv[0]->i;
const int32_t program = argv[1]->f;
d_debug("osc_program_handler(%i, %i)", bank, program);
initUiIfNeeded();
globalUI->dssiui_program(bank, program);
return 0;
}
#endif
int osc_sample_rate_handler(const char*, const char*, lo_arg** argv, int, lo_message, void*)
{
const int32_t sampleRate = argv[0]->i;
d_debug("osc_sample_rate_handler(%i)", sampleRate);
d_lastUiSampleRate = sampleRate;
if (globalUI != nullptr)
globalUI->dssiui_samplerate(sampleRate);
return 0;
}
int osc_show_handler(const char*, const char*, lo_arg**, int, lo_message, void*)
{
d_debug("osc_show_handler()");
initUiIfNeeded();
globalUI->dssiui_show();
return 0;
}
int osc_hide_handler(const char*, const char*, lo_arg**, int, lo_message, void*)
{
d_debug("osc_hide_handler()");
if (globalUI != nullptr)
globalUI->dssiui_hide();
return 0;
}
int osc_quit_handler(const char*, const char*, lo_arg**, int, lo_message, void*)
{
d_debug("osc_quit_handler()");
if (globalUI != nullptr)
globalUI->dssiui_quit();
return 0;
}
END_NAMESPACE_DISTRHO
// -----------------------------------------------------------------------
int main(int argc, char* argv[])
{
USE_NAMESPACE_DISTRHO
// dummy test mode
if (argc == 1)
{
gUiTitle = "DSSI UI Test";
initUiIfNeeded();
globalUI->dssiui_show();
globalUI->exec();
delete globalUI;
globalUI = nullptr;
return 0;
}
if (argc != 5)
{
fprintf(stderr, "Usage: %s <osc-url> <plugin-dll> <plugin-label> <instance-name>\n", argv[0]);
return 1;
}
const char* oscUrl = argv[1];
const char* uiTitle = argv[4];
char* const oscHost = lo_url_get_hostname(oscUrl);
char* const oscPort = lo_url_get_port(oscUrl);
char* const oscPath = lo_url_get_path(oscUrl);
size_t oscPathSize = strlen(oscPath);
lo_address oscAddr = lo_address_new(oscHost, oscPort);
lo_server oscServer = lo_server_new_with_proto(nullptr, LO_UDP, osc_error_handler);
char* const oscServerPath = lo_server_get_url(oscServer);
char pluginPath[strlen(oscServerPath)+oscPathSize];
strcpy(pluginPath, oscServerPath);
strcat(pluginPath, oscPath+1);
#if DISTRHO_PLUGIN_WANT_STATE
char oscPathConfigure[oscPathSize+11];
strcpy(oscPathConfigure, oscPath);
strcat(oscPathConfigure, "/configure");
lo_server_add_method(oscServer, oscPathConfigure, "ss", osc_configure_handler, nullptr);
#endif
char oscPathControl[oscPathSize+9];
strcpy(oscPathControl, oscPath);
strcat(oscPathControl, "/control");
lo_server_add_method(oscServer, oscPathControl, "if", osc_control_handler, nullptr);
d_stdout("oscServerPath: \"%s\"", oscServerPath);
d_stdout("pluginPath: \"%s\"", pluginPath);
d_stdout("oscPathControl: \"%s\"", oscPathControl);
#if DISTRHO_PLUGIN_WANT_PROGRAMS
char oscPathProgram[oscPathSize+9];
strcpy(oscPathProgram, oscPath);
strcat(oscPathProgram, "/program");
lo_server_add_method(oscServer, oscPathProgram, "ii", osc_program_handler, nullptr);
#endif
char oscPathSampleRate[oscPathSize+13];
strcpy(oscPathSampleRate, oscPath);
strcat(oscPathSampleRate, "/sample-rate");
lo_server_add_method(oscServer, oscPathSampleRate, "i", osc_sample_rate_handler, nullptr);
char oscPathShow[oscPathSize+6];
strcpy(oscPathShow, oscPath);
strcat(oscPathShow, "/show");
lo_server_add_method(oscServer, oscPathShow, "", osc_show_handler, nullptr);
char oscPathHide[oscPathSize+6];
strcpy(oscPathHide, oscPath);
strcat(oscPathHide, "/hide");
lo_server_add_method(oscServer, oscPathHide, "", osc_hide_handler, nullptr);
char oscPathQuit[oscPathSize+6];
strcpy(oscPathQuit, oscPath);
strcat(oscPathQuit, "/quit");
lo_server_add_method(oscServer, oscPathQuit, "", osc_quit_handler, nullptr);
lo_server_add_method(oscServer, nullptr, nullptr, osc_debug_handler, nullptr);
gUiTitle = uiTitle;
gOscData.addr = oscAddr;
gOscData.path = oscPath;
gOscData.server = oscServer;
gOscData.send_update(pluginPath);
// wait for init
for (int i=0; i < 100; ++i)
{
lo_server_recv(oscServer);
if (d_lastUiSampleRate != 0.0 || globalUI != nullptr)
break;
d_msleep(50);
}
int ret = 1;
if (d_lastUiSampleRate != 0.0 || globalUI != nullptr)
{
initUiIfNeeded();
globalUI->exec();
delete globalUI;
globalUI = nullptr;
ret = 0;
}
#if DISTRHO_PLUGIN_WANT_STATE
lo_server_del_method(oscServer, oscPathConfigure, "ss");
#endif
lo_server_del_method(oscServer, oscPathControl, "if");
#if DISTRHO_PLUGIN_WANT_PROGRAMS
lo_server_del_method(oscServer, oscPathProgram, "ii");
#endif
lo_server_del_method(oscServer, oscPathSampleRate, "i");
lo_server_del_method(oscServer, oscPathShow, "");
lo_server_del_method(oscServer, oscPathHide, "");
lo_server_del_method(oscServer, oscPathQuit, "");
lo_server_del_method(oscServer, nullptr, nullptr);
std::free(oscServerPath);
std::free(oscHost);
std::free(oscPort);
std::free(oscPath);
lo_address_free(oscAddr);
lo_server_free(oscServer);
return ret;
}
|
Remove leftover debug prints
|
Remove leftover debug prints
Signed-off-by: falkTX <[email protected]>
|
C++
|
isc
|
DISTRHO/DPF,DISTRHO/DPF,DISTRHO/DPF,DISTRHO/DPF
|
fcdde594381dea26f9662b934172b52fe7a7c625
|
src/muz_qe/pdr_dl_interface.cpp
|
src/muz_qe/pdr_dl_interface.cpp
|
/*++
Copyright (c) 2011 Microsoft Corporation
Module Name:
pdr_dl.cpp
Abstract:
SMT2 interface for the datalog PDR
Author:
Krystof Hoder (t-khoder) 2011-9-22.
Revision History:
--*/
#include "dl_cmds.h"
#include "dl_context.h"
#include "dl_mk_coi_filter.h"
#include "dl_mk_interp_tail_simplifier.h"
#include "dl_mk_subsumption_checker.h"
#include "dl_mk_rule_inliner.h"
#include "dl_rule.h"
#include "dl_rule_transformer.h"
//include "dl_mk_extract_quantifiers.h"
#include "smt2parser.h"
#include "pdr_context.h"
#include "pdr_dl_interface.h"
#include "dl_rule_set.h"
#include "dl_mk_slice.h"
#include "dl_mk_unfold.h"
#include "dl_mk_coalesce.h"
#include "pdr_quantifiers.h"
using namespace pdr;
dl_interface::dl_interface(datalog::context& ctx) :
m_ctx(ctx),
m_pdr_rules(ctx),
m_old_rules(ctx),
m_context(0),
m_refs(ctx.get_manager()) {
m_context = alloc(pdr::context, ctx.get_fparams(), ctx.get_params(), ctx.get_manager());
}
dl_interface::~dl_interface() {
dealloc(m_context);
}
//
// Check if the new rules are weaker so that we can
// re-use existing context.
//
void dl_interface::check_reset() {
datalog::rule_ref_vector const& new_rules = m_ctx.get_rules().get_rules();
datalog::rule_ref_vector const& old_rules = m_old_rules.get_rules();
for (unsigned i = 0; i < new_rules.size(); ++i) {
bool found = false;
for (unsigned j = 0; !found && j < old_rules.size(); ++j) {
if (m_ctx.check_subsumes(*old_rules[j], *new_rules[i])) {
found = true;
}
}
if (!found) {
CTRACE("pdr", (old_rules.size() > 0), new_rules[i]->display(m_ctx, tout << "Fresh rule "););
m_context->reset();
break;
}
}
m_old_rules.reset();
m_old_rules.add_rules(new_rules.size(), new_rules.c_ptr());
}
lbool dl_interface::query(expr * query) {
//we restore the initial state in the datalog context
m_ctx.ensure_opened();
m_pdr_rules.reset();
m_refs.reset();
m_pred2slice.reset();
m_ctx.get_rmanager().reset_relations();
ast_manager& m = m_ctx.get_manager();
datalog::rule_manager& rule_manager = m_ctx.get_rule_manager();
datalog::rule_set old_rules(m_ctx.get_rules());
func_decl_ref query_pred(m);
datalog::rule_ref_vector query_rules(rule_manager);
datalog::rule_ref query_rule(rule_manager);
rule_manager.mk_query(query, query_pred, query_rules, query_rule);
m_ctx.add_rules(query_rules);
expr_ref bg_assertion = m_ctx.get_background_assertion();
check_reset();
TRACE("pdr",
if (!m.is_true(bg_assertion)) {
tout << "axioms:\n";
tout << mk_pp(bg_assertion, m) << "\n";
}
tout << "query: " << mk_pp(query, m) << "\n";
tout << "rules:\n";
m_ctx.display_rules(tout);
);
model_converter_ref mc = datalog::mk_skip_model_converter();
proof_converter_ref pc;
if (m_ctx.get_params().get_bool(":generate-proof-trace", false)) {
pc = datalog::mk_skip_proof_converter();
}
m_ctx.set_output_predicate(query_pred);
m_ctx.apply_default_transformation(mc, pc);
if (m_ctx.get_params().get_bool(":slice", true)) {
datalog::rule_transformer transformer(m_ctx);
datalog::mk_slice* slice = alloc(datalog::mk_slice, m_ctx);
transformer.register_plugin(slice);
m_ctx.transform_rules(transformer, mc, pc);
query_pred = slice->get_predicate(query_pred.get());
m_ctx.set_output_predicate(query_pred);
// track sliced predicates.
obj_map<func_decl, func_decl*> const& preds = slice->get_predicates();
obj_map<func_decl, func_decl*>::iterator it = preds.begin();
obj_map<func_decl, func_decl*>::iterator end = preds.end();
for (; it != end; ++it) {
m_pred2slice.insert(it->m_key, it->m_value);
m_refs.push_back(it->m_key);
m_refs.push_back(it->m_value);
}
}
if (m_ctx.get_params().get_uint(":unfold-rules",0) > 0) {
unsigned num_unfolds = m_ctx.get_params().get_uint(":unfold-rules", 0);
datalog::rule_transformer transformer1(m_ctx), transformer2(m_ctx);
if (m_ctx.get_params().get_uint(":coalesce-rules", false)) {
transformer1.register_plugin(alloc(datalog::mk_coalesce, m_ctx));
m_ctx.transform_rules(transformer1, mc, pc);
}
transformer2.register_plugin(alloc(datalog::mk_unfold, m_ctx));
while (num_unfolds > 0) {
m_ctx.transform_rules(transformer2, mc, pc);
--num_unfolds;
}
}
#if 0
// remove universal quantifiers from body.
datalog::mk_extract_quantifiers* extract_quantifiers = alloc(datalog::mk_extract_quantifiers, m_ctx);
datalog::rule_transformer extract_q_tr(m_ctx);
extract_q_tr.register_plugin(extract_quantifiers);
m_ctx.transform_rules(extract_q_tr, mc, pc);
IF_VERBOSE(2, m_ctx.display_rules(verbose_stream()););
m_pdr_rules.add_rules(m_ctx.get_rules());
m_pdr_rules.close();
m_ctx.reopen();
m_ctx.replace_rules(old_rules);
quantifier_model_checker quantifier_mc(*m_context, m, extract_quantifiers->quantifiers(), m_pdr_rules);
m_context->set_proof_converter(pc);
m_context->set_model_converter(mc);
m_context->set_query(query_pred);
m_context->set_axioms(bg_assertion);
m_context->update_rules(m_pdr_rules);
if (m_pdr_rules.get_rules().empty()) {
m_context->set_unsat();
return l_false;
}
lbool result;
while (true) {
result = m_context->solve();
if (result == l_true && extract_quantifiers->has_quantifiers()) {
if (quantifier_mc.check()) {
return l_true;
}
// else continue
}
else {
return result;
}
}
#endif
return l_undef;
}
expr_ref dl_interface::get_cover_delta(int level, func_decl* pred_orig) {
func_decl* pred = pred_orig;
m_pred2slice.find(pred_orig, pred);
SASSERT(pred);
return m_context->get_cover_delta(level, pred_orig, pred);
}
void dl_interface::add_cover(int level, func_decl* pred, expr* property) {
if (m_ctx.get_params().get_bool(":slice", true)) {
throw default_exception("Covers are incompatible with slicing. Disable slicing before using covers");
}
m_context->add_cover(level, pred, property);
}
unsigned dl_interface::get_num_levels(func_decl* pred) {
m_pred2slice.find(pred, pred);
SASSERT(pred);
return m_context->get_num_levels(pred);
}
void dl_interface::collect_statistics(statistics& st) const {
m_context->collect_statistics(st);
}
void dl_interface::reset_statistics() {
m_context->reset_statistics();
}
void dl_interface::display_certificate(std::ostream& out) const {
m_context->display_certificate(out);
}
expr_ref dl_interface::get_answer() {
return m_context->get_answer();
}
void dl_interface::cancel() {
m_context->cancel();
}
void dl_interface::cleanup() {
m_context->cleanup();
}
void dl_interface::updt_params() {
dealloc(m_context);
m_context = alloc(pdr::context, m_ctx.get_fparams(), m_ctx.get_params(), m_ctx.get_manager());
}
model_ref dl_interface::get_model() {
return m_context->get_model();
}
proof_ref dl_interface::get_proof() {
return m_context->get_proof();
}
void dl_interface::collect_params(param_descrs& p) {
p.insert(":bfs-model-search", CPK_BOOL, "PDR: (default true) use BFS strategy for expanding model search");
p.insert(":use-farkas", CPK_BOOL, "PDR: (default true) use lemma generator based on Farkas (for linear real arithmetic)");
p.insert(":generate-proof-trace", CPK_BOOL, "PDR: (default false) trace for 'sat' answer as proof object");
p.insert(":inline-proofs", CPK_BOOL, "PDR: (default true) run PDR with proof mode turned on and extract "
"Farkas coefficients directly (instead of creating a separate proof object when extracting coefficients)");
p.insert(":flexible-trace", CPK_BOOL, "PDR: (default false) allow PDR generate long counter-examples "
"by extending candidate trace within search area");
p.insert(":unfold-rules", CPK_UINT, "PDR: (default 0) unfold rules statically using iterative squarring");
p.insert(":use-model-generalizer", CPK_BOOL, "PDR: (default false) use model for backwards propagation (instead of symbolic simulation)");
p.insert(":validate-result", CPK_BOOL, "PDR (default false) validate result (by proof checking or model checking)");
PRIVATE_PARAMS(p.insert(":use-multicore-generalizer", CPK_BOOL, "PDR: (default false) extract multiple cores for blocking states"););
PRIVATE_PARAMS(p.insert(":use-inductive-generalizer", CPK_BOOL, "PDR: (default true) generalize lemmas using induction strengthening"););
PRIVATE_PARAMS(p.insert(":use-interpolants", CPK_BOOL, "PDR: (default false) use iZ3 interpolation for lemma generation"););
PRIVATE_PARAMS(p.insert(":dump-interpolants", CPK_BOOL, "PDR: (default false) display interpolants"););
PRIVATE_PARAMS(p.insert(":cache-mode", CPK_UINT, "PDR: use no (0 - default) symbolic (1) or explicit cache (2) for model search"););
PRIVATE_PARAMS(p.insert(":inductive-reachability-check", CPK_BOOL,
"PDR: (default false) assume negation of the cube on the previous level when "
"checking for reachability (not only during cube weakening)"););
PRIVATE_PARAMS(p.insert(":max-num-contexts", CPK_UINT, "PDR: (default 500) maximal number of contexts to create"););
PRIVATE_PARAMS(p.insert(":try-minimize-core", CPK_BOOL, "PDR: (default false) try to reduce core size (before inductive minimization)"););
p.insert(":simplify-formulas-pre", CPK_BOOL, "PDR: (default false) simplify derived formulas before inductive propagation");
p.insert(":simplify-formulas-post", CPK_BOOL, "PDR: (default false) simplify derived formulas after inductive propagation");
p.insert(":slice", CPK_BOOL, "PDR: (default true) simplify clause set using slicing");
p.insert(":coalesce-rules", CPK_BOOL, "BMC: (default false) coalesce rules");
}
|
/*++
Copyright (c) 2011 Microsoft Corporation
Module Name:
pdr_dl.cpp
Abstract:
SMT2 interface for the datalog PDR
Author:
Krystof Hoder (t-khoder) 2011-9-22.
Revision History:
--*/
#include "dl_cmds.h"
#include "dl_context.h"
#include "dl_mk_coi_filter.h"
#include "dl_mk_interp_tail_simplifier.h"
#include "dl_mk_subsumption_checker.h"
#include "dl_mk_rule_inliner.h"
#include "dl_rule.h"
#include "dl_rule_transformer.h"
#include "dl_mk_extract_quantifiers.h"
#include "smt2parser.h"
#include "pdr_context.h"
#include "pdr_dl_interface.h"
#include "dl_rule_set.h"
#include "dl_mk_slice.h"
#include "dl_mk_unfold.h"
#include "dl_mk_coalesce.h"
#include "pdr_quantifiers.h"
using namespace pdr;
dl_interface::dl_interface(datalog::context& ctx) :
m_ctx(ctx),
m_pdr_rules(ctx),
m_old_rules(ctx),
m_context(0),
m_refs(ctx.get_manager()) {
m_context = alloc(pdr::context, ctx.get_fparams(), ctx.get_params(), ctx.get_manager());
}
dl_interface::~dl_interface() {
dealloc(m_context);
}
//
// Check if the new rules are weaker so that we can
// re-use existing context.
//
void dl_interface::check_reset() {
datalog::rule_ref_vector const& new_rules = m_ctx.get_rules().get_rules();
datalog::rule_ref_vector const& old_rules = m_old_rules.get_rules();
for (unsigned i = 0; i < new_rules.size(); ++i) {
bool found = false;
for (unsigned j = 0; !found && j < old_rules.size(); ++j) {
if (m_ctx.check_subsumes(*old_rules[j], *new_rules[i])) {
found = true;
}
}
if (!found) {
CTRACE("pdr", (old_rules.size() > 0), new_rules[i]->display(m_ctx, tout << "Fresh rule "););
m_context->reset();
break;
}
}
m_old_rules.reset();
m_old_rules.add_rules(new_rules.size(), new_rules.c_ptr());
}
lbool dl_interface::query(expr * query) {
//we restore the initial state in the datalog context
m_ctx.ensure_opened();
m_pdr_rules.reset();
m_refs.reset();
m_pred2slice.reset();
m_ctx.get_rmanager().reset_relations();
ast_manager& m = m_ctx.get_manager();
datalog::rule_manager& rule_manager = m_ctx.get_rule_manager();
datalog::rule_set old_rules(m_ctx.get_rules());
func_decl_ref query_pred(m);
datalog::rule_ref_vector query_rules(rule_manager);
datalog::rule_ref query_rule(rule_manager);
rule_manager.mk_query(query, query_pred, query_rules, query_rule);
m_ctx.add_rules(query_rules);
expr_ref bg_assertion = m_ctx.get_background_assertion();
check_reset();
TRACE("pdr",
if (!m.is_true(bg_assertion)) {
tout << "axioms:\n";
tout << mk_pp(bg_assertion, m) << "\n";
}
tout << "query: " << mk_pp(query, m) << "\n";
tout << "rules:\n";
m_ctx.display_rules(tout);
);
model_converter_ref mc = datalog::mk_skip_model_converter();
proof_converter_ref pc;
if (m_ctx.get_params().get_bool(":generate-proof-trace", false)) {
pc = datalog::mk_skip_proof_converter();
}
m_ctx.set_output_predicate(query_pred);
m_ctx.apply_default_transformation(mc, pc);
if (m_ctx.get_params().get_bool(":slice", true)) {
datalog::rule_transformer transformer(m_ctx);
datalog::mk_slice* slice = alloc(datalog::mk_slice, m_ctx);
transformer.register_plugin(slice);
m_ctx.transform_rules(transformer, mc, pc);
query_pred = slice->get_predicate(query_pred.get());
m_ctx.set_output_predicate(query_pred);
// track sliced predicates.
obj_map<func_decl, func_decl*> const& preds = slice->get_predicates();
obj_map<func_decl, func_decl*>::iterator it = preds.begin();
obj_map<func_decl, func_decl*>::iterator end = preds.end();
for (; it != end; ++it) {
m_pred2slice.insert(it->m_key, it->m_value);
m_refs.push_back(it->m_key);
m_refs.push_back(it->m_value);
}
}
if (m_ctx.get_params().get_uint(":unfold-rules",0) > 0) {
unsigned num_unfolds = m_ctx.get_params().get_uint(":unfold-rules", 0);
datalog::rule_transformer transformer1(m_ctx), transformer2(m_ctx);
if (m_ctx.get_params().get_uint(":coalesce-rules", false)) {
transformer1.register_plugin(alloc(datalog::mk_coalesce, m_ctx));
m_ctx.transform_rules(transformer1, mc, pc);
}
transformer2.register_plugin(alloc(datalog::mk_unfold, m_ctx));
while (num_unfolds > 0) {
m_ctx.transform_rules(transformer2, mc, pc);
--num_unfolds;
}
}
// remove universal quantifiers from body.
datalog::mk_extract_quantifiers* extract_quantifiers = alloc(datalog::mk_extract_quantifiers, m_ctx);
datalog::rule_transformer extract_q_tr(m_ctx);
extract_q_tr.register_plugin(extract_quantifiers);
m_ctx.transform_rules(extract_q_tr, mc, pc);
IF_VERBOSE(2, m_ctx.display_rules(verbose_stream()););
m_pdr_rules.add_rules(m_ctx.get_rules());
m_pdr_rules.close();
m_ctx.reopen();
m_ctx.replace_rules(old_rules);
quantifier_model_checker quantifier_mc(*m_context, m, extract_quantifiers->quantifiers(), m_pdr_rules);
m_context->set_proof_converter(pc);
m_context->set_model_converter(mc);
m_context->set_query(query_pred);
m_context->set_axioms(bg_assertion);
m_context->update_rules(m_pdr_rules);
if (m_pdr_rules.get_rules().empty()) {
m_context->set_unsat();
return l_false;
}
lbool result;
while (true) {
result = m_context->solve();
if (result == l_true && extract_quantifiers->has_quantifiers()) {
if (quantifier_mc.check()) {
return l_true;
}
// else continue
}
else {
return result;
}
}
}
expr_ref dl_interface::get_cover_delta(int level, func_decl* pred_orig) {
func_decl* pred = pred_orig;
m_pred2slice.find(pred_orig, pred);
SASSERT(pred);
return m_context->get_cover_delta(level, pred_orig, pred);
}
void dl_interface::add_cover(int level, func_decl* pred, expr* property) {
if (m_ctx.get_params().get_bool(":slice", true)) {
throw default_exception("Covers are incompatible with slicing. Disable slicing before using covers");
}
m_context->add_cover(level, pred, property);
}
unsigned dl_interface::get_num_levels(func_decl* pred) {
m_pred2slice.find(pred, pred);
SASSERT(pred);
return m_context->get_num_levels(pred);
}
void dl_interface::collect_statistics(statistics& st) const {
m_context->collect_statistics(st);
}
void dl_interface::reset_statistics() {
m_context->reset_statistics();
}
void dl_interface::display_certificate(std::ostream& out) const {
m_context->display_certificate(out);
}
expr_ref dl_interface::get_answer() {
return m_context->get_answer();
}
void dl_interface::cancel() {
m_context->cancel();
}
void dl_interface::cleanup() {
m_context->cleanup();
}
void dl_interface::updt_params() {
dealloc(m_context);
m_context = alloc(pdr::context, m_ctx.get_fparams(), m_ctx.get_params(), m_ctx.get_manager());
}
model_ref dl_interface::get_model() {
return m_context->get_model();
}
proof_ref dl_interface::get_proof() {
return m_context->get_proof();
}
void dl_interface::collect_params(param_descrs& p) {
p.insert(":bfs-model-search", CPK_BOOL, "PDR: (default true) use BFS strategy for expanding model search");
p.insert(":use-farkas", CPK_BOOL, "PDR: (default true) use lemma generator based on Farkas (for linear real arithmetic)");
p.insert(":generate-proof-trace", CPK_BOOL, "PDR: (default false) trace for 'sat' answer as proof object");
p.insert(":inline-proofs", CPK_BOOL, "PDR: (default true) run PDR with proof mode turned on and extract "
"Farkas coefficients directly (instead of creating a separate proof object when extracting coefficients)");
p.insert(":flexible-trace", CPK_BOOL, "PDR: (default false) allow PDR generate long counter-examples "
"by extending candidate trace within search area");
p.insert(":unfold-rules", CPK_UINT, "PDR: (default 0) unfold rules statically using iterative squarring");
p.insert(":use-model-generalizer", CPK_BOOL, "PDR: (default false) use model for backwards propagation (instead of symbolic simulation)");
p.insert(":validate-result", CPK_BOOL, "PDR (default false) validate result (by proof checking or model checking)");
PRIVATE_PARAMS(p.insert(":use-multicore-generalizer", CPK_BOOL, "PDR: (default false) extract multiple cores for blocking states"););
PRIVATE_PARAMS(p.insert(":use-inductive-generalizer", CPK_BOOL, "PDR: (default true) generalize lemmas using induction strengthening"););
PRIVATE_PARAMS(p.insert(":use-interpolants", CPK_BOOL, "PDR: (default false) use iZ3 interpolation for lemma generation"););
PRIVATE_PARAMS(p.insert(":dump-interpolants", CPK_BOOL, "PDR: (default false) display interpolants"););
PRIVATE_PARAMS(p.insert(":cache-mode", CPK_UINT, "PDR: use no (0 - default) symbolic (1) or explicit cache (2) for model search"););
PRIVATE_PARAMS(p.insert(":inductive-reachability-check", CPK_BOOL,
"PDR: (default false) assume negation of the cube on the previous level when "
"checking for reachability (not only during cube weakening)"););
PRIVATE_PARAMS(p.insert(":max-num-contexts", CPK_UINT, "PDR: (default 500) maximal number of contexts to create"););
PRIVATE_PARAMS(p.insert(":try-minimize-core", CPK_BOOL, "PDR: (default false) try to reduce core size (before inductive minimization)"););
p.insert(":simplify-formulas-pre", CPK_BOOL, "PDR: (default false) simplify derived formulas before inductive propagation");
p.insert(":simplify-formulas-post", CPK_BOOL, "PDR: (default false) simplify derived formulas after inductive propagation");
p.insert(":slice", CPK_BOOL, "PDR: (default true) simplify clause set using slicing");
p.insert(":coalesce-rules", CPK_BOOL, "BMC: (default false) coalesce rules");
}
|
add missing files
|
add missing files
Signed-off-by: Nikolaj Bjorner <[email protected]>
|
C++
|
mit
|
kyledewey/z3,zhuyue1314/z3,seahorn/z3,mschlaipfer/z3,mschlaipfer/z3,375670450/z3,375670450/z3,traiansf/z3-java,conceptofproof/z3,belyaev-mikhail/z3,Baha/z3,seahorn/z3,Baha/z3,jslhs/z3,melted/z3,huangshiyou/z3,kyledewey/z3,jirislaby/z3,gmeer/z3,hguenther/z3,zardus/z3,375670450/z3,wujunzero/z3,hguenther/z3,wujunzero/z3,kyledewey/z3,leodemoura/z3,smilliken/z3,leodemoura/z3,mschlaipfer/z3,smilliken/z3,kyledewey/z3,seahorn/z3,seahorn/z3,gmeer/z3,conceptofproof/z3,leodemoura/z3,melted/z3,375670450/z3,jirislaby/z3,jslhs/z3,jirislaby/z3,melted/z3,syjzwjj/z3,jirislaby/z3,hguenther/z3,zhuyue1314/z3,huangshiyou/z3,traiansf/z3-java,syjzwjj/z3,felixdae/z3,zardus/z3,felixdae/z3,jslhs/z3,belyaev-mikhail/z3,leodemoura/z3,smilliken/z3,kyledewey/z3,Drup/z3,wujunzero/z3,traiansf/z3-java,felixdae/z3,jirislaby/z3,zhuyue1314/z3,375670450/z3,zhuyue1314/z3,hguenther/z3,375670450/z3,mschlaipfer/z3,melted/z3,leodemoura/z3,zhuyue1314/z3,gmeer/z3,belyaev-mikhail/z3,mschlaipfer/z3,smilliken/z3,melted/z3,wujunzero/z3,gmeer/z3,conceptofproof/z3,traiansf/z3-java,gmeer/z3,traiansf/z3-java,Drup/z3,smilliken/z3,conceptofproof/z3,Baha/z3,kyledewey/z3,Baha/z3,jslhs/z3,gmeer/z3,hguenther/z3,syjzwjj/z3,mschlaipfer/z3,Drup/z3,jslhs/z3,smilliken/z3,zardus/z3,belyaev-mikhail/z3,zardus/z3,zardus/z3,syjzwjj/z3,huangshiyou/z3,Baha/z3,wujunzero/z3,seahorn/z3,felixdae/z3,syjzwjj/z3,leodemoura/z3,felixdae/z3,huangshiyou/z3,conceptofproof/z3,conceptofproof/z3,wujunzero/z3,Drup/z3,syjzwjj/z3,seahorn/z3,Drup/z3,huangshiyou/z3,jslhs/z3,zardus/z3,hguenther/z3,melted/z3,belyaev-mikhail/z3,jirislaby/z3,Drup/z3,zhuyue1314/z3,traiansf/z3-java,huangshiyou/z3,belyaev-mikhail/z3,Baha/z3,felixdae/z3
|
d34db292dc104818e05bca509f17b5fe5557d892
|
src/nostalgia/core/sdl/core.cpp
|
src/nostalgia/core/sdl/core.cpp
|
/*
* Copyright 2016 - 2021 [email protected]
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/.
*/
#include <SDL.h>
#include <nostalgia/core/gfx.hpp>
#include <nostalgia/core/input.hpp>
#include <nostalgia/core/core.hpp>
#include "core.hpp"
namespace nostalgia::core {
static event_handler g_eventHandler = nullptr;
void draw(Context *ctx);
ox::Error init(Context *ctx) {
oxReturnError(initGfx(ctx));
return OxError(0);
}
ox::Error run(Context *ctx) {
auto id = ctx->windowerData<SdlImplData>();
for (auto running = true; running;) {
SDL_Event event;
while (SDL_PollEvent(&event)) {
switch (event.type) {
case SDL_KEYDOWN:
if (event.key.keysym.sym == SDLK_q) {
running = false;
}
break;
case SDL_QUIT: {
running = false;
break;
}
}
}
draw(ctx);
SDL_GL_SwapWindow(id->window);
SDL_Delay(1);
}
return OxError(0);
}
void setEventHandler(event_handler h) {
g_eventHandler = h;
}
uint64_t ticksMs() {
return SDL_GetTicks();
}
bool buttonDown(Key) {
return false;
}
}
|
/*
* Copyright 2016 - 2021 [email protected]
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/.
*/
#include <SDL.h>
#include <nostalgia/core/gfx.hpp>
#include <nostalgia/core/input.hpp>
#include <nostalgia/core/core.hpp>
#include "core.hpp"
namespace nostalgia::core {
static event_handler g_eventHandler = nullptr;
static uint64_t g_wakeupTime;
void draw(Context *ctx);
ox::Error init(Context *ctx) {
oxReturnError(initGfx(ctx));
return OxError(0);
}
ox::Error run(Context *ctx) {
auto id = ctx->windowerData<SdlImplData>();
SDL_GL_SetSwapInterval(1);
for (auto running = true; running;) {
SDL_Event event;
while (SDL_PollEvent(&event)) {
switch (event.type) {
case SDL_KEYDOWN:
if (event.key.keysym.sym == SDLK_q) {
running = false;
}
break;
case SDL_QUIT: {
running = false;
break;
}
}
}
const auto ticks = ticksMs();
if (g_wakeupTime <= ticks && g_eventHandler) {
auto sleepTime = g_eventHandler(ctx);
if (sleepTime >= 0) {
g_wakeupTime = ticks + static_cast<unsigned>(sleepTime);
} else {
g_wakeupTime = ~uint64_t(0);
}
}
draw(ctx);
SDL_GL_SwapWindow(id->window);
}
return OxError(0);
}
void setEventHandler(event_handler h) {
g_eventHandler = h;
}
uint64_t ticksMs() {
return SDL_GetTicks();
}
bool buttonDown(Key) {
return false;
}
}
|
Add running of event handler to main loop
|
[nostlagia/core/userland] Add running of event handler to main loop
|
C++
|
mpl-2.0
|
wombatant/nostalgia,wombatant/nostalgia,wombatant/nostalgia
|
519f21ffa57f3aec37f48187123f850b402d25bf
|
myo_media.cpp
|
myo_media.cpp
|
#include <iostream>
#include <ctime>
#include <myo/myo.hpp>
class DataCollector : public myo::DeviceListener {
public:
DataCollector() : current_pose_(), locked_(true), unlocked_at_(0), roll_(0), roll_prev_(0) {}
void onPose(myo::Myo* myo, uint64_t timestamp, myo::Pose pose)
{
if (locked_) {
if (pose == myo::Pose::thumbToPinky) {
locked_ = false;
extendUnlock();
myo->vibrate(myo::Myo::vibrationShort);
myo->vibrate(myo::Myo::vibrationShort);
}
} else {
if (pose == myo::Pose::fingersSpread) {
system("osascript -e 'tell application \"VLC\" to play'");
extendUnlock();
} else if (pose == myo::Pose::fist && current_pose_ != myo::Pose::fist) {
roll_prev_ = roll_;
}
}
current_pose_ = pose;
}
void onOrientationData(myo::Myo* myo, uint64_t timestamp, const myo::Quaternion<float>& quat)
{
roll_ = atan2(2.0f * (quat.w() * quat.x() + quat.y() * quat.z()),
1.0f - 2.0f * (quat.x() * quat.x() + quat.y() * quat.y()));
roll_ += M_PI;
roll_ /= 2.0f * M_PI;
}
void onPeriodic(myo::Myo* myo)
{
if (! locked_) {
updateLockState(myo);
}
}
private:
myo::Pose current_pose_;
bool locked_;
time_t unlocked_at_;
float roll_;
float roll_prev_;
void extendUnlock() { unlocked_at_ = time(0); }
void updateLockState(myo::Myo* myo)
{
if (time(0) - unlocked_at_ > 6) {
locked_ = true;
myo->vibrate(myo::Myo::vibrationShort);
}
}
};
int main()
{
try {
myo::Hub hub("come.voidingwarranties.myo-media");
myo::Myo* myo = hub.waitForMyo(10000);
if (! myo) {
throw std::runtime_error("Unable to find a Myo!");
}
DataCollector collector;
hub.addListener(&collector);
while (true) {
hub.run(1000 / 5);
collector.onPeriodic(myo);
}
} catch (const std::exception& ex) {
std::cerr << "Error: " << ex.what() << std::endl;
return 1;
}
return 0;
}
|
#include <iostream>
#include <ctime>
#include <algorithm>
#include <cstdio>
#include <cstdlib>
#include <myo/myo.hpp>
class DataCollector : public myo::DeviceListener {
public:
DataCollector() : current_pose_(), locked_(true), unlocked_at_(0), base_volume_(0), roll_(0), roll_prev_(0) {}
void onPose(myo::Myo* myo, uint64_t timestamp, myo::Pose pose)
{
if (locked_) {
if (pose == myo::Pose::thumbToPinky) {
std::cout << "Unlocked" << std::endl;
locked_ = false;
extendUnlock();
myo->vibrate(myo::Myo::vibrationShort);
myo->vibrate(myo::Myo::vibrationShort);
}
} else {
if (pose == myo::Pose::fingersSpread) {
std::cout << "Toggling pause / play" << std::endl;
if (0 != std::system("osascript -e 'tell application \"VLC\" to play'")) {
throw std::runtime_error("Unable to pause / play VLC!");
}
extendUnlock();
} else if (pose == myo::Pose::fist && current_pose_ != myo::Pose::fist) {
std::cout << "Adjusting volume" << std::endl;
roll_prev_ = roll_;
char volume_cstr[4];
FILE* volume_p = popen("osascript -e 'get output volume of (get volume settings)'", "r");
if (volume_p == NULL) {
throw std::runtime_error("Unable to adjust volume!");
}
std::fgets(volume_cstr, 4, volume_p);
base_volume_ = std::atoi(volume_cstr);
pclose(volume_p);
}
}
current_pose_ = pose;
}
void onOrientationData(myo::Myo* myo, uint64_t timestamp, const myo::Quaternion<float>& quat)
{
// -pi < roll_ <= +pi
roll_ = atan2(2.0f * (quat.w() * quat.x() + quat.y() * quat.z()),
1.0f - 2.0f * (quat.x() * quat.x() + quat.y() * quat.y()));
}
void onPeriodic(myo::Myo* myo)
{
if (! locked_) {
if (current_pose_ == myo::Pose::fist) {
extendUnlock();
updateVolume();
}
updateLockState(myo);
}
}
private:
myo::Pose current_pose_;
bool locked_;
time_t unlocked_at_;
int base_volume_;
float roll_, roll_prev_;
void extendUnlock() { unlocked_at_ = time(0); }
void updateLockState(myo::Myo* myo)
{
if (time(0) - unlocked_at_ > 3) {
std::cout << "Locked" << std::endl;
locked_ = true;
myo->vibrate(myo::Myo::vibrationShort);
}
}
void updateVolume()
{
float roll_diff = roll_ - roll_prev_;
// Ensure that roll_diff is continuous from -pi/2 to +pi/2.
if (roll_diff > M_PI) {
roll_diff -= (2 * M_PI);
}
if (roll_diff < -M_PI) {
roll_diff += (2 * M_PI);
}
roll_diff *= 45 / M_PI; // Change this to your preference.
int new_volume = base_volume_ + roll_diff;
if (new_volume < 0) {
new_volume = 0;
} else if (new_volume > 100) {
new_volume = 100;
}
std::string volume_cmd = "osascript -e 'set volume output volume "
+ std::to_string(new_volume) + "'";
if (0 != std::system(volume_cmd.c_str())) {
throw std::runtime_error("Unable to adjust volume!");
}
}
};
int main()
{
try {
myo::Hub hub("come.voidingwarranties.myo-media");
myo::Myo* myo = hub.waitForMyo(10000);
if (! myo) {
throw std::runtime_error("Unable to find a Myo!");
}
DataCollector collector;
hub.addListener(&collector);
while (true) {
hub.run(1000 / 20);
collector.onPeriodic(myo);
}
} catch (const std::exception& ex) {
std::cerr << "Error: " << ex.what() << std::endl;
return 1;
}
return 0;
}
|
Implement system volume control
|
Implement system volume control
|
C++
|
mit
|
VoidingWarranties/Myo-Media
|
d6ba20b0e43ea2a6cadbd82c236ad5614faafbbc
|
src/passes/GenerateDynCalls.cpp
|
src/passes/GenerateDynCalls.cpp
|
/*
* Copyright 2020 WebAssembly Community Group participants
*
* 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.
*/
//
// Create `dynCall` helper functions used by emscripten. These allow JavaScript
// to call back into WebAssembly given a function pointer (table index). These
// are used primarily to implement the `invoke` functions which in turn are used
// to implment exceptions handling and setjmp/longjmp. Creates one for each
// signature in the indirect function table.
//
#include "abi/js.h"
#include "asm_v_wasm.h"
#include "ir/import-utils.h"
#include "pass.h"
#include "support/debug.h"
#include "wasm-builder.h"
#define DEBUG_TYPE "generate-dyncalls"
namespace wasm {
struct GenerateDynCalls : public WalkerPass<PostWalker<GenerateDynCalls>> {
GenerateDynCalls(bool onlyI64) : onlyI64(onlyI64) {}
void doWalkModule(Module* wasm) {
PostWalker<GenerateDynCalls>::doWalkModule(wasm);
for (auto& sig : invokeSigs) {
generateDynCallThunk(sig);
}
}
void visitTable(Table* table) {
// Generate dynCalls for functions in the table
if (table->segments.size() > 0) {
std::vector<Name> tableSegmentData;
for (const auto& indirectFunc : table->segments[0].data) {
generateDynCallThunk(getModule()->getFunction(indirectFunc)->sig);
}
}
}
void visitFunction(Function* func) {
// Generate dynCalls for invokes
if (func->imported() && func->module == ENV &&
func->base.startsWith("invoke_")) {
Signature sig = func->sig;
// The first parameter is a pointer to the original function that's called
// by the invoke, so skip it
std::vector<Type> newParams(sig.params.begin() + 1, sig.params.end());
invokeSigs.insert(Signature(Type(newParams), sig.results));
}
}
void generateDynCallThunk(Signature sig);
bool onlyI64;
// The set of all invokes' signatures
std::set<Signature> invokeSigs;
};
static bool hasI64(Signature sig) {
// We only generate dynCall functions for signatures that contain i64. This is
// because any other function can be called directly from JavaScript using the
// wasm table.
for (auto t : sig.results) {
if (t.getID() == Type::i64) {
return true;
}
}
for (auto t : sig.params) {
if (t.getID() == Type::i64) {
return true;
}
}
return false;
}
static void exportFunction(Module& wasm, Name name, bool must_export) {
if (!wasm.getFunctionOrNull(name)) {
assert(!must_export);
return;
}
if (wasm.getExportOrNull(name)) {
return; // Already exported
}
auto exp = new Export;
exp->name = exp->value = name;
exp->kind = ExternalKind::Function;
wasm.addExport(exp);
}
void GenerateDynCalls::generateDynCallThunk(Signature sig) {
if (onlyI64 && !hasI64(sig)) {
return;
}
Module* wasm = getModule();
Builder builder(*wasm);
Name name = std::string("dynCall_") + getSig(sig.results, sig.params);
if (wasm->getFunctionOrNull(name) || wasm->getExportOrNull(name)) {
return; // module already contains this dyncall
}
std::vector<NameType> params;
params.emplace_back("fptr", Type::i32); // function pointer param
int p = 0;
for (const auto& param : sig.params) {
params.emplace_back(std::to_string(p++), param);
}
auto f = builder.makeFunction(name, std::move(params), sig.results, {});
Expression* fptr = builder.makeLocalGet(0, Type::i32);
std::vector<Expression*> args;
Index i = 0;
for (const auto& param : sig.params) {
args.push_back(builder.makeLocalGet(++i, param));
}
// FIXME: Should the existence of a table be ensured here? i.e. create one if
// there is none?
assert(wasm->tables.size() > 0);
f->body = builder.makeCallIndirect(wasm->tables[0]->name, fptr, args, sig);
wasm->addFunction(std::move(f));
exportFunction(*wasm, name, true);
}
Pass* createGenerateDynCallsPass() { return new GenerateDynCalls(false); }
Pass* createGenerateI64DynCallsPass() { return new GenerateDynCalls(true); }
} // namespace wasm
|
/*
* Copyright 2020 WebAssembly Community Group participants
*
* 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.
*/
//
// Create `dynCall` helper functions used by emscripten. These allow JavaScript
// to call back into WebAssembly given a function pointer (table index). These
// are used primarily to implement the `invoke` functions which in turn are used
// to implment exceptions handling and setjmp/longjmp. Creates one for each
// signature in the indirect function table.
//
#include "abi/js.h"
#include "asm_v_wasm.h"
#include "ir/import-utils.h"
#include "pass.h"
#include "support/debug.h"
#include "wasm-builder.h"
#define DEBUG_TYPE "generate-dyncalls"
namespace wasm {
struct GenerateDynCalls : public WalkerPass<PostWalker<GenerateDynCalls>> {
GenerateDynCalls(bool onlyI64) : onlyI64(onlyI64) {}
void doWalkModule(Module* wasm) {
PostWalker<GenerateDynCalls>::doWalkModule(wasm);
for (auto& sig : invokeSigs) {
generateDynCallThunk(sig);
}
}
void visitTable(Table* table) {
// Generate dynCalls for functions in the table
if (table->segments.size() > 0) {
std::vector<Name> tableSegmentData;
for (const auto& indirectFunc : table->segments[0].data) {
generateDynCallThunk(getModule()->getFunction(indirectFunc)->sig);
}
}
}
void visitFunction(Function* func) {
// Generate dynCalls for invokes
if (func->imported() && func->module == ENV &&
func->base.startsWith("invoke_")) {
Signature sig = func->sig;
// The first parameter is a pointer to the original function that's called
// by the invoke, so skip it
std::vector<Type> newParams(sig.params.begin() + 1, sig.params.end());
invokeSigs.insert(Signature(Type(newParams), sig.results));
}
}
void generateDynCallThunk(Signature sig);
bool onlyI64;
// The set of all invokes' signatures
std::set<Signature> invokeSigs;
};
static bool hasI64(Signature sig) {
// We only generate dynCall functions for signatures that contain i64. This is
// because any other function can be called directly from JavaScript using the
// wasm table.
for (auto t : sig.results) {
if (t.getID() == Type::i64) {
return true;
}
}
for (auto t : sig.params) {
if (t.getID() == Type::i64) {
return true;
}
}
return false;
}
static void exportFunction(Module& wasm, Name name, bool must_export) {
if (!wasm.getFunctionOrNull(name)) {
assert(!must_export);
return;
}
if (wasm.getExportOrNull(name)) {
return; // Already exported
}
auto exp = new Export;
exp->name = exp->value = name;
exp->kind = ExternalKind::Function;
wasm.addExport(exp);
}
void GenerateDynCalls::generateDynCallThunk(Signature sig) {
if (onlyI64 && !hasI64(sig)) {
return;
}
Module* wasm = getModule();
Builder builder(*wasm);
Name name = std::string("dynCall_") + getSig(sig.results, sig.params);
if (wasm->getFunctionOrNull(name) || wasm->getExportOrNull(name)) {
return; // module already contains this dyncall
}
std::vector<NameType> params;
params.emplace_back("fptr", Type::i32); // function pointer param
int p = 0;
for (const auto& param : sig.params) {
params.emplace_back(std::to_string(p++), param);
}
auto f = builder.makeFunction(name, std::move(params), sig.results, {});
Expression* fptr = builder.makeLocalGet(0, Type::i32);
std::vector<Expression*> args;
Index i = 0;
for (const auto& param : sig.params) {
args.push_back(builder.makeLocalGet(++i, param));
}
if (wasm->tables.empty()) {
// Add an imported table in exactly the same manner as the LLVM wasm backend
// would add one.
auto* table = wasm->addTable(Builder::makeTable(Name::fromInt(0)));
table->module = ENV;
table->base = "__indirect_function_table";
}
f->body = builder.makeCallIndirect(wasm->tables[0]->name, fptr, args, sig);
wasm->addFunction(std::move(f));
exportFunction(*wasm, name, true);
}
Pass* createGenerateDynCallsPass() { return new GenerateDynCalls(false); }
Pass* createGenerateI64DynCallsPass() { return new GenerateDynCalls(true); }
} // namespace wasm
|
Create a table import if there is none in GenerateDynCalls::generateDynCallThunk (#3580)
|
Create a table import if there is none in GenerateDynCalls::generateDynCallThunk (#3580)
This fixes LLVM=>emscripten autoroller breakage due to llvm/llvm-project@f48923e
commit f48923e884611e6271a8da821a58aedd24d91cf7 (HEAD)
Author: Andy Wingo <[email protected]>
Date: Wed Feb 17 17:20:28 2021 +0100
[WebAssembly][lld] --importTable flag only imports table if needed
Before, --importTable forced the creation of an indirect function table,
whether it was needed or not. Now it only imports a table if needed.
Differential Revision: https://reviews.llvm.org/D96872
|
C++
|
apache-2.0
|
WebAssembly/binaryen,WebAssembly/binaryen,WebAssembly/binaryen,WebAssembly/binaryen,WebAssembly/binaryen
|
7eeaa6851fafa418b4264bc1ee1f6fd20ed6f991
|
src/plugins/git/remotemodel.cpp
|
src/plugins/git/remotemodel.cpp
|
/****************************************************************************
**
** Copyright (C) 2014 Digia Plc and/or its subsidiary(-ies).
** Contact: http://www.qt-project.org/legal
**
** This file is part of Qt Creator.
**
** Commercial License Usage
** Licensees holding valid commercial Qt licenses may use this file in
** accordance with the commercial license agreement provided with the
** Software or, alternatively, in accordance with the terms contained in
** a written agreement between you and Digia. For licensing terms and
** conditions see http://qt.digia.com/licensing. For further information
** use the contact form at http://qt.digia.com/contact-us.
**
** GNU Lesser General Public License Usage
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 as published by the Free Software
** Foundation and appearing in the file LICENSE.LGPL included in the
** packaging of this file. Please review the following information to
** ensure the GNU Lesser General Public License version 2.1 requirements
** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, Digia gives you certain additional
** rights. These rights are described in the Digia Qt LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
****************************************************************************/
#include "remotemodel.h"
#include "gitclient.h"
namespace Git {
namespace Internal {
// ------ RemoteModel
RemoteModel::RemoteModel(GitClient *client, QObject *parent) :
QAbstractTableModel(parent),
m_flags(Qt::ItemIsSelectable | Qt::ItemIsEnabled | Qt::ItemIsEditable),
m_client(client)
{ }
QString RemoteModel::remoteName(int row) const
{
return m_remotes.at(row).name;
}
QString RemoteModel::remoteUrl(int row) const
{
return m_remotes.at(row).url;
}
bool RemoteModel::removeRemote(int row)
{
QString output;
QString error;
bool success = m_client->synchronousRemoteCmd(m_workingDirectory,
QStringList() << QLatin1String("rm") << remoteName(row),
&output, &error);
if (success)
success = refresh(m_workingDirectory, &error);
return success;
}
bool RemoteModel::addRemote(const QString &name, const QString &url)
{
QString output;
QString error;
if (name.isEmpty() || url.isEmpty())
return false;
bool success = m_client->synchronousRemoteCmd(m_workingDirectory,
QStringList() << QLatin1String("add") << name << url,
&output, &error);
if (success)
success = refresh(m_workingDirectory, &error);
return success;
}
bool RemoteModel::renameRemote(const QString &oldName, const QString &newName)
{
QString output;
QString error;
bool success = m_client->synchronousRemoteCmd(m_workingDirectory,
QStringList() << QLatin1String("rename") << oldName << newName,
&output, &error);
if (success)
success = refresh(m_workingDirectory, &error);
return success;
}
bool RemoteModel::updateUrl(const QString &name, const QString &newUrl)
{
QString output;
QString error;
bool success = m_client->synchronousRemoteCmd(m_workingDirectory,
QStringList() << QLatin1String("set-url") << name << newUrl,
&output, &error);
if (success)
success = refresh(m_workingDirectory, &error);
return success;
}
QString RemoteModel::workingDirectory() const
{
return m_workingDirectory;
}
int RemoteModel::remoteCount() const
{
return m_remotes.size();
}
int RemoteModel::rowCount(const QModelIndex &parent) const
{
Q_UNUSED(parent);
return remoteCount();
}
int RemoteModel::columnCount(const QModelIndex &parent) const
{
Q_UNUSED(parent);
return 2;
}
QVariant RemoteModel::data(const QModelIndex &index, int role) const
{
const int row = index.row();
switch (role) {
case Qt::DisplayRole:
case Qt::EditRole:
if (index.column() == 0)
return remoteName(row);
else
return remoteUrl(row);
default:
break;
}
return QVariant();
}
QVariant RemoteModel::headerData(int section, Qt::Orientation orientation, int role) const
{
if (role != Qt::DisplayRole || orientation != Qt::Horizontal)
return QVariant();
return (section == 0) ? tr("Name") : tr("Url");
}
bool RemoteModel::setData(const QModelIndex &index, const QVariant &value, int role)
{
if (role != Qt::EditRole)
return false;
const QString name = remoteName(index.row());
const QString url = remoteUrl(index.row());
switch (index.column()) {
case 0:
if (name == value.toString())
return true;
return renameRemote(name, value.toString());
case 1:
if (url == value.toString())
return true;
return updateUrl(name, value.toString());
default:
return false;
}
}
Qt::ItemFlags RemoteModel::flags(const QModelIndex &index) const
{
Q_UNUSED(index);
return m_flags;
}
void RemoteModel::clear()
{
if (m_remotes.isEmpty())
return;
beginResetModel();
m_remotes.clear();
endResetModel();
}
bool RemoteModel::refresh(const QString &workingDirectory, QString *errorMessage)
{
m_workingDirectory = workingDirectory;
// get list of remotes.
QMap<QString,QString> remotesList =
m_client->synchronousRemotesList(workingDirectory, errorMessage);
if (remotesList.isEmpty())
return false;
beginResetModel();
m_remotes.clear();
foreach (const QString &remoteName, remotesList.keys()) {
Remote newRemote;
newRemote.name = remoteName;
newRemote.url = remotesList.value(remoteName);
m_remotes.push_back(newRemote);
}
endResetModel();
return true;
}
int RemoteModel::findRemoteByName(const QString &name) const
{
const int count = remoteCount();
for (int i = 0; i < count; i++)
if (remoteName(i) == name)
return i;
return -1;
}
GitClient *RemoteModel::client() const
{
return m_client;
}
} // namespace Internal
} // namespace Git
|
/****************************************************************************
**
** Copyright (C) 2014 Digia Plc and/or its subsidiary(-ies).
** Contact: http://www.qt-project.org/legal
**
** This file is part of Qt Creator.
**
** Commercial License Usage
** Licensees holding valid commercial Qt licenses may use this file in
** accordance with the commercial license agreement provided with the
** Software or, alternatively, in accordance with the terms contained in
** a written agreement between you and Digia. For licensing terms and
** conditions see http://qt.digia.com/licensing. For further information
** use the contact form at http://qt.digia.com/contact-us.
**
** GNU Lesser General Public License Usage
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 as published by the Free Software
** Foundation and appearing in the file LICENSE.LGPL included in the
** packaging of this file. Please review the following information to
** ensure the GNU Lesser General Public License version 2.1 requirements
** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, Digia gives you certain additional
** rights. These rights are described in the Digia Qt LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
****************************************************************************/
#include "remotemodel.h"
#include "gitclient.h"
namespace Git {
namespace Internal {
// ------ RemoteModel
RemoteModel::RemoteModel(GitClient *client, QObject *parent) :
QAbstractTableModel(parent),
m_flags(Qt::ItemIsSelectable | Qt::ItemIsEnabled | Qt::ItemIsEditable),
m_client(client)
{ }
QString RemoteModel::remoteName(int row) const
{
return m_remotes.at(row).name;
}
QString RemoteModel::remoteUrl(int row) const
{
return m_remotes.at(row).url;
}
bool RemoteModel::removeRemote(int row)
{
QString output;
QString error;
bool success = m_client->synchronousRemoteCmd(m_workingDirectory,
QStringList() << QLatin1String("rm") << remoteName(row),
&output, &error);
if (success)
success = refresh(m_workingDirectory, &error);
return success;
}
bool RemoteModel::addRemote(const QString &name, const QString &url)
{
QString output;
QString error;
if (name.isEmpty() || url.isEmpty())
return false;
bool success = m_client->synchronousRemoteCmd(m_workingDirectory,
QStringList() << QLatin1String("add") << name << url,
&output, &error);
if (success)
success = refresh(m_workingDirectory, &error);
return success;
}
bool RemoteModel::renameRemote(const QString &oldName, const QString &newName)
{
QString output;
QString error;
bool success = m_client->synchronousRemoteCmd(m_workingDirectory,
QStringList() << QLatin1String("rename") << oldName << newName,
&output, &error);
if (success)
success = refresh(m_workingDirectory, &error);
return success;
}
bool RemoteModel::updateUrl(const QString &name, const QString &newUrl)
{
QString output;
QString error;
bool success = m_client->synchronousRemoteCmd(m_workingDirectory,
QStringList() << QLatin1String("set-url") << name << newUrl,
&output, &error);
if (success)
success = refresh(m_workingDirectory, &error);
return success;
}
QString RemoteModel::workingDirectory() const
{
return m_workingDirectory;
}
int RemoteModel::remoteCount() const
{
return m_remotes.size();
}
int RemoteModel::rowCount(const QModelIndex &parent) const
{
Q_UNUSED(parent);
return remoteCount();
}
int RemoteModel::columnCount(const QModelIndex &parent) const
{
Q_UNUSED(parent);
return 2;
}
QVariant RemoteModel::data(const QModelIndex &index, int role) const
{
const int row = index.row();
switch (role) {
case Qt::DisplayRole:
case Qt::EditRole:
if (index.column() == 0)
return remoteName(row);
else
return remoteUrl(row);
default:
break;
}
return QVariant();
}
QVariant RemoteModel::headerData(int section, Qt::Orientation orientation, int role) const
{
if (role != Qt::DisplayRole || orientation != Qt::Horizontal)
return QVariant();
return (section == 0) ? tr("Name") : tr("URL");
}
bool RemoteModel::setData(const QModelIndex &index, const QVariant &value, int role)
{
if (role != Qt::EditRole)
return false;
const QString name = remoteName(index.row());
const QString url = remoteUrl(index.row());
switch (index.column()) {
case 0:
if (name == value.toString())
return true;
return renameRemote(name, value.toString());
case 1:
if (url == value.toString())
return true;
return updateUrl(name, value.toString());
default:
return false;
}
}
Qt::ItemFlags RemoteModel::flags(const QModelIndex &index) const
{
Q_UNUSED(index);
return m_flags;
}
void RemoteModel::clear()
{
if (m_remotes.isEmpty())
return;
beginResetModel();
m_remotes.clear();
endResetModel();
}
bool RemoteModel::refresh(const QString &workingDirectory, QString *errorMessage)
{
m_workingDirectory = workingDirectory;
// get list of remotes.
QMap<QString,QString> remotesList =
m_client->synchronousRemotesList(workingDirectory, errorMessage);
if (remotesList.isEmpty())
return false;
beginResetModel();
m_remotes.clear();
foreach (const QString &remoteName, remotesList.keys()) {
Remote newRemote;
newRemote.name = remoteName;
newRemote.url = remotesList.value(remoteName);
m_remotes.push_back(newRemote);
}
endResetModel();
return true;
}
int RemoteModel::findRemoteByName(const QString &name) const
{
const int count = remoteCount();
for (int i = 0; i < count; i++)
if (remoteName(i) == name)
return i;
return -1;
}
GitClient *RemoteModel::client() const
{
return m_client;
}
} // namespace Internal
} // namespace Git
|
replace "Url" with "URL" in UI text
|
Git: replace "Url" with "URL" in UI text
Change-Id: I6cf721e84b33183c97c9db8f98842a461af2f0d1
Reviewed-by: Orgad Shaneh <[email protected]>
|
C++
|
lgpl-2.1
|
amyvmiwei/qt-creator,danimo/qt-creator,martyone/sailfish-qtcreator,farseerri/git_code,martyone/sailfish-qtcreator,AltarBeastiful/qt-creator,danimo/qt-creator,martyone/sailfish-qtcreator,farseerri/git_code,Distrotech/qtcreator,farseerri/git_code,amyvmiwei/qt-creator,amyvmiwei/qt-creator,xianian/qt-creator,martyone/sailfish-qtcreator,xianian/qt-creator,maui-packages/qt-creator,AltarBeastiful/qt-creator,kuba1/qtcreator,martyone/sailfish-qtcreator,danimo/qt-creator,danimo/qt-creator,farseerri/git_code,xianian/qt-creator,martyone/sailfish-qtcreator,Distrotech/qtcreator,danimo/qt-creator,maui-packages/qt-creator,AltarBeastiful/qt-creator,danimo/qt-creator,danimo/qt-creator,AltarBeastiful/qt-creator,xianian/qt-creator,xianian/qt-creator,Distrotech/qtcreator,martyone/sailfish-qtcreator,maui-packages/qt-creator,Distrotech/qtcreator,kuba1/qtcreator,martyone/sailfish-qtcreator,Distrotech/qtcreator,maui-packages/qt-creator,farseerri/git_code,Distrotech/qtcreator,kuba1/qtcreator,xianian/qt-creator,kuba1/qtcreator,amyvmiwei/qt-creator,kuba1/qtcreator,xianian/qt-creator,danimo/qt-creator,kuba1/qtcreator,xianian/qt-creator,Distrotech/qtcreator,farseerri/git_code,AltarBeastiful/qt-creator,farseerri/git_code,amyvmiwei/qt-creator,kuba1/qtcreator,farseerri/git_code,martyone/sailfish-qtcreator,amyvmiwei/qt-creator,AltarBeastiful/qt-creator,danimo/qt-creator,maui-packages/qt-creator,xianian/qt-creator,maui-packages/qt-creator,AltarBeastiful/qt-creator,amyvmiwei/qt-creator,AltarBeastiful/qt-creator,kuba1/qtcreator,maui-packages/qt-creator,amyvmiwei/qt-creator,kuba1/qtcreator
|
ad59a29cb94e84997a924c4331c68a72aec290d6
|
Examples/Projections/VectorDataExtractROIExample.cxx
|
Examples/Projections/VectorDataExtractROIExample.cxx
|
/*
* Copyright (C) 2005-2020 Centre National d'Etudes Spatiales (CNES)
*
* This file is part of Orfeo Toolbox
*
* https://www.orfeo-toolbox.org/
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
// There is some vector data sets widely available on the internet. These data
// sets can be huge, covering an entire country, with hundreds of thousands
// objects.
//
// Most of the time, you won't be interested in the whole area and would like
// to focus only on the area corresponding to your satellite image.
//
// The \doxygen{otb}{VectorDataExtractROI} is able to extract the area corresponding
// to your satellite image, even if the image is still in sensor geometry (provided
// the sensor model is supported by OTB). Let's see how we can do that.
//
// This example demonstrates the use of the
// \doxygen{otb}{VectorDataExtractROI}.
#include "otbVectorData.h"
#include "otbVectorDataExtractROI.h"
#include "otbVectorDataFileReader.h"
#include "otbVectorDataFileWriter.h"
#include "otbImageMetadataInterfaceFactory.h"
#include "otbImage.h"
#include "otbImageFileReader.h"
int main(int argc, char* argv[])
{
if (argc < 4)
{
std::cout << argv[0] << " <input vector filename> <input image name> <output vector filename> " << std::endl;
return EXIT_FAILURE;
}
const char* inVectorName = argv[1];
const char* inImageName = argv[2];
const char* outVectorName = argv[3];
using Type = double;
using VectorDataType = otb::VectorData<>;
using VectorDataFileReaderType = otb::VectorDataFileReader<VectorDataType>;
using VectorDataWriterType = otb::VectorDataFileWriter<VectorDataType>;
using TypedRegion = otb::RemoteSensingRegion<Type>;
using ImageType = otb::Image<unsigned char, 2>;
using ImageReaderType = otb::ImageFileReader<ImageType>;
ImageReaderType::Pointer imageReader = ImageReaderType::New();
imageReader->SetFileName(inImageName);
imageReader->UpdateOutputInformation();
// After the usual declaration (you can check the source file for the details),
// we can declare the \doxygen{otb}{VectorDataExtractROI}:
using FilterType = otb::VectorDataExtractROI<VectorDataType>;
FilterType::Pointer filter = FilterType::New();
// Then, we need to specify the region to extract. This region is a bit special as
// it contains also information related to its reference system (cartographic projection
// or sensor model projection). We retrieve all these information from the image
// we gave as an input.
TypedRegion region;
TypedRegion::SizeType size;
TypedRegion::IndexType index;
size[0] = imageReader->GetOutput()->GetLargestPossibleRegion().GetSize()[0] * imageReader->GetOutput()->GetSignedSpacing()[0];
size[1] = imageReader->GetOutput()->GetLargestPossibleRegion().GetSize()[1] * imageReader->GetOutput()->GetSignedSpacing()[1];
index[0] = imageReader->GetOutput()->GetOrigin()[0] - 0.5 * imageReader->GetOutput()->GetSignedSpacing()[0];
index[1] = imageReader->GetOutput()->GetOrigin()[1] - 0.5 * imageReader->GetOutput()->GetSignedSpacing()[1];
region.SetSize(size);
region.SetOrigin(index);
region.SetRegionProjection(imageReader->GetOutput()->GetProjectionRef());
region.SetImageMetadata(imageReader->GetOutput()->GetImageMetadata());
filter->SetRegion(region);
VectorDataFileReaderType::Pointer reader = VectorDataFileReaderType::New();
VectorDataWriterType::Pointer writer = VectorDataWriterType::New();
reader->SetFileName(inVectorName);
writer->SetFileName(outVectorName);
// And finally, we can plug the filter in the pipeline:
filter->SetInput(reader->GetOutput());
writer->SetInput(filter->GetOutput());
writer->Update();
return EXIT_SUCCESS;
}
|
/*
* Copyright (C) 2005-2020 Centre National d'Etudes Spatiales (CNES)
*
* This file is part of Orfeo Toolbox
*
* https://www.orfeo-toolbox.org/
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
// There is some vector data sets widely available on the internet. These data
// sets can be huge, covering an entire country, with hundreds of thousands
// objects.
//
// Most of the time, you won't be interested in the whole area and would like
// to focus only on the area corresponding to your satellite image.
//
// The \doxygen{otb}{VectorDataExtractROI} is able to extract the area corresponding
// to your satellite image, even if the image is still in sensor geometry (provided
// the sensor model is supported by OTB). Let's see how we can do that.
//
// This example demonstrates the use of the
// \doxygen{otb}{VectorDataExtractROI}.
#include "otbVectorData.h"
#include "otbVectorDataExtractROI.h"
#include "otbVectorDataFileReader.h"
#include "otbVectorDataFileWriter.h"
#include "otbImage.h"
#include "otbImageFileReader.h"
int main(int argc, char* argv[])
{
if (argc < 4)
{
std::cout << argv[0] << " <input vector filename> <input image name> <output vector filename> " << std::endl;
return EXIT_FAILURE;
}
const char* inVectorName = argv[1];
const char* inImageName = argv[2];
const char* outVectorName = argv[3];
using Type = double;
using VectorDataType = otb::VectorData<>;
using VectorDataFileReaderType = otb::VectorDataFileReader<VectorDataType>;
using VectorDataWriterType = otb::VectorDataFileWriter<VectorDataType>;
using TypedRegion = otb::RemoteSensingRegion<Type>;
using ImageType = otb::Image<unsigned char, 2>;
using ImageReaderType = otb::ImageFileReader<ImageType>;
ImageReaderType::Pointer imageReader = ImageReaderType::New();
imageReader->SetFileName(inImageName);
imageReader->UpdateOutputInformation();
// After the usual declaration (you can check the source file for the details),
// we can declare the \doxygen{otb}{VectorDataExtractROI}:
using FilterType = otb::VectorDataExtractROI<VectorDataType>;
FilterType::Pointer filter = FilterType::New();
// Then, we need to specify the region to extract. This region is a bit special as
// it contains also information related to its reference system (cartographic projection
// or sensor model projection). We retrieve all these information from the image
// we gave as an input.
TypedRegion region;
TypedRegion::SizeType size;
TypedRegion::IndexType index;
size[0] = imageReader->GetOutput()->GetLargestPossibleRegion().GetSize()[0] * imageReader->GetOutput()->GetSignedSpacing()[0];
size[1] = imageReader->GetOutput()->GetLargestPossibleRegion().GetSize()[1] * imageReader->GetOutput()->GetSignedSpacing()[1];
index[0] = imageReader->GetOutput()->GetOrigin()[0] - 0.5 * imageReader->GetOutput()->GetSignedSpacing()[0];
index[1] = imageReader->GetOutput()->GetOrigin()[1] - 0.5 * imageReader->GetOutput()->GetSignedSpacing()[1];
region.SetSize(size);
region.SetOrigin(index);
region.SetRegionProjection(imageReader->GetOutput()->GetProjectionRef());
region.SetImageMetadata(imageReader->GetOutput()->GetImageMetadata());
filter->SetRegion(region);
VectorDataFileReaderType::Pointer reader = VectorDataFileReaderType::New();
VectorDataWriterType::Pointer writer = VectorDataWriterType::New();
reader->SetFileName(inVectorName);
writer->SetFileName(outVectorName);
// And finally, we can plug the filter in the pipeline:
filter->SetInput(reader->GetOutput());
writer->SetInput(filter->GetOutput());
writer->Update();
return EXIT_SUCCESS;
}
|
remove unnecesary include
|
REFAC: remove unnecesary include
|
C++
|
apache-2.0
|
orfeotoolbox/OTB,orfeotoolbox/OTB,orfeotoolbox/OTB,orfeotoolbox/OTB,orfeotoolbox/OTB,orfeotoolbox/OTB
|
140945568cb8d3b8ce4c7a2e73c95ae1a4b4a51f
|
src/gorgone.cpp
|
src/gorgone.cpp
|
#include "gorgone.h"
using namespace cv;
using namespace ofxCv;
int accum = 0;
void gorgone::setup()
{
parseCmdLineOptions();
vidGrabber.setup(filename);
}
void gorgone::update()
{
vidGrabber.update();
if(vidGrabber.isFrameNew()){
frame = vidGrabber.getFrame();
if ( frame.cols == 0 ) return;
cv::Mat gray;
if ( frame.channels() == 1 ){
gray = frame;
} else {
cv::cvtColor(frame, gray, CV_RGB2GRAY);
}
cout << "new frame to process : " << gray.cols << "x" << gray.rows << endl;
irisDetector.update(gray);
}
}
void gorgone::draw()
{
// cout << ofGetFrameRate() << " fps" << endl;
vidGrabber.draw(0,0);
// drawMat(frame,0,0);
irisDetector.drawEyes();
}
void gorgone::keyPressed(int key)
{
switch (key){
case 's':
irisDetector.save();
break;
case ' ':
irisDetector.reset();
break;
case 'i':
vidGrabber.led.switchOnIR();
break;
case 'o':
vidGrabber.led.switchOffIR();
break;
case 'w':
vidGrabber.led.switchOnWhite();
break;
case 'x':
vidGrabber.led.switchOffWhite();
break;
default :
break;
}
}
void gorgone::messageReceived(ofMessage& message)
{
}
void gorgone::parseCmdLineOptions(){
vector<string> keys = ofxArgParser::allKeys();
for (int i = 0; i < keys.size(); i++) {
if ( keys[i] == "f" ) { filename = ofxArgParser::getValue(keys[i]); }
cout << "key: " << keys[i] << ", value: " << ofxArgParser::getValue(keys[i]) << endl;
}
}
|
#include "gorgone.h"
using namespace cv;
using namespace ofxCv;
int accum = 0;
void gorgone::setup()
{
parseCmdLineOptions();
vidGrabber.setup(filename);
}
void gorgone::update()
{
vidGrabber.update();
if(vidGrabber.isFrameNew()){
frame = vidGrabber.getFrame();
if ( frame.cols == 0 ) return;
cv::Mat gray;
if ( frame.channels() == 1 ){
gray = frame;
} else {
cv::cvtColor(frame, gray, CV_RGB2GRAY);
}
cout << "new frame to process : " << gray.cols << "x" << gray.rows << endl;
irisDetector.update(gray);
}
}
void gorgone::draw()
{
// cout << ofGetFrameRate() << " fps" << endl;
vidGrabber.draw(0,0);
// drawMat(frame,0,0);
irisDetector.drawEyes();
}
void gorgone::keyPressed(int key)
{
switch (key){
case 's':
irisDetector.save();
break;
case ' ':
irisDetector.reset();
break;
#ifdef TARGET_RASPBERRY_PI
case 'i':
vidGrabber.led.switchOnIR();
break;
case 'o':
vidGrabber.led.switchOffIR();
break;
case 'w':
vidGrabber.led.switchOnWhite();
break;
case 'x':
vidGrabber.led.switchOffWhite();
break;
#endif
default :
break;
}
}
void gorgone::messageReceived(ofMessage& message)
{
}
void gorgone::parseCmdLineOptions(){
vector<string> keys = ofxArgParser::allKeys();
for (int i = 0; i < keys.size(); i++) {
if ( keys[i] == "f" ) filename = ofxArgParser::getValue(keys[i]);
cout << "key: " << keys[i] << ", value: " << ofxArgParser::getValue(keys[i]) << endl;
}
}
|
access I2C LED only on RPi
|
access I2C LED only on RPi
|
C++
|
mit
|
avilleret/gorgone,avilleret/gorgone
|
c517b3ac193ed97e6b03a1aacabd75aec0048310
|
ASCOfficeXlsFile2/source/XlsFormat/Logic/SummaryInformationStream/Structures/PropertyFactory.cpp
|
ASCOfficeXlsFile2/source/XlsFormat/Logic/SummaryInformationStream/Structures/PropertyFactory.cpp
|
/*
* (c) Copyright Ascensio System SIA 2010-2018
*
* This program is a free software product. You can redistribute it and/or
* modify it under the terms of the GNU Affero General Public License (AGPL)
* version 3 as published by the Free Software Foundation. In accordance with
* Section 7(a) of the GNU AGPL its Section 15 shall be amended to the effect
* that Ascensio System SIA expressly excludes the warranty of non-infringement
* of any third-party rights.
*
* This program is distributed WITHOUT ANY WARRANTY; without even the implied
* warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. For
* details, see the GNU AGPL at: http://www.gnu.org/licenses/agpl-3.0.html
*
* You can contact Ascensio System SIA at Lubanas st. 125a-25, Riga, Latvia,
* EU, LV-1021.
*
* The interactive user interfaces in modified source and object code versions
* of the Program must display Appropriate Legal Notices, as required under
* Section 5 of the GNU AGPL version 3.
*
* Pursuant to Section 7(b) of the License you must retain the original Product
* logo when distributing the program. Pursuant to Section 7(e) we decline to
* grant you any rights under trademark law for use of our trademarks.
*
* All the Product's GUI elements, including illustrations and icon sets, as
* well as technical writing content are licensed under the terms of the
* Creative Commons Attribution-ShareAlike 4.0 International. See the License
* terms at http://creativecommons.org/licenses/by-sa/4.0/legalcode
*
*/
#include <Binary/CFStream.h>
#include "PropertyFactory.h"
#include "CodePageOle.h"
namespace OLEPS
{
PropertyFactory::PropertyFactory()
{
}
PropertyPtr PropertyFactory::ReadProperty(const unsigned int prop_type, XLS::CFStreamPtr stream, const unsigned int property_offset)
{
stream->seekFromBegin(property_offset);
unsigned short value_type;
if (stream->getStreamPointer() + 2 > stream->getStreamSize()) return PropertyPtr();
*stream >> value_type;
stream->seekFromCurForward(2); // Skip 2 reserved unsigned chars
value_type = value_type & 0x00ff;
switch(prop_type)
{
case 0x01:
return PropertyPtr(new PropertyCodePage(prop_type, value_type, stream));
default:
{
if (value_type == 0x001E)
{
return PropertyPtr(new PropertyStr(prop_type, value_type, stream));
}
else if (value_type == 0x0003)
{
return PropertyPtr(new PropertyInt(prop_type, value_type, stream));
}
else if (value_type == 0x000b)
{
return PropertyPtr(new PropertyBool(prop_type, value_type, stream));
}
else if (value_type == 0x0040)
{
return PropertyPtr(new PropertyDTM(prop_type, value_type, stream));
}
else
return PropertyPtr();
}break;
}
}
} // namespace OLEPS
|
/*
* (c) Copyright Ascensio System SIA 2010-2018
*
* This program is a free software product. You can redistribute it and/or
* modify it under the terms of the GNU Affero General Public License (AGPL)
* version 3 as published by the Free Software Foundation. In accordance with
* Section 7(a) of the GNU AGPL its Section 15 shall be amended to the effect
* that Ascensio System SIA expressly excludes the warranty of non-infringement
* of any third-party rights.
*
* This program is distributed WITHOUT ANY WARRANTY; without even the implied
* warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. For
* details, see the GNU AGPL at: http://www.gnu.org/licenses/agpl-3.0.html
*
* You can contact Ascensio System SIA at Lubanas st. 125a-25, Riga, Latvia,
* EU, LV-1021.
*
* The interactive user interfaces in modified source and object code versions
* of the Program must display Appropriate Legal Notices, as required under
* Section 5 of the GNU AGPL version 3.
*
* Pursuant to Section 7(b) of the License you must retain the original Product
* logo when distributing the program. Pursuant to Section 7(e) we decline to
* grant you any rights under trademark law for use of our trademarks.
*
* All the Product's GUI elements, including illustrations and icon sets, as
* well as technical writing content are licensed under the terms of the
* Creative Commons Attribution-ShareAlike 4.0 International. See the License
* terms at http://creativecommons.org/licenses/by-sa/4.0/legalcode
*
*/
#include <Binary/CFStream.h>
#include "PropertyFactory.h"
#include "CodePageOle.h"
namespace OLEPS
{
PropertyFactory::PropertyFactory()
{
}
PropertyPtr PropertyFactory::ReadProperty(const unsigned int prop_type, XLS::CFStreamPtr stream, const unsigned int property_offset)
{
stream->seekFromBegin(property_offset);
unsigned short value_type;
if (stream->getStreamPointer() + 2 > stream->getStreamSize()) return PropertyPtr();
*stream >> value_type;
stream->seekFromCurForward(2); // Skip 2 reserved unsigned chars
value_type = value_type & 0x00ff;
switch(prop_type)
{
case 0x01:
return PropertyPtr(new PropertyCodePage(prop_type, value_type, stream));
default:
{
/* if (value_type == 0x001E)
{
return PropertyPtr(new PropertyStr(prop_type, value_type, stream));
}
else */if (value_type == 0x0003)
{
return PropertyPtr(new PropertyInt(prop_type, value_type, stream));
}
else if (value_type == 0x000b)
{
return PropertyPtr(new PropertyBool(prop_type, value_type, stream));
}
else if (value_type == 0x0040)
{
return PropertyPtr(new PropertyDTM(prop_type, value_type, stream));
}
else
return PropertyPtr();
}break;
}
}
} // namespace OLEPS
|
fix 5.1.3 after used icu6 (#73)
|
fix 5.1.3 after used icu6 (#73)
|
C++
|
agpl-3.0
|
ONLYOFFICE/core,ONLYOFFICE/core,ONLYOFFICE/core,ONLYOFFICE/core,ONLYOFFICE/core,ONLYOFFICE/core,ONLYOFFICE/core,ONLYOFFICE/core,ONLYOFFICE/core,ONLYOFFICE/core,ONLYOFFICE/core
|
0446f51e1c0e16bc9e3f1311967e31ac6dc40bab
|
lib/AST/InheritViz.cpp
|
lib/AST/InheritViz.cpp
|
//===- InheritViz.cpp - Graphviz visualization for inheritance --*- 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 CXXRecordDecl::viewInheritance, which
// generates a GraphViz DOT file that depicts the class inheritance
// diagram and then calls Graphviz/dot+gv on it.
//
//===----------------------------------------------------------------------===//
#include "clang/AST/ASTContext.h"
#include "clang/AST/Decl.h"
#include "clang/AST/DeclCXX.h"
#include "clang/AST/TypeOrdering.h"
#include "llvm/Support/GraphWriter.h"
#include "llvm/Support/raw_ostream.h"
#include <map>
using namespace llvm;
namespace clang {
/// InheritanceHierarchyWriter - Helper class that writes out a
/// GraphViz file that diagrams the inheritance hierarchy starting at
/// a given C++ class type. Note that we do not use LLVM's
/// GraphWriter, because the interface does not permit us to properly
/// differentiate between uses of types as virtual bases
/// vs. non-virtual bases.
class InheritanceHierarchyWriter {
ASTContext& Context;
raw_ostream &Out;
std::map<QualType, int, QualTypeOrdering> DirectBaseCount;
std::set<QualType, QualTypeOrdering> KnownVirtualBases;
public:
InheritanceHierarchyWriter(ASTContext& Context, raw_ostream& Out)
: Context(Context), Out(Out) { }
void WriteGraph(QualType Type) {
Out << "digraph \"" << DOT::EscapeString(Type.getAsString()) << "\" {\n";
WriteNode(Type, false);
Out << "}\n";
}
protected:
/// WriteNode - Write out the description of node in the inheritance
/// diagram, which may be a base class or it may be the root node.
void WriteNode(QualType Type, bool FromVirtual);
/// WriteNodeReference - Write out a reference to the given node,
/// using a unique identifier for each direct base and for the
/// (only) virtual base.
raw_ostream& WriteNodeReference(QualType Type, bool FromVirtual);
};
void InheritanceHierarchyWriter::WriteNode(QualType Type, bool FromVirtual) {
QualType CanonType = Context.getCanonicalType(Type);
if (FromVirtual) {
if (KnownVirtualBases.find(CanonType) != KnownVirtualBases.end())
return;
// We haven't seen this virtual base before, so display it and
// its bases.
KnownVirtualBases.insert(CanonType);
}
// Declare the node itself.
Out << " ";
WriteNodeReference(Type, FromVirtual);
// Give the node a label based on the name of the class.
std::string TypeName = Type.getAsString();
Out << " [ shape=\"box\", label=\"" << DOT::EscapeString(TypeName);
// If the name of the class was a typedef or something different
// from the "real" class name, show the real class name in
// parentheses so we don't confuse ourselves.
if (TypeName != CanonType.getAsString()) {
Out << "\\n(" << CanonType.getAsString() << ")";
}
// Finished describing the node.
Out << " \"];\n";
// Display the base classes.
const CXXRecordDecl *Decl
= static_cast<const CXXRecordDecl *>(Type->getAs<RecordType>()->getDecl());
for (CXXRecordDecl::base_class_const_iterator Base = Decl->bases_begin();
Base != Decl->bases_end(); ++Base) {
QualType CanonBaseType = Context.getCanonicalType(Base->getType());
// If this is not virtual inheritance, bump the direct base
// count for the type.
if (!Base->isVirtual())
++DirectBaseCount[CanonBaseType];
// Write out the node (if we need to).
WriteNode(Base->getType(), Base->isVirtual());
// Write out the edge.
Out << " ";
WriteNodeReference(Type, FromVirtual);
Out << " -> ";
WriteNodeReference(Base->getType(), Base->isVirtual());
// Write out edge attributes to show the kind of inheritance.
if (Base->isVirtual()) {
Out << " [ style=\"dashed\" ]";
}
Out << ";";
}
}
/// WriteNodeReference - Write out a reference to the given node,
/// using a unique identifier for each direct base and for the
/// (only) virtual base.
raw_ostream&
InheritanceHierarchyWriter::WriteNodeReference(QualType Type,
bool FromVirtual) {
QualType CanonType = Context.getCanonicalType(Type);
Out << "Class_" << CanonType.getAsOpaquePtr();
if (!FromVirtual)
Out << "_" << DirectBaseCount[CanonType];
return Out;
}
/// viewInheritance - Display the inheritance hierarchy of this C++
/// class using GraphViz.
void CXXRecordDecl::viewInheritance(ASTContext& Context) const {
QualType Self = Context.getTypeDeclType(const_cast<CXXRecordDecl *>(this));
std::string ErrMsg;
sys::Path Filename = sys::Path::GetTemporaryDirectory(&ErrMsg);
if (Filename.isEmpty()) {
llvm::errs() << "Error: " << ErrMsg << "\n";
return;
}
Filename.appendComponent(Self.getAsString() + ".dot");
if (Filename.makeUnique(true,&ErrMsg)) {
llvm::errs() << "Error: " << ErrMsg << "\n";
return;
}
llvm::errs() << "Writing '" << Filename.c_str() << "'... ";
llvm::raw_fd_ostream O(Filename.c_str(), ErrMsg);
if (ErrMsg.empty()) {
InheritanceHierarchyWriter Writer(Context, O);
Writer.WriteGraph(Self);
llvm::errs() << " done. \n";
O.close();
// Display the graph
DisplayGraph(Filename);
} else {
llvm::errs() << "error opening file for writing!\n";
}
}
}
|
//===- InheritViz.cpp - Graphviz visualization for inheritance --*- 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 CXXRecordDecl::viewInheritance, which
// generates a GraphViz DOT file that depicts the class inheritance
// diagram and then calls Graphviz/dot+gv on it.
//
//===----------------------------------------------------------------------===//
#include "clang/AST/ASTContext.h"
#include "clang/AST/Decl.h"
#include "clang/AST/DeclCXX.h"
#include "clang/AST/TypeOrdering.h"
#include "llvm/Support/GraphWriter.h"
#include "llvm/Support/raw_ostream.h"
#include <map>
using namespace llvm;
namespace clang {
/// InheritanceHierarchyWriter - Helper class that writes out a
/// GraphViz file that diagrams the inheritance hierarchy starting at
/// a given C++ class type. Note that we do not use LLVM's
/// GraphWriter, because the interface does not permit us to properly
/// differentiate between uses of types as virtual bases
/// vs. non-virtual bases.
class InheritanceHierarchyWriter {
ASTContext& Context;
raw_ostream &Out;
std::map<QualType, int, QualTypeOrdering> DirectBaseCount;
std::set<QualType, QualTypeOrdering> KnownVirtualBases;
public:
InheritanceHierarchyWriter(ASTContext& Context, raw_ostream& Out)
: Context(Context), Out(Out) { }
void WriteGraph(QualType Type) {
Out << "digraph \"" << DOT::EscapeString(Type.getAsString()) << "\" {\n";
WriteNode(Type, false);
Out << "}\n";
}
protected:
/// WriteNode - Write out the description of node in the inheritance
/// diagram, which may be a base class or it may be the root node.
void WriteNode(QualType Type, bool FromVirtual);
/// WriteNodeReference - Write out a reference to the given node,
/// using a unique identifier for each direct base and for the
/// (only) virtual base.
raw_ostream& WriteNodeReference(QualType Type, bool FromVirtual);
};
void InheritanceHierarchyWriter::WriteNode(QualType Type, bool FromVirtual) {
QualType CanonType = Context.getCanonicalType(Type);
if (FromVirtual) {
if (KnownVirtualBases.find(CanonType) != KnownVirtualBases.end())
return;
// We haven't seen this virtual base before, so display it and
// its bases.
KnownVirtualBases.insert(CanonType);
}
// Declare the node itself.
Out << " ";
WriteNodeReference(Type, FromVirtual);
// Give the node a label based on the name of the class.
std::string TypeName = Type.getAsString();
Out << " [ shape=\"box\", label=\"" << DOT::EscapeString(TypeName);
// If the name of the class was a typedef or something different
// from the "real" class name, show the real class name in
// parentheses so we don't confuse ourselves.
if (TypeName != CanonType.getAsString()) {
Out << "\\n(" << CanonType.getAsString() << ")";
}
// Finished describing the node.
Out << " \"];\n";
// Display the base classes.
const CXXRecordDecl *Decl
= static_cast<const CXXRecordDecl *>(Type->getAs<RecordType>()->getDecl());
for (CXXRecordDecl::base_class_const_iterator Base = Decl->bases_begin();
Base != Decl->bases_end(); ++Base) {
QualType CanonBaseType = Context.getCanonicalType(Base->getType());
// If this is not virtual inheritance, bump the direct base
// count for the type.
if (!Base->isVirtual())
++DirectBaseCount[CanonBaseType];
// Write out the node (if we need to).
WriteNode(Base->getType(), Base->isVirtual());
// Write out the edge.
Out << " ";
WriteNodeReference(Type, FromVirtual);
Out << " -> ";
WriteNodeReference(Base->getType(), Base->isVirtual());
// Write out edge attributes to show the kind of inheritance.
if (Base->isVirtual()) {
Out << " [ style=\"dashed\" ]";
}
Out << ";";
}
}
/// WriteNodeReference - Write out a reference to the given node,
/// using a unique identifier for each direct base and for the
/// (only) virtual base.
raw_ostream&
InheritanceHierarchyWriter::WriteNodeReference(QualType Type,
bool FromVirtual) {
QualType CanonType = Context.getCanonicalType(Type);
Out << "Class_" << CanonType.getAsOpaquePtr();
if (!FromVirtual)
Out << "_" << DirectBaseCount[CanonType];
return Out;
}
/// viewInheritance - Display the inheritance hierarchy of this C++
/// class using GraphViz.
void CXXRecordDecl::viewInheritance(ASTContext& Context) const {
QualType Self = Context.getTypeDeclType(this);
std::string ErrMsg;
sys::Path Filename = sys::Path::GetTemporaryDirectory(&ErrMsg);
if (Filename.isEmpty()) {
llvm::errs() << "Error: " << ErrMsg << "\n";
return;
}
Filename.appendComponent(Self.getAsString() + ".dot");
if (Filename.makeUnique(true,&ErrMsg)) {
llvm::errs() << "Error: " << ErrMsg << "\n";
return;
}
llvm::errs() << "Writing '" << Filename.c_str() << "'... ";
llvm::raw_fd_ostream O(Filename.c_str(), ErrMsg);
if (ErrMsg.empty()) {
InheritanceHierarchyWriter Writer(Context, O);
Writer.WriteGraph(Self);
llvm::errs() << " done. \n";
O.close();
// Display the graph
DisplayGraph(Filename);
} else {
llvm::errs() << "error opening file for writing!\n";
}
}
}
|
Remove an unneeded const_cast
|
Remove an unneeded const_cast
git-svn-id: ffe668792ed300d6c2daa1f6eba2e0aa28d7ec6c@172370 91177308-0d34-0410-b5e6-96231b3b80d8
|
C++
|
apache-2.0
|
apple/swift-clang,apple/swift-clang,llvm-mirror/clang,apple/swift-clang,llvm-mirror/clang,llvm-mirror/clang,llvm-mirror/clang,apple/swift-clang,llvm-mirror/clang,apple/swift-clang,llvm-mirror/clang,llvm-mirror/clang,llvm-mirror/clang,apple/swift-clang,llvm-mirror/clang,apple/swift-clang,apple/swift-clang,apple/swift-clang,llvm-mirror/clang,apple/swift-clang
|
2bc39b606f6171ec3529acbda69c60a5260f10e7
|
Modules/ExampleModule/src/ExampleImageInteractor.cpp
|
Modules/ExampleModule/src/ExampleImageInteractor.cpp
|
/*============================================================================
The Medical Imaging Interaction Toolkit (MITK)
Copyright (c) German Cancer Research Center (DKFZ)
All rights reserved.
Use of this source code is governed by a 3-clause BSD license that can be
found in the LICENSE file.
============================================================================*/
#include <mitkImage.h>
#include <mitkImagePixelWriteAccessor.h>
#include <mitkInteractionPositionEvent.h>
#include <ExampleImageInteractor.h>
#include <limits>
namespace
{
// Helper function to get an image from a data node.
mitk::Image::Pointer GetImage(mitk::DataNode::Pointer dataNode)
{
if (dataNode.IsNull())
mitkThrow();
mitk::Image::Pointer image = dynamic_cast<mitk::Image*>(dataNode->GetData());
if (image.IsNull())
mitkThrow();
return image;
}
// Helper function to get a geometry of an image for a specific time step.
mitk::BaseGeometry::Pointer GetGeometry(mitk::Image::Pointer image, unsigned int timeStep)
{
mitk::TimeGeometry::Pointer timeGeometry = image->GetTimeGeometry();
if (timeGeometry.IsNull())
mitkThrow();
auto geometry = timeGeometry->GetGeometryForTimeStep(timeStep);
if (geometry.IsNull())
mitkThrow();
return geometry;
}
}
// The actual painting happens here. We're using a write accessor to gain safe
// write access to our image. The whole image volume for a given time step is
// locked. However, it's also possible - and preferable - to lock the slice of
// interest only.
template <typename T>
static void Paint(mitk::Image::Pointer image, itk::Index<3> index, unsigned int timeStep)
{
// As soon as the ImagePixelWriteAccessor object goes out of scope at the
// end of this function, the image will be unlocked again (RAII).
mitk::ImagePixelWriteAccessor<T> writeAccessor(image, image->GetVolumeData(timeStep));
writeAccessor.SetPixelByIndex(index, std::numeric_limits<T>::min());
// Don't forget to update the modified time stamp of the image. Otherwise,
// everything downstream wouldn't recognize that the image changed,
// including the rendering system.
image->Modified();
}
// Helper function to multiplex the actual Paint function call for different
// pixel types. As it's cumbersome and ugly, you may want to avoid such
// functions by using ITK for the actual painting and use the ITK access
// macros like we did for the AwesomeImageFilter.
static void Paint(mitk::Image::Pointer image, itk::Index<3> index, unsigned int timeStep)
{
switch (image->GetPixelType().GetComponentType())
{
case itk::ImageIOBase::CHAR:
Paint<char>(image, index, timeStep);
break;
case itk::ImageIOBase::UCHAR:
Paint<unsigned char>(image, index, timeStep);
break;
case itk::ImageIOBase::SHORT:
Paint<short>(image, index, timeStep);
break;
case itk::ImageIOBase::USHORT:
Paint<unsigned short>(image, index, timeStep);
break;
case itk::ImageIOBase::INT:
Paint<int>(image, index, timeStep);
break;
case itk::ImageIOBase::UINT:
Paint<unsigned int>(image, index, timeStep);
break;
default:
mitkThrow();
}
}
ExampleImageInteractor::ExampleImageInteractor()
{
}
ExampleImageInteractor::~ExampleImageInteractor()
{
}
void ExampleImageInteractor::ConnectActionsAndFunctions()
{
// Wire up this interactor with the state machine that is described by
// resource/Interactions/Paint.xml.
CONNECT_FUNCTION("paint", Paint)
}
void ExampleImageInteractor::DataNodeChanged()
{
// You almost always want to reset the state machine when the interactor
// has been attached to another data node.
this->ResetToStartState();
}
// The state machine is wired up with this Paint method. We wrote a few helper
// functions at the top of this files to keep this method clear and easy to
// read.
void ExampleImageInteractor::Paint(mitk::StateMachineAction*, mitk::InteractionEvent* event)
{
try
{
auto renderer = event->GetSender();
auto image = GetImage(this->GetDataNode());
auto timeStep = renderer->GetTimeStep();
auto geometry = GetGeometry(image, timeStep);
// This method is wired up to mouse events. Thus, we can safely assume
// that the following cast will succeed and we have access to the mouse
// position and the first intersection point of a ray originating at the
// mouse position and shot into the scene. Convenient, isn't it? :-)
auto positionEvent = dynamic_cast<mitk::InteractionPositionEvent*>(event);
auto position = positionEvent->GetPositionInWorld();
if (!geometry->IsInside(position))
return; // Nothing to paint, as we're not inside the image bounds.
// Okay, we're safe. Convert the mouse position to the index of the pixel
// we're pointing at.
itk::Index<3> index;
geometry->WorldToIndex<3>(position, index);
// We don't need to paint over and over again while moving the mouse
// pointer inside the same pixel. That's especially relevant when operating
// on zoomed images.
if (index != m_LastPixelIndex)
{
// And finally...
::Paint(image, index, timeStep);
// Nearly done. We request the renderer to update the render window in
// order to see the result immediately. Actually, we should update all
// of the render windows by caling RequestUpdateAll() instead, as the
// painted pixels are possibly visible in other render windows, too.
// However, we decided to prefer performance here.
mitk::RenderingManager::GetInstance()->RequestUpdate(positionEvent->GetSender()->GetRenderWindow());
MITK_INFO << index[0] << " " << index[1] << " " << index[2];
m_LastPixelIndex = index;
}
}
catch (...)
{
return;
}
}
|
/*============================================================================
The Medical Imaging Interaction Toolkit (MITK)
Copyright (c) German Cancer Research Center (DKFZ)
All rights reserved.
Use of this source code is governed by a 3-clause BSD license that can be
found in the LICENSE file.
============================================================================*/
#include <mitkImage.h>
#include <mitkImagePixelWriteAccessor.h>
#include <mitkInteractionPositionEvent.h>
#include <ExampleImageInteractor.h>
#include <limits>
namespace
{
// Helper function to get an image from a data node.
mitk::Image::Pointer GetImage(mitk::DataNode::Pointer dataNode)
{
if (dataNode.IsNull())
mitkThrow();
mitk::Image::Pointer image = dynamic_cast<mitk::Image*>(dataNode->GetData());
if (image.IsNull())
mitkThrow();
return image;
}
// Helper function to get a geometry of an image for a specific time step.
mitk::BaseGeometry::Pointer GetGeometry(mitk::Image::Pointer image, unsigned int timeStep)
{
mitk::TimeGeometry::Pointer timeGeometry = image->GetTimeGeometry();
if (timeGeometry.IsNull())
mitkThrow();
auto geometry = timeGeometry->GetGeometryForTimeStep(timeStep);
if (geometry.IsNull())
mitkThrow();
return geometry;
}
}
// The actual painting happens here. We're using a write accessor to gain safe
// write access to our image. The whole image volume for a given time step is
// locked. However, it's also possible - and preferable - to lock the slice of
// interest only.
template <typename T>
static void Paint(mitk::Image::Pointer image, itk::Index<3> index, unsigned int timeStep)
{
// As soon as the ImagePixelWriteAccessor object goes out of scope at the
// end of this function, the image will be unlocked again (RAII).
mitk::ImagePixelWriteAccessor<T> writeAccessor(image, image->GetVolumeData(timeStep));
writeAccessor.SetPixelByIndex(index, std::numeric_limits<T>::min());
// Don't forget to update the modified time stamp of the image. Otherwise,
// everything downstream wouldn't recognize that the image changed,
// including the rendering system.
image->Modified();
}
// Helper function to multiplex the actual Paint function call for different
// pixel types. As it's cumbersome and ugly, you may want to avoid such
// functions by using ITK for the actual painting and use the ITK access
// macros like we did for the AwesomeImageFilter.
static void Paint(mitk::Image::Pointer image, itk::Index<3> index, unsigned int timeStep)
{
switch (image->GetPixelType().GetComponentType())
{
#if ITK_VERSION_MAJOR < 5
case itk::ImageIOBase::CHAR:
#else
case itk::IOComponentEnum::CHAR:
#endif
Paint<char>(image, index, timeStep);
break;
#if ITK_VERSION_MAJOR < 5
case itk::ImageIOBase::UCHAR:
#else
case itk::IOComponentEnum::UCHAR:
#endif
Paint<unsigned char>(image, index, timeStep);
break;
#if ITK_VERSION_MAJOR < 5
case itk::ImageIOBase::SHORT:
#else
case itk::IOComponentEnum::SHORT:
#endif
Paint<short>(image, index, timeStep);
break;
#if ITK_VERSION_MAJOR < 5
case itk::ImageIOBase::USHORT:
#else
case itk::IOComponentEnum::USHORT:
#endif
Paint<unsigned short>(image, index, timeStep);
break;
#if ITK_VERSION_MAJOR < 5
case itk::ImageIOBase::INT:
#else
case itk::IOComponentEnum::INT:
#endif
Paint<int>(image, index, timeStep);
break;
#if ITK_VERSION_MAJOR < 5
case itk::ImageIOBase::UINT:
#else
case itk::IOComponentEnum::UINT:
#endif
Paint<unsigned int>(image, index, timeStep);
break;
default:
mitkThrow();
}
}
ExampleImageInteractor::ExampleImageInteractor()
{
}
ExampleImageInteractor::~ExampleImageInteractor()
{
}
void ExampleImageInteractor::ConnectActionsAndFunctions()
{
// Wire up this interactor with the state machine that is described by
// resource/Interactions/Paint.xml.
CONNECT_FUNCTION("paint", Paint)
}
void ExampleImageInteractor::DataNodeChanged()
{
// You almost always want to reset the state machine when the interactor
// has been attached to another data node.
this->ResetToStartState();
}
// The state machine is wired up with this Paint method. We wrote a few helper
// functions at the top of this files to keep this method clear and easy to
// read.
void ExampleImageInteractor::Paint(mitk::StateMachineAction*, mitk::InteractionEvent* event)
{
try
{
auto renderer = event->GetSender();
auto image = GetImage(this->GetDataNode());
auto timeStep = renderer->GetTimeStep();
auto geometry = GetGeometry(image, timeStep);
// This method is wired up to mouse events. Thus, we can safely assume
// that the following cast will succeed and we have access to the mouse
// position and the first intersection point of a ray originating at the
// mouse position and shot into the scene. Convenient, isn't it? :-)
auto positionEvent = dynamic_cast<mitk::InteractionPositionEvent*>(event);
auto position = positionEvent->GetPositionInWorld();
if (!geometry->IsInside(position))
return; // Nothing to paint, as we're not inside the image bounds.
// Okay, we're safe. Convert the mouse position to the index of the pixel
// we're pointing at.
itk::Index<3> index;
geometry->WorldToIndex<3>(position, index);
// We don't need to paint over and over again while moving the mouse
// pointer inside the same pixel. That's especially relevant when operating
// on zoomed images.
if (index != m_LastPixelIndex)
{
// And finally...
::Paint(image, index, timeStep);
// Nearly done. We request the renderer to update the render window in
// order to see the result immediately. Actually, we should update all
// of the render windows by caling RequestUpdateAll() instead, as the
// painted pixels are possibly visible in other render windows, too.
// However, we decided to prefer performance here.
mitk::RenderingManager::GetInstance()->RequestUpdate(positionEvent->GetSender()->GetRenderWindow());
MITK_INFO << index[0] << " " << index[1] << " " << index[2];
m_LastPixelIndex = index;
}
}
catch (...)
{
return;
}
}
|
Make project template compatible to both ITK v4 and v5
|
Make project template compatible to both ITK v4 and v5
|
C++
|
bsd-3-clause
|
MITK/MITK-ProjectTemplate
|
c564e63ffa4037e27a52938f12a16f6102601b74
|
modules/eigenutils/src/eigenutilsmodule.cpp
|
modules/eigenutils/src/eigenutilsmodule.cpp
|
/*********************************************************************************
*
* Inviwo - Interactive Visualization Workshop
*
* Copyright (c) 2015-2018 Inviwo Foundation
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
* ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
*********************************************************************************/
#include <modules/eigenutils/eigenutilsmodule.h>
#include <modules/eigenutils/processors/eigenmatrixtoimage.h>
#include <modules/eigenutils/eigenports.h>
#include <modules/eigenutils/processors/eigenmix.h>
#include <modules/eigenutils/processors/eigennormalize.h>
namespace inviwo {
EigenUtilsModule::EigenUtilsModule(InviwoApplication* app) : InviwoModule(app, "EigenUtils") {
registerProcessor<EigenMatrixToImage>();
registerProcessor<EigenMix>();
registerProcessor<EigenNormalize>();
// Add a directory to the search path of the Shadermanager
// ShaderManager::getPtr()->addShaderSearchPath(PathType::Modules, "/eigenutils/glsl");
// Register objects that can be shared with the rest of inviwo here:
// Processors
// registerProcessor<EigenUtilsProcessor>());
// Properties
// registerProperty<EigenUtilsProperty>());
// Readers and writes
// registerDataReader(util::make_unique<EigenUtilsReader>());
// registerDataWriter(util::make_unique<EigenUtilsWriter>());
// Data converters
// registerRepresentationConverter(util::make_unique<EigenUtilsDisk2RAMConverter>());
// Ports
registerDefaultsForDataType<Eigen::MatrixXf>();
registerPortInspector("EigenMatrixXfOutport",
this->getPath(ModulePath::PortInspectors) + "/eigenmatrix.inv");
// PropertyWidgets
// registerPropertyWidget<EigenUtilsPropertyWidget, EigenUtilsProperty>("Default");
// Dialogs
// registerDialog<EigenUtilsDialog>(EigenUtilsOutport));
// Other varius things
// registerCapabilities(util::make_unique<EigenUtilsCapabilities>()));
// registerSettings(util::make_unique<EigenUtilsSettings>());
// registerMetaData(util::make_unique<EigenUtilsMetaData>());
// registerProcessorWidget(std::string processorClassName, std::unique_ptr<ProcessorWidget>
// processorWidget);
// registerDrawer(util::make_unique_ptr<EigenUtilsDrawer>());
}
} // namespace inviwo
|
/*********************************************************************************
*
* Inviwo - Interactive Visualization Workshop
*
* Copyright (c) 2015-2018 Inviwo Foundation
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
* ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
*********************************************************************************/
#include <modules/eigenutils/eigenutilsmodule.h>
#include <modules/eigenutils/processors/eigenmatrixtoimage.h>
#include <modules/eigenutils/eigenports.h>
#include <modules/eigenutils/processors/eigenmix.h>
#include <modules/eigenutils/processors/eigennormalize.h>
namespace inviwo {
EigenUtilsModule::EigenUtilsModule(InviwoApplication* app) : InviwoModule(app, "EigenUtils") {
registerProcessor<EigenMatrixToImage>();
registerProcessor<EigenMix>();
registerProcessor<EigenNormalize>();
// Add a directory to the search path of the Shadermanager
// ShaderManager::getPtr()->addShaderSearchPath(PathType::Modules, "/eigenutils/glsl");
// Register objects that can be shared with the rest of inviwo here:
// Processors
// registerProcessor<EigenUtilsProcessor>());
// Properties
// registerProperty<EigenUtilsProperty>());
// Readers and writes
// registerDataReader(util::make_unique<EigenUtilsReader>());
// registerDataWriter(util::make_unique<EigenUtilsWriter>());
// Data converters
// registerRepresentationConverter(util::make_unique<EigenUtilsDisk2RAMConverter>());
// Ports
registerDefaultsForDataType<Eigen::MatrixXf>();
registerPortInspector(PortTraits<DataOutport<Eigen::MatrixXf>>::classIdentifier(),
this->getPath(ModulePath::PortInspectors) + "/eigenmatrix.inv");
// PropertyWidgets
// registerPropertyWidget<EigenUtilsPropertyWidget, EigenUtilsProperty>("Default");
// Dialogs
// registerDialog<EigenUtilsDialog>(EigenUtilsOutport));
// Other varius things
// registerCapabilities(util::make_unique<EigenUtilsCapabilities>()));
// registerSettings(util::make_unique<EigenUtilsSettings>());
// registerMetaData(util::make_unique<EigenUtilsMetaData>());
// registerProcessorWidget(std::string processorClassName, std::unique_ptr<ProcessorWidget>
// processorWidget);
// registerDrawer(util::make_unique_ptr<EigenUtilsDrawer>());
}
} // namespace inviwo
|
Fix for port inspector not working
|
Eigen: Fix for port inspector not working
|
C++
|
bsd-2-clause
|
inviwo/inviwo,inviwo/inviwo,Sparkier/inviwo,inviwo/inviwo,inviwo/inviwo,Sparkier/inviwo,Sparkier/inviwo,Sparkier/inviwo,inviwo/inviwo,Sparkier/inviwo,inviwo/inviwo
|
3009fd4831b2f26f1c9b0efed8d50018f59f4e71
|
test/unit/attribute-specifier-sequence.cpp
|
test/unit/attribute-specifier-sequence.cpp
|
#include <catch/catch.hpp>
#include "cppparser.h"
#include "embedded-snippet-test-base.h"
#include <string>
class CppAtributeTest : public EmbeddedSnippetTestBase
{
protected:
CppAtributeTest()
: EmbeddedSnippetTestBase(__FILE__)
{
}
};
TEST_CASE_METHOD(CppAtributeTest, "Attribute specifier sequence")
{
#if TEST_CASE_SNIPPET_STARTS_FROM_NEXT_LINE
struct [[xnet::ValidateData]] SignUpRequest
{
[[xnet::StringNotEmpty]] [[xnet::StringMinLength(2)]] std::string name;
};
class [[xnet::HttpController]] [[xnet::Route("/plakmp")]] PlakMpApiController
{
public:
[[xnet::HttpGet]] [[xnet::Route("/players")]] std::string GetPlakMpPlayers(std::string first_name);
[[xnet::HttpGet]] std::string GetHelloWorld();
[[xnet::HttpPost]] [[xnet::Route("/register")]] std::string CreateAccount(
[[xnet::FromBody]] [[xnet::EnsureValid]] SignUpRequest request);
};
#endif
auto testSnippet = getTestSnippetParseStream(__LINE__ - 2);
CppParser parser;
const auto ast = parser.parseStream(testSnippet.data(), testSnippet.size());
REQUIRE(ast != nullptr);
const auto& members = ast->members();
REQUIRE(members.size() == 2);
CppCompoundEPtr structDefn = members[0];
REQUIRE(structDefn);
const auto& structAttribSeq = structDefn->attribSpecifierSequence();
REQUIRE(structAttribSeq);
REQUIRE(structAttribSeq->size() == 1);
CppExprEPtr structAttrib = structAttribSeq->at(0);
REQUIRE(structAttrib);
CHECK((*structAttrib) == CppExpr("xnet::ValidateData"));
const auto& structMembers = structDefn->members();
REQUIRE(structMembers.size() == 1);
CppCompoundEPtr classDefn = members[1];
REQUIRE(classDefn);
REQUIRE(classDefn->attribSpecifierSequence());
const auto& classMembers = classDefn->members();
REQUIRE(classMembers.size() == 3);
}
|
#include <catch/catch.hpp>
#include "cppparser.h"
#include "embedded-snippet-test-base.h"
#include <string>
class CppAtributeTest : public EmbeddedSnippetTestBase
{
protected:
CppAtributeTest()
: EmbeddedSnippetTestBase(__FILE__)
{
}
};
TEST_CASE_METHOD(CppAtributeTest, "Attribute specifier sequence")
{
#if TEST_CASE_SNIPPET_STARTS_FROM_NEXT_LINE
struct [[xnet::ValidateData]] SignUpRequest
{
[[xnet::StringNotEmpty]] [[xnet::StringMinLength(2)]] std::string name;
};
class [[xnet::HttpController]] [[xnet::Route("/plakmp")]] PlakMpApiController
{
public:
[[xnet::HttpGet]] [[xnet::Route("/players")]] std::string GetPlakMpPlayers(std::string first_name);
[[xnet::HttpGet]] std::string GetHelloWorld();
[[xnet::HttpPost]] [[xnet::Route("/register")]] std::string CreateAccount(
[[xnet::FromBody]] [[xnet::EnsureValid]] SignUpRequest request);
};
#endif
auto testSnippet = getTestSnippetParseStream(__LINE__ - 2);
CppParser parser;
const auto ast = parser.parseStream(testSnippet.data(), testSnippet.size());
REQUIRE(ast != nullptr);
const auto& members = ast->members();
REQUIRE(members.size() == 2);
CppCompoundEPtr structDefn = members[0];
REQUIRE(structDefn);
const auto& structAttribSeq = structDefn->attribSpecifierSequence();
REQUIRE(structAttribSeq);
REQUIRE(structAttribSeq->size() == 1);
CppExprEPtr structAttrib = structAttribSeq->at(0);
REQUIRE(structAttrib);
CHECK((*structAttrib) == CppExpr("xnet::ValidateData"));
const auto& structMembers = structDefn->members();
REQUIRE(structMembers.size() == 1);
CppCompoundEPtr classDefn = members[1];
REQUIRE(classDefn);
const auto& classAttribSeq = classDefn->attribSpecifierSequence();
REQUIRE(classAttribSeq);
REQUIRE(classAttribSeq->size() == 2);
CppExprEPtr classAttrib0 = classAttribSeq->at(0);
REQUIRE(classAttrib0);
CHECK((*classAttrib0) == CppExpr("xnet::HttpController"));
CppExprEPtr classAttrib1 = classAttribSeq->at(1);
REQUIRE(classAttrib1);
REQUIRE(classAttrib1->expr1_.atom);
CHECK(*(classAttrib1->expr1_.atom) == "xnet::Route");
CHECK(classAttrib1->oper_ == CppOperator::kFunctionCall);
const auto funcArgs = classAttrib1->expr2_.expr;
REQUIRE(funcArgs);
CHECK(funcArgs->expr1_.type == CppExprAtom::kAtom);
REQUIRE(funcArgs->expr1_.atom);
CHECK(*(funcArgs->expr1_.atom) == "\"/plakmp\"");
const auto& classMembers = classDefn->members();
REQUIRE(classMembers.size() == 3);
const CppFunctionEPtr methodGetPlakMpPlayers = classMembers[0];
REQUIRE(methodGetPlakMpPlayers);
const auto& returnTypeGetPlakMpPlayers = methodGetPlakMpPlayers->retType_;
REQUIRE(returnTypeGetPlakMpPlayers);
const auto& attribSeqGetPlakMpPlayers = returnTypeGetPlakMpPlayers->attribSpecifierSequence();
REQUIRE(attribSeqGetPlakMpPlayers);
REQUIRE(attribSeqGetPlakMpPlayers->size() == 2);
CppExprEPtr methodAttrib0 = attribSeqGetPlakMpPlayers->at(0);
REQUIRE(methodAttrib0);
CHECK((*methodAttrib0) == CppExpr("xnet::HttpGet"));
CppExprEPtr methodAttrib1 = attribSeqGetPlakMpPlayers->at(1);
REQUIRE(methodAttrib1);
REQUIRE(methodAttrib1->expr1_.atom);
CHECK(*(methodAttrib1->expr1_.atom) == "xnet::Route");
CHECK(methodAttrib1->oper_ == CppOperator::kFunctionCall);
const auto funcArgs2 = methodAttrib1->expr2_.expr;
REQUIRE(funcArgs2);
CHECK(funcArgs2->expr1_.type == CppExprAtom::kAtom);
REQUIRE(funcArgs2->expr1_.atom);
CHECK(*(funcArgs2->expr1_.atom) == "\"/players\"");
}
|
add more checks in test for attribute specifier
|
add more checks in test for attribute specifier
|
C++
|
mit
|
satya-das/cppparser,satya-das/cppparser,satya-das/cppparser
|
5763e7e06a9e693b4faedb132550096cbdadfda2
|
huntTheWumpus/myFunctions.cpp
|
huntTheWumpus/myFunctions.cpp
|
#include "myHeader.h"
#include <iostream>
#include <fstream>
#include <string>
#include <iomanip>
using namespace std;
void printStringArr(const string a[], int n, ostream &os) {
for (int i = 0; i < n; i++)
os << "\n" << a[i];
}
int getIntInRange(int start, int end) {
int x = getInt();
while (x < start || x > end) {
cout
<< "\a\tYour number must be " << (x < start ? "greater" : "less")
<< " than or equal to "
<< (x < start ? start : end)
<< ". \n\tTry again: ";
x = getInt();
}
return x;
}
int getInt() {
double x = getNum();
while (int(x) != x) {
cout << "\a\tYour number is not an integer! \n\tTry Again: ";
x = getNum();
}
return int(x);
}
double getNum() {
double x;
while (!(cin >> x)) {
cin.clear(); cin.ignore(30, '\n');
cout << "\a\tPlease no inapropriate characters! \n\tTry again: ";
}
cin.ignore(80, '\n');
return x;
}
void loadStringArrayFromFile(string a[], int n, ifstream &ifs, bool &isLoaded) {
for (int i = 0; i < n; i++)
getline(ifs, a[i]);
isLoaded = true;
}
void loadStats(int &gamesPld, int whoWon[], double winPct[], double numMvs[], int n, ifstream &ifs, bool &isLoaded) {
while (ifs.peek() < '0' || ifs.peek() > '9')
ifs.ignore();
ifs >> gamesPld;
while (ifs.peek() < '0' || ifs.peek() > '9')
ifs.ignore();
for (int i = 0; i < n; i++)
ifs >> whoWon[i];
while (ifs.peek() < '0' || ifs.peek() > '9')
ifs.ignore();
for (int i = 0; i < n; i++) {
ifs >> winPct[i];
ifs.ignore(); // for discarding '%'
}
while (ifs.peek() < '0' || ifs.peek() > '9')
ifs.ignore();
for (int i = 0; i < n; i++)
ifs >> numMvs[i];
isLoaded = true;
}
void printStats(int gamesPld, const int whoWon[], const double winPct[], const double numMvs[], int n, ostream &os) {
os
<< fixed << setprecision(1)
<< "\nHunt the Wumpus Game Statistics"
<< "\n\n\tGames Played: " << gamesPld
<< "\n\n\tWho Won:"
<< "\n\tWumpus\tPit\tPlayer\n";
for (int i = 0; i < n; i++)
os << "\t" << whoWon[i];
os
<< "\n\n\tWin Rate:"
<< "\n\tWumpus\tPit\tPlayer\n";
for (int i = 0; i < n; i++)
os << "\t" << winPct[i] << "%";
os
<< "\n\n\tMoves per Game:"
<< "\n\tLeast\tMost\tAverage\n"
<< "\t" << int(numMvs[0])
<< "\t" << int(numMvs[1])
<< "\t" << numMvs[2];
}
void load2DArr(int map[][SIZE_EXITS], int const n, int const m) {
int tempMap[21][3] = {
{ 0, 0, 0 }, // room not actually used
{ 2, 4, 19 },
{ 1, 3, 6 },
{ 2, 8, 20 },
{ 1, 5, 9 },
{ 4, 6, 11 },
{ 2, 5, 7 },
{ 6, 8, 12 },
{ 3, 7, 13 },
{ 4, 10, 16 },
{ 9, 11, 14 },
{ 5, 10, 12 },
{ 7, 11, 15 },
{ 8, 15, 18 },
{ 10, 15, 17 },
{ 12, 13, 14 },
{ 9, 17, 19 },
{ 14, 16, 18 },
{ 13, 17, 20 },
{ 1, 16, 20 },
{ 3, 18, 19 }
};
for (int i = 0; i < n; i++)
for (int j = 0; j < m; j++)
map[i][j] = tempMap[i][j];
}
void print2DArr(int const map[][SIZE_EXITS], int n, int m, ostream &os) {
cout << "\n";
for (int i = 0; i < n; i++)
for (int j = 0; j < m; j++)
cout << "\t" << map[i][j] << (j % m == m - 1 ? "\n" : ", ");
}
int startHunt(int const map[][SIZE_EXITS], int player, int wumpus, int bat1, int bat2, int pit1, int pit2, int &count) {
count = 0;
char move;
int target;
bool encounteredHazard; // for printing some extra space
while (true) {
encounteredHazard = false;
cout << "~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~" << endl;
if (player == wumpus) {
cout << "\n\n\tYou awakened the Wumpus. He eats you. \n\tYou lose.";
return -1;
}
else if (player == bat1 || player == bat2) {
cout
<< "\n\n\tA Giant Bat grabs you and carries you through the caves."
<< "\n\tAfter what seems like a long time, it drops you in a new room."
<< "\n\tYou see the familiar features of the room you started in!";
encounteredHazard = true;
player = 1; // back to start
}
else if (player == pit1 || player == pit2) {
cout << "\n\n\tYou fell into a bottomless pit. \n\tYou lose.";
return 0;
}
if (isHazardNear(map, player, wumpus)) {
cout << "\n\tYou smell the unmistakable stench of a Wumpus";
encounteredHazard = true;
}
if (isHazardNear(map, player, bat1) || isHazardNear(map, player, bat2)) {
cout << "\n\tYou hear the flapping of large wings";
encounteredHazard = true;
}
if (isHazardNear(map, player, pit1) || isHazardNear(map, player, pit2)) {
cout << "\n\tYou feel an ominous breeze";
encounteredHazard = true;
}
cout << endl << (encounteredHazard ? "\n" : "");
printRoomAndExits(map, player);
cout << "\n\n\tDo you want to (M)ove or (S)hoot? ";
move = getMorS();
cout << "\tWhere do you want to " << (move == 'M' ? "move" : "shoot") << "? ";
target = getValidExit(map, player);
count++;
if (move == 'M') {
player = target;
cout << "\n";
}
else if (target == wumpus) {
cout << "\n\n\tYou killed the Wumpus! \n\tCongradulations, you win!";
return 1;
}
else {
cout
<< "\n\tYou missed the Wumpus!"
<< "\n\tYou awakened the Wumpus. He eats you. \n\tYou lose.";
return -1;
}
}
}
bool isHazardNear(int const map[][SIZE_EXITS], int p, int h) {
for (int i = 0; i < SIZE_EXITS; i++) {
if (h == map[p][i]) {
return true;
}
}
return false;
}
void printRoomAndExits(int const map[][SIZE_EXITS], int p) {
cout
<< "\tYou are in room " << p << endl
<< "\tYou may go to rooms:" << endl;
for (int i = 0; i < SIZE_EXITS; i++) {
cout << "\t" << map[p][i];
}
}
char getMorS() {
char c;
cin >> c; cin.ignore(80, '\n');
while (c != 'M' && c != 'm' && c != 'S' && c != 's') {
cout << "\tPlease type 'M' for move or 'S' for shoot: ";
cin >> c; cin.ignore(80, '\n');
}
return (c == 'm' ? 'M' : c == 's' ? 'S' : c); // returns only capitals
}
int getValidExit(int const map[][SIZE_EXITS], int p) {
int t = getInt();
while (t != map[p][0] && t != map[p][1] && t != map[p][2]) {
cout
<< "\n\tYou " << (t == p ? "are already t" : "can't go there from ")
<< "here. Try again: ";
t = getInt();
}
return t;
}
void updateStats(int &gamesPld, int whoWon[], double winPct[], double numMvs[], int n, int outcome, int lengthOfGame) {
if (gamesPld++ == 0)
// if first game, no need to find shortest/longest game
// or avg game length
for (int i = 0; i < n; i++)
numMvs[i] = lengthOfGame;
else {
if (lengthOfGame < numMvs[0])
numMvs[0] = lengthOfGame;
if (lengthOfGame > numMvs[1])
numMvs[1] = lengthOfGame;
// calc running avg
// newAvg = (oldAvg * prevTotalGamesPld + lengthOfMostRecentGame) / newTotalGamesPld
numMvs[2] = (numMvs[2] * double(gamesPld - 1) + double(lengthOfGame)) / double(gamesPld);
}
// outcome is the winner code and will increment the int representing the entity that won the last game
whoWon[outcome + 1]++;
for (int i = 0; i < n; i++)
winPct[i] = whoWon[i] / double(gamesPld) * 100;
}
|
#include "myHeader.h"
#include <iostream>
#include <fstream>
#include <string>
#include <iomanip>
using namespace std;
void printStringArr(const string a[], int n, ostream &os) {
for (int i = 0; i < n; i++)
os << "\n" << a[i];
}
int getIntInRange(int start, int end) {
int x = getInt();
while (x < start || x > end) {
cout
<< "\a\tYour number must be " << (x < start ? "greater" : "less")
<< " than or equal to "
<< (x < start ? start : end)
<< ". \n\tTry again: ";
x = getInt();
}
return x;
}
int getInt() {
double x = getNum();
while (int(x) != x) {
cout << "\a\tYour number is not an integer! \n\tTry Again: ";
x = getNum();
}
return int(x);
}
double getNum() {
double x;
while (!(cin >> x)) {
cin.clear(); cin.ignore(30, '\n');
cout << "\a\tPlease no inapropriate characters! \n\tTry again: ";
}
cin.ignore(80, '\n');
return x;
}
void loadStringArrayFromFile(string a[], int n, ifstream &ifs, bool &isLoaded) {
for (int i = 0; i < n; i++)
getline(ifs, a[i]);
isLoaded = true;
}
void loadStats(int &gamesPld, int whoWon[], double winPct[], double numMvs[], int n, ifstream &ifs, bool &isLoaded) {
while (ifs.peek() < '0' || ifs.peek() > '9')
ifs.ignore();
ifs >> gamesPld;
while (ifs.peek() < '0' || ifs.peek() > '9')
ifs.ignore();
for (int i = 0; i < n; i++)
ifs >> whoWon[i];
while (ifs.peek() < '0' || ifs.peek() > '9')
ifs.ignore();
for (int i = 0; i < n; i++) {
ifs >> winPct[i];
ifs.ignore(); // for discarding '%'
}
while (ifs.peek() < '0' || ifs.peek() > '9')
ifs.ignore();
for (int i = 0; i < n; i++)
ifs >> numMvs[i];
isLoaded = true;
}
void printStats(int gamesPld, const int whoWon[], const double winPct[], const double numMvs[], int n, ostream &os) {
os
<< fixed << setprecision(1)
<< "\nHunt the Wumpus Game Statistics"
<< "\n\n\tGames Played: " << gamesPld
<< "\n\n\tWho Won:"
<< "\n\tWumpus\tPit\tPlayer\n";
for (int i = 0; i < n; i++)
os << "\t" << whoWon[i];
os << endl;
for (int i = 0; i < n; i++)
os << "\t" << winPct[i] << "%";
os
<< "\n\n\tMoves per Game:"
<< "\n\tLeast\tMost\tAverage\n"
<< "\t" << int(numMvs[0])
<< "\t" << int(numMvs[1])
<< "\t" << numMvs[2];
}
void load2DArr(int map[][SIZE_EXITS], int const n, int const m) {
int tempMap[21][3] = {
{ 0, 0, 0 }, // room not actually used
{ 2, 4, 19 },
{ 1, 3, 6 },
{ 2, 8, 20 },
{ 1, 5, 9 },
{ 4, 6, 11 },
{ 2, 5, 7 },
{ 6, 8, 12 },
{ 3, 7, 13 },
{ 4, 10, 16 },
{ 9, 11, 14 },
{ 5, 10, 12 },
{ 7, 11, 15 },
{ 8, 15, 18 },
{ 10, 15, 17 },
{ 12, 13, 14 },
{ 9, 17, 19 },
{ 14, 16, 18 },
{ 13, 17, 20 },
{ 1, 16, 20 },
{ 3, 18, 19 }
};
for (int i = 0; i < n; i++)
for (int j = 0; j < m; j++)
map[i][j] = tempMap[i][j];
}
void print2DArr(int const map[][SIZE_EXITS], int n, int m, ostream &os) {
cout << "\n";
for (int i = 0; i < n; i++)
for (int j = 0; j < m; j++)
cout << "\t" << map[i][j] << (j % m == m - 1 ? "\n" : ", ");
}
int startHunt(int const map[][SIZE_EXITS], int player, int wumpus, int bat1, int bat2, int pit1, int pit2, int &count) {
count = 0;
char move;
int target;
bool encounteredHazard; // for printing some extra space
while (true) {
encounteredHazard = false;
cout << "~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~" << endl;
if (player == wumpus) {
cout << "\n\n\tYou awakened the Wumpus. He eats you. \n\tYou lose.";
return -1;
}
else if (player == bat1 || player == bat2) {
cout
<< "\n\n\tA Giant Bat grabs you and carries you through the caves."
<< "\n\tAfter what seems like a long time, it drops you in a new room."
<< "\n\tYou see the familiar features of the room you started in!";
encounteredHazard = true;
player = 1; // back to start
}
else if (player == pit1 || player == pit2) {
cout << "\n\n\tYou fell into a bottomless pit. \n\tYou lose.";
return 0;
}
if (isHazardNear(map, player, wumpus)) {
cout << "\n\tYou smell the unmistakable stench of a Wumpus";
encounteredHazard = true;
}
if (isHazardNear(map, player, bat1) || isHazardNear(map, player, bat2)) {
cout << "\n\tYou hear the flapping of large wings";
encounteredHazard = true;
}
if (isHazardNear(map, player, pit1) || isHazardNear(map, player, pit2)) {
cout << "\n\tYou feel an ominous breeze";
encounteredHazard = true;
}
cout << endl << (encounteredHazard ? "\n" : "");
printRoomAndExits(map, player);
cout << "\n\n\tDo you want to (M)ove or (S)hoot? ";
move = getMorS();
cout << "\tWhere do you want to " << (move == 'M' ? "move" : "shoot") << "? ";
target = getValidExit(map, player);
count++;
if (move == 'M') {
player = target;
cout << "\n";
}
else if (target == wumpus) {
cout << "\n\n\tYou killed the Wumpus! \n\tCongradulations, you win!";
return 1;
}
else {
cout
<< "\n\tYou missed the Wumpus!"
<< "\n\tYou awakened the Wumpus. He eats you. \n\tYou lose.";
return -1;
}
}
}
bool isHazardNear(int const map[][SIZE_EXITS], int p, int h) {
for (int i = 0; i < SIZE_EXITS; i++) {
if (h == map[p][i]) {
return true;
}
}
return false;
}
void printRoomAndExits(int const map[][SIZE_EXITS], int p) {
cout
<< "\tYou are in room " << p << endl
<< "\tYou may go to rooms:" << endl;
for (int i = 0; i < SIZE_EXITS; i++) {
cout << "\t" << map[p][i];
}
}
char getMorS() {
char c;
cin >> c; cin.ignore(80, '\n');
while (c != 'M' && c != 'm' && c != 'S' && c != 's') {
cout << "\tPlease type 'M' for move or 'S' for shoot: ";
cin >> c; cin.ignore(80, '\n');
}
return (c == 'm' ? 'M' : c == 's' ? 'S' : c); // returns only capitals
}
int getValidExit(int const map[][SIZE_EXITS], int p) {
int t = getInt();
while (t != map[p][0] && t != map[p][1] && t != map[p][2]) {
cout
<< "\n\tYou " << (t == p ? "are already t" : "can't go there from ")
<< "here. Try again: ";
t = getInt();
}
return t;
}
void updateStats(int &gamesPld, int whoWon[], double winPct[], double numMvs[], int n, int outcome, int lengthOfGame) {
if (gamesPld++ == 0)
// if first game, no need to find shortest/longest game
// or avg game length
for (int i = 0; i < n; i++)
numMvs[i] = lengthOfGame;
else {
if (lengthOfGame < numMvs[0])
numMvs[0] = lengthOfGame;
if (lengthOfGame > numMvs[1])
numMvs[1] = lengthOfGame;
// calc running avg
// newAvg = (oldAvg * prevTotalGamesPld + lengthOfMostRecentGame) / newTotalGamesPld
numMvs[2] = (numMvs[2] * double(gamesPld - 1) + double(lengthOfGame)) / double(gamesPld);
}
// outcome is the winner code and will increment the int representing the entity that won the last game
whoWon[outcome + 1]++;
for (int i = 0; i < n; i++)
winPct[i] = whoWon[i] / double(gamesPld) * 100;
}
|
change in output file format
|
change in output file format
|
C++
|
mit
|
joshguerra/CIT-120
|
3f8db7e0dec8b54f0ec7d725b1fbcd263129a666
|
src/server/webserver_options.cc
|
src/server/webserver_options.cc
|
// Copyright (c) 2013, Cloudera, inc.
#include "server/webserver_options.h"
#include <gflags/gflags.h>
#include <string.h>
#include <stdlib.h>
using std::string;
namespace kudu {
static const char* GetDefaultDocumentRoot();
} // namespace kudu
// Flags defining web server behavior. The class implementation should
// not use these directly, but rather access them via WebserverOptions.
// This makes it easier to instantiate web servers with different options
// within a single unit test.
DEFINE_int32(webserver_port, 25000, "Port to start debug webserver on");
DEFINE_string(webserver_interface, "",
"Interface to start debug webserver on. If blank, webserver binds to 0.0.0.0");
DEFINE_string(webserver_doc_root, kudu::GetDefaultDocumentRoot(),
"Files under <webserver_doc_root>/www are accessible via the debug webserver. "
"Defaults to KUDU_HOME, or if KUDU_HOME is not set, disables the document "
"root");
DEFINE_bool(enable_webserver_doc_root, true,
"If true, webserver may serve static files from the webserver_doc_root");
DEFINE_string(webserver_certificate_file, "",
"The location of the debug webserver's SSL certificate file, in .pem format. If "
"empty, webserver SSL support is not enabled");
DEFINE_string(webserver_authentication_domain, "",
"Domain used for debug webserver authentication");
DEFINE_string(webserver_password_file, "",
"(Optional) Location of .htpasswd file containing user names and hashed passwords for"
" debug webserver authentication");
DEFINE_int32(webserver_num_worker_threads, 50,
"Number of threads to start for handling web server requests");
namespace kudu {
// Returns KUDU_HOME if set, otherwise we won't serve any static files.
static const char* GetDefaultDocumentRoot() {
char* kudu_home = getenv("KUDU_HOME");
if (kudu_home == NULL) {
return ""; // Empty document root means don't serve static files
} else {
// Deliberate memory leak, but this should be called exactly once.
string* str = new string(kudu_home);
return str->c_str();
}
}
WebserverOptions::WebserverOptions()
: bind_interface(FLAGS_webserver_interface),
port(FLAGS_webserver_port),
doc_root(FLAGS_webserver_doc_root),
enable_doc_root(FLAGS_enable_webserver_doc_root),
certificate_file(FLAGS_webserver_certificate_file),
authentication_domain(FLAGS_webserver_authentication_domain),
password_file(FLAGS_webserver_password_file),
num_worker_threads(FLAGS_webserver_num_worker_threads) {
}
} // namespace kudu
|
// Copyright (c) 2013, Cloudera, inc.
#include "server/webserver_options.h"
#include <gflags/gflags.h>
#include <string.h>
#include <stdlib.h>
using std::string;
namespace kudu {
static const char* GetDefaultDocumentRoot();
} // namespace kudu
// Flags defining web server behavior. The class implementation should
// not use these directly, but rather access them via WebserverOptions.
// This makes it easier to instantiate web servers with different options
// within a single unit test.
DEFINE_int32(webserver_port, 25000, "Port to start debug webserver on");
DEFINE_string(webserver_interface, "",
"Interface to start debug webserver on. If blank, webserver binds to 0.0.0.0");
DEFINE_string(webserver_doc_root, kudu::GetDefaultDocumentRoot(),
"Files under <webserver_doc_root>/www are accessible via the debug webserver. "
"Defaults to KUDU_HOME, or if KUDU_HOME is not set, disables the document "
"root");
DEFINE_bool(enable_webserver_doc_root, true,
"If true, webserver may serve static files from the webserver_doc_root");
DEFINE_string(webserver_certificate_file, "",
"The location of the debug webserver's SSL certificate file, in .pem format. If "
"empty, webserver SSL support is not enabled");
DEFINE_string(webserver_authentication_domain, "",
"Domain used for debug webserver authentication");
DEFINE_string(webserver_password_file, "",
"(Optional) Location of .htpasswd file containing user names and hashed passwords for"
" debug webserver authentication");
DEFINE_int32(webserver_num_worker_threads, 50,
"Number of threads to start for handling web server requests");
namespace kudu {
// Returns KUDU_HOME if set, otherwise we won't serve any static files.
static const char* GetDefaultDocumentRoot() {
char* kudu_home = getenv("KUDU_HOME");
// Empty document root means don't serve static files
return kudu_home ? kudu_home : "";
}
WebserverOptions::WebserverOptions()
: bind_interface(FLAGS_webserver_interface),
port(FLAGS_webserver_port),
doc_root(FLAGS_webserver_doc_root),
enable_doc_root(FLAGS_enable_webserver_doc_root),
certificate_file(FLAGS_webserver_certificate_file),
authentication_domain(FLAGS_webserver_authentication_domain),
password_file(FLAGS_webserver_password_file),
num_worker_threads(FLAGS_webserver_num_worker_threads) {
}
} // namespace kudu
|
Fix memory leak in web server
|
Fix memory leak in web server
Credit goes to Colin for the approach.
Change-Id: I7c74b9fb67f2975948653e671b522181574ef8fd
Reviewed-on: http://gerrit.ent.cloudera.com:8080/1341
Reviewed-by: Todd Lipcon <[email protected]>
Reviewed-by: Colin McCabe <[email protected]>
Tested-by: jenkins
|
C++
|
apache-2.0
|
helifu/kudu,andrwng/kudu,cloudera/kudu,EvilMcJerkface/kudu,InspurUSA/kudu,InspurUSA/kudu,andrwng/kudu,andrwng/kudu,InspurUSA/kudu,helifu/kudu,andrwng/kudu,EvilMcJerkface/kudu,cloudera/kudu,helifu/kudu,helifu/kudu,cloudera/kudu,helifu/kudu,cloudera/kudu,helifu/kudu,EvilMcJerkface/kudu,InspurUSA/kudu,InspurUSA/kudu,helifu/kudu,EvilMcJerkface/kudu,EvilMcJerkface/kudu,cloudera/kudu,helifu/kudu,cloudera/kudu,EvilMcJerkface/kudu,helifu/kudu,cloudera/kudu,andrwng/kudu,cloudera/kudu,InspurUSA/kudu,EvilMcJerkface/kudu,andrwng/kudu,EvilMcJerkface/kudu,EvilMcJerkface/kudu,InspurUSA/kudu,andrwng/kudu,andrwng/kudu,InspurUSA/kudu,andrwng/kudu,cloudera/kudu,InspurUSA/kudu
|
f6a79c07358337b94a093b0bd727d217a507d9a2
|
normalize.cpp
|
normalize.cpp
|
/* The MIT License
Copyright (c) 2013 Adrian Tan <[email protected]>
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
*/
#include "normalize.h"
namespace
{
class Igor : Program
{
public:
///////////
//options//
///////////
std::string input_vcf_file;
std::string output_vcf_file;
std::vector<GenomeInterval> intervals;
std::string ref_fasta_file;
///////
//i/o//
///////
BCFOrderedReader *odr;
BCFOrderedWriter *odw;
bcf1_t *v;
kstring_t s;
kstring_t new_alleles;
kstring_t old_alleles;
/////////
//stats//
/////////
uint32_t no_variants;
uint32_t no_lt; //# left trimmed
uint32_t no_lt_la; //# left trimmed and left aligned
uint32_t no_lt_rt; //# left trimmed and right trimmed
uint32_t no_la; //# left aligned
uint32_t no_rt; //# right trimmed
uint32_t no_multi_lt; //# left trimmed
uint32_t no_multi_lt_la; //# left trimmed and left aligned
uint32_t no_multi_lt_rt; //# left trimmed and right trimmed
uint32_t no_multi_la; //# left aligned
uint32_t no_multi_rt; //# right trimmed
/////////
//tools//
/////////
VariantManip *vm;
Igor(int argc, char **argv)
{
version = "0.5";
//////////////////////////
//options initialization//
//////////////////////////
try
{
std::string desc = "normalizes variants in a VCF file";
TCLAP::CmdLine cmd(desc, ' ', version);
VTOutput my; cmd.setOutput(&my);
TCLAP::ValueArg<std::string> arg_ref_fasta_file("r", "r", "reference sequence fasta file []", true, "", "str", cmd);
TCLAP::ValueArg<std::string> arg_intervals("i", "i", "intervals []", false, "", "str", cmd);
TCLAP::ValueArg<std::string> arg_interval_list("I", "I", "file containing list of intervals []", false, "", "file", cmd);
TCLAP::ValueArg<std::string> arg_output_vcf_file("o", "o", "output VCF file [-]", false, "-", "str", cmd);
TCLAP::UnlabeledValueArg<std::string> arg_input_vcf_file("<in.vcf>", "input VCF file", true, "","file", cmd);
cmd.parse(argc, argv);
input_vcf_file = arg_input_vcf_file.getValue();
output_vcf_file = arg_output_vcf_file.getValue();
parse_intervals(intervals, arg_interval_list.getValue(), arg_intervals.getValue());
ref_fasta_file = arg_ref_fasta_file.getValue();
}
catch (TCLAP::ArgException &e)
{
std::cerr << "error: " << e.error() << " for arg " << e.argId() << "\n";
abort();
}
};
void initialize()
{
//////////////////////
//i/o initialization//
//////////////////////
odr = new BCFOrderedReader(input_vcf_file, intervals);
odw = new BCFOrderedWriter(output_vcf_file, 100000);
odw->link_hdr(odr->hdr);
bcf_hdr_append(odw->hdr, "##INFO=<ID=OLD_VARIANT,Number=1,Type=String,Description=\"Original chr:pos:ref:alt encoding\">\n");
odw->write_hdr();
s = {0,0,0};
old_alleles = {0,0,0};
new_alleles = {0,0,0};
////////////////////////
//stats initialization//
////////////////////////
no_variants = 0;
no_lt = 0;
no_lt_la = 0;
no_lt_rt = 0;
no_la = 0;
no_rt = 0;
no_multi_lt = 0;
no_multi_lt_la = 0;
no_multi_lt_rt = 0;
no_multi_la = 0;
no_multi_rt = 0;
////////////////////////
//tools initialization//
////////////////////////
vm = new VariantManip(ref_fasta_file);
}
void normalize()
{
uint32_t left_aligned = 0;
uint32_t left_trimmed = 0;
uint32_t right_trimmed = 0;
int32_t ambiguous_variant_types = (VT_MNP | VT_INDEL | VT_CLUMPED);
v = odw->get_bcf1_from_pool();
Variant variant;
while (odr->read(v))
{
bcf_unpack(v, BCF_UN_INFO);
int32_t vtype = vm->classify_variant(odr->hdr, v, variant, false); //false argument to ensure no in situ left trimming
if (vtype & ambiguous_variant_types)
{
const char* chrom = odr->get_seqname(v);
uint32_t pos1 = bcf_get_pos1(v);
std::vector<std::string> alleles;
for (uint32_t i=0; i<bcf_get_n_allele(v); ++i)
{
alleles.push_back(std::string(bcf_get_alt(v, i)));
}
left_aligned = left_trimmed = right_trimmed = 0;
vm->left_align(alleles, pos1, chrom, left_aligned, right_trimmed);
vm->left_trim(alleles, pos1, left_trimmed);
if (left_trimmed || left_aligned || right_trimmed)
{
old_alleles.l = 0;
bcf_variant2string(odw->hdr, v, &old_alleles);
bcf_update_info_string(odw->hdr, v, "OLD_VARIANT", old_alleles.s);
bcf_set_pos1(v, pos1);
new_alleles.l=0;
for (uint32_t i=0; i<alleles.size(); ++i)
{
if (i) kputc(',', &new_alleles);
kputs(alleles[i].c_str(), &new_alleles);
}
bcf_update_alleles_str(odw->hdr, v, new_alleles.s);
if (bcf_get_n_allele(v)==2)
{
if (left_trimmed)
{
if (left_aligned)
{
++no_lt_la;
}
else if (right_trimmed)
{
++no_lt_rt;
}
else
{
++no_lt;
}
}
else
{
if (left_aligned)
{
++no_la;
}
else if (right_trimmed)
{
++no_rt;
}
}
}
else
{
if (left_trimmed)
{
if (left_aligned)
{
++no_multi_lt_la;
}
else if (right_trimmed)
{
++no_multi_lt_rt;
}
else
{
++no_multi_lt;
}
}
else
{
if (left_aligned)
{
++no_multi_la;
}
else if (right_trimmed)
{
++no_multi_rt;
}
}
}
}
}
++no_variants;
odw->write(v);
v = odw->get_bcf1_from_pool();
}
odr->close();
odw->close();
};
void print_options()
{
std::clog << "normalize v" << version << "\n";
std::clog << "\n";
std::clog << "options: input VCF file " << input_vcf_file << "\n";
std::clog << " [o] output VCF file " << output_vcf_file << "\n";
std::clog << " [r] reference FASTA file " << ref_fasta_file << "\n";
print_int_op(" [i] intervals ", intervals);
std::clog << "\n";
}
void print_stats()
{
std::clog << "\n";
std::clog << "stats: biallelic\n";
std::clog << " no. left trimmed : " << no_lt << "\n";
std::clog << " no. left trimmed and left aligned : " << no_lt_la << "\n";
std::clog << " no. left trimmed and right trimmed : " << no_lt_rt << "\n";
std::clog << " no. left aligned : " << no_la << "\n";
std::clog << " no. right trimmed : " << no_rt << "\n";
std::clog << "\n";
std::clog << " multiallelic\n";
std::clog << " no. left trimmed : " << no_multi_lt << "\n";
std::clog << " no. left trimmed and left aligned : " << no_multi_lt_la << "\n";
std::clog << " no. left trimmed and right trimmed : " << no_multi_lt_rt << "\n";
std::clog << " no. left aligned : " << no_multi_la << "\n";
std::clog << " no. right trimmed : " << no_multi_rt << "\n";
std::clog << "\n";
std::clog << " no. variants observed : " << no_variants << "\n";
std::clog << "\n";
};
~Igor() {};
private:
};
}
void normalize(int argc, char ** argv)
{
Igor igor(argc, argv);
igor.print_options();
igor.initialize();
igor.normalize();
igor.print_stats();
};
|
/* The MIT License
Copyright (c) 2013 Adrian Tan <[email protected]>
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
*/
#include "normalize.h"
namespace
{
class Igor : Program
{
public:
///////////
//options//
///////////
std::string input_vcf_file;
std::string output_vcf_file;
std::vector<GenomeInterval> intervals;
std::string ref_fasta_file;
///////
//i/o//
///////
BCFOrderedReader *odr;
BCFOrderedWriter *odw;
bcf1_t *v;
kstring_t s;
kstring_t new_alleles;
kstring_t old_alleles;
/////////
//stats//
/////////
uint32_t no_variants;
uint32_t no_lt; //# left trimmed
uint32_t no_lt_la; //# left trimmed and left aligned
uint32_t no_lt_rt; //# left trimmed and right trimmed
uint32_t no_la; //# left aligned
uint32_t no_rt; //# right trimmed
uint32_t no_multi_lt; //# left trimmed
uint32_t no_multi_lt_la; //# left trimmed and left aligned
uint32_t no_multi_lt_rt; //# left trimmed and right trimmed
uint32_t no_multi_la; //# left aligned
uint32_t no_multi_rt; //# right trimmed
/////////
//tools//
/////////
VariantManip *vm;
Igor(int argc, char **argv)
{
version = "0.5";
//////////////////////////
//options initialization//
//////////////////////////
try
{
std::string desc = "normalizes variants in a VCF file";
TCLAP::CmdLine cmd(desc, ' ', version);
VTOutput my; cmd.setOutput(&my);
TCLAP::ValueArg<std::string> arg_ref_fasta_file("r", "r", "reference sequence fasta file []", true, "", "str", cmd);
TCLAP::ValueArg<std::string> arg_intervals("i", "i", "intervals []", false, "", "str", cmd);
TCLAP::ValueArg<std::string> arg_interval_list("I", "I", "file containing list of intervals []", false, "", "file", cmd);
TCLAP::ValueArg<std::string> arg_output_vcf_file("o", "o", "output VCF file [-]", false, "-", "str", cmd);
TCLAP::UnlabeledValueArg<std::string> arg_input_vcf_file("<in.vcf>", "input VCF file", true, "","file", cmd);
cmd.parse(argc, argv);
input_vcf_file = arg_input_vcf_file.getValue();
output_vcf_file = arg_output_vcf_file.getValue();
parse_intervals(intervals, arg_interval_list.getValue(), arg_intervals.getValue());
ref_fasta_file = arg_ref_fasta_file.getValue();
}
catch (TCLAP::ArgException &e)
{
std::cerr << "error: " << e.error() << " for arg " << e.argId() << "\n";
abort();
}
};
void initialize()
{
//////////////////////
//i/o initialization//
//////////////////////
odr = new BCFOrderedReader(input_vcf_file, intervals);
odw = new BCFOrderedWriter(output_vcf_file, 100000);
odw->link_hdr(odr->hdr);
bcf_hdr_append(odw->hdr, "##INFO=<ID=OLD_VARIANT,Number=1,Type=String,Description=\"Original chr:pos:ref:alt encoding\">\n");
odw->write_hdr();
s = {0,0,0};
old_alleles = {0,0,0};
new_alleles = {0,0,0};
////////////////////////
//stats initialization//
////////////////////////
no_variants = 0;
no_lt = 0;
no_lt_la = 0;
no_lt_rt = 0;
no_la = 0;
no_rt = 0;
no_multi_lt = 0;
no_multi_lt_la = 0;
no_multi_lt_rt = 0;
no_multi_la = 0;
no_multi_rt = 0;
////////////////////////
//tools initialization//
////////////////////////
vm = new VariantManip(ref_fasta_file);
}
void normalize()
{
uint32_t left_aligned = 0;
uint32_t left_trimmed = 0;
uint32_t right_trimmed = 0;
int32_t ambiguous_variant_types = (VT_MNP | VT_INDEL | VT_CLUMPED);
v = odw->get_bcf1_from_pool();
Variant variant;
while (odr->read(v))
{
bcf_unpack(v, BCF_UN_INFO);
int32_t vtype = vm->classify_variant(odr->hdr, v, variant, false); //false argument to ensure no in situ left trimming
if (vtype & ambiguous_variant_types)
{
const char* chrom = odr->get_seqname(v);
uint32_t pos1 = bcf_get_pos1(v);
std::vector<std::string> alleles;
for (uint32_t i=0; i<bcf_get_n_allele(v); ++i)
{
char *s = bcf_get_alt(v, i);
while (*s)
{
*s = toupper(*s);
++s;
}
alleles.push_back(std::string(bcf_get_alt(v, i)));
}
left_aligned = left_trimmed = right_trimmed = 0;
vm->left_align(alleles, pos1, chrom, left_aligned, right_trimmed);
vm->left_trim(alleles, pos1, left_trimmed);
if (left_trimmed || left_aligned || right_trimmed)
{
old_alleles.l = 0;
bcf_variant2string(odw->hdr, v, &old_alleles);
bcf_update_info_string(odw->hdr, v, "OLD_VARIANT", old_alleles.s);
bcf_set_pos1(v, pos1);
new_alleles.l=0;
for (uint32_t i=0; i<alleles.size(); ++i)
{
if (i) kputc(',', &new_alleles);
kputs(alleles[i].c_str(), &new_alleles);
}
bcf_update_alleles_str(odw->hdr, v, new_alleles.s);
if (bcf_get_n_allele(v)==2)
{
if (left_trimmed)
{
if (left_aligned)
{
++no_lt_la;
}
else if (right_trimmed)
{
++no_lt_rt;
}
else
{
++no_lt;
}
}
else
{
if (left_aligned)
{
++no_la;
}
else if (right_trimmed)
{
++no_rt;
}
}
}
else
{
if (left_trimmed)
{
if (left_aligned)
{
++no_multi_lt_la;
}
else if (right_trimmed)
{
++no_multi_lt_rt;
}
else
{
++no_multi_lt;
}
}
else
{
if (left_aligned)
{
++no_multi_la;
}
else if (right_trimmed)
{
++no_multi_rt;
}
}
}
}
}
++no_variants;
odw->write(v);
v = odw->get_bcf1_from_pool();
}
odr->close();
odw->close();
};
void print_options()
{
std::clog << "normalize v" << version << "\n";
std::clog << "\n";
std::clog << "options: input VCF file " << input_vcf_file << "\n";
std::clog << " [o] output VCF file " << output_vcf_file << "\n";
std::clog << " [r] reference FASTA file " << ref_fasta_file << "\n";
print_int_op(" [i] intervals ", intervals);
std::clog << "\n";
}
void print_stats()
{
std::clog << "\n";
std::clog << "stats: biallelic\n";
std::clog << " no. left trimmed : " << no_lt << "\n";
std::clog << " no. left trimmed and left aligned : " << no_lt_la << "\n";
std::clog << " no. left trimmed and right trimmed : " << no_lt_rt << "\n";
std::clog << " no. left aligned : " << no_la << "\n";
std::clog << " no. right trimmed : " << no_rt << "\n";
std::clog << "\n";
std::clog << " multiallelic\n";
std::clog << " no. left trimmed : " << no_multi_lt << "\n";
std::clog << " no. left trimmed and left aligned : " << no_multi_lt_la << "\n";
std::clog << " no. left trimmed and right trimmed : " << no_multi_lt_rt << "\n";
std::clog << " no. left aligned : " << no_multi_la << "\n";
std::clog << " no. right trimmed : " << no_multi_rt << "\n";
std::clog << "\n";
std::clog << " no. variants observed : " << no_variants << "\n";
std::clog << "\n";
};
~Igor() {};
private:
};
}
void normalize(int argc, char ** argv)
{
Igor igor(argc, argv);
igor.print_options();
igor.initialize();
igor.normalize();
igor.print_stats();
};
|
make all alleles upper case before normalizing
|
make all alleles upper case before normalizing
|
C++
|
mit
|
atks/vt,gkno/vt,gkno/vt,gkno/vt,atks/vt,atks/vt,atks/vt,gkno/vt
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.