hexsha stringlengths 40 40 | size int64 19 11.4M | ext stringclasses 13 values | lang stringclasses 1 value | max_stars_repo_path stringlengths 3 270 | max_stars_repo_name stringlengths 5 110 | max_stars_repo_head_hexsha stringlengths 40 40 | max_stars_repo_licenses listlengths 1 9 | max_stars_count float64 1 191k ⌀ | max_stars_repo_stars_event_min_datetime stringlengths 24 24 ⌀ | max_stars_repo_stars_event_max_datetime stringlengths 24 24 ⌀ | max_issues_repo_path stringlengths 3 270 | max_issues_repo_name stringlengths 5 116 | max_issues_repo_head_hexsha stringlengths 40 78 | max_issues_repo_licenses listlengths 1 9 | max_issues_count float64 1 67k ⌀ | max_issues_repo_issues_event_min_datetime stringlengths 24 24 ⌀ | max_issues_repo_issues_event_max_datetime stringlengths 24 24 ⌀ | max_forks_repo_path stringlengths 3 270 | max_forks_repo_name stringlengths 5 116 | max_forks_repo_head_hexsha stringlengths 40 78 | max_forks_repo_licenses listlengths 1 9 | max_forks_count float64 1 105k ⌀ | max_forks_repo_forks_event_min_datetime stringlengths 24 24 ⌀ | max_forks_repo_forks_event_max_datetime stringlengths 24 24 ⌀ | content stringlengths 19 11.4M | avg_line_length float64 1.93 229k | max_line_length int64 12 688k | alphanum_fraction float64 0.07 0.99 | matches listlengths 1 10 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
17612e2de02e4da5da1925f9169a645e1ca9f97e | 18,272 | cpp | C++ | cpp/ndnrtcTOP/ndnrtcTOP_base.cpp | luckiday/ndnrtc | ea224ce8d9f01d164925448c7424cf0f0caa4b07 | [
"BSD-2-Clause"
] | null | null | null | cpp/ndnrtcTOP/ndnrtcTOP_base.cpp | luckiday/ndnrtc | ea224ce8d9f01d164925448c7424cf0f0caa4b07 | [
"BSD-2-Clause"
] | null | null | null | cpp/ndnrtcTOP/ndnrtcTOP_base.cpp | luckiday/ndnrtc | ea224ce8d9f01d164925448c7424cf0f0caa4b07 | [
"BSD-2-Clause"
] | null | null | null | //
// ndnrtcTOP_base.cpp
// ndnrtcTOP
//
// Created by Peter Gusev on 2/16/18.
// Copyright © 2018 UCLA REMAP. All rights reserved.
//
#include "ndnrtcTOP_base.hpp"
#include <stdio.h>
#include <map>
#include <iostream>
#include <ndn-cpp/interest.hpp>
#include <ndn-cpp/face.hpp>
#include <ndn-cpp/security/key-chain.hpp>
#include <ndn-cpp/util/memory-content-cache.hpp>
#include <ndnrtc/helpers/face-processor.hpp>
#include <ndnrtc/helpers/key-chain-manager.hpp>
#include <ndnrtc/c-wrapper.h> // for ndnrtc_getVersion()
#include <ndnrtc/statistics.hpp>
#include <ndnrtc/stream.hpp>
#include "foundation-helpers.h"
using namespace std;
//using namespace std::placeholders;
using namespace ndnrtc;
using namespace ndnrtc::helpers;
using namespace ndnlog::new_api;
namespace ndn {
class Face;
class Interest;
}
#define PAR_NFD_HOST "Nfdhost"
#define PAR_USE_MACOS_KEYCHAIN "Usemacoskeychain"
#define PAR_INIT "Init"
#define PAR_LOGFILE "Logfile"
#define PAR_LOGLEVEL "Loglevel"
//******************************************************************************
/**
* This enum identifies output DAT's different fields
* The output DAT is a table that contains two
* columns: name (identified by this enum) and value
* (either float or string)
*/
enum class InfoDatIndex {
LibVersion,
Prefix,
NdnRtcPrefix,
SignIdentity,
SignCertificate,
InstanceIdentity,
InstanceCertificate
};
/**
* This maps output DAT's field onto their textual representation
* (table caption)
*/
static std::map<InfoDatIndex, std::string> RowNames = {
{ InfoDatIndex::LibVersion, "Library Version" },
{ InfoDatIndex::Prefix, "Prefix" },
{ InfoDatIndex::NdnRtcPrefix, "NDNRTC Prefix" },
{ InfoDatIndex::SignIdentity, "Sign Identity" },
{ InfoDatIndex::SignCertificate, "Sign Certificate" },
{ InfoDatIndex::InstanceIdentity, "Instance Identity" },
{ InfoDatIndex::InstanceCertificate, "Instance Certificate" }
};
const std::string ndnrtcTOPbase::SigningIdentityName = "/touchdesigner";
const std::string ndnrtcTOPbase::NdnRtcStreamName = "s";
const std::string ndnrtcTOPbase::NdnRtcTrheadName = "t";
static set<string> ReinitParams({PAR_USE_MACOS_KEYCHAIN, PAR_NFD_HOST});
ndnrtcTOPbase::ndnrtcTOPbase(const OP_NodeInfo* info) : nodeInfo_(info),
errorString_(""), warningString_(""),
statStorage_(nullptr),
stream_(nullptr),
opName_(extractOpName(info->opPath)),
reinitParams_(ReinitParams),
prefixRegistered_(0)
{
description_ = "ndnrtcTOP_base";
Logger::initAsyncLogging();
logger_ = boost::make_shared<Logger>(ndnlog::NdnLoggerDetailLevelDefault,
boost::make_shared<CallbackSink>(bind(&ndnrtcTOPbase::logSink, this, _1)));
}
ndnrtcTOPbase::~ndnrtcTOPbase()
{
// making sure processing stopped
if (faceProcessor_)
faceProcessor_->stop();
if (statStorage_)
delete statStorage_;
}
void
ndnrtcTOPbase::getWarningString(OP_String *warning, void* reserved1)
{
if (warningString_.size())
warning->setString(warningString_.c_str());
}
void
ndnrtcTOPbase::getErrorString(OP_String *error, void* reserved1)
{
if (errorString_.size())
error->setString(errorString_.c_str());
}
void
ndnrtcTOPbase::execute(TOP_OutputFormatSpecs *outputFormat,
const OP_Inputs *inputs,
TOP_Context *context,
void* reserved1)
{
bool reinit = false;
std::string opName = extractOpName(nodeInfo_->opPath);
if (opName_ != opName)
{
opName_ = opName;
reinit = true;
}
set<string> updatedParams = checkInputs(outputFormat, inputs, context);
// check if any of NDN's params were update so that we need to reinit NDN...
if (ndnrtcTOPbase::intersect(updatedParams, ReinitParams).size() > 0)
init();
// check whether stream needs to be re-initialized
if (ndnrtcTOPbase::intersect(updatedParams, reinitParams_).size() > 0)
initStream();
{
try {
while (executeQueue_.size())
{
executeQueue_.front()(outputFormat, inputs, context);
executeQueue_.pop();
}
} catch (exception& e) {
executeQueue_.pop(); // just throw this naughty block away
logSink((string(string("Exception caught: ")+e.what())).c_str());
errorString_ = e.what();
}
}
}
bool
ndnrtcTOPbase::getInfoDATSize(OP_InfoDATSize* infoSize, void *reserved1)
{
infoSize->rows = (int)RowNames.size();
infoSize->cols = 2;
infoSize->byColumn = false;
return true;
}
void
ndnrtcTOPbase::getInfoDATEntries(int32_t index,
int32_t nEntries,
OP_InfoDATEntries* entries,
void *reserved1)
{
// It's safe to use static buffers here because Touch will make it's own
// copies of the strings immediately after this call returns
// (so the buffers can be reuse for each column/row)
static char tempBuffer1[4096];
static char tempBuffer2[4096];
memset(tempBuffer1, 0, 4096);
memset(tempBuffer2, 0, 4096);
InfoDatIndex idx = (InfoDatIndex)index;
if (RowNames.find(idx) != RowNames.end())
{
strcpy(tempBuffer1, RowNames[idx].c_str());
switch (idx) {
case InfoDatIndex::LibVersion:
{
const char *ndnrtcLibVersion = ndnrtc_getVersion();
snprintf(tempBuffer2, strlen(ndnrtcLibVersion), "%s", ndnrtcLibVersion);
}
break;
case InfoDatIndex::NdnRtcPrefix:
{
if (stream_)
strcpy(tempBuffer2, stream_->getPrefix().c_str());
}
break;
case InfoDatIndex::Prefix:
{
if (stream_)
strcpy(tempBuffer2, stream_->getBasePrefix().c_str());
}
break;
case InfoDatIndex::SignIdentity:
{
std::string identity(keyChainManager_->defaultKeyChain()->getDefaultIdentity().toUri().c_str());
strcpy(tempBuffer2, identity.c_str());
}
break;
case InfoDatIndex::SignCertificate:
{
strcpy(tempBuffer2, keyChainManager_->signingIdentityCertificate()->getName().toUri().c_str());
}
break;
case InfoDatIndex::InstanceIdentity:
{
strcpy(tempBuffer2, keyChainManager_->instancePrefix().c_str());
}
break;
case InfoDatIndex::InstanceCertificate:
{
strcpy(tempBuffer2, keyChainManager_->instanceCertificate()->getName().toUri().c_str());
}
break;
default:
break;
}
entries->values[0]->setString(tempBuffer1);
entries->values[1]->setString(tempBuffer2);
}
}
void
ndnrtcTOPbase::setupParameters(OP_ParameterManager* manager, void *reserved1)
{
{
OP_StringParameter nfdHost(PAR_NFD_HOST);
OP_NumericParameter useMacOsKeyChain(PAR_USE_MACOS_KEYCHAIN);
nfdHost.label = "NFD Host";
nfdHost.defaultValue = "localhost";
nfdHost.page = "Lib Config";
useMacOsKeyChain.label = "Use System KeyChain";
useMacOsKeyChain.defaultValues[0] = 0;
useMacOsKeyChain.page = "Lib Config";
// TODO: setup list of system's identities
OP_ParAppendResult res = manager->appendString(nfdHost);
assert(res == OP_ParAppendResult::Success);
res = manager->appendToggle(useMacOsKeyChain);
assert(res == OP_ParAppendResult::Success);
}
{
OP_NumericParameter np;
np.name = PAR_INIT;
np.label = "Init";
np.page = "Lib Config";
OP_ParAppendResult res = manager->appendPulse(np);
assert(res == OP_ParAppendResult::Success);
}
{
OP_StringParameter sp;
sp.name = PAR_LOGFILE;
sp.label = "Log File";
sp.page = "Advanced";
logFile_ =("/tmp/"+this->opName_+".log");
sp.defaultValue = logFile_.c_str();
OP_ParAppendResult res = manager->appendString(sp);
assert(res == OP_ParAppendResult::Success);
#define NLEVELS 4
static const char *logLevels[NLEVELS] = {"Info", "Debug", "All", "None"};
sp.name = PAR_LOGLEVEL;
sp.label = "Log Level";
res = manager->appendMenu(sp, NLEVELS, logLevels, logLevels);
assert(res == OP_ParAppendResult::Success);
}
}
void
ndnrtcTOPbase::pulsePressed(const char* name, void *reserved1)
{
if (!strcmp(name, "Init"))
{
init();
initStream();
}
}
set<string>
ndnrtcTOPbase::checkInputs(TOP_OutputFormatSpecs *, const OP_Inputs *inputs, TOP_Context *)
{
assert(params_);
set<string> updatedParams;
// enable menu
// inputs->enablePar(PAR_SIGNING_IDENTITY, !useMacOsKeyChain);
if (params_->useMacOsKeyChain_ != inputs->getParInt(PAR_USE_MACOS_KEYCHAIN))
{
updatedParams.insert(PAR_USE_MACOS_KEYCHAIN);
params_->useMacOsKeyChain_ = inputs->getParInt(PAR_USE_MACOS_KEYCHAIN);
}
if (params_->nfdHost_ != string(inputs->getParString(PAR_NFD_HOST)))
{
updatedParams.insert(PAR_NFD_HOST);
params_->nfdHost_ = string(inputs->getParString(PAR_NFD_HOST));
}
string logFile = inputs->getParString(PAR_LOGFILE);
string logLevel = inputs->getParString(PAR_LOGLEVEL);
checkUpdateLogger(logFile, logLevel);
return updatedParams;
}
set<string>
ndnrtcTOPbase::intersect(const std::set<std::string> &a, const std::set<std::string> &b)
{
vector<string> x;
set_intersection(a.begin(), a.end(), b.begin(), b.end(), back_inserter(x));
return set<string>(make_move_iterator(x.begin()), make_move_iterator(x.end()));
}
//******************************************************************************
void
ndnrtcTOPbase::init()
{
if (faceProcessor_)
faceProcessor_->stop();
stream_.reset();
keyChainManager_.reset();
faceProcessor_.reset();
queue<ExecuteCallback>().swap(executeQueue_); // is it cool to clear the queue?
executeQueue_.push(bind(&ndnrtcTOPbase::initFace, this, _1, _2, _3));
executeQueue_.push(bind(&ndnrtcTOPbase::initKeyChainManager, this, _1, _2, _3));
}
void
ndnrtcTOPbase::initFace(TOP_OutputFormatSpecs* outputFormat,
const OP_Inputs* inputs,
TOP_Context *context)
{
if (FaceProcessor::checkNfdConnection())
{
std::string hostname(inputs->getParString(PAR_NFD_HOST));
faceProcessor_ = boost::make_shared<FaceProcessor>(hostname);
faceProcessor_->start();
if (!faceProcessor_->isProcessing())
{
errorString_ = "Failed to start face processor";
faceProcessor_.reset();
return;
}
LogInfoC << "initialized Face Processor" << std::endl;
}
else
{
errorString_ = "Can't connect to NFD";
}
}
void
ndnrtcTOPbase::initKeyChainManager(TOP_OutputFormatSpecs* outputFormat,
const OP_Inputs* inputs,
TOP_Context *context)
{
if (!faceProcessor_)
return;
std::string signingIdentity(ndnrtcTOPbase::SigningIdentityName);
std::string instanceName(opName_);
bool useMacOsKeyChain = inputs->getParInt(PAR_USE_MACOS_KEYCHAIN);
string policyFilePath = string(get_resources_path())+"/policy.conf";
string keyChainPath = string(get_resources_path())+"/keychain";
try
{
errorString_ = "";
boost::shared_ptr<ndn::KeyChain> kc = KeyChainManager::createKeyChain(keyChainPath);
keyChainManager_ = boost::make_shared<KeyChainManager>(faceProcessor_->getFace(),
(useMacOsKeyChain ? KeyChainManager::createKeyChain("") : KeyChainManager::createKeyChain(keyChainPath)),
(useMacOsKeyChain ? signingIdentity : ndnrtcTOPbase::SigningIdentityName),
instanceName,
policyFilePath,
24*3600,
logger_);
if (!useMacOsKeyChain)
{
// TODO: enable identities menu
// inputs->enablePar(PAR_SIGNING_IDENTITY, false);
}
// LogInfoC << "command signing info: " << keyChainManager_->instanceKeyChain()->getDefaultCertificateName() << endl;
// faceProcessor_->getFace()->setCommandSigningInfo(*keyChainManager_->instanceKeyChain(),
// keyChainManager_->instanceKeyChain()->getDefaultCertificateName());
}
catch(std::exception &e)
{
errorString_ = string("Error initializing library: ") + e.what();
}
}
void
ndnrtcTOPbase::registerPrefix(TOP_OutputFormatSpecs* outputFormat,
const OP_Inputs* inputs,
TOP_Context *context)
{
if (!(faceProcessor_ && keyChainManager_))
return;
ndn::Name prefix(readBasePrefix(inputs));
prefixRegistered_ = 0;
faceProcessor_->registerPrefix(prefix,
[this](const boost::shared_ptr<const ndn::Name>& prefix,
const boost::shared_ptr<const ndn::Interest>& interest,
ndn::Face& face, uint64_t interestFilterId,
const boost::shared_ptr<const ndn::InterestFilter>& filter){
LogDebugC << "received interest " << interest->getName() << endl;
},
[this](const boost::shared_ptr<const ndn::Name>& prefix){
LogErrorC << "failed to register prefix " << prefix->toUri() << endl;
errorString_ = "Prefix registration failure: " + prefix->toUri();
},
[this](const boost::shared_ptr<const ndn::Name>& prefix,
uint64_t registeredPrefixId){
LogInfoC << "registered prefix " << *prefix << endl;
prefixRegistered_ = 1;
});
}
std::string
ndnrtcTOPbase::extractOpName(std::string opPath) const
{
size_t last = 0;
size_t next = 0;
while ((next = opPath.find("/", last)) != string::npos)
last = next + 1;
return opPath.substr(last);
}
void
ndnrtcTOPbase::readStreamStats()
{
if (stream_)
*statStorage_ = stream_->getStatistics();
}
string ndnrtcTOPbase::readBasePrefix(const OP_Inputs* inputs) const
{
stringstream basePrefix;
basePrefix << ndnrtcTOPbase::SigningIdentityName << "/" << opName_;
return basePrefix.str();
}
void
ndnrtcTOPbase::logSink(const char *msg)
{
cout << "[" << opName_ << "] " << msg;
}
void
ndnrtcTOPbase::flipFrame(int width, int height, uint8_t* buf,
bool flipH, bool flipV, bool convertToArgb)
{
// this code flips image vertically (but can do it horizontally too) and
// converts RGBA to ARGB (can be disabled too)
// all this is done in-place and in one pass without additional copying
int format = 4; // 4 bytes per pixel - ARGB32
int stride = width * format;
int yStop = (flipV) ? height / 2 : height;
int xStop = (flipH && !(flipH && flipV)) ? width / 2 : width;
for (int y = 0; y < yStop; ++y)
for (int x = 0; x < xStop; ++x)
{
int xSwap = (flipH ? width - 1 - x : x);
int ySwap = (flipV ? height - 1 - y : y);
// swap ARGB pixels
int p1Idx = y * stride + x * format;
int p2Idx = ySwap * stride + xSwap * format;
if (convertToArgb)
{
uint32_t temp = *(uint32_t*)(buf + p1Idx);
*(uint32_t*)(buf + p1Idx) = (*(uint32_t*)(buf + p2Idx)) >> 24 | (*(uint32_t*)(buf + p2Idx)) << 8;
*(uint32_t*)(buf + p2Idx) = temp >> 24 | temp << 8;
}
else
{
uint32_t temp = *(uint32_t*)(buf + p1Idx);
*(uint32_t*)(buf + p1Idx) = *(uint32_t*)(buf + p2Idx);
*(uint32_t*)(buf + p2Idx) = temp;
}
}
}
void
ndnrtcTOPbase::checkUpdateLogger(std::string logFile, std::string logLevel)
{
if ((!streamLogger_ || logFile_ != logFile) && stream_)
{
logFile_ = logFile;
boost::shared_ptr<ndnlog::new_api::Logger> logger = boost::make_shared<ndnlog::new_api::Logger>(ndnlog::NdnLoggerDetailLevelDefault, logFile_);
stream_->setLogger(logger);
streamLogger_ = logger;
}
static map<string, ndnlog::NdnLoggerDetailLevel> logLevels = {
{ "None", ndnlog::NdnLoggerDetailLevelNone },
{ "Info", ndnlog::NdnLoggerDetailLevelDefault },
{ "Debug", ndnlog::NdnLoggerDetailLevelDebug },
{ "All", ndnlog::NdnLoggerDetailLevelAll }
};
if (logLevels.find(logLevel) != logLevels.end())
{
ndnlog::NdnLoggerDetailLevel lvl = logLevels[logLevel];
if (streamLogger_ && streamLogger_->getLogLevel() != lvl)
streamLogger_->setLogLevel(lvl);
}
}
| 33.161525 | 168 | 0.571968 | [
"vector"
] |
1764961d8e52e055bc7279389897c4af6fde277b | 13,813 | cpp | C++ | SofaKernel/modules/SofaBaseCollision/CubeModel.cpp | sofa-framework/issofa | 94855f488465bc3ed41223cbde987581dfca5389 | [
"OML"
] | null | null | null | SofaKernel/modules/SofaBaseCollision/CubeModel.cpp | sofa-framework/issofa | 94855f488465bc3ed41223cbde987581dfca5389 | [
"OML"
] | null | null | null | SofaKernel/modules/SofaBaseCollision/CubeModel.cpp | sofa-framework/issofa | 94855f488465bc3ed41223cbde987581dfca5389 | [
"OML"
] | null | null | null | /******************************************************************************
* SOFA, Simulation Open-Framework Architecture, development version *
* (c) 2006-2017 INRIA, USTL, UJF, CNRS, MGH *
* *
* This program is free software; you can redistribute it and/or modify it *
* under the terms of the GNU Lesser General Public License as published by *
* the Free Software Foundation; either version 2.1 of the License, or (at *
* your option) any later version. *
* *
* This program is distributed in the hope that it will be useful, but WITHOUT *
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or *
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License *
* for more details. *
* *
* You should have received a copy of the GNU Lesser General Public License *
* along with this program. If not, see <http://www.gnu.org/licenses/>. *
*******************************************************************************
* Authors: The SOFA Team and external contributors (see Authors.txt) *
* *
* Contact information: contact@sofa-framework.org *
******************************************************************************/
#include <SofaBaseCollision/CubeModel.h>
#include <sofa/core/visual/VisualParams.h>
#include <sofa/simulation/Simulation.h>
#include <sofa/core/ObjectFactory.h>
#include <algorithm>
#include <math.h>
namespace sofa
{
namespace component
{
namespace collision
{
SOFA_DECL_CLASS(Cube)
using namespace sofa::defaulttype;
int CubeModelClass = core::RegisterObject("Collision model representing a cube")
.add< CubeModel >()
.addAlias("Cube")
;
CubeModel::CubeModel()
{
enum_type = AABB_TYPE;
}
void CubeModel::resize(int size)
{
int size0 = this->size;
if (size == size0) return;
// reset parent
CollisionModel* parent = getPrevious();
while(parent != NULL)
{
parent->resize(0);
parent = parent->getPrevious();
}
this->core::CollisionModel::resize(size);
this->elems.resize(size);
this->parentOf.resize(size);
// set additional indices
for (int i=size0; i<size; ++i)
{
this->elems[i].children.first=core::CollisionElementIterator(getNext(), i);
this->elems[i].children.second=core::CollisionElementIterator(getNext(), i+1);
this->parentOf[i] = i;
}
}
void CubeModel::setParentOf(int childIndex, const Vector3& min, const Vector3& max)
{
int i = parentOf[childIndex];
elems[i].minBBox = min;
elems[i].maxBBox = max;
}
void CubeModel::setLeafCube(int cubeIndex, int childIndex)
{
parentOf[childIndex] = cubeIndex;
this->elems[cubeIndex].children.first=core::CollisionElementIterator(getNext(), childIndex);
this->elems[cubeIndex].children.second=core::CollisionElementIterator(getNext(), childIndex+1);
//elems[cubeIndex].minBBox = min;
//elems[cubeIndex].maxBBox = max;
}
void CubeModel::setLeafCube(int cubeIndex, std::pair<core::CollisionElementIterator,core::CollisionElementIterator> children, const Vector3& min, const Vector3& max)
{
elems[cubeIndex].minBBox = min;
elems[cubeIndex].maxBBox = max;
elems[cubeIndex].children = children;
}
int CubeModel::addCube(Cube subcellsBegin, Cube subcellsEnd)
{
int i = size;
this->core::CollisionModel::resize(size+1);
elems.resize(size+1);
//elems[i].subcells = std::make_pair(subcellsBegin, subcellsEnd);
elems[i].subcells.first = subcellsBegin;
elems[i].subcells.second = subcellsEnd;
elems[i].children.first = core::CollisionElementIterator();
elems[i].children.second = core::CollisionElementIterator();
updateCube(i);
return i;
}
void CubeModel::updateCube(int index)
{
const std::pair<Cube,Cube>& subcells = elems[index].subcells;
if (subcells.first != subcells.second)
{
Cube c = subcells.first;
Vector3 minBBox = c.minVect();
Vector3 maxBBox = c.maxVect();
++c;
while(c != subcells.second)
{
const Vector3& cmin = c.minVect();
const Vector3& cmax = c.maxVect();
for (int j=0; j<3; j++)
{
if (cmax[j] > maxBBox[j]) maxBBox[j] = cmax[j];
if (cmin[j] < minBBox[j]) minBBox[j] = cmin[j];
}
++c;
}
elems[index].minBBox = minBBox;
elems[index].maxBBox = maxBBox;
}
}
void CubeModel::updateCubes()
{
for (int i=0; i<size; i++)
updateCube(i);
}
void CubeModel::draw(const core::visual::VisualParams* vparams)
{
if (!isActive() || !((getNext()==NULL)?vparams->displayFlags().getShowCollisionModels():vparams->displayFlags().getShowBoundingCollisionModels())) return;
int level=0;
CollisionModel* m = getPrevious();
float color = 1.0f;
while (m!=NULL)
{
m = m->getPrevious();
++level;
color *= 0.5f;
}
Vec<4,float> c;
if (isSimulated())
c=Vec<4,float>(1.0f, 1.0f, 1.0f, color);
else
c=Vec<4,float>(1.0f, 1.0f, 1.0f, color);
std::vector< Vector3 > points;
for (int i=0; i<size; i++)
{
const Vector3& vmin = elems[i].minBBox;
const Vector3& vmax = elems[i].maxBBox;
points.push_back(Vector3(vmin[0], vmin[1], vmin[2]));
points.push_back(Vector3(vmin[0], vmin[1], vmax[2]));
points.push_back(Vector3(vmin[0], vmax[1], vmin[2]));
points.push_back(Vector3(vmin[0], vmax[1], vmax[2]));
points.push_back(Vector3(vmax[0], vmin[1], vmin[2]));
points.push_back(Vector3(vmax[0], vmin[1], vmax[2]));
points.push_back(Vector3(vmax[0], vmax[1], vmin[2]));
points.push_back(Vector3(vmax[0], vmax[1], vmax[2]));
points.push_back(Vector3(vmin[0], vmin[1], vmin[2]));
points.push_back(Vector3(vmin[0], vmax[1], vmin[2]));
points.push_back(Vector3(vmin[0], vmin[1], vmax[2]));
points.push_back(Vector3(vmin[0], vmax[1], vmax[2]));
points.push_back(Vector3(vmax[0], vmin[1], vmin[2]));
points.push_back(Vector3(vmax[0], vmax[1], vmin[2]));
points.push_back(Vector3(vmax[0], vmin[1], vmax[2]));
points.push_back(Vector3(vmax[0], vmax[1], vmax[2]));
points.push_back(Vector3(vmin[0], vmin[1], vmin[2]));
points.push_back(Vector3(vmax[0], vmin[1], vmin[2]));
points.push_back(Vector3(vmin[0], vmax[1], vmin[2]));
points.push_back(Vector3(vmax[0], vmax[1], vmin[2]));
points.push_back(Vector3(vmin[0], vmin[1], vmax[2]));
points.push_back(Vector3(vmax[0], vmin[1], vmax[2]));
points.push_back(Vector3(vmin[0], vmax[1], vmax[2]));
points.push_back(Vector3(vmax[0], vmax[1], vmax[2]));
}
vparams->drawTool()->drawLines(points, 1, Vec<4,float>(c));
if (getPrevious()!=NULL)
getPrevious()->draw(vparams);
}
std::pair<core::CollisionElementIterator,core::CollisionElementIterator> CubeModel::getInternalChildren(int index) const
{
return elems[index].subcells;
}
std::pair<core::CollisionElementIterator,core::CollisionElementIterator> CubeModel::getExternalChildren(int index) const
{
return elems[index].children;
/*
core::CollisionElementIterator i1 = elems[index].leaf;
if (!i1.valid())
{
return std::make_pair(core::CollisionElementIterator(),core::CollisionElementIterator());
}
else
{
core::CollisionElementIterator i2 = i1; ++i2;
return std::make_pair(i1,i2);
}
*/
}
bool CubeModel::isLeaf( int index ) const
{
return elems[index].children.first.valid();
}
void CubeModel::computeBoundingTree(int maxDepth)
{
// if(maxDepth <= 0)
// return;
//sout << ">CubeModel::computeBoundingTree("<<maxDepth<<")"<<sendl;
std::list<CubeModel*> levels;
levels.push_front(createPrevious<CubeModel>());
for (int i=0; i<maxDepth; i++)
levels.push_front(levels.front()->createPrevious<CubeModel>());
CubeModel* root = levels.front();
//if (isStatic() && root->getPrevious() == NULL && !root->empty()) return; // No need to recompute BBox if immobile
if (root->empty() || root->getPrevious() != NULL)
{
// Tree must be reconstructed
//sout << "Building Tree with depth "<<maxDepth<<" from "<<size<<" elements."<<sendl;
// First remove extra levels
while(root->getPrevious()!=NULL)
{
core::CollisionModel::SPtr m = root->getPrevious();
root->setPrevious(m->getPrevious());
if (m->getMaster()) m->getMaster()->removeSlave(m);
//delete m;
m.reset();
}
// Then clear all existing levels
{
for (std::list<CubeModel*>::iterator it = levels.begin(); it != levels.end(); ++it)
(*it)->resize(0);
}
// Then build root cell
//sout << "CubeModel: add root cube"<<sendl;
root->addCube(Cube(this,0),Cube(this,size));
// Construct tree by splitting cells along their biggest dimension
std::list<CubeModel*>::iterator it = levels.begin();
CubeModel* level = *it;
++it;
int lvl = 0;
while(it != levels.end())
{
//sout << "CubeModel: split level "<<lvl<<sendl;
CubeModel* clevel = *it;
clevel->elems.reserve(level->size*2);
for(Cube cell = Cube(level->begin()); level->end() != cell; ++cell)
{
const std::pair<Cube,Cube>& subcells = cell.subcells();
int ncells = subcells.second.getIndex() - subcells.first.getIndex();
//sout << "CubeModel: level "<<lvl<<" cell "<<cell.getIndex()<<": current subcells "<<subcells.first.getIndex() << " - "<<subcells.second.getIndex()<<sendl;
if (ncells > 4)
{
// Only split cells with more than 4 childs
// Find the biggest dimension
int splitAxis;
Vector3 l = cell.maxVect()-cell.minVect();
int middle = subcells.first.getIndex()+(ncells+1)/2;
if(l[0]>l[1])
if (l[0]>l[2])
splitAxis = 0;
else
splitAxis = 2;
else if (l[1]>l[2])
splitAxis = 1;
else
splitAxis = 2;
// Separate cells on each side of the median cell
#if defined(__GNUC__) && (__GNUC__ == 4)
// && (__GNUC_MINOR__ == 1) && (__GNUC_PATCHLEVEL__ == 1)
// there is apparently a bug in std::sort with GCC 4.x
if (splitAxis == 0)
qsort(&(elems[subcells.first.getIndex()]), subcells.second.getIndex()-subcells.first.getIndex(), sizeof(elems[0]), CubeSortPredicate::sortCube<0>);
else if (splitAxis == 1)
qsort(&(elems[subcells.first.getIndex()]), subcells.second.getIndex()-subcells.first.getIndex(), sizeof(elems[0]), CubeSortPredicate::sortCube<1>);
else
qsort(&(elems[subcells.first.getIndex()]), subcells.second.getIndex()-subcells.first.getIndex(), sizeof(elems[0]), CubeSortPredicate::sortCube<2>);
#else
CubeSortPredicate sortpred(splitAxis);
//std::nth_element(elems.begin()+subcells.first.getIndex(),elems.begin()+middle,elems.begin()+subcells.second.getIndex(), sortpred);
std::sort(elems.begin()+subcells.first.getIndex(),elems.begin()+subcells.second.getIndex(), sortpred);
#endif
// Create the two new subcells
Cube cmiddle(this, middle);
int c1 = clevel->addCube(subcells.first, cmiddle);
int c2 = clevel->addCube(cmiddle, subcells.second);
//sout << "L"<<lvl<<" cell "<<cell.getIndex()<<" split along "<<(splitAxis==0?'X':splitAxis==1?'Y':'Z')<<" in cell "<<c1<<" size "<<middle-subcells.first.getIndex()<<" and cell "<<c2<<" size "<<subcells.second.getIndex()-middle<<"."<<sendl;
//level->elems[cell.getIndex()].subcells = std::make_pair(Cube(clevel,c1),Cube(clevel,c2+1));
level->elems[cell.getIndex()].subcells.first = Cube(clevel,c1);
level->elems[cell.getIndex()].subcells.second = Cube(clevel,c2+1);
}
}
++it;
level = clevel;
++lvl;
}
if (!parentOf.empty())
{
// Finally update parentOf to reflect new cell order
for (int i=0; i<size; i++)
parentOf[elems[i].children.first.getIndex()] = i;
}
}
else
{
// Simply update the existing tree, starting from the bottom
int lvl = 0;
for (std::list<CubeModel*>::reverse_iterator it = levels.rbegin(); it != levels.rend(); ++it)
{
//sout << "CubeModel: update level "<<lvl<<sendl;
(*it)->updateCubes();
++lvl;
}
}
//sout << "<CubeModel::computeBoundingTree("<<maxDepth<<")"<<sendl;
}
} // namespace collision
} // namespace component
} // namespace sofa
| 39.019774 | 260 | 0.555419 | [
"vector",
"model"
] |
176744c11720e0b3b5c455a1b22daaceb7818865 | 2,214 | cpp | C++ | src/test_suites/cm/cm_dp/kernels/cm_dp/dp_genx.cpp | intel/cassian | 8e9594f053f9b9464066c8002297346580e4aa2a | [
"MIT"
] | 1 | 2021-10-05T14:15:34.000Z | 2021-10-05T14:15:34.000Z | src/test_suites/cm/cm_dp/kernels/cm_dp/dp_genx.cpp | intel/cassian | 8e9594f053f9b9464066c8002297346580e4aa2a | [
"MIT"
] | null | null | null | src/test_suites/cm/cm_dp/kernels/cm_dp/dp_genx.cpp | intel/cassian | 8e9594f053f9b9464066c8002297346580e4aa2a | [
"MIT"
] | null | null | null | /*
* Copyright (C) 2021 Intel Corporation
*
* SPDX-License-Identifier: MIT
*
*/
#include <cm/cm.h>
#ifndef SAT_FLAG
#define SAT_FLAG 0
#endif
using out_t = OUT_TYPE;
using in_t = IN_TYPE;
extern "C" _GENX_MAIN_ _GENX_FLOAT_CONTROL_(CM_DENORM_ALLOW) void kernel(
SurfaceIndex in0_buf [[type("buffer_t")]],
#if defined(INPUT1_CONST)
#elif defined(INPUT1_SCALAR)
in_t in1,
#else
SurfaceIndex in1_buf [[type("buffer_t")]],
#endif
SurfaceIndex out_buf [[type("buffer_t")]]) {
#if defined(INPUT0_MATRIX)
constexpr int simd0_u = SIMD0_U;
constexpr int simd0_v = SIMD0_V;
constexpr int simd_out = simd0_u * simd0_v;
matrix<in_t, simd0_u, simd0_v> in0;
#elif defined(INPUT0_MATRIX_REF)
constexpr int simd0_u = SIMD0_U;
constexpr int simd0_v = SIMD0_V;
constexpr int simd_out = simd0_u * simd0_v;
matrix<in_t, simd0_u, simd0_v> in0_orig;
matrix_ref<in_t, simd0_u, simd0_v> in0 = in0_orig;
#elif defined(INPUT0_VECTOR)
constexpr int simd0 = SIMD0;
constexpr int simd_out = simd0;
vector<in_t, simd0> in0;
#elif defined(INPUT0_VECTOR_REF)
constexpr int simd0 = SIMD0;
constexpr int simd_out = simd0;
vector<in_t, simd0> in0_orig;
vector_ref<in_t, simd0> in0 = in0_orig;
#endif
read(in0_buf, 0, in0.template format<in_t>());
#if defined(INPUT1_MATRIX)
constexpr int simd1_u = SIMD1_U;
constexpr int simd1_v = SIMD1_V;
matrix<in_t, simd1_u, simd1_v> in1;
read(in1_buf, 0, in1.template format<in_t>());
#elif defined(INPUT1_MATRIX_REF)
constexpr int simd1_u = SIMD1_U;
constexpr int simd1_v = SIMD1_V;
matrix<in_t, simd1_u, simd1_v> in1_orig;
matrix_ref<in_t, simd1_u, simd1_v> in1 = in1_orig;
read(in1_buf, 0, in1.template format<in_t>());
#elif defined(INPUT1_VECTOR)
constexpr int simd1 = SIMD1;
vector<in_t, simd1> in1;
read(in1_buf, 0, in1.template format<in_t>());
#elif defined(INPUT1_VECTOR_REF)
constexpr int simd1 = SIMD1;
vector<in_t, simd1> in1_orig;
vector_ref<in_t, simd1> in1 = in1_orig;
read(in1_buf, 0, in1.template format<in_t>());
#elif defined(INPUT1_CONST)
constexpr in_t in1 = INPUT1;
#endif
vector<out_t, simd_out> out = TEST_FUNC<out_t>(in0, in1, SAT_FLAG);
write(out_buf, 0, out.template format<out_t>());
} | 30.328767 | 73 | 0.728094 | [
"vector"
] |
176c0c75b917247e833164dc8d50cdf137070779 | 2,757 | cpp | C++ | source/QtGui/QDialogButtonBoxSlots.cpp | kenny1818/qt4xhb | f62f40d8b17acb93761014317b52da9f919707d0 | [
"MIT"
] | 1 | 2021-03-07T10:44:03.000Z | 2021-03-07T10:44:03.000Z | source/QtGui/QDialogButtonBoxSlots.cpp | kenny1818/qt4xhb | f62f40d8b17acb93761014317b52da9f919707d0 | [
"MIT"
] | null | null | null | source/QtGui/QDialogButtonBoxSlots.cpp | kenny1818/qt4xhb | f62f40d8b17acb93761014317b52da9f919707d0 | [
"MIT"
] | 2 | 2020-07-19T03:28:08.000Z | 2021-03-05T18:07:20.000Z | /*
Qt4xHb - Bindings libraries for Harbour/xHarbour and Qt Framework 4
Copyright (C) 2021 Marcos Antonio Gambeta <marcosgambeta AT outlook DOT com>
*/
/*
DO NOT EDIT THIS FILE - the content was created using a source code generator
*/
#include "QDialogButtonBoxSlots.h"
QDialogButtonBoxSlots::QDialogButtonBoxSlots( QObject * parent ) : QObject( parent )
{
}
QDialogButtonBoxSlots::~QDialogButtonBoxSlots()
{
}
void QDialogButtonBoxSlots::accepted()
{
QObject * object = qobject_cast< QObject * >( sender() );
PHB_ITEM cb = Qt4xHb::Signals_return_codeblock( object, "accepted()" );
if( cb )
{
PHB_ITEM pSender = Qt4xHb::Signals_return_qobject( object, "QDIALOGBUTTONBOX" );
hb_vmEvalBlockV( cb, 1, pSender );
hb_itemRelease( pSender );
}
}
void QDialogButtonBoxSlots::clicked( QAbstractButton * button )
{
QObject * object = qobject_cast< QObject * >( sender() );
PHB_ITEM cb = Qt4xHb::Signals_return_codeblock( object, "clicked(QAbstractButton*)" );
if( cb )
{
PHB_ITEM pSender = Qt4xHb::Signals_return_qobject( object, "QDIALOGBUTTONBOX" );
PHB_ITEM pButton = Qt4xHb::Signals_return_qobject( button, "QABSTRACTBUTTON" );
hb_vmEvalBlockV( cb, 2, pSender, pButton );
hb_itemRelease( pSender );
hb_itemRelease( pButton );
}
}
void QDialogButtonBoxSlots::helpRequested()
{
QObject * object = qobject_cast< QObject * >( sender() );
PHB_ITEM cb = Qt4xHb::Signals_return_codeblock( object, "helpRequested()" );
if( cb )
{
PHB_ITEM pSender = Qt4xHb::Signals_return_qobject( object, "QDIALOGBUTTONBOX" );
hb_vmEvalBlockV( cb, 1, pSender );
hb_itemRelease( pSender );
}
}
void QDialogButtonBoxSlots::rejected()
{
QObject * object = qobject_cast< QObject * >( sender() );
PHB_ITEM cb = Qt4xHb::Signals_return_codeblock( object, "rejected()" );
if( cb )
{
PHB_ITEM pSender = Qt4xHb::Signals_return_qobject( object, "QDIALOGBUTTONBOX" );
hb_vmEvalBlockV( cb, 1, pSender );
hb_itemRelease( pSender );
}
}
void QDialogButtonBoxSlots_connect_signal( const QString & signal, const QString & slot )
{
QDialogButtonBox * obj = qobject_cast< QDialogButtonBox * >( Qt4xHb::getQObjectPointerFromSelfItem() );
if( obj )
{
QDialogButtonBoxSlots * s = QCoreApplication::instance()->findChild<QDialogButtonBoxSlots *>();
if( s == NULL )
{
s = new QDialogButtonBoxSlots();
s->moveToThread( QCoreApplication::instance()->thread() );
s->setParent( QCoreApplication::instance() );
}
hb_retl( Qt4xHb::Signals_connection_disconnection( s, signal, slot ) );
}
else
{
hb_retl( false );
}
}
| 24.837838 | 106 | 0.664853 | [
"object"
] |
6afed85949e76378e3d2cb9149e4c331c668c44f | 2,602 | cpp | C++ | src/RE/B/BGSKeywordForm.cpp | tossaponk/CommonLibSSE | 18c724dbc1128f11a581de16a9d372988ea0c8ce | [
"MIT"
] | 1 | 2022-02-21T21:31:27.000Z | 2022-02-21T21:31:27.000Z | src/RE/B/BGSKeywordForm.cpp | tossaponk/CommonLibSSE | 18c724dbc1128f11a581de16a9d372988ea0c8ce | [
"MIT"
] | null | null | null | src/RE/B/BGSKeywordForm.cpp | tossaponk/CommonLibSSE | 18c724dbc1128f11a581de16a9d372988ea0c8ce | [
"MIT"
] | 1 | 2022-02-21T21:31:29.000Z | 2022-02-21T21:31:29.000Z | #include "RE/B/BGSKeywordForm.h"
#include "RE/B/BGSKeyword.h"
#include "SKSE/Impl/Util.h"
namespace RE
{
bool BGSKeywordForm::AddKeyword(BGSKeyword* a_keyword)
{
if (!GetKeywordIndex(a_keyword)) {
std::vector<BGSKeyword*> copiedData{ keywords, keywords + numKeywords };
copiedData.push_back(a_keyword);
auto newNum = static_cast<std::uint32_t>(copiedData.size());
auto newData = calloc<BGSKeyword*>(newNum);
std::ranges::copy(copiedData, newData);
auto oldData = keywords;
numKeywords = newNum;
keywords = newData;
free(oldData);
return true;
}
return false;
}
bool BGSKeywordForm::ContainsKeywordString(std::string_view a_editorID) const
{
if (keywords) {
for (std::uint32_t idx = 0; idx < numKeywords; ++idx) {
if (keywords[idx] && stl::string::icontains(keywords[idx]->formEditorID, a_editorID)) {
return true;
}
}
}
return false;
}
bool BGSKeywordForm::HasKeyword(FormID a_formID) const
{
if (keywords) {
for (std::uint32_t idx = 0; idx < numKeywords; ++idx) {
if (keywords[idx] && keywords[idx]->formID == a_formID) {
return true;
}
}
}
return false;
}
bool BGSKeywordForm::HasKeywordString(std::string_view a_editorID) const
{
if (keywords) {
for (std::uint32_t idx = 0; idx < numKeywords; ++idx) {
if (keywords[idx] && keywords[idx]->formEditorID == a_editorID) {
return true;
}
}
}
return false;
}
std::optional<BGSKeyword*> BGSKeywordForm::GetKeywordAt(std::uint32_t a_idx) const
{
if (a_idx < numKeywords) {
return std::make_optional(keywords[a_idx]);
} else {
return std::nullopt;
}
}
std::optional<std::uint32_t> BGSKeywordForm::GetKeywordIndex(BGSKeyword* a_keyword) const
{
if (keywords) {
for (std::uint32_t i = 0; i < numKeywords; ++i) {
if (keywords[i] == a_keyword) {
return i;
}
}
}
return std::nullopt;
}
std::uint32_t BGSKeywordForm::GetNumKeywords() const
{
return numKeywords;
}
bool BGSKeywordForm::RemoveKeyword(std::uint32_t a_index)
{
std::vector<BGSKeyword*> copiedData{ keywords, keywords + numKeywords };
copiedData.erase(copiedData.cbegin() + a_index);
auto newNum = static_cast<std::uint32_t>(copiedData.size());
auto newData = calloc<BGSKeyword*>(newNum);
std::ranges::copy(copiedData, newData);
auto oldData = keywords;
numKeywords = newNum;
keywords = newData;
free(oldData);
return true;
}
bool BGSKeywordForm::RemoveKeyword(BGSKeyword* a_keyword)
{
auto index = GetKeywordIndex(a_keyword);
return index ? RemoveKeyword(*index) : false;
}
}
| 21.504132 | 91 | 0.67256 | [
"vector"
] |
6afee014a5c21bf0e97a187cdf05728bbb80c02b | 13,862 | cc | C++ | fides/simple_settings_map_unittest.cc | cschuet/fides | c31ad020f213f859ddeb7a7be558e7769a501044 | [
"FSFAP"
] | 2 | 2018-07-27T00:29:35.000Z | 2018-07-29T14:44:59.000Z | fides/simple_settings_map_unittest.cc | cschuet/fides | c31ad020f213f859ddeb7a7be558e7769a501044 | [
"FSFAP"
] | null | null | null | fides/simple_settings_map_unittest.cc | cschuet/fides | c31ad020f213f859ddeb7a7be558e7769a501044 | [
"FSFAP"
] | null | null | null | // Copyright 2015 The Chromium OS 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 "fides/simple_settings_map.h"
#include <gtest/gtest.h>
#include <memory>
#include <string>
#include "fides/identifier_utils.h"
#include "fides/mock_settings_document.h"
#include "fides/test_helpers.h"
#include "glog/logging.h"
namespace fides {
class SimpleSettingsMapTest : public testing::Test {
public:
SimpleSettingsMapTest() {
// Prepare document for writer A.
VersionStamp version_stamp_A;
version_stamp_A.Set("A", 1);
version_stamp_A.Set("B", 1);
document_A_.reset(new MockSettingsDocument(version_stamp_A));
// Prepare Document for writer B.
VersionStamp version_stamp_B;
version_stamp_B.Set("A", 2);
version_stamp_B.Set("B", 1);
document_B_.reset(new MockSettingsDocument(version_stamp_B));
// Prepare Document for writer C.
VersionStamp version_stamp_C;
version_stamp_C.Set("A", 3);
version_stamp_C.Set("B", 1);
document_C_.reset(new MockSettingsDocument(version_stamp_C));
// Prepare Document for writer D (concurrent to C).
document_D_.reset(new MockSettingsDocument(version_stamp_C));
}
void CheckSettingsMapContents(
const std::map<Key, std::string>& expected_values,
const std::set<Key> expected_deletions,
const SimpleSettingsMap& settings_map) {
std::set<Key> value_keys = settings_map.GetKeys(Key());
std::set<Key> expected_value_keys;
for (auto& expected_value : expected_values) {
expected_value_keys.insert(expected_value.first);
BlobRef value = settings_map.GetValue(expected_value.first);
EXPECT_TRUE(BlobRef(&expected_value.second).Equals(value))
<< "Unexpected value for key " << expected_value.first.ToString();
}
EXPECT_EQ(expected_value_keys, value_keys);
std::set<Key> actual_deletions;
for (auto& deletion : settings_map.deletion_map_) {
actual_deletions.insert(deletion.first);
}
EXPECT_EQ(expected_deletions, actual_deletions);
}
protected:
std::unique_ptr<MockSettingsDocument> document_A_;
std::unique_ptr<MockSettingsDocument> document_B_;
std::unique_ptr<MockSettingsDocument> document_C_;
std::unique_ptr<MockSettingsDocument> document_D_;
};
TEST_F(SimpleSettingsMapTest, InsertionSingleDocument) {
document_A_->SetKey(Key("A.B.C"), "1");
document_A_->SetDeletion(Key("A.B"));
document_A_->SetDeletion(Key("B"));
SimpleSettingsMap settings_map;
std::set<Key> modified_keys;
EXPECT_TRUE(
settings_map.InsertDocument(document_A_.get(), &modified_keys, nullptr));
std::set<Key> expected_modifications = {Key("A.B.C")};
EXPECT_EQ(expected_modifications, modified_keys);
std::set<Key> expected_deletions = {Key("B"), Key("A.B")};
std::map<Key, std::string> expected_values{
{Key("A.B.C"), "1"},
};
CheckSettingsMapContents(expected_values, expected_deletions, settings_map);
}
TEST_F(SimpleSettingsMapTest, InsertionTwoDocuments) {
document_A_->SetKey(Key("A.B.C"), "1");
document_A_->SetDeletion(Key("A.B"));
document_A_->SetDeletion(Key("B"));
document_A_->SetKey(Key("B.C"), "2");
document_B_->SetKey(Key("B.C"), "3");
document_B_->SetDeletion(Key("A"));
SimpleSettingsMap settings_map;
EXPECT_TRUE(settings_map.InsertDocument(document_A_.get(), nullptr, nullptr));
std::set<Key> modified_keys;
EXPECT_TRUE(
settings_map.InsertDocument(document_B_.get(), &modified_keys, nullptr));
std::set<Key> expected_modifications = {Key("A.B.C"), Key("B.C")};
EXPECT_EQ(expected_modifications, modified_keys);
std::set<Key> expected_deletions = {Key("A"), Key("B")};
std::map<Key, std::string> expected_values{
{Key("B.C"), "3"},
};
CheckSettingsMapContents(expected_values, expected_deletions, settings_map);
}
TEST_F(SimpleSettingsMapTest, InsertionTwoDocumentsInverseOrder) {
document_A_->SetKey(Key("A.B.C"), "1");
document_A_->SetDeletion(Key("A.B"));
document_A_->SetDeletion(Key("B"));
document_B_->SetKey(Key("B.C"), "2");
document_B_->SetDeletion(Key("A"));
SimpleSettingsMap settings_map;
EXPECT_TRUE(settings_map.InsertDocument(document_B_.get(), nullptr, nullptr));
std::set<Key> modified_keys;
EXPECT_TRUE(
settings_map.InsertDocument(document_A_.get(), &modified_keys, nullptr));
std::set<Key> expected_modifications;
EXPECT_EQ(expected_modifications, modified_keys);
std::set<Key> expected_deletions = {Key("A"), Key("B")};
std::map<Key, std::string> expected_values = {
{Key("B.C"), "2"},
};
CheckSettingsMapContents(expected_values, expected_deletions, settings_map);
}
TEST_F(SimpleSettingsMapTest, DocumentRemoval) {
document_A_->SetKey(Key("A"), "1");
document_A_->SetKey(Key("B"), "2");
document_B_->SetKey(Key("B"), "3");
document_B_->SetKey(Key("C"), "4");
SimpleSettingsMap settings_map;
EXPECT_TRUE(settings_map.InsertDocument(document_A_.get(), nullptr, nullptr));
EXPECT_TRUE(settings_map.InsertDocument(document_B_.get(), nullptr, nullptr));
std::set<Key> modified_keys;
settings_map.RemoveDocument(document_B_.get(), &modified_keys, nullptr);
std::set<Key> expected_modifications = {Key("B"), Key("C")};
EXPECT_EQ(expected_modifications, modified_keys);
std::set<Key> expected_deletions = {};
std::map<Key, std::string> expected_values{
{Key("A"), "1"}, {Key("B"), "2"},
};
CheckSettingsMapContents(expected_values, expected_deletions, settings_map);
}
TEST_F(SimpleSettingsMapTest, RemovalOfDeletion) {
document_A_->SetKey(Key("A"), "1");
document_A_->SetKey(Key("B.C"), "2");
document_B_->SetDeletion(Key("B"));
SimpleSettingsMap settings_map;
EXPECT_TRUE(settings_map.InsertDocument(document_A_.get(), nullptr, nullptr));
EXPECT_TRUE(settings_map.InsertDocument(document_B_.get(), nullptr, nullptr));
std::set<Key> modified_keys;
settings_map.RemoveDocument(document_B_.get(), &modified_keys, nullptr);
std::set<Key> expected_modifications = {Key("B.C")};
EXPECT_EQ(expected_modifications, modified_keys);
std::set<Key> expected_deletions = {};
std::map<Key, std::string> expected_values = {
{Key("A"), "1"}, {Key("B.C"), "2"},
};
CheckSettingsMapContents(expected_values, expected_deletions, settings_map);
}
TEST_F(SimpleSettingsMapTest, RemovalOfDeletionChildPrefixShineThrough) {
document_A_->SetKey(Key("A.B.D"), "1");
document_A_->SetKey(Key("Z.A"), "-1");
document_B_->SetKey(Key("A.B.C"), "2");
document_B_->SetKey(Key("Z.B"), "-1");
document_C_->SetDeletion(Key("A.B"));
SimpleSettingsMap settings_map;
EXPECT_TRUE(settings_map.InsertDocument(document_A_.get(), nullptr, nullptr));
EXPECT_TRUE(settings_map.InsertDocument(document_B_.get(), nullptr, nullptr));
EXPECT_TRUE(settings_map.InsertDocument(document_C_.get(), nullptr, nullptr));
std::set<Key> modified_keys;
settings_map.RemoveDocument(document_C_.get(), &modified_keys, nullptr);
std::set<Key> expected_modifications = {Key("A.B.C"), Key("A.B.D")};
EXPECT_EQ(expected_modifications, modified_keys);
std::set<Key> expected_deletions = {};
std::map<Key, std::string> expected_values = {
{Key("A.B.C"), "2"},
{Key("A.B.D"), "1"},
{Key("Z.A"), "-1"},
{Key("Z.B"), "-1"},
};
CheckSettingsMapContents(expected_values, expected_deletions, settings_map);
}
TEST_F(SimpleSettingsMapTest, RemovalOfDeletionParentDeleterUpstream) {
document_A_->SetKey(Key("A.A"), "1");
document_A_->SetKey(Key("A.B.C"), "2");
document_A_->SetKey(Key("Z.A"), "-1");
document_B_->SetDeletion(Key("A"));
document_B_->SetKey(Key("Z.B"), "-1");
document_C_->SetDeletion(Key("A.B"));
SimpleSettingsMap settings_map;
EXPECT_TRUE(settings_map.InsertDocument(document_A_.get(), nullptr, nullptr));
EXPECT_TRUE(settings_map.InsertDocument(document_B_.get(), nullptr, nullptr));
EXPECT_TRUE(settings_map.InsertDocument(document_C_.get(), nullptr, nullptr));
std::set<Key> modified_keys;
settings_map.RemoveDocument(document_C_.get(), &modified_keys, nullptr);
std::set<Key> expected_modifications;
EXPECT_EQ(expected_modifications, modified_keys);
std::set<Key> expected_deletions = {Key("A")};
std::map<Key, std::string> expected_values = {
{Key("Z.A"), "-1"}, {Key("Z.B"), "-1"},
};
CheckSettingsMapContents(expected_values, expected_deletions, settings_map);
}
TEST_F(SimpleSettingsMapTest, RemovalOfDeletionChildDeleterUpstream) {
document_A_->SetKey(Key("A.B.C.D"), "1");
document_A_->SetKey(Key("A.B.D"), "2");
document_A_->SetKey(Key("Z.A"), "-1");
document_B_->SetDeletion(Key("A.B.C"));
document_B_->SetKey(Key("Z.B"), "-1");
document_C_->SetDeletion(Key("A.B"));
SimpleSettingsMap settings_map;
EXPECT_TRUE(settings_map.InsertDocument(document_A_.get(), nullptr, nullptr));
EXPECT_TRUE(settings_map.InsertDocument(document_B_.get(), nullptr, nullptr));
EXPECT_TRUE(settings_map.InsertDocument(document_C_.get(), nullptr, nullptr));
std::set<Key> modified_keys;
settings_map.RemoveDocument(document_C_.get(), &modified_keys, nullptr);
std::set<Key> expected_modifications = {Key("A.B.D")};
EXPECT_EQ(expected_modifications, modified_keys);
std::set<Key> expected_deletions = {Key("A.B.C")};
std::map<Key, std::string> expected_values = {
{Key("A.B.D"), "2"},
{Key("Z.A"), "-1"},
{Key("Z.B"), "-1"},
};
CheckSettingsMapContents(expected_values, expected_deletions, settings_map);
}
TEST_F(SimpleSettingsMapTest, BasicRemovalOfDeletionSameDeletionUpstream) {
document_A_->SetKey(Key("A.B.C.D"), "1");
document_A_->SetKey(Key("A.B.D"), "2");
document_A_->SetKey(Key("Z.A"), "-1");
document_B_->SetDeletion(Key("A.B"));
document_B_->SetKey(Key("A.B.C"), "3");
document_B_->SetKey(Key("Z.B"), "-1");
document_C_->SetDeletion(Key("A.B"));
SimpleSettingsMap settings_map;
EXPECT_TRUE(settings_map.InsertDocument(document_A_.get(), nullptr, nullptr));
EXPECT_TRUE(settings_map.InsertDocument(document_B_.get(), nullptr, nullptr));
EXPECT_TRUE(settings_map.InsertDocument(document_C_.get(), nullptr, nullptr));
std::set<Key> modified_keys;
settings_map.RemoveDocument(document_C_.get(), &modified_keys, nullptr);
std::set<Key> expected_modifications = {Key("A.B.C")};
EXPECT_EQ(expected_modifications, modified_keys);
std::set<Key> expected_deletions = {Key("A.B")};
std::map<Key, std::string> expected_values = {
{Key("A.B.C"), "3"},
{Key("Z.A"), "-1"},
{Key("Z.B"), "-1"},
};
CheckSettingsMapContents(expected_values, expected_deletions, settings_map);
}
TEST_F(SimpleSettingsMapTest, DocumentCollision) {
document_C_->SetKey(Key("A.B.C.D"), "2");
document_D_->SetKey(Key("A.B.C.D"), "3");
SimpleSettingsMap settings_map;
EXPECT_TRUE(settings_map.InsertDocument(document_C_.get(), nullptr, nullptr));
std::set<Key> modified_keys;
EXPECT_FALSE(
settings_map.InsertDocument(document_D_.get(), &modified_keys, nullptr));
std::set<Key> expected_modifications;
EXPECT_EQ(expected_modifications, modified_keys);
std::set<Key> expected_deletions;
std::map<Key, std::string> expected_values = {
{Key("A.B.C.D"), "2"},
};
CheckSettingsMapContents(expected_values, expected_deletions, settings_map);
}
TEST_F(SimpleSettingsMapTest, InsertEmptyDocument) {
SimpleSettingsMap settings_map;
std::vector<const SettingsDocument*> unreferenced_documents;
EXPECT_TRUE(settings_map.InsertDocument(document_A_.get(), nullptr,
&unreferenced_documents));
std::vector<const SettingsDocument*> expected_unreferenced_documents = {
document_A_.get()
};
EXPECT_EQ(expected_unreferenced_documents, unreferenced_documents);
}
TEST_F(SimpleSettingsMapTest, UnreferencedDocsOverwrite) {
document_A_->SetKey(Key("A"), "1");
document_B_->SetKey(Key("A"), "2");
SimpleSettingsMap settings_map;
std::set<Key> modified_keys;
std::vector<const SettingsDocument*> unreferenced_documents;
EXPECT_TRUE(settings_map.InsertDocument(document_A_.get(), &modified_keys,
&unreferenced_documents));
std::set<Key> expected_modified_keys = {Key("A")};
std::vector<const SettingsDocument*> expected_unreferenced_documents;
EXPECT_EQ(expected_modified_keys, modified_keys);
EXPECT_EQ(expected_unreferenced_documents, unreferenced_documents);
EXPECT_TRUE(settings_map.InsertDocument(document_B_.get(), &modified_keys,
&unreferenced_documents));
expected_modified_keys = {Key("A")};
expected_unreferenced_documents = {document_A_.get()};
EXPECT_EQ(expected_modified_keys, modified_keys);
EXPECT_EQ(expected_unreferenced_documents, unreferenced_documents);
}
TEST_F(SimpleSettingsMapTest, UnreferencedDocsDeletion) {
document_A_->SetKey(Key("A.B"), "1");
document_B_->SetDeletion(Key("A"));
SimpleSettingsMap settings_map;
std::set<Key> modified_keys;
std::vector<const SettingsDocument*> unreferenced_documents;
EXPECT_TRUE(settings_map.InsertDocument(document_A_.get(), &modified_keys,
&unreferenced_documents));
std::set<Key> expected_modified_keys = {Key("A.B")};
std::vector<const SettingsDocument*> expected_unreferenced_documents;
EXPECT_EQ(expected_modified_keys, modified_keys);
EXPECT_EQ(expected_unreferenced_documents, unreferenced_documents);
EXPECT_TRUE(settings_map.InsertDocument(document_B_.get(), &modified_keys,
&unreferenced_documents));
expected_modified_keys = {Key("A.B")};
expected_unreferenced_documents = {document_A_.get()};
EXPECT_EQ(expected_modified_keys, modified_keys);
EXPECT_EQ(expected_unreferenced_documents, unreferenced_documents);
}
} // namespace fides
| 38.72067 | 80 | 0.71678 | [
"vector"
] |
ed02f4f61ac445947404418f30874312cd8db2f4 | 2,704 | cc | C++ | src/timer.cc | aiqu/cpp-utils | 38262037fc4c9d7c4838c41549cc086c731017ec | [
"MIT"
] | null | null | null | src/timer.cc | aiqu/cpp-utils | 38262037fc4c9d7c4838c41549cc086c731017ec | [
"MIT"
] | null | null | null | src/timer.cc | aiqu/cpp-utils | 38262037fc4c9d7c4838c41549cc086c731017ec | [
"MIT"
] | null | null | null | // Copyright (c) 2018 Gwangmin Lee
#include <timer.h>
#include <chrono> // NOLINT
#include <iostream>
#include <type_traits>
#include <vector>
template <class T>
Timer<T>::Timer(const std::string& description)
: begin_(std::chrono::steady_clock::now()), description_(description) {
split_ = begin_;
if (std::is_same<T, std::chrono::hours>()) {
time_suffix_ = "h";
} else if (std::is_same<T, std::chrono::minutes>()) {
time_suffix_ = "m";
} else if (std::is_same<T, std::chrono::seconds>()) {
time_suffix_ = "s";
} else if (std::is_same<T, std::chrono::milliseconds>()) {
time_suffix_ = "ms";
} else if (std::is_same<T, std::chrono::microseconds>()) {
time_suffix_ = "us";
} else if (std::is_same<T, std::chrono::nanoseconds>()) {
time_suffix_ = "ns";
} else {
time_suffix_ = "";
}
}
template <class T>
Timer<T>::~Timer() {
if (verbose_) {
const auto now = std::chrono::steady_clock::now();
const auto elapsed = std::chrono::duration_cast<T>(now - begin_);
for (const auto& p : splits_) {
std::cout << description_ << ": " << p.first << " took " << p.second.count() << time_suffix_ << "\n";
}
std::cout << description_ << ": Total " << elapsed.count() << time_suffix_ << "\n";
}
}
template <class T>
void Timer<T>::Split(const std::string& description) {
const auto now = std::chrono::steady_clock::now();
const auto elapsed = std::chrono::duration_cast<T>(now - split_);
splits_.emplace_back(description, elapsed);
split_ = now;
}
template <class T>
std::vector<std::pair<std::string, T>> Timer<T>::GetRecords(const TimerOption& option) const {
const auto now = std::chrono::steady_clock::now();
const auto elapsed = std::chrono::duration_cast<T>(now - begin_);
std::vector<std::pair<std::string, T>> record(splits_);
if (option == TimerOption::IncludeNow) {
record.emplace_back(description_, elapsed);
}
return record;
}
template <class T>
std::vector<typename T::rep> Timer<T>::GetCounts(const TimerOption& option) const {
const auto now = std::chrono::steady_clock::now();
const auto elapsed = std::chrono::duration_cast<T>(now - begin_);
std::vector<typename T::rep> record;
record.reserve(splits_.size() + 1);
for (const auto& split : splits_) {
record.emplace_back(split.second.count());
}
if (option == TimerOption::IncludeNow) {
record.emplace_back(elapsed.count());
}
return record;
}
template class Timer<std::chrono::hours>;
template class Timer<std::chrono::minutes>;
template class Timer<std::chrono::seconds>;
template class Timer<std::chrono::milliseconds>;
template class Timer<std::chrono::microseconds>;
template class Timer<std::chrono::nanoseconds>;
| 33.382716 | 107 | 0.661612 | [
"vector"
] |
ed05c6a5e46f9f8b3ce2aebbeee29ce7759058e1 | 221,939 | cpp | C++ | Sources/External/node/elastos/external/chromium_org/third_party/WebKit/Source/modules/modules_gyp/core/StyleBuilderFunctions.cpp | jingcao80/Elastos | d0f39852356bdaf3a1234743b86364493a0441bc | [
"Apache-2.0"
] | 7 | 2017-07-13T10:34:54.000Z | 2021-04-16T05:40:35.000Z | Sources/External/node/elastos/external/chromium_org/third_party/WebKit/Source/modules/modules_gyp/core/StyleBuilderFunctions.cpp | jingcao80/Elastos | d0f39852356bdaf3a1234743b86364493a0441bc | [
"Apache-2.0"
] | null | null | null | Sources/External/node/elastos/external/chromium_org/third_party/WebKit/Source/modules/modules_gyp/core/StyleBuilderFunctions.cpp | jingcao80/Elastos | d0f39852356bdaf3a1234743b86364493a0441bc | [
"Apache-2.0"
] | 9 | 2017-07-13T12:33:20.000Z | 2021-06-19T02:46:48.000Z | #include "config.h"
#include "StyleBuilderFunctions.h"
#include "CSSValueKeywords.h"
#include "core/css/BasicShapeFunctions.h"
#include "core/css/CSSPrimitiveValueMappings.h"
#include "core/css/Pair.h"
#include "core/css/resolver/StyleResolverState.h"
namespace WebCore {
void StyleBuilderFunctions::applyInitialCSSPropertyVectorEffect(StyleResolverState& state)
{
state.style()->accessSVGStyle()->setVectorEffect(SVGRenderStyle::initialVectorEffect());
}
void StyleBuilderFunctions::applyInheritCSSPropertyVectorEffect(StyleResolverState& state)
{
state.style()->accessSVGStyle()->setVectorEffect(state.parentStyle()->svgStyle()->vectorEffect());
}
void StyleBuilderFunctions::applyValueCSSPropertyVectorEffect(StyleResolverState& state, CSSValue* value)
{
state.style()->accessSVGStyle()->setVectorEffect(static_cast<EVectorEffect>(*toCSSPrimitiveValue(value)));
}
void StyleBuilderFunctions::applyInitialCSSPropertyFillRule(StyleResolverState& state)
{
state.style()->accessSVGStyle()->setFillRule(SVGRenderStyle::initialFillRule());
}
void StyleBuilderFunctions::applyInheritCSSPropertyFillRule(StyleResolverState& state)
{
state.style()->accessSVGStyle()->setFillRule(state.parentStyle()->svgStyle()->fillRule());
}
void StyleBuilderFunctions::applyValueCSSPropertyFillRule(StyleResolverState& state, CSSValue* value)
{
state.style()->accessSVGStyle()->setFillRule(static_cast<WindRule>(*toCSSPrimitiveValue(value)));
}
void StyleBuilderFunctions::applyInitialCSSPropertyWebkitLineBoxContain(StyleResolverState& state)
{
state.style()->setLineBoxContain(RenderStyle::initialLineBoxContain());
}
void StyleBuilderFunctions::applyInheritCSSPropertyWebkitLineBoxContain(StyleResolverState& state)
{
state.style()->setLineBoxContain(state.parentStyle()->lineBoxContain());
}
void StyleBuilderFunctions::applyValueCSSPropertyWebkitLineBoxContain(StyleResolverState& state, CSSValue* value)
{
state.style()->setLineBoxContain(StyleBuilderConverter::convertLineBoxContain(state, value));
}
void StyleBuilderFunctions::applyInitialCSSPropertyTextDecoration(StyleResolverState& state)
{
state.style()->setTextDecoration(RenderStyle::initialTextDecoration());
}
void StyleBuilderFunctions::applyInheritCSSPropertyTextDecoration(StyleResolverState& state)
{
state.style()->setTextDecoration(state.parentStyle()->textDecoration());
}
void StyleBuilderFunctions::applyInitialCSSPropertyShapeOutside(StyleResolverState& state)
{
state.style()->setShapeOutside(RenderStyle::initialShapeOutside());
}
void StyleBuilderFunctions::applyInheritCSSPropertyShapeOutside(StyleResolverState& state)
{
state.style()->setShapeOutside(state.parentStyle()->shapeOutside());
}
void StyleBuilderFunctions::applyInitialCSSPropertyGlyphOrientationVertical(StyleResolverState& state)
{
state.style()->accessSVGStyle()->setGlyphOrientationVertical(SVGRenderStyle::initialGlyphOrientationVertical());
}
void StyleBuilderFunctions::applyInheritCSSPropertyGlyphOrientationVertical(StyleResolverState& state)
{
state.style()->accessSVGStyle()->setGlyphOrientationVertical(state.parentStyle()->svgStyle()->glyphOrientationVertical());
}
void StyleBuilderFunctions::applyInitialCSSPropertyWebkitHyphenateCharacter(StyleResolverState& state)
{
state.style()->setHyphenationString(RenderStyle::initialHyphenationString());
}
void StyleBuilderFunctions::applyInheritCSSPropertyWebkitHyphenateCharacter(StyleResolverState& state)
{
state.style()->setHyphenationString(state.parentStyle()->hyphenationString());
}
void StyleBuilderFunctions::applyValueCSSPropertyWebkitHyphenateCharacter(StyleResolverState& state, CSSValue* value)
{
state.style()->setHyphenationString(StyleBuilderConverter::convertString<CSSValueAuto>(state, value));
}
void StyleBuilderFunctions::applyInitialCSSPropertyWebkitBoxPack(StyleResolverState& state)
{
state.style()->setBoxPack(RenderStyle::initialBoxPack());
}
void StyleBuilderFunctions::applyInheritCSSPropertyWebkitBoxPack(StyleResolverState& state)
{
state.style()->setBoxPack(state.parentStyle()->boxPack());
}
void StyleBuilderFunctions::applyValueCSSPropertyWebkitBoxPack(StyleResolverState& state, CSSValue* value)
{
state.style()->setBoxPack(static_cast<EBoxPack>(*toCSSPrimitiveValue(value)));
}
void StyleBuilderFunctions::applyInitialCSSPropertyWebkitMarginBottomCollapse(StyleResolverState& state)
{
state.style()->setMarginAfterCollapse(RenderStyle::initialMarginAfterCollapse());
}
void StyleBuilderFunctions::applyInheritCSSPropertyWebkitMarginBottomCollapse(StyleResolverState& state)
{
state.style()->setMarginAfterCollapse(state.parentStyle()->marginAfterCollapse());
}
void StyleBuilderFunctions::applyValueCSSPropertyWebkitMarginBottomCollapse(StyleResolverState& state, CSSValue* value)
{
state.style()->setMarginAfterCollapse(static_cast<EMarginCollapse>(*toCSSPrimitiveValue(value)));
}
void StyleBuilderFunctions::applyInitialCSSPropertyOutlineWidth(StyleResolverState& state)
{
state.style()->setOutlineWidth(RenderStyle::initialOutlineWidth());
}
void StyleBuilderFunctions::applyInheritCSSPropertyOutlineWidth(StyleResolverState& state)
{
state.style()->setOutlineWidth(state.parentStyle()->outlineWidth());
}
void StyleBuilderFunctions::applyValueCSSPropertyOutlineWidth(StyleResolverState& state, CSSValue* value)
{
state.style()->setOutlineWidth(StyleBuilderConverter::convertLineWidth<unsigned short>(state, value));
}
void StyleBuilderFunctions::applyInitialCSSPropertyStrokeOpacity(StyleResolverState& state)
{
state.style()->accessSVGStyle()->setStrokeOpacity(SVGRenderStyle::initialStrokeOpacity());
}
void StyleBuilderFunctions::applyInheritCSSPropertyStrokeOpacity(StyleResolverState& state)
{
state.style()->accessSVGStyle()->setStrokeOpacity(state.parentStyle()->svgStyle()->strokeOpacity());
}
void StyleBuilderFunctions::applyValueCSSPropertyStrokeOpacity(StyleResolverState& state, CSSValue* value)
{
state.style()->accessSVGStyle()->setStrokeOpacity(StyleBuilderConverter::convertNumberOrPercentage(state, value));
}
void StyleBuilderFunctions::applyInitialCSSPropertyWebkitWrapThrough(StyleResolverState& state)
{
state.style()->setWrapThrough(RenderStyle::initialWrapThrough());
}
void StyleBuilderFunctions::applyInheritCSSPropertyWebkitWrapThrough(StyleResolverState& state)
{
state.style()->setWrapThrough(state.parentStyle()->wrapThrough());
}
void StyleBuilderFunctions::applyValueCSSPropertyWebkitWrapThrough(StyleResolverState& state, CSSValue* value)
{
state.style()->setWrapThrough(static_cast<WrapThrough>(*toCSSPrimitiveValue(value)));
}
void StyleBuilderFunctions::applyInitialCSSPropertyWebkitBoxFlex(StyleResolverState& state)
{
state.style()->setBoxFlex(RenderStyle::initialBoxFlex());
}
void StyleBuilderFunctions::applyInheritCSSPropertyWebkitBoxFlex(StyleResolverState& state)
{
state.style()->setBoxFlex(state.parentStyle()->boxFlex());
}
void StyleBuilderFunctions::applyValueCSSPropertyWebkitBoxFlex(StyleResolverState& state, CSSValue* value)
{
state.style()->setBoxFlex(static_cast<float>(*toCSSPrimitiveValue(value)));
}
void StyleBuilderFunctions::applyInitialCSSPropertyWebkitAppearance(StyleResolverState& state)
{
state.style()->setAppearance(RenderStyle::initialAppearance());
}
void StyleBuilderFunctions::applyInheritCSSPropertyWebkitAppearance(StyleResolverState& state)
{
state.style()->setAppearance(state.parentStyle()->appearance());
}
void StyleBuilderFunctions::applyValueCSSPropertyWebkitAppearance(StyleResolverState& state, CSSValue* value)
{
state.style()->setAppearance(static_cast<ControlPart>(*toCSSPrimitiveValue(value)));
}
void StyleBuilderFunctions::applyInitialCSSPropertyBorderBottomStyle(StyleResolverState& state)
{
state.style()->setBorderBottomStyle(RenderStyle::initialBorderStyle());
}
void StyleBuilderFunctions::applyInheritCSSPropertyBorderBottomStyle(StyleResolverState& state)
{
state.style()->setBorderBottomStyle(state.parentStyle()->borderBottomStyle());
}
void StyleBuilderFunctions::applyValueCSSPropertyBorderBottomStyle(StyleResolverState& state, CSSValue* value)
{
state.style()->setBorderBottomStyle(static_cast<EBorderStyle>(*toCSSPrimitiveValue(value)));
}
void StyleBuilderFunctions::applyInitialCSSPropertyHeight(StyleResolverState& state)
{
state.style()->setHeight(RenderStyle::initialSize());
}
void StyleBuilderFunctions::applyInheritCSSPropertyHeight(StyleResolverState& state)
{
state.style()->setHeight(state.parentStyle()->height());
}
void StyleBuilderFunctions::applyValueCSSPropertyHeight(StyleResolverState& state, CSSValue* value)
{
state.style()->setHeight(StyleBuilderConverter::convertLengthSizing(state, value));
}
void StyleBuilderFunctions::applyInitialCSSPropertyPaintOrder(StyleResolverState& state)
{
state.style()->accessSVGStyle()->setPaintOrder(SVGRenderStyle::initialPaintOrder());
}
void StyleBuilderFunctions::applyInheritCSSPropertyPaintOrder(StyleResolverState& state)
{
state.style()->accessSVGStyle()->setPaintOrder(state.parentStyle()->svgStyle()->paintOrder());
}
void StyleBuilderFunctions::applyValueCSSPropertyPaintOrder(StyleResolverState& state, CSSValue* value)
{
state.style()->accessSVGStyle()->setPaintOrder(StyleBuilderConverter::convertPaintOrder(state, value));
}
void StyleBuilderFunctions::applyInitialCSSPropertyTextRendering(StyleResolverState& state)
{
state.fontBuilder().setTextRendering(FontBuilder::initialTextRendering());
}
void StyleBuilderFunctions::applyInheritCSSPropertyTextRendering(StyleResolverState& state)
{
state.fontBuilder().setTextRendering(state.parentFontDescription().textRendering());
}
void StyleBuilderFunctions::applyValueCSSPropertyTextRendering(StyleResolverState& state, CSSValue* value)
{
state.fontBuilder().setTextRendering(static_cast<TextRenderingMode>(*toCSSPrimitiveValue(value)));
}
void StyleBuilderFunctions::applyInitialCSSPropertyWebkitColumnBreakAfter(StyleResolverState& state)
{
state.style()->setColumnBreakAfter(RenderStyle::initialPageBreak());
}
void StyleBuilderFunctions::applyInheritCSSPropertyWebkitColumnBreakAfter(StyleResolverState& state)
{
state.style()->setColumnBreakAfter(state.parentStyle()->columnBreakAfter());
}
void StyleBuilderFunctions::applyValueCSSPropertyWebkitColumnBreakAfter(StyleResolverState& state, CSSValue* value)
{
state.style()->setColumnBreakAfter(static_cast<EPageBreak>(*toCSSPrimitiveValue(value)));
}
void StyleBuilderFunctions::applyInitialCSSPropertyBorderBottomLeftRadius(StyleResolverState& state)
{
state.style()->setBorderBottomLeftRadius(RenderStyle::initialBorderRadius());
}
void StyleBuilderFunctions::applyInheritCSSPropertyBorderBottomLeftRadius(StyleResolverState& state)
{
state.style()->setBorderBottomLeftRadius(state.parentStyle()->borderBottomLeftRadius());
}
void StyleBuilderFunctions::applyValueCSSPropertyBorderBottomLeftRadius(StyleResolverState& state, CSSValue* value)
{
state.style()->setBorderBottomLeftRadius(StyleBuilderConverter::convertRadius(state, value));
}
void StyleBuilderFunctions::applyInitialCSSPropertyColorInterpolation(StyleResolverState& state)
{
state.style()->accessSVGStyle()->setColorInterpolation(SVGRenderStyle::initialColorInterpolation());
}
void StyleBuilderFunctions::applyInheritCSSPropertyColorInterpolation(StyleResolverState& state)
{
state.style()->accessSVGStyle()->setColorInterpolation(state.parentStyle()->svgStyle()->colorInterpolation());
}
void StyleBuilderFunctions::applyValueCSSPropertyColorInterpolation(StyleResolverState& state, CSSValue* value)
{
state.style()->accessSVGStyle()->setColorInterpolation(static_cast<EColorInterpolation>(*toCSSPrimitiveValue(value)));
}
void StyleBuilderFunctions::applyInitialCSSPropertyFilter(StyleResolverState& state)
{
state.style()->accessSVGStyle()->setFilterResource(SVGRenderStyle::initialFilterResource());
}
void StyleBuilderFunctions::applyInheritCSSPropertyFilter(StyleResolverState& state)
{
state.style()->accessSVGStyle()->setFilterResource(state.parentStyle()->svgStyle()->filterResource());
}
void StyleBuilderFunctions::applyValueCSSPropertyFilter(StyleResolverState& state, CSSValue* value)
{
state.style()->accessSVGStyle()->setFilterResource(StyleBuilderConverter::convertFragmentIdentifier(state, value));
}
void StyleBuilderFunctions::applyInitialCSSPropertyShapeMargin(StyleResolverState& state)
{
state.style()->setShapeMargin(RenderStyle::initialShapeMargin());
}
void StyleBuilderFunctions::applyInheritCSSPropertyShapeMargin(StyleResolverState& state)
{
state.style()->setShapeMargin(state.parentStyle()->shapeMargin());
}
void StyleBuilderFunctions::applyValueCSSPropertyShapeMargin(StyleResolverState& state, CSSValue* value)
{
state.style()->setShapeMargin(StyleBuilderConverter::convertLength(state, value));
}
void StyleBuilderFunctions::applyInitialCSSPropertyInternalMarqueeDirection(StyleResolverState& state)
{
state.style()->setMarqueeDirection(RenderStyle::initialMarqueeDirection());
}
void StyleBuilderFunctions::applyInheritCSSPropertyInternalMarqueeDirection(StyleResolverState& state)
{
state.style()->setMarqueeDirection(state.parentStyle()->marqueeDirection());
}
void StyleBuilderFunctions::applyValueCSSPropertyInternalMarqueeDirection(StyleResolverState& state, CSSValue* value)
{
state.style()->setMarqueeDirection(static_cast<EMarqueeDirection>(*toCSSPrimitiveValue(value)));
}
void StyleBuilderFunctions::applyInitialCSSPropertyImageRendering(StyleResolverState& state)
{
state.style()->setImageRendering(RenderStyle::initialImageRendering());
}
void StyleBuilderFunctions::applyInheritCSSPropertyImageRendering(StyleResolverState& state)
{
state.style()->setImageRendering(state.parentStyle()->imageRendering());
}
void StyleBuilderFunctions::applyValueCSSPropertyImageRendering(StyleResolverState& state, CSSValue* value)
{
state.style()->setImageRendering(static_cast<EImageRendering>(*toCSSPrimitiveValue(value)));
}
void StyleBuilderFunctions::applyInitialCSSPropertyWebkitUserSelect(StyleResolverState& state)
{
state.style()->setUserSelect(RenderStyle::initialUserSelect());
}
void StyleBuilderFunctions::applyInheritCSSPropertyWebkitUserSelect(StyleResolverState& state)
{
state.style()->setUserSelect(state.parentStyle()->userSelect());
}
void StyleBuilderFunctions::applyValueCSSPropertyWebkitUserSelect(StyleResolverState& state, CSSValue* value)
{
state.style()->setUserSelect(static_cast<EUserSelect>(*toCSSPrimitiveValue(value)));
}
void StyleBuilderFunctions::applyInitialCSSPropertyPaddingBottom(StyleResolverState& state)
{
state.style()->setPaddingBottom(RenderStyle::initialPadding());
}
void StyleBuilderFunctions::applyInheritCSSPropertyPaddingBottom(StyleResolverState& state)
{
state.style()->setPaddingBottom(state.parentStyle()->paddingBottom());
}
void StyleBuilderFunctions::applyValueCSSPropertyPaddingBottom(StyleResolverState& state, CSSValue* value)
{
state.style()->setPaddingBottom(StyleBuilderConverter::convertLength(state, value));
}
void StyleBuilderFunctions::applyInitialCSSPropertyQuotes(StyleResolverState& state)
{
state.style()->setQuotes(RenderStyle::initialQuotes());
}
void StyleBuilderFunctions::applyInheritCSSPropertyQuotes(StyleResolverState& state)
{
state.style()->setQuotes(state.parentStyle()->quotes());
}
void StyleBuilderFunctions::applyValueCSSPropertyQuotes(StyleResolverState& state, CSSValue* value)
{
state.style()->setQuotes(StyleBuilderConverter::convertQuotes(state, value));
}
void StyleBuilderFunctions::applyInitialCSSPropertyGridAutoRows(StyleResolverState& state)
{
state.style()->setGridAutoRows(RenderStyle::initialGridAutoRows());
}
void StyleBuilderFunctions::applyInheritCSSPropertyGridAutoRows(StyleResolverState& state)
{
state.style()->setGridAutoRows(state.parentStyle()->gridAutoRows());
}
void StyleBuilderFunctions::applyValueCSSPropertyGridAutoRows(StyleResolverState& state, CSSValue* value)
{
state.style()->setGridAutoRows(StyleBuilderConverter::convertGridTrackSize(state, value));
}
void StyleBuilderFunctions::applyInitialCSSPropertyClipPath(StyleResolverState& state)
{
state.style()->accessSVGStyle()->setClipperResource(SVGRenderStyle::initialClipperResource());
}
void StyleBuilderFunctions::applyInheritCSSPropertyClipPath(StyleResolverState& state)
{
state.style()->accessSVGStyle()->setClipperResource(state.parentStyle()->svgStyle()->clipperResource());
}
void StyleBuilderFunctions::applyValueCSSPropertyClipPath(StyleResolverState& state, CSSValue* value)
{
state.style()->accessSVGStyle()->setClipperResource(StyleBuilderConverter::convertFragmentIdentifier(state, value));
}
void StyleBuilderFunctions::applyInitialCSSPropertyObjectFit(StyleResolverState& state)
{
state.style()->setObjectFit(RenderStyle::initialObjectFit());
}
void StyleBuilderFunctions::applyInheritCSSPropertyObjectFit(StyleResolverState& state)
{
state.style()->setObjectFit(state.parentStyle()->objectFit());
}
void StyleBuilderFunctions::applyValueCSSPropertyObjectFit(StyleResolverState& state, CSSValue* value)
{
state.style()->setObjectFit(static_cast<ObjectFit>(*toCSSPrimitiveValue(value)));
}
void StyleBuilderFunctions::applyInitialCSSPropertyStopOpacity(StyleResolverState& state)
{
state.style()->accessSVGStyle()->setStopOpacity(SVGRenderStyle::initialStopOpacity());
}
void StyleBuilderFunctions::applyInheritCSSPropertyStopOpacity(StyleResolverState& state)
{
state.style()->accessSVGStyle()->setStopOpacity(state.parentStyle()->svgStyle()->stopOpacity());
}
void StyleBuilderFunctions::applyValueCSSPropertyStopOpacity(StyleResolverState& state, CSSValue* value)
{
state.style()->accessSVGStyle()->setStopOpacity(StyleBuilderConverter::convertNumberOrPercentage(state, value));
}
void StyleBuilderFunctions::applyInitialCSSPropertyWebkitBoxReflect(StyleResolverState& state)
{
state.style()->setBoxReflect(RenderStyle::initialBoxReflect());
}
void StyleBuilderFunctions::applyInheritCSSPropertyWebkitBoxReflect(StyleResolverState& state)
{
state.style()->setBoxReflect(state.parentStyle()->boxReflect());
}
void StyleBuilderFunctions::applyValueCSSPropertyWebkitBoxReflect(StyleResolverState& state, CSSValue* value)
{
state.style()->setBoxReflect(StyleBuilderConverter::convertBoxReflect(state, value));
}
void StyleBuilderFunctions::applyInitialCSSPropertyBorderTopRightRadius(StyleResolverState& state)
{
state.style()->setBorderTopRightRadius(RenderStyle::initialBorderRadius());
}
void StyleBuilderFunctions::applyInheritCSSPropertyBorderTopRightRadius(StyleResolverState& state)
{
state.style()->setBorderTopRightRadius(state.parentStyle()->borderTopRightRadius());
}
void StyleBuilderFunctions::applyValueCSSPropertyBorderTopRightRadius(StyleResolverState& state, CSSValue* value)
{
state.style()->setBorderTopRightRadius(StyleBuilderConverter::convertRadius(state, value));
}
void StyleBuilderFunctions::applyInitialCSSPropertyWebkitBoxDirection(StyleResolverState& state)
{
state.style()->setBoxDirection(RenderStyle::initialBoxDirection());
}
void StyleBuilderFunctions::applyInheritCSSPropertyWebkitBoxDirection(StyleResolverState& state)
{
state.style()->setBoxDirection(state.parentStyle()->boxDirection());
}
void StyleBuilderFunctions::applyValueCSSPropertyWebkitBoxDirection(StyleResolverState& state, CSSValue* value)
{
state.style()->setBoxDirection(static_cast<EBoxDirection>(*toCSSPrimitiveValue(value)));
}
void StyleBuilderFunctions::applyInitialCSSPropertyWebkitUserModify(StyleResolverState& state)
{
state.style()->setUserModify(RenderStyle::initialUserModify());
}
void StyleBuilderFunctions::applyInheritCSSPropertyWebkitUserModify(StyleResolverState& state)
{
state.style()->setUserModify(state.parentStyle()->userModify());
}
void StyleBuilderFunctions::applyValueCSSPropertyWebkitUserModify(StyleResolverState& state, CSSValue* value)
{
state.style()->setUserModify(static_cast<EUserModify>(*toCSSPrimitiveValue(value)));
}
void StyleBuilderFunctions::applyInitialCSSPropertyWebkitBoxDecorationBreak(StyleResolverState& state)
{
state.style()->setBoxDecorationBreak(RenderStyle::initialBoxDecorationBreak());
}
void StyleBuilderFunctions::applyInheritCSSPropertyWebkitBoxDecorationBreak(StyleResolverState& state)
{
state.style()->setBoxDecorationBreak(state.parentStyle()->boxDecorationBreak());
}
void StyleBuilderFunctions::applyValueCSSPropertyWebkitBoxDecorationBreak(StyleResolverState& state, CSSValue* value)
{
state.style()->setBoxDecorationBreak(static_cast<EBoxDecorationBreak>(*toCSSPrimitiveValue(value)));
}
void StyleBuilderFunctions::applyInitialCSSPropertyFontKerning(StyleResolverState& state)
{
state.fontBuilder().setKerning(FontBuilder::initialKerning());
}
void StyleBuilderFunctions::applyInheritCSSPropertyFontKerning(StyleResolverState& state)
{
state.fontBuilder().setKerning(state.parentFontDescription().kerning());
}
void StyleBuilderFunctions::applyValueCSSPropertyFontKerning(StyleResolverState& state, CSSValue* value)
{
state.fontBuilder().setKerning(static_cast<FontDescription::Kerning>(*toCSSPrimitiveValue(value)));
}
void StyleBuilderFunctions::applyInitialCSSPropertyShapeImageThreshold(StyleResolverState& state)
{
state.style()->setShapeImageThreshold(RenderStyle::initialShapeImageThreshold());
}
void StyleBuilderFunctions::applyInheritCSSPropertyShapeImageThreshold(StyleResolverState& state)
{
state.style()->setShapeImageThreshold(state.parentStyle()->shapeImageThreshold());
}
void StyleBuilderFunctions::applyValueCSSPropertyShapeImageThreshold(StyleResolverState& state, CSSValue* value)
{
state.style()->setShapeImageThreshold(static_cast<float>(*toCSSPrimitiveValue(value)));
}
void StyleBuilderFunctions::applyInitialCSSPropertyMarginRight(StyleResolverState& state)
{
state.style()->setMarginRight(RenderStyle::initialMargin());
}
void StyleBuilderFunctions::applyInheritCSSPropertyMarginRight(StyleResolverState& state)
{
state.style()->setMarginRight(state.parentStyle()->marginRight());
}
void StyleBuilderFunctions::applyValueCSSPropertyMarginRight(StyleResolverState& state, CSSValue* value)
{
state.style()->setMarginRight(StyleBuilderConverter::convertLengthOrAuto(state, value));
}
void StyleBuilderFunctions::applyInitialCSSPropertyWebkitFontSmoothing(StyleResolverState& state)
{
state.fontBuilder().setFontSmoothing(FontBuilder::initialFontSmoothing());
}
void StyleBuilderFunctions::applyInheritCSSPropertyWebkitFontSmoothing(StyleResolverState& state)
{
state.fontBuilder().setFontSmoothing(state.parentFontDescription().fontSmoothing());
}
void StyleBuilderFunctions::applyValueCSSPropertyWebkitFontSmoothing(StyleResolverState& state, CSSValue* value)
{
state.fontBuilder().setFontSmoothing(static_cast<FontSmoothingMode>(*toCSSPrimitiveValue(value)));
}
void StyleBuilderFunctions::applyInitialCSSPropertyPageBreakBefore(StyleResolverState& state)
{
state.style()->setPageBreakBefore(RenderStyle::initialPageBreak());
}
void StyleBuilderFunctions::applyInheritCSSPropertyPageBreakBefore(StyleResolverState& state)
{
state.style()->setPageBreakBefore(state.parentStyle()->pageBreakBefore());
}
void StyleBuilderFunctions::applyValueCSSPropertyPageBreakBefore(StyleResolverState& state, CSSValue* value)
{
state.style()->setPageBreakBefore(static_cast<EPageBreak>(*toCSSPrimitiveValue(value)));
}
void StyleBuilderFunctions::applyInitialCSSPropertyOpacity(StyleResolverState& state)
{
state.style()->setOpacity(RenderStyle::initialOpacity());
}
void StyleBuilderFunctions::applyInheritCSSPropertyOpacity(StyleResolverState& state)
{
state.style()->setOpacity(state.parentStyle()->opacity());
}
void StyleBuilderFunctions::applyValueCSSPropertyOpacity(StyleResolverState& state, CSSValue* value)
{
state.style()->setOpacity(static_cast<float>(*toCSSPrimitiveValue(value)));
}
void StyleBuilderFunctions::applyInitialCSSPropertyDominantBaseline(StyleResolverState& state)
{
state.style()->accessSVGStyle()->setDominantBaseline(SVGRenderStyle::initialDominantBaseline());
}
void StyleBuilderFunctions::applyInheritCSSPropertyDominantBaseline(StyleResolverState& state)
{
state.style()->accessSVGStyle()->setDominantBaseline(state.parentStyle()->svgStyle()->dominantBaseline());
}
void StyleBuilderFunctions::applyValueCSSPropertyDominantBaseline(StyleResolverState& state, CSSValue* value)
{
state.style()->accessSVGStyle()->setDominantBaseline(static_cast<EDominantBaseline>(*toCSSPrimitiveValue(value)));
}
void StyleBuilderFunctions::applyInitialCSSPropertyAlignSelf(StyleResolverState& state)
{
state.style()->setAlignSelf(RenderStyle::initialAlignSelf());
}
void StyleBuilderFunctions::applyInheritCSSPropertyAlignSelf(StyleResolverState& state)
{
state.style()->setAlignSelf(state.parentStyle()->alignSelf());
}
void StyleBuilderFunctions::applyInitialCSSPropertyClear(StyleResolverState& state)
{
state.style()->setClear(RenderStyle::initialClear());
}
void StyleBuilderFunctions::applyInheritCSSPropertyClear(StyleResolverState& state)
{
state.style()->setClear(state.parentStyle()->clear());
}
void StyleBuilderFunctions::applyValueCSSPropertyClear(StyleResolverState& state, CSSValue* value)
{
state.style()->setClear(static_cast<EClear>(*toCSSPrimitiveValue(value)));
}
void StyleBuilderFunctions::applyInitialCSSPropertyWebkitColumnBreakInside(StyleResolverState& state)
{
state.style()->setColumnBreakInside(RenderStyle::initialPageBreak());
}
void StyleBuilderFunctions::applyInheritCSSPropertyWebkitColumnBreakInside(StyleResolverState& state)
{
state.style()->setColumnBreakInside(state.parentStyle()->columnBreakInside());
}
void StyleBuilderFunctions::applyValueCSSPropertyWebkitColumnBreakInside(StyleResolverState& state, CSSValue* value)
{
state.style()->setColumnBreakInside(static_cast<EPageBreak>(*toCSSPrimitiveValue(value)));
}
void StyleBuilderFunctions::applyInitialCSSPropertyWebkitMaskBoxImageSource(StyleResolverState& state)
{
state.style()->setMaskBoxImageSource(RenderStyle::initialMaskBoxImageSource());
}
void StyleBuilderFunctions::applyInheritCSSPropertyWebkitMaskBoxImageSource(StyleResolverState& state)
{
state.style()->setMaskBoxImageSource(state.parentStyle()->maskBoxImageSource());
}
void StyleBuilderFunctions::applyInitialCSSPropertyTransformStyle(StyleResolverState& state)
{
state.style()->setTransformStyle3D(RenderStyle::initialTransformStyle3D());
}
void StyleBuilderFunctions::applyInheritCSSPropertyTransformStyle(StyleResolverState& state)
{
state.style()->setTransformStyle3D(state.parentStyle()->transformStyle3D());
}
void StyleBuilderFunctions::applyValueCSSPropertyTransformStyle(StyleResolverState& state, CSSValue* value)
{
state.style()->setTransformStyle3D(static_cast<ETransformStyle3D>(*toCSSPrimitiveValue(value)));
}
void StyleBuilderFunctions::applyInitialCSSPropertyWebkitBorderHorizontalSpacing(StyleResolverState& state)
{
state.style()->setHorizontalBorderSpacing(RenderStyle::initialHorizontalBorderSpacing());
}
void StyleBuilderFunctions::applyInheritCSSPropertyWebkitBorderHorizontalSpacing(StyleResolverState& state)
{
state.style()->setHorizontalBorderSpacing(state.parentStyle()->horizontalBorderSpacing());
}
void StyleBuilderFunctions::applyValueCSSPropertyWebkitBorderHorizontalSpacing(StyleResolverState& state, CSSValue* value)
{
state.style()->setHorizontalBorderSpacing(StyleBuilderConverter::convertComputedLength<short>(state, value));
}
void StyleBuilderFunctions::applyInitialCSSPropertyWebkitTapHighlightColor(StyleResolverState& state)
{
state.style()->setTapHighlightColor(RenderStyle::initialTapHighlightColor());
}
void StyleBuilderFunctions::applyInheritCSSPropertyWebkitTapHighlightColor(StyleResolverState& state)
{
state.style()->setTapHighlightColor(state.parentStyle()->tapHighlightColor());
}
void StyleBuilderFunctions::applyInitialCSSPropertyCaptionSide(StyleResolverState& state)
{
state.style()->setCaptionSide(RenderStyle::initialCaptionSide());
}
void StyleBuilderFunctions::applyInheritCSSPropertyCaptionSide(StyleResolverState& state)
{
state.style()->setCaptionSide(state.parentStyle()->captionSide());
}
void StyleBuilderFunctions::applyValueCSSPropertyCaptionSide(StyleResolverState& state, CSSValue* value)
{
state.style()->setCaptionSide(static_cast<ECaptionSide>(*toCSSPrimitiveValue(value)));
}
void StyleBuilderFunctions::applyInitialCSSPropertyWebkitPrintColorAdjust(StyleResolverState& state)
{
state.style()->setPrintColorAdjust(RenderStyle::initialPrintColorAdjust());
}
void StyleBuilderFunctions::applyInheritCSSPropertyWebkitPrintColorAdjust(StyleResolverState& state)
{
state.style()->setPrintColorAdjust(state.parentStyle()->printColorAdjust());
}
void StyleBuilderFunctions::applyValueCSSPropertyWebkitPrintColorAdjust(StyleResolverState& state, CSSValue* value)
{
state.style()->setPrintColorAdjust(static_cast<PrintColorAdjust>(*toCSSPrimitiveValue(value)));
}
void StyleBuilderFunctions::applyInitialCSSPropertyStrokeDasharray(StyleResolverState& state)
{
state.style()->accessSVGStyle()->setStrokeDashArray(SVGRenderStyle::initialStrokeDashArray());
}
void StyleBuilderFunctions::applyInheritCSSPropertyStrokeDasharray(StyleResolverState& state)
{
state.style()->accessSVGStyle()->setStrokeDashArray(state.parentStyle()->svgStyle()->strokeDashArray());
}
void StyleBuilderFunctions::applyValueCSSPropertyStrokeDasharray(StyleResolverState& state, CSSValue* value)
{
state.style()->accessSVGStyle()->setStrokeDashArray(StyleBuilderConverter::convertStrokeDasharray(state, value));
}
void StyleBuilderFunctions::applyInitialCSSPropertyFlexBasis(StyleResolverState& state)
{
state.style()->setFlexBasis(RenderStyle::initialFlexBasis());
}
void StyleBuilderFunctions::applyInheritCSSPropertyFlexBasis(StyleResolverState& state)
{
state.style()->setFlexBasis(state.parentStyle()->flexBasis());
}
void StyleBuilderFunctions::applyValueCSSPropertyFlexBasis(StyleResolverState& state, CSSValue* value)
{
state.style()->setFlexBasis(StyleBuilderConverter::convertLengthOrAuto(state, value));
}
void StyleBuilderFunctions::applyInitialCSSPropertyWebkitRubyPosition(StyleResolverState& state)
{
state.style()->setRubyPosition(RenderStyle::initialRubyPosition());
}
void StyleBuilderFunctions::applyInheritCSSPropertyWebkitRubyPosition(StyleResolverState& state)
{
state.style()->setRubyPosition(state.parentStyle()->rubyPosition());
}
void StyleBuilderFunctions::applyValueCSSPropertyWebkitRubyPosition(StyleResolverState& state, CSSValue* value)
{
state.style()->setRubyPosition(static_cast<RubyPosition>(*toCSSPrimitiveValue(value)));
}
void StyleBuilderFunctions::applyInitialCSSPropertyFlexShrink(StyleResolverState& state)
{
state.style()->setFlexShrink(RenderStyle::initialFlexShrink());
}
void StyleBuilderFunctions::applyInheritCSSPropertyFlexShrink(StyleResolverState& state)
{
state.style()->setFlexShrink(state.parentStyle()->flexShrink());
}
void StyleBuilderFunctions::applyValueCSSPropertyFlexShrink(StyleResolverState& state, CSSValue* value)
{
state.style()->setFlexShrink(static_cast<float>(*toCSSPrimitiveValue(value)));
}
void StyleBuilderFunctions::applyInitialCSSPropertyWebkitTransformOriginY(StyleResolverState& state)
{
state.style()->setTransformOriginY(RenderStyle::initialTransformOriginY());
}
void StyleBuilderFunctions::applyInheritCSSPropertyWebkitTransformOriginY(StyleResolverState& state)
{
state.style()->setTransformOriginY(state.parentStyle()->transformOriginY());
}
void StyleBuilderFunctions::applyValueCSSPropertyWebkitTransformOriginY(StyleResolverState& state, CSSValue* value)
{
state.style()->setTransformOriginY(StyleBuilderConverter::convertLength(state, value));
}
void StyleBuilderFunctions::applyInitialCSSPropertyWebkitTransformOriginX(StyleResolverState& state)
{
state.style()->setTransformOriginX(RenderStyle::initialTransformOriginX());
}
void StyleBuilderFunctions::applyInheritCSSPropertyWebkitTransformOriginX(StyleResolverState& state)
{
state.style()->setTransformOriginX(state.parentStyle()->transformOriginX());
}
void StyleBuilderFunctions::applyValueCSSPropertyWebkitTransformOriginX(StyleResolverState& state, CSSValue* value)
{
state.style()->setTransformOriginX(StyleBuilderConverter::convertLength(state, value));
}
void StyleBuilderFunctions::applyInitialCSSPropertyTransform(StyleResolverState& state)
{
state.style()->setTransform(RenderStyle::initialTransform());
}
void StyleBuilderFunctions::applyInheritCSSPropertyTransform(StyleResolverState& state)
{
state.style()->setTransform(state.parentStyle()->transform());
}
void StyleBuilderFunctions::applyInitialCSSPropertyScrollBehavior(StyleResolverState& state)
{
state.style()->setScrollBehavior(RenderStyle::initialScrollBehavior());
}
void StyleBuilderFunctions::applyInheritCSSPropertyScrollBehavior(StyleResolverState& state)
{
state.style()->setScrollBehavior(state.parentStyle()->scrollBehavior());
}
void StyleBuilderFunctions::applyValueCSSPropertyScrollBehavior(StyleResolverState& state, CSSValue* value)
{
state.style()->setScrollBehavior(static_cast<ScrollBehavior>(*toCSSPrimitiveValue(value)));
}
void StyleBuilderFunctions::applyInitialCSSPropertyGridAutoFlow(StyleResolverState& state)
{
state.style()->setGridAutoFlow(RenderStyle::initialGridAutoFlow());
}
void StyleBuilderFunctions::applyInheritCSSPropertyGridAutoFlow(StyleResolverState& state)
{
state.style()->setGridAutoFlow(state.parentStyle()->gridAutoFlow());
}
void StyleBuilderFunctions::applyValueCSSPropertyGridAutoFlow(StyleResolverState& state, CSSValue* value)
{
state.style()->setGridAutoFlow(static_cast<GridAutoFlow>(*toCSSPrimitiveValue(value)));
}
void StyleBuilderFunctions::applyInitialCSSPropertyTouchActionDelay(StyleResolverState& state)
{
state.style()->setTouchActionDelay(RenderStyle::initialTouchActionDelay());
}
void StyleBuilderFunctions::applyInheritCSSPropertyTouchActionDelay(StyleResolverState& state)
{
state.style()->setTouchActionDelay(state.parentStyle()->touchActionDelay());
}
void StyleBuilderFunctions::applyValueCSSPropertyTouchActionDelay(StyleResolverState& state, CSSValue* value)
{
state.style()->setTouchActionDelay(static_cast<TouchActionDelay>(*toCSSPrimitiveValue(value)));
}
void StyleBuilderFunctions::applyInitialCSSPropertyStopColor(StyleResolverState& state)
{
state.style()->accessSVGStyle()->setStopColor(SVGRenderStyle::initialStopColor());
}
void StyleBuilderFunctions::applyInheritCSSPropertyStopColor(StyleResolverState& state)
{
state.style()->accessSVGStyle()->setStopColor(state.parentStyle()->svgStyle()->stopColor());
}
void StyleBuilderFunctions::applyValueCSSPropertyStopColor(StyleResolverState& state, CSSValue* value)
{
state.style()->accessSVGStyle()->setStopColor(StyleBuilderConverter::convertSVGColor(state, value));
}
void StyleBuilderFunctions::applyInitialCSSPropertyWebkitLineClamp(StyleResolverState& state)
{
state.style()->setLineClamp(RenderStyle::initialLineClamp());
}
void StyleBuilderFunctions::applyInheritCSSPropertyWebkitLineClamp(StyleResolverState& state)
{
state.style()->setLineClamp(state.parentStyle()->lineClamp());
}
void StyleBuilderFunctions::applyValueCSSPropertyWebkitLineClamp(StyleResolverState& state, CSSValue* value)
{
state.style()->setLineClamp(static_cast<LineClampValue>(*toCSSPrimitiveValue(value)));
}
void StyleBuilderFunctions::applyInitialCSSPropertyJustifySelf(StyleResolverState& state)
{
state.style()->setJustifySelf(RenderStyle::initialJustifySelf());
}
void StyleBuilderFunctions::applyInheritCSSPropertyJustifySelf(StyleResolverState& state)
{
state.style()->setJustifySelf(state.parentStyle()->justifySelf());
}
void StyleBuilderFunctions::applyInitialCSSPropertyWebkitTransformStyle(StyleResolverState& state)
{
state.style()->setTransformStyle3D(RenderStyle::initialTransformStyle3D());
}
void StyleBuilderFunctions::applyInheritCSSPropertyWebkitTransformStyle(StyleResolverState& state)
{
state.style()->setTransformStyle3D(state.parentStyle()->transformStyle3D());
}
void StyleBuilderFunctions::applyValueCSSPropertyWebkitTransformStyle(StyleResolverState& state, CSSValue* value)
{
state.style()->setTransformStyle3D(static_cast<ETransformStyle3D>(*toCSSPrimitiveValue(value)));
}
void StyleBuilderFunctions::applyInitialCSSPropertyTextJustify(StyleResolverState& state)
{
state.style()->setTextJustify(RenderStyle::initialTextJustify());
}
void StyleBuilderFunctions::applyInheritCSSPropertyTextJustify(StyleResolverState& state)
{
state.style()->setTextJustify(state.parentStyle()->textJustify());
}
void StyleBuilderFunctions::applyValueCSSPropertyTextJustify(StyleResolverState& state, CSSValue* value)
{
state.style()->setTextJustify(static_cast<TextJustify>(*toCSSPrimitiveValue(value)));
}
void StyleBuilderFunctions::applyInitialCSSPropertyTextAnchor(StyleResolverState& state)
{
state.style()->accessSVGStyle()->setTextAnchor(SVGRenderStyle::initialTextAnchor());
}
void StyleBuilderFunctions::applyInheritCSSPropertyTextAnchor(StyleResolverState& state)
{
state.style()->accessSVGStyle()->setTextAnchor(state.parentStyle()->svgStyle()->textAnchor());
}
void StyleBuilderFunctions::applyValueCSSPropertyTextAnchor(StyleResolverState& state, CSSValue* value)
{
state.style()->accessSVGStyle()->setTextAnchor(static_cast<ETextAnchor>(*toCSSPrimitiveValue(value)));
}
void StyleBuilderFunctions::applyInitialCSSPropertyFontStyle(StyleResolverState& state)
{
state.fontBuilder().setStyle(FontBuilder::initialStyle());
}
void StyleBuilderFunctions::applyInheritCSSPropertyFontStyle(StyleResolverState& state)
{
state.fontBuilder().setStyle(state.parentFontDescription().style());
}
void StyleBuilderFunctions::applyValueCSSPropertyFontStyle(StyleResolverState& state, CSSValue* value)
{
state.fontBuilder().setStyle(static_cast<FontStyle>(*toCSSPrimitiveValue(value)));
}
void StyleBuilderFunctions::applyInitialCSSPropertyBorderBottomRightRadius(StyleResolverState& state)
{
state.style()->setBorderBottomRightRadius(RenderStyle::initialBorderRadius());
}
void StyleBuilderFunctions::applyInheritCSSPropertyBorderBottomRightRadius(StyleResolverState& state)
{
state.style()->setBorderBottomRightRadius(state.parentStyle()->borderBottomRightRadius());
}
void StyleBuilderFunctions::applyValueCSSPropertyBorderBottomRightRadius(StyleResolverState& state, CSSValue* value)
{
state.style()->setBorderBottomRightRadius(StyleBuilderConverter::convertRadius(state, value));
}
void StyleBuilderFunctions::applyInitialCSSPropertyBorderRightWidth(StyleResolverState& state)
{
state.style()->setBorderRightWidth(RenderStyle::initialBorderWidth());
}
void StyleBuilderFunctions::applyInheritCSSPropertyBorderRightWidth(StyleResolverState& state)
{
state.style()->setBorderRightWidth(state.parentStyle()->borderRightWidth());
}
void StyleBuilderFunctions::applyValueCSSPropertyBorderRightWidth(StyleResolverState& state, CSSValue* value)
{
state.style()->setBorderRightWidth(StyleBuilderConverter::convertLineWidth<unsigned>(state, value));
}
void StyleBuilderFunctions::applyInitialCSSPropertyBorderTopLeftRadius(StyleResolverState& state)
{
state.style()->setBorderTopLeftRadius(RenderStyle::initialBorderRadius());
}
void StyleBuilderFunctions::applyInheritCSSPropertyBorderTopLeftRadius(StyleResolverState& state)
{
state.style()->setBorderTopLeftRadius(state.parentStyle()->borderTopLeftRadius());
}
void StyleBuilderFunctions::applyValueCSSPropertyBorderTopLeftRadius(StyleResolverState& state, CSSValue* value)
{
state.style()->setBorderTopLeftRadius(StyleBuilderConverter::convertRadius(state, value));
}
void StyleBuilderFunctions::applyInitialCSSPropertyFontVariant(StyleResolverState& state)
{
state.fontBuilder().setVariant(FontBuilder::initialVariant());
}
void StyleBuilderFunctions::applyInheritCSSPropertyFontVariant(StyleResolverState& state)
{
state.fontBuilder().setVariant(state.parentFontDescription().variant());
}
void StyleBuilderFunctions::applyValueCSSPropertyFontVariant(StyleResolverState& state, CSSValue* value)
{
state.fontBuilder().setVariant(static_cast<FontVariant>(*toCSSPrimitiveValue(value)));
}
void StyleBuilderFunctions::applyInitialCSSPropertyWritingMode(StyleResolverState& state)
{
state.style()->accessSVGStyle()->setWritingMode(SVGRenderStyle::initialWritingMode());
}
void StyleBuilderFunctions::applyInheritCSSPropertyWritingMode(StyleResolverState& state)
{
state.style()->accessSVGStyle()->setWritingMode(state.parentStyle()->svgStyle()->writingMode());
}
void StyleBuilderFunctions::applyValueCSSPropertyWritingMode(StyleResolverState& state, CSSValue* value)
{
state.style()->accessSVGStyle()->setWritingMode(static_cast<SVGWritingMode>(*toCSSPrimitiveValue(value)));
}
void StyleBuilderFunctions::applyInitialCSSPropertyWebkitTextSecurity(StyleResolverState& state)
{
state.style()->setTextSecurity(RenderStyle::initialTextSecurity());
}
void StyleBuilderFunctions::applyInheritCSSPropertyWebkitTextSecurity(StyleResolverState& state)
{
state.style()->setTextSecurity(state.parentStyle()->textSecurity());
}
void StyleBuilderFunctions::applyValueCSSPropertyWebkitTextSecurity(StyleResolverState& state, CSSValue* value)
{
state.style()->setTextSecurity(static_cast<ETextSecurity>(*toCSSPrimitiveValue(value)));
}
void StyleBuilderFunctions::applyInitialCSSPropertyBorderLeftWidth(StyleResolverState& state)
{
state.style()->setBorderLeftWidth(RenderStyle::initialBorderWidth());
}
void StyleBuilderFunctions::applyInheritCSSPropertyBorderLeftWidth(StyleResolverState& state)
{
state.style()->setBorderLeftWidth(state.parentStyle()->borderLeftWidth());
}
void StyleBuilderFunctions::applyValueCSSPropertyBorderLeftWidth(StyleResolverState& state, CSSValue* value)
{
state.style()->setBorderLeftWidth(StyleBuilderConverter::convertLineWidth<unsigned>(state, value));
}
void StyleBuilderFunctions::applyInitialCSSPropertyWebkitLineBreak(StyleResolverState& state)
{
state.style()->setLineBreak(RenderStyle::initialLineBreak());
}
void StyleBuilderFunctions::applyInheritCSSPropertyWebkitLineBreak(StyleResolverState& state)
{
state.style()->setLineBreak(state.parentStyle()->lineBreak());
}
void StyleBuilderFunctions::applyValueCSSPropertyWebkitLineBreak(StyleResolverState& state, CSSValue* value)
{
state.style()->setLineBreak(static_cast<LineBreak>(*toCSSPrimitiveValue(value)));
}
void StyleBuilderFunctions::applyInitialCSSPropertyIsolation(StyleResolverState& state)
{
state.style()->setIsolation(RenderStyle::initialIsolation());
}
void StyleBuilderFunctions::applyInheritCSSPropertyIsolation(StyleResolverState& state)
{
state.style()->setIsolation(state.parentStyle()->isolation());
}
void StyleBuilderFunctions::applyValueCSSPropertyIsolation(StyleResolverState& state, CSSValue* value)
{
state.style()->setIsolation(static_cast<EIsolation>(*toCSSPrimitiveValue(value)));
}
void StyleBuilderFunctions::applyInitialCSSPropertyGlyphOrientationHorizontal(StyleResolverState& state)
{
state.style()->accessSVGStyle()->setGlyphOrientationHorizontal(SVGRenderStyle::initialGlyphOrientationHorizontal());
}
void StyleBuilderFunctions::applyInheritCSSPropertyGlyphOrientationHorizontal(StyleResolverState& state)
{
state.style()->accessSVGStyle()->setGlyphOrientationHorizontal(state.parentStyle()->svgStyle()->glyphOrientationHorizontal());
}
void StyleBuilderFunctions::applyValueCSSPropertyGlyphOrientationHorizontal(StyleResolverState& state, CSSValue* value)
{
state.style()->accessSVGStyle()->setGlyphOrientationHorizontal(StyleBuilderConverter::convertGlyphOrientation(state, value));
}
void StyleBuilderFunctions::applyInitialCSSPropertyFillOpacity(StyleResolverState& state)
{
state.style()->accessSVGStyle()->setFillOpacity(SVGRenderStyle::initialFillOpacity());
}
void StyleBuilderFunctions::applyInheritCSSPropertyFillOpacity(StyleResolverState& state)
{
state.style()->accessSVGStyle()->setFillOpacity(state.parentStyle()->svgStyle()->fillOpacity());
}
void StyleBuilderFunctions::applyValueCSSPropertyFillOpacity(StyleResolverState& state, CSSValue* value)
{
state.style()->accessSVGStyle()->setFillOpacity(StyleBuilderConverter::convertNumberOrPercentage(state, value));
}
void StyleBuilderFunctions::applyInitialCSSPropertyBorderTopWidth(StyleResolverState& state)
{
state.style()->setBorderTopWidth(RenderStyle::initialBorderWidth());
}
void StyleBuilderFunctions::applyInheritCSSPropertyBorderTopWidth(StyleResolverState& state)
{
state.style()->setBorderTopWidth(state.parentStyle()->borderTopWidth());
}
void StyleBuilderFunctions::applyValueCSSPropertyBorderTopWidth(StyleResolverState& state, CSSValue* value)
{
state.style()->setBorderTopWidth(StyleBuilderConverter::convertLineWidth<unsigned>(state, value));
}
void StyleBuilderFunctions::applyInitialCSSPropertyBottom(StyleResolverState& state)
{
state.style()->setBottom(RenderStyle::initialOffset());
}
void StyleBuilderFunctions::applyInheritCSSPropertyBottom(StyleResolverState& state)
{
state.style()->setBottom(state.parentStyle()->bottom());
}
void StyleBuilderFunctions::applyValueCSSPropertyBottom(StyleResolverState& state, CSSValue* value)
{
state.style()->setBottom(StyleBuilderConverter::convertLengthOrAuto(state, value));
}
void StyleBuilderFunctions::applyInitialCSSPropertyBorderCollapse(StyleResolverState& state)
{
state.style()->setBorderCollapse(RenderStyle::initialBorderCollapse());
}
void StyleBuilderFunctions::applyInheritCSSPropertyBorderCollapse(StyleResolverState& state)
{
state.style()->setBorderCollapse(state.parentStyle()->borderCollapse());
}
void StyleBuilderFunctions::applyValueCSSPropertyBorderCollapse(StyleResolverState& state, CSSValue* value)
{
state.style()->setBorderCollapse(static_cast<EBorderCollapse>(*toCSSPrimitiveValue(value)));
}
void StyleBuilderFunctions::applyInitialCSSPropertyTop(StyleResolverState& state)
{
state.style()->setTop(RenderStyle::initialOffset());
}
void StyleBuilderFunctions::applyInheritCSSPropertyTop(StyleResolverState& state)
{
state.style()->setTop(state.parentStyle()->top());
}
void StyleBuilderFunctions::applyValueCSSPropertyTop(StyleResolverState& state, CSSValue* value)
{
state.style()->setTop(StyleBuilderConverter::convertLengthOrAuto(state, value));
}
void StyleBuilderFunctions::applyInitialCSSPropertyUnicodeBidi(StyleResolverState& state)
{
state.style()->setUnicodeBidi(RenderStyle::initialUnicodeBidi());
}
void StyleBuilderFunctions::applyInheritCSSPropertyUnicodeBidi(StyleResolverState& state)
{
state.style()->setUnicodeBidi(state.parentStyle()->unicodeBidi());
}
void StyleBuilderFunctions::applyValueCSSPropertyUnicodeBidi(StyleResolverState& state, CSSValue* value)
{
state.style()->setUnicodeBidi(static_cast<EUnicodeBidi>(*toCSSPrimitiveValue(value)));
}
void StyleBuilderFunctions::applyInitialCSSPropertyFloat(StyleResolverState& state)
{
state.style()->setFloating(RenderStyle::initialFloating());
}
void StyleBuilderFunctions::applyInheritCSSPropertyFloat(StyleResolverState& state)
{
state.style()->setFloating(state.parentStyle()->floating());
}
void StyleBuilderFunctions::applyValueCSSPropertyFloat(StyleResolverState& state, CSSValue* value)
{
state.style()->setFloating(static_cast<EFloat>(*toCSSPrimitiveValue(value)));
}
void StyleBuilderFunctions::applyInitialCSSPropertyWebkitRtlOrdering(StyleResolverState& state)
{
state.style()->setRTLOrdering(RenderStyle::initialRTLOrdering());
}
void StyleBuilderFunctions::applyInheritCSSPropertyWebkitRtlOrdering(StyleResolverState& state)
{
state.style()->setRTLOrdering(state.parentStyle()->rtlOrdering());
}
void StyleBuilderFunctions::applyValueCSSPropertyWebkitRtlOrdering(StyleResolverState& state, CSSValue* value)
{
state.style()->setRTLOrdering(static_cast<Order>(*toCSSPrimitiveValue(value)));
}
void StyleBuilderFunctions::applyInitialCSSPropertyInternalMarqueeSpeed(StyleResolverState& state)
{
state.style()->setMarqueeSpeed(RenderStyle::initialMarqueeSpeed());
}
void StyleBuilderFunctions::applyInheritCSSPropertyInternalMarqueeSpeed(StyleResolverState& state)
{
state.style()->setMarqueeSpeed(state.parentStyle()->marqueeSpeed());
}
void StyleBuilderFunctions::applyInitialCSSPropertyWordWrap(StyleResolverState& state)
{
state.style()->setOverflowWrap(RenderStyle::initialOverflowWrap());
}
void StyleBuilderFunctions::applyInheritCSSPropertyWordWrap(StyleResolverState& state)
{
state.style()->setOverflowWrap(state.parentStyle()->overflowWrap());
}
void StyleBuilderFunctions::applyValueCSSPropertyWordWrap(StyleResolverState& state, CSSValue* value)
{
state.style()->setOverflowWrap(static_cast<EOverflowWrap>(*toCSSPrimitiveValue(value)));
}
void StyleBuilderFunctions::applyInitialCSSPropertyMarginTop(StyleResolverState& state)
{
state.style()->setMarginTop(RenderStyle::initialMargin());
}
void StyleBuilderFunctions::applyInheritCSSPropertyMarginTop(StyleResolverState& state)
{
state.style()->setMarginTop(state.parentStyle()->marginTop());
}
void StyleBuilderFunctions::applyValueCSSPropertyMarginTop(StyleResolverState& state, CSSValue* value)
{
state.style()->setMarginTop(StyleBuilderConverter::convertLengthOrAuto(state, value));
}
void StyleBuilderFunctions::applyInitialCSSPropertyMaxWidth(StyleResolverState& state)
{
state.style()->setMaxWidth(RenderStyle::initialMaxSize());
}
void StyleBuilderFunctions::applyInheritCSSPropertyMaxWidth(StyleResolverState& state)
{
state.style()->setMaxWidth(state.parentStyle()->maxWidth());
}
void StyleBuilderFunctions::applyValueCSSPropertyMaxWidth(StyleResolverState& state, CSSValue* value)
{
state.style()->setMaxWidth(StyleBuilderConverter::convertLengthMaxSizing(state, value));
}
void StyleBuilderFunctions::applyInitialCSSPropertyTextShadow(StyleResolverState& state)
{
state.style()->setTextShadow(RenderStyle::initialTextShadow());
}
void StyleBuilderFunctions::applyInheritCSSPropertyTextShadow(StyleResolverState& state)
{
state.style()->setTextShadow(state.parentStyle()->textShadow());
}
void StyleBuilderFunctions::applyValueCSSPropertyTextShadow(StyleResolverState& state, CSSValue* value)
{
state.style()->setTextShadow(StyleBuilderConverter::convertShadow(state, value));
}
void StyleBuilderFunctions::applyInitialCSSPropertyPaddingRight(StyleResolverState& state)
{
state.style()->setPaddingRight(RenderStyle::initialPadding());
}
void StyleBuilderFunctions::applyInheritCSSPropertyPaddingRight(StyleResolverState& state)
{
state.style()->setPaddingRight(state.parentStyle()->paddingRight());
}
void StyleBuilderFunctions::applyValueCSSPropertyPaddingRight(StyleResolverState& state, CSSValue* value)
{
state.style()->setPaddingRight(StyleBuilderConverter::convertLength(state, value));
}
void StyleBuilderFunctions::applyInitialCSSPropertyAlignContent(StyleResolverState& state)
{
state.style()->setAlignContent(RenderStyle::initialAlignContent());
}
void StyleBuilderFunctions::applyInheritCSSPropertyAlignContent(StyleResolverState& state)
{
state.style()->setAlignContent(state.parentStyle()->alignContent());
}
void StyleBuilderFunctions::applyValueCSSPropertyAlignContent(StyleResolverState& state, CSSValue* value)
{
state.style()->setAlignContent(static_cast<EAlignContent>(*toCSSPrimitiveValue(value)));
}
void StyleBuilderFunctions::applyInitialCSSPropertyWebkitBoxOrdinalGroup(StyleResolverState& state)
{
state.style()->setBoxOrdinalGroup(RenderStyle::initialBoxOrdinalGroup());
}
void StyleBuilderFunctions::applyInheritCSSPropertyWebkitBoxOrdinalGroup(StyleResolverState& state)
{
state.style()->setBoxOrdinalGroup(state.parentStyle()->boxOrdinalGroup());
}
void StyleBuilderFunctions::applyValueCSSPropertyWebkitBoxOrdinalGroup(StyleResolverState& state, CSSValue* value)
{
state.style()->setBoxOrdinalGroup(static_cast<unsigned int>(*toCSSPrimitiveValue(value)));
}
void StyleBuilderFunctions::applyInitialCSSPropertyColumnFill(StyleResolverState& state)
{
state.style()->setColumnFill(RenderStyle::initialColumnFill());
}
void StyleBuilderFunctions::applyInheritCSSPropertyColumnFill(StyleResolverState& state)
{
state.style()->setColumnFill(state.parentStyle()->columnFill());
}
void StyleBuilderFunctions::applyValueCSSPropertyColumnFill(StyleResolverState& state, CSSValue* value)
{
state.style()->setColumnFill(static_cast<ColumnFill>(*toCSSPrimitiveValue(value)));
}
void StyleBuilderFunctions::applyInitialCSSPropertyOverflowX(StyleResolverState& state)
{
state.style()->setOverflowX(RenderStyle::initialOverflowX());
}
void StyleBuilderFunctions::applyInheritCSSPropertyOverflowX(StyleResolverState& state)
{
state.style()->setOverflowX(state.parentStyle()->overflowX());
}
void StyleBuilderFunctions::applyValueCSSPropertyOverflowX(StyleResolverState& state, CSSValue* value)
{
state.style()->setOverflowX(static_cast<EOverflow>(*toCSSPrimitiveValue(value)));
}
void StyleBuilderFunctions::applyInitialCSSPropertyOverflowY(StyleResolverState& state)
{
state.style()->setOverflowY(RenderStyle::initialOverflowY());
}
void StyleBuilderFunctions::applyInheritCSSPropertyOverflowY(StyleResolverState& state)
{
state.style()->setOverflowY(state.parentStyle()->overflowY());
}
void StyleBuilderFunctions::applyValueCSSPropertyOverflowY(StyleResolverState& state, CSSValue* value)
{
state.style()->setOverflowY(static_cast<EOverflow>(*toCSSPrimitiveValue(value)));
}
void StyleBuilderFunctions::applyInitialCSSPropertyPerspective(StyleResolverState& state)
{
state.style()->setPerspective(RenderStyle::initialPerspective());
}
void StyleBuilderFunctions::applyInheritCSSPropertyPerspective(StyleResolverState& state)
{
state.style()->setPerspective(state.parentStyle()->perspective());
}
void StyleBuilderFunctions::applyInitialCSSPropertyLineHeight(StyleResolverState& state)
{
state.style()->setLineHeight(RenderStyle::initialLineHeight());
}
void StyleBuilderFunctions::applyInheritCSSPropertyLineHeight(StyleResolverState& state)
{
state.style()->setLineHeight(state.parentStyle()->specifiedLineHeight());
}
void StyleBuilderFunctions::applyInitialCSSPropertyOrder(StyleResolverState& state)
{
state.style()->setOrder(RenderStyle::initialOrder());
}
void StyleBuilderFunctions::applyInheritCSSPropertyOrder(StyleResolverState& state)
{
state.style()->setOrder(state.parentStyle()->order());
}
void StyleBuilderFunctions::applyValueCSSPropertyOrder(StyleResolverState& state, CSSValue* value)
{
state.style()->setOrder(static_cast<int>(*toCSSPrimitiveValue(value)));
}
void StyleBuilderFunctions::applyInitialCSSPropertyWebkitBoxAlign(StyleResolverState& state)
{
state.style()->setBoxAlign(RenderStyle::initialBoxAlign());
}
void StyleBuilderFunctions::applyInheritCSSPropertyWebkitBoxAlign(StyleResolverState& state)
{
state.style()->setBoxAlign(state.parentStyle()->boxAlign());
}
void StyleBuilderFunctions::applyValueCSSPropertyWebkitBoxAlign(StyleResolverState& state, CSSValue* value)
{
state.style()->setBoxAlign(static_cast<EBoxAlignment>(*toCSSPrimitiveValue(value)));
}
void StyleBuilderFunctions::applyInitialCSSPropertyGridAutoColumns(StyleResolverState& state)
{
state.style()->setGridAutoColumns(RenderStyle::initialGridAutoColumns());
}
void StyleBuilderFunctions::applyInheritCSSPropertyGridAutoColumns(StyleResolverState& state)
{
state.style()->setGridAutoColumns(state.parentStyle()->gridAutoColumns());
}
void StyleBuilderFunctions::applyValueCSSPropertyGridAutoColumns(StyleResolverState& state, CSSValue* value)
{
state.style()->setGridAutoColumns(StyleBuilderConverter::convertGridTrackSize(state, value));
}
void StyleBuilderFunctions::applyInitialCSSPropertyGridRowStart(StyleResolverState& state)
{
state.style()->setGridRowStart(RenderStyle::initialGridRowStart());
}
void StyleBuilderFunctions::applyInheritCSSPropertyGridRowStart(StyleResolverState& state)
{
state.style()->setGridRowStart(state.parentStyle()->gridRowStart());
}
void StyleBuilderFunctions::applyValueCSSPropertyGridRowStart(StyleResolverState& state, CSSValue* value)
{
state.style()->setGridRowStart(StyleBuilderConverter::convertGridPosition(state, value));
}
void StyleBuilderFunctions::applyInitialCSSPropertyWebkitTextStrokeWidth(StyleResolverState& state)
{
state.style()->setTextStrokeWidth(RenderStyle::initialTextStrokeWidth());
}
void StyleBuilderFunctions::applyInheritCSSPropertyWebkitTextStrokeWidth(StyleResolverState& state)
{
state.style()->setTextStrokeWidth(state.parentStyle()->textStrokeWidth());
}
void StyleBuilderFunctions::applyValueCSSPropertyWebkitTextStrokeWidth(StyleResolverState& state, CSSValue* value)
{
state.style()->setTextStrokeWidth(StyleBuilderConverter::convertTextStrokeWidth(state, value));
}
void StyleBuilderFunctions::applyInitialCSSPropertyStrokeDashoffset(StyleResolverState& state)
{
state.style()->accessSVGStyle()->setStrokeDashOffset(SVGRenderStyle::initialStrokeDashOffset());
}
void StyleBuilderFunctions::applyInheritCSSPropertyStrokeDashoffset(StyleResolverState& state)
{
state.style()->accessSVGStyle()->setStrokeDashOffset(state.parentStyle()->svgStyle()->strokeDashOffset());
}
void StyleBuilderFunctions::applyValueCSSPropertyStrokeDashoffset(StyleResolverState& state, CSSValue* value)
{
state.style()->accessSVGStyle()->setStrokeDashOffset(StyleBuilderConverter::convertSVGLength(state, value));
}
void StyleBuilderFunctions::applyInitialCSSPropertyPosition(StyleResolverState& state)
{
state.style()->setPosition(RenderStyle::initialPosition());
}
void StyleBuilderFunctions::applyInheritCSSPropertyPosition(StyleResolverState& state)
{
state.style()->setPosition(state.parentStyle()->position());
}
void StyleBuilderFunctions::applyValueCSSPropertyPosition(StyleResolverState& state, CSSValue* value)
{
state.style()->setPosition(static_cast<EPosition>(*toCSSPrimitiveValue(value)));
}
void StyleBuilderFunctions::applyInitialCSSPropertyMixBlendMode(StyleResolverState& state)
{
state.style()->setBlendMode(RenderStyle::initialBlendMode());
}
void StyleBuilderFunctions::applyInheritCSSPropertyMixBlendMode(StyleResolverState& state)
{
state.style()->setBlendMode(state.parentStyle()->blendMode());
}
void StyleBuilderFunctions::applyValueCSSPropertyMixBlendMode(StyleResolverState& state, CSSValue* value)
{
state.style()->setBlendMode(static_cast<blink::WebBlendMode>(*toCSSPrimitiveValue(value)));
}
void StyleBuilderFunctions::applyInitialCSSPropertyBaselineShift(StyleResolverState& state)
{
state.style()->accessSVGStyle()->setBaselineShift(SVGRenderStyle::initialBaselineShift());
}
void StyleBuilderFunctions::applyInheritCSSPropertyBaselineShift(StyleResolverState& state)
{
state.style()->accessSVGStyle()->setBaselineShift(state.parentStyle()->svgStyle()->baselineShift());
}
void StyleBuilderFunctions::applyInitialCSSPropertyPaddingLeft(StyleResolverState& state)
{
state.style()->setPaddingLeft(RenderStyle::initialPadding());
}
void StyleBuilderFunctions::applyInheritCSSPropertyPaddingLeft(StyleResolverState& state)
{
state.style()->setPaddingLeft(state.parentStyle()->paddingLeft());
}
void StyleBuilderFunctions::applyValueCSSPropertyPaddingLeft(StyleResolverState& state, CSSValue* value)
{
state.style()->setPaddingLeft(StyleBuilderConverter::convertLength(state, value));
}
void StyleBuilderFunctions::applyInitialCSSPropertyWhiteSpace(StyleResolverState& state)
{
state.style()->setWhiteSpace(RenderStyle::initialWhiteSpace());
}
void StyleBuilderFunctions::applyInheritCSSPropertyWhiteSpace(StyleResolverState& state)
{
state.style()->setWhiteSpace(state.parentStyle()->whiteSpace());
}
void StyleBuilderFunctions::applyValueCSSPropertyWhiteSpace(StyleResolverState& state, CSSValue* value)
{
state.style()->setWhiteSpace(static_cast<EWhiteSpace>(*toCSSPrimitiveValue(value)));
}
void StyleBuilderFunctions::applyInitialCSSPropertyOverflowWrap(StyleResolverState& state)
{
state.style()->setOverflowWrap(RenderStyle::initialOverflowWrap());
}
void StyleBuilderFunctions::applyInheritCSSPropertyOverflowWrap(StyleResolverState& state)
{
state.style()->setOverflowWrap(state.parentStyle()->overflowWrap());
}
void StyleBuilderFunctions::applyValueCSSPropertyOverflowWrap(StyleResolverState& state, CSSValue* value)
{
state.style()->setOverflowWrap(static_cast<EOverflowWrap>(*toCSSPrimitiveValue(value)));
}
void StyleBuilderFunctions::applyInitialCSSPropertyVerticalAlign(StyleResolverState& state)
{
state.style()->setVerticalAlign(RenderStyle::initialVerticalAlign());
}
void StyleBuilderFunctions::applyInitialCSSPropertyWebkitLocale(StyleResolverState& state)
{
state.style()->setLocale(RenderStyle::initialLocale());
}
void StyleBuilderFunctions::applyInheritCSSPropertyWebkitLocale(StyleResolverState& state)
{
state.style()->setLocale(state.parentStyle()->locale());
}
void StyleBuilderFunctions::applyInitialCSSPropertyWebkitMarginAfterCollapse(StyleResolverState& state)
{
state.style()->setMarginAfterCollapse(RenderStyle::initialMarginAfterCollapse());
}
void StyleBuilderFunctions::applyInheritCSSPropertyWebkitMarginAfterCollapse(StyleResolverState& state)
{
state.style()->setMarginAfterCollapse(state.parentStyle()->marginAfterCollapse());
}
void StyleBuilderFunctions::applyValueCSSPropertyWebkitMarginAfterCollapse(StyleResolverState& state, CSSValue* value)
{
state.style()->setMarginAfterCollapse(static_cast<EMarginCollapse>(*toCSSPrimitiveValue(value)));
}
void StyleBuilderFunctions::applyInitialCSSPropertyWebkitTextEmphasisPosition(StyleResolverState& state)
{
state.style()->setTextEmphasisPosition(RenderStyle::initialTextEmphasisPosition());
}
void StyleBuilderFunctions::applyInheritCSSPropertyWebkitTextEmphasisPosition(StyleResolverState& state)
{
state.style()->setTextEmphasisPosition(state.parentStyle()->textEmphasisPosition());
}
void StyleBuilderFunctions::applyValueCSSPropertyWebkitTextEmphasisPosition(StyleResolverState& state, CSSValue* value)
{
state.style()->setTextEmphasisPosition(static_cast<TextEmphasisPosition>(*toCSSPrimitiveValue(value)));
}
void StyleBuilderFunctions::applyInitialCSSPropertyWordSpacing(StyleResolverState& state)
{
state.style()->setWordSpacing(RenderStyle::initialLetterWordSpacing());
}
void StyleBuilderFunctions::applyInheritCSSPropertyWordSpacing(StyleResolverState& state)
{
state.style()->setWordSpacing(state.parentStyle()->wordSpacing());
}
void StyleBuilderFunctions::applyValueCSSPropertyWordSpacing(StyleResolverState& state, CSSValue* value)
{
state.style()->setWordSpacing(StyleBuilderConverter::convertSpacing(state, value));
}
void StyleBuilderFunctions::applyInitialCSSPropertyPageBreakAfter(StyleResolverState& state)
{
state.style()->setPageBreakAfter(RenderStyle::initialPageBreak());
}
void StyleBuilderFunctions::applyInheritCSSPropertyPageBreakAfter(StyleResolverState& state)
{
state.style()->setPageBreakAfter(state.parentStyle()->pageBreakAfter());
}
void StyleBuilderFunctions::applyValueCSSPropertyPageBreakAfter(StyleResolverState& state, CSSValue* value)
{
state.style()->setPageBreakAfter(static_cast<EPageBreak>(*toCSSPrimitiveValue(value)));
}
void StyleBuilderFunctions::applyInitialCSSPropertyMarkerEnd(StyleResolverState& state)
{
state.style()->accessSVGStyle()->setMarkerEndResource(SVGRenderStyle::initialMarkerEndResource());
}
void StyleBuilderFunctions::applyInheritCSSPropertyMarkerEnd(StyleResolverState& state)
{
state.style()->accessSVGStyle()->setMarkerEndResource(state.parentStyle()->svgStyle()->markerEndResource());
}
void StyleBuilderFunctions::applyValueCSSPropertyMarkerEnd(StyleResolverState& state, CSSValue* value)
{
state.style()->accessSVGStyle()->setMarkerEndResource(StyleBuilderConverter::convertFragmentIdentifier(state, value));
}
void StyleBuilderFunctions::applyInitialCSSPropertyWebkitBoxLines(StyleResolverState& state)
{
state.style()->setBoxLines(RenderStyle::initialBoxLines());
}
void StyleBuilderFunctions::applyInheritCSSPropertyWebkitBoxLines(StyleResolverState& state)
{
state.style()->setBoxLines(state.parentStyle()->boxLines());
}
void StyleBuilderFunctions::applyValueCSSPropertyWebkitBoxLines(StyleResolverState& state, CSSValue* value)
{
state.style()->setBoxLines(static_cast<EBoxLines>(*toCSSPrimitiveValue(value)));
}
void StyleBuilderFunctions::applyInitialCSSPropertyTableLayout(StyleResolverState& state)
{
state.style()->setTableLayout(RenderStyle::initialTableLayout());
}
void StyleBuilderFunctions::applyInheritCSSPropertyTableLayout(StyleResolverState& state)
{
state.style()->setTableLayout(state.parentStyle()->tableLayout());
}
void StyleBuilderFunctions::applyValueCSSPropertyTableLayout(StyleResolverState& state, CSSValue* value)
{
state.style()->setTableLayout(static_cast<ETableLayout>(*toCSSPrimitiveValue(value)));
}
void StyleBuilderFunctions::applyInitialCSSPropertyBorderRightStyle(StyleResolverState& state)
{
state.style()->setBorderRightStyle(RenderStyle::initialBorderStyle());
}
void StyleBuilderFunctions::applyInheritCSSPropertyBorderRightStyle(StyleResolverState& state)
{
state.style()->setBorderRightStyle(state.parentStyle()->borderRightStyle());
}
void StyleBuilderFunctions::applyValueCSSPropertyBorderRightStyle(StyleResolverState& state, CSSValue* value)
{
state.style()->setBorderRightStyle(static_cast<EBorderStyle>(*toCSSPrimitiveValue(value)));
}
void StyleBuilderFunctions::applyInitialCSSPropertyGridRowEnd(StyleResolverState& state)
{
state.style()->setGridRowEnd(RenderStyle::initialGridRowEnd());
}
void StyleBuilderFunctions::applyInheritCSSPropertyGridRowEnd(StyleResolverState& state)
{
state.style()->setGridRowEnd(state.parentStyle()->gridRowEnd());
}
void StyleBuilderFunctions::applyValueCSSPropertyGridRowEnd(StyleResolverState& state, CSSValue* value)
{
state.style()->setGridRowEnd(StyleBuilderConverter::convertGridPosition(state, value));
}
void StyleBuilderFunctions::applyInitialCSSPropertyTextUnderlinePosition(StyleResolverState& state)
{
state.style()->setTextUnderlinePosition(RenderStyle::initialTextUnderlinePosition());
}
void StyleBuilderFunctions::applyInheritCSSPropertyTextUnderlinePosition(StyleResolverState& state)
{
state.style()->setTextUnderlinePosition(state.parentStyle()->textUnderlinePosition());
}
void StyleBuilderFunctions::applyInitialCSSPropertyBackfaceVisibility(StyleResolverState& state)
{
state.style()->setBackfaceVisibility(RenderStyle::initialBackfaceVisibility());
}
void StyleBuilderFunctions::applyInheritCSSPropertyBackfaceVisibility(StyleResolverState& state)
{
state.style()->setBackfaceVisibility(state.parentStyle()->backfaceVisibility());
}
void StyleBuilderFunctions::applyValueCSSPropertyBackfaceVisibility(StyleResolverState& state, CSSValue* value)
{
state.style()->setBackfaceVisibility(static_cast<EBackfaceVisibility>(*toCSSPrimitiveValue(value)));
}
void StyleBuilderFunctions::applyInitialCSSPropertyLeft(StyleResolverState& state)
{
state.style()->setLeft(RenderStyle::initialOffset());
}
void StyleBuilderFunctions::applyInheritCSSPropertyLeft(StyleResolverState& state)
{
state.style()->setLeft(state.parentStyle()->left());
}
void StyleBuilderFunctions::applyValueCSSPropertyLeft(StyleResolverState& state, CSSValue* value)
{
state.style()->setLeft(StyleBuilderConverter::convertLengthOrAuto(state, value));
}
void StyleBuilderFunctions::applyInitialCSSPropertyWidth(StyleResolverState& state)
{
state.style()->setWidth(RenderStyle::initialSize());
}
void StyleBuilderFunctions::applyInheritCSSPropertyWidth(StyleResolverState& state)
{
state.style()->setWidth(state.parentStyle()->width());
}
void StyleBuilderFunctions::applyValueCSSPropertyWidth(StyleResolverState& state, CSSValue* value)
{
state.style()->setWidth(StyleBuilderConverter::convertLengthSizing(state, value));
}
void StyleBuilderFunctions::applyInitialCSSPropertyTouchAction(StyleResolverState& state)
{
state.style()->setTouchAction(RenderStyle::initialTouchAction());
}
void StyleBuilderFunctions::applyInheritCSSPropertyTouchAction(StyleResolverState& state)
{
state.style()->setTouchAction(state.parentStyle()->touchAction());
}
void StyleBuilderFunctions::applyInitialCSSPropertyWebkitClipPath(StyleResolverState& state)
{
state.style()->setClipPath(RenderStyle::initialClipPath());
}
void StyleBuilderFunctions::applyInheritCSSPropertyWebkitClipPath(StyleResolverState& state)
{
state.style()->setClipPath(state.parentStyle()->clipPath());
}
void StyleBuilderFunctions::applyInitialCSSPropertyStrokeMiterlimit(StyleResolverState& state)
{
state.style()->accessSVGStyle()->setStrokeMiterLimit(SVGRenderStyle::initialStrokeMiterLimit());
}
void StyleBuilderFunctions::applyInheritCSSPropertyStrokeMiterlimit(StyleResolverState& state)
{
state.style()->accessSVGStyle()->setStrokeMiterLimit(state.parentStyle()->svgStyle()->strokeMiterLimit());
}
void StyleBuilderFunctions::applyValueCSSPropertyStrokeMiterlimit(StyleResolverState& state, CSSValue* value)
{
state.style()->accessSVGStyle()->setStrokeMiterLimit(static_cast<float>(*toCSSPrimitiveValue(value)));
}
void StyleBuilderFunctions::applyInitialCSSPropertyGridColumnStart(StyleResolverState& state)
{
state.style()->setGridColumnStart(RenderStyle::initialGridColumnStart());
}
void StyleBuilderFunctions::applyInheritCSSPropertyGridColumnStart(StyleResolverState& state)
{
state.style()->setGridColumnStart(state.parentStyle()->gridColumnStart());
}
void StyleBuilderFunctions::applyValueCSSPropertyGridColumnStart(StyleResolverState& state, CSSValue* value)
{
state.style()->setGridColumnStart(StyleBuilderConverter::convertGridPosition(state, value));
}
void StyleBuilderFunctions::applyInitialCSSPropertyMarginBottom(StyleResolverState& state)
{
state.style()->setMarginBottom(RenderStyle::initialMargin());
}
void StyleBuilderFunctions::applyInheritCSSPropertyMarginBottom(StyleResolverState& state)
{
state.style()->setMarginBottom(state.parentStyle()->marginBottom());
}
void StyleBuilderFunctions::applyValueCSSPropertyMarginBottom(StyleResolverState& state, CSSValue* value)
{
state.style()->setMarginBottom(StyleBuilderConverter::convertLengthOrAuto(state, value));
}
void StyleBuilderFunctions::applyInitialCSSPropertyListStylePosition(StyleResolverState& state)
{
state.style()->setListStylePosition(RenderStyle::initialListStylePosition());
}
void StyleBuilderFunctions::applyInheritCSSPropertyListStylePosition(StyleResolverState& state)
{
state.style()->setListStylePosition(state.parentStyle()->listStylePosition());
}
void StyleBuilderFunctions::applyValueCSSPropertyListStylePosition(StyleResolverState& state, CSSValue* value)
{
state.style()->setListStylePosition(static_cast<EListStylePosition>(*toCSSPrimitiveValue(value)));
}
void StyleBuilderFunctions::applyInitialCSSPropertyWebkitFilter(StyleResolverState& state)
{
state.style()->setFilter(RenderStyle::initialFilter());
}
void StyleBuilderFunctions::applyInheritCSSPropertyWebkitFilter(StyleResolverState& state)
{
state.style()->setFilter(state.parentStyle()->filter());
}
void StyleBuilderFunctions::applyInitialCSSPropertyOutlineOffset(StyleResolverState& state)
{
state.style()->setOutlineOffset(RenderStyle::initialOutlineOffset());
}
void StyleBuilderFunctions::applyInheritCSSPropertyOutlineOffset(StyleResolverState& state)
{
state.style()->setOutlineOffset(state.parentStyle()->outlineOffset());
}
void StyleBuilderFunctions::applyValueCSSPropertyOutlineOffset(StyleResolverState& state, CSSValue* value)
{
state.style()->setOutlineOffset(StyleBuilderConverter::convertComputedLength<int>(state, value));
}
void StyleBuilderFunctions::applyInitialCSSPropertyShapeRendering(StyleResolverState& state)
{
state.style()->accessSVGStyle()->setShapeRendering(SVGRenderStyle::initialShapeRendering());
}
void StyleBuilderFunctions::applyInheritCSSPropertyShapeRendering(StyleResolverState& state)
{
state.style()->accessSVGStyle()->setShapeRendering(state.parentStyle()->svgStyle()->shapeRendering());
}
void StyleBuilderFunctions::applyValueCSSPropertyShapeRendering(StyleResolverState& state, CSSValue* value)
{
state.style()->accessSVGStyle()->setShapeRendering(static_cast<EShapeRendering>(*toCSSPrimitiveValue(value)));
}
void StyleBuilderFunctions::applyInitialCSSPropertyWebkitBorderFit(StyleResolverState& state)
{
state.style()->setBorderFit(RenderStyle::initialBorderFit());
}
void StyleBuilderFunctions::applyInheritCSSPropertyWebkitBorderFit(StyleResolverState& state)
{
state.style()->setBorderFit(state.parentStyle()->borderFit());
}
void StyleBuilderFunctions::applyValueCSSPropertyWebkitBorderFit(StyleResolverState& state, CSSValue* value)
{
state.style()->setBorderFit(static_cast<EBorderFit>(*toCSSPrimitiveValue(value)));
}
void StyleBuilderFunctions::applyInitialCSSPropertyColorRendering(StyleResolverState& state)
{
state.style()->accessSVGStyle()->setColorRendering(SVGRenderStyle::initialColorRendering());
}
void StyleBuilderFunctions::applyInheritCSSPropertyColorRendering(StyleResolverState& state)
{
state.style()->accessSVGStyle()->setColorRendering(state.parentStyle()->svgStyle()->colorRendering());
}
void StyleBuilderFunctions::applyValueCSSPropertyColorRendering(StyleResolverState& state, CSSValue* value)
{
state.style()->accessSVGStyle()->setColorRendering(static_cast<EColorRendering>(*toCSSPrimitiveValue(value)));
}
void StyleBuilderFunctions::applyInitialCSSPropertyStrokeLinejoin(StyleResolverState& state)
{
state.style()->accessSVGStyle()->setJoinStyle(SVGRenderStyle::initialJoinStyle());
}
void StyleBuilderFunctions::applyInheritCSSPropertyStrokeLinejoin(StyleResolverState& state)
{
state.style()->accessSVGStyle()->setJoinStyle(state.parentStyle()->svgStyle()->joinStyle());
}
void StyleBuilderFunctions::applyValueCSSPropertyStrokeLinejoin(StyleResolverState& state, CSSValue* value)
{
state.style()->accessSVGStyle()->setJoinStyle(static_cast<LineJoin>(*toCSSPrimitiveValue(value)));
}
void StyleBuilderFunctions::applyInitialCSSPropertyFlexGrow(StyleResolverState& state)
{
state.style()->setFlexGrow(RenderStyle::initialFlexGrow());
}
void StyleBuilderFunctions::applyInheritCSSPropertyFlexGrow(StyleResolverState& state)
{
state.style()->setFlexGrow(state.parentStyle()->flexGrow());
}
void StyleBuilderFunctions::applyValueCSSPropertyFlexGrow(StyleResolverState& state, CSSValue* value)
{
state.style()->setFlexGrow(static_cast<float>(*toCSSPrimitiveValue(value)));
}
void StyleBuilderFunctions::applyInitialCSSPropertyMask(StyleResolverState& state)
{
state.style()->accessSVGStyle()->setMaskerResource(SVGRenderStyle::initialMaskerResource());
}
void StyleBuilderFunctions::applyInheritCSSPropertyMask(StyleResolverState& state)
{
state.style()->accessSVGStyle()->setMaskerResource(state.parentStyle()->svgStyle()->maskerResource());
}
void StyleBuilderFunctions::applyValueCSSPropertyMask(StyleResolverState& state, CSSValue* value)
{
state.style()->accessSVGStyle()->setMaskerResource(StyleBuilderConverter::convertFragmentIdentifier(state, value));
}
void StyleBuilderFunctions::applyInitialCSSPropertyWebkitMarginBeforeCollapse(StyleResolverState& state)
{
state.style()->setMarginBeforeCollapse(RenderStyle::initialMarginBeforeCollapse());
}
void StyleBuilderFunctions::applyInheritCSSPropertyWebkitMarginBeforeCollapse(StyleResolverState& state)
{
state.style()->setMarginBeforeCollapse(state.parentStyle()->marginBeforeCollapse());
}
void StyleBuilderFunctions::applyValueCSSPropertyWebkitMarginBeforeCollapse(StyleResolverState& state, CSSValue* value)
{
state.style()->setMarginBeforeCollapse(static_cast<EMarginCollapse>(*toCSSPrimitiveValue(value)));
}
void StyleBuilderFunctions::applyInitialCSSPropertyPointerEvents(StyleResolverState& state)
{
state.style()->setPointerEvents(RenderStyle::initialPointerEvents());
}
void StyleBuilderFunctions::applyInheritCSSPropertyPointerEvents(StyleResolverState& state)
{
state.style()->setPointerEvents(state.parentStyle()->pointerEvents());
}
void StyleBuilderFunctions::applyValueCSSPropertyPointerEvents(StyleResolverState& state, CSSValue* value)
{
state.style()->setPointerEvents(static_cast<EPointerEvents>(*toCSSPrimitiveValue(value)));
}
void StyleBuilderFunctions::applyInitialCSSPropertyWebkitBoxOrient(StyleResolverState& state)
{
state.style()->setBoxOrient(RenderStyle::initialBoxOrient());
}
void StyleBuilderFunctions::applyInheritCSSPropertyWebkitBoxOrient(StyleResolverState& state)
{
state.style()->setBoxOrient(state.parentStyle()->boxOrient());
}
void StyleBuilderFunctions::applyValueCSSPropertyWebkitBoxOrient(StyleResolverState& state, CSSValue* value)
{
state.style()->setBoxOrient(static_cast<EBoxOrient>(*toCSSPrimitiveValue(value)));
}
void StyleBuilderFunctions::applyInitialCSSPropertyStrokeLinecap(StyleResolverState& state)
{
state.style()->accessSVGStyle()->setCapStyle(SVGRenderStyle::initialCapStyle());
}
void StyleBuilderFunctions::applyInheritCSSPropertyStrokeLinecap(StyleResolverState& state)
{
state.style()->accessSVGStyle()->setCapStyle(state.parentStyle()->svgStyle()->capStyle());
}
void StyleBuilderFunctions::applyValueCSSPropertyStrokeLinecap(StyleResolverState& state, CSSValue* value)
{
state.style()->accessSVGStyle()->setCapStyle(static_cast<LineCap>(*toCSSPrimitiveValue(value)));
}
void StyleBuilderFunctions::applyInitialCSSPropertyBorderLeftStyle(StyleResolverState& state)
{
state.style()->setBorderLeftStyle(RenderStyle::initialBorderStyle());
}
void StyleBuilderFunctions::applyInheritCSSPropertyBorderLeftStyle(StyleResolverState& state)
{
state.style()->setBorderLeftStyle(state.parentStyle()->borderLeftStyle());
}
void StyleBuilderFunctions::applyValueCSSPropertyBorderLeftStyle(StyleResolverState& state, CSSValue* value)
{
state.style()->setBorderLeftStyle(static_cast<EBorderStyle>(*toCSSPrimitiveValue(value)));
}
void StyleBuilderFunctions::applyInitialCSSPropertyWebkitColumnRuleWidth(StyleResolverState& state)
{
state.style()->setColumnRuleWidth(RenderStyle::initialColumnRuleWidth());
}
void StyleBuilderFunctions::applyInheritCSSPropertyWebkitColumnRuleWidth(StyleResolverState& state)
{
state.style()->setColumnRuleWidth(state.parentStyle()->columnRuleWidth());
}
void StyleBuilderFunctions::applyValueCSSPropertyWebkitColumnRuleWidth(StyleResolverState& state, CSSValue* value)
{
state.style()->setColumnRuleWidth(StyleBuilderConverter::convertLineWidth<unsigned short>(state, value));
}
void StyleBuilderFunctions::applyInitialCSSPropertyWebkitUserDrag(StyleResolverState& state)
{
state.style()->setUserDrag(RenderStyle::initialUserDrag());
}
void StyleBuilderFunctions::applyInheritCSSPropertyWebkitUserDrag(StyleResolverState& state)
{
state.style()->setUserDrag(state.parentStyle()->userDrag());
}
void StyleBuilderFunctions::applyValueCSSPropertyWebkitUserDrag(StyleResolverState& state, CSSValue* value)
{
state.style()->setUserDrag(static_cast<EUserDrag>(*toCSSPrimitiveValue(value)));
}
void StyleBuilderFunctions::applyInitialCSSPropertyMarkerMid(StyleResolverState& state)
{
state.style()->accessSVGStyle()->setMarkerMidResource(SVGRenderStyle::initialMarkerMidResource());
}
void StyleBuilderFunctions::applyInheritCSSPropertyMarkerMid(StyleResolverState& state)
{
state.style()->accessSVGStyle()->setMarkerMidResource(state.parentStyle()->svgStyle()->markerMidResource());
}
void StyleBuilderFunctions::applyValueCSSPropertyMarkerMid(StyleResolverState& state, CSSValue* value)
{
state.style()->accessSVGStyle()->setMarkerMidResource(StyleBuilderConverter::convertFragmentIdentifier(state, value));
}
void StyleBuilderFunctions::applyInitialCSSPropertyWebkitTextCombine(StyleResolverState& state)
{
state.style()->setTextCombine(RenderStyle::initialTextCombine());
}
void StyleBuilderFunctions::applyInheritCSSPropertyWebkitTextCombine(StyleResolverState& state)
{
state.style()->setTextCombine(state.parentStyle()->textCombine());
}
void StyleBuilderFunctions::applyValueCSSPropertyWebkitTextCombine(StyleResolverState& state, CSSValue* value)
{
state.style()->setTextCombine(static_cast<TextCombine>(*toCSSPrimitiveValue(value)));
}
void StyleBuilderFunctions::applyInitialCSSPropertyWebkitColumnSpan(StyleResolverState& state)
{
state.style()->setColumnSpan(RenderStyle::initialColumnSpan());
}
void StyleBuilderFunctions::applyInheritCSSPropertyWebkitColumnSpan(StyleResolverState& state)
{
state.style()->setColumnSpan(state.parentStyle()->columnSpan());
}
void StyleBuilderFunctions::applyValueCSSPropertyWebkitColumnSpan(StyleResolverState& state, CSSValue* value)
{
state.style()->setColumnSpan(static_cast<ColumnSpan>(*toCSSPrimitiveValue(value)));
}
void StyleBuilderFunctions::applyInitialCSSPropertyResize(StyleResolverState& state)
{
state.style()->setResize(RenderStyle::initialResize());
}
void StyleBuilderFunctions::applyInheritCSSPropertyResize(StyleResolverState& state)
{
state.style()->setResize(state.parentStyle()->resize());
}
void StyleBuilderFunctions::applyInitialCSSPropertyLetterSpacing(StyleResolverState& state)
{
state.style()->setLetterSpacing(RenderStyle::initialLetterWordSpacing());
}
void StyleBuilderFunctions::applyInheritCSSPropertyLetterSpacing(StyleResolverState& state)
{
state.style()->setLetterSpacing(state.parentStyle()->letterSpacing());
}
void StyleBuilderFunctions::applyValueCSSPropertyLetterSpacing(StyleResolverState& state, CSSValue* value)
{
state.style()->setLetterSpacing(StyleBuilderConverter::convertSpacing(state, value));
}
void StyleBuilderFunctions::applyInitialCSSPropertyWebkitTransformOriginZ(StyleResolverState& state)
{
state.style()->setTransformOriginZ(RenderStyle::initialTransformOriginZ());
}
void StyleBuilderFunctions::applyInheritCSSPropertyWebkitTransformOriginZ(StyleResolverState& state)
{
state.style()->setTransformOriginZ(state.parentStyle()->transformOriginZ());
}
void StyleBuilderFunctions::applyValueCSSPropertyWebkitTransformOriginZ(StyleResolverState& state, CSSValue* value)
{
state.style()->setTransformOriginZ(StyleBuilderConverter::convertComputedLength<float>(state, value));
}
void StyleBuilderFunctions::applyInitialCSSPropertyWebkitTextOrientation(StyleResolverState& state)
{
state.style()->setTextOrientation(RenderStyle::initialTextOrientation());
}
void StyleBuilderFunctions::applyInheritCSSPropertyWebkitTextOrientation(StyleResolverState& state)
{
state.style()->setTextOrientation(state.parentStyle()->textOrientation());
}
void StyleBuilderFunctions::applyInitialCSSPropertyColorInterpolationFilters(StyleResolverState& state)
{
state.style()->accessSVGStyle()->setColorInterpolationFilters(SVGRenderStyle::initialColorInterpolationFilters());
}
void StyleBuilderFunctions::applyInheritCSSPropertyColorInterpolationFilters(StyleResolverState& state)
{
state.style()->accessSVGStyle()->setColorInterpolationFilters(state.parentStyle()->svgStyle()->colorInterpolationFilters());
}
void StyleBuilderFunctions::applyValueCSSPropertyColorInterpolationFilters(StyleResolverState& state, CSSValue* value)
{
state.style()->accessSVGStyle()->setColorInterpolationFilters(static_cast<EColorInterpolation>(*toCSSPrimitiveValue(value)));
}
void StyleBuilderFunctions::applyInitialCSSPropertyWebkitColumnBreakBefore(StyleResolverState& state)
{
state.style()->setColumnBreakBefore(RenderStyle::initialPageBreak());
}
void StyleBuilderFunctions::applyInheritCSSPropertyWebkitColumnBreakBefore(StyleResolverState& state)
{
state.style()->setColumnBreakBefore(state.parentStyle()->columnBreakBefore());
}
void StyleBuilderFunctions::applyValueCSSPropertyWebkitColumnBreakBefore(StyleResolverState& state, CSSValue* value)
{
state.style()->setColumnBreakBefore(static_cast<EPageBreak>(*toCSSPrimitiveValue(value)));
}
void StyleBuilderFunctions::applyInitialCSSPropertyTextTransform(StyleResolverState& state)
{
state.style()->setTextTransform(RenderStyle::initialTextTransform());
}
void StyleBuilderFunctions::applyInheritCSSPropertyTextTransform(StyleResolverState& state)
{
state.style()->setTextTransform(state.parentStyle()->textTransform());
}
void StyleBuilderFunctions::applyValueCSSPropertyTextTransform(StyleResolverState& state, CSSValue* value)
{
state.style()->setTextTransform(static_cast<ETextTransform>(*toCSSPrimitiveValue(value)));
}
void StyleBuilderFunctions::applyInitialCSSPropertyRight(StyleResolverState& state)
{
state.style()->setRight(RenderStyle::initialOffset());
}
void StyleBuilderFunctions::applyInheritCSSPropertyRight(StyleResolverState& state)
{
state.style()->setRight(state.parentStyle()->right());
}
void StyleBuilderFunctions::applyValueCSSPropertyRight(StyleResolverState& state, CSSValue* value)
{
state.style()->setRight(StyleBuilderConverter::convertLengthOrAuto(state, value));
}
void StyleBuilderFunctions::applyInitialCSSPropertyGridColumnEnd(StyleResolverState& state)
{
state.style()->setGridColumnEnd(RenderStyle::initialGridColumnEnd());
}
void StyleBuilderFunctions::applyInheritCSSPropertyGridColumnEnd(StyleResolverState& state)
{
state.style()->setGridColumnEnd(state.parentStyle()->gridColumnEnd());
}
void StyleBuilderFunctions::applyValueCSSPropertyGridColumnEnd(StyleResolverState& state, CSSValue* value)
{
state.style()->setGridColumnEnd(StyleBuilderConverter::convertGridPosition(state, value));
}
void StyleBuilderFunctions::applyInitialCSSPropertyDirection(StyleResolverState& state)
{
state.style()->setDirection(RenderStyle::initialDirection());
}
void StyleBuilderFunctions::applyInheritCSSPropertyDirection(StyleResolverState& state)
{
state.style()->setDirection(state.parentStyle()->direction());
}
void StyleBuilderFunctions::applyInitialCSSPropertyInternalMarqueeRepetition(StyleResolverState& state)
{
state.style()->setMarqueeLoopCount(RenderStyle::initialMarqueeLoopCount());
}
void StyleBuilderFunctions::applyInheritCSSPropertyInternalMarqueeRepetition(StyleResolverState& state)
{
state.style()->setMarqueeLoopCount(state.parentStyle()->marqueeLoopCount());
}
void StyleBuilderFunctions::applyInitialCSSPropertyWebkitBackfaceVisibility(StyleResolverState& state)
{
state.style()->setBackfaceVisibility(RenderStyle::initialBackfaceVisibility());
}
void StyleBuilderFunctions::applyInheritCSSPropertyWebkitBackfaceVisibility(StyleResolverState& state)
{
state.style()->setBackfaceVisibility(state.parentStyle()->backfaceVisibility());
}
void StyleBuilderFunctions::applyValueCSSPropertyWebkitBackfaceVisibility(StyleResolverState& state, CSSValue* value)
{
state.style()->setBackfaceVisibility(static_cast<EBackfaceVisibility>(*toCSSPrimitiveValue(value)));
}
void StyleBuilderFunctions::applyInitialCSSPropertyWebkitBorderImage(StyleResolverState& state)
{
state.style()->setBorderImage(RenderStyle::initialNinePieceImage());
}
void StyleBuilderFunctions::applyInheritCSSPropertyWebkitBorderImage(StyleResolverState& state)
{
state.style()->setBorderImage(state.parentStyle()->borderImage());
}
void StyleBuilderFunctions::applyInitialCSSPropertyWebkitBorderVerticalSpacing(StyleResolverState& state)
{
state.style()->setVerticalBorderSpacing(RenderStyle::initialVerticalBorderSpacing());
}
void StyleBuilderFunctions::applyInheritCSSPropertyWebkitBorderVerticalSpacing(StyleResolverState& state)
{
state.style()->setVerticalBorderSpacing(state.parentStyle()->verticalBorderSpacing());
}
void StyleBuilderFunctions::applyValueCSSPropertyWebkitBorderVerticalSpacing(StyleResolverState& state, CSSValue* value)
{
state.style()->setVerticalBorderSpacing(StyleBuilderConverter::convertComputedLength<short>(state, value));
}
void StyleBuilderFunctions::applyInitialCSSPropertyMarginLeft(StyleResolverState& state)
{
state.style()->setMarginLeft(RenderStyle::initialMargin());
}
void StyleBuilderFunctions::applyInheritCSSPropertyMarginLeft(StyleResolverState& state)
{
state.style()->setMarginLeft(state.parentStyle()->marginLeft());
}
void StyleBuilderFunctions::applyValueCSSPropertyMarginLeft(StyleResolverState& state, CSSValue* value)
{
state.style()->setMarginLeft(StyleBuilderConverter::convertLengthOrAuto(state, value));
}
void StyleBuilderFunctions::applyInitialCSSPropertyFlexWrap(StyleResolverState& state)
{
state.style()->setFlexWrap(RenderStyle::initialFlexWrap());
}
void StyleBuilderFunctions::applyInheritCSSPropertyFlexWrap(StyleResolverState& state)
{
state.style()->setFlexWrap(state.parentStyle()->flexWrap());
}
void StyleBuilderFunctions::applyValueCSSPropertyFlexWrap(StyleResolverState& state, CSSValue* value)
{
state.style()->setFlexWrap(static_cast<EFlexWrap>(*toCSSPrimitiveValue(value)));
}
void StyleBuilderFunctions::applyInitialCSSPropertyMinHeight(StyleResolverState& state)
{
state.style()->setMinHeight(RenderStyle::initialMinSize());
}
void StyleBuilderFunctions::applyInheritCSSPropertyMinHeight(StyleResolverState& state)
{
state.style()->setMinHeight(state.parentStyle()->minHeight());
}
void StyleBuilderFunctions::applyValueCSSPropertyMinHeight(StyleResolverState& state, CSSValue* value)
{
state.style()->setMinHeight(StyleBuilderConverter::convertLengthSizing(state, value));
}
void StyleBuilderFunctions::applyInitialCSSPropertyFloodColor(StyleResolverState& state)
{
state.style()->accessSVGStyle()->setFloodColor(SVGRenderStyle::initialFloodColor());
}
void StyleBuilderFunctions::applyInheritCSSPropertyFloodColor(StyleResolverState& state)
{
state.style()->accessSVGStyle()->setFloodColor(state.parentStyle()->svgStyle()->floodColor());
}
void StyleBuilderFunctions::applyValueCSSPropertyFloodColor(StyleResolverState& state, CSSValue* value)
{
state.style()->accessSVGStyle()->setFloodColor(StyleBuilderConverter::convertSVGColor(state, value));
}
void StyleBuilderFunctions::applyInitialCSSPropertyMaxHeight(StyleResolverState& state)
{
state.style()->setMaxHeight(RenderStyle::initialMaxSize());
}
void StyleBuilderFunctions::applyInheritCSSPropertyMaxHeight(StyleResolverState& state)
{
state.style()->setMaxHeight(state.parentStyle()->maxHeight());
}
void StyleBuilderFunctions::applyValueCSSPropertyMaxHeight(StyleResolverState& state, CSSValue* value)
{
state.style()->setMaxHeight(StyleBuilderConverter::convertLengthMaxSizing(state, value));
}
void StyleBuilderFunctions::applyInitialCSSPropertyBufferedRendering(StyleResolverState& state)
{
state.style()->accessSVGStyle()->setBufferedRendering(SVGRenderStyle::initialBufferedRendering());
}
void StyleBuilderFunctions::applyInheritCSSPropertyBufferedRendering(StyleResolverState& state)
{
state.style()->accessSVGStyle()->setBufferedRendering(state.parentStyle()->svgStyle()->bufferedRendering());
}
void StyleBuilderFunctions::applyValueCSSPropertyBufferedRendering(StyleResolverState& state, CSSValue* value)
{
state.style()->accessSVGStyle()->setBufferedRendering(static_cast<EBufferedRendering>(*toCSSPrimitiveValue(value)));
}
void StyleBuilderFunctions::applyInitialCSSPropertyWebkitWritingMode(StyleResolverState& state)
{
state.style()->setWritingMode(RenderStyle::initialWritingMode());
}
void StyleBuilderFunctions::applyInheritCSSPropertyWebkitWritingMode(StyleResolverState& state)
{
state.style()->setWritingMode(state.parentStyle()->writingMode());
}
void StyleBuilderFunctions::applyInitialCSSPropertyAlignmentBaseline(StyleResolverState& state)
{
state.style()->accessSVGStyle()->setAlignmentBaseline(SVGRenderStyle::initialAlignmentBaseline());
}
void StyleBuilderFunctions::applyInheritCSSPropertyAlignmentBaseline(StyleResolverState& state)
{
state.style()->accessSVGStyle()->setAlignmentBaseline(state.parentStyle()->svgStyle()->alignmentBaseline());
}
void StyleBuilderFunctions::applyValueCSSPropertyAlignmentBaseline(StyleResolverState& state, CSSValue* value)
{
state.style()->accessSVGStyle()->setAlignmentBaseline(static_cast<EAlignmentBaseline>(*toCSSPrimitiveValue(value)));
}
void StyleBuilderFunctions::applyInitialCSSPropertyWebkitWrapFlow(StyleResolverState& state)
{
state.style()->setWrapFlow(RenderStyle::initialWrapFlow());
}
void StyleBuilderFunctions::applyInheritCSSPropertyWebkitWrapFlow(StyleResolverState& state)
{
state.style()->setWrapFlow(state.parentStyle()->wrapFlow());
}
void StyleBuilderFunctions::applyValueCSSPropertyWebkitWrapFlow(StyleResolverState& state, CSSValue* value)
{
state.style()->setWrapFlow(static_cast<WrapFlow>(*toCSSPrimitiveValue(value)));
}
void StyleBuilderFunctions::applyInitialCSSPropertyMinWidth(StyleResolverState& state)
{
state.style()->setMinWidth(RenderStyle::initialMinSize());
}
void StyleBuilderFunctions::applyInheritCSSPropertyMinWidth(StyleResolverState& state)
{
state.style()->setMinWidth(state.parentStyle()->minWidth());
}
void StyleBuilderFunctions::applyValueCSSPropertyMinWidth(StyleResolverState& state, CSSValue* value)
{
state.style()->setMinWidth(StyleBuilderConverter::convertLengthSizing(state, value));
}
void StyleBuilderFunctions::applyInitialCSSPropertyMaskType(StyleResolverState& state)
{
state.style()->accessSVGStyle()->setMaskType(SVGRenderStyle::initialMaskType());
}
void StyleBuilderFunctions::applyInheritCSSPropertyMaskType(StyleResolverState& state)
{
state.style()->accessSVGStyle()->setMaskType(state.parentStyle()->svgStyle()->maskType());
}
void StyleBuilderFunctions::applyValueCSSPropertyMaskType(StyleResolverState& state, CSSValue* value)
{
state.style()->accessSVGStyle()->setMaskType(static_cast<EMaskType>(*toCSSPrimitiveValue(value)));
}
void StyleBuilderFunctions::applyInitialCSSPropertyWebkitColumnRuleStyle(StyleResolverState& state)
{
state.style()->setColumnRuleStyle(RenderStyle::initialBorderStyle());
}
void StyleBuilderFunctions::applyInheritCSSPropertyWebkitColumnRuleStyle(StyleResolverState& state)
{
state.style()->setColumnRuleStyle(state.parentStyle()->columnRuleStyle());
}
void StyleBuilderFunctions::applyValueCSSPropertyWebkitColumnRuleStyle(StyleResolverState& state, CSSValue* value)
{
state.style()->setColumnRuleStyle(static_cast<EBorderStyle>(*toCSSPrimitiveValue(value)));
}
void StyleBuilderFunctions::applyInitialCSSPropertyWebkitPerspectiveOriginY(StyleResolverState& state)
{
state.style()->setPerspectiveOriginY(RenderStyle::initialPerspectiveOriginY());
}
void StyleBuilderFunctions::applyInheritCSSPropertyWebkitPerspectiveOriginY(StyleResolverState& state)
{
state.style()->setPerspectiveOriginY(state.parentStyle()->perspectiveOriginY());
}
void StyleBuilderFunctions::applyValueCSSPropertyWebkitPerspectiveOriginY(StyleResolverState& state, CSSValue* value)
{
state.style()->setPerspectiveOriginY(StyleBuilderConverter::convertLength(state, value));
}
void StyleBuilderFunctions::applyInitialCSSPropertyTextAlignLast(StyleResolverState& state)
{
state.style()->setTextAlignLast(RenderStyle::initialTextAlignLast());
}
void StyleBuilderFunctions::applyInheritCSSPropertyTextAlignLast(StyleResolverState& state)
{
state.style()->setTextAlignLast(state.parentStyle()->textAlignLast());
}
void StyleBuilderFunctions::applyValueCSSPropertyTextAlignLast(StyleResolverState& state, CSSValue* value)
{
state.style()->setTextAlignLast(static_cast<TextAlignLast>(*toCSSPrimitiveValue(value)));
}
void StyleBuilderFunctions::applyInitialCSSPropertyWebkitMarginTopCollapse(StyleResolverState& state)
{
state.style()->setMarginBeforeCollapse(RenderStyle::initialMarginBeforeCollapse());
}
void StyleBuilderFunctions::applyInheritCSSPropertyWebkitMarginTopCollapse(StyleResolverState& state)
{
state.style()->setMarginBeforeCollapse(state.parentStyle()->marginBeforeCollapse());
}
void StyleBuilderFunctions::applyValueCSSPropertyWebkitMarginTopCollapse(StyleResolverState& state, CSSValue* value)
{
state.style()->setMarginBeforeCollapse(static_cast<EMarginCollapse>(*toCSSPrimitiveValue(value)));
}
void StyleBuilderFunctions::applyInitialCSSPropertyTabSize(StyleResolverState& state)
{
state.style()->setTabSize(RenderStyle::initialTabSize());
}
void StyleBuilderFunctions::applyInheritCSSPropertyTabSize(StyleResolverState& state)
{
state.style()->setTabSize(state.parentStyle()->tabSize());
}
void StyleBuilderFunctions::applyValueCSSPropertyTabSize(StyleResolverState& state, CSSValue* value)
{
state.style()->setTabSize(static_cast<unsigned>(*toCSSPrimitiveValue(value)));
}
void StyleBuilderFunctions::applyInitialCSSPropertyInternalMarqueeIncrement(StyleResolverState& state)
{
state.style()->setMarqueeIncrement(RenderStyle::initialMarqueeIncrement());
}
void StyleBuilderFunctions::applyInheritCSSPropertyInternalMarqueeIncrement(StyleResolverState& state)
{
state.style()->setMarqueeIncrement(state.parentStyle()->marqueeIncrement());
}
void StyleBuilderFunctions::applyInitialCSSPropertyBorderBottomWidth(StyleResolverState& state)
{
state.style()->setBorderBottomWidth(RenderStyle::initialBorderWidth());
}
void StyleBuilderFunctions::applyInheritCSSPropertyBorderBottomWidth(StyleResolverState& state)
{
state.style()->setBorderBottomWidth(state.parentStyle()->borderBottomWidth());
}
void StyleBuilderFunctions::applyValueCSSPropertyBorderBottomWidth(StyleResolverState& state, CSSValue* value)
{
state.style()->setBorderBottomWidth(StyleBuilderConverter::convertLineWidth<unsigned>(state, value));
}
void StyleBuilderFunctions::applyInitialCSSPropertyWebkitHighlight(StyleResolverState& state)
{
state.style()->setHighlight(RenderStyle::initialHighlight());
}
void StyleBuilderFunctions::applyInheritCSSPropertyWebkitHighlight(StyleResolverState& state)
{
state.style()->setHighlight(state.parentStyle()->highlight());
}
void StyleBuilderFunctions::applyValueCSSPropertyWebkitHighlight(StyleResolverState& state, CSSValue* value)
{
state.style()->setHighlight(StyleBuilderConverter::convertString<CSSValueNone>(state, value));
}
void StyleBuilderFunctions::applyInitialCSSPropertyEmptyCells(StyleResolverState& state)
{
state.style()->setEmptyCells(RenderStyle::initialEmptyCells());
}
void StyleBuilderFunctions::applyInheritCSSPropertyEmptyCells(StyleResolverState& state)
{
state.style()->setEmptyCells(state.parentStyle()->emptyCells());
}
void StyleBuilderFunctions::applyValueCSSPropertyEmptyCells(StyleResolverState& state, CSSValue* value)
{
state.style()->setEmptyCells(static_cast<EEmptyCell>(*toCSSPrimitiveValue(value)));
}
void StyleBuilderFunctions::applyInitialCSSPropertyBorderImageSource(StyleResolverState& state)
{
state.style()->setBorderImageSource(RenderStyle::initialBorderImageSource());
}
void StyleBuilderFunctions::applyInheritCSSPropertyBorderImageSource(StyleResolverState& state)
{
state.style()->setBorderImageSource(state.parentStyle()->borderImageSource());
}
void StyleBuilderFunctions::applyInitialCSSPropertyInternalMarqueeStyle(StyleResolverState& state)
{
state.style()->setMarqueeBehavior(RenderStyle::initialMarqueeBehavior());
}
void StyleBuilderFunctions::applyInheritCSSPropertyInternalMarqueeStyle(StyleResolverState& state)
{
state.style()->setMarqueeBehavior(state.parentStyle()->marqueeBehavior());
}
void StyleBuilderFunctions::applyValueCSSPropertyInternalMarqueeStyle(StyleResolverState& state, CSSValue* value)
{
state.style()->setMarqueeBehavior(static_cast<EMarqueeBehavior>(*toCSSPrimitiveValue(value)));
}
void StyleBuilderFunctions::applyInitialCSSPropertyTextOverflow(StyleResolverState& state)
{
state.style()->setTextOverflow(RenderStyle::initialTextOverflow());
}
void StyleBuilderFunctions::applyInheritCSSPropertyTextOverflow(StyleResolverState& state)
{
state.style()->setTextOverflow(state.parentStyle()->textOverflow());
}
void StyleBuilderFunctions::applyValueCSSPropertyTextOverflow(StyleResolverState& state, CSSValue* value)
{
state.style()->setTextOverflow(static_cast<TextOverflow>(*toCSSPrimitiveValue(value)));
}
void StyleBuilderFunctions::applyInitialCSSPropertyBoxSizing(StyleResolverState& state)
{
state.style()->setBoxSizing(RenderStyle::initialBoxSizing());
}
void StyleBuilderFunctions::applyInheritCSSPropertyBoxSizing(StyleResolverState& state)
{
state.style()->setBoxSizing(state.parentStyle()->boxSizing());
}
void StyleBuilderFunctions::applyValueCSSPropertyBoxSizing(StyleResolverState& state, CSSValue* value)
{
state.style()->setBoxSizing(static_cast<EBoxSizing>(*toCSSPrimitiveValue(value)));
}
void StyleBuilderFunctions::applyInitialCSSPropertyStrokeWidth(StyleResolverState& state)
{
state.style()->accessSVGStyle()->setStrokeWidth(SVGRenderStyle::initialStrokeWidth());
}
void StyleBuilderFunctions::applyInheritCSSPropertyStrokeWidth(StyleResolverState& state)
{
state.style()->accessSVGStyle()->setStrokeWidth(state.parentStyle()->svgStyle()->strokeWidth());
}
void StyleBuilderFunctions::applyValueCSSPropertyStrokeWidth(StyleResolverState& state, CSSValue* value)
{
state.style()->accessSVGStyle()->setStrokeWidth(StyleBuilderConverter::convertSVGLength(state, value));
}
void StyleBuilderFunctions::applyInitialCSSPropertyMarkerStart(StyleResolverState& state)
{
state.style()->accessSVGStyle()->setMarkerStartResource(SVGRenderStyle::initialMarkerStartResource());
}
void StyleBuilderFunctions::applyInheritCSSPropertyMarkerStart(StyleResolverState& state)
{
state.style()->accessSVGStyle()->setMarkerStartResource(state.parentStyle()->svgStyle()->markerStartResource());
}
void StyleBuilderFunctions::applyValueCSSPropertyMarkerStart(StyleResolverState& state, CSSValue* value)
{
state.style()->accessSVGStyle()->setMarkerStartResource(StyleBuilderConverter::convertFragmentIdentifier(state, value));
}
void StyleBuilderFunctions::applyInitialCSSPropertyTextDecorationStyle(StyleResolverState& state)
{
state.style()->setTextDecorationStyle(RenderStyle::initialTextDecorationStyle());
}
void StyleBuilderFunctions::applyInheritCSSPropertyTextDecorationStyle(StyleResolverState& state)
{
state.style()->setTextDecorationStyle(state.parentStyle()->textDecorationStyle());
}
void StyleBuilderFunctions::applyValueCSSPropertyTextDecorationStyle(StyleResolverState& state, CSSValue* value)
{
state.style()->setTextDecorationStyle(static_cast<TextDecorationStyle>(*toCSSPrimitiveValue(value)));
}
void StyleBuilderFunctions::applyInitialCSSPropertyPaddingTop(StyleResolverState& state)
{
state.style()->setPaddingTop(RenderStyle::initialPadding());
}
void StyleBuilderFunctions::applyInheritCSSPropertyPaddingTop(StyleResolverState& state)
{
state.style()->setPaddingTop(state.parentStyle()->paddingTop());
}
void StyleBuilderFunctions::applyValueCSSPropertyPaddingTop(StyleResolverState& state, CSSValue* value)
{
state.style()->setPaddingTop(StyleBuilderConverter::convertLength(state, value));
}
void StyleBuilderFunctions::applyInitialCSSPropertyDisplay(StyleResolverState& state)
{
state.style()->setDisplay(RenderStyle::initialDisplay());
}
void StyleBuilderFunctions::applyInitialCSSPropertyWordBreak(StyleResolverState& state)
{
state.style()->setWordBreak(RenderStyle::initialWordBreak());
}
void StyleBuilderFunctions::applyInheritCSSPropertyWordBreak(StyleResolverState& state)
{
state.style()->setWordBreak(state.parentStyle()->wordBreak());
}
void StyleBuilderFunctions::applyValueCSSPropertyWordBreak(StyleResolverState& state, CSSValue* value)
{
state.style()->setWordBreak(static_cast<EWordBreak>(*toCSSPrimitiveValue(value)));
}
void StyleBuilderFunctions::applyInitialCSSPropertyBorderTopStyle(StyleResolverState& state)
{
state.style()->setBorderTopStyle(RenderStyle::initialBorderStyle());
}
void StyleBuilderFunctions::applyInheritCSSPropertyBorderTopStyle(StyleResolverState& state)
{
state.style()->setBorderTopStyle(state.parentStyle()->borderTopStyle());
}
void StyleBuilderFunctions::applyValueCSSPropertyBorderTopStyle(StyleResolverState& state, CSSValue* value)
{
state.style()->setBorderTopStyle(static_cast<EBorderStyle>(*toCSSPrimitiveValue(value)));
}
void StyleBuilderFunctions::applyInitialCSSPropertyJustifyContent(StyleResolverState& state)
{
state.style()->setJustifyContent(RenderStyle::initialJustifyContent());
}
void StyleBuilderFunctions::applyInheritCSSPropertyJustifyContent(StyleResolverState& state)
{
state.style()->setJustifyContent(state.parentStyle()->justifyContent());
}
void StyleBuilderFunctions::applyValueCSSPropertyJustifyContent(StyleResolverState& state, CSSValue* value)
{
state.style()->setJustifyContent(static_cast<EJustifyContent>(*toCSSPrimitiveValue(value)));
}
void StyleBuilderFunctions::applyInitialCSSPropertyBoxShadow(StyleResolverState& state)
{
state.style()->setBoxShadow(RenderStyle::initialBoxShadow());
}
void StyleBuilderFunctions::applyInheritCSSPropertyBoxShadow(StyleResolverState& state)
{
state.style()->setBoxShadow(state.parentStyle()->boxShadow());
}
void StyleBuilderFunctions::applyValueCSSPropertyBoxShadow(StyleResolverState& state, CSSValue* value)
{
state.style()->setBoxShadow(StyleBuilderConverter::convertShadow(state, value));
}
void StyleBuilderFunctions::applyInitialCSSPropertySpeak(StyleResolverState& state)
{
state.style()->setSpeak(RenderStyle::initialSpeak());
}
void StyleBuilderFunctions::applyInheritCSSPropertySpeak(StyleResolverState& state)
{
state.style()->setSpeak(state.parentStyle()->speak());
}
void StyleBuilderFunctions::applyValueCSSPropertySpeak(StyleResolverState& state, CSSValue* value)
{
state.style()->setSpeak(static_cast<ESpeak>(*toCSSPrimitiveValue(value)));
}
void StyleBuilderFunctions::applyInitialCSSPropertyListStyleImage(StyleResolverState& state)
{
state.style()->setListStyleImage(RenderStyle::initialListStyleImage());
}
void StyleBuilderFunctions::applyInheritCSSPropertyListStyleImage(StyleResolverState& state)
{
state.style()->setListStyleImage(state.parentStyle()->listStyleImage());
}
void StyleBuilderFunctions::applyInitialCSSPropertyFloodOpacity(StyleResolverState& state)
{
state.style()->accessSVGStyle()->setFloodOpacity(SVGRenderStyle::initialFloodOpacity());
}
void StyleBuilderFunctions::applyInheritCSSPropertyFloodOpacity(StyleResolverState& state)
{
state.style()->accessSVGStyle()->setFloodOpacity(state.parentStyle()->svgStyle()->floodOpacity());
}
void StyleBuilderFunctions::applyValueCSSPropertyFloodOpacity(StyleResolverState& state, CSSValue* value)
{
state.style()->accessSVGStyle()->setFloodOpacity(StyleBuilderConverter::convertNumberOrPercentage(state, value));
}
void StyleBuilderFunctions::applyInitialCSSPropertyClipRule(StyleResolverState& state)
{
state.style()->accessSVGStyle()->setClipRule(SVGRenderStyle::initialClipRule());
}
void StyleBuilderFunctions::applyInheritCSSPropertyClipRule(StyleResolverState& state)
{
state.style()->accessSVGStyle()->setClipRule(state.parentStyle()->svgStyle()->clipRule());
}
void StyleBuilderFunctions::applyValueCSSPropertyClipRule(StyleResolverState& state, CSSValue* value)
{
state.style()->accessSVGStyle()->setClipRule(static_cast<WindRule>(*toCSSPrimitiveValue(value)));
}
void StyleBuilderFunctions::applyInitialCSSPropertyFlexDirection(StyleResolverState& state)
{
state.style()->setFlexDirection(RenderStyle::initialFlexDirection());
}
void StyleBuilderFunctions::applyInheritCSSPropertyFlexDirection(StyleResolverState& state)
{
state.style()->setFlexDirection(state.parentStyle()->flexDirection());
}
void StyleBuilderFunctions::applyValueCSSPropertyFlexDirection(StyleResolverState& state, CSSValue* value)
{
state.style()->setFlexDirection(static_cast<EFlexDirection>(*toCSSPrimitiveValue(value)));
}
void StyleBuilderFunctions::applyInitialCSSPropertyLightingColor(StyleResolverState& state)
{
state.style()->accessSVGStyle()->setLightingColor(SVGRenderStyle::initialLightingColor());
}
void StyleBuilderFunctions::applyInheritCSSPropertyLightingColor(StyleResolverState& state)
{
state.style()->accessSVGStyle()->setLightingColor(state.parentStyle()->svgStyle()->lightingColor());
}
void StyleBuilderFunctions::applyValueCSSPropertyLightingColor(StyleResolverState& state, CSSValue* value)
{
state.style()->accessSVGStyle()->setLightingColor(StyleBuilderConverter::convertSVGColor(state, value));
}
void StyleBuilderFunctions::applyInitialCSSPropertyPageBreakInside(StyleResolverState& state)
{
state.style()->setPageBreakInside(RenderStyle::initialPageBreak());
}
void StyleBuilderFunctions::applyInheritCSSPropertyPageBreakInside(StyleResolverState& state)
{
state.style()->setPageBreakInside(state.parentStyle()->pageBreakInside());
}
void StyleBuilderFunctions::applyValueCSSPropertyPageBreakInside(StyleResolverState& state, CSSValue* value)
{
state.style()->setPageBreakInside(static_cast<EPageBreak>(*toCSSPrimitiveValue(value)));
}
void StyleBuilderFunctions::applyInitialCSSPropertyListStyleType(StyleResolverState& state)
{
state.style()->setListStyleType(RenderStyle::initialListStyleType());
}
void StyleBuilderFunctions::applyInheritCSSPropertyListStyleType(StyleResolverState& state)
{
state.style()->setListStyleType(state.parentStyle()->listStyleType());
}
void StyleBuilderFunctions::applyValueCSSPropertyListStyleType(StyleResolverState& state, CSSValue* value)
{
state.style()->setListStyleType(static_cast<EListStyleType>(*toCSSPrimitiveValue(value)));
}
void StyleBuilderFunctions::applyInitialCSSPropertyTextAlign(StyleResolverState& state)
{
state.style()->setTextAlign(RenderStyle::initialTextAlign());
}
void StyleBuilderFunctions::applyInheritCSSPropertyTextAlign(StyleResolverState& state)
{
state.style()->setTextAlign(state.parentStyle()->textAlign());
}
void StyleBuilderFunctions::applyInitialCSSPropertyAlignItems(StyleResolverState& state)
{
state.style()->setAlignItems(RenderStyle::initialAlignItems());
}
void StyleBuilderFunctions::applyInheritCSSPropertyAlignItems(StyleResolverState& state)
{
state.style()->setAlignItems(state.parentStyle()->alignItems());
}
void StyleBuilderFunctions::applyInitialCSSPropertyObjectPosition(StyleResolverState& state)
{
state.style()->setObjectPosition(RenderStyle::initialObjectPosition());
}
void StyleBuilderFunctions::applyInheritCSSPropertyObjectPosition(StyleResolverState& state)
{
state.style()->setObjectPosition(state.parentStyle()->objectPosition());
}
void StyleBuilderFunctions::applyValueCSSPropertyObjectPosition(StyleResolverState& state, CSSValue* value)
{
state.style()->setObjectPosition(StyleBuilderConverter::convertLengthPoint(state, value));
}
void StyleBuilderFunctions::applyInitialCSSPropertyWebkitBoxFlexGroup(StyleResolverState& state)
{
state.style()->setBoxFlexGroup(RenderStyle::initialBoxFlexGroup());
}
void StyleBuilderFunctions::applyInheritCSSPropertyWebkitBoxFlexGroup(StyleResolverState& state)
{
state.style()->setBoxFlexGroup(state.parentStyle()->boxFlexGroup());
}
void StyleBuilderFunctions::applyValueCSSPropertyWebkitBoxFlexGroup(StyleResolverState& state, CSSValue* value)
{
state.style()->setBoxFlexGroup(static_cast<unsigned int>(*toCSSPrimitiveValue(value)));
}
void StyleBuilderFunctions::applyInitialCSSPropertyWebkitPerspectiveOriginX(StyleResolverState& state)
{
state.style()->setPerspectiveOriginX(RenderStyle::initialPerspectiveOriginX());
}
void StyleBuilderFunctions::applyInheritCSSPropertyWebkitPerspectiveOriginX(StyleResolverState& state)
{
state.style()->setPerspectiveOriginX(state.parentStyle()->perspectiveOriginX());
}
void StyleBuilderFunctions::applyValueCSSPropertyWebkitPerspectiveOriginX(StyleResolverState& state, CSSValue* value)
{
state.style()->setPerspectiveOriginX(StyleBuilderConverter::convertLength(state, value));
}
void StyleBuilderFunctions::applyInitialCSSPropertyVisibility(StyleResolverState& state)
{
state.style()->setVisibility(RenderStyle::initialVisibility());
}
void StyleBuilderFunctions::applyInheritCSSPropertyVisibility(StyleResolverState& state)
{
state.style()->setVisibility(state.parentStyle()->visibility());
}
void StyleBuilderFunctions::applyValueCSSPropertyVisibility(StyleResolverState& state, CSSValue* value)
{
state.style()->setVisibility(static_cast<EVisibility>(*toCSSPrimitiveValue(value)));
}
void StyleBuilderFunctions::applyInitialCSSPropertyWebkitAnimationDelay(StyleResolverState& state)
{
CSSAnimationData& data = state.style()->accessAnimations();
data.delayList().clear();
data.delayList().append(CSSAnimationData::initialDelay());
}
void StyleBuilderFunctions::applyInheritCSSPropertyWebkitAnimationDelay(StyleResolverState& state)
{
const CSSAnimationData* parentData = state.parentStyle()->animations();
if (!parentData)
applyInitialCSSPropertyWebkitAnimationDelay(state);
else
state.style()->accessAnimations().delayList() = parentData->delayList();
}
void StyleBuilderFunctions::applyValueCSSPropertyWebkitAnimationDelay(StyleResolverState& state, CSSValue* value)
{
CSSAnimationData& data = state.style()->accessAnimations();
data.delayList().clear();
for (CSSValueListIterator i = value; i.hasMore(); i.advance())
data.delayList().append(state.styleMap().mapAnimationDelay(i.value()));
}
void StyleBuilderFunctions::applyInitialCSSPropertyWebkitAnimationDirection(StyleResolverState& state)
{
CSSAnimationData& data = state.style()->accessAnimations();
data.directionList().clear();
data.directionList().append(CSSAnimationData::initialDirection());
}
void StyleBuilderFunctions::applyInheritCSSPropertyWebkitAnimationDirection(StyleResolverState& state)
{
const CSSAnimationData* parentData = state.parentStyle()->animations();
if (!parentData)
applyInitialCSSPropertyWebkitAnimationDirection(state);
else
state.style()->accessAnimations().directionList() = parentData->directionList();
}
void StyleBuilderFunctions::applyValueCSSPropertyWebkitAnimationDirection(StyleResolverState& state, CSSValue* value)
{
CSSAnimationData& data = state.style()->accessAnimations();
data.directionList().clear();
for (CSSValueListIterator i = value; i.hasMore(); i.advance())
data.directionList().append(state.styleMap().mapAnimationDirection(i.value()));
}
void StyleBuilderFunctions::applyInitialCSSPropertyWebkitAnimationDuration(StyleResolverState& state)
{
CSSAnimationData& data = state.style()->accessAnimations();
data.durationList().clear();
data.durationList().append(CSSAnimationData::initialDuration());
}
void StyleBuilderFunctions::applyInheritCSSPropertyWebkitAnimationDuration(StyleResolverState& state)
{
const CSSAnimationData* parentData = state.parentStyle()->animations();
if (!parentData)
applyInitialCSSPropertyWebkitAnimationDuration(state);
else
state.style()->accessAnimations().durationList() = parentData->durationList();
}
void StyleBuilderFunctions::applyValueCSSPropertyWebkitAnimationDuration(StyleResolverState& state, CSSValue* value)
{
CSSAnimationData& data = state.style()->accessAnimations();
data.durationList().clear();
for (CSSValueListIterator i = value; i.hasMore(); i.advance())
data.durationList().append(state.styleMap().mapAnimationDuration(i.value()));
}
void StyleBuilderFunctions::applyInitialCSSPropertyWebkitAnimationFillMode(StyleResolverState& state)
{
CSSAnimationData& data = state.style()->accessAnimations();
data.fillModeList().clear();
data.fillModeList().append(CSSAnimationData::initialFillMode());
}
void StyleBuilderFunctions::applyInheritCSSPropertyWebkitAnimationFillMode(StyleResolverState& state)
{
const CSSAnimationData* parentData = state.parentStyle()->animations();
if (!parentData)
applyInitialCSSPropertyWebkitAnimationFillMode(state);
else
state.style()->accessAnimations().fillModeList() = parentData->fillModeList();
}
void StyleBuilderFunctions::applyValueCSSPropertyWebkitAnimationFillMode(StyleResolverState& state, CSSValue* value)
{
CSSAnimationData& data = state.style()->accessAnimations();
data.fillModeList().clear();
for (CSSValueListIterator i = value; i.hasMore(); i.advance())
data.fillModeList().append(state.styleMap().mapAnimationFillMode(i.value()));
}
void StyleBuilderFunctions::applyInitialCSSPropertyWebkitAnimationIterationCount(StyleResolverState& state)
{
CSSAnimationData& data = state.style()->accessAnimations();
data.iterationCountList().clear();
data.iterationCountList().append(CSSAnimationData::initialIterationCount());
}
void StyleBuilderFunctions::applyInheritCSSPropertyWebkitAnimationIterationCount(StyleResolverState& state)
{
const CSSAnimationData* parentData = state.parentStyle()->animations();
if (!parentData)
applyInitialCSSPropertyWebkitAnimationIterationCount(state);
else
state.style()->accessAnimations().iterationCountList() = parentData->iterationCountList();
}
void StyleBuilderFunctions::applyValueCSSPropertyWebkitAnimationIterationCount(StyleResolverState& state, CSSValue* value)
{
CSSAnimationData& data = state.style()->accessAnimations();
data.iterationCountList().clear();
for (CSSValueListIterator i = value; i.hasMore(); i.advance())
data.iterationCountList().append(state.styleMap().mapAnimationIterationCount(i.value()));
}
void StyleBuilderFunctions::applyInitialCSSPropertyWebkitAnimationName(StyleResolverState& state)
{
CSSAnimationData& data = state.style()->accessAnimations();
data.nameList().clear();
data.nameList().append(CSSAnimationData::initialName());
}
void StyleBuilderFunctions::applyInheritCSSPropertyWebkitAnimationName(StyleResolverState& state)
{
const CSSAnimationData* parentData = state.parentStyle()->animations();
if (!parentData)
applyInitialCSSPropertyWebkitAnimationName(state);
else
state.style()->accessAnimations().nameList() = parentData->nameList();
}
void StyleBuilderFunctions::applyValueCSSPropertyWebkitAnimationName(StyleResolverState& state, CSSValue* value)
{
CSSAnimationData& data = state.style()->accessAnimations();
data.nameList().clear();
for (CSSValueListIterator i = value; i.hasMore(); i.advance())
data.nameList().append(state.styleMap().mapAnimationName(i.value()));
}
void StyleBuilderFunctions::applyInitialCSSPropertyWebkitAnimationPlayState(StyleResolverState& state)
{
CSSAnimationData& data = state.style()->accessAnimations();
data.playStateList().clear();
data.playStateList().append(CSSAnimationData::initialPlayState());
}
void StyleBuilderFunctions::applyInheritCSSPropertyWebkitAnimationPlayState(StyleResolverState& state)
{
const CSSAnimationData* parentData = state.parentStyle()->animations();
if (!parentData)
applyInitialCSSPropertyWebkitAnimationPlayState(state);
else
state.style()->accessAnimations().playStateList() = parentData->playStateList();
}
void StyleBuilderFunctions::applyValueCSSPropertyWebkitAnimationPlayState(StyleResolverState& state, CSSValue* value)
{
CSSAnimationData& data = state.style()->accessAnimations();
data.playStateList().clear();
for (CSSValueListIterator i = value; i.hasMore(); i.advance())
data.playStateList().append(state.styleMap().mapAnimationPlayState(i.value()));
}
void StyleBuilderFunctions::applyInitialCSSPropertyWebkitAnimationTimingFunction(StyleResolverState& state)
{
CSSAnimationData& data = state.style()->accessAnimations();
data.timingFunctionList().clear();
data.timingFunctionList().append(CSSAnimationData::initialTimingFunction());
}
void StyleBuilderFunctions::applyInheritCSSPropertyWebkitAnimationTimingFunction(StyleResolverState& state)
{
const CSSAnimationData* parentData = state.parentStyle()->animations();
if (!parentData)
applyInitialCSSPropertyWebkitAnimationTimingFunction(state);
else
state.style()->accessAnimations().timingFunctionList() = parentData->timingFunctionList();
}
void StyleBuilderFunctions::applyValueCSSPropertyWebkitAnimationTimingFunction(StyleResolverState& state, CSSValue* value)
{
CSSAnimationData& data = state.style()->accessAnimations();
data.timingFunctionList().clear();
for (CSSValueListIterator i = value; i.hasMore(); i.advance())
data.timingFunctionList().append(state.styleMap().mapAnimationTimingFunction(i.value()));
}
void StyleBuilderFunctions::applyInitialCSSPropertyWebkitTransitionDelay(StyleResolverState& state)
{
CSSTransitionData& data = state.style()->accessTransitions();
data.delayList().clear();
data.delayList().append(CSSTransitionData::initialDelay());
}
void StyleBuilderFunctions::applyInheritCSSPropertyWebkitTransitionDelay(StyleResolverState& state)
{
const CSSTransitionData* parentData = state.parentStyle()->transitions();
if (!parentData)
applyInitialCSSPropertyWebkitTransitionDelay(state);
else
state.style()->accessTransitions().delayList() = parentData->delayList();
}
void StyleBuilderFunctions::applyValueCSSPropertyWebkitTransitionDelay(StyleResolverState& state, CSSValue* value)
{
CSSTransitionData& data = state.style()->accessTransitions();
data.delayList().clear();
for (CSSValueListIterator i = value; i.hasMore(); i.advance())
data.delayList().append(state.styleMap().mapAnimationDelay(i.value()));
}
void StyleBuilderFunctions::applyInitialCSSPropertyWebkitTransitionDuration(StyleResolverState& state)
{
CSSTransitionData& data = state.style()->accessTransitions();
data.durationList().clear();
data.durationList().append(CSSTransitionData::initialDuration());
}
void StyleBuilderFunctions::applyInheritCSSPropertyWebkitTransitionDuration(StyleResolverState& state)
{
const CSSTransitionData* parentData = state.parentStyle()->transitions();
if (!parentData)
applyInitialCSSPropertyWebkitTransitionDuration(state);
else
state.style()->accessTransitions().durationList() = parentData->durationList();
}
void StyleBuilderFunctions::applyValueCSSPropertyWebkitTransitionDuration(StyleResolverState& state, CSSValue* value)
{
CSSTransitionData& data = state.style()->accessTransitions();
data.durationList().clear();
for (CSSValueListIterator i = value; i.hasMore(); i.advance())
data.durationList().append(state.styleMap().mapAnimationDuration(i.value()));
}
void StyleBuilderFunctions::applyInitialCSSPropertyWebkitTransitionProperty(StyleResolverState& state)
{
CSSTransitionData& data = state.style()->accessTransitions();
data.propertyList().clear();
data.propertyList().append(CSSTransitionData::initialProperty());
}
void StyleBuilderFunctions::applyInheritCSSPropertyWebkitTransitionProperty(StyleResolverState& state)
{
const CSSTransitionData* parentData = state.parentStyle()->transitions();
if (!parentData)
applyInitialCSSPropertyWebkitTransitionProperty(state);
else
state.style()->accessTransitions().propertyList() = parentData->propertyList();
}
void StyleBuilderFunctions::applyValueCSSPropertyWebkitTransitionProperty(StyleResolverState& state, CSSValue* value)
{
CSSTransitionData& data = state.style()->accessTransitions();
data.propertyList().clear();
for (CSSValueListIterator i = value; i.hasMore(); i.advance())
data.propertyList().append(state.styleMap().mapAnimationProperty(i.value()));
}
void StyleBuilderFunctions::applyInitialCSSPropertyWebkitTransitionTimingFunction(StyleResolverState& state)
{
CSSTransitionData& data = state.style()->accessTransitions();
data.timingFunctionList().clear();
data.timingFunctionList().append(CSSTransitionData::initialTimingFunction());
}
void StyleBuilderFunctions::applyInheritCSSPropertyWebkitTransitionTimingFunction(StyleResolverState& state)
{
const CSSTransitionData* parentData = state.parentStyle()->transitions();
if (!parentData)
applyInitialCSSPropertyWebkitTransitionTimingFunction(state);
else
state.style()->accessTransitions().timingFunctionList() = parentData->timingFunctionList();
}
void StyleBuilderFunctions::applyValueCSSPropertyWebkitTransitionTimingFunction(StyleResolverState& state, CSSValue* value)
{
CSSTransitionData& data = state.style()->accessTransitions();
data.timingFunctionList().clear();
for (CSSValueListIterator i = value; i.hasMore(); i.advance())
data.timingFunctionList().append(state.styleMap().mapAnimationTimingFunction(i.value()));
}
void StyleBuilderFunctions::applyInitialCSSPropertyOrphans(StyleResolverState& state)
{
state.style()->setHasAutoOrphans();
}
void StyleBuilderFunctions::applyInheritCSSPropertyOrphans(StyleResolverState& state)
{
if (state.parentStyle()->hasAutoOrphans())
state.style()->setHasAutoOrphans();
else
state.style()->setOrphans(state.parentStyle()->orphans());
}
void StyleBuilderFunctions::applyValueCSSPropertyOrphans(StyleResolverState& state, CSSValue* value)
{
if (!value->isPrimitiveValue())
return;
CSSPrimitiveValue* primitiveValue = toCSSPrimitiveValue(value);
if (primitiveValue->getValueID() == CSSValueAuto)
state.style()->setHasAutoOrphans();
else
state.style()->setOrphans(*primitiveValue);
}
void StyleBuilderFunctions::applyInitialCSSPropertyWebkitColumnCount(StyleResolverState& state)
{
state.style()->setHasAutoColumnCount();
}
void StyleBuilderFunctions::applyInheritCSSPropertyWebkitColumnCount(StyleResolverState& state)
{
if (state.parentStyle()->hasAutoColumnCount())
state.style()->setHasAutoColumnCount();
else
state.style()->setColumnCount(state.parentStyle()->columnCount());
}
void StyleBuilderFunctions::applyValueCSSPropertyWebkitColumnCount(StyleResolverState& state, CSSValue* value)
{
if (!value->isPrimitiveValue())
return;
CSSPrimitiveValue* primitiveValue = toCSSPrimitiveValue(value);
if (primitiveValue->getValueID() == CSSValueAuto)
state.style()->setHasAutoColumnCount();
else
state.style()->setColumnCount(*primitiveValue);
}
void StyleBuilderFunctions::applyInitialCSSPropertyWebkitColumnGap(StyleResolverState& state)
{
state.style()->setHasNormalColumnGap();
}
void StyleBuilderFunctions::applyInheritCSSPropertyWebkitColumnGap(StyleResolverState& state)
{
if (state.parentStyle()->hasNormalColumnGap())
state.style()->setHasNormalColumnGap();
else
state.style()->setColumnGap(state.parentStyle()->columnGap());
}
void StyleBuilderFunctions::applyValueCSSPropertyWebkitColumnGap(StyleResolverState& state, CSSValue* value)
{
if (!value->isPrimitiveValue())
return;
CSSPrimitiveValue* primitiveValue = toCSSPrimitiveValue(value);
if (primitiveValue->getValueID() == CSSValueNormal)
state.style()->setHasNormalColumnGap();
else
state.style()->setColumnGap(primitiveValue->computeLength<float>(state.cssToLengthConversionData()));
}
void StyleBuilderFunctions::applyInitialCSSPropertyWebkitColumnWidth(StyleResolverState& state)
{
state.style()->setHasAutoColumnWidth();
}
void StyleBuilderFunctions::applyInheritCSSPropertyWebkitColumnWidth(StyleResolverState& state)
{
if (state.parentStyle()->hasAutoColumnWidth())
state.style()->setHasAutoColumnWidth();
else
state.style()->setColumnWidth(state.parentStyle()->columnWidth());
}
void StyleBuilderFunctions::applyValueCSSPropertyWebkitColumnWidth(StyleResolverState& state, CSSValue* value)
{
if (!value->isPrimitiveValue())
return;
CSSPrimitiveValue* primitiveValue = toCSSPrimitiveValue(value);
if (primitiveValue->getValueID() == CSSValueAuto)
state.style()->setHasAutoColumnWidth();
else
state.style()->setColumnWidth(primitiveValue->computeLength<float>(state.cssToLengthConversionData()));
}
void StyleBuilderFunctions::applyInitialCSSPropertyWidows(StyleResolverState& state)
{
state.style()->setHasAutoWidows();
}
void StyleBuilderFunctions::applyInheritCSSPropertyWidows(StyleResolverState& state)
{
if (state.parentStyle()->hasAutoWidows())
state.style()->setHasAutoWidows();
else
state.style()->setWidows(state.parentStyle()->widows());
}
void StyleBuilderFunctions::applyValueCSSPropertyWidows(StyleResolverState& state, CSSValue* value)
{
if (!value->isPrimitiveValue())
return;
CSSPrimitiveValue* primitiveValue = toCSSPrimitiveValue(value);
if (primitiveValue->getValueID() == CSSValueAuto)
state.style()->setHasAutoWidows();
else
state.style()->setWidows(*primitiveValue);
}
void StyleBuilderFunctions::applyInitialCSSPropertyZIndex(StyleResolverState& state)
{
state.style()->setHasAutoZIndex();
}
void StyleBuilderFunctions::applyInheritCSSPropertyZIndex(StyleResolverState& state)
{
if (state.parentStyle()->hasAutoZIndex())
state.style()->setHasAutoZIndex();
else
state.style()->setZIndex(state.parentStyle()->zIndex());
}
void StyleBuilderFunctions::applyValueCSSPropertyZIndex(StyleResolverState& state, CSSValue* value)
{
if (!value->isPrimitiveValue())
return;
CSSPrimitiveValue* primitiveValue = toCSSPrimitiveValue(value);
if (primitiveValue->getValueID() == CSSValueAuto)
state.style()->setHasAutoZIndex();
else
state.style()->setZIndex(*primitiveValue);
}
static bool lengthTypeAndValueMatch(const Length& length, LengthType type, float value)
{
return length.type() == type && length.value() == value;
}
static bool lengthTypeAndValueMatch(const LengthBox& lengthBox, LengthType type, float value)
{
return (lengthTypeAndValueMatch(lengthBox.left(), type, value)
&& lengthTypeAndValueMatch(lengthBox.right(), type, value)
&& lengthTypeAndValueMatch(lengthBox.top(), type, value)
&& lengthTypeAndValueMatch(lengthBox.bottom(), type, value));
}
static bool lengthTypeAndValueMatch(const BorderImageLength& borderImageLength, LengthType type, float value)
{
return borderImageLength.isLength() && lengthTypeAndValueMatch(borderImageLength.length(), type, value);
}
static bool lengthTypeAndValueMatch(const BorderImageLengthBox& borderImageLengthBox, LengthType type, float value)
{
return (lengthTypeAndValueMatch(borderImageLengthBox.left(), type, value)
&& lengthTypeAndValueMatch(borderImageLengthBox.right(), type, value)
&& lengthTypeAndValueMatch(borderImageLengthBox.top(), type, value)
&& lengthTypeAndValueMatch(borderImageLengthBox.bottom(), type, value));
}
void StyleBuilderFunctions::applyInitialCSSPropertyBorderImageOutset(StyleResolverState& state)
{
const NinePieceImage& currentImage = state.style()->borderImage();
if (lengthTypeAndValueMatch(currentImage.outset(), Fixed, 0))
return;
NinePieceImage image(currentImage);
image.setOutset(Length(0, Fixed));
state.style()->setBorderImage(image);
}
void StyleBuilderFunctions::applyInheritCSSPropertyBorderImageOutset(StyleResolverState& state)
{
NinePieceImage image(state.style()->borderImage());
image.copyOutsetFrom(state.parentStyle()->borderImage());
state.style()->setBorderImage(image);
}
void StyleBuilderFunctions::applyValueCSSPropertyBorderImageOutset(StyleResolverState& state, CSSValue* value)
{
NinePieceImage image(state.style()->borderImage());
image.setOutset(state.styleMap().mapNinePieceImageQuad(value));
state.style()->setBorderImage(image);
}
void StyleBuilderFunctions::applyInitialCSSPropertyBorderImageRepeat(StyleResolverState& state)
{
const NinePieceImage& currentImage = state.style()->borderImage();
if (currentImage.horizontalRule() == StretchImageRule && currentImage.verticalRule() == StretchImageRule)
return;
NinePieceImage image(currentImage);
image.setHorizontalRule(StretchImageRule);
image.setVerticalRule(StretchImageRule);
state.style()->setBorderImage(image);
}
void StyleBuilderFunctions::applyInheritCSSPropertyBorderImageRepeat(StyleResolverState& state)
{
NinePieceImage image(state.style()->borderImage());
image.copyRepeatFrom(state.parentStyle()->borderImage());
state.style()->setBorderImage(image);
}
void StyleBuilderFunctions::applyValueCSSPropertyBorderImageRepeat(StyleResolverState& state, CSSValue* value)
{
NinePieceImage image(state.style()->borderImage());
state.styleMap().mapNinePieceImageRepeat(value, image);
state.style()->setBorderImage(image);
}
void StyleBuilderFunctions::applyInitialCSSPropertyBorderImageSlice(StyleResolverState& state)
{
const NinePieceImage& currentImage = state.style()->borderImage();
if (currentImage.fill() == false && lengthTypeAndValueMatch(currentImage.imageSlices(), Percent, 100))
return;
NinePieceImage image(currentImage);
image.setImageSlices(LengthBox(Length(100, Percent), Length(100, Percent), Length(100, Percent), Length(100, Percent)));
image.setFill(false);
state.style()->setBorderImage(image);
}
void StyleBuilderFunctions::applyInheritCSSPropertyBorderImageSlice(StyleResolverState& state)
{
NinePieceImage image(state.style()->borderImage());
image.copyImageSlicesFrom(state.parentStyle()->borderImage());
state.style()->setBorderImage(image);
}
void StyleBuilderFunctions::applyValueCSSPropertyBorderImageSlice(StyleResolverState& state, CSSValue* value)
{
NinePieceImage image(state.style()->borderImage());
state.styleMap().mapNinePieceImageSlice(value, image);
state.style()->setBorderImage(image);
}
void StyleBuilderFunctions::applyInitialCSSPropertyBorderImageWidth(StyleResolverState& state)
{
const NinePieceImage& currentImage = state.style()->borderImage();
if (lengthTypeAndValueMatch(currentImage.borderSlices(), Fixed, 1))
return;
NinePieceImage image(currentImage);
image.setBorderSlices(1.0);
state.style()->setBorderImage(image);
}
void StyleBuilderFunctions::applyInheritCSSPropertyBorderImageWidth(StyleResolverState& state)
{
NinePieceImage image(state.style()->borderImage());
image.copyBorderSlicesFrom(state.parentStyle()->borderImage());
state.style()->setBorderImage(image);
}
void StyleBuilderFunctions::applyValueCSSPropertyBorderImageWidth(StyleResolverState& state, CSSValue* value)
{
NinePieceImage image(state.style()->borderImage());
image.setBorderSlices(state.styleMap().mapNinePieceImageQuad(value));
state.style()->setBorderImage(image);
}
void StyleBuilderFunctions::applyInitialCSSPropertyWebkitMaskBoxImageOutset(StyleResolverState& state)
{
const NinePieceImage& currentImage = state.style()->maskBoxImage();
if (lengthTypeAndValueMatch(currentImage.outset(), Fixed, 0))
return;
NinePieceImage image(currentImage);
image.setOutset(Length(0, Fixed));
state.style()->setMaskBoxImage(image);
}
void StyleBuilderFunctions::applyInheritCSSPropertyWebkitMaskBoxImageOutset(StyleResolverState& state)
{
NinePieceImage image(state.style()->maskBoxImage());
image.copyOutsetFrom(state.parentStyle()->maskBoxImage());
state.style()->setMaskBoxImage(image);
}
void StyleBuilderFunctions::applyValueCSSPropertyWebkitMaskBoxImageOutset(StyleResolverState& state, CSSValue* value)
{
NinePieceImage image(state.style()->maskBoxImage());
image.setOutset(state.styleMap().mapNinePieceImageQuad(value));
state.style()->setMaskBoxImage(image);
}
void StyleBuilderFunctions::applyInitialCSSPropertyWebkitMaskBoxImageRepeat(StyleResolverState& state)
{
const NinePieceImage& currentImage = state.style()->maskBoxImage();
if (currentImage.horizontalRule() == StretchImageRule && currentImage.verticalRule() == StretchImageRule)
return;
NinePieceImage image(currentImage);
image.setHorizontalRule(StretchImageRule);
image.setVerticalRule(StretchImageRule);
state.style()->setMaskBoxImage(image);
}
void StyleBuilderFunctions::applyInheritCSSPropertyWebkitMaskBoxImageRepeat(StyleResolverState& state)
{
NinePieceImage image(state.style()->maskBoxImage());
image.copyRepeatFrom(state.parentStyle()->maskBoxImage());
state.style()->setMaskBoxImage(image);
}
void StyleBuilderFunctions::applyValueCSSPropertyWebkitMaskBoxImageRepeat(StyleResolverState& state, CSSValue* value)
{
NinePieceImage image(state.style()->maskBoxImage());
state.styleMap().mapNinePieceImageRepeat(value, image);
state.style()->setMaskBoxImage(image);
}
void StyleBuilderFunctions::applyInitialCSSPropertyWebkitMaskBoxImageSlice(StyleResolverState& state)
{
const NinePieceImage& currentImage = state.style()->maskBoxImage();
// Masks have a different initial value for slices. Preserve the value of 0 for backwards compatibility.
if (currentImage.fill() == true && lengthTypeAndValueMatch(currentImage.imageSlices(), Fixed, 0))
return;
NinePieceImage image(currentImage);
image.setImageSlices(LengthBox(Length(0, Fixed), Length(0, Fixed), Length(0, Fixed), Length(0, Fixed)));
image.setFill(true);
state.style()->setMaskBoxImage(image);
}
void StyleBuilderFunctions::applyInheritCSSPropertyWebkitMaskBoxImageSlice(StyleResolverState& state)
{
NinePieceImage image(state.style()->maskBoxImage());
image.copyImageSlicesFrom(state.parentStyle()->maskBoxImage());
state.style()->setMaskBoxImage(image);
}
void StyleBuilderFunctions::applyValueCSSPropertyWebkitMaskBoxImageSlice(StyleResolverState& state, CSSValue* value)
{
NinePieceImage image(state.style()->maskBoxImage());
state.styleMap().mapNinePieceImageSlice(value, image);
state.style()->setMaskBoxImage(image);
}
void StyleBuilderFunctions::applyInitialCSSPropertyWebkitMaskBoxImageWidth(StyleResolverState& state)
{
const NinePieceImage& currentImage = state.style()->maskBoxImage();
// Masks have a different initial value for widths. Preserve the value of 'auto' for backwards compatibility.
if (lengthTypeAndValueMatch(currentImage.borderSlices(), Auto, 0))
return;
NinePieceImage image(currentImage);
image.setBorderSlices(Length(Auto));
state.style()->setMaskBoxImage(image);
}
void StyleBuilderFunctions::applyInheritCSSPropertyWebkitMaskBoxImageWidth(StyleResolverState& state)
{
NinePieceImage image(state.style()->maskBoxImage());
image.copyBorderSlicesFrom(state.parentStyle()->maskBoxImage());
state.style()->setMaskBoxImage(image);
}
void StyleBuilderFunctions::applyValueCSSPropertyWebkitMaskBoxImageWidth(StyleResolverState& state, CSSValue* value)
{
NinePieceImage image(state.style()->maskBoxImage());
image.setBorderSlices(state.styleMap().mapNinePieceImageQuad(value));
state.style()->setMaskBoxImage(image);
}
void StyleBuilderFunctions::applyValueCSSPropertyBorderImageSource(StyleResolverState& state, CSSValue* value)
{
state.style()->setBorderImageSource(state.styleImage(CSSPropertyBorderImageSource, value));
}
void StyleBuilderFunctions::applyValueCSSPropertyWebkitMaskBoxImageSource(StyleResolverState& state, CSSValue* value)
{
state.style()->setMaskBoxImageSource(state.styleImage(CSSPropertyWebkitMaskBoxImageSource, value));
}
void StyleBuilderFunctions::applyInitialCSSPropertyBackgroundColor(StyleResolverState& state)
{
StyleColor color = RenderStyle::initialBackgroundColor();
if (state.applyPropertyToRegularStyle())
state.style()->setBackgroundColor(color);
if (state.applyPropertyToVisitedLinkStyle())
state.style()->setVisitedLinkBackgroundColor(color);
}
void StyleBuilderFunctions::applyInheritCSSPropertyBackgroundColor(StyleResolverState& state)
{
// Visited link style can never explicitly inherit from parent visited link style so no separate getters are needed.
StyleColor color = state.parentStyle()->backgroundColor();
Color resolvedColor = color.resolve(state.parentStyle()->color());
if (state.applyPropertyToRegularStyle())
state.style()->setBackgroundColor(resolvedColor);
if (state.applyPropertyToVisitedLinkStyle())
state.style()->setVisitedLinkBackgroundColor(resolvedColor);
}
void StyleBuilderFunctions::applyValueCSSPropertyBackgroundColor(StyleResolverState& state, CSSValue* value)
{
CSSPrimitiveValue* primitiveValue = toCSSPrimitiveValue(value);
if (state.applyPropertyToRegularStyle())
state.style()->setBackgroundColor(state.document().textLinkColors().colorFromPrimitiveValue(primitiveValue, state.style()->color()));
if (state.applyPropertyToVisitedLinkStyle())
state.style()->setVisitedLinkBackgroundColor(state.document().textLinkColors().colorFromPrimitiveValue(primitiveValue, state.style()->color(), true));
}
void StyleBuilderFunctions::applyInitialCSSPropertyBorderBottomColor(StyleResolverState& state)
{
StyleColor color = StyleColor::currentColor();
if (state.applyPropertyToRegularStyle())
state.style()->setBorderBottomColor(color);
if (state.applyPropertyToVisitedLinkStyle())
state.style()->setVisitedLinkBorderBottomColor(color);
}
void StyleBuilderFunctions::applyInheritCSSPropertyBorderBottomColor(StyleResolverState& state)
{
// Visited link style can never explicitly inherit from parent visited link style so no separate getters are needed.
StyleColor color = state.parentStyle()->borderBottomColor();
Color resolvedColor = color.resolve(state.parentStyle()->color());
if (state.applyPropertyToRegularStyle())
state.style()->setBorderBottomColor(resolvedColor);
if (state.applyPropertyToVisitedLinkStyle())
state.style()->setVisitedLinkBorderBottomColor(resolvedColor);
}
void StyleBuilderFunctions::applyValueCSSPropertyBorderBottomColor(StyleResolverState& state, CSSValue* value)
{
CSSPrimitiveValue* primitiveValue = toCSSPrimitiveValue(value);
if (state.applyPropertyToRegularStyle())
state.style()->setBorderBottomColor(state.document().textLinkColors().colorFromPrimitiveValue(primitiveValue, state.style()->color()));
if (state.applyPropertyToVisitedLinkStyle())
state.style()->setVisitedLinkBorderBottomColor(state.document().textLinkColors().colorFromPrimitiveValue(primitiveValue, state.style()->color(), true));
}
void StyleBuilderFunctions::applyInitialCSSPropertyBorderLeftColor(StyleResolverState& state)
{
StyleColor color = StyleColor::currentColor();
if (state.applyPropertyToRegularStyle())
state.style()->setBorderLeftColor(color);
if (state.applyPropertyToVisitedLinkStyle())
state.style()->setVisitedLinkBorderLeftColor(color);
}
void StyleBuilderFunctions::applyInheritCSSPropertyBorderLeftColor(StyleResolverState& state)
{
// Visited link style can never explicitly inherit from parent visited link style so no separate getters are needed.
StyleColor color = state.parentStyle()->borderLeftColor();
Color resolvedColor = color.resolve(state.parentStyle()->color());
if (state.applyPropertyToRegularStyle())
state.style()->setBorderLeftColor(resolvedColor);
if (state.applyPropertyToVisitedLinkStyle())
state.style()->setVisitedLinkBorderLeftColor(resolvedColor);
}
void StyleBuilderFunctions::applyValueCSSPropertyBorderLeftColor(StyleResolverState& state, CSSValue* value)
{
CSSPrimitiveValue* primitiveValue = toCSSPrimitiveValue(value);
if (state.applyPropertyToRegularStyle())
state.style()->setBorderLeftColor(state.document().textLinkColors().colorFromPrimitiveValue(primitiveValue, state.style()->color()));
if (state.applyPropertyToVisitedLinkStyle())
state.style()->setVisitedLinkBorderLeftColor(state.document().textLinkColors().colorFromPrimitiveValue(primitiveValue, state.style()->color(), true));
}
void StyleBuilderFunctions::applyInitialCSSPropertyBorderRightColor(StyleResolverState& state)
{
StyleColor color = StyleColor::currentColor();
if (state.applyPropertyToRegularStyle())
state.style()->setBorderRightColor(color);
if (state.applyPropertyToVisitedLinkStyle())
state.style()->setVisitedLinkBorderRightColor(color);
}
void StyleBuilderFunctions::applyInheritCSSPropertyBorderRightColor(StyleResolverState& state)
{
// Visited link style can never explicitly inherit from parent visited link style so no separate getters are needed.
StyleColor color = state.parentStyle()->borderRightColor();
Color resolvedColor = color.resolve(state.parentStyle()->color());
if (state.applyPropertyToRegularStyle())
state.style()->setBorderRightColor(resolvedColor);
if (state.applyPropertyToVisitedLinkStyle())
state.style()->setVisitedLinkBorderRightColor(resolvedColor);
}
void StyleBuilderFunctions::applyValueCSSPropertyBorderRightColor(StyleResolverState& state, CSSValue* value)
{
CSSPrimitiveValue* primitiveValue = toCSSPrimitiveValue(value);
if (state.applyPropertyToRegularStyle())
state.style()->setBorderRightColor(state.document().textLinkColors().colorFromPrimitiveValue(primitiveValue, state.style()->color()));
if (state.applyPropertyToVisitedLinkStyle())
state.style()->setVisitedLinkBorderRightColor(state.document().textLinkColors().colorFromPrimitiveValue(primitiveValue, state.style()->color(), true));
}
void StyleBuilderFunctions::applyInitialCSSPropertyBorderTopColor(StyleResolverState& state)
{
StyleColor color = StyleColor::currentColor();
if (state.applyPropertyToRegularStyle())
state.style()->setBorderTopColor(color);
if (state.applyPropertyToVisitedLinkStyle())
state.style()->setVisitedLinkBorderTopColor(color);
}
void StyleBuilderFunctions::applyInheritCSSPropertyBorderTopColor(StyleResolverState& state)
{
// Visited link style can never explicitly inherit from parent visited link style so no separate getters are needed.
StyleColor color = state.parentStyle()->borderTopColor();
Color resolvedColor = color.resolve(state.parentStyle()->color());
if (state.applyPropertyToRegularStyle())
state.style()->setBorderTopColor(resolvedColor);
if (state.applyPropertyToVisitedLinkStyle())
state.style()->setVisitedLinkBorderTopColor(resolvedColor);
}
void StyleBuilderFunctions::applyValueCSSPropertyBorderTopColor(StyleResolverState& state, CSSValue* value)
{
CSSPrimitiveValue* primitiveValue = toCSSPrimitiveValue(value);
if (state.applyPropertyToRegularStyle())
state.style()->setBorderTopColor(state.document().textLinkColors().colorFromPrimitiveValue(primitiveValue, state.style()->color()));
if (state.applyPropertyToVisitedLinkStyle())
state.style()->setVisitedLinkBorderTopColor(state.document().textLinkColors().colorFromPrimitiveValue(primitiveValue, state.style()->color(), true));
}
void StyleBuilderFunctions::applyInitialCSSPropertyOutlineColor(StyleResolverState& state)
{
StyleColor color = StyleColor::currentColor();
if (state.applyPropertyToRegularStyle())
state.style()->setOutlineColor(color);
if (state.applyPropertyToVisitedLinkStyle())
state.style()->setVisitedLinkOutlineColor(color);
}
void StyleBuilderFunctions::applyInheritCSSPropertyOutlineColor(StyleResolverState& state)
{
// Visited link style can never explicitly inherit from parent visited link style so no separate getters are needed.
StyleColor color = state.parentStyle()->outlineColor();
Color resolvedColor = color.resolve(state.parentStyle()->color());
if (state.applyPropertyToRegularStyle())
state.style()->setOutlineColor(resolvedColor);
if (state.applyPropertyToVisitedLinkStyle())
state.style()->setVisitedLinkOutlineColor(resolvedColor);
}
void StyleBuilderFunctions::applyValueCSSPropertyOutlineColor(StyleResolverState& state, CSSValue* value)
{
CSSPrimitiveValue* primitiveValue = toCSSPrimitiveValue(value);
if (state.applyPropertyToRegularStyle())
state.style()->setOutlineColor(state.document().textLinkColors().colorFromPrimitiveValue(primitiveValue, state.style()->color()));
if (state.applyPropertyToVisitedLinkStyle())
state.style()->setVisitedLinkOutlineColor(state.document().textLinkColors().colorFromPrimitiveValue(primitiveValue, state.style()->color(), true));
}
void StyleBuilderFunctions::applyInitialCSSPropertyTextDecorationColor(StyleResolverState& state)
{
StyleColor color = StyleColor::currentColor();
if (state.applyPropertyToRegularStyle())
state.style()->setTextDecorationColor(color);
if (state.applyPropertyToVisitedLinkStyle())
state.style()->setVisitedLinkTextDecorationColor(color);
}
void StyleBuilderFunctions::applyInheritCSSPropertyTextDecorationColor(StyleResolverState& state)
{
// Visited link style can never explicitly inherit from parent visited link style so no separate getters are needed.
StyleColor color = state.parentStyle()->textDecorationColor();
Color resolvedColor = color.resolve(state.parentStyle()->color());
if (state.applyPropertyToRegularStyle())
state.style()->setTextDecorationColor(resolvedColor);
if (state.applyPropertyToVisitedLinkStyle())
state.style()->setVisitedLinkTextDecorationColor(resolvedColor);
}
void StyleBuilderFunctions::applyValueCSSPropertyTextDecorationColor(StyleResolverState& state, CSSValue* value)
{
CSSPrimitiveValue* primitiveValue = toCSSPrimitiveValue(value);
if (state.applyPropertyToRegularStyle())
state.style()->setTextDecorationColor(state.document().textLinkColors().colorFromPrimitiveValue(primitiveValue, state.style()->color()));
if (state.applyPropertyToVisitedLinkStyle())
state.style()->setVisitedLinkTextDecorationColor(state.document().textLinkColors().colorFromPrimitiveValue(primitiveValue, state.style()->color(), true));
}
void StyleBuilderFunctions::applyInitialCSSPropertyWebkitColumnRuleColor(StyleResolverState& state)
{
StyleColor color = StyleColor::currentColor();
if (state.applyPropertyToRegularStyle())
state.style()->setColumnRuleColor(color);
if (state.applyPropertyToVisitedLinkStyle())
state.style()->setVisitedLinkColumnRuleColor(color);
}
void StyleBuilderFunctions::applyInheritCSSPropertyWebkitColumnRuleColor(StyleResolverState& state)
{
// Visited link style can never explicitly inherit from parent visited link style so no separate getters are needed.
StyleColor color = state.parentStyle()->columnRuleColor();
Color resolvedColor = color.resolve(state.parentStyle()->color());
if (state.applyPropertyToRegularStyle())
state.style()->setColumnRuleColor(resolvedColor);
if (state.applyPropertyToVisitedLinkStyle())
state.style()->setVisitedLinkColumnRuleColor(resolvedColor);
}
void StyleBuilderFunctions::applyValueCSSPropertyWebkitColumnRuleColor(StyleResolverState& state, CSSValue* value)
{
CSSPrimitiveValue* primitiveValue = toCSSPrimitiveValue(value);
if (state.applyPropertyToRegularStyle())
state.style()->setColumnRuleColor(state.document().textLinkColors().colorFromPrimitiveValue(primitiveValue, state.style()->color()));
if (state.applyPropertyToVisitedLinkStyle())
state.style()->setVisitedLinkColumnRuleColor(state.document().textLinkColors().colorFromPrimitiveValue(primitiveValue, state.style()->color(), true));
}
void StyleBuilderFunctions::applyInitialCSSPropertyWebkitTextEmphasisColor(StyleResolverState& state)
{
StyleColor color = StyleColor::currentColor();
if (state.applyPropertyToRegularStyle())
state.style()->setTextEmphasisColor(color);
if (state.applyPropertyToVisitedLinkStyle())
state.style()->setVisitedLinkTextEmphasisColor(color);
}
void StyleBuilderFunctions::applyInheritCSSPropertyWebkitTextEmphasisColor(StyleResolverState& state)
{
// Visited link style can never explicitly inherit from parent visited link style so no separate getters are needed.
StyleColor color = state.parentStyle()->textEmphasisColor();
Color resolvedColor = color.resolve(state.parentStyle()->color());
if (state.applyPropertyToRegularStyle())
state.style()->setTextEmphasisColor(resolvedColor);
if (state.applyPropertyToVisitedLinkStyle())
state.style()->setVisitedLinkTextEmphasisColor(resolvedColor);
}
void StyleBuilderFunctions::applyValueCSSPropertyWebkitTextEmphasisColor(StyleResolverState& state, CSSValue* value)
{
CSSPrimitiveValue* primitiveValue = toCSSPrimitiveValue(value);
if (state.applyPropertyToRegularStyle())
state.style()->setTextEmphasisColor(state.document().textLinkColors().colorFromPrimitiveValue(primitiveValue, state.style()->color()));
if (state.applyPropertyToVisitedLinkStyle())
state.style()->setVisitedLinkTextEmphasisColor(state.document().textLinkColors().colorFromPrimitiveValue(primitiveValue, state.style()->color(), true));
}
void StyleBuilderFunctions::applyInitialCSSPropertyWebkitTextFillColor(StyleResolverState& state)
{
StyleColor color = StyleColor::currentColor();
if (state.applyPropertyToRegularStyle())
state.style()->setTextFillColor(color);
if (state.applyPropertyToVisitedLinkStyle())
state.style()->setVisitedLinkTextFillColor(color);
}
void StyleBuilderFunctions::applyInheritCSSPropertyWebkitTextFillColor(StyleResolverState& state)
{
// Visited link style can never explicitly inherit from parent visited link style so no separate getters are needed.
StyleColor color = state.parentStyle()->textFillColor();
Color resolvedColor = color.resolve(state.parentStyle()->color());
if (state.applyPropertyToRegularStyle())
state.style()->setTextFillColor(resolvedColor);
if (state.applyPropertyToVisitedLinkStyle())
state.style()->setVisitedLinkTextFillColor(resolvedColor);
}
void StyleBuilderFunctions::applyValueCSSPropertyWebkitTextFillColor(StyleResolverState& state, CSSValue* value)
{
CSSPrimitiveValue* primitiveValue = toCSSPrimitiveValue(value);
if (state.applyPropertyToRegularStyle())
state.style()->setTextFillColor(state.document().textLinkColors().colorFromPrimitiveValue(primitiveValue, state.style()->color()));
if (state.applyPropertyToVisitedLinkStyle())
state.style()->setVisitedLinkTextFillColor(state.document().textLinkColors().colorFromPrimitiveValue(primitiveValue, state.style()->color(), true));
}
void StyleBuilderFunctions::applyInitialCSSPropertyWebkitTextStrokeColor(StyleResolverState& state)
{
StyleColor color = StyleColor::currentColor();
if (state.applyPropertyToRegularStyle())
state.style()->setTextStrokeColor(color);
if (state.applyPropertyToVisitedLinkStyle())
state.style()->setVisitedLinkTextStrokeColor(color);
}
void StyleBuilderFunctions::applyInheritCSSPropertyWebkitTextStrokeColor(StyleResolverState& state)
{
// Visited link style can never explicitly inherit from parent visited link style so no separate getters are needed.
StyleColor color = state.parentStyle()->textStrokeColor();
Color resolvedColor = color.resolve(state.parentStyle()->color());
if (state.applyPropertyToRegularStyle())
state.style()->setTextStrokeColor(resolvedColor);
if (state.applyPropertyToVisitedLinkStyle())
state.style()->setVisitedLinkTextStrokeColor(resolvedColor);
}
void StyleBuilderFunctions::applyValueCSSPropertyWebkitTextStrokeColor(StyleResolverState& state, CSSValue* value)
{
CSSPrimitiveValue* primitiveValue = toCSSPrimitiveValue(value);
if (state.applyPropertyToRegularStyle())
state.style()->setTextStrokeColor(state.document().textLinkColors().colorFromPrimitiveValue(primitiveValue, state.style()->color()));
if (state.applyPropertyToVisitedLinkStyle())
state.style()->setVisitedLinkTextStrokeColor(state.document().textLinkColors().colorFromPrimitiveValue(primitiveValue, state.style()->color(), true));
}
void StyleBuilderFunctions::applyInitialCSSPropertyCounterIncrement(StyleResolverState& state) { }
void StyleBuilderFunctions::applyInheritCSSPropertyCounterIncrement(StyleResolverState& state)
{
CounterDirectiveMap& map = state.style()->accessCounterDirectives();
CounterDirectiveMap& parentMap = state.parentStyle()->accessCounterDirectives();
typedef CounterDirectiveMap::iterator Iterator;
Iterator end = parentMap.end();
for (Iterator it = parentMap.begin(); it != end; ++it) {
CounterDirectives& directives = map.add(it->key, CounterDirectives()).storedValue->value;
directives.inheritIncrement(it->value);
}
}
void StyleBuilderFunctions::applyValueCSSPropertyCounterIncrement(StyleResolverState& state, CSSValue* value)
{
CounterDirectiveMap& map = state.style()->accessCounterDirectives();
typedef CounterDirectiveMap::iterator Iterator;
Iterator end = map.end();
for (Iterator it = map.begin(); it != end; ++it)
it->value.clearIncrement();
if (!value->isValueList()) {
ASSERT(value->isPrimitiveValue() && toCSSPrimitiveValue(value)->getValueID() == CSSValueNone);
return;
}
CSSValueList* list = toCSSValueList(value);
int length = list ? list->length() : 0;
for (int i = 0; i < length; ++i) {
CSSValue* currValue = list->itemWithoutBoundsCheck(i);
if (!currValue->isPrimitiveValue())
continue;
Pair* pair = toCSSPrimitiveValue(currValue)->getPairValue();
if (!pair || !pair->first() || !pair->second())
continue;
AtomicString identifier(pair->first()->getStringValue());
int value = pair->second()->getIntValue();
CounterDirectives& directives = map.add(identifier, CounterDirectives()).storedValue->value;
directives.addIncrementValue(value);
}
}
void StyleBuilderFunctions::applyInitialCSSPropertyCounterReset(StyleResolverState& state) { }
void StyleBuilderFunctions::applyInheritCSSPropertyCounterReset(StyleResolverState& state)
{
CounterDirectiveMap& map = state.style()->accessCounterDirectives();
CounterDirectiveMap& parentMap = state.parentStyle()->accessCounterDirectives();
typedef CounterDirectiveMap::iterator Iterator;
Iterator end = parentMap.end();
for (Iterator it = parentMap.begin(); it != end; ++it) {
CounterDirectives& directives = map.add(it->key, CounterDirectives()).storedValue->value;
directives.inheritReset(it->value);
}
}
void StyleBuilderFunctions::applyValueCSSPropertyCounterReset(StyleResolverState& state, CSSValue* value)
{
CounterDirectiveMap& map = state.style()->accessCounterDirectives();
typedef CounterDirectiveMap::iterator Iterator;
Iterator end = map.end();
for (Iterator it = map.begin(); it != end; ++it)
it->value.clearReset();
if (!value->isValueList()) {
ASSERT(value->isPrimitiveValue() && toCSSPrimitiveValue(value)->getValueID() == CSSValueNone);
return;
}
CSSValueList* list = toCSSValueList(value);
int length = list ? list->length() : 0;
for (int i = 0; i < length; ++i) {
CSSValue* currValue = list->itemWithoutBoundsCheck(i);
if (!currValue->isPrimitiveValue())
continue;
Pair* pair = toCSSPrimitiveValue(currValue)->getPairValue();
if (!pair || !pair->first() || !pair->second())
continue;
AtomicString identifier(pair->first()->getStringValue());
int value = pair->second()->getIntValue();
CounterDirectives& directives = map.add(identifier, CounterDirectives()).storedValue->value;
directives.setResetValue(value);
}
}
void StyleBuilderFunctions::applyInitialCSSPropertyBackgroundAttachment(StyleResolverState& state)
{
FillLayer* currChild = state.style()->accessBackgroundLayers();
currChild->setAttachment(FillLayer::initialFillAttachment(BackgroundFillLayer));
for (currChild = currChild->next(); currChild; currChild = currChild->next())
currChild->clearAttachment();
}
void StyleBuilderFunctions::applyInheritCSSPropertyBackgroundAttachment(StyleResolverState& state)
{
FillLayer* currChild = state.style()->accessBackgroundLayers();
FillLayer* prevChild = 0;
const FillLayer* currParent = state.parentStyle()->backgroundLayers();
while (currParent && currParent->isAttachmentSet()) {
if (!currChild) {
/* Need to make a new layer.*/
currChild = new FillLayer(BackgroundFillLayer);
prevChild->setNext(currChild);
}
currChild->setAttachment(currParent->attachment());
prevChild = currChild;
currChild = prevChild->next();
currParent = currParent->next();
}
while (currChild) {
/* Reset any remaining layers to not have the property set. */
currChild->clearAttachment();
currChild = currChild->next();
}
}
void StyleBuilderFunctions::applyValueCSSPropertyBackgroundAttachment(StyleResolverState& state, CSSValue* value)
{
FillLayer* currChild = state.style()->accessBackgroundLayers();
FillLayer* prevChild = 0;
if (value->isValueList() && !value->isImageSetValue()) {
/* Walk each value and put it into a layer, creating new layers as needed. */
CSSValueList* valueList = toCSSValueList(value);
for (unsigned int i = 0; i < valueList->length(); i++) {
if (!currChild) {
/* Need to make a new layer to hold this value */
currChild = new FillLayer(BackgroundFillLayer);
prevChild->setNext(currChild);
}
state.styleMap().mapFillAttachment(CSSPropertyBackgroundAttachment, currChild, valueList->itemWithoutBoundsCheck(i));
prevChild = currChild;
currChild = currChild->next();
}
} else {
state.styleMap().mapFillAttachment(CSSPropertyBackgroundAttachment, currChild, value);
currChild = currChild->next();
}
while (currChild) {
/* Reset all remaining layers to not have the property set. */
currChild->clearAttachment();
currChild = currChild->next();
}
}
void StyleBuilderFunctions::applyInitialCSSPropertyBackgroundBlendMode(StyleResolverState& state)
{
FillLayer* currChild = state.style()->accessBackgroundLayers();
currChild->setBlendMode(FillLayer::initialFillBlendMode(BackgroundFillLayer));
for (currChild = currChild->next(); currChild; currChild = currChild->next())
currChild->clearBlendMode();
}
void StyleBuilderFunctions::applyInheritCSSPropertyBackgroundBlendMode(StyleResolverState& state)
{
FillLayer* currChild = state.style()->accessBackgroundLayers();
FillLayer* prevChild = 0;
const FillLayer* currParent = state.parentStyle()->backgroundLayers();
while (currParent && currParent->isBlendModeSet()) {
if (!currChild) {
/* Need to make a new layer.*/
currChild = new FillLayer(BackgroundFillLayer);
prevChild->setNext(currChild);
}
currChild->setBlendMode(currParent->blendMode());
prevChild = currChild;
currChild = prevChild->next();
currParent = currParent->next();
}
while (currChild) {
/* Reset any remaining layers to not have the property set. */
currChild->clearBlendMode();
currChild = currChild->next();
}
}
void StyleBuilderFunctions::applyValueCSSPropertyBackgroundBlendMode(StyleResolverState& state, CSSValue* value)
{
FillLayer* currChild = state.style()->accessBackgroundLayers();
FillLayer* prevChild = 0;
if (value->isValueList() && !value->isImageSetValue()) {
/* Walk each value and put it into a layer, creating new layers as needed. */
CSSValueList* valueList = toCSSValueList(value);
for (unsigned int i = 0; i < valueList->length(); i++) {
if (!currChild) {
/* Need to make a new layer to hold this value */
currChild = new FillLayer(BackgroundFillLayer);
prevChild->setNext(currChild);
}
state.styleMap().mapFillBlendMode(CSSPropertyBackgroundBlendMode, currChild, valueList->itemWithoutBoundsCheck(i));
prevChild = currChild;
currChild = currChild->next();
}
} else {
state.styleMap().mapFillBlendMode(CSSPropertyBackgroundBlendMode, currChild, value);
currChild = currChild->next();
}
while (currChild) {
/* Reset all remaining layers to not have the property set. */
currChild->clearBlendMode();
currChild = currChild->next();
}
}
void StyleBuilderFunctions::applyInitialCSSPropertyBackgroundClip(StyleResolverState& state)
{
FillLayer* currChild = state.style()->accessBackgroundLayers();
currChild->setClip(FillLayer::initialFillClip(BackgroundFillLayer));
for (currChild = currChild->next(); currChild; currChild = currChild->next())
currChild->clearClip();
}
void StyleBuilderFunctions::applyInheritCSSPropertyBackgroundClip(StyleResolverState& state)
{
FillLayer* currChild = state.style()->accessBackgroundLayers();
FillLayer* prevChild = 0;
const FillLayer* currParent = state.parentStyle()->backgroundLayers();
while (currParent && currParent->isClipSet()) {
if (!currChild) {
/* Need to make a new layer.*/
currChild = new FillLayer(BackgroundFillLayer);
prevChild->setNext(currChild);
}
currChild->setClip(currParent->clip());
prevChild = currChild;
currChild = prevChild->next();
currParent = currParent->next();
}
while (currChild) {
/* Reset any remaining layers to not have the property set. */
currChild->clearClip();
currChild = currChild->next();
}
}
void StyleBuilderFunctions::applyValueCSSPropertyBackgroundClip(StyleResolverState& state, CSSValue* value)
{
FillLayer* currChild = state.style()->accessBackgroundLayers();
FillLayer* prevChild = 0;
if (value->isValueList() && !value->isImageSetValue()) {
/* Walk each value and put it into a layer, creating new layers as needed. */
CSSValueList* valueList = toCSSValueList(value);
for (unsigned int i = 0; i < valueList->length(); i++) {
if (!currChild) {
/* Need to make a new layer to hold this value */
currChild = new FillLayer(BackgroundFillLayer);
prevChild->setNext(currChild);
}
state.styleMap().mapFillClip(CSSPropertyBackgroundClip, currChild, valueList->itemWithoutBoundsCheck(i));
prevChild = currChild;
currChild = currChild->next();
}
} else {
state.styleMap().mapFillClip(CSSPropertyBackgroundClip, currChild, value);
currChild = currChild->next();
}
while (currChild) {
/* Reset all remaining layers to not have the property set. */
currChild->clearClip();
currChild = currChild->next();
}
}
void StyleBuilderFunctions::applyInitialCSSPropertyBackgroundImage(StyleResolverState& state)
{
FillLayer* currChild = state.style()->accessBackgroundLayers();
currChild->setImage(FillLayer::initialFillImage(BackgroundFillLayer));
for (currChild = currChild->next(); currChild; currChild = currChild->next())
currChild->clearImage();
}
void StyleBuilderFunctions::applyInheritCSSPropertyBackgroundImage(StyleResolverState& state)
{
FillLayer* currChild = state.style()->accessBackgroundLayers();
FillLayer* prevChild = 0;
const FillLayer* currParent = state.parentStyle()->backgroundLayers();
while (currParent && currParent->isImageSet()) {
if (!currChild) {
/* Need to make a new layer.*/
currChild = new FillLayer(BackgroundFillLayer);
prevChild->setNext(currChild);
}
currChild->setImage(currParent->image());
prevChild = currChild;
currChild = prevChild->next();
currParent = currParent->next();
}
while (currChild) {
/* Reset any remaining layers to not have the property set. */
currChild->clearImage();
currChild = currChild->next();
}
}
void StyleBuilderFunctions::applyValueCSSPropertyBackgroundImage(StyleResolverState& state, CSSValue* value)
{
FillLayer* currChild = state.style()->accessBackgroundLayers();
FillLayer* prevChild = 0;
if (value->isValueList() && !value->isImageSetValue()) {
/* Walk each value and put it into a layer, creating new layers as needed. */
CSSValueList* valueList = toCSSValueList(value);
for (unsigned int i = 0; i < valueList->length(); i++) {
if (!currChild) {
/* Need to make a new layer to hold this value */
currChild = new FillLayer(BackgroundFillLayer);
prevChild->setNext(currChild);
}
state.styleMap().mapFillImage(CSSPropertyBackgroundImage, currChild, valueList->itemWithoutBoundsCheck(i));
prevChild = currChild;
currChild = currChild->next();
}
} else {
state.styleMap().mapFillImage(CSSPropertyBackgroundImage, currChild, value);
currChild = currChild->next();
}
while (currChild) {
/* Reset all remaining layers to not have the property set. */
currChild->clearImage();
currChild = currChild->next();
}
}
void StyleBuilderFunctions::applyInitialCSSPropertyBackgroundOrigin(StyleResolverState& state)
{
FillLayer* currChild = state.style()->accessBackgroundLayers();
currChild->setOrigin(FillLayer::initialFillOrigin(BackgroundFillLayer));
for (currChild = currChild->next(); currChild; currChild = currChild->next())
currChild->clearOrigin();
}
void StyleBuilderFunctions::applyInheritCSSPropertyBackgroundOrigin(StyleResolverState& state)
{
FillLayer* currChild = state.style()->accessBackgroundLayers();
FillLayer* prevChild = 0;
const FillLayer* currParent = state.parentStyle()->backgroundLayers();
while (currParent && currParent->isOriginSet()) {
if (!currChild) {
/* Need to make a new layer.*/
currChild = new FillLayer(BackgroundFillLayer);
prevChild->setNext(currChild);
}
currChild->setOrigin(currParent->origin());
prevChild = currChild;
currChild = prevChild->next();
currParent = currParent->next();
}
while (currChild) {
/* Reset any remaining layers to not have the property set. */
currChild->clearOrigin();
currChild = currChild->next();
}
}
void StyleBuilderFunctions::applyValueCSSPropertyBackgroundOrigin(StyleResolverState& state, CSSValue* value)
{
FillLayer* currChild = state.style()->accessBackgroundLayers();
FillLayer* prevChild = 0;
if (value->isValueList() && !value->isImageSetValue()) {
/* Walk each value and put it into a layer, creating new layers as needed. */
CSSValueList* valueList = toCSSValueList(value);
for (unsigned int i = 0; i < valueList->length(); i++) {
if (!currChild) {
/* Need to make a new layer to hold this value */
currChild = new FillLayer(BackgroundFillLayer);
prevChild->setNext(currChild);
}
state.styleMap().mapFillOrigin(CSSPropertyBackgroundOrigin, currChild, valueList->itemWithoutBoundsCheck(i));
prevChild = currChild;
currChild = currChild->next();
}
} else {
state.styleMap().mapFillOrigin(CSSPropertyBackgroundOrigin, currChild, value);
currChild = currChild->next();
}
while (currChild) {
/* Reset all remaining layers to not have the property set. */
currChild->clearOrigin();
currChild = currChild->next();
}
}
void StyleBuilderFunctions::applyInitialCSSPropertyBackgroundPositionX(StyleResolverState& state)
{
FillLayer* currChild = state.style()->accessBackgroundLayers();
currChild->setXPosition(FillLayer::initialFillXPosition(BackgroundFillLayer));
for (currChild = currChild->next(); currChild; currChild = currChild->next())
currChild->clearXPosition();
}
void StyleBuilderFunctions::applyInheritCSSPropertyBackgroundPositionX(StyleResolverState& state)
{
FillLayer* currChild = state.style()->accessBackgroundLayers();
FillLayer* prevChild = 0;
const FillLayer* currParent = state.parentStyle()->backgroundLayers();
while (currParent && currParent->isXPositionSet()) {
if (!currChild) {
/* Need to make a new layer.*/
currChild = new FillLayer(BackgroundFillLayer);
prevChild->setNext(currChild);
}
currChild->setXPosition(currParent->xPosition());
prevChild = currChild;
currChild = prevChild->next();
currParent = currParent->next();
}
while (currChild) {
/* Reset any remaining layers to not have the property set. */
currChild->clearXPosition();
currChild = currChild->next();
}
}
void StyleBuilderFunctions::applyValueCSSPropertyBackgroundPositionX(StyleResolverState& state, CSSValue* value)
{
FillLayer* currChild = state.style()->accessBackgroundLayers();
FillLayer* prevChild = 0;
if (value->isValueList() && !value->isImageSetValue()) {
/* Walk each value and put it into a layer, creating new layers as needed. */
CSSValueList* valueList = toCSSValueList(value);
for (unsigned int i = 0; i < valueList->length(); i++) {
if (!currChild) {
/* Need to make a new layer to hold this value */
currChild = new FillLayer(BackgroundFillLayer);
prevChild->setNext(currChild);
}
state.styleMap().mapFillXPosition(CSSPropertyBackgroundPositionX, currChild, valueList->itemWithoutBoundsCheck(i));
prevChild = currChild;
currChild = currChild->next();
}
} else {
state.styleMap().mapFillXPosition(CSSPropertyBackgroundPositionX, currChild, value);
currChild = currChild->next();
}
while (currChild) {
/* Reset all remaining layers to not have the property set. */
currChild->clearXPosition();
currChild = currChild->next();
}
}
void StyleBuilderFunctions::applyInitialCSSPropertyBackgroundPositionY(StyleResolverState& state)
{
FillLayer* currChild = state.style()->accessBackgroundLayers();
currChild->setYPosition(FillLayer::initialFillYPosition(BackgroundFillLayer));
for (currChild = currChild->next(); currChild; currChild = currChild->next())
currChild->clearYPosition();
}
void StyleBuilderFunctions::applyInheritCSSPropertyBackgroundPositionY(StyleResolverState& state)
{
FillLayer* currChild = state.style()->accessBackgroundLayers();
FillLayer* prevChild = 0;
const FillLayer* currParent = state.parentStyle()->backgroundLayers();
while (currParent && currParent->isYPositionSet()) {
if (!currChild) {
/* Need to make a new layer.*/
currChild = new FillLayer(BackgroundFillLayer);
prevChild->setNext(currChild);
}
currChild->setYPosition(currParent->yPosition());
prevChild = currChild;
currChild = prevChild->next();
currParent = currParent->next();
}
while (currChild) {
/* Reset any remaining layers to not have the property set. */
currChild->clearYPosition();
currChild = currChild->next();
}
}
void StyleBuilderFunctions::applyValueCSSPropertyBackgroundPositionY(StyleResolverState& state, CSSValue* value)
{
FillLayer* currChild = state.style()->accessBackgroundLayers();
FillLayer* prevChild = 0;
if (value->isValueList() && !value->isImageSetValue()) {
/* Walk each value and put it into a layer, creating new layers as needed. */
CSSValueList* valueList = toCSSValueList(value);
for (unsigned int i = 0; i < valueList->length(); i++) {
if (!currChild) {
/* Need to make a new layer to hold this value */
currChild = new FillLayer(BackgroundFillLayer);
prevChild->setNext(currChild);
}
state.styleMap().mapFillYPosition(CSSPropertyBackgroundPositionY, currChild, valueList->itemWithoutBoundsCheck(i));
prevChild = currChild;
currChild = currChild->next();
}
} else {
state.styleMap().mapFillYPosition(CSSPropertyBackgroundPositionY, currChild, value);
currChild = currChild->next();
}
while (currChild) {
/* Reset all remaining layers to not have the property set. */
currChild->clearYPosition();
currChild = currChild->next();
}
}
void StyleBuilderFunctions::applyInitialCSSPropertyBackgroundRepeatX(StyleResolverState& state)
{
FillLayer* currChild = state.style()->accessBackgroundLayers();
currChild->setRepeatX(FillLayer::initialFillRepeatX(BackgroundFillLayer));
for (currChild = currChild->next(); currChild; currChild = currChild->next())
currChild->clearRepeatX();
}
void StyleBuilderFunctions::applyInheritCSSPropertyBackgroundRepeatX(StyleResolverState& state)
{
FillLayer* currChild = state.style()->accessBackgroundLayers();
FillLayer* prevChild = 0;
const FillLayer* currParent = state.parentStyle()->backgroundLayers();
while (currParent && currParent->isRepeatXSet()) {
if (!currChild) {
/* Need to make a new layer.*/
currChild = new FillLayer(BackgroundFillLayer);
prevChild->setNext(currChild);
}
currChild->setRepeatX(currParent->repeatX());
prevChild = currChild;
currChild = prevChild->next();
currParent = currParent->next();
}
while (currChild) {
/* Reset any remaining layers to not have the property set. */
currChild->clearRepeatX();
currChild = currChild->next();
}
}
void StyleBuilderFunctions::applyValueCSSPropertyBackgroundRepeatX(StyleResolverState& state, CSSValue* value)
{
FillLayer* currChild = state.style()->accessBackgroundLayers();
FillLayer* prevChild = 0;
if (value->isValueList() && !value->isImageSetValue()) {
/* Walk each value and put it into a layer, creating new layers as needed. */
CSSValueList* valueList = toCSSValueList(value);
for (unsigned int i = 0; i < valueList->length(); i++) {
if (!currChild) {
/* Need to make a new layer to hold this value */
currChild = new FillLayer(BackgroundFillLayer);
prevChild->setNext(currChild);
}
state.styleMap().mapFillRepeatX(CSSPropertyBackgroundRepeatX, currChild, valueList->itemWithoutBoundsCheck(i));
prevChild = currChild;
currChild = currChild->next();
}
} else {
state.styleMap().mapFillRepeatX(CSSPropertyBackgroundRepeatX, currChild, value);
currChild = currChild->next();
}
while (currChild) {
/* Reset all remaining layers to not have the property set. */
currChild->clearRepeatX();
currChild = currChild->next();
}
}
void StyleBuilderFunctions::applyInitialCSSPropertyBackgroundRepeatY(StyleResolverState& state)
{
FillLayer* currChild = state.style()->accessBackgroundLayers();
currChild->setRepeatY(FillLayer::initialFillRepeatY(BackgroundFillLayer));
for (currChild = currChild->next(); currChild; currChild = currChild->next())
currChild->clearRepeatY();
}
void StyleBuilderFunctions::applyInheritCSSPropertyBackgroundRepeatY(StyleResolverState& state)
{
FillLayer* currChild = state.style()->accessBackgroundLayers();
FillLayer* prevChild = 0;
const FillLayer* currParent = state.parentStyle()->backgroundLayers();
while (currParent && currParent->isRepeatYSet()) {
if (!currChild) {
/* Need to make a new layer.*/
currChild = new FillLayer(BackgroundFillLayer);
prevChild->setNext(currChild);
}
currChild->setRepeatY(currParent->repeatY());
prevChild = currChild;
currChild = prevChild->next();
currParent = currParent->next();
}
while (currChild) {
/* Reset any remaining layers to not have the property set. */
currChild->clearRepeatY();
currChild = currChild->next();
}
}
void StyleBuilderFunctions::applyValueCSSPropertyBackgroundRepeatY(StyleResolverState& state, CSSValue* value)
{
FillLayer* currChild = state.style()->accessBackgroundLayers();
FillLayer* prevChild = 0;
if (value->isValueList() && !value->isImageSetValue()) {
/* Walk each value and put it into a layer, creating new layers as needed. */
CSSValueList* valueList = toCSSValueList(value);
for (unsigned int i = 0; i < valueList->length(); i++) {
if (!currChild) {
/* Need to make a new layer to hold this value */
currChild = new FillLayer(BackgroundFillLayer);
prevChild->setNext(currChild);
}
state.styleMap().mapFillRepeatY(CSSPropertyBackgroundRepeatY, currChild, valueList->itemWithoutBoundsCheck(i));
prevChild = currChild;
currChild = currChild->next();
}
} else {
state.styleMap().mapFillRepeatY(CSSPropertyBackgroundRepeatY, currChild, value);
currChild = currChild->next();
}
while (currChild) {
/* Reset all remaining layers to not have the property set. */
currChild->clearRepeatY();
currChild = currChild->next();
}
}
void StyleBuilderFunctions::applyInitialCSSPropertyBackgroundSize(StyleResolverState& state)
{
FillLayer* currChild = state.style()->accessBackgroundLayers();
currChild->setSize(FillLayer::initialFillSize(BackgroundFillLayer));
for (currChild = currChild->next(); currChild; currChild = currChild->next())
currChild->clearSize();
}
void StyleBuilderFunctions::applyInheritCSSPropertyBackgroundSize(StyleResolverState& state)
{
FillLayer* currChild = state.style()->accessBackgroundLayers();
FillLayer* prevChild = 0;
const FillLayer* currParent = state.parentStyle()->backgroundLayers();
while (currParent && currParent->isSizeSet()) {
if (!currChild) {
/* Need to make a new layer.*/
currChild = new FillLayer(BackgroundFillLayer);
prevChild->setNext(currChild);
}
currChild->setSize(currParent->size());
prevChild = currChild;
currChild = prevChild->next();
currParent = currParent->next();
}
while (currChild) {
/* Reset any remaining layers to not have the property set. */
currChild->clearSize();
currChild = currChild->next();
}
}
void StyleBuilderFunctions::applyValueCSSPropertyBackgroundSize(StyleResolverState& state, CSSValue* value)
{
FillLayer* currChild = state.style()->accessBackgroundLayers();
FillLayer* prevChild = 0;
if (value->isValueList() && !value->isImageSetValue()) {
/* Walk each value and put it into a layer, creating new layers as needed. */
CSSValueList* valueList = toCSSValueList(value);
for (unsigned int i = 0; i < valueList->length(); i++) {
if (!currChild) {
/* Need to make a new layer to hold this value */
currChild = new FillLayer(BackgroundFillLayer);
prevChild->setNext(currChild);
}
state.styleMap().mapFillSize(CSSPropertyBackgroundSize, currChild, valueList->itemWithoutBoundsCheck(i));
prevChild = currChild;
currChild = currChild->next();
}
} else {
state.styleMap().mapFillSize(CSSPropertyBackgroundSize, currChild, value);
currChild = currChild->next();
}
while (currChild) {
/* Reset all remaining layers to not have the property set. */
currChild->clearSize();
currChild = currChild->next();
}
}
void StyleBuilderFunctions::applyInitialCSSPropertyMaskSourceType(StyleResolverState& state)
{
FillLayer* currChild = state.style()->accessMaskLayers();
currChild->setMaskSourceType(FillLayer::initialFillMaskSourceType(MaskFillLayer));
for (currChild = currChild->next(); currChild; currChild = currChild->next())
currChild->clearMaskSourceType();
}
void StyleBuilderFunctions::applyInheritCSSPropertyMaskSourceType(StyleResolverState& state)
{
FillLayer* currChild = state.style()->accessMaskLayers();
FillLayer* prevChild = 0;
const FillLayer* currParent = state.parentStyle()->maskLayers();
while (currParent && currParent->isMaskSourceTypeSet()) {
if (!currChild) {
/* Need to make a new layer.*/
currChild = new FillLayer(MaskFillLayer);
prevChild->setNext(currChild);
}
currChild->setMaskSourceType(currParent->maskSourceType());
prevChild = currChild;
currChild = prevChild->next();
currParent = currParent->next();
}
while (currChild) {
/* Reset any remaining layers to not have the property set. */
currChild->clearMaskSourceType();
currChild = currChild->next();
}
}
void StyleBuilderFunctions::applyValueCSSPropertyMaskSourceType(StyleResolverState& state, CSSValue* value)
{
FillLayer* currChild = state.style()->accessMaskLayers();
FillLayer* prevChild = 0;
if (value->isValueList() && !value->isImageSetValue()) {
/* Walk each value and put it into a layer, creating new layers as needed. */
CSSValueList* valueList = toCSSValueList(value);
for (unsigned int i = 0; i < valueList->length(); i++) {
if (!currChild) {
/* Need to make a new layer to hold this value */
currChild = new FillLayer(MaskFillLayer);
prevChild->setNext(currChild);
}
state.styleMap().mapFillMaskSourceType(CSSPropertyMaskSourceType, currChild, valueList->itemWithoutBoundsCheck(i));
prevChild = currChild;
currChild = currChild->next();
}
} else {
state.styleMap().mapFillMaskSourceType(CSSPropertyMaskSourceType, currChild, value);
currChild = currChild->next();
}
while (currChild) {
/* Reset all remaining layers to not have the property set. */
currChild->clearMaskSourceType();
currChild = currChild->next();
}
}
void StyleBuilderFunctions::applyInitialCSSPropertyWebkitBackgroundComposite(StyleResolverState& state)
{
FillLayer* currChild = state.style()->accessBackgroundLayers();
currChild->setComposite(FillLayer::initialFillComposite(BackgroundFillLayer));
for (currChild = currChild->next(); currChild; currChild = currChild->next())
currChild->clearComposite();
}
void StyleBuilderFunctions::applyInheritCSSPropertyWebkitBackgroundComposite(StyleResolverState& state)
{
FillLayer* currChild = state.style()->accessBackgroundLayers();
FillLayer* prevChild = 0;
const FillLayer* currParent = state.parentStyle()->backgroundLayers();
while (currParent && currParent->isCompositeSet()) {
if (!currChild) {
/* Need to make a new layer.*/
currChild = new FillLayer(BackgroundFillLayer);
prevChild->setNext(currChild);
}
currChild->setComposite(currParent->composite());
prevChild = currChild;
currChild = prevChild->next();
currParent = currParent->next();
}
while (currChild) {
/* Reset any remaining layers to not have the property set. */
currChild->clearComposite();
currChild = currChild->next();
}
}
void StyleBuilderFunctions::applyValueCSSPropertyWebkitBackgroundComposite(StyleResolverState& state, CSSValue* value)
{
FillLayer* currChild = state.style()->accessBackgroundLayers();
FillLayer* prevChild = 0;
if (value->isValueList() && !value->isImageSetValue()) {
/* Walk each value and put it into a layer, creating new layers as needed. */
CSSValueList* valueList = toCSSValueList(value);
for (unsigned int i = 0; i < valueList->length(); i++) {
if (!currChild) {
/* Need to make a new layer to hold this value */
currChild = new FillLayer(BackgroundFillLayer);
prevChild->setNext(currChild);
}
state.styleMap().mapFillComposite(CSSPropertyWebkitBackgroundComposite, currChild, valueList->itemWithoutBoundsCheck(i));
prevChild = currChild;
currChild = currChild->next();
}
} else {
state.styleMap().mapFillComposite(CSSPropertyWebkitBackgroundComposite, currChild, value);
currChild = currChild->next();
}
while (currChild) {
/* Reset all remaining layers to not have the property set. */
currChild->clearComposite();
currChild = currChild->next();
}
}
void StyleBuilderFunctions::applyInitialCSSPropertyWebkitMaskClip(StyleResolverState& state)
{
FillLayer* currChild = state.style()->accessMaskLayers();
currChild->setClip(FillLayer::initialFillClip(MaskFillLayer));
for (currChild = currChild->next(); currChild; currChild = currChild->next())
currChild->clearClip();
}
void StyleBuilderFunctions::applyInheritCSSPropertyWebkitMaskClip(StyleResolverState& state)
{
FillLayer* currChild = state.style()->accessMaskLayers();
FillLayer* prevChild = 0;
const FillLayer* currParent = state.parentStyle()->maskLayers();
while (currParent && currParent->isClipSet()) {
if (!currChild) {
/* Need to make a new layer.*/
currChild = new FillLayer(MaskFillLayer);
prevChild->setNext(currChild);
}
currChild->setClip(currParent->clip());
prevChild = currChild;
currChild = prevChild->next();
currParent = currParent->next();
}
while (currChild) {
/* Reset any remaining layers to not have the property set. */
currChild->clearClip();
currChild = currChild->next();
}
}
void StyleBuilderFunctions::applyValueCSSPropertyWebkitMaskClip(StyleResolverState& state, CSSValue* value)
{
FillLayer* currChild = state.style()->accessMaskLayers();
FillLayer* prevChild = 0;
if (value->isValueList() && !value->isImageSetValue()) {
/* Walk each value and put it into a layer, creating new layers as needed. */
CSSValueList* valueList = toCSSValueList(value);
for (unsigned int i = 0; i < valueList->length(); i++) {
if (!currChild) {
/* Need to make a new layer to hold this value */
currChild = new FillLayer(MaskFillLayer);
prevChild->setNext(currChild);
}
state.styleMap().mapFillClip(CSSPropertyWebkitMaskClip, currChild, valueList->itemWithoutBoundsCheck(i));
prevChild = currChild;
currChild = currChild->next();
}
} else {
state.styleMap().mapFillClip(CSSPropertyWebkitMaskClip, currChild, value);
currChild = currChild->next();
}
while (currChild) {
/* Reset all remaining layers to not have the property set. */
currChild->clearClip();
currChild = currChild->next();
}
}
void StyleBuilderFunctions::applyInitialCSSPropertyWebkitMaskComposite(StyleResolverState& state)
{
FillLayer* currChild = state.style()->accessMaskLayers();
currChild->setComposite(FillLayer::initialFillComposite(MaskFillLayer));
for (currChild = currChild->next(); currChild; currChild = currChild->next())
currChild->clearComposite();
}
void StyleBuilderFunctions::applyInheritCSSPropertyWebkitMaskComposite(StyleResolverState& state)
{
FillLayer* currChild = state.style()->accessMaskLayers();
FillLayer* prevChild = 0;
const FillLayer* currParent = state.parentStyle()->maskLayers();
while (currParent && currParent->isCompositeSet()) {
if (!currChild) {
/* Need to make a new layer.*/
currChild = new FillLayer(MaskFillLayer);
prevChild->setNext(currChild);
}
currChild->setComposite(currParent->composite());
prevChild = currChild;
currChild = prevChild->next();
currParent = currParent->next();
}
while (currChild) {
/* Reset any remaining layers to not have the property set. */
currChild->clearComposite();
currChild = currChild->next();
}
}
void StyleBuilderFunctions::applyValueCSSPropertyWebkitMaskComposite(StyleResolverState& state, CSSValue* value)
{
FillLayer* currChild = state.style()->accessMaskLayers();
FillLayer* prevChild = 0;
if (value->isValueList() && !value->isImageSetValue()) {
/* Walk each value and put it into a layer, creating new layers as needed. */
CSSValueList* valueList = toCSSValueList(value);
for (unsigned int i = 0; i < valueList->length(); i++) {
if (!currChild) {
/* Need to make a new layer to hold this value */
currChild = new FillLayer(MaskFillLayer);
prevChild->setNext(currChild);
}
state.styleMap().mapFillComposite(CSSPropertyWebkitMaskComposite, currChild, valueList->itemWithoutBoundsCheck(i));
prevChild = currChild;
currChild = currChild->next();
}
} else {
state.styleMap().mapFillComposite(CSSPropertyWebkitMaskComposite, currChild, value);
currChild = currChild->next();
}
while (currChild) {
/* Reset all remaining layers to not have the property set. */
currChild->clearComposite();
currChild = currChild->next();
}
}
void StyleBuilderFunctions::applyInitialCSSPropertyWebkitMaskImage(StyleResolverState& state)
{
FillLayer* currChild = state.style()->accessMaskLayers();
currChild->setImage(FillLayer::initialFillImage(MaskFillLayer));
for (currChild = currChild->next(); currChild; currChild = currChild->next())
currChild->clearImage();
}
void StyleBuilderFunctions::applyInheritCSSPropertyWebkitMaskImage(StyleResolverState& state)
{
FillLayer* currChild = state.style()->accessMaskLayers();
FillLayer* prevChild = 0;
const FillLayer* currParent = state.parentStyle()->maskLayers();
while (currParent && currParent->isImageSet()) {
if (!currChild) {
/* Need to make a new layer.*/
currChild = new FillLayer(MaskFillLayer);
prevChild->setNext(currChild);
}
currChild->setImage(currParent->image());
prevChild = currChild;
currChild = prevChild->next();
currParent = currParent->next();
}
while (currChild) {
/* Reset any remaining layers to not have the property set. */
currChild->clearImage();
currChild = currChild->next();
}
}
void StyleBuilderFunctions::applyValueCSSPropertyWebkitMaskImage(StyleResolverState& state, CSSValue* value)
{
FillLayer* currChild = state.style()->accessMaskLayers();
FillLayer* prevChild = 0;
if (value->isValueList() && !value->isImageSetValue()) {
/* Walk each value and put it into a layer, creating new layers as needed. */
CSSValueList* valueList = toCSSValueList(value);
for (unsigned int i = 0; i < valueList->length(); i++) {
if (!currChild) {
/* Need to make a new layer to hold this value */
currChild = new FillLayer(MaskFillLayer);
prevChild->setNext(currChild);
}
state.styleMap().mapFillImage(CSSPropertyWebkitMaskImage, currChild, valueList->itemWithoutBoundsCheck(i));
prevChild = currChild;
currChild = currChild->next();
}
} else {
state.styleMap().mapFillImage(CSSPropertyWebkitMaskImage, currChild, value);
currChild = currChild->next();
}
while (currChild) {
/* Reset all remaining layers to not have the property set. */
currChild->clearImage();
currChild = currChild->next();
}
}
void StyleBuilderFunctions::applyInitialCSSPropertyWebkitMaskOrigin(StyleResolverState& state)
{
FillLayer* currChild = state.style()->accessMaskLayers();
currChild->setOrigin(FillLayer::initialFillOrigin(MaskFillLayer));
for (currChild = currChild->next(); currChild; currChild = currChild->next())
currChild->clearOrigin();
}
void StyleBuilderFunctions::applyInheritCSSPropertyWebkitMaskOrigin(StyleResolverState& state)
{
FillLayer* currChild = state.style()->accessMaskLayers();
FillLayer* prevChild = 0;
const FillLayer* currParent = state.parentStyle()->maskLayers();
while (currParent && currParent->isOriginSet()) {
if (!currChild) {
/* Need to make a new layer.*/
currChild = new FillLayer(MaskFillLayer);
prevChild->setNext(currChild);
}
currChild->setOrigin(currParent->origin());
prevChild = currChild;
currChild = prevChild->next();
currParent = currParent->next();
}
while (currChild) {
/* Reset any remaining layers to not have the property set. */
currChild->clearOrigin();
currChild = currChild->next();
}
}
void StyleBuilderFunctions::applyValueCSSPropertyWebkitMaskOrigin(StyleResolverState& state, CSSValue* value)
{
FillLayer* currChild = state.style()->accessMaskLayers();
FillLayer* prevChild = 0;
if (value->isValueList() && !value->isImageSetValue()) {
/* Walk each value and put it into a layer, creating new layers as needed. */
CSSValueList* valueList = toCSSValueList(value);
for (unsigned int i = 0; i < valueList->length(); i++) {
if (!currChild) {
/* Need to make a new layer to hold this value */
currChild = new FillLayer(MaskFillLayer);
prevChild->setNext(currChild);
}
state.styleMap().mapFillOrigin(CSSPropertyWebkitMaskOrigin, currChild, valueList->itemWithoutBoundsCheck(i));
prevChild = currChild;
currChild = currChild->next();
}
} else {
state.styleMap().mapFillOrigin(CSSPropertyWebkitMaskOrigin, currChild, value);
currChild = currChild->next();
}
while (currChild) {
/* Reset all remaining layers to not have the property set. */
currChild->clearOrigin();
currChild = currChild->next();
}
}
void StyleBuilderFunctions::applyInitialCSSPropertyWebkitMaskPositionX(StyleResolverState& state)
{
FillLayer* currChild = state.style()->accessMaskLayers();
currChild->setXPosition(FillLayer::initialFillXPosition(MaskFillLayer));
for (currChild = currChild->next(); currChild; currChild = currChild->next())
currChild->clearXPosition();
}
void StyleBuilderFunctions::applyInheritCSSPropertyWebkitMaskPositionX(StyleResolverState& state)
{
FillLayer* currChild = state.style()->accessMaskLayers();
FillLayer* prevChild = 0;
const FillLayer* currParent = state.parentStyle()->maskLayers();
while (currParent && currParent->isXPositionSet()) {
if (!currChild) {
/* Need to make a new layer.*/
currChild = new FillLayer(MaskFillLayer);
prevChild->setNext(currChild);
}
currChild->setXPosition(currParent->xPosition());
prevChild = currChild;
currChild = prevChild->next();
currParent = currParent->next();
}
while (currChild) {
/* Reset any remaining layers to not have the property set. */
currChild->clearXPosition();
currChild = currChild->next();
}
}
void StyleBuilderFunctions::applyValueCSSPropertyWebkitMaskPositionX(StyleResolverState& state, CSSValue* value)
{
FillLayer* currChild = state.style()->accessMaskLayers();
FillLayer* prevChild = 0;
if (value->isValueList() && !value->isImageSetValue()) {
/* Walk each value and put it into a layer, creating new layers as needed. */
CSSValueList* valueList = toCSSValueList(value);
for (unsigned int i = 0; i < valueList->length(); i++) {
if (!currChild) {
/* Need to make a new layer to hold this value */
currChild = new FillLayer(MaskFillLayer);
prevChild->setNext(currChild);
}
state.styleMap().mapFillXPosition(CSSPropertyWebkitMaskPositionX, currChild, valueList->itemWithoutBoundsCheck(i));
prevChild = currChild;
currChild = currChild->next();
}
} else {
state.styleMap().mapFillXPosition(CSSPropertyWebkitMaskPositionX, currChild, value);
currChild = currChild->next();
}
while (currChild) {
/* Reset all remaining layers to not have the property set. */
currChild->clearXPosition();
currChild = currChild->next();
}
}
void StyleBuilderFunctions::applyInitialCSSPropertyWebkitMaskPositionY(StyleResolverState& state)
{
FillLayer* currChild = state.style()->accessMaskLayers();
currChild->setYPosition(FillLayer::initialFillYPosition(MaskFillLayer));
for (currChild = currChild->next(); currChild; currChild = currChild->next())
currChild->clearYPosition();
}
void StyleBuilderFunctions::applyInheritCSSPropertyWebkitMaskPositionY(StyleResolverState& state)
{
FillLayer* currChild = state.style()->accessMaskLayers();
FillLayer* prevChild = 0;
const FillLayer* currParent = state.parentStyle()->maskLayers();
while (currParent && currParent->isYPositionSet()) {
if (!currChild) {
/* Need to make a new layer.*/
currChild = new FillLayer(MaskFillLayer);
prevChild->setNext(currChild);
}
currChild->setYPosition(currParent->yPosition());
prevChild = currChild;
currChild = prevChild->next();
currParent = currParent->next();
}
while (currChild) {
/* Reset any remaining layers to not have the property set. */
currChild->clearYPosition();
currChild = currChild->next();
}
}
void StyleBuilderFunctions::applyValueCSSPropertyWebkitMaskPositionY(StyleResolverState& state, CSSValue* value)
{
FillLayer* currChild = state.style()->accessMaskLayers();
FillLayer* prevChild = 0;
if (value->isValueList() && !value->isImageSetValue()) {
/* Walk each value and put it into a layer, creating new layers as needed. */
CSSValueList* valueList = toCSSValueList(value);
for (unsigned int i = 0; i < valueList->length(); i++) {
if (!currChild) {
/* Need to make a new layer to hold this value */
currChild = new FillLayer(MaskFillLayer);
prevChild->setNext(currChild);
}
state.styleMap().mapFillYPosition(CSSPropertyWebkitMaskPositionY, currChild, valueList->itemWithoutBoundsCheck(i));
prevChild = currChild;
currChild = currChild->next();
}
} else {
state.styleMap().mapFillYPosition(CSSPropertyWebkitMaskPositionY, currChild, value);
currChild = currChild->next();
}
while (currChild) {
/* Reset all remaining layers to not have the property set. */
currChild->clearYPosition();
currChild = currChild->next();
}
}
void StyleBuilderFunctions::applyInitialCSSPropertyWebkitMaskRepeatX(StyleResolverState& state)
{
FillLayer* currChild = state.style()->accessMaskLayers();
currChild->setRepeatX(FillLayer::initialFillRepeatX(MaskFillLayer));
for (currChild = currChild->next(); currChild; currChild = currChild->next())
currChild->clearRepeatX();
}
void StyleBuilderFunctions::applyInheritCSSPropertyWebkitMaskRepeatX(StyleResolverState& state)
{
FillLayer* currChild = state.style()->accessMaskLayers();
FillLayer* prevChild = 0;
const FillLayer* currParent = state.parentStyle()->maskLayers();
while (currParent && currParent->isRepeatXSet()) {
if (!currChild) {
/* Need to make a new layer.*/
currChild = new FillLayer(MaskFillLayer);
prevChild->setNext(currChild);
}
currChild->setRepeatX(currParent->repeatX());
prevChild = currChild;
currChild = prevChild->next();
currParent = currParent->next();
}
while (currChild) {
/* Reset any remaining layers to not have the property set. */
currChild->clearRepeatX();
currChild = currChild->next();
}
}
void StyleBuilderFunctions::applyValueCSSPropertyWebkitMaskRepeatX(StyleResolverState& state, CSSValue* value)
{
FillLayer* currChild = state.style()->accessMaskLayers();
FillLayer* prevChild = 0;
if (value->isValueList() && !value->isImageSetValue()) {
/* Walk each value and put it into a layer, creating new layers as needed. */
CSSValueList* valueList = toCSSValueList(value);
for (unsigned int i = 0; i < valueList->length(); i++) {
if (!currChild) {
/* Need to make a new layer to hold this value */
currChild = new FillLayer(MaskFillLayer);
prevChild->setNext(currChild);
}
state.styleMap().mapFillRepeatX(CSSPropertyWebkitMaskRepeatX, currChild, valueList->itemWithoutBoundsCheck(i));
prevChild = currChild;
currChild = currChild->next();
}
} else {
state.styleMap().mapFillRepeatX(CSSPropertyWebkitMaskRepeatX, currChild, value);
currChild = currChild->next();
}
while (currChild) {
/* Reset all remaining layers to not have the property set. */
currChild->clearRepeatX();
currChild = currChild->next();
}
}
void StyleBuilderFunctions::applyInitialCSSPropertyWebkitMaskRepeatY(StyleResolverState& state)
{
FillLayer* currChild = state.style()->accessMaskLayers();
currChild->setRepeatY(FillLayer::initialFillRepeatY(MaskFillLayer));
for (currChild = currChild->next(); currChild; currChild = currChild->next())
currChild->clearRepeatY();
}
void StyleBuilderFunctions::applyInheritCSSPropertyWebkitMaskRepeatY(StyleResolverState& state)
{
FillLayer* currChild = state.style()->accessMaskLayers();
FillLayer* prevChild = 0;
const FillLayer* currParent = state.parentStyle()->maskLayers();
while (currParent && currParent->isRepeatYSet()) {
if (!currChild) {
/* Need to make a new layer.*/
currChild = new FillLayer(MaskFillLayer);
prevChild->setNext(currChild);
}
currChild->setRepeatY(currParent->repeatY());
prevChild = currChild;
currChild = prevChild->next();
currParent = currParent->next();
}
while (currChild) {
/* Reset any remaining layers to not have the property set. */
currChild->clearRepeatY();
currChild = currChild->next();
}
}
void StyleBuilderFunctions::applyValueCSSPropertyWebkitMaskRepeatY(StyleResolverState& state, CSSValue* value)
{
FillLayer* currChild = state.style()->accessMaskLayers();
FillLayer* prevChild = 0;
if (value->isValueList() && !value->isImageSetValue()) {
/* Walk each value and put it into a layer, creating new layers as needed. */
CSSValueList* valueList = toCSSValueList(value);
for (unsigned int i = 0; i < valueList->length(); i++) {
if (!currChild) {
/* Need to make a new layer to hold this value */
currChild = new FillLayer(MaskFillLayer);
prevChild->setNext(currChild);
}
state.styleMap().mapFillRepeatY(CSSPropertyWebkitMaskRepeatY, currChild, valueList->itemWithoutBoundsCheck(i));
prevChild = currChild;
currChild = currChild->next();
}
} else {
state.styleMap().mapFillRepeatY(CSSPropertyWebkitMaskRepeatY, currChild, value);
currChild = currChild->next();
}
while (currChild) {
/* Reset all remaining layers to not have the property set. */
currChild->clearRepeatY();
currChild = currChild->next();
}
}
void StyleBuilderFunctions::applyInitialCSSPropertyWebkitMaskSize(StyleResolverState& state)
{
FillLayer* currChild = state.style()->accessMaskLayers();
currChild->setSize(FillLayer::initialFillSize(MaskFillLayer));
for (currChild = currChild->next(); currChild; currChild = currChild->next())
currChild->clearSize();
}
void StyleBuilderFunctions::applyInheritCSSPropertyWebkitMaskSize(StyleResolverState& state)
{
FillLayer* currChild = state.style()->accessMaskLayers();
FillLayer* prevChild = 0;
const FillLayer* currParent = state.parentStyle()->maskLayers();
while (currParent && currParent->isSizeSet()) {
if (!currChild) {
/* Need to make a new layer.*/
currChild = new FillLayer(MaskFillLayer);
prevChild->setNext(currChild);
}
currChild->setSize(currParent->size());
prevChild = currChild;
currChild = prevChild->next();
currParent = currParent->next();
}
while (currChild) {
/* Reset any remaining layers to not have the property set. */
currChild->clearSize();
currChild = currChild->next();
}
}
void StyleBuilderFunctions::applyValueCSSPropertyWebkitMaskSize(StyleResolverState& state, CSSValue* value)
{
FillLayer* currChild = state.style()->accessMaskLayers();
FillLayer* prevChild = 0;
if (value->isValueList() && !value->isImageSetValue()) {
/* Walk each value and put it into a layer, creating new layers as needed. */
CSSValueList* valueList = toCSSValueList(value);
for (unsigned int i = 0; i < valueList->length(); i++) {
if (!currChild) {
/* Need to make a new layer to hold this value */
currChild = new FillLayer(MaskFillLayer);
prevChild->setNext(currChild);
}
state.styleMap().mapFillSize(CSSPropertyWebkitMaskSize, currChild, valueList->itemWithoutBoundsCheck(i));
prevChild = currChild;
currChild = currChild->next();
}
} else {
state.styleMap().mapFillSize(CSSPropertyWebkitMaskSize, currChild, value);
currChild = currChild->next();
}
while (currChild) {
/* Reset all remaining layers to not have the property set. */
currChild->clearSize();
currChild = currChild->next();
}
}
void StyleBuilderFunctions::applyInitialCSSPropertyGridTemplateColumns(StyleResolverState& state)
{
state.style()->setGridTemplateColumns(RenderStyle::initialGridTemplateColumns());
state.style()->setNamedGridColumnLines(RenderStyle::initialNamedGridColumnLines());
state.style()->setOrderedNamedGridColumnLines(RenderStyle::initialOrderedNamedGridColumnLines());
}
void StyleBuilderFunctions::applyInheritCSSPropertyGridTemplateColumns(StyleResolverState& state)
{
state.style()->setGridTemplateColumns(state.parentStyle()->gridTemplateColumns());
state.style()->setNamedGridColumnLines(state.parentStyle()->namedGridColumnLines());
state.style()->setOrderedNamedGridColumnLines(state.parentStyle()->orderedNamedGridColumnLines());
}
void StyleBuilderFunctions::applyValueCSSPropertyGridTemplateColumns(StyleResolverState& state, CSSValue* value)
{
Vector<GridTrackSize> trackSizes;
NamedGridLinesMap namedGridLines;
OrderedNamedGridLines orderedNamedGridLines;
if (!StyleBuilderConverter::convertGridTrackList(value, trackSizes, namedGridLines, orderedNamedGridLines, state))
return;
const NamedGridAreaMap& namedGridAreas = state.style()->namedGridArea();
if (!namedGridAreas.isEmpty())
StyleBuilderConverter::createImplicitNamedGridLinesFromGridArea(namedGridAreas, namedGridLines, ForColumns);
state.style()->setGridTemplateColumns(trackSizes);
state.style()->setNamedGridColumnLines(namedGridLines);
state.style()->setOrderedNamedGridColumnLines(orderedNamedGridLines);
}
void StyleBuilderFunctions::applyInitialCSSPropertyGridTemplateRows(StyleResolverState& state)
{
state.style()->setGridTemplateRows(RenderStyle::initialGridTemplateRows());
state.style()->setNamedGridRowLines(RenderStyle::initialNamedGridRowLines());
state.style()->setOrderedNamedGridRowLines(RenderStyle::initialOrderedNamedGridRowLines());
}
void StyleBuilderFunctions::applyInheritCSSPropertyGridTemplateRows(StyleResolverState& state)
{
state.style()->setGridTemplateRows(state.parentStyle()->gridTemplateRows());
state.style()->setNamedGridRowLines(state.parentStyle()->namedGridRowLines());
state.style()->setOrderedNamedGridRowLines(state.parentStyle()->orderedNamedGridRowLines());
}
void StyleBuilderFunctions::applyValueCSSPropertyGridTemplateRows(StyleResolverState& state, CSSValue* value)
{
Vector<GridTrackSize> trackSizes;
NamedGridLinesMap namedGridLines;
OrderedNamedGridLines orderedNamedGridLines;
if (!StyleBuilderConverter::convertGridTrackList(value, trackSizes, namedGridLines, orderedNamedGridLines, state))
return;
const NamedGridAreaMap& namedGridAreas = state.style()->namedGridArea();
if (!namedGridAreas.isEmpty())
StyleBuilderConverter::createImplicitNamedGridLinesFromGridArea(namedGridAreas, namedGridLines, ForRows);
state.style()->setGridTemplateRows(trackSizes);
state.style()->setNamedGridRowLines(namedGridLines);
state.style()->setOrderedNamedGridRowLines(orderedNamedGridLines);
}
void StyleBuilderFunctions::applyValueCSSPropertyInternalMarqueeRepetition(StyleResolverState& state, CSSValue* value)
{
if (!value->isPrimitiveValue())
return;
CSSPrimitiveValue* primitiveValue = toCSSPrimitiveValue(value);
if (primitiveValue->getValueID() == CSSValueInfinite)
state.style()->setMarqueeLoopCount(-1);
else
state.style()->setMarqueeLoopCount(primitiveValue->getValue<int>(CSSPrimitiveValue::CSS_NUMBER));
}
void StyleBuilderFunctions::applyValueCSSPropertyShapeOutside(StyleResolverState& state, CSSValue* value)
{
if (value->isPrimitiveValue()) {
CSSPrimitiveValue* primitiveValue = toCSSPrimitiveValue(value);
if (primitiveValue->getValueID() == CSSValueNone)
state.style()->setShapeOutside(nullptr);
} else if (value->isImageValue() || value->isImageGeneratorValue() || value->isImageSetValue()) {
state.style()->setShapeOutside(ShapeValue::createImageValue(state.styleImage(CSSPropertyShapeOutside, value)));
} else if (value->isValueList()) {
RefPtr<BasicShape> shape;
CSSBoxType cssBox = BoxMissing;
CSSValueList* valueList = toCSSValueList(value);
for (unsigned i = 0; i < valueList->length(); ++i) {
CSSPrimitiveValue* primitiveValue = toCSSPrimitiveValue(valueList->itemWithoutBoundsCheck(i));
if (primitiveValue->isShape())
shape = basicShapeForValue(state, primitiveValue->getShapeValue());
else if (primitiveValue->getValueID() == CSSValueContentBox
|| primitiveValue->getValueID() == CSSValueBorderBox
|| primitiveValue->getValueID() == CSSValuePaddingBox
|| primitiveValue->getValueID() == CSSValueMarginBox)
cssBox = CSSBoxType(*primitiveValue);
else
return;
}
if (shape)
state.style()->setShapeOutside(ShapeValue::createShapeValue(shape.release(), cssBox));
else if (cssBox != BoxMissing)
state.style()->setShapeOutside(ShapeValue::createBoxShapeValue(cssBox));
}
}
void StyleBuilderFunctions::applyValueCSSPropertyJustifySelf(StyleResolverState& state, CSSValue* value)
{
CSSPrimitiveValue* primitiveValue = toCSSPrimitiveValue(value);
if (Pair* pairValue = primitiveValue->getPairValue()) {
state.style()->setJustifySelf(*pairValue->first());
state.style()->setJustifySelfOverflowAlignment(*pairValue->second());
} else {
state.style()->setJustifySelf(*primitiveValue);
// FIXME: We should clear the overflow-alignment mode here and probably
// also set it in the initial and inherit handlers
}
}
void StyleBuilderFunctions::applyValueCSSPropertyAlignItems(StyleResolverState& state, CSSValue* value)
{
CSSPrimitiveValue* primitiveValue = toCSSPrimitiveValue(value);
if (Pair* pairValue = primitiveValue->getPairValue()) {
state.style()->setAlignItems(*pairValue->first());
state.style()->setAlignItemsOverflowAlignment(*pairValue->second());
} else {
state.style()->setAlignItems(*primitiveValue);
// FIXME: We should clear the overflow-alignment mode here and probably
// also set it in the initial and inherit handlers
}
}
void StyleBuilderFunctions::applyValueCSSPropertyAlignSelf(StyleResolverState& state, CSSValue* value)
{
CSSPrimitiveValue* primitiveValue = toCSSPrimitiveValue(value);
if (Pair* pairValue = primitiveValue->getPairValue()) {
state.style()->setAlignSelf(*pairValue->first());
state.style()->setAlignSelfOverflowAlignment(*pairValue->second());
} else {
state.style()->setAlignSelf(*primitiveValue);
// FIXME: We should clear the overflow-alignment mode here and probably
// also set it in the initial and inherit handlers
}
}
void StyleBuilderFunctions::applyInitialCSSPropertyFill(StyleResolverState& state)
{
state.style()->accessSVGStyle()->setFillPaint(
SVGRenderStyle::initialFillPaintType(),
SVGRenderStyle::initialFillPaintColor(),
SVGRenderStyle::initialFillPaintUri(),
state.applyPropertyToRegularStyle(),
state.applyPropertyToVisitedLinkStyle());
}
void StyleBuilderFunctions::applyInheritCSSPropertyFill(StyleResolverState& state)
{
const SVGRenderStyle* svgParentStyle = state.parentStyle()->svgStyle();
state.style()->accessSVGStyle()->setFillPaint(
svgParentStyle->fillPaintType(),
svgParentStyle->fillPaintColor(),
svgParentStyle->fillPaintUri(),
state.applyPropertyToRegularStyle(),
state.applyPropertyToVisitedLinkStyle());
}
void StyleBuilderFunctions::applyValueCSSPropertyFill(StyleResolverState& state, CSSValue* value)
{
if (value->isSVGPaint()) {
SVGPaint* svgPaint = toSVGPaint(value);
Color color;
if (svgPaint->paintType() == SVGPaint::SVG_PAINTTYPE_CURRENTCOLOR
|| svgPaint->paintType() == SVGPaint::SVG_PAINTTYPE_URI_CURRENTCOLOR)
color = state.style()->color();
else
color = svgPaint->color();
state.style()->accessSVGStyle()->setFillPaint(svgPaint->paintType(),
color,
svgPaint->uri(),
state.applyPropertyToRegularStyle(),
state.applyPropertyToVisitedLinkStyle());
}
}
void StyleBuilderFunctions::applyInitialCSSPropertyStroke(StyleResolverState& state)
{
state.style()->accessSVGStyle()->setStrokePaint(
SVGRenderStyle::initialStrokePaintType(),
SVGRenderStyle::initialStrokePaintColor(),
SVGRenderStyle::initialStrokePaintUri(),
state.applyPropertyToRegularStyle(),
state.applyPropertyToVisitedLinkStyle());
}
void StyleBuilderFunctions::applyInheritCSSPropertyStroke(StyleResolverState& state)
{
const SVGRenderStyle* svgParentStyle = state.parentStyle()->svgStyle();
state.style()->accessSVGStyle()->setStrokePaint(
svgParentStyle->strokePaintType(),
svgParentStyle->strokePaintColor(),
svgParentStyle->strokePaintUri(),
state.applyPropertyToRegularStyle(),
state.applyPropertyToVisitedLinkStyle());
}
void StyleBuilderFunctions::applyValueCSSPropertyStroke(StyleResolverState& state, CSSValue* value)
{
if (value->isSVGPaint()) {
SVGPaint* svgPaint = toSVGPaint(value);
Color color;
if (svgPaint->paintType() == SVGPaint::SVG_PAINTTYPE_CURRENTCOLOR
|| svgPaint->paintType() == SVGPaint::SVG_PAINTTYPE_URI_CURRENTCOLOR)
color = state.style()->color();
else
color = svgPaint->color();
state.style()->accessSVGStyle()->setStrokePaint(svgPaint->paintType(),
color,
svgPaint->uri(),
state.applyPropertyToRegularStyle(),
state.applyPropertyToVisitedLinkStyle());
}
}
} // namespace WebCore
| 39.281239 | 162 | 0.762755 | [
"shape",
"vector",
"transform"
] |
ed0bff2a87ffaa945f5ad04dac10c810deaecd84 | 1,984 | cpp | C++ | C++/minimum-number-of-work-sessions-to-finish-the-tasks.cpp | Priyansh2/LeetCode-Solutions | d613da1881ec2416ccbe15f20b8000e36ddf1291 | [
"MIT"
] | 3,269 | 2018-10-12T01:29:40.000Z | 2022-03-31T17:58:41.000Z | C++/minimum-number-of-work-sessions-to-finish-the-tasks.cpp | Priyansh2/LeetCode-Solutions | d613da1881ec2416ccbe15f20b8000e36ddf1291 | [
"MIT"
] | 53 | 2018-12-16T22:54:20.000Z | 2022-02-25T08:31:20.000Z | C++/minimum-number-of-work-sessions-to-finish-the-tasks.cpp | Priyansh2/LeetCode-Solutions | d613da1881ec2416ccbe15f20b8000e36ddf1291 | [
"MIT"
] | 1,236 | 2018-10-12T02:51:40.000Z | 2022-03-30T13:30:37.000Z | // Time: O(n * 2^n)
// Space: O(2^n)
class Solution {
public:
int minSessions(vector<int>& tasks, int sessionTime) {
// dp[mask]: min used time by choosing tasks in mask bitset
vector<int> dp(1 << size(tasks), numeric_limits<int>::max());
dp[0] = 0;
for (int mask = 0; mask < size(dp) - 1; ++mask) {
int basis = 1;
for (auto task : tasks) {
const int new_mask = mask | basis;
basis <<= 1;
if (new_mask == mask) {
continue;
}
if (dp[mask] % sessionTime + task > sessionTime) {
task += sessionTime - dp[mask] % sessionTime; // take a break
}
dp[new_mask] = min(dp[new_mask], dp[mask] + task);
}
}
return (dp.back() + sessionTime - 1) / sessionTime;
}
};
// Time: O(n * 2^n)
// Space: O(2^n)
class Solution2 {
public:
int minSessions(vector<int>& tasks, int sessionTime) {
// dp[mask][0]: min number of sessions by choosing tasks in mask bitset
// dp[mask][1]: min used time of last session by choosing tasks in mask bitset
vector<pair<int, int>> dp(1 << size(tasks), pair(numeric_limits<int>::max(), numeric_limits<int>::max()));
dp[0] = {0, sessionTime};
for (int mask = 0; mask < size(dp) - 1; ++mask) {
int basis = 1;
for (const auto& task : tasks) {
const int new_mask = mask | basis;
basis <<= 1;
if (new_mask == mask) {
continue;
}
if (dp[mask].second + task <= sessionTime) {
dp[new_mask] = min(dp[new_mask], {dp[mask].first, dp[mask].second + task});
} else {
dp[new_mask] = min(dp[new_mask], {dp[mask].first + 1, task});
}
}
}
return dp.back().first;
}
};
| 36.072727 | 114 | 0.472782 | [
"vector"
] |
ed0d0886d5bd7de6130b0013d385ac80cb3796ed | 874 | cpp | C++ | LeetCode/Largest Plus Sign/main.cpp | Code-With-Aagam/competitive-programming | 610520cc396fb13a03c606b5fb6739cfd68cc444 | [
"MIT"
] | 2 | 2022-02-08T12:37:41.000Z | 2022-03-09T03:48:56.000Z | LeetCode/Largest Plus Sign/main.cpp | Code-With-Aagam/competitive-programming | 610520cc396fb13a03c606b5fb6739cfd68cc444 | [
"MIT"
] | null | null | null | LeetCode/Largest Plus Sign/main.cpp | Code-With-Aagam/competitive-programming | 610520cc396fb13a03c606b5fb6739cfd68cc444 | [
"MIT"
] | null | null | null | class Solution {
public:
int orderOfLargestPlusSign(int n, vector<vector<int>> &mines) {
vector<vector<int>> dp(n, vector<int>(n, n));
for (const auto &ele : mines) {
dp[ele[0]][ele[1]] = 0;
}
for (int i = 0; i < n; ++i) {
int l = 0, r = 0, t = 0, b = 0;
for (int j = 0; j < n; ++j) {
dp[i][j] = min(dp[i][j], (l = dp[i][j] ? l + 1 : 0));
dp[i][n - j - 1] = min(dp[i][n - j - 1], (r = dp[i][n - j - 1] ? r + 1 : 0));
dp[j][i] = min(dp[j][i], (t = dp[j][i] ? t + 1 : 0));
dp[n - j - 1][i] = min(dp[n - j - 1][i], (b = dp[n - j - 1][i] ? b + 1 : 0));
}
}
int ans = 0;
for (const auto &ele : dp) {
ans = max(ans, *max_element(cbegin(ele), cend(ele)));
}
return ans;
}
}; | 38 | 93 | 0.363844 | [
"vector"
] |
ed13a3f0c5e40a72f600925877dda2e26d96d06d | 2,409 | cpp | C++ | Topcoder/practice/PrimeAnagrams.cpp | Shahraaz/CP_P_S5 | b068ad02d34338337e549d92a14e3b3d9e8df712 | [
"MIT"
] | null | null | null | Topcoder/practice/PrimeAnagrams.cpp | Shahraaz/CP_P_S5 | b068ad02d34338337e549d92a14e3b3d9e8df712 | [
"MIT"
] | null | null | null | Topcoder/practice/PrimeAnagrams.cpp | Shahraaz/CP_P_S5 | b068ad02d34338337e549d92a14e3b3d9e8df712 | [
"MIT"
] | null | null | null | //Optimise
#include <bits/stdc++.h>
using namespace std;
// #define multitest 1
// #define Debug
#ifdef Debug
#define db(...) ZZ(#__VA_ARGS__, __VA_ARGS__);
#define pc(...) PC(#__VA_ARGS__, __VA_ARGS__);
template <typename T, typename U>
ostream &operator<<(ostream &out, const pair<T, U> &p)
{
out << '[' << p.first << ", " << p.second << ']';
return out;
}
template <typename Arg>
void PC(const char *name, Arg &&arg)
{
std::cerr << name << " { ";
for (const auto &v : arg)
cerr << v << ' ';
cerr << " }\n";
}
template <typename Arg1>
void ZZ(const char *name, Arg1 &&arg1)
{
std::cerr << name << " = " << arg1 << endl;
}
template <typename Arg1, typename... Args>
void ZZ(const char *names, Arg1 &&arg1, Args &&... args)
{
const char *comma = strchr(names + 1, ',');
std::cerr.write(names, comma - names) << " = " << arg1;
ZZ(comma, args...);
}
#else
#define db(...)
#define pc(...)
#endif
using ll = long long;
#define f first
#define s second
#define pb push_back
const long long mod = 1000000007;
const int nax = 2e5 + 10;
const int _NSeive = 2e5 + 10;
vector<bool> isPrime(_NSeive, true);
void buildSeive()
{
isPrime[1] = false;
isPrime[0] = false;
for (int i = 4; i < _NSeive; i += 2)
isPrime[i] = false;
for (int i = 3; i * i < _NSeive; i += 3)
if (isPrime[i])
for (int j = i * i; j < _NSeive; j += i)
isPrime[j] = false;
}
class PrimeAnagrams
{
private:
vector<int> DCnt;
vector<int> Ret;
ll minProd;
string anagram;
pair<bool, int> solve(vector<char> N)
{
sort(N.begin(), N.end());
do
{
/* code */
} while (next_permutation(N.begin(), N.end()));
return {0, 0};
}
public:
vector<int> primes(string anagram)
{
buildSeive();
this->anagram = anagram;
minProd = LLONG_MAX;
int l = anagram.length();
for (int i = 1; i < (1 << (l + 1)); ++i)
{
int n1 = 0;
vector<char> N1;
for (int j = 0; j < l; ++j)
N1.pb(anagram[j]);
auto minPoss = solve(N1);
for (int j = 1; j < (1 << (l + 1)); ++j)
{
}
}
sort(Ret.begin(), Ret.end());
return Ret;
}
};
#ifdef Offline
int main()
{
ios_base::sync_with_stdio(0);
cin.tie(0);
int t = 1;
auto TimeStart = chrono::steady_clock::now();
#ifdef multitest
cin >> t;
#endif
Solver S;
while (t--)
S.Solve();
#ifdef TIME
cerr << "\n\nTime elapsed: " << chrono::duration<double>(chrono::steady_clock::now() - TimeStart).count() << " seconds.\n";
#endif
return 0;
}
#endif | 19.909091 | 124 | 0.589041 | [
"vector"
] |
ed1caffc3ffc902e1870ae3958eb65d972ee578b | 1,264 | hpp | C++ | std/string/split.hpp | aconstlink/snakeoil | 3c6e02655e1134f8422f01073090efdde80fc109 | [
"MIT"
] | 1 | 2017-08-11T19:12:24.000Z | 2017-08-11T19:12:24.000Z | std/string/split.hpp | aconstlink/snakeoil | 3c6e02655e1134f8422f01073090efdde80fc109 | [
"MIT"
] | 11 | 2018-07-07T20:09:44.000Z | 2020-02-16T22:45:09.000Z | std/string/split.hpp | aconstlink/snakeoil | 3c6e02655e1134f8422f01073090efdde80fc109 | [
"MIT"
] | null | null | null | //------------------------------------------------------------
// snakeoil (c) Alexis Constantin Link
// Distributed under the MIT license
//------------------------------------------------------------
#ifndef _SNAKEOIL_CORE_STRING_SPLIT_HPP_
#define _SNAKEOIL_CORE_STRING_SPLIT_HPP_
#include "../typedefs.h"
#include "string.hpp"
#include "../container/vector.hpp"
namespace so_std
{
struct string_ops
{
static size_t split( so_std::string_cref_t string_in, char_t deli,
std::vector<so_std::string_t> & split_out )
{
size_t num_found = 0 ;
size_t found_at = 0 ;
size_t begin = 0 ;
do
{
found_at = string_in.find_first_of( deli, begin ) ;
if( begin < found_at )
{
split_out.push_back( string_in.substr( begin, found_at - begin ) ) ;
++num_found ;
}
begin = found_at + 1 ;
} while( found_at != std::string::npos ) ;
if( num_found > 0 && split_out.back().size() == 0 )
{
split_out.resize( split_out.size() - 1 ) ;
}
return num_found ;
}
};
}
#endif
| 26.893617 | 88 | 0.464399 | [
"vector"
] |
ed1d3067b265ea69dfb325b94973c2af6f72a68b | 5,893 | cpp | C++ | torch_mlu/csrc/aten/operators/cnnl/nllloss_backward.cpp | Cambricon/catch | 2625da389f25a67066d20fb6b0c38250ef98f8ab | [
"BSD-2-Clause"
] | 20 | 2022-03-01T11:40:51.000Z | 2022-03-30T08:17:47.000Z | torch_mlu/csrc/aten/operators/cnnl/nllloss_backward.cpp | Cambricon/catch | 2625da389f25a67066d20fb6b0c38250ef98f8ab | [
"BSD-2-Clause"
] | null | null | null | torch_mlu/csrc/aten/operators/cnnl/nllloss_backward.cpp | Cambricon/catch | 2625da389f25a67066d20fb6b0c38250ef98f8ab | [
"BSD-2-Clause"
] | null | null | null | /*
All modification made by Cambricon Corporation: © 2022 Cambricon Corporation
All rights reserved.
All other contributions:
Copyright (c) 2014--2022, the respective contributors
All rights reserved.
For the list of contributors go to https://github.com/pytorch/pytorch/graphs/contributors
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 Intel Corporation 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 "aten/operators/cnnl/cnnl_kernel.h"
#include "aten/operators/cnnl/internal/cnnl_internal.h"
namespace torch_mlu {
namespace cnnl {
namespace ops {
// nll_loss_wrapper
// input tensor should be 1D or 2D
at::Tensor cnnl_nll_loss_backward(const at::Tensor& grad_output,
const at::Tensor& self,
const at::Tensor& target,
const at::Tensor& weight, int64_t reduction,
int64_t ignore_index,
const at::Tensor& total_weight) {
bool is_half_data = (self.scalar_type() == at::kHalf);
auto self_cast = is_half_data ? self.to(at::kFloat) : self;
auto grad_output_cast = is_half_data ? grad_output.to(at::kFloat) : grad_output;
auto total_weight_cast = is_half_data ? total_weight.to(at::kFloat) : total_weight;
at::Tensor weight_;
if (!weight.defined()) {
weight_ = at::ones(
self_cast.size(1), self_cast.options().device(at::Device(at::Device::Type::MLU)));
} else {
weight_ = is_half_data ? weight.to(at::kFloat) : weight;
}
auto grad_output_contiguous = cnnl_contiguous(grad_output_cast);
auto self_contiguous = cnnl_contiguous(self_cast);
auto target_contiguous = cnnl_contiguous(target);
auto weight_contiguous = cnnl_contiguous(weight_);
auto total_weight_contiguous = cnnl_contiguous(total_weight_cast);
auto grad_input = cnnl_nll_loss_backward_internal(
grad_output_contiguous, self_contiguous, target_contiguous, weight_contiguous, reduction,
ignore_index, total_weight_contiguous);
auto grad_input_cast = is_half_data ? grad_input.to(at::kHalf) : grad_input;
return grad_input_cast;
}
at::Tensor cnnl_nll_loss2d_backward(const at::Tensor& grad_output,
const at::Tensor& self,
const at::Tensor& target,
const at::Tensor& weight, int64_t reduction,
int64_t ignore_index,
const at::Tensor& total_weight) {
/*
* transform nll_loss2d bp to nll_loss bp
* ==> nll_loss2d
*
* CPU(NCHW) <==> MLU(NHWC)
* [m, N, d1, d2] (nll_loss2d) [m, d1, d2, N] {input}
* [m, d1, d2] [m, d2, d1] {target}
*
* || ||
*
* [mxd1xd2, N] [mxd1xd2, N]
* [mxd1xd2] [mxd1xd2]
*
* ==> nll_loss
*/
at::Tensor weight_ = weight;
if (!weight.defined()) {
weight_ = at::ones(
self.size(1), self.options().device(at::Device(at::Device::Type::MLU)));
}
auto weight_contiguous = cnnl_contiguous(weight_, weight_.suggest_memory_format());
/*
* transform self
*
* CPU(NCHW) <==> MLU(NHWC)
* [m, N, d1, d2] (nll_loss2d) [m, d1, d2, N] {input}
*
* [mxd1xd2, N] [mxd1xd2, N]
* [mxd1xd2] [mxd1xd2]
*/
auto memory_format = get_channels_last_memory_format(self.dim());
auto self_contiguous = cnnl_contiguous(self, memory_format);
/*
* transform weight
*
* CPU(NCHW) <==> MLU(NHWC)
* [m, d1, d2] [m, d2, d1] {target}
*
* [m, d1, d2] (permute 021) [m, d1, d2]
*
* [mxd1xd2] [mxd1xd2]
*
*/
auto target_contiguous = cnnl_contiguous(target, target.suggest_memory_format());
auto total_weight_contiguous = cnnl_contiguous(total_weight);
// nll_loss bakcward
at::Tensor grad_input = cnnl_nll_loss_backward_internal(grad_output, self_contiguous,
target_contiguous, weight_contiguous, reduction,
ignore_index, total_weight_contiguous);
// transform grad_input
at::Tensor grad_trans = at::empty_like(self_contiguous);
getMluTensorImpl(grad_trans)
->copy_cnnl_metadata_from(getMluTensorImpl(grad_input));
return grad_trans;
}
} // namespace ops
} // namespace cnnl
} // namespace torch_mlu
| 42.702899 | 96 | 0.647718 | [
"transform"
] |
ed212516d201d5f7a19d531598ec5db6f3b1b2fe | 7,257 | cpp | C++ | src/mync1/ArrayBuff.cpp | msatyan/MyNCExtension | 9793cbed1766c7c085e10bd196d6cd2a4af0828a | [
"MIT"
] | 32 | 2019-08-01T09:03:35.000Z | 2022-03-11T04:53:57.000Z | src/mync1/ArrayBuff.cpp | msatyan/MyNCExtension | 9793cbed1766c7c085e10bd196d6cd2a4af0828a | [
"MIT"
] | null | null | null | src/mync1/ArrayBuff.cpp | msatyan/MyNCExtension | 9793cbed1766c7c085e10bd196d6cd2a4af0828a | [
"MIT"
] | 6 | 2019-09-26T20:35:36.000Z | 2022-02-08T06:41:35.000Z | #include <assert.h>
#include "addon_api.h"
#include "cpp_util.h"
#include "stdio.h"
#include "stdlib.h"
void FreeExternalArrayBufferMemory(napi_env env, void* data, void* hint)
{
// externally-owned data is ready to be cleaned up
// the object with which it was associated with, has been garbage-collected
printf("C-Free : AB External Memory Address: %p\n", data);
free(data);
}
// Receive an ArrayBuffer from JavaScript
// Print the values of ArrayBuffer and then modify value at native layer.
// Then JavaScript print the modified value
napi_value CArrayBuffSum(napi_env env, napi_callback_info info)
{
napi_status status;
const size_t MaxArgExpected = 1;
napi_value args[MaxArgExpected];
size_t argc = sizeof(args) / sizeof(napi_value);
status = napi_get_cb_info(env, info, &argc, args, nullptr, nullptr);
assert(status == napi_ok);
if (argc < 1)
napi_throw_error(env, "EINVAL", "Too few arguments");
napi_value buff = args[0];
napi_valuetype valuetype;
status = napi_typeof(env, buff, &valuetype);
assert(status == napi_ok);
if (valuetype == napi_object)
{
bool isArrayBuff = 0;
status = napi_is_arraybuffer(env, buff, &isArrayBuff);
assert(status == napi_ok);
if (isArrayBuff != true)
napi_throw_error(env, "EINVAL", "Expected an ArrayBuffer");
}
int32_t *buff_data = NULL;
size_t byte_length = 0;
int32_t sum = 0;
napi_get_arraybuffer_info(env, buff, (void **)&buff_data, &byte_length);
assert(status == napi_ok);
printf("\nC: Int32Array size = %d, (ie: bytes=%d)",
(int)(byte_length / sizeof(int32_t)), (int)byte_length);
for (int i = 0; i < byte_length / sizeof(int32_t); ++i)
{
sum += *(buff_data + i);
printf("\nC: i32array[%d] = %d", i, *(buff_data + i));
}
napi_value rcValue;
napi_create_int32(env, sum, &rcValue);
// ArrayBuff share the same memory buffer at native and JS
// To verify this let us change the value here and access it at JS
for (int i = 0; i < byte_length / sizeof(int32_t); ++i)
{
*(buff_data + i) = i * 10;
}
return (rcValue);
}
/////////////////////////////////////////////////////////////////////////
// Create ArrayBuffer at native layer and return it to JavaScript
// It take two parameters 's' and 'm' and return an array buffer.
// s is the size of the int32 array
// m multiplication factor against the index value.
napi_value CArrayBuffer_GetMultiplicationTable(napi_env env, napi_callback_info info)
{
napi_status status;
napi_value argv[2];
// [in-out] argc: Specifies the size of the provided argv array and
// receives the actual count of arguments
size_t argc = 2;
int32_t s = 0;
int32_t m = 0;
napi_get_cb_info(env, info, &argc, argv, NULL, NULL);
if (argc != 2)
{
napi_throw_error(env, "EINVAL", "arguments missmatch");
return NULL;
}
// First parm is size of the array
if ((status = napi_get_value_int32(env, argv[0], &s)) != napi_ok)
{
napi_throw_error(env, "EINVAL", "parm 1: int32 expected");
return NULL;
}
// Second parameter multiplication factor.
if ((status = napi_get_value_int32(env, argv[1], &m)) != napi_ok)
{
napi_throw_error(env, "EINVAL", "parm 2: int32 expected");
return NULL;
}
napi_value rcValue;
int32_t *buff_data = NULL;
// Create an array buffer
status = napi_create_arraybuffer(env, (s * sizeof(int32_t)), (void **)&buff_data, &rcValue);
assert(status == napi_ok);
for( int i=0; i<s; ++i )
{
*(buff_data + i) = i * m;
}
return (rcValue);
}
/////////////////////////////////////////////////////////////////////////
// Create TypedArray of Int32 at native layer and return it to JavaScript
// It take two parameters 's' and 'm' and return an array buffer.
// s is the size of the int32 array
// m multiplication factor against the index value.
napi_value CInt32TypedArray_GetMultiplicationTable(napi_env env, napi_callback_info info)
{
napi_status status;
napi_value argv[2];
// [in-out] argc: Specifies the size of the provided argv array and
// receives the actual count of arguments
size_t argc = 2;
int32_t s = 0;
int32_t m = 0;
napi_get_cb_info(env, info, &argc, argv, NULL, NULL);
if (argc != 2)
{
napi_throw_error(env, "EINVAL", "arguments missmatch");
return NULL;
}
// First parm is size of the array
if ((status = napi_get_value_int32(env, argv[0], &s)) != napi_ok)
{
napi_throw_error(env, "EINVAL", "parm 1: int32 expected");
return NULL;
}
// Second parameter multiplication factor.
if ((status = napi_get_value_int32(env, argv[1], &m)) != napi_ok)
{
napi_throw_error(env, "EINVAL", "parm 2: int32 expected");
return NULL;
}
napi_value rcValue;
napi_value napi_arraybuffer;
int32_t *buff_data = NULL;
// Create an array buffer
status = napi_create_arraybuffer(env, (s * sizeof(int32_t)), (void **)&buff_data, &napi_arraybuffer);
assert(status == napi_ok);
// Create a TypedArray by consuming the original Array Buffer.
size_t byte_offset = 0; // Let it be from the starting of the original array with full length
status = napi_create_typedarray( env, napi_int32_array, (size_t)s, napi_arraybuffer, byte_offset, &rcValue);
assert(status == napi_ok);
for( int i=0; i<s; ++i )
{
*(buff_data + i) = i * m;
}
return (rcValue);
}
/////////////////////////////////////////////////////////////////////////
// Create ArrayBuffer at native layer with externally allocated memory and return it to JavaScript
// This function expects two parameters 's' and 'm' and return an array buffer.
// s is the size of the int32 array
// m multiplication factor against the index value.
napi_value CArrayBufferExternalMem_GetMultiplicationTable(napi_env env, napi_callback_info info)
{
napi_status status;
napi_value argv[2];
// [in-out] argc: Specifies the size of the provided argv array and
// receives the actual count of arguments
size_t argc = 2;
int32_t s = 0;
int32_t m = 0;
napi_get_cb_info(env, info, &argc, argv, NULL, NULL);
if (argc != 2)
{
napi_throw_error(env, "EINVAL", "arguments missmatch");
return NULL;
}
// First parm is size of the array
if ((status = napi_get_value_int32(env, argv[0], &s)) != napi_ok)
{
napi_throw_error(env, "EINVAL", "parm 1: int32 expected");
return NULL;
}
// Second parameter multiplication factor.
if ((status = napi_get_value_int32(env, argv[1], &m)) != napi_ok)
{
napi_throw_error(env, "EINVAL", "parm 2: int32 expected");
return NULL;
}
size_t byte_length = sizeof(int32_t)*s;
int32_t *external_data = (int32_t *) malloc( byte_length );
printf("C-Alloc: AB External Memory Address: %p\n", (void*)external_data);
napi_value rcValue;
// Create array buffer with externally allocated memory.
// When the item is GCed, it will call FreeExternalArrayBufferMemory
status = napi_create_external_arraybuffer( env, (void *)external_data, byte_length,
FreeExternalArrayBufferMemory, NULL, &rcValue);
assert(status == napi_ok);
for( int i=0; i<s; ++i )
{
*(external_data + i) = i * m;
}
return (rcValue);
}
| 29.987603 | 112 | 0.652749 | [
"object"
] |
ed2472f56cae8fc3996ef1b653035851aa295a68 | 494 | cpp | C++ | 202101/1/_26_RemoveDuplicatesfromSortedArray.cpp | uaniheng/leetcode-cpp | d7b4c9ef43cca8ecb703da5a910d79af61eb3394 | [
"Apache-2.0"
] | null | null | null | 202101/1/_26_RemoveDuplicatesfromSortedArray.cpp | uaniheng/leetcode-cpp | d7b4c9ef43cca8ecb703da5a910d79af61eb3394 | [
"Apache-2.0"
] | null | null | null | 202101/1/_26_RemoveDuplicatesfromSortedArray.cpp | uaniheng/leetcode-cpp | d7b4c9ef43cca8ecb703da5a910d79af61eb3394 | [
"Apache-2.0"
] | null | null | null | //
// Created by gyc on 2021/1/7.
//
#include "../../common.h"
class Solution {
public:
int removeDuplicates(vector<int>& nums) {
if (nums.size() < 2) return nums.size();
int i = 0;
for(int j = 1; j < nums.size(); ++j) {
if (nums[i] != nums[j]) {
i ++;
nums[i] = nums[j];
}
}
return i + 1;
}
};
int main() {
vector<int> v{1,1,1,2,4,5,8};
cout << Solution().removeDuplicates(v);
} | 19.76 | 48 | 0.439271 | [
"vector"
] |
ed26048cef7e2ad07ca44eba4f5f41650147e6cd | 9,806 | cc | C++ | FWCore/Integration/test/TestESSource.cc | ckamtsikis/cmssw | ea19fe642bb7537cbf58451dcf73aa5fd1b66250 | [
"Apache-2.0"
] | 852 | 2015-01-11T21:03:51.000Z | 2022-03-25T21:14:00.000Z | FWCore/Integration/test/TestESSource.cc | ckamtsikis/cmssw | ea19fe642bb7537cbf58451dcf73aa5fd1b66250 | [
"Apache-2.0"
] | 30,371 | 2015-01-02T00:14:40.000Z | 2022-03-31T23:26:05.000Z | FWCore/Integration/test/TestESSource.cc | ckamtsikis/cmssw | ea19fe642bb7537cbf58451dcf73aa5fd1b66250 | [
"Apache-2.0"
] | 3,240 | 2015-01-02T05:53:18.000Z | 2022-03-31T17:24:21.000Z | // -*- C++ -*-
//
// Package: FWCore/Integration
// Class : TestESSource
//
// Implementation:
// ESSource used for tests of Framework support for
// ESSources and ESProducers. This is primarily focused
// on the infrastructure used by CondDBESSource.
//
// Original Author: W. David Dagenhart
// Created: 15 August 2019
#include "DataFormats/Provenance/interface/EventID.h"
#include "FWCore/Framework/interface/DataKey.h"
#include "FWCore/Framework/interface/ESSourceDataProxyBase.h"
#include "FWCore/Framework/interface/DataProxyProvider.h"
#include "FWCore/Framework/interface/EventSetupRecordIntervalFinder.h"
#include "FWCore/Framework/interface/EventSetupRecordKey.h"
#include "FWCore/Framework/interface/IOVSyncValue.h"
#include "FWCore/Framework/interface/SourceFactory.h"
#include "FWCore/Framework/interface/ValidityInterval.h"
#include "FWCore/Integration/interface/ESTestRecords.h"
#include "FWCore/Integration/test/IOVTestInfo.h"
#include "FWCore/MessageLogger/interface/MessageLogger.h"
#include "FWCore/ParameterSet/interface/ConfigurationDescriptions.h"
#include "FWCore/ParameterSet/interface/ParameterSet.h"
#include "FWCore/ParameterSet/interface/ParameterSetDescription.h"
#include "FWCore/Utilities/interface/Exception.h"
#include <atomic>
#include <cmath>
#include <limits>
#include <set>
#include <utility>
#include <vector>
#include <mutex>
namespace edmtest {
class TestESSource;
class TestESSourceTestProxy : public edm::eventsetup::ESSourceDataProxyBase {
public:
TestESSourceTestProxy(TestESSource* testESSource);
private:
void prefetch(edm::eventsetup::DataKey const&, edm::EventSetupRecordDetails) override;
void initializeForNewIOV() override;
void const* getAfterPrefetchImpl() const override;
IOVTestInfo iovTestInfo_;
TestESSource* testESSource_;
};
class TestESSource : public edm::eventsetup::DataProxyProvider, public edm::EventSetupRecordIntervalFinder {
public:
using EventSetupRecordKey = edm::eventsetup::EventSetupRecordKey;
explicit TestESSource(edm::ParameterSet const&);
~TestESSource();
static void fillDescriptions(edm::ConfigurationDescriptions& descriptions);
void busyWait(char const* msg) const;
std::atomic<unsigned int> count_;
std::atomic<unsigned int> count1_;
std::atomic<unsigned int> count2_;
edm::SerialTaskQueue queue_;
std::mutex mutex_;
private:
bool isConcurrentFinder() const override { return true; }
void setIntervalFor(EventSetupRecordKey const&, edm::IOVSyncValue const&, edm::ValidityInterval&) override;
KeyedProxiesVector registerProxies(EventSetupRecordKey const&, unsigned int iovIndex) override;
void initConcurrentIOVs(EventSetupRecordKey const&, unsigned int nConcurrentIOVs) override;
std::set<edm::IOVSyncValue> setOfIOV_;
const unsigned int iterations_;
const double pi_;
unsigned int expectedNumberOfConcurrentIOVs_;
unsigned int nConcurrentIOVs_ = 0;
bool checkIOVInitialization_;
};
TestESSourceTestProxy::TestESSourceTestProxy(TestESSource* testESSource)
: edm::eventsetup::ESSourceDataProxyBase(&testESSource->queue_, &testESSource->mutex_),
testESSource_(testESSource) {}
void TestESSourceTestProxy::prefetch(edm::eventsetup::DataKey const& iKey, edm::EventSetupRecordDetails iRecord) {
++testESSource_->count_;
if (testESSource_->count_.load() > 1) {
throw cms::Exception("TestFailure") << "TestESSourceTestProxy::getImpl,"
<< " functions in mutex should not run concurrently";
}
testESSource_->busyWait("getImpl");
edm::ValidityInterval iov = iRecord.validityInterval();
edm::LogAbsolute("TestESSourceTestProxy")
<< "TestESSoureTestProxy::getImpl startIOV = " << iov.first().luminosityBlockNumber()
<< " endIOV = " << iov.last().luminosityBlockNumber() << " IOV index = " << iRecord.iovIndex()
<< " cache identifier = " << iRecord.cacheIdentifier();
iovTestInfo_.iovStartLumi_ = iov.first().luminosityBlockNumber();
iovTestInfo_.iovEndLumi_ = iov.last().luminosityBlockNumber();
iovTestInfo_.iovIndex_ = iRecord.iovIndex();
iovTestInfo_.cacheIdentifier_ = iRecord.cacheIdentifier();
--testESSource_->count_;
}
void const* TestESSourceTestProxy::getAfterPrefetchImpl() const { return &iovTestInfo_; }
void TestESSourceTestProxy::initializeForNewIOV() {
edm::LogAbsolute("TestESSourceTestProxy::initializeForNewIOV") << "TestESSourceTestProxy::initializeForNewIOV";
++testESSource_->count2_;
}
TestESSource::TestESSource(edm::ParameterSet const& pset)
: count_(0),
count1_(0),
count2_(0),
iterations_(pset.getParameter<unsigned int>("iterations")),
pi_(std::acos(-1)),
expectedNumberOfConcurrentIOVs_(pset.getParameter<unsigned int>("expectedNumberOfConcurrentIOVs")),
checkIOVInitialization_(pset.getParameter<bool>("checkIOVInitialization")) {
std::vector<unsigned int> temp(pset.getParameter<std::vector<unsigned int>>("firstValidLumis"));
for (auto val : temp) {
setOfIOV_.insert(edm::IOVSyncValue(edm::EventID(1, val, 0)));
}
findingRecord<ESTestRecordI>();
usingRecord<ESTestRecordI>();
}
TestESSource::~TestESSource() {}
void TestESSource::fillDescriptions(edm::ConfigurationDescriptions& descriptions) {
edm::ParameterSetDescription desc;
std::vector<unsigned int> emptyVector;
desc.add<unsigned int>("iterations", 10 * 1000 * 1000);
desc.add<bool>("checkIOVInitialization", false);
desc.add<unsigned int>("expectedNumberOfConcurrentIOVs", 0);
desc.add<std::vector<unsigned int>>("firstValidLumis", emptyVector);
descriptions.addDefault(desc);
}
void TestESSource::setIntervalFor(EventSetupRecordKey const&,
edm::IOVSyncValue const& syncValue,
edm::ValidityInterval& iov) {
std::lock_guard<std::mutex> guard(mutex_);
if (checkIOVInitialization_) {
// Note that this check should pass with the specific configuration where I enable
// the check, but in general it does not have to be true. The counts are offset
// by 1 because the beginRun IOV is invalid (no IOV initialization).
if (count1_ > 0 && count2_ + 1 != count1_) {
throw cms::Exception("TestFailure") << "TestESSource::setIntervalFor,"
<< " unexpected number of IOV initializations";
}
}
++count_;
++count1_;
if (count_.load() > 1) {
throw cms::Exception("TestFailure") << "TestESSource::setIntervalFor,"
<< " functions in mutex should not run concurrently";
}
busyWait("setIntervalFor");
iov = edm::ValidityInterval::invalidInterval();
if (setOfIOV_.empty()) {
--count_;
return;
}
std::pair<std::set<edm::IOVSyncValue>::iterator, std::set<edm::IOVSyncValue>::iterator> itFound =
setOfIOV_.equal_range(syncValue);
if (itFound.first == itFound.second) {
if (itFound.first == setOfIOV_.begin()) {
//request is before first valid interval, so fail
--count_;
return;
}
//go back one step
--itFound.first;
}
edm::IOVSyncValue endOfInterval = edm::IOVSyncValue::endOfTime();
if (itFound.second != setOfIOV_.end()) {
endOfInterval = edm::IOVSyncValue(
edm::EventID(1, itFound.second->eventID().luminosityBlock() - 1, edm::EventID::maxEventNumber()));
}
iov = edm::ValidityInterval(*(itFound.first), endOfInterval);
--count_;
}
edm::eventsetup::DataProxyProvider::KeyedProxiesVector TestESSource::registerProxies(EventSetupRecordKey const&,
unsigned int iovIndex) {
if (expectedNumberOfConcurrentIOVs_ != 0 && nConcurrentIOVs_ != expectedNumberOfConcurrentIOVs_) {
throw cms::Exception("TestFailure") << "TestESSource::registerProxies,"
<< " unexpected number of concurrent IOVs";
}
KeyedProxiesVector keyedProxiesVector;
edm::eventsetup::DataKey dataKey(edm::eventsetup::DataKey::makeTypeTag<IOVTestInfo>(), edm::eventsetup::IdTags(""));
keyedProxiesVector.emplace_back(dataKey, std::make_shared<TestESSourceTestProxy>(this));
return keyedProxiesVector;
}
void TestESSource::initConcurrentIOVs(EventSetupRecordKey const& key, unsigned int nConcurrentIOVs) {
edm::LogAbsolute("TestESSource::initConcurrentIOVs")
<< "Start TestESSource::initConcurrentIOVs " << nConcurrentIOVs << " " << key.name();
if (EventSetupRecordKey::makeKey<ESTestRecordI>() != key) {
throw cms::Exception("TestFailure") << "TestESSource::initConcurrentIOVs,"
<< " unexpected EventSetupRecordKey";
}
if (expectedNumberOfConcurrentIOVs_ != 0 && nConcurrentIOVs != expectedNumberOfConcurrentIOVs_) {
throw cms::Exception("TestFailure") << "TestESSource::initConcurrentIOVs,"
<< " unexpected number of concurrent IOVs";
}
nConcurrentIOVs_ = nConcurrentIOVs;
}
void TestESSource::busyWait(char const* msg) const {
edm::LogAbsolute("TestESSource::busyWait") << "Start TestESSource::busyWait " << msg;
double sum = 0.;
const double stepSize = pi_ / iterations_;
for (unsigned int i = 0; i < iterations_; ++i) {
sum += stepSize * cos(i * stepSize);
}
edm::LogAbsolute("TestESSource::busyWait") << "Stop TestESSource::busyWait " << msg << " " << sum;
}
} // namespace edmtest
using namespace edmtest;
DEFINE_FWK_EVENTSETUP_SOURCE(TestESSource);
| 41.375527 | 120 | 0.689476 | [
"vector"
] |
ed2a0fde47e5dbc06ba65e0f139d00cf2f238090 | 2,662 | cpp | C++ | UVa/uva_147_Dollars.cpp | bishoy-magdy/Competitive-Programming | 689daac9aeb475da3c28aba4a69df394c68a9a34 | [
"MIT"
] | 2 | 2020-04-23T17:47:27.000Z | 2020-04-25T19:40:50.000Z | UVa/uva_147_Dollars.cpp | bishoy-magdy/Competitive-Programming | 689daac9aeb475da3c28aba4a69df394c68a9a34 | [
"MIT"
] | null | null | null | UVa/uva_147_Dollars.cpp | bishoy-magdy/Competitive-Programming | 689daac9aeb475da3c28aba4a69df394c68a9a34 | [
"MIT"
] | 1 | 2020-06-14T20:52:39.000Z | 2020-06-14T20:52:39.000Z | #include<bits/stdc++.h>
#include<iostream>
#include<string>
#include<vector>
#include<cmath>
#include<list>
#include <algorithm>
#include<vector>
#include<set>
#include <cctype>
#include <cstring>
#include <cstdio>
#include<queue>
#include<stack>
#include<bitset>
#include<time.h>
#include<fstream>
/******************************************************/
using namespace std;
/********************define***************************/
#define ll long long
#define ld long double
#define all(v) ((v).begin()), ((v).end())
#define for_(vec) for(int i=0;i<(int)vec.size();i++)
#define lp(j,n) for(int i=j;i<(int)(n);i++)
#define clr(arr,x) memset(arr,x,sizeof(arr))
#define fillstl(arr,X) fill(arr.begin(),arr.end(),X)
#define pb push_back
#define mp make_pair
#define print_vector(X) for(int i=0;i<X.size();i++)
/********************************************************/
typedef vector<int> vi;
typedef vector<pair<int, int> > vii;
typedef vector<vector<int> > vvi;
typedef vector<ll> vl;
/***********************function************************/
void fast()
{
ios_base::sync_with_stdio(NULL);
cin.tie(0);
cout.tie(0);
}
void online_judge()
{
freopen("input.txt", "r", stdin);
freopen("output.txt", "w", stdout);
}
const int flag_max=0x3f3f3f3f;
const ll OO=1e9+9 ;
const double EPS = (1e-9);
int dcmp(double x, double y)
{
return fabs(x-y) <= EPS ? 0 : x < y ? -1 : 1;
}
ll gcd(ll a, ll b)
{
return !b ? a : gcd(b, a % b);
}
ll lcm(ll a, ll b)
{
return (a / gcd(a, b)) * b;
}
/***********************main_problem****************************/
const int Ncoins=11;
int coins[Ncoins]={5,10,20,50,100,200,500,1000,2000,5000,10000};
ll dp[2][30005];
/**************************Bisho_O*****************************************/
int main()
{
fast();
dp[0][0]=dp[1][0]=1;
int star=1;
for(int i=0;i<11;i++){
star^=1;
for(int rem=coins[0];rem<=30000;rem+=5){
dp[star][rem]=0;
if(i) dp[star][rem]=dp[1^star][rem];
if(rem-coins[i]>=0) dp[star][rem]+=dp[star][rem-coins[i]];
}
}
//cout<<dp[1][200];
double n;
while(cin>>n && n>EPS){
int print_=n;
string s=to_string(n);
int i;
for(i=0;i<s.size();i++)
if(s[i]=='.')
break;
double N=stod(s.substr(0,i));
N*=100;
int Y=0;
if(s[i+1]-'0' >0){
Y+=s[i+1]-'0';
}
if(s[i+2]-'0'>=0)
{Y*=10; Y+=s[i+2]-'0'; }
N+=Y;
string print=to_string(print_);
print+='.';
print+=s[i+1];
print+=s[i+2];
cout<<setw(6)<<print<<setw(17)<<dp[0][(int)N]<<'\n';
}
return 0;
}
| 19.014286 | 76 | 0.486852 | [
"vector"
] |
ed2aeb3ba88f3bf203f638fc1d4ded6bf214a74a | 912 | cpp | C++ | provides/library/test.cpp | jaeheum/testing.cpp | 4fcd9f1ca9bdd56b4a06e2a8c488d789988126a8 | [
"MIT"
] | null | null | null | provides/library/test.cpp | jaeheum/testing.cpp | 4fcd9f1ca9bdd56b4a06e2a8c488d789988126a8 | [
"MIT"
] | null | null | null | provides/library/test.cpp | jaeheum/testing.cpp | 4fcd9f1ca9bdd56b4a06e2a8c488d789988126a8 | [
"MIT"
] | 1 | 2021-06-30T20:42:23.000Z | 2021-06-30T20:42:23.000Z | #include "testing_v1/test.hpp"
#include <algorithm>
#include <cstdio>
#include <cstdlib>
#include <tuple>
#include <vector>
void testing_v1::verify(bool ok) {
if (ok)
return;
fprintf(stderr, "FAIL\n");
exit(1);
}
class testing_v1::Private::Static {
friend int ::main();
friend class test_base_t;
using tests_t = std::vector<test_base_t *>;
static tests_t &tests() {
static tests_t tests;
return tests;
}
static void run_all() {
for (auto test : tests())
test->run();
}
};
testing_v1::Private::test_base_t::test_base_t() {
Static::tests().push_back(this);
}
testing_v1::Private::test_base_t::~test_base_t() {
auto &tests = Static::tests();
auto it = std::find(tests.rbegin(), tests.rend(), this);
if (it != tests.rend()) {
std::swap(*it, tests.back());
tests.pop_back();
}
}
int main() {
testing_v1::Private::Static::run_all();
return 0;
}
| 18.24 | 58 | 0.635965 | [
"vector"
] |
ed2fee22dd88eb3380f9c122bfabc92a6b30ed96 | 5,392 | cpp | C++ | nuclear_pedigree.cpp | Yichen-Si/cramore | 18ed327c2bb9deb6c2ec4243d259b93142304719 | [
"Apache-2.0"
] | 2 | 2019-03-04T23:08:17.000Z | 2021-08-24T08:10:03.000Z | nuclear_pedigree.cpp | Yichen-Si/cramore | 18ed327c2bb9deb6c2ec4243d259b93142304719 | [
"Apache-2.0"
] | 2 | 2018-09-19T05:16:20.000Z | 2020-10-01T18:28:36.000Z | nuclear_pedigree.cpp | Yichen-Si/cramore | 18ed327c2bb9deb6c2ec4243d259b93142304719 | [
"Apache-2.0"
] | 3 | 2018-09-06T22:04:40.000Z | 2019-08-19T16:55:42.000Z | #include "nuclear_pedigree.h"
NuclearPedigree::NuclearPedigree(const char* pedFile) {
htsFile *hts = hts_open(pedFile, "r");
kstring_t s = {0,0,0};
std::vector<std::string> v;
std::vector<std::string> smIDs;
while(hts_getline(hts,'\n', &s)>=0) {
if ( s.s[0] == '#' ) continue;
std::string line(s.s);
split(v, "\t", line);
split(smIDs, ",", v[1]);
addPerson(v[0].c_str(), smIDs, v[2] == "0" ? NULL : v[2].c_str(), v[3] == "0" ? NULL : v[3].c_str(), atoi(v[4].c_str()) );
}
}
void NuclearPedigree::addPerson(const char* famID, const std::vector<std::string>& smIDs, const char* dadID, const char* momID, int sex) {
// register family ID if absent
NuclearFamily* pFam = NULL;
if ( famIDmap.find(famID) == famIDmap.end() ) { // family ID does not exist
pFam = new NuclearFamily(famID);
famIDmap[famID] = pFam;
}
else
pFam = famIDmap[famID];
// check whether the sample was seen before
int32_t i;
for(i=0; i < (int32_t)smIDs.size(); ++i) {
if ( smIDmap.find(smIDs[i]) != smIDmap.end() ) { // sample ID has not seen before
break;
}
}
NuclearFamilyPerson* pPerson = NULL;
if ( i < (int32_t)smIDs.size() ) { // if sample was seen before, it must be dad or mom
if ( ( pFam->pDad != NULL ) && ( pFam->pDad->hasSample(smIDs[i].c_str()) ) ) { // matches dad
pPerson = pFam->pDad; // assign the person pointer
}
else if ( ( pFam->pMom != NULL ) && ( pFam->pMom->hasSample(smIDs[i].c_str()) ) ) {
pPerson = pFam->pMom;
}
else {
fprintf(stderr,"FATAL ERROR: Sample ID %s has already observed previously but the sample is not founders in the family %s\n", smIDs[i].c_str(), famID);
exit(1);
}
}
else { // if the sample was not seen before, create the sample
pPerson = new NuclearFamilyPerson(sex);
}
// register samples and assign to the person
for(size_t j=0; j < smIDs.size(); ++j) {
if ( smIDmap.find(smIDs[j]) == smIDmap.end() ) { // register missing sample IDs
NuclearFamilySample* p = new NuclearFamilySample(smIDs[j].c_str());
smIDmap[smIDs[j]] = p;
pPerson->addSample(p);
}
else { // if already registered, make sure that it belongs to the same person
if ( !pPerson->hasSample(smIDs[j].c_str()) ) {
fprintf(stderr,"FATAL ERROR: Sample ID %s has already observed previously but the sample is not founders in the family %s\n", smIDs[j].c_str(), famID);
exit(1);
}
}
}
// add the person to the family
if ( ( dadID == NULL ) && ( momID == NULL ) ) { // founders
if ( sex == 1 ) { // dad
if ( ( pFam->pDad != NULL ) && ( pFam->pDad != pPerson ) ) {
fprintf(stderr,"FATAL ERROR: Multiple fathers %s, %s are observed for family %s\n", pPerson->getUID(), pFam->pDad->getUID(), famID);
exit(1);
}
pFam->pDad = pPerson;
}
else if ( sex == 2 ) {
if ( ( pFam->pMom != NULL ) && ( pFam->pMom != pPerson ) ) {
fprintf(stderr,"FATAL ERROR: Multiple fathers %s, %s are observed for family %s\n", pPerson->getUID(), pFam->pMom->getUID(), famID);
exit(1);
}
pFam->pMom = pPerson;
}
else {
fprintf(stderr,"FATAL ERROR: Founder %s must have sex information available", smIDs[0].c_str());
exit(1);
}
}
else { // not a founder - then add as children
pFam->pKids.push_back(pPerson);
}
}
bool NuclearPedigree::setSampleIndex(const char* smID, int _index) {
if ( smIDmap.find(smID) == smIDmap.end() )
return false;
else {
smIDmap[smID]->index = _index;
return true;
}
}
int NuclearPedigree::numSamplesWithIndex() {
int count = 0;
std::map<std::string, NuclearFamilySample*>::iterator it;
for(it = smIDmap.begin(); it != smIDmap.end(); ++it) {
if ( it->second->index >= 0 )
++count;
}
return count;
}
int NuclearPedigree::numPeople() {
int count = 0;
std::map<std::string, NuclearFamily*>::iterator it;
for(it = famIDmap.begin(); it != famIDmap.end(); ++it) {
NuclearFamily* pFam = it->second;
if ( pFam->pDad ) ++count;
if ( pFam->pMom ) ++count;
count += (int)pFam->pKids.size();
}
return count;
}
int NuclearPedigree::removeSamplesWithoutIndex() {
std::map<std::string, NuclearFamily*>::iterator it;
int nRemoved = 0;
for(it = famIDmap.begin(); it != famIDmap.end(); ++it) {
NuclearFamily* pFam = it->second;
if ( pFam->pDad ) {
int org = (int)pFam->pDad->samples.size();
int rm = pFam->pDad->removeSamplesWithoutIndex(smIDmap);
if ( org == rm ) {
delete pFam->pDad;
pFam->pDad = NULL;
}
nRemoved += rm;
}
if ( pFam->pMom ) {
int org = (int)pFam->pMom->samples.size();
int rm = pFam->pMom->removeSamplesWithoutIndex(smIDmap);
if ( org == rm ) {
delete pFam->pMom;
pFam->pMom = NULL;
}
nRemoved += rm;
}
for(int i=(int)pFam->pKids.size()-1; i>=0; --i) {
int org = (int)pFam->pKids[i]->samples.size();
int rm = pFam->pKids[i]->removeSamplesWithoutIndex(smIDmap);
if ( org == rm ) {
delete pFam->pKids[i];
pFam->pKids.erase(pFam->pKids.begin()+i);
}
nRemoved += rm;
}
// remove family if no sample exists in the VCF/BCF file
if (pFam->pKids.empty() && pFam->pDad == NULL && pFam->pMom == NULL) {
famIDmap.erase(pFam->famID);
delete pFam;
}
}
return nRemoved;
}
| 32.481928 | 157 | 0.589021 | [
"vector"
] |
ed3117954409db15c626fc7f5a71c6cad7ecec43 | 1,126 | cpp | C++ | src/FireFist.cpp | snow482/grawing_way_oop_3.0 | 3ce20640f1c943fe9929b8d39e00c6d90ed4cb32 | [
"MIT"
] | null | null | null | src/FireFist.cpp | snow482/grawing_way_oop_3.0 | 3ce20640f1c943fe9929b8d39e00c6d90ed4cb32 | [
"MIT"
] | null | null | null | src/FireFist.cpp | snow482/grawing_way_oop_3.0 | 3ce20640f1c943fe9929b8d39e00c6d90ed4cb32 | [
"MIT"
] | null | null | null | #include "FireFist.hpp"
FireFist::FireFist(int fireDamage)
: m_fireDamage(fireDamage)
{}
std::vector<std::pair<phazeType, Involve>> FireFist::operator()(std::weak_ptr<Character> self,
std::weak_ptr<Character> enemy) {
noused(self);
std::pair<phazeType, Involve> startDamage = {phazeType::Start, [this, enemy]() mutable {
auto enemyPtr = enemy.lock();
enemyPtr->getDamage(m_fireDamage);
std::cout<< "damaged by arrow" << std::endl;
return 0;
}};
std::pair<phazeType, Involve> instantDamage = {phazeType::Instantly, [this, enemy]() mutable {
auto enemyPtr = enemy.lock();
enemyPtr->getDamage(m_fireDamage);
std::cout<< "damaged by arrow" << std::endl;
return 0;
}};
std::pair<phazeType, Involve> endDamage = {phazeType::End, [this, enemy]() mutable {
auto enemyPtr = enemy.lock();
enemyPtr->getDamage(m_fireDamage);
std::cout<< "damaged by arrow" << std::endl;
return 0;
}};
return {startDamage, instantDamage, endDamage};
}
| 32.171429 | 98 | 0.589698 | [
"vector"
] |
ed3ba514d06c2d1ad5a9339802f37f36182411c6 | 5,673 | cpp | C++ | inference_backend/image_inference/openvino/model_loader.cpp | vtpl1/gst-video-analytics | 43fb12756e39d8d92b7e45e96622ce547c8f4041 | [
"MIT"
] | null | null | null | inference_backend/image_inference/openvino/model_loader.cpp | vtpl1/gst-video-analytics | 43fb12756e39d8d92b7e45e96622ce547c8f4041 | [
"MIT"
] | null | null | null | inference_backend/image_inference/openvino/model_loader.cpp | vtpl1/gst-video-analytics | 43fb12756e39d8d92b7e45e96622ce547c8f4041 | [
"MIT"
] | 1 | 2020-05-14T15:30:03.000Z | 2020-05-14T15:30:03.000Z | /*******************************************************************************
* Copyright (C) 2018-2020 Intel Corporation
*
* SPDX-License-Identifier: MIT
******************************************************************************/
#include "model_loader.h"
#include "inference_backend/image_inference.h"
#include "inference_backend/logger.h"
#include <fstream>
using namespace InferenceBackend;
namespace {
void ReshapeNetwork(InferenceEngine::CNNNetwork &network, size_t batch_size, size_t width = 0, size_t height = 0) {
try {
InferenceEngine::ICNNNetwork::InputShapes input_shapes = network.getInputShapes();
if (input_shapes.empty())
throw std::invalid_argument("There are no input shapes");
InferenceEngine::InputsDataMap inputs = network.getInputsInfo();
if (inputs.empty())
throw std::invalid_argument("Input layers info is absent for model");
InferenceEngine::InputInfo::Ptr &input = inputs.begin()->second;
InferenceEngine::Layout layout = input->getInputData()->getLayout();
std::string input_name;
size_t batch_index, width_index, height_index;
InferenceEngine::SizeVector input_shape;
std::tie(input_name, input_shape) = *input_shapes.begin();
switch (layout) {
case InferenceEngine::Layout::NCHW: {
batch_index = 0;
height_index = 2;
width_index = 3;
break;
}
case InferenceEngine::Layout::NHWC: {
batch_index = 0;
height_index = 1;
width_index = 2;
break;
}
default:
throw std::runtime_error("Unsupported InferenceEngine::Layout format: " + std::to_string(layout));
}
input_shape[batch_index] = batch_size;
if (height > 0)
input_shape[height_index] = height;
if (width > 0)
input_shape[width_index] = width;
input_shapes[input_name] = input_shape;
network.reshape(input_shapes);
} catch (const std::exception &e) {
std::throw_with_nested(std::runtime_error("Failed to reshape network '" + network.getName() + "'"));
}
}
inline std::string fileNameNoExt(const std::string &filepath) {
auto pos = filepath.rfind('.');
if (pos == std::string::npos)
return filepath;
return filepath.substr(0, pos);
}
bool file_exists(const std::string &path) {
return std::ifstream(path).good();
}
} // namespace
bool ModelLoader::is_ir_model(const std::string &model_path) {
bool is_ir = false;
if (model_path.find(".xml") != std::string::npos) {
const std::string model_bin = fileNameNoExt(model_path) + ".bin";
is_ir = file_exists(model_path) && file_exists(model_bin);
}
return is_ir;
}
InferenceEngine::CNNNetwork IrModelLoader::load(InferenceEngine::Core &core, const std::string &model_xml,
const std::map<std::string, std::string> &base_config) {
try {
// Load IR network (.xml file)
InferenceEngine::CNNNetwork network = core.ReadNetwork(model_xml);
const bool reshape = std::stoi(base_config.at(KEY_RESHAPE));
if (reshape) {
ReshapeNetwork(network, std::stoul(base_config.at(KEY_BATCH_SIZE)),
std::stoul(base_config.at(KEY_RESHAPE_WIDTH)),
std::stoul(base_config.at(KEY_RESHAPE_HEIGHT)));
}
return network;
} catch (const std::exception &e) {
std::throw_with_nested(std::runtime_error("Failed to load IR model '" + model_xml + "'"));
}
return InferenceEngine::CNNNetwork();
}
std::string IrModelLoader::name(const InferenceEngine::CNNNetwork &network) {
return network.getName();
}
InferenceEngine::ExecutableNetwork IrModelLoader::import(InferenceEngine::CNNNetwork &network, const std::string &,
InferenceEngine::Core &core,
const std::map<std::string, std::string> &base_config,
const std::map<std::string, std::string> &inference_config) {
if (base_config.count(KEY_DEVICE) == 0)
throw std::runtime_error("Device does not specified");
const std::string &device = base_config.at(KEY_DEVICE);
return core.LoadNetwork(network, device, inference_config);
}
InferenceEngine::CNNNetwork CompiledModelLoader::load(InferenceEngine::Core &, const std::string &,
const std::map<std::string, std::string> &) {
return InferenceEngine::CNNNetwork();
}
std::string CompiledModelLoader::name(const InferenceEngine::CNNNetwork &) {
return std::string();
}
InferenceEngine::ExecutableNetwork
CompiledModelLoader::import(InferenceEngine::CNNNetwork &, const std::string &model, InferenceEngine::Core &core,
const std::map<std::string, std::string> &base_config,
const std::map<std::string, std::string> &inference_config) {
try {
InferenceEngine::ExecutableNetwork executable_network;
if (base_config.count(KEY_DEVICE) == 0)
throw std::invalid_argument("Inference device is not specified");
const std::string &device = base_config.at(KEY_DEVICE);
executable_network = core.ImportNetwork(model, device, inference_config);
return executable_network;
} catch (const std::exception &e) {
std::throw_with_nested(std::runtime_error("Failed to import pre-compiled model"));
}
}
| 39.395833 | 118 | 0.607262 | [
"model"
] |
ed3fd8e288faa41e70d41b2b09dffc3ba413666f | 10,239 | cpp | C++ | test/sandbox/matrix.cpp | rbock/hana | 2b76377f91a5ebe037dea444e4eaabba6498d3a8 | [
"BSL-1.0"
] | 2 | 2015-05-07T14:29:13.000Z | 2015-07-04T10:59:46.000Z | test/sandbox/matrix.cpp | rbock/hana | 2b76377f91a5ebe037dea444e4eaabba6498d3a8 | [
"BSL-1.0"
] | null | null | null | test/sandbox/matrix.cpp | rbock/hana | 2b76377f91a5ebe037dea444e4eaabba6498d3a8 | [
"BSL-1.0"
] | null | null | null | /*
@copyright Louis Dionne 2014
Distributed under the Boost Software License, Version 1.0.
(See accompanying file LICENSE.md or copy at http://boost.org/LICENSE_1_0.txt)
*/
#include <boost/hana/comparable/equal_mcd.hpp>
#include <boost/hana/core/datatype.hpp>
#include <boost/hana/detail/assert.hpp>
#include <boost/hana/functional.hpp>
#include <boost/hana/functor/fmap_mcd.hpp>
#include <boost/hana/integral.hpp>
#include <boost/hana/list/instance.hpp>
#include <boost/hana/range.hpp>
#include <boost/hana/type.hpp>
using namespace boost::hana;
struct Matrix;
template <typename Storage, typename = operators<Comparable>>
struct matrix_type {
using hana_datatype = Matrix;
Storage rows_;
constexpr auto ncolumns() const
{ return length(head(rows_)); }
constexpr auto nrows() const
{ return length(rows_); }
constexpr auto size() const
{ return nrows() * ncolumns(); }
template <typename I, typename J>
constexpr auto at(I i, J j) const
{ return boost::hana::at(j, boost::hana::at(i, rows_)); }
};
auto transpose = [](auto m) {
auto new_storage = unpack(m.rows_, zip);
return matrix_type<decltype(new_storage)>{new_storage};
};
auto rows = [](auto m) {
return m.rows_;
};
auto columns = [](auto m) {
return rows(transpose(m));
};
auto elementwise = [](auto f) {
return [=](auto ...matrices) {
auto new_storage = zip_with(partial(zip_with, f), matrices.rows_...);
return matrix_type<decltype(new_storage)>{new_storage};
};
};
template <typename S1, typename S2>
constexpr auto operator+(matrix_type<S1> m1, matrix_type<S2> m2)
{ return elementwise(_+_)(m1, m2); }
template <typename S1, typename S2>
constexpr auto operator-(matrix_type<S1> m1, matrix_type<S2> m2)
{ return elementwise(_-_)(m1, m2); }
auto scalar_prod = [](auto v1, auto v2) {
return sum(zip_with(_*_, v1, v2));
};
auto repeat_n = [](auto n, auto x) {
return unpack(range(int_<0>, n), on(list, always(x)));
};
template <typename S1, typename S2>
constexpr auto operator*(matrix_type<S1> m1, matrix_type<S2> m2) {
auto storage = fmap(
[=](auto row) {
return zip_with(
scalar_prod,
repeat_n(m2.ncolumns(), row),
columns(m2));
}
, rows(m1));
return matrix_type<decltype(storage)>{storage};
}
auto row = [](auto ...entries) {
return list(entries...);
};
auto matrix = [](auto ...rows) {
auto storage = list(rows...);
auto all_same_length = all(tail(storage), [=](auto row) {
return length(row) == length(head(storage));
});
static_assert(all_same_length, "");
return matrix_type<decltype(storage)>{storage};
};
auto vector = on(matrix, row);
constexpr int exponent(int x, unsigned int n) {
if (n == 0) return 1;
else return x * exponent(x, n - 1);
}
auto remove_at = [](auto n, auto xs) {
auto with_indices = zip(xs, range(int_<0>, length(xs)));
auto removed = filter(with_indices, compose(n != _, last));
return fmap(head, removed);
};
template <typename Matrix>
struct _det; // remove circular dependency between matrix_minor and det
auto matrix_minor = [](auto m, auto i, auto j) {
auto submatrix_storage = fmap(partial(remove_at, j), remove_at(i, rows(m)));
matrix_type<decltype(submatrix_storage)> submatrix{submatrix_storage};
return _det<decltype(submatrix)>{}(submatrix);
};
auto cofactor = [](auto m, auto i, auto j) {
auto i_plus_j = i + j;
return int_<exponent(-1, i_plus_j())> * matrix_minor(m, i, j);
};
template <typename Matrix>
struct _det {
constexpr auto operator()(Matrix m) const {
return eval_if(m.size() == int_<1>,
always(m.at(int_<0>, int_<0>)),
[=](auto _) {
auto cofactors_1st_row = unpack(_(range)(int_<0>, m.ncolumns()),
on(list, partial(cofactor, m, int_<0>))
);
return scalar_prod(head(rows(m)), cofactors_1st_row);
}
);
}
};
auto det = [](auto m) {
return _det<decltype(m)>{}(m);
};
namespace boost { namespace hana {
template <>
struct Functor::instance<Matrix> : Functor::fmap_mcd {
template <typename F, typename M>
static constexpr auto fmap_impl(F f, M mat) {
auto new_storage = fmap(partial(fmap, f), mat.rows_);
return matrix_type<decltype(new_storage)>{new_storage};
}
};
template <>
struct Comparable::instance<Matrix, Matrix> : Comparable::equal_mcd {
template <typename M1, typename M2>
static constexpr auto equal_impl(M1 m1, M2 m2) {
return m1.nrows() == m2.nrows() &&
m1.ncolumns() == m2.ncolumns() &&
all_of(zip_with(_==_, m1.rows_, m2.rows_));
}
};
}}
void test_sizes() {
auto m = matrix(
row(1, '2', 3),
row('4', char_<'5'>, 6)
);
BOOST_HANA_CONSTEXPR_ASSERT(m.size() == 6);
BOOST_HANA_CONSTEXPR_ASSERT(m.ncolumns() == 3);
BOOST_HANA_CONSTEXPR_ASSERT(m.nrows() == 2);
}
void test_at() {
auto m = matrix(
row(1, '2', 3),
row('4', char_<'5'>, 6),
row(int_<7>, '8', 9.3)
);
BOOST_HANA_CONSTEXPR_ASSERT(m.at(int_<0>, int_<0>) == 1);
BOOST_HANA_CONSTEXPR_ASSERT(m.at(int_<0>, int_<1>) == '2');
BOOST_HANA_CONSTEXPR_ASSERT(m.at(int_<0>, int_<2>) == 3);
BOOST_HANA_CONSTEXPR_ASSERT(m.at(int_<1>, int_<0>) == '4');
BOOST_HANA_CONSTANT_ASSERT(m.at(int_<1>, int_<1>) == char_<'5'>);
BOOST_HANA_CONSTEXPR_ASSERT(m.at(int_<1>, int_<2>) == 6);
BOOST_HANA_CONSTANT_ASSERT(m.at(int_<2>, int_<0>) == int_<7>);
BOOST_HANA_CONSTEXPR_ASSERT(m.at(int_<2>, int_<1>) == '8');
BOOST_HANA_CONSTEXPR_ASSERT(m.at(int_<2>, int_<2>) == 9.3);
}
void test_comparable() {
BOOST_HANA_CONSTEXPR_ASSERT(matrix(row(1, 2)) == matrix(row(1, 2)));
BOOST_HANA_CONSTEXPR_ASSERT(matrix(row(1, 2)) != matrix(row(1, 5)));
BOOST_HANA_CONSTEXPR_ASSERT(matrix(row(1, 2), row(3, 4)) == matrix(row(1, 2), row(3, 4)));
BOOST_HANA_CONSTEXPR_ASSERT(matrix(row(1, 2), row(3, 4)) != matrix(row(1, 2), row(0, 4)));
BOOST_HANA_CONSTEXPR_ASSERT(matrix(row(1, 2), row(3, 4)) != matrix(row(0, 2), row(3, 4)));
BOOST_HANA_CONSTANT_ASSERT(matrix(row(1), row(2)) != matrix(row(3, 4), row(5, 6)));
BOOST_HANA_CONSTANT_ASSERT(matrix(row(1), row(2)) != matrix(row(3, 4)));
}
void test_functor() {
auto m = matrix(
row(1, int_<2>, 3),
row(int_<4>, 5, 6),
row(7, 8, int_<9>)
);
BOOST_HANA_CONSTEXPR_ASSERT(fmap(_ + int_<1>, m) ==
matrix(
row(2, int_<3>, 4),
row(int_<5>, 6, 7),
row(8, 9, int_<10>)
)
);
}
void test_operators() {
auto m = matrix(row(1, 2), row(3, 4));
BOOST_HANA_CONSTEXPR_ASSERT(m + m == matrix(row(2, 4), row(6, 8)));
BOOST_HANA_CONSTEXPR_ASSERT(m - m == matrix(row(0, 0), row(0, 0)));
}
void test_matrix_multiplication() {
auto A = matrix(
row(1, 2, 3),
row(4, 5, 6)
);
auto B = matrix(
row(1, 2),
row(3, 4),
row(5, 6)
);
BOOST_HANA_CONSTEXPR_ASSERT(A * B == matrix(
row(1*1 + 2*3 + 5*3, 1*2 + 2*4 + 3*6),
row(4*1 + 3*5 + 5*6, 4*2 + 5*4 + 6*6)
));
}
void test_vector() {
auto v = vector(1, '2', int_<3>, 4.2f);
BOOST_HANA_CONSTEXPR_ASSERT(v.size() == 4);
BOOST_HANA_CONSTEXPR_ASSERT(v.nrows() == 4);
BOOST_HANA_CONSTEXPR_ASSERT(v.ncolumns() == 1);
}
void test_transpose() {
auto m = matrix(
row(1, 2.2, '3'),
row(4, '5', 6)
);
BOOST_HANA_CONSTEXPR_ASSERT(transpose(m) ==
matrix(
row(1, 4),
row(2.2, '5'),
row('3', 6)
)
);
}
void test_repeat_n() {
struct T;
BOOST_HANA_CONSTANT_ASSERT(repeat_n(int_<0>, type<T>) == list());
BOOST_HANA_CONSTANT_ASSERT(repeat_n(int_<1>, type<T>) == list(type<T>));
BOOST_HANA_CONSTANT_ASSERT(repeat_n(int_<2>, type<T>) == list(type<T>, type<T>));
BOOST_HANA_CONSTANT_ASSERT(repeat_n(int_<3>, type<T>) == list(type<T>, type<T>, type<T>));
BOOST_HANA_CONSTANT_ASSERT(repeat_n(int_<4>, type<T>) == list(type<T>, type<T>, type<T>, type<T>));
}
void test_determinant() {
BOOST_HANA_CONSTEXPR_ASSERT(det(matrix(row(1))) == 1);
BOOST_HANA_CONSTEXPR_ASSERT(det(matrix(row(2))) == 2);
BOOST_HANA_CONSTEXPR_ASSERT(det(matrix(row(1, 2), row(3, 4))) == -2);
BOOST_HANA_CONSTEXPR_ASSERT(
det(matrix(
row(1, 5, 6),
row(3, 2, 4),
row(7, 8, 9)
))
== 51
);
BOOST_HANA_CONSTEXPR_ASSERT(
det(matrix(
row(1, 5, 6, -3),
row(3, 2, 4, -5),
row(7, 8, 9, -1),
row(8, 2, 1, 10)
)) == 214
);
BOOST_HANA_CONSTEXPR_ASSERT(
det(matrix(
row(1, 5, 6, -3, 92),
row(3, 2, 4, -5, 13),
row(7, 8, 9, -1, 0),
row(8, 2, 1, 10, 41),
row(3, 12, 92, -7, -4)
)) == -3115014
);
}
void test_remove_at() {
BOOST_HANA_CONSTANT_ASSERT(remove_at(int_<0>, list(1)) == list());
BOOST_HANA_CONSTEXPR_ASSERT(remove_at(int_<0>, list(1, '2')) == list('2'));
BOOST_HANA_CONSTEXPR_ASSERT(remove_at(int_<0>, list(1, '2', 3.3)) == list('2', 3.3));
BOOST_HANA_CONSTEXPR_ASSERT(remove_at(int_<1>, list(1, '2')) == list(1));
BOOST_HANA_CONSTEXPR_ASSERT(remove_at(int_<1>, list(1, '2', 3.3)) == list(1, 3.3));
BOOST_HANA_CONSTEXPR_ASSERT(remove_at(int_<2>, list(1, '2', 3.3)) == list(1, '2'));
}
void test_exponent() {
BOOST_HANA_CONSTEXPR_ASSERT(exponent(3, 0) == 1);
BOOST_HANA_CONSTEXPR_ASSERT(exponent(3, 1) == 3);
BOOST_HANA_CONSTEXPR_ASSERT(exponent(3, 2) == 3 * 3);
BOOST_HANA_CONSTEXPR_ASSERT(exponent(3, 3) == 3 * 3 * 3);
BOOST_HANA_CONSTEXPR_ASSERT(exponent(3, 4) == 3 * 3 * 3 * 3);
}
int main() {
test_repeat_n();
test_remove_at();
test_exponent();
test_sizes();
test_at();
test_comparable();
test_functor();
test_operators();
test_vector();
test_transpose();
test_matrix_multiplication();
test_determinant();
}
| 29.17094 | 103 | 0.589608 | [
"vector"
] |
ed4190af469b95ef2ff30d27fff4cfb357b66306 | 2,580 | hpp | C++ | include/function_deduction.hpp | bergesenha/metamusil | 9de1c7c9a7905966b3ced72fa9a2c32d804b1f00 | [
"MIT"
] | 1 | 2017-08-04T20:59:20.000Z | 2017-08-04T20:59:20.000Z | include/function_deduction.hpp | bergesenha/metamusil | 9de1c7c9a7905966b3ced72fa9a2c32d804b1f00 | [
"MIT"
] | null | null | null | include/function_deduction.hpp | bergesenha/metamusil | 9de1c7c9a7905966b3ced72fa9a2c32d804b1f00 | [
"MIT"
] | null | null | null | #pragma once
#include "type_list.hpp"
namespace metamusil
{
////////////////////////////////////////////////////////////////////////////////
// returns return type of a function type of function pointer type
template <class FunctionType>
struct deduce_return_type;
template <class RetType, class... ArgTypes>
struct deduce_return_type<RetType(ArgTypes...)>
{
typedef RetType type;
};
template <class RetType, class... ArgTypes>
struct deduce_return_type<RetType (*)(ArgTypes...)>
{
typedef RetType type;
};
template <class RetType, class ObjectType, class... ArgTypes>
struct deduce_return_type<RetType (ObjectType::*)(ArgTypes...)>
{
typedef RetType type;
};
template <class RetType, class ObjectType, class... ArgTypes>
struct deduce_return_type<RetType (ObjectType::*)(ArgTypes...) const>
{
typedef RetType type;
};
template <class FunctionType>
using deduce_return_type_t = typename deduce_return_type<FunctionType>::type;
////////////////////////////////////////////////////////////////////////////////
// returns parameter types in a type_list
template <class FunctionType>
struct deduce_parameter_types;
template <class RetType, class... ArgTypes>
struct deduce_parameter_types<RetType(ArgTypes...)>
{
typedef t_list::type_list<ArgTypes...> type;
};
template <class RetType, class... ArgTypes>
struct deduce_parameter_types<RetType (*)(ArgTypes...)>
{
typedef t_list::type_list<ArgTypes...> type;
};
template <class RetType, class ObjectType, class... ArgTypes>
struct deduce_parameter_types<RetType (ObjectType::*)(ArgTypes...)>
{
typedef t_list::type_list<ArgTypes...> type;
};
template <class RetType, class ObjectType, class... ArgTypes>
struct deduce_parameter_types<RetType (ObjectType::*)(ArgTypes...) const>
{
typedef t_list::type_list<ArgTypes...> type;
};
template <class FunctionType>
using deduce_parameter_types_t =
typename deduce_parameter_types<FunctionType>::type;
////////////////////////////////////////////////////////////////////////////////
// returns type of object the member function is a member of
template <class FunctionType>
struct deduce_object_type;
template <class RetType, class ObjectType, class... ArgTypes>
struct deduce_object_type<RetType (ObjectType::*)(ArgTypes...)>
{
typedef ObjectType type;
};
template <class RetType, class ObjectType, class... ArgTypes>
struct deduce_object_type<RetType (ObjectType::*)(ArgTypes...) const>
{
typedef ObjectType type;
};
template <class FunctionType>
using deduce_object_type_t = typename deduce_object_type<FunctionType>::type;
}
| 27.157895 | 80 | 0.684496 | [
"object"
] |
ed4357505c5be89f36b8349a998b88f2cac2d1f4 | 17,560 | cpp | C++ | src/chainparams.cpp | chronokings/huntercore | 57739078e557db181ae4ee66c16f51d8f8f18da2 | [
"MIT"
] | 11 | 2019-04-15T21:57:47.000Z | 2022-01-18T22:53:22.000Z | src/chainparams.cpp | Palem1988/huntercore | 149413f7b69d3ae21d10e0f69970cf4e3ad2af12 | [
"MIT"
] | 14 | 2016-04-21T17:14:12.000Z | 2018-08-06T13:30:15.000Z | src/chainparams.cpp | Palem1988/huntercore | 149413f7b69d3ae21d10e0f69970cf4e3ad2af12 | [
"MIT"
] | 13 | 2017-04-06T20:53:25.000Z | 2021-12-05T02:59:32.000Z | // Copyright (c) 2010 Satoshi Nakamoto
// Copyright (c) 2009-2017 The Bitcoin Core developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include <chainparams.h>
#include <consensus/merkle.h>
#include <names/common.h>
#include <tinyformat.h>
#include <util.h>
#include <utilstrencodings.h>
#include <assert.h>
#include <chainparamsseeds.h>
bool CChainParams::IsHistoricBug(const uint256& txid, unsigned nHeight, BugType& type) const
{
const std::pair<unsigned, uint256> key(nHeight, txid);
std::map<std::pair<unsigned, uint256>, BugType>::const_iterator mi;
mi = mapHistoricBugs.find (key);
if (mi != mapHistoricBugs.end ())
{
type = mi->second;
return true;
}
return false;
}
static CBlock CreateGenesisBlock(const char* pszTimestamp, const CScript& genesisOutputScript, uint32_t nTime, uint32_t nNonce, uint32_t nBits, int32_t nVersion, const CAmount& genesisReward)
{
CMutableTransaction txNew;
txNew.nVersion = 1;
txNew.vin.resize(1);
txNew.vout.resize(1);
txNew.vin[0].scriptSig = CScript() << ValtypeFromString(std::string(pszTimestamp));
txNew.vout[0].nValue = genesisReward;
txNew.vout[0].scriptPubKey = genesisOutputScript;
CBlock genesis;
genesis.nTime = nTime;
genesis.nBits = nBits;
genesis.nNonce = nNonce;
genesis.nVersion = nVersion;
genesis.vtx.push_back(MakeTransactionRef(std::move(txNew)));
genesis.hashPrevBlock.SetNull();
genesis.hashMerkleRoot = BlockMerkleRoot(genesis);
return genesis;
}
/**
* Build the genesis block.
*/
static CBlock CreateGenesisBlock(uint32_t nTime, uint32_t nNonce, uint32_t nBits, int32_t nVersion, const CAmount& genesisReward)
{
const char *pszTimestamp =
"\n"
"Huntercoin genesis timestamp\n"
"31/Jan/2014 20:10 GMT\n"
"Bitcoin block 283440: 0000000000000001795d3c369b0746c0b5d315a6739a7410ada886de5d71ca86\n"
"Litecoin block 506479: 77c49384e6e8dd322da0ebb32ca6c8f047d515d355e9f22b116430a888fffd38\n"
;
const CScript genesisOutputScript = CScript() << OP_DUP << OP_HASH160 << ParseHex("fe2435b201d25290533bdaacdfe25dc7548b3058") << OP_EQUALVERIFY << OP_CHECKSIG;
return CreateGenesisBlock(pszTimestamp, genesisOutputScript, nTime, nNonce, nBits, nVersion, genesisReward);
}
/**
* Build genesis block for testnet. In Huntercoin, it has a changed timestamp
* and output script.
*/
static CBlock CreateTestnetGenesisBlock(uint32_t nTime, uint32_t nNonce, uint32_t nBits, int32_t nVersion, const CAmount& genesisReward)
{
const char* pszTimestamp = "\nHuntercoin test net\n";
const CScript genesisOutputScript = CScript() << OP_DUP << OP_HASH160 << ParseHex("7238d2df990b8e333ed28a84a8df8408f6dbcd57") << OP_EQUALVERIFY << OP_CHECKSIG;
return CreateGenesisBlock(pszTimestamp, genesisOutputScript, nTime, nNonce, nBits, nVersion, genesisReward);
}
void CChainParams::UpdateVersionBitsParameters(Consensus::DeploymentPos d, int64_t nStartTime, int64_t nTimeout)
{
consensus.vDeployments[d].nStartTime = nStartTime;
consensus.vDeployments[d].nTimeout = nTimeout;
}
void CChainParams::TurnOffSegwitForUnitTests ()
{
consensus.BIP16Height = 1000000000;
}
/**
* Main network
*/
/**
* What makes a good checkpoint block?
* + Is surrounded by blocks with reasonable timestamps
* (no blocks before with a timestamp after, none after with
* timestamp before)
* + Contains no strange transactions
*/
class CMainParams : public CChainParams {
public:
CMainParams() {
strNetworkID = "main";
consensus.nSubsidyHalvingInterval = 2100000;
/* FIXME: Set to activate the forks. */
consensus.BIP16Height = 1000000000;
consensus.BIP34Height = 1000000000;
consensus.BIP65Height = 1000000000;
consensus.BIP66Height = 1000000000;
consensus.powLimit[ALGO_SHA256D] = uint256S("00000000ffffffffffffffffffffffffffffffffffffffffffffffffffffffff");
consensus.powLimit[ALGO_SCRYPT] = uint256S("00000fffffffffffffffffffffffffffffffffffffffffffffffffffffffffff");
consensus.nPowTargetSpacing = 60 * NUM_ALGOS;
consensus.nPowTargetTimespan = consensus.nPowTargetSpacing * 2016;
consensus.fPowNoRetargeting = false;
consensus.nRuleChangeActivationThreshold = 1916; // 95% of 2016
consensus.nMinerConfirmationWindow = 2016; // nPowTargetTimespan / nPowTargetSpacing
consensus.vDeployments[Consensus::DEPLOYMENT_TESTDUMMY].bit = 28;
consensus.vDeployments[Consensus::DEPLOYMENT_TESTDUMMY].nStartTime = 1199145601; // January 1, 2008
consensus.vDeployments[Consensus::DEPLOYMENT_TESTDUMMY].nTimeout = 1230767999; // December 31, 2008
// CSV (BIP68, BIP112 and BIP113) as well as segwit (BIP141, BIP143 and
// BIP147) are deployed together with P2SH.
// The best chain should have at least this much work.
// The value is the chain work of the Huntercoin mainnet chain at height
// 1,490,000, with best block hash:
// d38feb2df0fc1b64bd3b3fe5b1e90d15a5d8ca17a13b735db381d16ce359393f
consensus.nMinimumChainWork = uint256S("0x0000000000000000000000000000000000000000000326ede22d6f88e27b6e95");
// By default assume that the signatures in ancestors of this block are valid.
consensus.defaultAssumeValid = uint256S("0x4bf3a4e732a8ef2c8d93c996f9ffc9e8c9044ec687b13defb9b86cd33b7428e2"); //1500000
consensus.nAuxpowChainId[ALGO_SHA256D] = 0x0006;
consensus.nAuxpowChainId[ALGO_SCRYPT] = 0x0002;
consensus.fStrictChainId = true;
consensus.rules.reset(new Consensus::MainNetConsensus());
/**
* The message start string is designed to be unlikely to occur in normal data.
* The characters are rarely used upper ASCII, not valid as UTF-8, and produce
* a large 32-bit integer with any alignment.
*/
pchMessageStart[0] = 0xf9;
pchMessageStart[1] = 0xbe;
pchMessageStart[2] = 0xb4;
pchMessageStart[3] = 0xfe;
nDefaultPort = 8398;
nPruneAfterHeight = 100000;
genesis = CreateGenesisBlock(1391199780, 1906435634u, 486604799, 1, 85000 * COIN);
consensus.hashGenesisBlock = genesis.GetHash();
assert(consensus.hashGenesisBlock == uint256S("0x00000000db7eb7a9e1a06cf995363dcdc4c28e8ae04827a961942657db9a1631"));
assert(genesis.hashMerkleRoot == uint256S("0xc4ee946ffcb0bffa454782432d530bbeb8562b09594c1fbc8ceccd46ce34a754"));
// Note that of those which support the service bits prefix, most only support a subset of
// possible options.
// This is fine at runtime as we'll fall back to using them as a oneshot if they don't support the
// service bits we want, but we should get them updated to support all service bits wanted by any
// release ASAP to avoid it where possible.
/* FIXME: Add DNS seeds. */
//vSeeds.emplace_back("nmc.seed.quisquis.de");
base58Prefixes[PUBKEY_ADDRESS] = std::vector<unsigned char>(1,40);
base58Prefixes[SCRIPT_ADDRESS] = std::vector<unsigned char>(1,13); // FIXME: Update.
base58Prefixes[SECRET_KEY] = std::vector<unsigned char>(1,168);
/* FIXME: Update these below. */
base58Prefixes[EXT_PUBLIC_KEY] = {0x04, 0x88, 0xB2, 0x1E};
base58Prefixes[EXT_SECRET_KEY] = {0x04, 0x88, 0xAD, 0xE4};
bech32_hrp = "hc";
// FIXME: Set seeds for Huntercoin.
//vFixedSeeds = std::vector<SeedSpec6>(pnSeed6_main, pnSeed6_main + ARRAYLEN(pnSeed6_main));
fDefaultConsistencyChecks = false;
fRequireStandard = true;
fMineBlocksOnDemand = false;
checkpointData = {
{
{0, uint256S("00000000db7eb7a9e1a06cf995363dcdc4c28e8ae04827a961942657db9a1631")},
}
};
chainTxData = ChainTxData{
0, // * UNIX timestamp of last checkpoint block
0, // * total number of transactions between genesis and last checkpoint
// (the tx=... number in the SetBestChain debug.log lines)
0 // * estimated number of transactions per day after checkpoint
};
/* disable fallback fee on mainnet */
m_fallback_fee_enabled = false;
}
int DefaultCheckNameDB () const
{
return -1;
}
};
/**
* Testnet (v3)
*/
class CTestNetParams : public CChainParams {
public:
CTestNetParams() {
strNetworkID = "test";
consensus.nSubsidyHalvingInterval = 2100000;
/* FIXME: Set to activate the forks. */
consensus.BIP16Height = 1000000000;
consensus.BIP34Height = 1000000000;
consensus.BIP65Height = 1000000000;
consensus.BIP66Height = 1000000000;
consensus.powLimit[ALGO_SHA256D] = uint256S("000000ffffffffffffffffffffffffffffffffffffffffffffffffffffffffff");
consensus.powLimit[ALGO_SCRYPT] = uint256S("000fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff");
consensus.nPowTargetSpacing = 60 * NUM_ALGOS;
consensus.nPowTargetTimespan = consensus.nPowTargetSpacing * 2016;
consensus.fPowNoRetargeting = false;
consensus.nRuleChangeActivationThreshold = 1512; // 75% for testchains
consensus.nMinerConfirmationWindow = 2016; // nPowTargetTimespan / nPowTargetSpacing
consensus.vDeployments[Consensus::DEPLOYMENT_TESTDUMMY].bit = 28;
consensus.vDeployments[Consensus::DEPLOYMENT_TESTDUMMY].nStartTime = 1199145601; // January 1, 2008
consensus.vDeployments[Consensus::DEPLOYMENT_TESTDUMMY].nTimeout = 1230767999; // December 31, 2008
// CSV (BIP68, BIP112 and BIP113) as well as segwit (BIP141, BIP143 and
// BIP147) are deployed together with P2SH.
// The best chain should have at least this much work.
// The value is the chain work of the Huntercoin testnet chain at height
// 350,000, with best block hash:
// 884920fb406847e9ebaac69305d97d6df9fa125603fd7d3e26c00a0d79c29ddc
consensus.nMinimumChainWork = uint256S("0x00000000000000000000000000000000000000000000000000038998cea702f2");
// By default assume that the signatures in ancestors of this block are valid.
consensus.defaultAssumeValid = uint256S("0xdabe819758cfe24c960d335ed420f77bdaf7aa98e4beea51ea7c9f14448f6a3a"); //300000
consensus.nAuxpowChainId[ALGO_SHA256D] = 0x0006;
consensus.nAuxpowChainId[ALGO_SCRYPT] = 0x0002;
consensus.fStrictChainId = false;
consensus.rules.reset(new Consensus::TestNetConsensus());
pchMessageStart[0] = 0xfa;
pchMessageStart[1] = 0xbf;
pchMessageStart[2] = 0xb5;
pchMessageStart[3] = 0xfe;
nDefaultPort = 18398;
nPruneAfterHeight = 1000;
genesis = CreateTestnetGenesisBlock(1391193136, 1997599826u, 503382015, 1, 100 * COIN);
consensus.hashGenesisBlock = genesis.GetHash();
assert(consensus.hashGenesisBlock == uint256S("000000492c361a01ce7558a3bfb198ea3ff2f86f8b0c2e00d26135c53f4acbf7"));
assert(genesis.hashMerkleRoot == uint256S("28da665eada1b006bb9caf83e7541c6f995e0681debfc2540507bbfdf2d4ac84"));
vFixedSeeds.clear();
vSeeds.clear();
/* FIXME: Testnet seeds? */
// nodes with support for servicebits filtering should be at the top
//vSeeds.emplace_back("dnsseed.test.namecoin.webbtc.com");
base58Prefixes[PUBKEY_ADDRESS] = std::vector<unsigned char>(1,100);
base58Prefixes[SCRIPT_ADDRESS] = std::vector<unsigned char>(1,196); // FIXME: Update
base58Prefixes[SECRET_KEY] = std::vector<unsigned char>(1,228);
/* FIXME: Update these below. */
base58Prefixes[EXT_PUBLIC_KEY] = {0x04, 0x35, 0x87, 0xCF};
base58Prefixes[EXT_SECRET_KEY] = {0x04, 0x35, 0x83, 0x94};
bech32_hrp = "th";
// FIXME: Set seeds for Huntercoin.
//vFixedSeeds = std::vector<SeedSpec6>(pnSeed6_test, pnSeed6_test + ARRAYLEN(pnSeed6_test));
fDefaultConsistencyChecks = false;
fRequireStandard = false;
fMineBlocksOnDemand = false;
checkpointData = {
{
{0, uint256S("000000492c361a01ce7558a3bfb198ea3ff2f86f8b0c2e00d26135c53f4acbf7")},
}
};
chainTxData = ChainTxData{
0,
0,
0
};
/* enable fallback fee on testnet */
m_fallback_fee_enabled = true;
assert(mapHistoricBugs.empty());
}
int DefaultCheckNameDB () const
{
return -1;
}
};
/**
* Regression test
*/
class CRegTestParams : public CChainParams {
public:
CRegTestParams() {
strNetworkID = "regtest";
consensus.nSubsidyHalvingInterval = 150;
consensus.BIP16Height = 432; // Corresponds to activation height using BIP9 rules
consensus.BIP34Height = 100000000; // BIP34 has not activated on regtest (far in the future so block v1 are not rejected in tests)
consensus.BIP65Height = 1351; // BIP65 activated on regtest (Used in rpc activation tests)
consensus.BIP66Height = 1251; // BIP66 activated on regtest (Used in rpc activation tests)
consensus.powLimit[ALGO_SHA256D] = uint256S("7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff");
consensus.powLimit[ALGO_SCRYPT] = uint256S("7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff");
consensus.nPowTargetSpacing = 60 * NUM_ALGOS;
consensus.nPowTargetTimespan = consensus.nPowTargetSpacing * 2016;
consensus.fPowNoRetargeting = true;
consensus.nRuleChangeActivationThreshold = 108; // 75% for testchains
consensus.nMinerConfirmationWindow = 144; // Faster than normal for regtest (144 instead of 2016)
consensus.vDeployments[Consensus::DEPLOYMENT_TESTDUMMY].bit = 28;
consensus.vDeployments[Consensus::DEPLOYMENT_TESTDUMMY].nStartTime = 0;
consensus.vDeployments[Consensus::DEPLOYMENT_TESTDUMMY].nTimeout = Consensus::BIP9Deployment::NO_TIMEOUT;
// The best chain should have at least this much work.
consensus.nMinimumChainWork = uint256S("0x00");
// By default assume that the signatures in ancestors of this block are valid.
consensus.defaultAssumeValid = uint256S("0x00");
consensus.nAuxpowChainId[ALGO_SHA256D] = 0x0006;
consensus.nAuxpowChainId[ALGO_SCRYPT] = 0x0002;
consensus.fStrictChainId = true;
consensus.rules.reset(new Consensus::RegTestConsensus());
pchMessageStart[0] = 0xfa;
pchMessageStart[1] = 0xbf;
pchMessageStart[2] = 0xb5;
pchMessageStart[3] = 0xda;
nDefaultPort = 18498;
nPruneAfterHeight = 1000;
genesis = CreateTestnetGenesisBlock(1296688602, 2, 0x207fffff, 1, 50 * COIN);
consensus.hashGenesisBlock = genesis.GetHash();
assert(consensus.hashGenesisBlock == uint256S("0x3867dcd08712d9b49de33d4ab145d57ad14a78c7843c51f8c5d782d5f102fb4a"));
assert(genesis.hashMerkleRoot == uint256S("0x71c88ed0560ee7d644deba07485c4eff571e3f86f9485692ed3966e4f0f3a59c"));
vFixedSeeds.clear(); //!< Regtest mode doesn't have any fixed seeds.
vSeeds.clear(); //!< Regtest mode doesn't have any DNS seeds.
fDefaultConsistencyChecks = true;
fRequireStandard = false;
fMineBlocksOnDemand = true;
checkpointData = {
{
{0, uint256S("3867dcd08712d9b49de33d4ab145d57ad14a78c7843c51f8c5d782d5f102fb4a")},
}
};
chainTxData = ChainTxData{
0,
0,
0
};
base58Prefixes[PUBKEY_ADDRESS] = std::vector<unsigned char>(1,100);
base58Prefixes[SCRIPT_ADDRESS] = std::vector<unsigned char>(1,196); // FIXME: Update.
base58Prefixes[SECRET_KEY] = std::vector<unsigned char>(1,228);
/* FIXME: Update below. */
base58Prefixes[EXT_PUBLIC_KEY] = {0x04, 0x35, 0x87, 0xCF};
base58Prefixes[EXT_SECRET_KEY] = {0x04, 0x35, 0x83, 0x94};
bech32_hrp = "hcrt";
/* enable fallback fee on regtest */
m_fallback_fee_enabled = true;
assert(mapHistoricBugs.empty());
}
int DefaultCheckNameDB () const
{
return 0;
}
};
static std::unique_ptr<CChainParams> globalChainParams;
const CChainParams &Params() {
assert(globalChainParams);
return *globalChainParams;
}
std::unique_ptr<CChainParams> CreateChainParams(const std::string& chain)
{
if (chain == CBaseChainParams::MAIN)
return std::unique_ptr<CChainParams>(new CMainParams());
else if (chain == CBaseChainParams::TESTNET)
return std::unique_ptr<CChainParams>(new CTestNetParams());
else if (chain == CBaseChainParams::REGTEST)
return std::unique_ptr<CChainParams>(new CRegTestParams());
throw std::runtime_error(strprintf("%s: Unknown chain %s.", __func__, chain));
}
void SelectParams(const std::string& network)
{
SelectBaseParams(network);
globalChainParams = CreateChainParams(network);
}
void UpdateVersionBitsParameters(Consensus::DeploymentPos d, int64_t nStartTime, int64_t nTimeout)
{
globalChainParams->UpdateVersionBitsParameters(d, nStartTime, nTimeout);
}
void TurnOffSegwitForUnitTests ()
{
globalChainParams->TurnOffSegwitForUnitTests ();
}
| 41.124122 | 191 | 0.694818 | [
"vector"
] |
ed450c45e12a13f5c8519ea52ca581785d5b4848 | 3,459 | cxx | C++ | src/Cxx/Images/ImageDivergence.cxx | cvandijck/VTKExamples | b6bb89414522afc1467be8a1f0089a37d0c16883 | [
"Apache-2.0"
] | 309 | 2017-05-21T09:07:19.000Z | 2022-03-15T09:18:55.000Z | src/Cxx/Images/ImageDivergence.cxx | yijianmingliu/VTKExamples | dc8aac47c4384f9a2de9facbdd1ab3249f62ec99 | [
"Apache-2.0"
] | 379 | 2017-05-21T09:06:43.000Z | 2021-03-29T20:30:50.000Z | src/Cxx/Images/ImageDivergence.cxx | yijianmingliu/VTKExamples | dc8aac47c4384f9a2de9facbdd1ab3249f62ec99 | [
"Apache-2.0"
] | 170 | 2017-05-17T14:47:41.000Z | 2022-03-31T13:16:26.000Z | #include <vtkSmartPointer.h>
#include <vtkImageCast.h>
#include <vtkImageData.h>
#include <vtkImageMapper3D.h>
#include <vtkImageCanvasSource2D.h>
#include <vtkImageDivergence.h>
#include <vtkImageGradient.h>
#include <vtkImageCanvasSource2D.h>
#include <vtkImageCorrelation.h>
#include <vtkInteractorStyleImage.h>
#include <vtkImageActor.h>
#include <vtkActor.h>
#include <vtkRenderWindow.h>
#include <vtkRenderer.h>
#include <vtkRenderWindowInteractor.h>
#include <vtkImageMandelbrotSource.h>
int main(int, char *[])
{
// Create an image
vtkSmartPointer<vtkImageMandelbrotSource> source =
vtkSmartPointer<vtkImageMandelbrotSource>::New();
source->Update();
vtkSmartPointer<vtkImageCast> originalCastFilter =
vtkSmartPointer<vtkImageCast>::New();
originalCastFilter->SetInputConnection(source->GetOutputPort());
originalCastFilter->SetOutputScalarTypeToFloat();
originalCastFilter->Update();
// Compute the gradient (to produce a vector field)
vtkSmartPointer<vtkImageGradient> gradientFilter =
vtkSmartPointer<vtkImageGradient>::New();
gradientFilter->SetInputConnection(source->GetOutputPort());
gradientFilter->Update();
vtkSmartPointer<vtkImageDivergence> divergenceFilter =
vtkSmartPointer<vtkImageDivergence>::New();
divergenceFilter->SetInputConnection(gradientFilter->GetOutputPort());
divergenceFilter->Update();
vtkSmartPointer<vtkImageCast> divergenceCastFilter =
vtkSmartPointer<vtkImageCast>::New();
divergenceCastFilter->SetInputConnection(divergenceFilter->GetOutputPort());
divergenceCastFilter->SetOutputScalarTypeToFloat();
divergenceCastFilter->Update();
// Create actors
vtkSmartPointer<vtkImageActor> originalActor =
vtkSmartPointer<vtkImageActor>::New();
originalActor->GetMapper()->SetInputConnection(
originalCastFilter->GetOutputPort());
vtkSmartPointer<vtkImageActor> divergenceActor =
vtkSmartPointer<vtkImageActor>::New();
divergenceActor->GetMapper()->SetInputConnection(
divergenceCastFilter->GetOutputPort());
// Define viewport ranges
// (xmin, ymin, xmax, ymax)
double leftViewport[4] = {0.0, 0.0, 0.5, 1.0};
double rightViewport[4] = {0.5, 0.0, 1.0, 1.0};
// Setup renderers
vtkSmartPointer<vtkRenderer> originalRenderer =
vtkSmartPointer<vtkRenderer>::New();
originalRenderer->SetViewport(leftViewport);
originalRenderer->AddActor(originalActor);
originalRenderer->ResetCamera();
vtkSmartPointer<vtkRenderer> divergenceRenderer =
vtkSmartPointer<vtkRenderer>::New();
divergenceRenderer->SetViewport(rightViewport);
divergenceRenderer->AddActor(divergenceActor);
divergenceRenderer->ResetCamera();
// Setup render window
vtkSmartPointer<vtkRenderWindow> renderWindow =
vtkSmartPointer<vtkRenderWindow>::New();
renderWindow->SetSize(600,300);
renderWindow->AddRenderer(originalRenderer);
renderWindow->AddRenderer(divergenceRenderer);
// Setup render window interactor
vtkSmartPointer<vtkRenderWindowInteractor> renderWindowInteractor =
vtkSmartPointer<vtkRenderWindowInteractor>::New();
vtkSmartPointer<vtkInteractorStyleImage> style =
vtkSmartPointer<vtkInteractorStyleImage>::New();
renderWindowInteractor->SetInteractorStyle(style);
// Render and start interaction
renderWindowInteractor->SetRenderWindow(renderWindow);
renderWindow->Render();
renderWindowInteractor->Initialize();
renderWindowInteractor->Start();
return EXIT_SUCCESS;
}
| 34.247525 | 78 | 0.777971 | [
"render",
"vector"
] |
ed470d82cf4d7817afadf8f93696cf45a060ed97 | 5,776 | cpp | C++ | src/render/opengl/shaders/ribbon_shaders.cpp | DavidJourdan/polyscope | 5134f225143c1713904c3bbbe3a25d910dbcfbb1 | [
"MIT"
] | 4 | 2020-04-16T08:55:33.000Z | 2020-04-16T08:55:37.000Z | src/render/opengl/shaders/ribbon_shaders.cpp | DavidJourdan/polyscope | 5134f225143c1713904c3bbbe3a25d910dbcfbb1 | [
"MIT"
] | null | null | null | src/render/opengl/shaders/ribbon_shaders.cpp | DavidJourdan/polyscope | 5134f225143c1713904c3bbbe3a25d910dbcfbb1 | [
"MIT"
] | null | null | null | // Copyright 2017-2019, Nicholas Sharp and the Polyscope contributors. http://polyscope.run.
#include "polyscope/render/opengl/gl_shaders.h"
namespace polyscope {
namespace render {
// clang-format off
const ShaderStageSpecification RIBBON_VERT_SHADER = {
ShaderStageType::Vertex,
{ }, // uniforms
// attributes
{
{"a_position", DataType::Vector3Float},
{"a_color", DataType::Vector3Float},
{"a_normal", DataType::Vector3Float},
},
{}, // textures
// source
POLYSCOPE_GLSL(150,
in vec3 a_position;
in vec3 a_color;
in vec3 a_normal;
out vec3 Color;
out vec3 Normal;
void main()
{
Color = a_color;
Normal = a_normal;
gl_Position = vec4(a_position,1.0);
}
)
};
const ShaderStageSpecification RIBBON_GEOM_SHADER = {
ShaderStageType::Geometry,
// uniforms
{
{"u_modelView", DataType::Matrix44Float},
{"u_projMatrix", DataType::Matrix44Float},
{"u_ribbonWidth", DataType::Float},
{"u_depthOffset", DataType::Float},
},
// attributes
{
},
{}, // textures
// source
POLYSCOPE_GLSL(150,
layout(lines_adjacency) in;
layout(triangle_strip, max_vertices=20) out;
in vec3 Color[];
in vec3 Normal[];
uniform mat4 u_modelView;
uniform mat4 u_projMatrix;
uniform float u_ribbonWidth;
uniform float u_depthOffset;
out vec3 colorToFrag;
out vec3 cameraNormalToFrag;
out float intensityToFrag;
void main() {
mat4 PV = u_projMatrix * u_modelView;
const float PI = 3.14159265358;
vec3 pos0 = gl_in[0].gl_Position.xyz;
vec3 pos1 = gl_in[1].gl_Position.xyz;
vec3 pos2 = gl_in[2].gl_Position.xyz;
vec3 pos3 = gl_in[3].gl_Position.xyz;
vec3 dir = normalize(pos2 - pos1);
vec3 prevDir = normalize(pos1 - pos0);
vec3 nextDir = normalize(pos3 - pos2);
vec3 sideVec0 = normalize(cross(normalize(dir + prevDir), Normal[1]));
vec3 sideVec1 = normalize(cross(normalize(dir + nextDir), Normal[2]));
// The points on the front and back sides of the ribbon
vec4 pStartLeft = vec4(pos1 + sideVec0 * u_ribbonWidth, 1);
vec4 pStartMid = vec4(pos1, 1);
vec4 pStartRight = vec4(pos1 - sideVec0 * u_ribbonWidth, 1);
vec4 pEndLeft = vec4(pos2 + sideVec1 * u_ribbonWidth, 1);
vec4 pEndMid = vec4(pos2, 1);
vec4 pEndRight = vec4(pos2 - sideVec1 * u_ribbonWidth, 1);
// First triangle
gl_Position = PV * pStartRight;
gl_Position.z -= u_depthOffset;
cameraNormalToFrag = mat3(u_modelView) * Normal[1];
colorToFrag = Color[1];
intensityToFrag = 0.0;
EmitVertex();
gl_Position = PV * pEndRight;
gl_Position.z -= u_depthOffset;
cameraNormalToFrag = mat3(u_modelView) * Normal[2];
colorToFrag = Color[2];
intensityToFrag = 0.0;
EmitVertex();
gl_Position = PV * pStartMid;
gl_Position.z -= u_depthOffset;
cameraNormalToFrag = mat3(u_modelView) * Normal[1];
colorToFrag = Color[1];
intensityToFrag = 1.0;
EmitVertex();
// Second triangle
gl_Position = PV * pEndMid;
gl_Position.z -= u_depthOffset;
cameraNormalToFrag = mat3(u_modelView) * Normal[2];
colorToFrag = Color[2];
intensityToFrag = 1.0;
EmitVertex();
// Third triangle
gl_Position = PV * pStartLeft;
gl_Position.z -= u_depthOffset;
cameraNormalToFrag = mat3(u_modelView) * Normal[1];
colorToFrag = Color[1];
intensityToFrag = 0.0;
EmitVertex();
// Fourth triangle
gl_Position = PV * pEndLeft;
gl_Position.z -= u_depthOffset;
cameraNormalToFrag = mat3(u_modelView) * Normal[2];
colorToFrag = Color[2];
intensityToFrag = 0.0;
EmitVertex();
EndPrimitive();
}
)
};
const ShaderStageSpecification RIBBON_FRAG_SHADER = {
ShaderStageType::Fragment,
{ }, // uniforms
{ }, // attributes
// textures
{
{"t_mat_r", 2},
{"t_mat_g", 2},
{"t_mat_b", 2},
{"t_mat_k", 2},
},
// source
POLYSCOPE_GLSL(330 core,
uniform sampler2D t_mat_r;
uniform sampler2D t_mat_g;
uniform sampler2D t_mat_b;
uniform sampler2D t_mat_k;
in vec3 colorToFrag;
in vec3 cameraNormalToFrag;
in float intensityToFrag;
layout(location = 0) out vec4 outputF;
vec3 lightSurfaceMat(vec3 normal, vec3 color, sampler2D t_mat_r, sampler2D t_mat_g, sampler2D t_mat_b, sampler2D t_mat_k);
void main()
{
// Compute a fade factor to set the transparency
// Basically amounts to antialiasing in screen space when lines are relatively large on screen
float screenFadeLen = 2.5;
float dF = length(vec2(dFdx(intensityToFrag),dFdy(intensityToFrag)));
float thresh = min(dF * screenFadeLen, 0.2);
float fadeFactor = smoothstep(0, thresh, intensityToFrag);
outputF = vec4(lightSurfaceMat(cameraNormalToFrag, colorToFrag, t_mat_r, t_mat_g, t_mat_b, t_mat_k), fadeFactor);
}
)
};
// clang-format on
} // namespace gl
} // namespace polyscope
| 29.319797 | 130 | 0.569598 | [
"geometry",
"render"
] |
ed48118e808f970de21db373d45053fee85a9c7e | 16,097 | cc | C++ | chrome/browser/nearby_sharing/client/nearby_share_api_call_flow_impl_unittest.cc | DamieFC/chromium | 54ce2d3c77723697efd22cfdb02aea38f9dfa25c | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | 1 | 2020-10-18T02:33:40.000Z | 2020-10-18T02:33:40.000Z | chrome/browser/nearby_sharing/client/nearby_share_api_call_flow_impl_unittest.cc | DamieFC/chromium | 54ce2d3c77723697efd22cfdb02aea38f9dfa25c | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | 3 | 2021-05-17T16:28:52.000Z | 2021-05-21T22:42:22.000Z | chrome/browser/nearby_sharing/client/nearby_share_api_call_flow_impl_unittest.cc | DamieFC/chromium | 54ce2d3c77723697efd22cfdb02aea38f9dfa25c | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | null | null | null | // Copyright 2020 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 <memory>
#include <string>
#include <utility>
#include <vector>
#include "base/bind.h"
#include "base/no_destructor.h"
#include "base/test/task_environment.h"
#include "chrome/browser/nearby_sharing/client/nearby_share_api_call_flow_impl.h"
#include "net/base/net_errors.h"
#include "net/base/url_util.h"
#include "net/traffic_annotation/network_traffic_annotation_test_helper.h"
#include "services/network/public/cpp/weak_wrapper_shared_url_loader_factory.h"
#include "services/network/test/test_url_loader_factory.h"
#include "services/network/test/test_utils.h"
#include "testing/gtest/include/gtest/gtest.h"
#include "third_party/abseil-cpp/absl/types/optional.h"
namespace {
const char kSerializedRequestProto[] = "serialized_request_proto";
const char kSerializedResponseProto[] = "result_proto";
const char kRequestUrl[] = "https://googleapis.com/nearbysharing/test";
const char kAccessToken[] = "access_token";
const char kQueryParameterAlternateOutputKey[] = "alt";
const char kQueryParameterAlternateOutputProto[] = "proto";
const char kGet[] = "GET";
const char kPost[] = "POST";
const char kPatch[] = "PATCH";
const NearbyShareApiCallFlow::QueryParameters&
GetTestRequestProtoAsQueryParameters() {
static const base::NoDestructor<NearbyShareApiCallFlow::QueryParameters>
request_as_query_parameters(
{{"field1", "value1a"}, {"field1", "value1b"}, {"field2", "value2"}});
return *request_as_query_parameters;
}
// Adds the "alt=proto" query parameters which specifies that the response
// should be formatted as a serialized proto. Adds the key-value pairs of
// |request_as_query_parameters| as query parameters.
// |request_as_query_parameters| is only non-null for GET requests.
GURL UrlWithQueryParameters(
const std::string& url,
const absl::optional<NearbyShareApiCallFlow::QueryParameters>&
request_as_query_parameters) {
GURL url_with_qp(url);
url_with_qp =
net::AppendQueryParameter(url_with_qp, kQueryParameterAlternateOutputKey,
kQueryParameterAlternateOutputProto);
if (request_as_query_parameters) {
for (const auto& key_value : *request_as_query_parameters) {
url_with_qp = net::AppendQueryParameter(url_with_qp, key_value.first,
key_value.second);
}
}
return url_with_qp;
}
} // namespace
class NearbyShareApiCallFlowImplTest : public testing::Test {
protected:
NearbyShareApiCallFlowImplTest()
: shared_factory_(
base::MakeRefCounted<network::WeakWrapperSharedURLLoaderFactory>(
&test_url_loader_factory_)) {
flow_.SetPartialNetworkTrafficAnnotation(
PARTIAL_TRAFFIC_ANNOTATION_FOR_TESTS);
}
void StartPostRequestApiCallFlow() {
StartPostRequestApiCallFlowWithSerializedRequest(kSerializedRequestProto);
}
void StartPostRequestApiCallFlowWithSerializedRequest(
const std::string& serialized_request) {
flow_.StartPostRequest(
GURL(kRequestUrl), serialized_request, shared_factory_, kAccessToken,
base::BindOnce(&NearbyShareApiCallFlowImplTest::OnResult,
base::Unretained(this)),
base::BindOnce(&NearbyShareApiCallFlowImplTest::OnError,
base::Unretained(this)));
// A pending fetch for the API request should be created.
CheckNearbySharingClientHttpPostRequest(serialized_request);
}
void StartPatchRequestApiCallFlow() {
StartPatchRequestApiCallFlowWithSerializedRequest(kSerializedRequestProto);
}
void StartPatchRequestApiCallFlowWithSerializedRequest(
const std::string& serialized_request) {
flow_.StartPatchRequest(
GURL(kRequestUrl), serialized_request, shared_factory_, kAccessToken,
base::BindOnce(&NearbyShareApiCallFlowImplTest::OnResult,
base::Unretained(this)),
base::BindOnce(&NearbyShareApiCallFlowImplTest::OnError,
base::Unretained(this)));
// A pending fetch for the API request should be created.
CheckNearbySharingClientHttpPatchRequest(serialized_request);
}
void StartGetRequestApiCallFlow() {
StartGetRequestApiCallFlowWithRequestAsQueryParameters(
GetTestRequestProtoAsQueryParameters());
}
void StartGetRequestApiCallFlowWithRequestAsQueryParameters(
const NearbyShareApiCallFlow::QueryParameters&
request_as_query_parameters) {
flow_.StartGetRequest(
GURL(kRequestUrl), request_as_query_parameters, shared_factory_,
kAccessToken,
base::BindOnce(&NearbyShareApiCallFlowImplTest::OnResult,
base::Unretained(this)),
base::BindOnce(&NearbyShareApiCallFlowImplTest::OnError,
base::Unretained(this)));
// A pending fetch for the API request should be created.
CheckNearbySharingClientHttpGetRequest(request_as_query_parameters);
}
void OnResult(const std::string& result) {
EXPECT_FALSE(result_ || network_error_);
result_ = std::make_unique<std::string>(result);
}
void OnError(NearbyShareHttpError network_error) {
EXPECT_FALSE(result_ || network_error_);
network_error_ = std::make_unique<NearbyShareHttpError>(network_error);
}
void CheckPlatformTypeHeader(const net::HttpRequestHeaders& headers) {
std::string platform_type;
EXPECT_TRUE(headers.GetHeader("X-Sharing-Platform-Type", &platform_type));
EXPECT_EQ("OSType.CHROME_OS", platform_type);
}
void CheckNearbySharingClientHttpPostRequest(
const std::string& serialized_request) {
const std::vector<network::TestURLLoaderFactory::PendingRequest>& pending =
*test_url_loader_factory_.pending_requests();
ASSERT_EQ(1u, pending.size());
const network::ResourceRequest& request = pending[0].request;
CheckPlatformTypeHeader(request.headers);
EXPECT_EQ(UrlWithQueryParameters(
kRequestUrl, absl::nullopt /* request_as_query_parameters */),
request.url);
EXPECT_EQ(kPost, request.method);
EXPECT_EQ(serialized_request, network::GetUploadData(request));
std::string content_type;
EXPECT_TRUE(request.headers.GetHeader(net::HttpRequestHeaders::kContentType,
&content_type));
EXPECT_EQ("application/x-protobuf", content_type);
}
void CheckNearbySharingClientHttpPatchRequest(
const std::string& serialized_request) {
const std::vector<network::TestURLLoaderFactory::PendingRequest>& pending =
*test_url_loader_factory_.pending_requests();
ASSERT_EQ(1u, pending.size());
const network::ResourceRequest& request = pending[0].request;
CheckPlatformTypeHeader(request.headers);
EXPECT_EQ(UrlWithQueryParameters(
kRequestUrl, absl::nullopt /* request_as_query_parameters */),
request.url);
EXPECT_EQ(kPatch, request.method);
EXPECT_EQ(serialized_request, network::GetUploadData(request));
std::string content_type;
EXPECT_TRUE(request.headers.GetHeader(net::HttpRequestHeaders::kContentType,
&content_type));
EXPECT_EQ("application/x-protobuf", content_type);
}
void CheckNearbySharingClientHttpGetRequest(
const NearbyShareApiCallFlow::QueryParameters&
request_as_query_parameters) {
const std::vector<network::TestURLLoaderFactory::PendingRequest>& pending =
*test_url_loader_factory_.pending_requests();
ASSERT_EQ(1u, pending.size());
const network::ResourceRequest& request = pending[0].request;
CheckPlatformTypeHeader(request.headers);
EXPECT_EQ(UrlWithQueryParameters(kRequestUrl, request_as_query_parameters),
request.url);
EXPECT_EQ(kGet, request.method);
// Expect no body.
EXPECT_TRUE(network::GetUploadData(request).empty());
EXPECT_FALSE(
request.headers.HasHeader(net::HttpRequestHeaders::kContentType));
}
// Responds to the current HTTP POST request. If the |error| is not net::OK,
// then the |response_code| and |response_string| are null.
void CompleteCurrentPostRequest(
net::Error error,
absl::optional<int> response_code = absl::nullopt,
const absl::optional<std::string>& response_string = absl::nullopt) {
network::URLLoaderCompletionStatus completion_status(error);
auto response_head = network::mojom::URLResponseHead::New();
std::string content;
if (error == net::OK) {
response_head = network::CreateURLResponseHead(
static_cast<net::HttpStatusCode>(*response_code));
content = *response_string;
}
// Use kUrlMatchPrefix flag to match URL without query parameters.
EXPECT_TRUE(test_url_loader_factory_.SimulateResponseForPendingRequest(
GURL(kRequestUrl), completion_status, std::move(response_head), content,
network::TestURLLoaderFactory::ResponseMatchFlags::kUrlMatchPrefix));
task_environment_.RunUntilIdle();
EXPECT_TRUE(result_ || network_error_);
}
// Responds to the current HTTP PATCH request. If the |error| is not net::OK,
// then the |response_code| and |response_string| are null.
void CompleteCurrentPatchRequest(
net::Error error,
absl::optional<int> response_code = absl::nullopt,
const absl::optional<std::string>& response_string = absl::nullopt) {
network::URLLoaderCompletionStatus completion_status(error);
auto response_head = network::mojom::URLResponseHead::New();
std::string content;
if (error == net::OK) {
response_head = network::CreateURLResponseHead(
static_cast<net::HttpStatusCode>(*response_code));
content = *response_string;
}
// Use kUrlMatchPrefix flag to match URL without query parameters.
EXPECT_TRUE(test_url_loader_factory_.SimulateResponseForPendingRequest(
GURL(kRequestUrl), completion_status, std::move(response_head), content,
network::TestURLLoaderFactory::ResponseMatchFlags::kUrlMatchPrefix));
task_environment_.RunUntilIdle();
EXPECT_TRUE(result_ || network_error_);
}
// Responds to the current HTTP GET request. If the |error| is not net::OK,
// then the |response_code| and |response_string| are null.
void CompleteCurrentGetRequest(
net::Error error,
absl::optional<int> response_code = absl::nullopt,
const absl::optional<std::string>& response_string = absl::nullopt) {
network::URLLoaderCompletionStatus completion_status(error);
auto response_head = network::mojom::URLResponseHead::New();
std::string content;
if (error == net::OK) {
response_head = network::CreateURLResponseHead(
static_cast<net::HttpStatusCode>(*response_code));
content = *response_string;
}
// Use kUrlMatchPrefix flag to match URL without query parameters.
EXPECT_TRUE(test_url_loader_factory_.SimulateResponseForPendingRequest(
GURL(kRequestUrl), completion_status, std::move(response_head), content,
network::TestURLLoaderFactory::ResponseMatchFlags::kUrlMatchPrefix));
task_environment_.RunUntilIdle();
EXPECT_TRUE(result_ || network_error_);
}
std::unique_ptr<std::string> result_;
std::unique_ptr<NearbyShareHttpError> network_error_;
private:
base::test::TaskEnvironment task_environment_;
network::TestURLLoaderFactory test_url_loader_factory_;
scoped_refptr<network::SharedURLLoaderFactory> shared_factory_;
NearbyShareApiCallFlowImpl flow_;
};
TEST_F(NearbyShareApiCallFlowImplTest, PostRequestSuccess) {
StartPostRequestApiCallFlow();
CompleteCurrentPostRequest(net::OK, net::HTTP_OK, kSerializedResponseProto);
EXPECT_EQ(kSerializedResponseProto, *result_);
EXPECT_FALSE(network_error_);
}
TEST_F(NearbyShareApiCallFlowImplTest, PatchRequestSuccess) {
StartPatchRequestApiCallFlow();
CompleteCurrentPatchRequest(net::OK, net::HTTP_OK, kSerializedResponseProto);
EXPECT_EQ(kSerializedResponseProto, *result_);
EXPECT_FALSE(network_error_);
}
TEST_F(NearbyShareApiCallFlowImplTest, GetRequestSuccess) {
StartGetRequestApiCallFlow();
CompleteCurrentGetRequest(net::OK, net::HTTP_OK, kSerializedResponseProto);
EXPECT_EQ(kSerializedResponseProto, *result_);
EXPECT_FALSE(network_error_);
}
TEST_F(NearbyShareApiCallFlowImplTest, PostRequestFailure) {
StartPostRequestApiCallFlow();
CompleteCurrentPostRequest(net::ERR_FAILED);
EXPECT_FALSE(result_);
EXPECT_EQ(NearbyShareHttpError::kOffline, *network_error_);
}
TEST_F(NearbyShareApiCallFlowImplTest, PatchRequestFailure) {
StartPatchRequestApiCallFlow();
CompleteCurrentPatchRequest(net::ERR_FAILED);
EXPECT_FALSE(result_);
EXPECT_EQ(NearbyShareHttpError::kOffline, *network_error_);
}
TEST_F(NearbyShareApiCallFlowImplTest, GetRequestFailure) {
StartGetRequestApiCallFlow();
CompleteCurrentPostRequest(net::ERR_FAILED);
EXPECT_FALSE(result_);
EXPECT_EQ(NearbyShareHttpError::kOffline, *network_error_);
}
TEST_F(NearbyShareApiCallFlowImplTest, RequestStatus500) {
StartPostRequestApiCallFlow();
CompleteCurrentPostRequest(net::OK, net::HTTP_INTERNAL_SERVER_ERROR,
"Nearby Sharing Meltdown.");
EXPECT_FALSE(result_);
EXPECT_EQ(NearbyShareHttpError::kInternalServerError, *network_error_);
}
TEST_F(NearbyShareApiCallFlowImplTest, PatchRequestStatus500) {
StartPatchRequestApiCallFlow();
CompleteCurrentPatchRequest(net::OK, net::HTTP_INTERNAL_SERVER_ERROR,
"Nearby Sharing Meltdown.");
EXPECT_FALSE(result_);
EXPECT_EQ(NearbyShareHttpError::kInternalServerError, *network_error_);
}
TEST_F(NearbyShareApiCallFlowImplTest, GetRequestStatus500) {
StartGetRequestApiCallFlow();
CompleteCurrentPostRequest(net::OK, net::HTTP_INTERNAL_SERVER_ERROR,
"Nearby Sharing Meltdown.");
EXPECT_FALSE(result_);
EXPECT_EQ(NearbyShareHttpError::kInternalServerError, *network_error_);
}
// The empty string is a valid protocol buffer message serialization.
TEST_F(NearbyShareApiCallFlowImplTest, PostRequestWithNoBody) {
StartPostRequestApiCallFlowWithSerializedRequest(std::string());
CompleteCurrentPostRequest(net::OK, net::HTTP_OK, kSerializedResponseProto);
EXPECT_EQ(kSerializedResponseProto, *result_);
EXPECT_FALSE(network_error_);
}
// The empty string is a valid protocol buffer message serialization.
TEST_F(NearbyShareApiCallFlowImplTest, PatchRequestWithNoBody) {
StartPatchRequestApiCallFlowWithSerializedRequest(std::string());
CompleteCurrentPatchRequest(net::OK, net::HTTP_OK, kSerializedResponseProto);
EXPECT_EQ(kSerializedResponseProto, *result_);
EXPECT_FALSE(network_error_);
}
TEST_F(NearbyShareApiCallFlowImplTest, GetRequestWithNoQueryParameters) {
StartGetRequestApiCallFlowWithRequestAsQueryParameters(
{} /* request_as_query_parameters */);
CompleteCurrentPostRequest(net::OK, net::HTTP_OK, kSerializedResponseProto);
EXPECT_EQ(kSerializedResponseProto, *result_);
EXPECT_FALSE(network_error_);
}
// The empty string is a valid protocol buffer message serialization.
TEST_F(NearbyShareApiCallFlowImplTest, PostResponseWithNoBody) {
StartPostRequestApiCallFlow();
CompleteCurrentPostRequest(net::OK, net::HTTP_OK, std::string());
EXPECT_EQ(std::string(), *result_);
EXPECT_FALSE(network_error_);
}
// The empty string is a valid protocol buffer message serialization.
TEST_F(NearbyShareApiCallFlowImplTest, PatchResponseWithNoBody) {
StartPatchRequestApiCallFlow();
CompleteCurrentPatchRequest(net::OK, net::HTTP_OK, std::string());
EXPECT_EQ(std::string(), *result_);
EXPECT_FALSE(network_error_);
}
// The empty string is a valid protocol buffer message serialization.
TEST_F(NearbyShareApiCallFlowImplTest, GetResponseWithNoBody) {
StartGetRequestApiCallFlow();
CompleteCurrentPostRequest(net::OK, net::HTTP_OK, std::string());
EXPECT_EQ(std::string(), *result_);
EXPECT_FALSE(network_error_);
}
| 39.356968 | 81 | 0.748462 | [
"vector"
] |
ed4c687fd085636228689afddfe721e340894f68 | 10,453 | cpp | C++ | appgrm.cpp | njau-sri/grm | 2302defcb2126770797aea55b93a45676c3dc6b8 | [
"MIT"
] | null | null | null | appgrm.cpp | njau-sri/grm | 2302defcb2126770797aea55b93a45676c3dc6b8 | [
"MIT"
] | null | null | null | appgrm.cpp | njau-sri/grm | 2302defcb2126770797aea55b93a45676c3dc6b8 | [
"MIT"
] | null | null | null | #include <cmath>
#include <memory>
#include <limits>
#include <fstream>
#include <iostream>
#include <algorithm>
#include <utility>
#include "appgrm.h"
#include "cmdline.h"
#include "vcfio.h"
namespace {
template<typename T>
int count_shared_allele(T a, T b, T c, T d)
{
if (a == b)
return static_cast<int>(a == c) + (a == d);
if (c == d)
return static_cast<int>(c == a) + (c == b);
return static_cast<int>(a == c) + (a == d) + (b == c) + (b == d);
}
std::pair<size_t,size_t> match_kernel_haplo(size_t n, const allele_t *x, const allele_t *y)
{
size_t a = 0, b = 0;
for (size_t i = 0; i < n; ++i) {
if (x[i] && y[i]) {
++a;
if (x[i] == y[i])
++b;
}
}
return std::make_pair(a, b);
}
std::pair<size_t,size_t> match_kernel_diplo(size_t n, const allele_t *x, const allele_t *y)
{
size_t a = 0, b = 0;
for (size_t i = 0; i < n; ++i) {
size_t j1 = i*2, j2 = i*2+1;
if (x[j1] && x[j2] && y[j1] && y[j2]) {
a += 2;
b += count_shared_allele(x[j1], x[j2], y[j1], y[j2]);
}
}
return std::make_pair(a, b);
}
void recode_012_haploid(const vector<allele_t> &g, vector<double> &x)
{
size_t n = g.size();
static const allele_t ref = 1;
x.assign(n, std::numeric_limits<double>::quiet_NaN());
for (size_t i = 0; i < n; ++i) {
if ( g[i] )
x[i] = g[i] == ref ? 2.0 : 0.0;
}
}
void recode_012_diploid(const vector<allele_t> &g, vector<double> &x)
{
size_t n = g.size() / 2;
static const allele_t ref = 1;
x.assign(n, std::numeric_limits<double>::quiet_NaN());
for (size_t i = 0; i < n; ++i) {
auto a = g[i*2], b = g[i*2+1];
if (a && b)
x[i] = static_cast<int>(a == ref) + static_cast<int>(b == ref);
}
}
bool is_biallelic(const Genotype >)
{
for (auto &v : gt.allele)
if (v.size() > 2)
return false;
return true;
}
} // namespace
int AppGRM::run(int argc, char *argv[])
{
auto cmd = std::make_shared<CmdLine>("grm [options]");
cmd->add("--vcf", "VCF file", "");
cmd->add("--out", "output file prefix", "appgrm.out");
cmd->add("--method", "IBS/EIGENSTRAT/VanRaden1/VanRaden2", "IBS");
if (argc < 2) {
cmd->help();
return 1;
}
cmd->parse(argc, argv);
m_par.vcf = cmd->get("--vcf");
m_par.out = cmd->get("--out");
m_par.method = cmd->get("--method");
cmd.reset();
std::transform(m_par.method.begin(), m_par.method.end(), m_par.method.begin(), ::toupper);
int info = perform();
return info;
}
int AppGRM::perform()
{
load_genotype();
if ( m_gt.loc.empty() || m_gt.ind.size() < 2 ) {
std::cerr << "ERROR: not enough observations\n";
return 1;
}
if (m_par.method != "IBS") {
if ( ! is_biallelic(m_gt) )
std::cerr << "WARNING: method " << m_par.method
<< " is not compatible with multi-allelic marker\n";
}
if (m_par.method == "IBS") {
calc_grm_IBS(m_gt, m_grm.dat);
}
else if (m_par.method == "EIGENSTRAT") {
calc_grm_EIGENSTRAT(m_gt, m_grm.dat);
}
else if (m_par.method == "VANRADEN1") {
calc_grm_VanRaden1(m_gt, m_grm.dat);
}
else if (m_par.method == "VANRADEN2") {
calc_grm_VanRaden2(m_gt, m_grm.dat);
}
else {
std::cerr << "ERROR: invalid method: " << m_par.method << "\n";
return 1;
}
m_grm.ind = m_gt.ind;
std::ofstream ofs(m_par.out);
if ( ! ofs ) {
std::cerr << "ERROR: can't open file for writing: " << m_par.out << "\n";
return 1;
}
auto n = m_grm.ind.size();
for (size_t i = 0; i < n; ++i) {
ofs << m_grm.ind[i];
for (size_t j = 0; j < n; ++j)
ofs << "\t" << m_grm.dat[i][j];
ofs << "\n";
}
return 0;
}
void AppGRM::load_genotype()
{
if ( m_par.vcf.empty() )
return;
std::cerr << "INFO: reading genotype file...\n";
int info = read_vcf(m_par.vcf, m_gt);
if (info != 0) {
m_gt.loc.clear();
m_gt.ind.clear();
m_gt.dat.clear();
}
std::cerr << "INFO: " << m_gt.ind.size() << " individuals and "
<< m_gt.loc.size() << " loci were observed\n";
}
void AppGRM::calc_grm_IBS(const Genotype >, vector< vector<double> > &x)
{
static const size_t nb = 1000;
size_t m = 0;
size_t n = gt.ind.size();
vector< vector<size_t> > z(n, vector<size_t>(n, 0));
x.assign(n, vector<double>(n, 0.0));
if (gt.ploidy == 1) {
vector< vector<allele_t> > dat(n, vector<allele_t>(nb));
for (auto &v : gt.dat) {
if (m < nb) {
for (size_t i = 0; i < n; ++i)
dat[i][m] = v[i];
++m;
continue;
}
#pragma omp parallel for collapse(2) schedule(dynamic)
for (size_t i = 0; i < n; ++i) {
for (size_t j = 0; j < n; ++j) {
if (j <= i)
continue;
auto p = match_kernel_haplo(m, dat[i].data(), dat[j].data());
z[i][j] += p.first;
z[j][i] += p.second;
}
}
for (size_t i = 0; i < n; ++i)
dat[i][0] = v[i];
m = 1;
}
if (m > 0) {
for (size_t i = 0; i < n; ++i) {
for (size_t j = i + 1; j < n; ++j) {
auto p = match_kernel_haplo(m, dat[i].data(), dat[j].data());
z[i][j] += p.first;
z[j][i] += p.second;
}
}
}
}
else {
vector< vector<allele_t> > dat(n, vector<allele_t>(nb*2));
for (auto &v : gt.dat) {
if (m < nb) {
for (size_t i = 0; i < n; ++i) {
dat[i][m*2] = v[i*2];
dat[i][m*2+1] = v[i*2+1];
}
++m;
continue;
}
#pragma omp parallel for collapse(2) schedule(dynamic)
for (size_t i = 0; i < n; ++i) {
for (size_t j = 0; j < n; ++j) {
if (j <= i)
continue;
auto p = match_kernel_diplo(m, dat[i].data(), dat[j].data());
z[i][j] += p.first;
z[j][i] += p.second;
}
}
for (size_t i = 0; i < n; ++i) {
dat[i][0] = v[i*2];
dat[i][1] = v[i*2+1];
}
m = 1;
}
if (m > 0) {
for (size_t i = 0; i < n; ++i) {
for (size_t j = i+1; j < n; ++j) {
auto p = match_kernel_diplo(m, dat[i].data(), dat[j].data());
z[i][j] += p.first;
z[j][i] += p.second;
}
}
}
}
for (size_t i = 0; i < n; ++i) {
x[i][i] = 1.0;
for (size_t j = i+1; j < n; ++j) {
if (z[i][j] != 0) {
auto a = static_cast<double>(z[j][i]) / z[i][j];
x[i][j] = x[j][i] = a;
}
}
}
}
// Price A.L. et al., Nat Genet, 2006, 38(8): 904-9
void AppGRM::calc_grm_EIGENSTRAT(const Genotype >, vector< vector<double> > &x)
{
size_t n = gt.ind.size();
std::vector<double> z;
x.assign(n, vector<double>(n, 0.0));
for (auto &v : gt.dat) {
if (gt.ploidy == 1)
recode_012_haploid(v, z);
else
recode_012_diploid(v, z);
size_t nz = 0;
double sz = 0.0;
for (auto e : z) {
if (e == e) {
++nz;
sz += e;
}
}
auto p = (sz + 1) / (2 * nz + 2);
auto mu = sz / nz;
auto sd = std::sqrt( p * (1 - p) );
for (auto &e : z)
e = e != e ? 0.0 : (e - mu) / sd;
for (size_t i = 0; i < n; ++i) {
for (size_t j = i; j < n; ++j)
x[i][j] += z[i] * z[j];
}
}
double d = 0.0;
for (size_t i = 0; i < n; ++i)
d += x[i][i];
d /= (n - 1);
for (size_t i = 0; i < n; ++i) {
for (size_t j = i; j < n; ++j)
x[i][j] = x[j][i] = x[i][j] / d;
}
}
// VanRaden P.M., J Dairy Sci, 2008, 91(11): 4414-23
void AppGRM::calc_grm_VanRaden1(const Genotype >, vector< vector<double> > &x)
{
size_t n = gt.ind.size();
std::vector<double> z;
x.assign(n, vector<double>(n, 0.0));
double scal = 0.0;
for (auto &v : gt.dat) {
if (gt.ploidy == 1)
recode_012_haploid(v, z);
else
recode_012_diploid(v, z);
size_t nz = 0;
double sz = 0.0;
for (auto e : z) {
if (e == e) {
++nz;
sz += e;
}
}
auto p = 0.5 * sz / nz;
auto mu = 2 * p;
scal += 2 * p * (1 - p);
for (auto &e : z)
e = e != e ? 0.0 : e - mu;
for (size_t i = 0; i < n; ++i) {
for (size_t j = i; j < n; ++j)
x[i][j] += z[i] * z[j];
}
}
for (size_t i = 0; i < n; ++i) {
for (size_t j = i; j < n; ++j)
x[i][j] = x[j][i] = x[i][j] / scal;
}
}
// VanRaden P.M., J Dairy Sci, 2008, 91(11): 4414-23
void AppGRM::calc_grm_VanRaden2(const Genotype >, vector< vector<double> > &x)
{
size_t n = gt.ind.size();
std::vector<double> z;
x.assign(n, vector<double>(n, 0.0));
for (auto &v : gt.dat) {
if (gt.ploidy == 1)
recode_012_haploid(v, z);
else
recode_012_diploid(v, z);
size_t nz = 0;
double sz = 0.0;
for (auto e : z) {
if (e == e) {
++nz;
sz += e;
}
}
auto p = 0.5 * sz / nz;
auto mu = 2 * p;
auto sd = std::sqrt( 2 * p * (1 - p) );
for (auto &e : z)
e = e != e ? 0.0 : (e - mu) / sd;
for (size_t i = 0; i < n; ++i) {
for (size_t j = i; j < n; ++j)
x[i][j] += z[i] * z[j];
}
}
size_t m = gt.loc.size();
for (size_t i = 0; i < n; ++i) {
for (size_t j = i; j < n; ++j)
x[i][j] = x[j][i] = x[i][j] / m;
}
}
| 24.828979 | 94 | 0.419879 | [
"vector",
"transform"
] |
ed508016b057ff6586eb779ec8ed73ad272744f7 | 490 | cpp | C++ | RandomQuestions/008.cpp | harveyc95/ProgrammingProblems | d81dc58de0347fa155f5e25f27d3d426ce13cdc6 | [
"MIT"
] | null | null | null | RandomQuestions/008.cpp | harveyc95/ProgrammingProblems | d81dc58de0347fa155f5e25f27d3d426ce13cdc6 | [
"MIT"
] | null | null | null | RandomQuestions/008.cpp | harveyc95/ProgrammingProblems | d81dc58de0347fa155f5e25f27d3d426ce13cdc6 | [
"MIT"
] | null | null | null | // 8. You are given an array A. A[0:k] = 0 and A[k+1:n] = 1. Find k.
#include <vector>
#include <iostream>
using namespace std;
int findK(std::vector<int> &a) {
int l = 0, r = a.size() - 1;
int mid = (l+r)/2;
while (l < r) {
cout<<l<<" : "<<r<<" : "<<mid<<endl;
if (a[mid] == 0) {
l = mid + 1;
} else {
r = mid;
}
mid = (l+r)/2;
}
cout<<mid<<endl;
return (a[mid]) ? mid : -1;
}
int main () {
std::vector<int> a = {0,0,0,0};
std::cout<<findK(a)<<"\n";
return 0;
} | 18.148148 | 68 | 0.489796 | [
"vector"
] |
ed51a20a28e66a99ed6020b4bec07b1c7a74ed83 | 1,296 | hpp | C++ | include/boost/simd/function/dist.hpp | yaeldarmon/boost.simd | 561316cc54bdc6353ca78f3b6d7e9120acd11144 | [
"BSL-1.0"
] | null | null | null | include/boost/simd/function/dist.hpp | yaeldarmon/boost.simd | 561316cc54bdc6353ca78f3b6d7e9120acd11144 | [
"BSL-1.0"
] | null | null | null | include/boost/simd/function/dist.hpp | yaeldarmon/boost.simd | 561316cc54bdc6353ca78f3b6d7e9120acd11144 | [
"BSL-1.0"
] | null | null | null | //==================================================================================================
/*!
@file
@copyright 2016 NumScale SAS
@copyright 2016 J.T. Lapreste
Distributed under the Boost Software License, Version 1.0.
(See accompanying file LICENSE.md or copy at http://boost.org/LICENSE_1_0.txt)
*/
//==================================================================================================
#ifndef BOOST_SIMD_FUNCTION_DIST_HPP_INCLUDED
#define BOOST_SIMD_FUNCTION_DIST_HPP_INCLUDED
#if defined(DOXYGEN_ONLY)
namespace boost { namespace simd
{
/*!
@ingroup group-arithmetic
Function object implementing dist capabilities
Computes the absolute value of the difference of its parameters.
@par semantic:
For any given value @c x, @c y of type @c T:
@code
T r = dist(x, y);
@endcode
is similar to:
@code
T r = abs(x-y);
@endcode
@par Note
The result can be negative for signed integers as @ref abs(@ref Valmin) is @ref Valmin.
To avoid the problem you can use the saturated version @ref dists.
@see dists, ulpdist
**/
const boost::dispatch::functor<tag::dist_> dist = {};
} }
#endif
#include <boost/simd/function/scalar/dist.hpp>
#include <boost/simd/function/simd/dist.hpp>
#endif
| 23.563636 | 100 | 0.587191 | [
"object"
] |
ed52cb1ac3141bad4f31b69555ae41f490a9cd94 | 6,068 | cpp | C++ | HP-Socket/Demo/TestEcho/Server/ServerDlg.cpp | jjzhang166/HP-Socket | b58c2d9bb088e19f30a2ce0171886bf801ef4c00 | [
"Apache-2.0"
] | 1 | 2016-07-05T04:07:20.000Z | 2016-07-05T04:07:20.000Z | HP-Socket/Demo/TestEcho/Server/ServerDlg.cpp | jjzhang166/HP-Socket | b58c2d9bb088e19f30a2ce0171886bf801ef4c00 | [
"Apache-2.0"
] | null | null | null | HP-Socket/Demo/TestEcho/Server/ServerDlg.cpp | jjzhang166/HP-Socket | b58c2d9bb088e19f30a2ce0171886bf801ef4c00 | [
"Apache-2.0"
] | null | null | null |
// ServerDlg.cpp : implementation file
//
#include "stdafx.h"
#include "Server.h"
#include "ServerDlg.h"
#include "afxdialogex.h"
// CServerDlg dialog
const LPCTSTR CServerDlg::ADDRESS = _T("0.0.0.0");
const USHORT CServerDlg::PORT = 5555;
CServerDlg::CServerDlg(CWnd* pParent /*=NULL*/)
: CDialogEx(CServerDlg::IDD, pParent), m_Server(this)
{
m_hIcon = AfxGetApp()->LoadIcon(IDR_MAINFRAME);
}
void CServerDlg::DoDataExchange(CDataExchange* pDX)
{
CDialogEx::DoDataExchange(pDX);
DDX_Control(pDX, IDC_INFO, m_Info);
DDX_Control(pDX, IDC_START, m_Start);
DDX_Control(pDX, IDC_STOP, m_Stop);
DDX_Control(pDX, IDC_ADDRESS, m_Address);
DDX_Control(pDX, IDC_CONN_ID, m_ConnID);
DDX_Control(pDX, IDC_DISCONNECT, m_DisConn);
}
BEGIN_MESSAGE_MAP(CServerDlg, CDialogEx)
ON_WM_PAINT()
ON_WM_QUERYDRAGICON()
ON_BN_CLICKED(IDC_START, &CServerDlg::OnBnClickedStart)
ON_BN_CLICKED(IDC_STOP, &CServerDlg::OnBnClickedStop)
ON_MESSAGE(USER_INFO_MSG, OnUserInfoMsg)
ON_BN_CLICKED(IDC_DISCONNECT, &CServerDlg::OnBnClickedDisconnect)
ON_EN_CHANGE(IDC_CONN_ID, &CServerDlg::OnEnChangeConnId)
ON_WM_VKEYTOITEM()
END_MESSAGE_MAP()
// CServerDlg message handlers
BOOL CServerDlg::OnInitDialog()
{
CDialogEx::OnInitDialog();
// Set the icon for this dialog. The framework does this automatically
// when the application's main window is not a dialog
SetIcon(m_hIcon, TRUE); // Set big icon
SetIcon(m_hIcon, FALSE); // Set small icon
// TODO: Add extra initialization here
CString strTitle;
CString strOriginTitle;
GetWindowText(strOriginTitle);
strTitle.Format(_T("%s - (%s:%d)"), strOriginTitle, ADDRESS, PORT);
SetWindowText(strTitle);
::SetMainWnd(this);
::SetInfoList(&m_Info);
SetAppState(ST_STOPPED);
return TRUE; // return TRUE unless you set the focus to a control
}
// If you add a minimize button to your dialog, you will need the code below
// to draw the icon. For MFC applications using the document/view model,
// this is automatically done for you by the framework.
void CServerDlg::OnPaint()
{
if (IsIconic())
{
CPaintDC dc(this); // device context for painting
SendMessage(WM_ICONERASEBKGND, reinterpret_cast<WPARAM>(dc.GetSafeHdc()), 0);
// Center icon in client rectangle
int cxIcon = GetSystemMetrics(SM_CXICON);
int cyIcon = GetSystemMetrics(SM_CYICON);
CRect rect;
GetClientRect(&rect);
int x = (rect.Width() - cxIcon + 1) / 2;
int y = (rect.Height() - cyIcon + 1) / 2;
// Draw the icon
dc.DrawIcon(x, y, m_hIcon);
}
else
{
CDialogEx::OnPaint();
}
}
// The system calls this function to obtain the cursor to display while the user drags
// the minimized window.
HCURSOR CServerDlg::OnQueryDragIcon()
{
return static_cast<HCURSOR>(m_hIcon);
}
BOOL CServerDlg::PreTranslateMessage(MSG* pMsg)
{
if (
pMsg->message == WM_KEYDOWN
&&( pMsg->wParam == VK_ESCAPE
|| pMsg->wParam == VK_CANCEL
|| pMsg->wParam == VK_RETURN
))
return TRUE;
return CDialog::PreTranslateMessage(pMsg);
}
void CServerDlg::SetAppState(EnAppState state)
{
m_enState = state;
if(this->GetSafeHwnd() == nullptr)
return;
m_Start.EnableWindow(m_enState == ST_STOPPED);
m_Stop.EnableWindow(m_enState == ST_STARTED);
m_Address.EnableWindow(m_enState == ST_STOPPED);
m_DisConn.EnableWindow(m_enState == ST_STARTED && m_ConnID.GetWindowTextLength() > 0);
}
void CServerDlg::OnBnClickedStart()
{
m_Address.GetWindowText(m_strAddress);
m_strAddress.Trim();
SetAppState(ST_STARTING);
if(m_Server.Start(ADDRESS, PORT))
{
::LogServerStart(ADDRESS, PORT);
SetAppState(ST_STARTED);
}
else
{
::LogServerStartFail(m_Server.GetLastError(), m_Server.GetLastErrorDesc());
SetAppState(ST_STOPPED);
}
}
void CServerDlg::OnBnClickedStop()
{
SetAppState(ST_STOPPING);
if(m_Server.Stop())
{
::LogServerStop();
SetAppState(ST_STOPPED);
}
else
{
ASSERT(FALSE);
}
}
void CServerDlg::OnBnClickedDisconnect()
{
CString strConnID;
m_ConnID.GetWindowText(strConnID);
CONNID dwConnID = (CONNID)_ttoi(strConnID);
if(m_Server.Disconnect(dwConnID))
::LogDisconnect(dwConnID);
else
::LogDisconnectFail(dwConnID);
}
void CServerDlg::OnEnChangeConnId()
{
m_DisConn.EnableWindow(m_enState == ST_STARTED && m_ConnID.GetWindowTextLength() > 0);
}
int CServerDlg::OnVKeyToItem(UINT nKey, CListBox* pListBox, UINT nIndex)
{
if(nKey == 'C')
pListBox->ResetContent();
return __super::OnVKeyToItem(nKey, pListBox, nIndex);
}
LRESULT CServerDlg::OnUserInfoMsg(WPARAM wp, LPARAM lp)
{
info_msg* msg = (info_msg*)wp;
::LogInfoMsg(msg);
return 0;
}
EnHandleResult CServerDlg::OnPrepareListen(SOCKET soListen)
{
TCHAR szAddress[40];
int iAddressLen = sizeof(szAddress) / sizeof(TCHAR);
USHORT usPort;
m_Server.GetListenAddress(szAddress, iAddressLen, usPort);
::PostOnPrepareListen(szAddress, usPort);
return HR_OK;
}
EnHandleResult CServerDlg::OnAccept(CONNID dwConnID, SOCKET soClient)
{
BOOL bPass = TRUE;
TCHAR szAddress[40];
int iAddressLen = sizeof(szAddress) / sizeof(TCHAR);
USHORT usPort;
m_Server.GetRemoteAddress(dwConnID, szAddress, iAddressLen, usPort);
if(!m_strAddress.IsEmpty())
{
if(m_strAddress.CompareNoCase(szAddress) == 0)
bPass = FALSE;
}
::PostOnAccept(dwConnID, szAddress, usPort, bPass);
return bPass ? HR_OK : HR_ERROR;
}
EnHandleResult CServerDlg::OnSend(CONNID dwConnID, const BYTE* pData, int iLength)
{
//static int t = 0;
//if(++t % 3 == 0) return HR_ERROR;
::PostOnSend(dwConnID, pData, iLength);
return HR_OK;
}
EnHandleResult CServerDlg::OnReceive(CONNID dwConnID, const BYTE* pData, int iLength)
{
//static int t = 0;
//if(++t % 3 == 0) return HR_ERROR;
::PostOnReceive(dwConnID, pData, iLength);
if(m_Server.Send(dwConnID, pData, iLength))
return HR_OK;
else
return HR_ERROR;
}
EnHandleResult CServerDlg::OnClose(CONNID dwConnID, EnSocketOperation enOperation, int iErrorCode)
{
iErrorCode == SE_OK ? ::PostOnClose(dwConnID) :
::PostOnError(dwConnID, enOperation, iErrorCode);
return HR_OK;
}
EnHandleResult CServerDlg::OnShutdown()
{
::PostOnShutdown();
return HR_OK;
}
| 22.726592 | 98 | 0.733355 | [
"model"
] |
ed54bcdbf86b9c7c956f4b75d4c3017840ca80a8 | 17,207 | cpp | C++ | dev/Code/CryEngine/CryAnimation/cvars.cpp | crazyskateface/lumberyard | 164512f8d415d6bdf37e195af319ffe5f96a8f0b | [
"AML"
] | 5 | 2018-08-17T21:05:55.000Z | 2021-04-17T10:48:26.000Z | dev/Code/CryEngine/CryAnimation/cvars.cpp | JulianoCristian/Lumberyard-3 | dc523dd780f3cd1874251181b7cf6848b8db9959 | [
"AML"
] | null | null | null | dev/Code/CryEngine/CryAnimation/cvars.cpp | JulianoCristian/Lumberyard-3 | dc523dd780f3cd1874251181b7cf6848b8db9959 | [
"AML"
] | 5 | 2017-12-05T16:36:00.000Z | 2021-04-27T06:33:54.000Z | /*
* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or
* its licensors.
*
* For complete copyright and license terms please see the LICENSE at the root of this
* distribution (the "License"). All use of this software is governed by the License,
* or, if provided, by the license below or the license accompanying this file. Do not
* remove or modify any license notices. This file is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
*
*/
// Original file Copyright Crytek GMBH or its affiliates, used under license.
#include "stdafx.h"
//need global var as the singleton approach is too expensive
Console g_Consoleself;
namespace
{
int g_ConsoleInstanceCount;
}
Console::Console()
{
if (g_ConsoleInstanceCount++)
{
abort();
}
}
static void CADebugText(IConsoleCmdArgs* pArgs)
{
#ifndef CONSOLE_CONST_CVAR_MODE
if (pArgs->GetArgCount() == 1)
{
CryLogAlways("%d", Console::GetInst().ca_DebugText);
}
else if (pArgs->GetArgCount() >= 2)
{
if (strcmp(pArgs->GetArg(1), "0") == 0)
{
Console::GetInst().ca_DebugText = 0;
Console::GetInst().ca_DebugTextTarget = "";
Console::GetInst().ca_DebugTextLayer = 0xffffffff;
}
else if (atoi(pArgs->GetArg(1)) > 0)
{
Console::GetInst().ca_DebugText = 1;
Console::GetInst().ca_DebugTextTarget = "";
Console::GetInst().ca_DebugTextLayer = 0xffffffff;
}
else
{
Console::GetInst().ca_DebugText = 1;
Console::GetInst().ca_DebugTextTarget = pArgs->GetArg(1);
Console::GetInst().ca_DebugTextLayer = 0xffffffff;
}
if (pArgs->GetArgCount() > 2)
{
Console::GetInst().ca_DebugTextLayer = atoi(pArgs->GetArg(2));
}
}
#endif
}
void Console::Init()
{
#ifndef _RELEASE
REGISTER_CVAR(ca_DebugAnimUsageOnFileAccess, 0, 0, "shows what animation assets are used in the level, triggered by key fileAccess events");
REGISTER_CVAR(ca_AttachmentTextureMemoryBudget, 100, 0, "texture budget for e_debugdraw 20 - in megabytes");
#endif
ca_CharEditModel = "objects/characters/human_male/humanmale_default.cdf";
REGISTER_STRING("ca_CharEditModel", ca_CharEditModel, VF_NULL, "");
REGISTER_STRING("ca_FilterJoints", ca_FilterJoints, VF_NULL, "");
REGISTER_STRING("ca_DrawPose", NULL, VF_NULL, "");
assert(this);
DefineConstIntCVar(ca_DrawAllSimulatedSockets, 0, VF_CHEAT, "if set to 1, the own bounding box of the character is drawn");
DefineConstIntCVar(ca_DrawBBox, 0, VF_CHEAT, "if set to 1, the own bounding box of the character is drawn");
DefineConstIntCVar(ca_DrawSkeleton, 0, VF_CHEAT, "if set to 1, the skeleton is drawn");
DefineConstIntCVar(ca_DrawDecalsBBoxes, 0, VF_CHEAT, "if set to 1, the decals bboxes are drawn");
DefineConstIntCVar(ca_DrawPositionPost, 0, VF_CHEAT, "draws the world position of the character (after update)");
DefineConstIntCVar(ca_DrawEmptyAttachments, 0, VF_CHEAT, "draws a wireframe cube if there is no object linked to an attachment");
DefineConstIntCVar(ca_DrawWireframe, 0, VF_CHEAT, "draws a wireframe on top of the rendered character");
DefineConstIntCVar(ca_DrawAimPoses, 0, VF_CHEAT, "draws the wireframe of the aim poses");
DefineConstIntCVar(ca_DrawLookIK, 0, VF_CHEAT, "draws a visualization of look ik");
DefineConstIntCVar(ca_DrawTangents, 0, VF_CHEAT, "draws the tangents of the rendered character");
DefineConstIntCVar(ca_DrawBinormals, 0, VF_CHEAT, "draws the binormals of the rendered character");
DefineConstIntCVar(ca_DrawNormals, 0, VF_CHEAT, "draws the normals of the rendered character");
DefineConstIntCVar(ca_DrawAttachments, 1, VF_CHEAT, "if this is 0, will not draw the attachments objects");
DefineConstIntCVar(ca_DrawAttachmentOBB, 0, VF_CHEAT, "if this is 0, will not draw the attachments objects");
DefineConstIntCVar(ca_DrawAttachmentProjection, 0, VF_CHEAT, "if this is 0, will not draw the attachment projections");
DefineConstIntCVar(ca_DrawBaseMesh, 1, VF_CHEAT, "if this is 0, will not draw the characters");
DefineConstIntCVar(ca_DrawLocator, 0, 0, "if this is 1, we will draw the body and move-direction. If this is 2, we will also print out the move direction");
DefineConstIntCVar(ca_DrawCGA, 1, VF_CHEAT, "if this is 0, will not draw the CGA characters");
DefineConstIntCVar(ca_DrawCHR, 1, VF_CHEAT, "if this is 0, will not draw the CHR characters");
DefineConstIntCVar(ca_DrawCC, 1, VF_CHEAT, "if this is 0, will not draw the CC characters");
DefineConstIntCVar(ca_DebugSWSkinning, 0, VF_CHEAT | VF_DUMPTODISK, "if this is 1, then we will see a green wireframe on top of software skinned meshes");
DefineConstIntCVar(ca_DebugAnimMemTracking, 0, VF_CHEAT | VF_DUMPTODISK, "if this is 1, then its shows the anim-key allocations");
REGISTER_COMMAND("ca_DebugText", (ConsoleCommandFunc)CADebugText, VF_CHEAT | VF_DUMPTODISK, "if this is 1, it will print some debug text on the screen\nif you give a file path or part of it instead, only the info for that character will appear");
ca_DebugTextLayer = 0xffffffff;
DefineConstIntCVar(ca_DebugCommandBuffer, 0, VF_CHEAT | VF_DUMPTODISK, "if this is 1, it will print the amount of commands for the blend-buffer");
DefineConstIntCVar(ca_DebugAnimationStreaming, 0, VF_CHEAT | VF_DUMPTODISK, "if this is 1, then it shows what animations are streamed in");
DefineConstIntCVar(ca_LoadUncompressedChunks, 0, VF_CHEAT, "If this 1, then uncompressed chunks prefer compressed while loading");
DefineConstIntCVar(ca_UseMorph, 1, VF_CHEAT, "the morph skinning step is skipped (it's part of overall skinning during rendering)");
DefineConstIntCVar(ca_NoAnim, 0, VF_CHEAT, "the animation isn't updated (the characters remain in the same pose)");
DefineConstIntCVar(ca_UsePhysics, 1, VF_CHEAT, "the physics is not applied (effectively, no IK)");
DefineConstIntCVar(ca_DisableAuxPhysics, 0, 0, "disable simulation of character ropes and cloth");
DefineConstIntCVar(ca_UseLookIK, 1, VF_CHEAT, "If this is set to 1, then we are adding a look-at animation to the skeleton");
DefineConstIntCVar(ca_UseAimIK, 1, VF_CHEAT, "If this is set to 1, then we are adding a look-at animation to the skeleton");
DefineConstIntCVar(ca_UseRecoil, 1, VF_CHEAT, "If this is set to 1, then we enable procedural recoil");
DefineConstIntCVar(ca_SnapToVGrid, 0, VF_CHEAT, "if set to 1, we snap the control parameter to the closest VCell");
DefineConstIntCVar(ca_DebugSegmentation, 0, VF_CHEAT, "if set to 1, we can see the timing and the segment-counter of all assets in a BSpace");
DefineConstIntCVar(ca_DrawAimIKVEGrid, 0, VF_CHEAT, "if set to 1, we will the the grid with the virtual examples");
DefineConstIntCVar(ca_UseFacialAnimation, 1, VF_CHEAT,
"If this is set to 1, we can play facial animations");
DefineConstIntCVar(ca_LockFeetWithIK, 1, VF_CHEAT,
"If this is set to 1, then we lock the feet to prevent sliding when additive animations are used"
);
DefineConstIntCVar(ca_ForceUpdateSkeletons, 0, VF_CHEAT, "Always update all skeletons, even if not visible.");
DefineConstIntCVar(ca_ApplyJointVelocitiesMode, 2, VF_CHEAT, "Joint velocity preservation code mode: 0=Disabled, 1=Physics-driven, 2=Animation-driven");
DefineConstIntCVar(ca_UseDecals, 0, 0, "if set to 0, effectively disables creation of decals on characters\n2 - alternative method of calculating/building the decals");
DefineConstIntCVar(ca_DebugModelCache, 0, VF_CHEAT, "shows what models are currently loaded and how much memory they take");
DefineConstIntCVar(ca_ReloadAllCHRPARAMS, 0, VF_CHEAT, "reload all CHRPARAMS");
DefineConstIntCVar(ca_DebugAnimUpdates, 0, VF_CHEAT, "shows the amount of skeleton-updates");
DefineConstIntCVar(ca_DebugAnimUsage, 0, VF_CHEAT, "shows what animation assets are used in the level");
DefineConstIntCVar(ca_StoreAnimNamesOnLoad, 0, VF_CHEAT, "stores the names of animations during load to allow name lookup for debugging");
DefineConstIntCVar(ca_DumpUsedAnims, 0, VF_CHEAT, "writes animation asset statistics to the disk");
DefineConstIntCVar(ca_AnimWarningLevel, 3, VF_CHEAT | VF_DUMPTODISK,
"if you set this to 0, there won't be any\nfrequest warnings from the animation system");
DefineConstIntCVar(ca_KeepModels, 0, VF_CHEAT,
"If set to 1, will prevent models from unloading from memory\nupon destruction of the last referencing character");
// if this is not empty string, the animations of characters with the given model will be logged
DefineConstIntCVar(ca_DebugSkeletonEffects, 0, VF_CHEAT, "If true, dump log messages when skeleton effects are handled.");
DefineConstIntCVar(ca_lipsync_phoneme_offset, 20, VF_CHEAT, "Offset phoneme start time by this value in milliseconds");
DefineConstIntCVar(ca_lipsync_phoneme_crossfade, 70, VF_CHEAT, "Cross fade time between phonemes in milliseconds");
DefineConstIntCVar(ca_eyes_procedural, 1, 0, "Enables/Disables procedural eyes animation");
DefineConstIntCVar(ca_lipsync_debug, 0, VF_CHEAT, "Enables facial animation debug draw");
DefineConstIntCVar(ca_DebugFacial, 0, VF_CHEAT, "Debug facial playback info");
DefineConstIntCVar(ca_DebugFacialEyes, 0, VF_CHEAT, "Debug facial eyes info");
DefineConstIntCVar(ca_useADIKTargets, 1, VF_CHEAT, "Use Animation Driven Ik Targets.");
DefineConstIntCVar(ca_DebugADIKTargets, 0, VF_CHEAT, "If 1, then it will show if there are animation-driven IK-Targets for this model.");
DefineConstIntCVar(ca_SaveAABB, 0, 0, "if the AABB is invalid, replace it by the default AABB");
DefineConstIntCVar(ca_DebugCriticalErrors, 0, VF_CHEAT, "if 1, then we stop with a Fatal-Error if we detect a serious issue");
DefineConstIntCVar(ca_UseIMG_CAF, 1, VF_CHEAT, "if 1, then we use the IMG file. In development mode it is suppose to be off");
DefineConstIntCVar(ca_UseIMG_AIM, 1, VF_CHEAT, "if 1, then we use the IMG file. In development mode it is suppose to be off");
DefineConstIntCVar(ca_UnloadAnimationCAF, 1, VF_DUMPTODISK, "unloading streamed CAFs as soon as they are not used");
DefineConstIntCVar(ca_UnloadAnimationDBA, 1, VF_NULL, "if 1, then unload DBA if not used");
DefineConstIntCVar(ca_MinInPlaceCAFStreamSize, 128 * 1024, VF_CHEAT, "min size a caf should be for in-place streaming");
DefineConstIntCVar(ca_cloth_vars_reset, 2, 0, "1 - load the values from the next char, 1 - apply normally, 2+ - ignore");
DefineConstIntCVar(ca_SerializeSkeletonAnim, 0, VF_CHEAT, "Turn on CSkeletonAnim Serialization.");
DefineConstIntCVar(ca_AllowMultipleEffectsOfSameName, 1, VF_CHEAT, "Allow a skeleton animation to spawn more than one instance of an effect with the same name on the same instance.");
DefineConstIntCVar(ca_UseAssetDefinedLod, 0, VF_CHEAT, "Lowers render LODs for characters with respect to \"consoles_lod0\" UDP. Requires characters to be reloaded.");
DefineConstIntCVar(ca_Validate, 0, VF_CHEAT, "if set to 1, will run validation on animation data");
#if USE_FACIAL_ANIMATION_FRAMERATE_LIMITING
DefineConstIntCVar(ca_FacialAnimationFramerate, 20, VF_CHEAT, "Update facial system at a maximum framerate of n. This framerate falls off linearly to zero with the distance.");
#endif
// Command Buffer
DefineConstIntCVar(ca_UseJointMasking, 1, VF_DUMPTODISK, "Use Joint Masking to speed up motion decoding.");
// Multi-Threading
DefineConstIntCVar(ca_disable_thread, 1, VF_DUMPTODISK, "TEMP Disable Animation Thread.");
DefineConstIntCVar(ca_thread, 1, VF_DUMPTODISK, "If >0 enables Animation Multi-Threading.");
DefineConstIntCVar(ca_thread0Affinity, 5, VF_DUMPTODISK, "Affinity of first Animation Thread.");
DefineConstIntCVar(ca_thread1Affinity, 3, VF_DUMPTODISK, "Affinity of second Animation Thread.");
// DBA unloading timings
DefineConstIntCVar(ca_DBAUnloadUnregisterTime, 2, VF_CHEAT, "DBA Unload Timing: CAF Unregister Time.");
DefineConstIntCVar(ca_DBAUnloadRemoveTime, 4, VF_CHEAT, "DBA Unload Timing: DBA Remove Time.");
// Animation data caching behavior (PC specific)
DefineConstIntCVar(ca_PrecacheAnimationSets, 0, VF_NULL, "Enable Precaching of Animation Sets per Character.");
DefineConstIntCVar(ca_DisableAnimationUnloading, 0, VF_NULL, "Disable Animation Unloading.");
DefineConstIntCVar(ca_PreloadAllCAFs, 0, VF_NULL, "Preload all CAFs during level preloading.");
// vars in console .cfgs
REGISTER_CVAR(ca_DrawVEGInfo, 0.0f, VF_CHEAT, "if set to 1, the VEG debug info is drawn");
REGISTER_CVAR(ca_DecalSizeMultiplier, 1.0f, VF_CHEAT, "The multiplier for the decal sizes");
REGISTER_CVAR(ca_physicsProcessImpact, 1, VF_CHEAT | VF_DUMPTODISK, "Process physics impact pulses.");
REGISTER_CVAR(ca_MemoryUsageLog, 0, VF_CHEAT, "enables a memory usage log");
const int32 defaultDefragPoolSize = 64 * 1024 * 1024;
REGISTER_CVAR(ca_MemoryDefragPoolSize, defaultDefragPoolSize, 0, "Sets the upper limit on the defrag pool size");
REGISTER_CVAR(ca_MemoryDefragEnabled, 1, 0, "Enables defragmentation of anim data");
REGISTER_CVAR(ca_ParametricPoolSize, 64, 0, "Size of the parametric pool");
REGISTER_CVAR(ca_StreamCHR, 1, 0, "Set to enable CHR streaming");
REGISTER_CVAR(ca_StreamDBAInPlace, 1, 0, "Set to stream DBA files in place");
//vertex animation
REGISTER_CVAR(ca_vaEnable, 1, 0, "Enables Vertex Animation");
REGISTER_CVAR(ca_vaProfile, 0, 0, "Enable Vertex Animation profile");
REGISTER_CVAR(ca_vaBlendEnable, 1, 0, "Enables Vertex Animation blends");
REGISTER_CVAR(ca_vaBlendPostSkinning, 0, 0, "Perform Vertex Animation blends post skinning");
REGISTER_CVAR(ca_vaBlendCullingDebug, 0, 0, "Show Blend Shapes culling difference");
REGISTER_CVAR(ca_vaBlendCullingThreshold, 1.f, 0, "Blend Shapes culling threshold");
REGISTER_CVAR(ca_vaScaleFactor, 1.0f, 0, "Vertex Animation Weight Scale Factor");
REGISTER_CVAR(ca_vaUpdateTangents, 1, 0, "Update Tangents on SKIN attachments that have the vertex color blue channel set to 255 and 8 weights");
REGISTER_CVAR(ca_vaSkipVertexAnimationLOD, 0, 0, "Skip LOD 0 for characters using vertex animation");
//motion blur
REGISTER_CVAR(ca_MotionBlurMovementThreshold, 0.0f, 0, "\"advanced\" Set motion blur movement threshold for discarding skinned object");
REGISTER_CVAR(ca_DeathBlendTime, 0.3f, VF_CHEAT, "Specifies the blending time between low-detail dead body skeleton and current skeleton");
REGISTER_CVAR(ca_lipsync_vertex_drag, 1.2f, VF_CHEAT, "Vertex drag coefficient when blending morph targets");
REGISTER_CVAR(ca_lipsync_phoneme_strength, 1.0f, 0, "LipSync phoneme strength");
REGISTER_CVAR(ca_AttachmentCullingRation, 200.0f, 0, "ration between size of attachment and distance to camera");
REGISTER_CVAR(ca_AttachmentCullingRationMP, 300.0f, 0, "ration between size of attachment and distance to camera for MP");
//cloth
REGISTER_CVAR(ca_cloth_max_timestep, 0.0f, 0, "");
REGISTER_CVAR(ca_cloth_max_safe_step, 0.0f, 0, "if a segment stretches more than this (in *relative* units), its length is reinforced");
REGISTER_CVAR(ca_cloth_stiffness, 0.0f, 0, "stiffness for stretching");
REGISTER_CVAR(ca_cloth_thickness, 0.0f, 0, "thickness for collision checks");
REGISTER_CVAR(ca_cloth_friction, 0.0f, 0, "");
REGISTER_CVAR(ca_cloth_stiffness_norm, 0.0f, 0, "stiffness for shape preservation along normals (\"convexity preservation\")");
REGISTER_CVAR(ca_cloth_stiffness_tang, 0.0f, 0, "stiffness for shape preservation against tilting");
REGISTER_CVAR(ca_cloth_damping, 0.0f, 0, "");
REGISTER_CVAR(ca_cloth_air_resistance, 0.0f, 0, "\"advanced\" (more correct) version of damping");
REGISTER_CVAR(ca_FacialAnimationRadius, 30.f, VF_CHEAT, "Maximum distance at which facial animations are updated - handles zooming correctly");
DefineConstIntCVar(ca_DrawCloth, 1, VF_CHEAT, "bitfield: 2 shows particles, 4 shows proxies, 6 shows both");
DefineConstIntCVar(ca_ClothBlending, 1, VF_CHEAT, "if this is 0 blending with animation is disabled");
DefineConstIntCVar(ca_ClothBypassSimulation, 0, VF_CHEAT, "if this is 0 actual cloth simulation is disabled (wrap skinning still works)");
DefineConstIntCVar(ca_ClothMaxChars, 10, VF_CHEAT, "max characters with cloth on screen");
}
bool Console::DrawPose(const char mode)
{
static ICVar* pVar = gEnv->pSystem->GetIConsole()->GetCVar("ca_DrawPose");
const char* poseDraw = pVar ? pVar->GetString() : NULL;
if (!poseDraw)
{
return false;
}
for (; *poseDraw; ++poseDraw)
{
if (*poseDraw == mode)
{
return true;
}
}
return false;
}
| 67.478431 | 250 | 0.736096 | [
"render",
"object",
"shape",
"model"
] |
ed577ffe8d49e4a74d03820f41212c4688cfd54c | 267,851 | hpp | C++ | third_party/omr/compiler/z/codegen/S390Instruction.hpp | xiacijie/omr-wala-linkage | a1aff7aef9ed131a45555451abde4615a04412c1 | [
"Apache-2.0"
] | null | null | null | third_party/omr/compiler/z/codegen/S390Instruction.hpp | xiacijie/omr-wala-linkage | a1aff7aef9ed131a45555451abde4615a04412c1 | [
"Apache-2.0"
] | null | null | null | third_party/omr/compiler/z/codegen/S390Instruction.hpp | xiacijie/omr-wala-linkage | a1aff7aef9ed131a45555451abde4615a04412c1 | [
"Apache-2.0"
] | null | null | null | /*******************************************************************************
* Copyright (c) 2000, 2019 IBM Corp. and others
*
* This program and the accompanying materials are made available under
* the terms of the Eclipse Public License 2.0 which accompanies this
* distribution and is available at http://eclipse.org/legal/epl-2.0
* or the Apache License, Version 2.0 which accompanies this distribution
* and is available at https://www.apache.org/licenses/LICENSE-2.0.
*
* This Source Code may also be made available under the following Secondary
* Licenses when the conditions for such availability set forth in the
* Eclipse Public License, v. 2.0 are satisfied: GNU General Public License,
* version 2 with the GNU Classpath Exception [1] and GNU General Public
* License, version 2 with the OpenJDK Assembly Exception [2].
*
* [1] https://www.gnu.org/software/classpath/license.html
* [2] http://openjdk.java.net/legal/assembly-exception.html
*
* SPDX-License-Identifier: EPL-2.0 OR Apache-2.0 OR GPL-2.0 WITH Classpath-exception-2.0 OR LicenseRef-GPL-2.0 WITH Assembly-exception
*******************************************************************************/
#ifndef S390INSTRUCTION_INCL
#define S390INSTRUCTION_INCL
#include <stdint.h>
#include <string.h>
#include "codegen/CodeGenerator.hpp"
#include "codegen/InstOpCode.hpp"
#include "codegen/Instruction.hpp"
#include "codegen/MemoryReference.hpp"
#include "codegen/RealRegister.hpp"
#include "codegen/Register.hpp"
#include "codegen/RegisterConstants.hpp"
#include "codegen/RegisterPair.hpp"
#include "codegen/Snippet.hpp"
#include "codegen/UnresolvedDataSnippet.hpp"
#include "compile/Compilation.hpp"
#include "control/Options.hpp"
#include "control/Options_inlines.hpp"
#include "env/TRMemory.hpp"
#include "env/jittypes.h"
#include "il/symbol/LabelSymbol.hpp"
#include "infra/Assert.hpp"
#include "infra/Flags.hpp"
#include "ras/Debug.hpp"
#include "codegen/RegisterDependency.hpp"
class TR_AsmData;
class TR_VirtualGuardSite;
namespace TR { class Node; }
namespace TR { class RegisterDependencyConditions; }
namespace TR { class Symbol; }
namespace TR { class SymbolReference; }
////////////////////////////////////////////////////////////////////////////////
// TR::S390Instruction Class Definition
////////////////////////////////////////////////////////////////////////////////
/**
* Pseudo-safe downcast function.
*/
inline uint32_t *toS390Cursor(uint8_t *i)
{
return (uint32_t *)i;
}
namespace TR {
////////////////////////////////////////////////////////////////////////////////
// TR::S390LabeledInstruction Class Definition
////////////////////////////////////////////////////////////////////////////////
class S390LabeledInstruction : public TR::Instruction
{
TR::LabelSymbol *_symbol;
TR::Snippet *_snippet;
public:
S390LabeledInstruction(TR::InstOpCode::Mnemonic op,
TR::Node *n,
TR::LabelSymbol *sym,
TR::CodeGenerator *cg)
: TR::Instruction(op, n, cg), _symbol(sym), _snippet(NULL)
{
if ( !cg->comp()->getOption(TR_EnableEBBCCInfo) )
clearCCInfo();
else if (isLabel() || isCall()) //otherwise clearCCInfo for real Label instruction or call only
clearCCInfo();
}
S390LabeledInstruction(TR::InstOpCode::Mnemonic op,
TR::Node *n,
TR::LabelSymbol *sym,
TR::RegisterDependencyConditions * cond,
TR::CodeGenerator *cg)
: TR::Instruction(op, n, cond, cg), _symbol(sym), _snippet(NULL)
{
if ( !cg->comp()->getOption(TR_EnableEBBCCInfo) )
clearCCInfo();
else if (isLabel() || isCall()) //otherwise clearCCInfo for real Label instruction or call only
clearCCInfo();
}
S390LabeledInstruction(TR::InstOpCode::Mnemonic op,
TR::Node *n,
TR::LabelSymbol *sym,
TR::Instruction *precedingInstruction,
TR::CodeGenerator *cg)
: TR::Instruction(op, n, precedingInstruction, cg), _symbol(sym), _snippet(NULL)
{
if ( !cg->comp()->getOption(TR_EnableEBBCCInfo) )
clearCCInfo();
else if (isLabel() || isCall()) //otherwise clearCCInfo for real Label instruction or call only
clearCCInfo();
}
S390LabeledInstruction(TR::InstOpCode::Mnemonic op,
TR::Node *n,
TR::LabelSymbol *sym,
TR::RegisterDependencyConditions * cond,
TR::Instruction *precedingInstruction,
TR::CodeGenerator *cg)
: TR::Instruction(op, n, cond, precedingInstruction, cg), _symbol(sym), _snippet(NULL)
{
if ( !cg->comp()->getOption(TR_EnableEBBCCInfo) )
clearCCInfo();
else if (isLabel() || isCall()) //otherwise clearCCInfo for real Label instruction or call only
clearCCInfo();
}
S390LabeledInstruction(TR::InstOpCode::Mnemonic op,
TR::Node *n,
TR::Snippet *s,
TR::CodeGenerator *cg)
: TR::Instruction(op, n, cg), _symbol(NULL), _snippet(s)
{
if ( !cg->comp()->getOption(TR_EnableEBBCCInfo) )
clearCCInfo();
else if (isLabel() || isCall()) //otherwise clearCCInfo for real Label instruction or call only
clearCCInfo();
}
S390LabeledInstruction(TR::InstOpCode::Mnemonic op,
TR::Node *n,
TR::Snippet *s,
TR::RegisterDependencyConditions * cond,
TR::CodeGenerator *cg)
: TR::Instruction(op, n, cond, cg), _symbol(NULL), _snippet(s)
{
if ( !cg->comp()->getOption(TR_EnableEBBCCInfo) )
clearCCInfo();
else if (isLabel() || isCall()) //otherwise clearCCInfo for real Label instruction or call only
clearCCInfo();
}
S390LabeledInstruction(TR::InstOpCode::Mnemonic op,
TR::Node *n,
TR::Snippet *s,
TR::Instruction *precedingInstruction,
TR::CodeGenerator *cg)
: TR::Instruction(op, n, precedingInstruction, cg), _symbol(NULL), _snippet(s)
{
if ( !cg->comp()->getOption(TR_EnableEBBCCInfo) )
clearCCInfo();
else if (isLabel() || isCall()) //otherwise clearCCInfo for real Label instruction or call only
clearCCInfo();
}
S390LabeledInstruction(TR::InstOpCode::Mnemonic op,
TR::Node *n,
TR::Snippet *s,
TR::RegisterDependencyConditions * cond,
TR::Instruction *precedingInstruction,
TR::CodeGenerator *cg)
: TR::Instruction(op, n, cond, precedingInstruction, cg), _symbol(NULL), _snippet(s)
{
if ( !cg->comp()->getOption(TR_EnableEBBCCInfo) )
clearCCInfo();
else if (isLabel() || isCall()) //otherwise clearCCInfo for real Label instruction or call only
clearCCInfo();
}
TR::LabelSymbol *getLabelSymbol()
{
return _symbol;
}
TR::LabelSymbol *setLabelSymbol(TR::LabelSymbol *sym) {return _symbol = sym;}
TR::Snippet *getCallSnippet() {return _snippet;}
virtual char *description() { return "S390Instruction"; }
virtual Kind getKind()=0;
virtual uint8_t *generateBinaryEncoding()=0;
virtual int32_t estimateBinaryLength(int32_t currentEstimate)=0;
virtual bool isNopCandidate(); // Check to determine whether we should NOP to align instruction.
};
////////////////////////////////////////////////////////////////////////////////
// S390BranchInstruction Class Definition
////////////////////////////////////////////////////////////////////////////////
class S390BranchInstruction : public TR::S390LabeledInstruction
{
TR::InstOpCode::S390BranchCondition _branchCondition;
public:
S390BranchInstruction(TR::InstOpCode::Mnemonic op,
TR::InstOpCode::S390BranchCondition branchCondition,
TR::Node *n,
TR::LabelSymbol *sym,
TR::CodeGenerator *cg)
: S390LabeledInstruction(op, n, sym, cg),
_branchCondition(branchCondition)
{}
S390BranchInstruction(TR::InstOpCode::Mnemonic op,
TR::InstOpCode::S390BranchCondition branchCondition,
TR::Node *n,
TR::LabelSymbol *sym,
TR::RegisterDependencyConditions * cond,
TR::CodeGenerator *cg)
: S390LabeledInstruction(op, n, sym, cond, cg),
_branchCondition(branchCondition)
{}
S390BranchInstruction(TR::InstOpCode::Mnemonic op,
TR::InstOpCode::S390BranchCondition branchCondition,
TR::Node *n,
TR::LabelSymbol *sym,
TR::Instruction *precedingInstruction,
TR::CodeGenerator *cg)
: S390LabeledInstruction(op, n, sym, precedingInstruction, cg),
_branchCondition(branchCondition)
{}
S390BranchInstruction(TR::InstOpCode::Mnemonic op,
TR::InstOpCode::S390BranchCondition branchCondition,
TR::Node *n,
TR::LabelSymbol *sym,
TR::RegisterDependencyConditions * cond,
TR::Instruction *precedingInstruction,
TR::CodeGenerator *cg)
: S390LabeledInstruction(op, n, sym, cond, precedingInstruction, cg),
_branchCondition(branchCondition)
{}
S390BranchInstruction(TR::InstOpCode::Mnemonic op,
TR::InstOpCode::S390BranchCondition branchCondition,
TR::Node *n,
TR::Snippet *s,
TR::CodeGenerator *cg)
: S390LabeledInstruction(op, n, s, cg),
_branchCondition(branchCondition)
{}
S390BranchInstruction(TR::InstOpCode::Mnemonic op,
TR::InstOpCode::S390BranchCondition branchCondition,
TR::Node *n,
TR::Snippet *s,
TR::RegisterDependencyConditions * cond,
TR::CodeGenerator *cg)
: S390LabeledInstruction(op, n, s, cond, cg),
_branchCondition(branchCondition)
{}
S390BranchInstruction(TR::InstOpCode::Mnemonic op,
TR::InstOpCode::S390BranchCondition branchCondition,
TR::Node *n,
TR::Snippet *s,
TR::Instruction *precedingInstruction,
TR::CodeGenerator *cg)
: S390LabeledInstruction(op, n, s, precedingInstruction, cg),
_branchCondition(branchCondition)
{}
S390BranchInstruction(TR::InstOpCode::Mnemonic op,
TR::InstOpCode::S390BranchCondition branchCondition,
TR::Node *n,
TR::Snippet *s,
TR::RegisterDependencyConditions * cond,
TR::Instruction *precedingInstruction,
TR::CodeGenerator *cg)
: S390LabeledInstruction(op, n, s, cond, precedingInstruction, cg),
_branchCondition(branchCondition)
{}
virtual char *description() { return "S390Branch"; }
virtual Kind getKind() { return IsBranch; }
virtual TR::Snippet *getSnippetForGC()
{
if (getLabelSymbol() != NULL)
return getLabelSymbol()->getSnippet();
return NULL;
}
virtual uint8_t *generateBinaryEncoding();
virtual int32_t estimateBinaryLength(int32_t currentEstimate);
void assignRegistersAndDependencies(TR_RegisterKinds kindToBeAssigned);
TR::InstOpCode::S390BranchCondition getBranchCondition() {return _branchCondition;}
TR::InstOpCode::S390BranchCondition setBranchCondition(TR::InstOpCode::S390BranchCondition branchCondition) {return _branchCondition = branchCondition;}
uint8_t getMask() {return getMaskForBranchCondition(getBranchCondition()) << 4;}
};
////////////////////////////////////////////////////////////////////////////////
// For virtual guard nop instruction
////////////////////////////////////////////////////////////////////////////////
#ifdef J9_PROJECT_SPECIFIC
class S390VirtualGuardNOPInstruction : public TR::S390BranchInstruction
{
private:
TR_VirtualGuardSite *_site;
public:
S390VirtualGuardNOPInstruction(TR::Node *node,
TR_VirtualGuardSite *site,
TR::RegisterDependencyConditions *cond,
TR::LabelSymbol *label,
TR::CodeGenerator *cg)
: S390BranchInstruction(TR::InstOpCode::BRC, TR::InstOpCode::COND_VGNOP, node, label, cond, cg), _site(site) {}
S390VirtualGuardNOPInstruction(TR::Node *node,
TR_VirtualGuardSite *site,
TR::RegisterDependencyConditions *cond,
TR::LabelSymbol *label,
TR::Instruction *precedingInstruction,
TR::CodeGenerator *cg)
: S390BranchInstruction(TR::InstOpCode::BRC, TR::InstOpCode::COND_VGNOP, node, label, cond, precedingInstruction, cg), _site(site) {}
virtual char *description() { return "S390VirtualGuardNOP"; }
virtual Kind getKind() { return IsVirtualGuardNOP; }
void setSite(TR_VirtualGuardSite *site) { _site = site; }
TR_VirtualGuardSite * getSite() { return _site; }
virtual uint8_t *generateBinaryEncoding();
virtual bool isVirtualGuardNOPInstruction() {return true;}
};
#endif
////////////////////////////////////////////////////////////////////////////////
// S390BranchOnCountInstruction Class Definition
////////////////////////////////////////////////////////////////////////////////
class S390BranchOnCountInstruction : public TR::S390LabeledInstruction
{
#define br_targidx 0
public:
S390BranchOnCountInstruction(TR::InstOpCode::Mnemonic op,
TR::Node *n,
TR::Register *targetReg,
TR::LabelSymbol *sym,
TR::CodeGenerator *cg)
: S390LabeledInstruction(op, n, sym, cg)
{useTargetRegister(targetReg);}
S390BranchOnCountInstruction(TR::InstOpCode::Mnemonic op,
TR::Node *n,
TR::Register *targetReg,
TR::RegisterDependencyConditions * cond,
TR::LabelSymbol *sym,
TR::CodeGenerator *cg)
: S390LabeledInstruction(op, n, sym, cond, cg)
{useTargetRegister(targetReg); }
S390BranchOnCountInstruction(TR::InstOpCode::Mnemonic op,
TR::Node *n,
TR::Register *targetReg,
TR::LabelSymbol *sym,
TR::Instruction *precedingInstruction,
TR::CodeGenerator *cg)
: S390LabeledInstruction(op, n, sym, precedingInstruction, cg)
{useTargetRegister(targetReg); }
S390BranchOnCountInstruction(TR::InstOpCode::Mnemonic op,
TR::Node *n,
TR::Register *targetReg,
TR::RegisterDependencyConditions * cond,
TR::LabelSymbol *sym,
TR::Instruction *precedingInstruction,
TR::CodeGenerator *cg)
: S390LabeledInstruction(op, n, sym, precedingInstruction, cg)
{useTargetRegister(targetReg);}
virtual char *description() { return "S390BranchOnCount"; }
virtual Kind getKind() { return IsBranchOnCount; }
virtual uint8_t *generateBinaryEncoding();
virtual int32_t estimateBinaryLength(int32_t currentEstimate);
virtual bool refsRegister(TR::Register *reg);
};
////////////////////////////////////////////////////////////////////////////////
// S390BranchOnCountInstruction Class Definition
////////////////////////////////////////////////////////////////////////////////
class S390BranchOnIndexInstruction : public TR::S390LabeledInstruction
{
#define br_srcidx 0
#define br_targidx 0
public:
S390BranchOnIndexInstruction(TR::InstOpCode::Mnemonic op,
TR::Node *n,
TR::Register *sourceReg,
TR::Register *targetReg,
TR::LabelSymbol *sym,
TR::CodeGenerator *cg)
: S390LabeledInstruction(op, n, sym, cg)
{useTargetRegister(targetReg); useSourceRegister(sourceReg); }
S390BranchOnIndexInstruction(TR::InstOpCode::Mnemonic op,
TR::Node *n,
TR::Register *sourceReg,
TR::Register *targetReg,
TR::LabelSymbol *sym,
TR::Instruction *precedingInstruction,
TR::CodeGenerator *cg)
: S390LabeledInstruction(op, n, sym, precedingInstruction, cg)
{useTargetRegister(targetReg); useSourceRegister(sourceReg); }
S390BranchOnIndexInstruction(TR::InstOpCode::Mnemonic op,
TR::Node *n,
TR::RegisterPair *sourceReg,
TR::Register *targetReg,
TR::LabelSymbol *sym,
TR::CodeGenerator *cg)
: S390LabeledInstruction(op, n, sym, cg)
{useTargetRegister(targetReg); useSourceRegister(sourceReg);}
S390BranchOnIndexInstruction(TR::InstOpCode::Mnemonic op,
TR::Node *n,
TR::RegisterPair *sourceReg,
TR::Register *targetReg,
TR::LabelSymbol *sym,
TR::Instruction *precedingInstruction,
TR::CodeGenerator *cg)
: S390LabeledInstruction(op, n, sym, precedingInstruction, cg)
{useTargetRegister(targetReg); useSourceRegister(sourceReg);}
virtual char *description() { return "S390BranchOnIndex"; }
virtual Kind getKind() { return IsBranchOnIndex; }
virtual uint8_t *generateBinaryEncoding();
virtual int32_t estimateBinaryLength(int32_t currentEstimate);
virtual bool refsRegister(TR::Register *reg);
};
////////////////////////////////////////////////////////////////////////////////
// S390LabelInstruction Class Definition
////////////////////////////////////////////////////////////////////////////////
class S390LabelInstruction : public TR::S390LabeledInstruction
{
flags8_t _flags;
enum
{
doPrint = 0x01,
skipForLabelTargetNOPs = 0x02,
estimateDoneForLabelTargetNOPs = 0x04,
// AVAILABLE = 0x08
};
public:
S390LabelInstruction(TR::InstOpCode::Mnemonic op,
TR::Node *n,
TR::LabelSymbol *sym,
TR::CodeGenerator *cg)
: S390LabeledInstruction(op, n, sym, cg), _alignment(0), _handle(0), _flags(0)
{
if (op==TR::InstOpCode::LABEL)
sym->setInstruction(this);
cg->getNextAvailableBlockIndex();
}
S390LabelInstruction(TR::InstOpCode::Mnemonic op,
TR::Node *n,
TR::Register *targetReg,
TR::LabelSymbol *sym,
TR::CodeGenerator *cg)
: S390LabeledInstruction(op, n, sym, cg), _alignment(0), _handle(0), _flags(0)
{
if (op==TR::InstOpCode::LABEL)
sym->setInstruction(this);
cg->getNextAvailableBlockIndex();
}
S390LabelInstruction(TR::InstOpCode::Mnemonic op,
TR::Node *n,
TR::Register *targetReg,
TR::LabelSymbol *sym,
TR::Instruction *precedingInstruction,
TR::CodeGenerator *cg)
: S390LabeledInstruction(op, n, sym, precedingInstruction, cg), _alignment(0), _handle(0), _flags(0)
{
if (op==TR::InstOpCode::LABEL)
sym->setInstruction(this);
cg->getNextAvailableBlockIndex();
}
S390LabelInstruction(TR::InstOpCode::Mnemonic op,
TR::Node *n,
TR::LabelSymbol *sym,
TR::RegisterDependencyConditions * cond,
TR::CodeGenerator *cg)
: S390LabeledInstruction(op, n, sym, cond, cg), _alignment(0), _handle(0), _flags(0)
{
if (op==TR::InstOpCode::LABEL)
sym->setInstruction(this);
cg->getNextAvailableBlockIndex();
}
S390LabelInstruction(TR::InstOpCode::Mnemonic op,
TR::Node *n,
TR::LabelSymbol *sym,
TR::Instruction *precedingInstruction,
TR::CodeGenerator *cg)
: S390LabeledInstruction(op, n, sym, precedingInstruction, cg), _alignment(0), _handle(0), _flags(0)
{
if (op==TR::InstOpCode::LABEL)
sym->setInstruction(this);
cg->getNextAvailableBlockIndex();
}
S390LabelInstruction(TR::InstOpCode::Mnemonic op,
TR::Node *n,
TR::LabelSymbol *sym,
TR::RegisterDependencyConditions * cond,
TR::Instruction *precedingInstruction,
TR::CodeGenerator *cg)
: S390LabeledInstruction(op, n, sym, cond, precedingInstruction, cg), _alignment(0), _handle(0), _flags(0)
{
if (op==TR::InstOpCode::LABEL)
sym->setInstruction(this);
cg->getNextAvailableBlockIndex();
}
S390LabelInstruction(TR::InstOpCode::Mnemonic op,
TR::Node *n,
TR::Snippet *s,
TR::CodeGenerator *cg)
: S390LabeledInstruction(op, n, s, cg), _alignment(0), _handle(0), _flags(0)
{}
S390LabelInstruction(TR::InstOpCode::Mnemonic op,
TR::Node *n,
TR::Snippet *s,
TR::RegisterDependencyConditions * cond,
TR::CodeGenerator *cg)
: S390LabeledInstruction(op, n, s, cond, cg), _alignment(0), _handle(0), _flags(0)
{}
S390LabelInstruction(TR::InstOpCode::Mnemonic op,
TR::Node *n,
TR::Snippet *s,
TR::Instruction *precedingInstruction,
TR::CodeGenerator *cg)
: S390LabeledInstruction(op, n, s, precedingInstruction, cg), _alignment(0), _handle(0), _flags(0)
{}
S390LabelInstruction(TR::InstOpCode::Mnemonic op,
TR::Node *n,
TR::Snippet *s,
TR::RegisterDependencyConditions * cond,
TR::Instruction *precedingInstruction,
TR::CodeGenerator *cg)
: S390LabeledInstruction(op, n, s, cond, precedingInstruction, cg), _alignment(0), _handle(0), _flags(0)
{}
virtual char *description() { return "S390LabelInstruction"; }
virtual Kind getKind() { return IsLabel; }
virtual uint8_t *generateBinaryEncoding();
virtual int32_t estimateBinaryLength(int32_t currentEstimate);
void assignRegistersAndDependencies(TR_RegisterKinds kindToBeAssigned);
void preservedForListing() { _flags.set(doPrint);}
bool isPreservedForListing() {return _flags.testAny(doPrint); }
void setSkipForLabelTargetNOPs() { _flags.set(skipForLabelTargetNOPs);}
bool isSkipForLabelTargetNOPs() {return _flags.testAny(skipForLabelTargetNOPs); }
void setEstimateDoneForLabelTargetNOPs() { _flags.set(estimateDoneForLabelTargetNOPs);}
bool wasEstimateDoneForLabelTargetNOPs() {return _flags.testAny(estimateDoneForLabelTargetNOPs); }
bool considerForLabelTargetNOPs(bool inEncodingPhase);
uint16_t getAlignment() {return _alignment;}
uint16_t setAlignment(uint16_t alignment) {return _alignment = alignment;}
protected:
uint16_t _alignment;
int32_t _handle;
};
////////////////////////////////////////////////////////////////////////////////
// S390PseudoInstruction Class Definition
////////////////////////////////////////////////////////////////////////////////
class S390PseudoInstruction : public TR::Instruction
{
TR::Node *_fenceNode;
uint64_t _callDescValue; ///< Call Descriptor for XPLINK on zOS 31 JNI Calls.
uint8_t _padbytes;
TR::LabelSymbol *_callDescLabel;
bool _shouldBeginNewLine;
public:
S390PseudoInstruction(TR::InstOpCode::Mnemonic op,
TR::Node *n,
TR::Node * fenceNode,
TR::CodeGenerator *cg)
: TR::Instruction(op, n, cg),
_fenceNode(fenceNode),
_callDescValue(0),
_padbytes(0),
_callDescLabel(NULL),
_shouldBeginNewLine(false){}
S390PseudoInstruction(TR::InstOpCode::Mnemonic op,
TR::Node *n,
TR::Node * fenceNode,
TR::RegisterDependencyConditions * cond,
TR::CodeGenerator *cg)
: TR::Instruction(op, n, cond, cg),
_fenceNode(fenceNode),
_callDescValue(0),
_padbytes(0),
_callDescLabel(NULL),
_shouldBeginNewLine(false){}
S390PseudoInstruction(TR::InstOpCode::Mnemonic op,
TR::Node * n,
TR::Node *fenceNode,
TR::Instruction *precedingInstruction,
TR::CodeGenerator *cg)
: TR::Instruction(op, n, precedingInstruction, cg),
_fenceNode(fenceNode),
_callDescValue(0),
_padbytes(0),
_callDescLabel(NULL),
_shouldBeginNewLine(false){}
S390PseudoInstruction(TR::InstOpCode::Mnemonic op,
TR::Node * n,
TR::Node *fenceNode,
TR::RegisterDependencyConditions * cond,
TR::Instruction *precedingInstruction,
TR::CodeGenerator *cg)
: TR::Instruction(op, n, cond, precedingInstruction, cg),
_fenceNode(fenceNode),
_callDescValue(0),
_padbytes(0),
_callDescLabel(NULL),
_shouldBeginNewLine(false){}
virtual char *description() { return "S390PseudoInstruction"; }
virtual Kind getKind() { return IsPseudo; }
TR::Node * getFenceNode() { return _fenceNode; }
// TR::Register *getTargetRegister() { return (_targetRegSize!=0) ? (targetRegBase())[0] : NULL;}
void setShouldBeginNewLine(bool sbnl) { _shouldBeginNewLine = sbnl; }
bool shouldBeginNewLine() { return _shouldBeginNewLine; }
virtual uint8_t *generateBinaryEncoding();
uint64_t setCallDescValue(uint64_t cdv, TR_Memory * m)
{
if (!_callDescLabel)
{
_callDescLabel = TR::LabelSymbol::create(m->trHeapMemory());
}
return _callDescValue = cdv;
}
uint64_t getCallDescValue() { return _callDescValue; }
TR::LabelSymbol * setCallDescLabel(TR::LabelSymbol * ls) { return _callDescLabel = ls; }
TR::LabelSymbol * getCallDescLabel() { return _callDescLabel; }
uint8_t getNumPadBytes() { return _padbytes; }
virtual int32_t estimateBinaryLength(int32_t currentEstimate);
};
/**
* Extends from S390PseudoInstruction to exploit the property of register assignment ignoring
* these types or treating them specially
*/
class S390DebugCounterBumpInstruction : public S390PseudoInstruction
{
private:
/** Contains address information necessary for LGRL during binary encoding */
TR::Snippet * _counterSnippet;
/** A free real register for DCB to use during binary encoding */
TR::RealRegister * _assignableReg;
/** Specifies amount to increment the counter */
int32_t _delta;
public:
S390DebugCounterBumpInstruction(TR::InstOpCode::Mnemonic op,
TR::Node *n,
TR::Snippet* counterSnip,
TR::CodeGenerator *cg,
int32_t delta)
: S390PseudoInstruction(op, n, NULL, cg),
_counterSnippet(counterSnip),
_assignableReg(NULL),
_delta(delta){}
S390DebugCounterBumpInstruction(TR::InstOpCode::Mnemonic op,
TR::Node *n,
TR::Snippet* counterSnip,
TR::CodeGenerator *cg,
int32_t delta,
TR::Instruction *precedingInstruction)
: S390PseudoInstruction(op, n, NULL, precedingInstruction, cg),
_counterSnippet(counterSnip),
_assignableReg(NULL),
_delta(delta){}
/**
* A real register must only be assigned for DCB to use if it is guaranteed to be free at the cursor position where DCB is inserted
* @param ar Real Register to be assigned
*/
void setAssignableReg(TR::RealRegister * ar){ _assignableReg = ar; }
/**
* @return Assigned Real Register
*/
TR::RealRegister * getAssignableReg(){ return _assignableReg; }
/**
* @return The snippet that holds the debugCounter's counter address in persistent memory
*/
TR::Snippet * getCounterSnippet(){ return _counterSnippet; }
/**
* @return The integer amount to increment the counter
*/
int32_t getDelta(){ return _delta; }
virtual uint8_t *generateBinaryEncoding();
};
////////////////////////////////////////////////////////////////////////////////
// S390AnnotationInstruction Class Definition
////////////////////////////////////////////////////////////////////////////////
class S390AnnotationInstruction : public TR::Instruction
{
public:
S390AnnotationInstruction(TR::InstOpCode::Mnemonic op,
TR::Node *n,
int16_t regionNum,
int32_t statementNum,
int32_t flags,
bool printNumber,
char * annotation,
TR::CodeGenerator *cg)
: TR::Instruction(op, n, cg),
_annotation(annotation),
_flags(flags),
_shouldPrintNumber(printNumber)
{
setRegionNumber(regionNum);
}
S390AnnotationInstruction(TR::InstOpCode::Mnemonic op,
TR::Node *n,
int16_t regionNum,
int32_t statementNum,
int32_t flags,
bool printNumber,
char * annotation,
TR::Instruction *precedingInstruction,
TR::CodeGenerator *cg)
: TR::Instruction(op, n, precedingInstruction, cg),
_annotation(annotation),
_flags(flags),
_shouldPrintNumber(printNumber)
{
setRegionNumber(regionNum);
}
S390AnnotationInstruction(TR::InstOpCode::Mnemonic op,
TR::Node *n,
int16_t regionNum,
int32_t statementNum,
int32_t flags,
bool printNumber,
char * annotation,
TR::RegisterDependencyConditions *cond,
TR::CodeGenerator *cg)
: TR::Instruction(op, n, cond, cg),
_annotation(annotation),
_flags(flags),
_shouldPrintNumber(printNumber)
{
setRegionNumber(regionNum);
}
S390AnnotationInstruction(TR::InstOpCode::Mnemonic op,
TR::Node *n,
int16_t regionNum,
int32_t statementNum,
int32_t flags,
bool printNumber,
char * annotation,
TR::RegisterDependencyConditions *cond,
TR::Instruction *precedingInstruction,
TR::CodeGenerator *cg)
: TR::Instruction(op, n, cond, precedingInstruction, cg),
_annotation(annotation),
_flags(flags),
_shouldPrintNumber(printNumber)
{
setRegionNumber(regionNum);
}
virtual char *description() { return "S390AnnotInstruction"; }
virtual Kind getKind() { return IsAnnot; }
char *getAnnotation() { return _annotation; }
int32_t getFlags() { return _flags; }
bool shouldPrintNumber() { return _shouldPrintNumber; }
private:
char *_annotation;
int32_t _flags;
bool _shouldPrintNumber;
};
////////////////////////////////////////////////////////////////////////////////
// S390ImmInstruction Class Definition
////////////////////////////////////////////////////////////////////////////////
class S390ImmInstruction : public TR::Instruction
{
uint32_t _sourceImmediate;
public:
S390ImmInstruction(TR::InstOpCode::Mnemonic op,
TR::Node *n,
uint32_t imm,
TR::CodeGenerator *cg)
: TR::Instruction(op, n, cg), _sourceImmediate(imm)
{}
S390ImmInstruction(TR::InstOpCode::Mnemonic op,
TR::Node *n,
uint32_t imm,
TR::Instruction *precedingInstruction,
TR::CodeGenerator *cg)
: TR::Instruction(op, n, precedingInstruction, cg), _sourceImmediate(imm)
{}
S390ImmInstruction(TR::InstOpCode::Mnemonic op,
TR::Node *n,
uint32_t imm,
TR::RegisterDependencyConditions *cond,
TR::CodeGenerator *cg)
: TR::Instruction(op, n, cond, cg), _sourceImmediate(imm)
{}
S390ImmInstruction(TR::InstOpCode::Mnemonic op,
TR::Node *n,
uint32_t imm,
TR::RegisterDependencyConditions *cond,
TR::Instruction *precedingInstruction,
TR::CodeGenerator *cg)
: TR::Instruction(op, n, cond, precedingInstruction, cg), _sourceImmediate(imm)
{}
virtual char *description() { return "S390ImmInstruction"; }
virtual Kind getKind() { return IsImm; }
uint32_t getSourceImmediate() {return _sourceImmediate;}
uint32_t setSourceImmediate(uint32_t si) {return _sourceImmediate = si;}
virtual uint8_t *generateBinaryEncoding();
// The following safe virtual downcast method is used under debug only
// for assertion checking
#if defined(DEBUG) || defined(PROD_WITH_ASSUMES)
virtual S390ImmInstruction *getS390ImmInstruction();
#endif
};
////////////////////////////////////////////////////////////////////////////////
// S390Imm2Instruction (2-byte) Class Definition
////////////////////////////////////////////////////////////////////////////////
class S390Imm2Instruction : public TR::Instruction
{
uint16_t _sourceImmediate;
public:
S390Imm2Instruction(TR::InstOpCode::Mnemonic op,
TR::Node *n,
uint16_t imm,
TR::CodeGenerator *cg)
: TR::Instruction(op, n, cg), _sourceImmediate(imm)
{ setEstimatedBinaryLength(2); }
S390Imm2Instruction(TR::InstOpCode::Mnemonic op,
TR::Node *n,
uint16_t imm,
TR::Instruction *precedingInstruction,
TR::CodeGenerator *cg)
: TR::Instruction(op, n, precedingInstruction, cg), _sourceImmediate(imm)
{ setEstimatedBinaryLength(2); }
S390Imm2Instruction(TR::InstOpCode::Mnemonic op,
TR::Node *n,
uint16_t imm,
TR::RegisterDependencyConditions *cond,
TR::CodeGenerator *cg)
: TR::Instruction(op, n, cond, cg), _sourceImmediate(imm)
{ setEstimatedBinaryLength(2); }
S390Imm2Instruction(TR::InstOpCode::Mnemonic op,
TR::Node *n,
uint16_t imm,
TR::RegisterDependencyConditions *cond,
TR::Instruction *precedingInstruction,
TR::CodeGenerator *cg)
: TR::Instruction(op, n, cond, precedingInstruction, cg), _sourceImmediate(imm)
{ setEstimatedBinaryLength(2); }
virtual char *description() { return "S390Imm2Instruction"; }
virtual Kind getKind() { return IsImm2Byte; }
uint16_t getSourceImmediate() {return _sourceImmediate;}
uint16_t setSourceImmediate(uint16_t si) {return _sourceImmediate = si;}
virtual uint8_t *generateBinaryEncoding();
};
////////////////////////////////////////////////////////////////////////////////
// S390ImmSnippetInstruction Class Definition
////////////////////////////////////////////////////////////////////////////////
class S390ImmSnippetInstruction : public TR::S390ImmInstruction
{
TR::UnresolvedDataSnippet *_unresolvedSnippet;
TR::Snippet *_snippet;
public:
S390ImmSnippetInstruction(TR::InstOpCode::Mnemonic op,
TR::Node *n,
uint32_t imm,
TR::UnresolvedDataSnippet *us,
TR::Snippet *s,
TR::CodeGenerator *cg)
: S390ImmInstruction(op, n,imm, cg), _unresolvedSnippet(us),
_snippet(s) {}
S390ImmSnippetInstruction(
TR::InstOpCode::Mnemonic op,
TR::Node *n,
uint32_t imm,
TR::UnresolvedDataSnippet *us,
TR::Snippet *s,
TR::Instruction *precedingInstruction,
TR::CodeGenerator *cg)
: S390ImmInstruction(op, n, imm, precedingInstruction, cg),
_unresolvedSnippet(us), _snippet(s) {}
virtual char *description() { return "S390ImmSnippetInstruction"; }
virtual Kind getKind() { return IsImmSnippet; }
TR::UnresolvedDataSnippet *getUnresolvedSnippet() {return _unresolvedSnippet;}
TR::UnresolvedDataSnippet *setUnresolvedSnippet(TR::UnresolvedDataSnippet *us)
{
return _unresolvedSnippet = us;
}
virtual uint8_t *generateBinaryEncoding();
};
////////////////////////////////////////////////////////////////////////////////
// S390ImmSymInstruction Class Definition
////////////////////////////////////////////////////////////////////////////////
class S390ImmSymInstruction : public TR::S390ImmInstruction
{
TR::SymbolReference *_symbolReference;
public:
S390ImmSymInstruction(TR::InstOpCode::Mnemonic op,
TR::Node *node,
uint32_t imm,
TR::SymbolReference *sr,
TR::CodeGenerator *cg)
: S390ImmInstruction(op, node, imm, cg), _symbolReference(sr)
{}
S390ImmSymInstruction(TR::InstOpCode::Mnemonic op,
TR::Node *node,
uint32_t imm,
TR::SymbolReference *sr,
TR::Instruction *precedingInstruction,
TR::CodeGenerator *cg)
: S390ImmInstruction(op, node, imm, precedingInstruction, cg), _symbolReference(sr)
{}
S390ImmSymInstruction(TR::InstOpCode::Mnemonic op,
TR::Node *node,
uint32_t imm,
TR::SymbolReference *sr,
TR::RegisterDependencyConditions *cond,
TR::CodeGenerator *cg)
: S390ImmInstruction(op, node, imm, cond, cg), _symbolReference(sr)
{}
S390ImmSymInstruction(TR::InstOpCode::Mnemonic op,
TR::Node *node,
uint32_t imm,
TR::SymbolReference *sr,
TR::RegisterDependencyConditions *cond,
TR::Instruction *precedingInstruction,
TR::CodeGenerator *cg)
: S390ImmInstruction(op, node, imm, cond, precedingInstruction, cg), _symbolReference(sr)
{}
virtual char *description() { return "S390ImmSymInstruction"; }
virtual Kind getKind() { return IsImmSym; }
TR::SymbolReference *getSymbolReference() {return _symbolReference;}
TR::SymbolReference *setSymbolReference(TR::SymbolReference *sr)
{
return _symbolReference = sr;
}
virtual uint8_t *generateBinaryEncoding();
};
/**
* S390RegInstruction Class Definition
*
*
*/
class S390RegInstruction : public TR::Instruction
{
protected:
int8_t _firstConstant;
/** Flag identifying pair or single */
bool _targetPairFlag;
TR::InstOpCode::S390BranchCondition _branchCondition;
public:
S390RegInstruction(TR::InstOpCode::Mnemonic op,
TR::Node *n,
TR::Register *reg,
TR::CodeGenerator *cg)
: TR::Instruction(op, n, cg), _branchCondition(TR::InstOpCode::COND_NOP), _firstConstant(-1)
{
checkRegForGPR0Disable(op, reg);
_targetPairFlag=reg->getRegisterPair()?true:false;
if(!getOpCode().setsOperand1())
useSourceRegister(reg);
else
useTargetRegister(reg);
// ShouldUseRegPairForTarget returns true for those instructions that require consequtive even-odd register pairs.
// CanUseRegPairForTarget returns true for all the above instructions + STM/LTM (which can potentially take a register pair range).
// So, if we find a register pair passed in, we check to make sure the instruction CAN use a register pair.
// If we do not find a register pair, we check to make sure the instruction SHOULD NOT use a register pair.
TR_ASSERT( (!_targetPairFlag && !getOpCode().shouldUseRegPairForTarget())
|| (_targetPairFlag && getOpCode().canUseRegPairForTarget()) ,
"OpCode [%s] %s use Register Pair for Target.\n",
getOpCode().getMnemonicName(),
(_targetPairFlag)?"cannot":"should");
}
S390RegInstruction(TR::InstOpCode::Mnemonic op,
TR::Node *n,
TR::CodeGenerator *cg)
: TR::Instruction(op, n, cg), _branchCondition(TR::InstOpCode::COND_NOP), _firstConstant(-1), _targetPairFlag(false)
{
}
S390RegInstruction(TR::InstOpCode::Mnemonic op,
TR::Node *n,
TR::Instruction *precedingInstruction,
TR::CodeGenerator *cg)
: TR::Instruction(op, n, precedingInstruction, cg), _branchCondition(TR::InstOpCode::COND_NOP), _firstConstant(-1), _targetPairFlag(false)
{
}
S390RegInstruction(TR::InstOpCode::Mnemonic op,
TR::Node *n,
int8_t firstConstant,
TR::CodeGenerator *cg)
: TR::Instruction(op, n, cg), _branchCondition(TR::InstOpCode::COND_NOP), _firstConstant(firstConstant), _targetPairFlag(false)
{
}
S390RegInstruction(TR::InstOpCode::Mnemonic op,
TR::Node *n,
int8_t firstConstant,
TR::Instruction *precedingInstruction,
TR::CodeGenerator *cg)
: TR::Instruction(op, n, precedingInstruction, cg), _branchCondition(TR::InstOpCode::COND_NOP), _firstConstant(firstConstant), _targetPairFlag(false)
{
}
S390RegInstruction(TR::InstOpCode::Mnemonic op,
TR::Node *n,
TR::Register *reg,
TR::RegisterDependencyConditions * cond,
TR::CodeGenerator *cg)
: TR::Instruction(op, n, cond, cg), _branchCondition(TR::InstOpCode::COND_NOP), _firstConstant(-1)
{
checkRegForGPR0Disable(op, reg);
_targetPairFlag=reg->getRegisterPair()?true:false;
if (!getOpCode().setsOperand1())
useSourceRegister(reg);
else
useTargetRegister(reg);
// ShouldUseRegPairForTarget returns true for those instructions that require consequtive even-odd register pairs.
// CanUseRegPairForTarget returns true for all the above instructions + STM/LTM (which can potentially take a register pair range).
// So, if we find a register pair passed in, we check to make sure the instruction CAN use a register pair.
// If we do not find a register pair, we check to make sure the instruction SHOULD NOT use a register pair.
TR_ASSERT((!_targetPairFlag && !getOpCode().shouldUseRegPairForTarget())
|| (_targetPairFlag && getOpCode().canUseRegPairForTarget()) ,
"OpCode [%s] %s use Register Pair for Target.\n",
getOpCode().getMnemonicName(),
(_targetPairFlag)?"cannot":"should");
}
S390RegInstruction(TR::InstOpCode::Mnemonic op,
TR::Node *n,
TR::Register *reg,
TR::Instruction *precedingInstruction,
TR::CodeGenerator *cg)
: TR::Instruction(op, n, precedingInstruction, cg), _branchCondition(TR::InstOpCode::COND_NOP), _firstConstant(-1)
{
checkRegForGPR0Disable(op, reg);
_targetPairFlag=reg->getRegisterPair()?true:false;
if (!getOpCode().setsOperand1())
useSourceRegister(reg);
else
useTargetRegister(reg);
// ShouldUseRegPairForTarget returns true for those instructions that require consequtive even-odd register pairs.
// CanUseRegPairForTarget returns true for all the above instructions + STM/LTM (which can potentially take a register pair range).
// So, if we find a register pair passed in, we check to make sure the instruction CAN use a register pair.
// If we do not find a register pair, we check to make sure the instruction SHOULD NOT use a register pair.
TR_ASSERT((!_targetPairFlag && !getOpCode().shouldUseRegPairForTarget())
|| (_targetPairFlag && getOpCode().canUseRegPairForTarget()) ,
"OpCode [%s] %s use Register Pair for Target.\n",
getOpCode().getMnemonicName(),
(_targetPairFlag)?"cannot":"should");
}
S390RegInstruction(TR::InstOpCode::Mnemonic op,
TR::Node *n,
TR::Register *reg,
TR::RegisterDependencyConditions * cond,
TR::Instruction *precedingInstruction,
TR::CodeGenerator *cg)
: TR::Instruction(op, n, cond, precedingInstruction, cg), _branchCondition(TR::InstOpCode::COND_NOP), _firstConstant(-1)
{
checkRegForGPR0Disable(op, reg);
_targetPairFlag=reg->getRegisterPair()?true:false;
useTargetRegister(reg);
// ShouldUseRegPairForTarget returns true for those instructions that require consequtive even-odd register pairs.
// CanUseRegPairForTarget returns true for all the above instructions + STM/LTM (which can potentially take a register pair range).
// So, if we find a register pair passed in, we check to make sure the instruction CAN use a register pair.
// If we do not find a register pair, we check to make sure the instruction SHOULD NOT use a register pair.
TR_ASSERT((!_targetPairFlag && !getOpCode().shouldUseRegPairForTarget())
|| (_targetPairFlag && getOpCode().canUseRegPairForTarget()) ,
"OpCode [%s] %s use Register Pair for Target.\n",
getOpCode().getMnemonicName(),
(_targetPairFlag)?"cannot":"should");
}
S390RegInstruction(TR::InstOpCode::Mnemonic op,
TR::Node *n,
TR::InstOpCode::S390BranchCondition brCond,
TR::Register *reg,
TR::CodeGenerator *cg)
: TR::Instruction(op, n, cg), _branchCondition(brCond), _firstConstant(0)
{
checkRegForGPR0Disable(op, reg);
_targetPairFlag=reg->getRegisterPair()?true:false;
if (!getOpCode().setsOperand1())
useSourceRegister(reg);
else
useTargetRegister(reg);
// ShouldUseRegPairForTarget returns true for those instructions that require consequtive even-odd register pairs.
// CanUseRegPairForTarget returns true for all the above instructions + STM/LTM (which can potentially take a register pair range).
// So, if we find a register pair passed in, we check to make sure the instruction CAN use a register pair.
// If we do not find a register pair, we check to make sure the instruction SHOULD NOT use a register pair.
TR_ASSERT((!_targetPairFlag && !getOpCode().shouldUseRegPairForTarget())
|| (_targetPairFlag && getOpCode().canUseRegPairForTarget()) ,
"OpCode [%s] %s use Register Pair for Target.\n",
getOpCode().getMnemonicName(),
(_targetPairFlag)?"cannot":"should");
}
S390RegInstruction(TR::InstOpCode::Mnemonic op,
TR::Node *n,
TR::InstOpCode::S390BranchCondition brCond,
TR::Register *reg,
TR::Instruction *precedingInstruction,
TR::CodeGenerator *cg)
: TR::Instruction(op, n, precedingInstruction, cg), _branchCondition(brCond), _firstConstant(0)
{
checkRegForGPR0Disable(op, reg);
_targetPairFlag=reg->getRegisterPair()?true:false;
if (!getOpCode().setsOperand1())
useSourceRegister(reg);
else
useTargetRegister(reg);
// ShouldUseRegPairForTarget returns true for those instructions that require consequtive even-odd register pairs.
// CanUseRegPairForTarget returns true for all the above instructions + STM/LTM (which can potentially take a register pair range).
// So, if we find a register pair passed in, we check to make sure the instruction CAN use a register pair.
// If we do not find a register pair, we check to make sure the instruction SHOULD NOT use a register pair.
TR_ASSERT( (!_targetPairFlag && !getOpCode().shouldUseRegPairForTarget())
|| (_targetPairFlag && getOpCode().canUseRegPairForTarget()) ,
"OpCode [%s] %s use Register Pair for Target.\n",
getOpCode().getMnemonicName(),
(_targetPairFlag)?"cannot":"should");
}
S390RegInstruction(TR::InstOpCode::Mnemonic op,
TR::Node *n,
TR::InstOpCode::S390BranchCondition brCond,
TR::Register *reg,
TR::RegisterDependencyConditions * cond,
TR::CodeGenerator *cg)
: TR::Instruction(op, n, cond, cg), _branchCondition(brCond), _firstConstant(0)
{
checkRegForGPR0Disable(op, reg);
_targetPairFlag=reg->getRegisterPair()?true:false;
if (!getOpCode().setsOperand1())
useSourceRegister(reg);
else
useTargetRegister(reg);
// ShouldUseRegPairForTarget returns true for those instructions that require consequtive even-odd register pairs.
// CanUseRegPairForTarget returns true for all the above instructions + STM/LTM (which can potentially take a register pair range).
// So, if we find a register pair passed in, we check to make sure the instruction CAN use a register pair.
// If we do not find a register pair, we check to make sure the instruction SHOULD NOT use a register pair.
TR_ASSERT((!_targetPairFlag && !getOpCode().shouldUseRegPairForTarget())
|| (_targetPairFlag && getOpCode().canUseRegPairForTarget()) ,
"OpCode [%s] %s use Register Pair for Target.\n",
getOpCode().getMnemonicName(),
(_targetPairFlag)?"cannot":"should");
}
S390RegInstruction(TR::InstOpCode::Mnemonic op,
TR::Node *n,
TR::InstOpCode::S390BranchCondition brCond,
TR::Register *reg,
TR::RegisterDependencyConditions * cond,
TR::Instruction *precedingInstruction,
TR::CodeGenerator *cg)
: TR::Instruction(op, n, cond, precedingInstruction, cg), _branchCondition(brCond), _firstConstant(0)
{
checkRegForGPR0Disable(op, reg);
_targetPairFlag=reg->getRegisterPair()?true:false;
if (!getOpCode().setsOperand1())
useSourceRegister(reg);
else
useTargetRegister(reg);
// ShouldUseRegPairForTarget returns true for those instructions that require consequtive even-odd register pairs.
// CanUseRegPairForTarget returns true for all the above instructions + STM/LTM (which can potentially take a register pair range).
// So, if we find a register pair passed in, we check to make sure the instruction CAN use a register pair.
// If we do not find a register pair, we check to make sure the instruction SHOULD NOT use a register pair.
TR_ASSERT((!_targetPairFlag && !getOpCode().shouldUseRegPairForTarget())
|| (_targetPairFlag && getOpCode().canUseRegPairForTarget()) ,
"OpCode [%s] %s use Register Pair for Target.\n",
getOpCode().getMnemonicName(),
(_targetPairFlag)?"cannot":"should");
}
virtual char *description() { return "S390RegInstruction"; }
virtual Kind getKind() { return IsReg; }
virtual bool isRegInstruction() { return true; }
void blockTargetRegister()
{
if (isTargetPair())
{
getFirstRegister()->block();
getLastRegister()->block();
}
else
getRegisterOperand(1)->block();
}
int8_t getFirstConstant() { return _firstConstant; }
void unblockTargetRegister()
{
if (isTargetPair())
{
getFirstRegister()->unblock();
getLastRegister()->unblock();
}
else
getRegisterOperand(1)->unblock();
}
// 'r' Could be a pair or not
// TR::Register *getTargetRegister() { return (_targetRegSize != 0) ? tgtRegArrElem(0) : NULL; }
// TR::Register *setTargetRegister(TR::Register *r) {assume0(_targetRegSize != 0); return (targetRegBase())[0] = r;}
/**
* Given that instruction expresses a register range (eg. LM or STM) the first and last register of the range
* is fetched from first operand as a register pair or from the first two operands
*/
TR::Register *getFirstRegister() {return _targetPairFlag? getRegisterOperand(1)->getHighOrder() : getRegisterOperand(1);}
TR::Register *getLastRegister() {return _targetPairFlag? getRegisterOperand(1)->getLowOrder():NULL;}
bool isTargetPair() { return _targetPairFlag; }
bool matchesTargetRegister(TR::Register* reg)
{
TR::RealRegister * realReg = NULL;
TR::RealRegister * targetReg1 = NULL;
TR::RealRegister * targetReg2 = NULL;
if (reg->getKind() != TR_FPR && reg->getKind() != TR_VRF && reg->getRealRegister())
{
realReg = toRealRegister(reg);
}
if (isTargetPair())
{
// if we are matching real regs
if (reg->getKind() != TR_FPR && reg->getKind() != TR_VRF && getFirstRegister()->getRealRegister())
{
targetReg1 = (TR::RealRegister *)getFirstRegister();
targetReg2 = toRealRegister(getLastRegister());
return realReg == targetReg1 || realReg == targetReg2;
}
// if we are matching virt regs
return reg == getFirstRegister() || reg == getLastRegister();
}
else if (getRegisterOperand(1))
{
// if we are matching real regs
if (reg->getKind() != TR_FPR && reg->getKind() != TR_VRF && getRegisterOperand(1)->getRealRegister())
{
targetReg1 = (TR::RealRegister *)getRegisterOperand(1);
return realReg == targetReg1;
}
// if we are matching virt regs
return reg == getRegisterOperand(1);
}
return false;
}
virtual uint8_t *generateBinaryEncoding();
virtual void assignRegistersNoDependencies(TR_RegisterKinds kindToBeAssigned);
virtual bool refsRegister(TR::Register *reg);
TR::InstOpCode::S390BranchCondition getBranchCondition() {return _branchCondition;}
TR::InstOpCode::S390BranchCondition setBranchCondition(TR::InstOpCode::S390BranchCondition branchCondition) {return _branchCondition = branchCondition;}
uint8_t getMask() {return getMaskForBranchCondition(getBranchCondition()) << 4;}
};
////////////////////////////////////////////////////////////////////////////////
// S390RRInstruction Class Definition
////////////////////////////////////////////////////////////////////////////////
class S390RRInstruction : public TR::S390RegInstruction
{
int8_t _secondConstant;
public:
S390RRInstruction(TR::InstOpCode::Mnemonic op,
TR::Node *n,
TR::Register *treg,
TR::CodeGenerator *cg)
: S390RegInstruction(op, n, treg, cg), _secondConstant(-1)
{
}
S390RRInstruction(TR::InstOpCode::Mnemonic op,
TR::Node *n,
TR::CodeGenerator *cg)
: S390RegInstruction(op, n, cg), _secondConstant(-1)
{
}
S390RRInstruction(TR::InstOpCode::Mnemonic op,
TR::Node *n,
TR::Register *treg,
TR::Register *sreg,
TR::CodeGenerator *cg)
: S390RegInstruction(op, n, treg, cg), _secondConstant(-1)
{
checkRegForGPR0Disable(op, sreg);
if (!getOpCode().setsOperand2())
useSourceRegister(sreg);
else
useTargetRegister(sreg);
}
S390RRInstruction(TR::InstOpCode::Mnemonic op,
TR::Node *n,
TR::Register *treg,
TR::Register *sreg,
TR::RegisterDependencyConditions * cond,
TR::CodeGenerator *cg)
: S390RegInstruction(op, n, treg, cond, cg), _secondConstant(-1)
{
checkRegForGPR0Disable(op, sreg);
if (!getOpCode().setsOperand2())
useSourceRegister(sreg);
else
useTargetRegister(sreg);
}
S390RRInstruction(TR::InstOpCode::Mnemonic op,
TR::Node *n,
TR::Register *treg,
TR::Register *sreg,
TR::Instruction *precedingInstruction,
TR::CodeGenerator *cg)
: S390RegInstruction(op, n, treg, precedingInstruction, cg), _secondConstant(-1)
{
checkRegForGPR0Disable(op, sreg);
if (!getOpCode().setsOperand2())
useSourceRegister(sreg);
else
useTargetRegister(sreg);
}
S390RRInstruction(TR::InstOpCode::Mnemonic op,
TR::Node *n,
TR::Register *treg,
int8_t secondConstant,
TR::Instruction *precedingInstruction,
TR::CodeGenerator *cg)
: S390RegInstruction(op, n, treg, precedingInstruction, cg), _secondConstant(secondConstant)
{
}
S390RRInstruction(TR::InstOpCode::Mnemonic op,
TR::Node *n,
TR::Register *treg,
int8_t secondConstant,
TR::CodeGenerator *cg)
: S390RegInstruction(op, n, treg, cg), _secondConstant(secondConstant)
{
}
S390RRInstruction(TR::InstOpCode::Mnemonic op,
TR::Node *n,
int8_t firstConstant,
int8_t secondConstant,
TR::Instruction *precedingInstruction,
TR::CodeGenerator *cg)
: S390RegInstruction(op, n, firstConstant, precedingInstruction, cg), _secondConstant(secondConstant)
{
}
S390RRInstruction(TR::InstOpCode::Mnemonic op,
TR::Node *n,
int8_t firstConstant,
int8_t secondConstant,
TR::CodeGenerator *cg)
: S390RegInstruction(op, n, firstConstant, cg), _secondConstant(secondConstant)
{
}
S390RRInstruction(TR::InstOpCode::Mnemonic op,
TR::Node *n,
int8_t firstConstant,
TR::Register *sreg,
TR::Instruction *precedingInstruction,
TR::CodeGenerator *cg)
: S390RegInstruction(op, n, firstConstant, precedingInstruction, cg), _secondConstant(-1)
{
checkRegForGPR0Disable(op,sreg);
if (!getOpCode().setsOperand2())
useSourceRegister(sreg);
else
useTargetRegister(sreg);
}
S390RRInstruction(TR::InstOpCode::Mnemonic op,
TR::Node *n,
int8_t firstConstant,
TR::Register *sreg,
TR::CodeGenerator *cg)
: S390RegInstruction(op, n, firstConstant, cg), _secondConstant(-1)
{
checkRegForGPR0Disable(op,sreg);
if (!getOpCode().setsOperand2())
useSourceRegister(sreg);
else
useTargetRegister(sreg);
}
S390RRInstruction(TR::InstOpCode::Mnemonic op,
TR::Node *n,
TR::Register *treg,
TR::Register *sreg,
TR::RegisterDependencyConditions * cond,
TR::Instruction *precedingInstruction,
TR::CodeGenerator *cg)
: S390RegInstruction(op, n, treg, cond, precedingInstruction, cg), _secondConstant(-1)
{
checkRegForGPR0Disable(op, sreg);
if (!getOpCode().setsOperand2())
useSourceRegister(sreg);
else
useTargetRegister(sreg);
}
S390RRInstruction(TR::InstOpCode::Mnemonic op,
TR::Node *n,
TR::Register *treg,
TR::Instruction *precedingInstruction,
TR::CodeGenerator *cg)
: S390RegInstruction(op, n, treg, precedingInstruction, cg), _secondConstant(-1)
{
}
virtual char *description() { return "S390RRInstruction"; }
virtual Kind getKind() { return IsRR; }
// TR::Register *getSourceRegister() {return (_sourceRegSize!=0) ? (sourceRegBase())[0] : NULL; }
// TR::Register *setSourceRegister(TR::Register *sr) { (sourceRegBase())[0] = sr; return sr; }
int8_t getSecondConstant() { return _secondConstant; }
virtual uint8_t *generateBinaryEncoding();
virtual bool refsRegister(TR::Register *reg);
};
////////////////////////////////////////////////////////////////////////////////
// S390TranslateInstruction Class Definition
// This currently includes TROO, TROT, TRTO, TRTT
////////////////////////////////////////////////////////////////////////////////
class S390TranslateInstruction : public TR::Instruction
{
private:
#define tr_srcidx 2
#define tr_tblidx 3
#define tr_termidx 4
#define tr_targidx 1
uint8_t _mask; ///< Mask for ETF-2
bool _isMaskPresent;
public:
/**
* There is no version -without- dependency conditions since at a minimum
* real register R0 and real register R1 will need to have been assigned to
* _termCharRegister and _tableRegister respectively
*/
S390TranslateInstruction(TR::InstOpCode::Mnemonic op,
TR::Node *n,
TR::Register *treg,
TR::Register *sreg,
TR::Register *tableReg,
TR::Register *termCharReg,
TR::RegisterDependencyConditions * cond,
TR::CodeGenerator *cg)
: TR::Instruction(op, n, cond, cg), _isMaskPresent(false)
{
if (!getOpCode().setsOperand1())
useSourceRegister(treg);
else
useTargetRegister(treg);
useSourceRegister(sreg);
useSourceRegister(tableReg);
useSourceRegister(termCharReg);
}
/** Add mask for ETF-2 TRxx instructions - RRE format */
S390TranslateInstruction(TR::InstOpCode::Mnemonic op,
TR::Node *n,
TR::Register *treg,
TR::Register *sreg,
TR::Register *tableReg,
TR::Register *termCharReg,
TR::RegisterDependencyConditions * cond,
TR::CodeGenerator *cg,
uint8_t mask)
: TR::Instruction(op, n, cond, cg), _mask(mask), _isMaskPresent(true)
{
if (!getOpCode().setsOperand1())
useSourceRegister(treg);
else
useTargetRegister(treg);
useSourceRegister(sreg);
useSourceRegister(tableReg);
useSourceRegister(termCharReg);
}
S390TranslateInstruction(TR::InstOpCode::Mnemonic op,
TR::Node *n,
TR::Register *treg,
TR::Register *sreg,
TR::Register *tableReg,
TR::Register *termCharReg,
TR::RegisterDependencyConditions * cond,
TR::Instruction *precedingInstruction,
TR::CodeGenerator *cg)
: TR::Instruction(op, n, cond, precedingInstruction, cg), _isMaskPresent(false)
{
if (!getOpCode().setsOperand1())
useSourceRegister(treg);
else
useTargetRegister(treg);
useSourceRegister(sreg);
useSourceRegister(tableReg);
useSourceRegister(termCharReg);
}
virtual char *description() { return "S390TranslateInstruction"; }
virtual Kind getKind() { return IsRRE; }
TR::Register *getTableRegister() {return getRegisterOperand(tr_tblidx); }
// TR::Register *setTableRegister(TR::Register* tableReg) {return (sourceRegBase())[tr_tblidx] = tableReg;}
TR::Register *getTermCharRegister() {return getRegisterOperand(tr_termidx); }
// TR::Register *setTermCharRegister(TR::Register* termCharReg) {return (sourceRegBase())[tr_termidx] = termCharReg;}
// TR::Register *getSourceRegister() {return (sourceRegBase())[tr_srcidx]; }
// TR::Register *setSourceRegister(TR::Register *sr) {return (sourceRegBase())[tr_srcidx] = sr;}
// TR::Register *getTargetRegister() { return (targetRegBase())[tr_targidx];}
// TR::Register *setTargetRegister(TR::Register *sr) { return (targetRegBase())[tr_targidx]=sr;}
virtual uint8_t *generateBinaryEncoding();
virtual bool refsRegister(TR::Register *reg);
bool isMaskPresent() {return _isMaskPresent;}
uint8_t getMask() {return _mask;}
uint8_t setMask(uint8_t mask) {return _mask = mask;}
};
////////////////////////////////////////////////////////////////////////////////
// S390RRFInstruction Class Definition
////////////////////////////////////////////////////////////////////////////////
class S390RRFInstruction : public TR::S390RRInstruction
{
bool _isMask3Present, _isMask4Present, _isSourceReg2Present;
bool _encodeAsRRD;
uint8_t _mask3, _mask4;
public:
S390RRFInstruction(bool encodeAsRRD,
TR::InstOpCode::Mnemonic op,
TR::Node *n,
TR::Register *treg,
TR::Register *sreg,
TR::Register *sreg2,
TR::CodeGenerator *cg)
: S390RRInstruction(op, n, treg, sreg, cg), _encodeAsRRD(encodeAsRRD),
_isSourceReg2Present(true), _isMask3Present(false), _isMask4Present(false)
{
if (!getOpCode().setsOperand3())
useSourceRegister(sreg2);
else
useTargetRegister(sreg2);
}
S390RRFInstruction(bool encodeAsRRD,
TR::InstOpCode::Mnemonic op,
TR::Node *n,
TR::Register *treg,
TR::Register *sreg,
TR::Register *sreg2,
TR::Instruction *precedingInstruction,
TR::CodeGenerator *cg)
: S390RRInstruction(op, n, treg, sreg, precedingInstruction, cg), _encodeAsRRD(encodeAsRRD),
_isSourceReg2Present(true), _isMask3Present(false),_isMask4Present(false)
{
if (!getOpCode().setsOperand3())
useSourceRegister(sreg2);
else
useTargetRegister(sreg2);
}
S390RRFInstruction(TR::InstOpCode::Mnemonic op,
TR::Node *n,
TR::Register *treg,
TR::Register *sreg,
TR::Register *sreg2,
TR::CodeGenerator *cg)
: S390RRInstruction(op, n, treg, sreg, cg), _encodeAsRRD(false),
_isSourceReg2Present(true), _isMask3Present(false), _isMask4Present(false)
{
if (!getOpCode().setsOperand3())
useSourceRegister(sreg2);
else
useTargetRegister(sreg2);
}
S390RRFInstruction(TR::InstOpCode::Mnemonic op,
TR::Node *n,
TR::Register *treg,
TR::Register *sreg,
uint8_t mask,
bool isMask3,
TR::CodeGenerator *cg)
: S390RRInstruction(op, n, treg, sreg, cg), _encodeAsRRD(false),
_isSourceReg2Present(false), _isMask3Present(isMask3),_isMask4Present(!isMask3)
{
if (isMask3)
_mask3 = mask;
else
_mask4 = mask;
}
S390RRFInstruction(TR::InstOpCode::Mnemonic op,
TR::Node *n,
uint8_t mask,
bool isMask3,
TR::CodeGenerator *cg)
: S390RRInstruction(op, n, cg), _encodeAsRRD(false),
_isMask3Present(isMask3), _isMask4Present(!isMask3), _isSourceReg2Present(false)
{
if (isMask3)
_mask3 = mask;
else
_mask4 = mask;
}
S390RRFInstruction(TR::InstOpCode::Mnemonic op,
TR::Node *n,
TR::Register *treg,
TR::Register *sreg,
uint8_t mask,
bool isMask3,
TR::RegisterDependencyConditions * cond,
TR::CodeGenerator *cg)
: S390RRInstruction(op, n, treg, sreg, cond, cg), _encodeAsRRD(false),
_isSourceReg2Present(false), _isMask3Present(isMask3),_isMask4Present(!isMask3)
{
if (isMask3)
_mask3 = mask;
else
_mask4 = mask;
}
S390RRFInstruction(TR::InstOpCode::Mnemonic op,
TR::Node *n,
TR::Register *treg,
TR::Register *sreg,
TR::Register *sreg2,
uint8_t mask,
TR::CodeGenerator *cg)
: S390RRInstruction(op, n, treg, sreg, cg), _encodeAsRRD(false),
_isSourceReg2Present(true), _isMask3Present(false),_isMask4Present(true),_mask4(mask)
{
if (!getOpCode().setsOperand3())
useSourceRegister(sreg2);
else
useTargetRegister(sreg2);
}
S390RRFInstruction(TR::InstOpCode::Mnemonic op,
TR::Node *n,
TR::Register *treg,
TR::Register *sreg,
TR::Register *sreg2,
TR::RegisterDependencyConditions * cond,
TR::CodeGenerator *cg)
: S390RRInstruction(op, n, treg, sreg, cond, cg), _encodeAsRRD(false),
_isSourceReg2Present(true), _isMask3Present(false),_isMask4Present(false)
{
if (!getOpCode().setsOperand3())
useSourceRegister(sreg2);
else
useTargetRegister(sreg2);
}
S390RRFInstruction(TR::InstOpCode::Mnemonic op,
TR::Node *n,
TR::Register *treg,
TR::Register *sreg,
TR::Register *sreg2,
TR::Instruction *precedingInstruction,
TR::CodeGenerator *cg)
: S390RRInstruction(op, n, treg, sreg, precedingInstruction, cg), _encodeAsRRD(false),
_isSourceReg2Present(true), _isMask3Present(false),_isMask4Present(false)
{
if (!getOpCode().setsOperand3())
useSourceRegister(sreg2);
else
useTargetRegister(sreg2);
}
S390RRFInstruction(TR::InstOpCode::Mnemonic op,
TR::Node *n,
TR::Register *treg,
TR::Register *sreg,
TR::Register *sreg2,
TR::RegisterDependencyConditions * cond,
TR::Instruction *precedingInstruction,
TR::CodeGenerator *cg)
: S390RRInstruction(op, n, treg, sreg, cond, precedingInstruction, cg), _encodeAsRRD(false),
_isSourceReg2Present(true), _isMask3Present(false),_isMask4Present(false)
{
if (!getOpCode().setsOperand3())
useSourceRegister(sreg2);
else
useTargetRegister(sreg2);
}
S390RRFInstruction(TR::InstOpCode::Mnemonic op,
TR::Node *n,
TR::Register *treg,
TR::Register *sreg,
uint8_t mask3,
uint8_t mask4,
TR::CodeGenerator *cg)
: S390RRInstruction(op, n, treg, sreg, cg),
_mask3(mask3),_mask4(mask4), _encodeAsRRD(false),
_isSourceReg2Present(false), _isMask3Present(true),_isMask4Present(true)
{
}
virtual char *description() { return "S390RRFInstruction"; }
virtual Kind getKind()
{
if (_encodeAsRRD)
return IsRRD;
if (_isMask3Present)
{
if (_isMask4Present)
return IsRRF5; // M3, M4, R1, R2
else
return IsRRF2; // M3, ., R1, R2
}
else if(_isMask4Present)
{
if (_isSourceReg2Present)
return IsRRF3; // R3, M4, R1, R2
else
return IsRRF4; // ., M4, R1, R2
}
else
return IsRRF; // R1, ., R3, R2
}
// TR::Register *getSourceRegister2() {return (_sourceRegSize==2) ? (sourceRegBase())[1] : NULL; }
// TR::Register *setSourceRegister2(TR::Register *sr) {return (sourceRegBase())[1]=sr;}
bool isSourceRegister2Present() {return _isSourceReg2Present;}
bool isMask3Present() {return _isMask3Present;}
bool isMask4Present() {return _isMask4Present;}
bool encodeAsRRD() {return _encodeAsRRD; }
uint8_t getMask() {TR_ASSERT(0, "RRF: getMask() is obsolete, use getMask3(..) or getMask4(..)\n"); return 0;}
uint8_t setMask(uint8_t mask) {TR_ASSERT(0, "RRF: setMask() is obsolete, use setMask3(..) or setMask4(..)\n"); return 0;}
uint8_t getMask3() {return _mask3;}
uint8_t setMask3(uint8_t mask) {return _mask3 = mask;}
uint8_t getMask4() {return _mask4;}
uint8_t setMask4(uint8_t mask) {return _mask4 = mask;}
virtual uint8_t *generateBinaryEncoding();
virtual bool refsRegister(TR::Register *reg);
};
////////////////////////////////////////////////////////////////////////////////
// S390RRRInstruction Class Definition
////////////////////////////////////////////////////////////////////////////////
class S390RRRInstruction : public TR::S390RRInstruction
{
#define rrr_srcidx 1
public:
S390RRRInstruction(TR::InstOpCode::Mnemonic op,
TR::Node *n,
TR::Register *treg,
TR::Register *sreg,
TR::Register *sreg2,
TR::CodeGenerator *cg)
: S390RRInstruction(op, n, treg, sreg, cg)
{
if (!getOpCode().setsOperand3())
useSourceRegister(sreg2);
else
useTargetRegister(sreg2);
}
S390RRRInstruction(TR::InstOpCode::Mnemonic op,
TR::Node *n,
TR::Register *treg,
TR::Register *sreg,
TR::Register *sreg2,
TR::RegisterDependencyConditions * cond,
TR::Instruction *precedingInstruction,
TR::CodeGenerator *cg)
: S390RRInstruction(op, n, treg, sreg, cond, precedingInstruction, cg)
{
if (!getOpCode().setsOperand3())
useSourceRegister(sreg2);
else
useTargetRegister(sreg2);
}
S390RRRInstruction(TR::InstOpCode::Mnemonic op,
TR::Node *n,
TR::Register *treg,
TR::Register *sreg,
TR::Register *sreg2,
TR::Instruction *precedingInstruction,
TR::CodeGenerator *cg)
: S390RRInstruction(op, n, treg, sreg, precedingInstruction, cg)
{
if (!getOpCode().setsOperand3())
useSourceRegister(sreg2);
else
useTargetRegister(sreg2);
}
virtual char *description() { return "S390RRRInstruction"; }
virtual Kind getKind()
{
return IsRRR;
}
// TR::Register *getSourceRegister2() {return (sourceRegBase())[rrr_srcidx];}
// TR::Register *setSourceRegister2(TR::Register *sr) {return (sourceRegBase())[rrr_srcidx]=sr;}
virtual uint8_t *generateBinaryEncoding();
virtual bool refsRegister(TR::Register *reg);
};
////////////////////////////////////////////////////////////////////////////////
// S390RIInstruction Class Definition
////////////////////////////////////////////////////////////////////////////////
class S390RIInstruction : public TR::S390RegInstruction
{
union
{
int32_t _sourceImmediate;
char* _namedDataField;
};
bool _isImm;
public:
S390RIInstruction(TR::InstOpCode::Mnemonic op, TR::Node *n,
TR::CodeGenerator *cg)
: S390RegInstruction(op, n, cg), _isImm(false), _sourceImmediate(0) {};
S390RIInstruction(TR::InstOpCode::Mnemonic op, TR::Node *n,
TR::Instruction *precedingInstruction,
TR::CodeGenerator *cg)
: S390RegInstruction(op, n, precedingInstruction, cg), _isImm(false), _sourceImmediate(0) {};
S390RIInstruction(TR::InstOpCode::Mnemonic op, TR::Node *n, TR::Register *treg,
TR::CodeGenerator *cg)
: S390RegInstruction(op, n, treg, cg), _isImm(false), _sourceImmediate(0) {};
S390RIInstruction(TR::InstOpCode::Mnemonic op, TR::Node *n, TR::Register *treg,
TR::Instruction *precedingInstruction,
TR::CodeGenerator *cg)
: S390RegInstruction(op, n, treg, precedingInstruction, cg), _isImm(false), _sourceImmediate(0) {};
S390RIInstruction(TR::InstOpCode::Mnemonic op, TR::Node *n, TR::Register *treg,
char *data,
TR::CodeGenerator *cg)
: S390RegInstruction(op, n, treg, cg), _namedDataField(data), _isImm(false) {};
S390RIInstruction(TR::InstOpCode::Mnemonic op, TR::Node *n, TR::Register *treg,
char *data,
TR::Instruction *precedingInstruction,
TR::CodeGenerator *cg)
: S390RegInstruction(op, n, treg, precedingInstruction, cg), _namedDataField(data), _isImm(false) {};
S390RIInstruction(TR::InstOpCode::Mnemonic op, TR::Node *n, TR::Register *treg,
int32_t imm,
TR::CodeGenerator *cg)
: S390RegInstruction(op, n, treg, cg), _sourceImmediate(imm), _isImm(true) {};
S390RIInstruction(TR::InstOpCode::Mnemonic op, TR::Node *n, TR::Register *treg,
int32_t imm,
TR::Instruction *precedingInstruction,
TR::CodeGenerator *cg)
: S390RegInstruction(op, n, treg, precedingInstruction, cg), _sourceImmediate(imm), _isImm(true) {};
virtual char *description() { return "S390RIInstruction"; }
virtual Kind getKind() { return IsRI; }
int32_t getSourceImmediate() {return _sourceImmediate;}
int32_t setSourceImmediate(int32_t si) {return _sourceImmediate = si;}
char* getDataField() {return _namedDataField;}
bool isImm() {return _isImm;}
virtual uint8_t *generateBinaryEncoding();
};
////////////////////////////////////////////////////////////////////////////////
// S390RILInstruction Class Definition
////////////////////////////////////////////////////////////////////////////////
class S390RILInstruction : public TR::Instruction
{
uint32_t _mask;
void *_targetPtr;
TR::Snippet *_targetSnippet;
TR::Symbol *_targetSymbol;
TR::LabelSymbol *_targetLabel;
flags8_t _flagsRIL;
TR::SymbolReference *_symbolReference;
/** _flagsRIL */
enum
{
isLiteralPoolAddressFlag = 0x01,
isImmediateOffsetInBytesFlag = 0x02
};
/** Use to store immediate value where the immediate is not used as a relative offset in address calculation.*/
uint32_t _sourceImmediate;
public:
S390RILInstruction(TR::InstOpCode::Mnemonic op, TR::Node * n, TR::Register *treg,
uint32_t imm,
TR::CodeGenerator *cg)
: TR::Instruction(op, n, cg), _targetPtr(NULL), _targetSnippet(NULL), _targetSymbol(NULL), _flagsRIL(0), _mask(0xffffffff), _targetLabel(NULL), _symbolReference(NULL), _sourceImmediate(imm)
{
TR_ASSERT_FATAL(getOpCode().isExtendedImmediate(), "Incorrect S390RILInstruction constructor used.\n"
"%s expects an address as the immediate but this constructor is for integer immediates.", getOpCode().getMnemonicName());
checkRegForGPR0Disable(op,treg);
if (!getOpCode().setsOperand1())
useSourceRegister(treg);
else
useTargetRegister(treg);
}
S390RILInstruction(TR::InstOpCode::Mnemonic op, TR::Node * n, TR::Register *treg,
int32_t imm,
TR::CodeGenerator *cg)
: TR::Instruction(op, n, cg), _targetPtr(NULL), _targetSnippet(NULL), _targetSymbol(NULL), _flagsRIL(0), _mask(0xffffffff), _targetLabel(NULL), _symbolReference(NULL), _sourceImmediate(imm)
{
TR_ASSERT_FATAL(getOpCode().isExtendedImmediate(), "Incorrect S390RILInstruction constructor used.\n"
"%s expects an address as the immediate but this constructor is for integer immediates.", getOpCode().getMnemonicName());
checkRegForGPR0Disable(op,treg);
if (!getOpCode().setsOperand1())
useSourceRegister(treg);
else
useTargetRegister(treg);
}
S390RILInstruction(TR::InstOpCode::Mnemonic op, TR::Node * n, TR::Register *treg,
void *targetPtr,
TR::CodeGenerator *cg)
: TR::Instruction(op, n, cg), _targetPtr(targetPtr), _targetSnippet(NULL), _targetSymbol(NULL), _flagsRIL(0), _mask(0xffffffff), _targetLabel(NULL), _symbolReference(NULL), _sourceImmediate(0)
{
TR_ASSERT_FATAL(!getOpCode().isExtendedImmediate(), "Incorrect S390RILInstruction constructor used.\n"
"%s expects an integer as the immediate but this constructor is for address immediates.", getOpCode().getMnemonicName());
checkRegForGPR0Disable(op,treg);
if (!getOpCode().setsOperand1())
useSourceRegister(treg);
else
useTargetRegister(treg);
}
S390RILInstruction(TR::InstOpCode::Mnemonic op, TR::Node * n, TR::Register *treg,
void *targetPtr,
TR::SymbolReference *sr,
TR::CodeGenerator *cg)
: TR::Instruction(op, n, cg), _targetPtr(targetPtr), _targetSnippet(NULL), _targetSymbol(NULL), _flagsRIL(0), _mask(0xffffffff), _targetLabel(NULL), _symbolReference(sr), _sourceImmediate(0)
{
checkRegForGPR0Disable(op,treg);
if (!getOpCode().setsOperand1())
useSourceRegister(treg);
else
useTargetRegister(treg);
}
S390RILInstruction(TR::InstOpCode::Mnemonic op, TR::Node * n, TR::Register *treg,
void *targetPtr,
TR::SymbolReference *sr,
TR::Instruction *precedingInstruction,
TR::CodeGenerator *cg)
: TR::Instruction(op, n, precedingInstruction, cg), _targetPtr(targetPtr), _targetSnippet(NULL), _targetSymbol(NULL), _flagsRIL(0), _mask(0xffffffff), _targetLabel(NULL), _symbolReference(sr), _sourceImmediate(0)
{
checkRegForGPR0Disable(op,treg);
if (!getOpCode().setsOperand1())
useSourceRegister(treg);
else
useTargetRegister(treg);
}
S390RILInstruction(TR::InstOpCode::Mnemonic op, TR::Node * n, TR::Register *treg,
uint32_t imm,
TR::Instruction *precedingInstruction,
TR::CodeGenerator *cg)
: TR::Instruction(op, n, precedingInstruction, cg), _targetPtr(NULL), _targetSnippet(NULL), _targetSymbol(NULL), _flagsRIL(0), _mask(0xffffffff), _targetLabel(NULL), _symbolReference(NULL), _sourceImmediate(imm)
{
TR_ASSERT_FATAL(getOpCode().isExtendedImmediate(), "Incorrect S390RILInstruction constructor used.\n"
"%s expects an adddress as the immediate but this constructor is for integer immediates.", getOpCode().getMnemonicName());
checkRegForGPR0Disable(op,treg);
if (!getOpCode().setsOperand1())
useSourceRegister(treg);
else
useTargetRegister(treg);
}
S390RILInstruction(TR::InstOpCode::Mnemonic op, TR::Node * n, TR::Register *treg,
int32_t imm,
TR::Instruction *precedingInstruction,
TR::CodeGenerator *cg)
: TR::Instruction(op, n, precedingInstruction, cg), _targetPtr(NULL), _targetSnippet(NULL), _targetSymbol(NULL), _flagsRIL(0), _mask(0xffffffff), _targetLabel(NULL), _symbolReference(NULL), _sourceImmediate(imm)
{
TR_ASSERT_FATAL(getOpCode().isExtendedImmediate(), "Incorrect S390RILInstruction constructor used.\n"
"%s expects an address as the immediate but this constructor is for integer immediates.", getOpCode().getMnemonicName());
checkRegForGPR0Disable(op,treg);
if (!getOpCode().setsOperand1())
useSourceRegister(treg);
else
useTargetRegister(treg);
}
S390RILInstruction(TR::InstOpCode::Mnemonic op, TR::Node * n, TR::Register *treg,
void *targetPtr,
TR::Instruction *precedingInstruction,
TR::CodeGenerator *cg)
: TR::Instruction(op, n, precedingInstruction, cg), _targetPtr(targetPtr), _targetSnippet(NULL), _targetSymbol(NULL), _flagsRIL(0), _mask(0xffffffff), _targetLabel(NULL), _symbolReference(NULL), _sourceImmediate(0)
{
TR_ASSERT_FATAL(!getOpCode().isExtendedImmediate(), "Incorrect S390RILInstruction constructor used.\n"
"%s expects an address as the immediate but this constructor is for integer immediates.", getOpCode().getMnemonicName());
checkRegForGPR0Disable(op,treg);
if (!getOpCode().setsOperand1())
useSourceRegister(treg);
else
useTargetRegister(treg);
}
/** For TR::InstOpCode::BRCL */
S390RILInstruction(TR::InstOpCode::Mnemonic op, TR::Node * n, TR::Register *treg,
TR::Snippet *ts,
TR::CodeGenerator *cg)
: TR::Instruction(op, n, cg), _targetPtr(NULL), _targetSnippet(ts), _targetSymbol(NULL), _flagsRIL(0), _mask(0xffffffff), _targetLabel(NULL), _symbolReference(NULL), _sourceImmediate(0)
{
checkRegForGPR0Disable(op,treg);
if (!getOpCode().setsOperand1())
useSourceRegister(treg);
else
useTargetRegister(treg);
}
S390RILInstruction(TR::InstOpCode::Mnemonic op, TR::Node * n, uint32_t mask,
void *targetPtr,
TR::CodeGenerator *cg)
: TR::Instruction(op, n, cg), _targetPtr(targetPtr), _targetSnippet(NULL), _targetSymbol(NULL), _flagsRIL(0), _mask(mask), _targetLabel(NULL), _symbolReference(NULL), _sourceImmediate(0)
{
}
S390RILInstruction(TR::InstOpCode::Mnemonic op, TR::Node * n, uint32_t mask,
TR::Snippet *ts,
TR::CodeGenerator *cg)
: TR::Instruction(op, n, cg), _targetPtr(NULL), _targetSnippet(ts), _targetSymbol(NULL), _flagsRIL(0), _mask(mask), _targetLabel(NULL), _symbolReference(NULL), _sourceImmediate(0)
{
}
S390RILInstruction(TR::InstOpCode::Mnemonic op, TR::Node * n, TR::Register *treg,
TR::Snippet *ts,
TR::Instruction *precedingInstruction,
TR::CodeGenerator *cg)
: TR::Instruction(op, n, precedingInstruction, cg), _targetPtr(NULL), _targetSnippet(ts), _targetSymbol(NULL), _flagsRIL(0), _mask(0xffffffff), _targetLabel(NULL), _symbolReference(NULL), _sourceImmediate(0)
{
checkRegForGPR0Disable(op,treg);
if (!getOpCode().setsOperand1())
useSourceRegister(treg);
else
useTargetRegister(treg);
}
S390RILInstruction(TR::InstOpCode::Mnemonic op, TR::Node * n, uint32_t mask,
void *targetPtr,
TR::Instruction *precedingInstruction,
TR::CodeGenerator *cg)
: TR::Instruction(op, n, precedingInstruction, cg), _targetPtr(targetPtr), _targetSnippet(NULL), _targetSymbol(NULL), _flagsRIL(0), _mask(mask), _targetLabel(NULL), _symbolReference(NULL), _sourceImmediate(0)
{
}
/** For TR::InstOpCode::BRASL */
S390RILInstruction(TR::InstOpCode::Mnemonic op, TR::Node * n, TR::Register *treg,
TR::Snippet *ts,
TR::RegisterDependencyConditions *cond,
TR::CodeGenerator *cg)
: TR::Instruction(op, n, cond, cg), _targetPtr(NULL), _targetSnippet(ts), _targetSymbol(NULL), _flagsRIL(0), _mask(0xffffffff), _targetLabel(NULL) ,_symbolReference(NULL), _sourceImmediate(0)
{
checkRegForGPR0Disable(op,treg);
if (!getOpCode().setsOperand1())
useSourceRegister(treg);
else
useTargetRegister(treg);
}
S390RILInstruction(TR::InstOpCode::Mnemonic op, TR::Node * n, TR::Register *treg,
TR::Snippet *ts,
TR::RegisterDependencyConditions *cond,
TR::SymbolReference *sr,
TR::CodeGenerator *cg)
: TR::Instruction(op, n, cond, cg), _targetPtr(NULL), _targetSnippet(ts), _targetSymbol(NULL), _flagsRIL(0), _mask(0xffffffff), _targetLabel(NULL), _symbolReference(sr), _sourceImmediate(0)
{
checkRegForGPR0Disable(op,treg);
if (!getOpCode().setsOperand1())
useSourceRegister(treg);
else
useTargetRegister(treg);
}
S390RILInstruction(TR::InstOpCode::Mnemonic op, TR::Node * n, uint32_t mask,
TR::Snippet *ts,
TR::RegisterDependencyConditions *cond,
TR::CodeGenerator *cg)
: TR::Instruction(op, n, cond, cg), _targetPtr(NULL), _targetSnippet(ts), _targetSymbol(NULL), _flagsRIL(0), _mask(mask), _targetLabel(NULL), _symbolReference(NULL), _sourceImmediate(0)
{
}
S390RILInstruction(TR::InstOpCode::Mnemonic op, TR::Node * n, TR::Register *treg,
void *targetPtr,
TR::RegisterDependencyConditions *cond,
TR::CodeGenerator *cg)
: TR::Instruction(op, n, cond, cg), _targetPtr(targetPtr), _targetSnippet(NULL), _targetSymbol(NULL), _flagsRIL(0), _mask(0xffffffff), _targetLabel(NULL), _symbolReference(NULL), _sourceImmediate(0)
{
checkRegForGPR0Disable(op,treg);
if (!getOpCode().setsOperand1())
useSourceRegister(treg);
else
useTargetRegister(treg);
}
S390RILInstruction(TR::InstOpCode::Mnemonic op, TR::Node * n, TR::Register *treg,
TR::Symbol *sym,
TR::RegisterDependencyConditions *cond,
TR::CodeGenerator *cg)
: TR::Instruction(op, n, cond, cg), _targetPtr(NULL), _targetSnippet(NULL), _targetSymbol(sym), _flagsRIL(0), _mask(0xffffffff), _targetLabel(NULL), _symbolReference(NULL), _sourceImmediate(0)
{
checkRegForGPR0Disable(op,treg);
if (!getOpCode().setsOperand1())
useSourceRegister(treg);
else
useTargetRegister(treg);
if (sym->isLabel())
_targetLabel = sym->castToLabelSymbol();
}
S390RILInstruction(TR::InstOpCode::Mnemonic op, TR::Node * n, TR::Register *treg,
TR::Symbol *sym,
TR::CodeGenerator *cg)
: TR::Instruction(op, n, cg), _targetPtr(NULL), _targetSnippet(NULL), _targetSymbol(sym), _flagsRIL(0), _mask(0xffffffff), _targetLabel(NULL), _symbolReference(NULL), _sourceImmediate(0)
{
checkRegForGPR0Disable(op,treg);
useTargetRegister(treg);
if (sym->isLabel())
_targetLabel = sym->castToLabelSymbol();
}
S390RILInstruction(TR::InstOpCode::Mnemonic op, TR::Node * n, TR::Register *treg,
TR::Symbol *sym,
TR::SymbolReference *sr,
TR::CodeGenerator *cg)
: TR::Instruction(op, n, cg), _targetPtr(NULL), _targetSnippet(NULL), _targetSymbol(sym), _flagsRIL(0), _mask(0xffffffff), _targetLabel(NULL), _symbolReference(sr), _sourceImmediate(0)
{
checkRegForGPR0Disable(op,treg);
if (!getOpCode().setsOperand1())
useSourceRegister(treg);
else
useTargetRegister(treg);
if (sym->isLabel())
_targetLabel = sym->castToLabelSymbol();
}
S390RILInstruction(TR::InstOpCode::Mnemonic op, TR::Node * n, TR::Register *treg,
TR::Symbol *sym,
TR::SymbolReference *sr,
TR::RegisterDependencyConditions *cond,
TR::CodeGenerator *cg)
: TR::Instruction(op, n, cond, cg), _targetPtr(NULL), _targetSnippet(NULL), _targetSymbol(sym), _flagsRIL(0), _mask(0xffffffff), _targetLabel(NULL), _symbolReference(sr), _sourceImmediate(0)
{
checkRegForGPR0Disable(op,treg);
if (!getOpCode().setsOperand1())
useSourceRegister(treg);
else
useTargetRegister(treg);
if (sym->isLabel())
_targetLabel = sym->castToLabelSymbol();
}
S390RILInstruction(TR::InstOpCode::Mnemonic op, TR::Node * n, TR::Register *treg,
TR::Symbol *sym,
TR::SymbolReference *sr,
TR::Instruction *precedingInstruction,
TR::CodeGenerator *cg)
: TR::Instruction(op, n, precedingInstruction, cg), _targetPtr(NULL), _targetSnippet(NULL), _targetSymbol(sym), _flagsRIL(0), _mask(0xffffffff), _targetLabel(NULL), _symbolReference(sr), _sourceImmediate(0)
{
checkRegForGPR0Disable(op,treg);
if (!getOpCode().setsOperand1())
useSourceRegister(treg);
else
useTargetRegister(treg);
if (sym->isLabel())
_targetLabel = sym->castToLabelSymbol();
}
/** For PFDRL */
S390RILInstruction(TR::InstOpCode::Mnemonic op, TR::Node * n, uint32_t mask,
TR::Symbol *sym,
TR::SymbolReference *sr,
TR::CodeGenerator *cg)
: TR::Instruction(op, n, cg), _targetPtr(NULL), _targetSnippet(NULL), _targetSymbol(sym), _flagsRIL(0), _mask(mask), _targetLabel(NULL), _symbolReference(sr), _sourceImmediate(0)
{
if (sym->isLabel())
_targetLabel = sym->castToLabelSymbol();
}
S390RILInstruction(TR::InstOpCode::Mnemonic op, TR::Node * n, uint32_t mask,
TR::Symbol *sym,
TR::SymbolReference *sr,
TR::Instruction *precedingInstruction,
TR::CodeGenerator *cg)
: TR::Instruction(op, n, precedingInstruction, cg), _targetPtr(NULL), _targetSnippet(NULL), _targetSymbol(sym), _flagsRIL(0), _mask(mask), _targetLabel(NULL), _symbolReference(sr), _sourceImmediate(0)
{
if (sym->isLabel())
_targetLabel = sym->castToLabelSymbol();
}
S390RILInstruction(TR::InstOpCode::Mnemonic op, TR::Node * n, TR::Register *treg,
TR::LabelSymbol *label,
TR::CodeGenerator *cg)
: TR::Instruction(op, n, cg), _targetPtr(NULL), _targetSnippet(NULL), _targetSymbol(NULL), _flagsRIL(0), _mask(0xffffffff), _targetLabel(label), _symbolReference(NULL), _sourceImmediate(0)
{
checkRegForGPR0Disable(op,treg);
if (!getOpCode().setsOperand1())
useSourceRegister(treg);
else
useTargetRegister(treg);
}
S390RILInstruction(TR::InstOpCode::Mnemonic op, TR::Node * n, TR::Register *treg,
TR::LabelSymbol *label,
TR::Instruction *precedingInstruction,
TR::CodeGenerator *cg)
: TR::Instruction(op, n, precedingInstruction, cg), _targetPtr(NULL), _targetSnippet(NULL), _targetSymbol(NULL), _flagsRIL(0), _mask(0xffffffff), _targetLabel(label), _symbolReference(NULL), _sourceImmediate(0)
{
checkRegForGPR0Disable(op,treg);
if (!getOpCode().setsOperand1())
useSourceRegister(treg);
else
useTargetRegister(treg);
}
virtual char *description() { return "S390RILInstruction"; }
virtual Kind getKind() { return IsRIL; }
bool isLiteralPoolAddress() {return _flagsRIL.testAny(isLiteralPoolAddressFlag); }
void setIsLiteralPoolAddress() { _flagsRIL.set(isLiteralPoolAddressFlag);}
bool isImmediateOffsetInBytes() {return _flagsRIL.testAny(isImmediateOffsetInBytesFlag); }
void setIsImmediateOffsetInBytes() { _flagsRIL.set(isImmediateOffsetInBytesFlag);}
uintptrj_t getTargetPtr()
{ return reinterpret_cast<uintptrj_t>(_targetPtr); }
uintptrj_t setTargetPtr(uintptrj_t tp)
{ TR_ASSERT(!isImmediateOffsetInBytes(), "Immediate Offset already set on RIL instruction."); _targetPtr = reinterpret_cast<void*>(tp); return tp; }
uintptrj_t getImmediateOffsetInBytes()
{ TR_ASSERT(isImmediateOffsetInBytes(), "Immediate Offset not set for RIL Instruction."); return reinterpret_cast<uintptrj_t>(_targetPtr); }
uintptrj_t setImmediateOffsetInBytes(uintptrj_t tp)
{ setIsImmediateOffsetInBytes(); _targetPtr = reinterpret_cast<void*>(tp); return tp; }
TR::Snippet *getTargetSnippet()
{ return _targetSnippet; }
TR::Snippet *setTargetSnippet(TR::Snippet *ts)
{ return _targetSnippet = ts; }
TR::Symbol *getTargetSymbol()
{ return _targetSymbol; }
TR::LabelSymbol *getTargetLabel()
{ return _targetLabel; }
TR::Symbol *setTargetSymbol(TR::Symbol *sym)
{ return _targetSymbol = sym; }
uint32_t getMask()
{ return _mask; }
TR::SymbolReference *getSymbolReference() {return _symbolReference;}
TR::SymbolReference *setSymbolReference(TR::SymbolReference *sr)
{ return _symbolReference = sr; }
// TR::Register *getTargetRegister() { return (_targetRegSize!=0) ? (targetRegBase())[0] : NULL;}
// TR::Register *setTargetRegister(TR::Register *r) { assume0(_targetRegSize!=0); (targetRegBase())[0] = r; return r; }
bool matchesTargetRegister(TR::Register* reg)
{
TR::RealRegister * realReg = NULL;
TR::RealRegister * targetReg = NULL;
if (reg->getKind() != TR_FPR && reg->getKind() != TR_VRF && reg->getRealRegister())
{
realReg = (TR::RealRegister *)reg;
}
// if we are matching real regs
if (reg->getKind() != TR_FPR && reg->getKind() != TR_VRF && getRegisterOperand(1) && getRegisterOperand(1)->getRealRegister())
{
targetReg = (TR::RealRegister *)getRegisterOperand(1);
return realReg == targetReg;
}
// if we are matching virt regs
return reg == getRegisterOperand(1);
}
bool refsRegister(TR::Register *reg);
virtual int32_t estimateBinaryLength(int32_t currentEstimate);
virtual uint8_t *generateBinaryEncoding();
// Get value from extended immediate instructions
int32_t getSourceImmediate() {return _sourceImmediate;}
int32_t setSourceImmediate(int32_t si) {return _sourceImmediate = si;}
int32_t adjustCallOffsetWithTrampoline(int32_t offset, uint8_t * currentInst);
};
////////////////////////////////////////////////////////////////////////////////
// S390RSInstruction Class Definition
////////////////////////////////////////////////////////////////////////////////
class S390RSInstruction : public TR::S390RegInstruction
{
protected:
int16_t _sourceImmediate;
int8_t _maskImmediate;
/// Set to true if a mask value was specified during the construction of this object, indicating an RS instruction of RS-b format
/// where the third operand is a mask
bool _hasMaskImmediate;
/// Set to true if a mask value was specified during the construction of this object, indicating an RS instruction of RS-b format
/// where the third operand is a mask
bool _hasSourceImmediate;
int8_t _idx;
public:
/**
* RS instruction with R1,D2(0) format
* e.g. SLL R1,12(0) - shifting R1 with constant value 12 and the value is < 4K
* in this case, base register doesn't need to be set
*/
S390RSInstruction(TR::InstOpCode::Mnemonic op,
TR::Node *n,
TR::Register *treg,
uint32_t imm,
TR::CodeGenerator *cg)
: S390RegInstruction(op, n, treg, cg), _sourceImmediate(imm), _maskImmediate(0), _idx(-1), _hasMaskImmediate(false), _hasSourceImmediate(true)
{
// 1 Register is specified - If it is not a register pair, make sure instruction doesn't take a range (i.e. STM).
TR_ASSERT(treg->getRegisterPair() || !getOpCode().usesRegRangeForTarget(),
"OpCode [%s] requires a register range.\n",
getOpCode().getMnemonicName());
};
S390RSInstruction(TR::InstOpCode::Mnemonic op,
TR::Node *n,
TR::Register *treg,
uint32_t imm,
TR::Instruction *precedingInstruction,
TR::CodeGenerator *cg)
: S390RegInstruction(op, n, treg, precedingInstruction, cg),
_sourceImmediate(imm), _maskImmediate(0), _idx(-1), _hasMaskImmediate(false), _hasSourceImmediate(true)
{
// 1 Register is specified - If it is not a register pair, make sure instruction doesn't take a range (i.e. STM).
TR_ASSERT(treg->getRegisterPair() || !getOpCode().usesRegRangeForTarget(),
"OpCode [%s] requires a register range.\n",
getOpCode().getMnemonicName());
};
S390RSInstruction(TR::InstOpCode::Mnemonic op,
TR::Node *n,
TR::Register *treg,
uint32_t imm,
TR::RegisterDependencyConditions *_conditions,
TR::CodeGenerator *cg)
: S390RegInstruction(op, n, treg, _conditions, cg), _sourceImmediate(imm), _maskImmediate(0), _idx(-1), _hasMaskImmediate(false), _hasSourceImmediate(true)
{
// 1 Register is specified - If it is not a register pair, make sure instruction doesn't take a range (i.e. STM).
TR_ASSERT(treg->getRegisterPair() || !getOpCode().usesRegRangeForTarget(),
"OpCode [%s] requires a register range.\n",
getOpCode().getMnemonicName());
};
S390RSInstruction(TR::InstOpCode::Mnemonic op,
TR::Node *n,
TR::Register *treg,
uint32_t imm,
TR::RegisterDependencyConditions *_conditions,
TR::Instruction *precedingInstruction,
TR::CodeGenerator *cg)
: S390RegInstruction(op, n, treg, _conditions, precedingInstruction, cg),
_sourceImmediate(imm), _maskImmediate(0), _idx(-1), _hasMaskImmediate(false), _hasSourceImmediate(true)
{
// 1 Register is specified - If it is not a register pair, make sure instruction doesn't take a range (i.e. STM).
TR_ASSERT(treg->getRegisterPair() || !getOpCode().usesRegRangeForTarget(),
"OpCode [%s] requires a register range.\n",
getOpCode().getMnemonicName());
};
// RS instruction with R1,D2(B2) format
S390RSInstruction(TR::InstOpCode::Mnemonic op,
TR::Node *n,
TR::Register *treg,
TR::MemoryReference *mf,
TR::CodeGenerator *cg)
: S390RegInstruction(op, n, treg, cg), _sourceImmediate(0), _maskImmediate(0), _idx(-1), _hasMaskImmediate(false), _hasSourceImmediate(false)
{
useSourceMemoryReference(mf);
setupThrowsImplicitNullPointerException(n,mf);
if (mf->getUnresolvedSnippet() != NULL)
(mf->getUnresolvedSnippet())->setDataReferenceInstruction(this);
// 1 Register is specified - If it is not a register pair, make sure instruction doesn't take a range (i.e. STM).
TR_ASSERT(treg->getRegisterPair() || !getOpCode().usesRegRangeForTarget(),
"OpCode [%s] requires a register range.\n",
getOpCode().getMnemonicName());
}
S390RSInstruction(TR::InstOpCode::Mnemonic op,
TR::Node *n,
TR::Register *treg,
TR::MemoryReference *mf,
TR::Instruction *precedingInstruction,
TR::CodeGenerator *cg)
: S390RegInstruction(op, n, treg, precedingInstruction, cg),
_sourceImmediate(0), _maskImmediate(0), _idx(-1), _hasMaskImmediate(false), _hasSourceImmediate(false)
{
useSourceMemoryReference(mf);
setupThrowsImplicitNullPointerException(n,mf);
if (mf->getUnresolvedSnippet() != NULL)
(mf->getUnresolvedSnippet())->setDataReferenceInstruction(this);
// 1 Register is specified - If it is not a register pair, make sure instruction doesn't take a range (i.e. STM).
TR_ASSERT(treg->getRegisterPair() || !getOpCode().usesRegRangeForTarget(),
"OpCode [%s] requires a register range.\n",
getOpCode().getMnemonicName());
}
/** Used for ICM instruction */
S390RSInstruction(TR::InstOpCode::Mnemonic op,
TR::Node *n,
TR::Register *treg,
uint32_t mask,
TR::MemoryReference *mf,
TR::Instruction *precedingInstruction,
TR::CodeGenerator *cg)
: S390RegInstruction(op, n, treg, precedingInstruction, cg),
_sourceImmediate(0), _maskImmediate(mask), _idx(-1), _hasMaskImmediate(true), _hasSourceImmediate(false)
{
useSourceMemoryReference(mf);
setupThrowsImplicitNullPointerException(n,mf);
if (mf->getUnresolvedSnippet() != NULL)
(mf->getUnresolvedSnippet())->setDataReferenceInstruction(this);
// 1 Register is specified - If it is not a register pair, make sure instruction doesn't take a range (i.e. STM).
TR_ASSERT(treg->getRegisterPair() || !getOpCode().usesRegRangeForTarget(),
"OpCode [%s] requires a register range.\n",
getOpCode().getMnemonicName());
}
/** Used for ICM instruction */
S390RSInstruction(TR::InstOpCode::Mnemonic op,
TR::Node *n,
TR::Register *treg,
uint32_t mask,
TR::MemoryReference *mf,
TR::CodeGenerator *cg)
: S390RegInstruction(op, n, treg, cg),
_sourceImmediate(0), _maskImmediate(mask), _idx(-1), _hasMaskImmediate(true), _hasSourceImmediate(false)
{
useSourceMemoryReference(mf);
setupThrowsImplicitNullPointerException(n,mf);
if (mf->getUnresolvedSnippet() != NULL)
(mf->getUnresolvedSnippet())->setDataReferenceInstruction(this);
}
/**
* Used for range of registers STM R1,R2 (R2!=R1+1)
* also for SLLG, SLAG, SRLG for 64bit codegen
*/
S390RSInstruction(TR::InstOpCode::Mnemonic op,
TR::Node *n,
TR::Register *freg,
TR::Register *lreg,
TR::MemoryReference *mf,
TR::CodeGenerator *cg)
: S390RegInstruction(op, n, freg, cg), _sourceImmediate(0), _maskImmediate(0), _idx(-1), _hasMaskImmediate(false), _hasSourceImmediate(false)
{
if (getOpCode().setsOperand2())
useTargetRegister(lreg);
else
useSourceRegister(lreg);
useSourceMemoryReference(mf);
setupThrowsImplicitNullPointerException(n,mf);
if (mf->getUnresolvedSnippet() != NULL)
(mf->getUnresolvedSnippet())->setDataReferenceInstruction(this);
}
S390RSInstruction(TR::InstOpCode::Mnemonic op,
TR::Node *n,
TR::Register *freg,
TR::Register *lreg,
TR::MemoryReference *mf,
TR::Instruction *precedingInstruction,
TR::CodeGenerator *cg)
: S390RegInstruction(op, n, freg, precedingInstruction, cg), _sourceImmediate(0), _maskImmediate(0), _idx(-1), _hasMaskImmediate(false), _hasSourceImmediate(false)
{
if (getOpCode().setsOperand2())
useTargetRegister(lreg);
else
useSourceRegister(lreg);
useSourceMemoryReference(mf);
setupThrowsImplicitNullPointerException(n,mf);
if (mf->getUnresolvedSnippet() != NULL)
(mf->getUnresolvedSnippet())->setDataReferenceInstruction(this);
}
/** Used specifically for consecutive even-odd pairs (STM,LM) */
S390RSInstruction(TR::InstOpCode::Mnemonic op,
TR::Node *n,
TR::RegisterPair *regp,
TR::MemoryReference *mf,
TR::CodeGenerator *cg)
: S390RegInstruction(op, n, regp, cg), _sourceImmediate(0), _maskImmediate(0), _idx(-1), _hasMaskImmediate(false), _hasSourceImmediate(false)
{
useSourceMemoryReference(mf);
setupThrowsImplicitNullPointerException(n,mf);
if (mf->getUnresolvedSnippet() != NULL)
(mf->getUnresolvedSnippet())->setDataReferenceInstruction(this);
}
S390RSInstruction(TR::InstOpCode::Mnemonic op,
TR::Node *n,
TR::RegisterPair *regp,
TR::MemoryReference *mf,
TR::Instruction *precedingInstruction,
TR::CodeGenerator *cg)
: S390RegInstruction(op, n, regp, precedingInstruction, cg), _sourceImmediate(0), _maskImmediate(0), _idx(-1), _hasMaskImmediate(false), _hasSourceImmediate(false)
{
useSourceMemoryReference(mf);
setupThrowsImplicitNullPointerException(n,mf);
if (mf->getUnresolvedSnippet() != NULL)
(mf->getUnresolvedSnippet())->setDataReferenceInstruction(this);
}
/** Used specifically for source/target consecutive even-odd pairs (CLCLE,MVCLE)*/
S390RSInstruction(TR::InstOpCode::Mnemonic op,
TR::Node *n,
TR::RegisterPair *regp,
TR::RegisterPair *regp2,
TR::MemoryReference *mf,
TR::CodeGenerator *cg)
: S390RegInstruction(op, n, regp, cg), _sourceImmediate(0), _maskImmediate(0), _idx(-1), _hasMaskImmediate(false), _hasSourceImmediate(false)
{
if (getOpCode().setsOperand2())
useTargetRegister(regp2);
else
useSourceRegister(regp2);
useSourceMemoryReference(mf);
setupThrowsImplicitNullPointerException(n,mf);
if (mf->getUnresolvedSnippet() != NULL)
mf->getUnresolvedSnippet()->setDataReferenceInstruction(this);
}
S390RSInstruction(TR::InstOpCode::Mnemonic op,
TR::Node *n,
TR::RegisterPair *regp,
TR::RegisterPair *regp2,
TR::MemoryReference *mf,
TR::Instruction *precedingInstruction,
TR::CodeGenerator *cg)
: S390RegInstruction(op, n, regp, precedingInstruction, cg), _sourceImmediate(0), _maskImmediate(0), _idx(-1), _hasMaskImmediate(false), _hasSourceImmediate(false)
{
if (getOpCode().setsOperand2())
useTargetRegister(regp2);
else
useSourceRegister(regp2);
useSourceMemoryReference(mf);
setupThrowsImplicitNullPointerException(n,mf);
if (mf->getUnresolvedSnippet() != NULL)
(mf->getUnresolvedSnippet())->setDataReferenceInstruction(this);
}
/** For 64bit code-gen SLLG, SLAG, SRLG */
S390RSInstruction(TR::InstOpCode::Mnemonic op,
TR::Node *n,
TR::Register *treg,
TR::Register *sreg,
uint32_t imm,
TR::CodeGenerator *cg)
: S390RegInstruction(op, n, treg, cg), _sourceImmediate(imm), _maskImmediate(0), _idx(-1), _hasMaskImmediate(false), _hasSourceImmediate(true)
{
if (getOpCode().setsOperand2())
useTargetRegister(sreg);
else
useSourceRegister(sreg);
};
S390RSInstruction(TR::InstOpCode::Mnemonic op,
TR::Node *n,
TR::Register *treg,
TR::Register *sreg,
uint32_t imm,
TR::Instruction *precedingInstruction,
TR::CodeGenerator *cg)
: S390RegInstruction(op, n, treg, precedingInstruction, cg),
_sourceImmediate(imm), _maskImmediate(0), _idx(-1), _hasMaskImmediate(false), _hasSourceImmediate(true)
{
if (getOpCode().setsOperand2())
useTargetRegister(sreg);
else
useSourceRegister(sreg);
};
virtual char *description() { return "S390RSInstruction"; }
virtual Kind getKind() {return IsRS;}
uint32_t getSourceImmediate() {return _sourceImmediate;}
uint32_t setSourceImmediate(uint32_t si) {return _sourceImmediate = si;}
uint32_t getMaskImmediate() {return _maskImmediate;}
uint32_t setMaskImmediate(uint32_t mi) {return _maskImmediate = mi;}
/// Determines whether a mask value was specified during the construction of this object, indicating an RS instruction of RS-b format
/// where the third operand is a mask
bool hasMaskImmediate() {return _hasMaskImmediate;}
/// Determines whether a mask value was specified during the construction of this object, indicating an RS instruction of RS-b format
/// where the third operand is a mask
bool hasSourceImmediate() {return _hasSourceImmediate;}
TR::Register* getFirstRegister() { return isTargetPair()? S390RegInstruction::getFirstRegister() : getRegisterOperand(1); }
TR::Register* getLastRegister() { return isTargetPair()? S390RegInstruction::getLastRegister() : getRegisterOperand(2); }
TR::Register* getSecondRegister() {return getRegisterOperand(2); }
virtual TR::MemoryReference* getMemoryReference() { return (_sourceMemSize!=0) ? (sourceMemBase())[0] : NULL; }
virtual uint8_t *generateBinaryEncoding();
virtual int32_t estimateBinaryLength(int32_t currentEstimate);
void generateAdditionalSourceRegisters(TR::Register *, TR::Register *);
};
////////////////////////////////////////////////////////////////////////////////
// S390RSWithImplicitPairStoresInstruction Class Definition
////////////////////////////////////////////////////////////////////////////////
/**
* @todo complex source <-> target copies
*/
class S390RSWithImplicitPairStoresInstruction : public TR::S390RSInstruction
{
public:
/** Used specifically for source/target consecutive even-odd pairs (CLCLE,MVCLE)*/
S390RSWithImplicitPairStoresInstruction(TR::InstOpCode::Mnemonic op,
TR::Node *n,
TR::RegisterPair *regp,
TR::RegisterPair *regp2,
TR::MemoryReference *mf,
TR::CodeGenerator *cg)
: S390RSInstruction(op, n, regp, regp2, mf, cg)
{
}
S390RSWithImplicitPairStoresInstruction(TR::InstOpCode::Mnemonic op,
TR::Node *n,
TR::RegisterPair *regp,
TR::RegisterPair *regp2,
TR::MemoryReference *mf,
TR::Instruction *precedingInstruction,
TR::CodeGenerator *cg)
: S390RSInstruction(op, n, regp, regp2, mf, precedingInstruction, cg)
{
}
void swap_operands(int i,int j) { void *op1 = _operands[i]; _operands[i]=_operands[j]; _operands[j]=op1; }
};
////////////////////////////////////////////////////////////////////////////////
// S390RSYInstruction Class Definition
////////////////////////////////////////////////////////////////////////////////
class S390RSYInstruction : public TR::S390RSInstruction
{
public:
S390RSYInstruction(TR::InstOpCode::Mnemonic op,
TR::Node *n,
TR::Register *treg,
uint32_t mask,
TR::MemoryReference *mf,
TR::CodeGenerator *cg)
: S390RSInstruction(op, n, treg, mask, mf, cg)
{
}
S390RSYInstruction(TR::InstOpCode::Mnemonic op,
TR::Node *n,
TR::Register *treg,
uint32_t mask,
TR::MemoryReference *mf,
TR::Instruction *preced,
TR::CodeGenerator *cg)
: S390RSInstruction(op, n, treg, mask, mf, preced, cg)
{
}
S390RSYInstruction(TR::InstOpCode::Mnemonic op,
TR::Node *n,
TR::RegisterPair *treg,
TR::RegisterPair *sreg,
TR::MemoryReference *mf,
TR::CodeGenerator *cg)
: S390RSInstruction(op, n, treg, sreg, mf, cg)
{
}
S390RSYInstruction(TR::InstOpCode::Mnemonic op,
TR::Node *n,
TR::RegisterPair *treg,
TR::RegisterPair *sreg,
TR::MemoryReference *mf,
TR::Instruction *preced,
TR::CodeGenerator *cg)
: S390RSInstruction(op, n, treg, sreg, mf, preced, cg)
{
}
S390RSYInstruction(TR::InstOpCode::Mnemonic op,
TR::Node *n,
TR::Register *treg,
TR::Register *sreg,
TR::MemoryReference *mf,
TR::CodeGenerator *cg)
: S390RSInstruction(op, n, treg, sreg, mf, cg)
{
}
S390RSYInstruction(TR::InstOpCode::Mnemonic op,
TR::Node *n,
TR::Register *treg,
TR::Register *sreg,
TR::MemoryReference *mf,
TR::Instruction *preced,
TR::CodeGenerator *cg)
: S390RSInstruction(op, n, treg, sreg, mf, preced, cg)
{
}
virtual char *description() { return "S390RSYInstruction"; }
virtual Kind getKind() { return IsRSY; }
//virtual uint8_t *generateBinaryEncoding();
//virtual int32_t estimateBinaryLength(int32_t currentEstimate);
};
////////////////////////////////////////////////////////////////////////////////
// S390RRSInstruction Class Definition
////////////////////////////////////////////////////////////////////////////////
class S390RRSInstruction : public TR::S390RRInstruction
{
TR::MemoryReference * _branchDestination;
TR::InstOpCode::S390BranchCondition _branchCondition;
public:
/** Construct a new RRS instruction with no preceding instruction */
S390RRSInstruction(TR::InstOpCode::Mnemonic op,
TR::Node * n,
TR::Register * targetRegister,
TR::Register * sourceRegister,
TR::MemoryReference * branchDestination,
TR::InstOpCode::S390BranchCondition branchCondition,
TR::CodeGenerator * cg)
: S390RRInstruction(op, n, targetRegister, sourceRegister, cg),
_branchDestination(branchDestination),
_branchCondition(branchCondition)
{
setupThrowsImplicitNullPointerException(n,branchDestination);
}
/** Construct a new RRS instruction with preceding instruction */
S390RRSInstruction(TR::InstOpCode::Mnemonic op,
TR::Node * n,
TR::Register * targetRegister,
TR::Register * sourceRegister,
TR::MemoryReference * branchDestination,
TR::InstOpCode::S390BranchCondition branchCondition,
TR::Instruction * precedingInstruction,
TR::CodeGenerator * cg)
: S390RRInstruction(op, n, targetRegister, sourceRegister, precedingInstruction, cg),
_branchDestination(branchDestination),
_branchCondition(branchCondition)
{
setupThrowsImplicitNullPointerException(n,branchDestination);
}
virtual char *description() { return "S390RRSInstruction"; }
virtual Kind getKind() { return IsRRS; }
/** Get branch condition information */
virtual TR::InstOpCode::S390BranchCondition getBranchCondition() {return _branchCondition;}
virtual TR::InstOpCode::S390BranchCondition setBranchCondition(TR::InstOpCode::S390BranchCondition branchCondition) {return _branchCondition = branchCondition;}
uint8_t getMask() {return getMaskForBranchCondition(getBranchCondition()) << 4;}
/** Get branch destination information */
virtual TR::MemoryReference * getBranchDestinationLabel() { return _branchDestination; }
virtual uint8_t * generateBinaryEncoding();
};
////////////////////////////////////////////////////////////////////////////////
// S390RREInstruction Class Definition
////////////////////////////////////////////////////////////////////////////////
class S390RREInstruction : public TR::S390RRInstruction
{
public:
S390RREInstruction(TR::InstOpCode::Mnemonic op,
TR::Node *n,
TR::Register *treg,
TR::CodeGenerator *cg)
: S390RRInstruction(op, n, treg, cg)
{
}
S390RREInstruction(TR::InstOpCode::Mnemonic op,
TR::Node *n,
TR::Register *treg,
TR::Register *sreg,
TR::CodeGenerator *cg)
: S390RRInstruction(op, n, treg, sreg, cg)
{
}
S390RREInstruction(TR::InstOpCode::Mnemonic op,
TR::Node *n,
TR::Register *treg,
TR::Register *sreg,
TR::RegisterDependencyConditions * cond,
TR::CodeGenerator *cg)
: S390RRInstruction(op, n, treg, sreg, cond, cg)
{
}
S390RREInstruction(TR::InstOpCode::Mnemonic op,
TR::Node *n,
TR::Register *treg,
TR::Register *sreg,
TR::RegisterDependencyConditions * cond,
TR::Instruction *preced,
TR::CodeGenerator *cg)
: S390RRInstruction(op, n, treg, sreg, cond, preced, cg)
{
}
S390RREInstruction(TR::InstOpCode::Mnemonic op,
TR::Node *n,
TR::Register *treg,
TR::Register *sreg,
TR::Instruction *preced,
TR::CodeGenerator *cg)
: S390RRInstruction(op, n, treg, sreg, preced, cg)
{
}
S390RREInstruction(TR::InstOpCode::Mnemonic op,
TR::Node *n,
TR::Register *treg,
TR::Instruction *preced,
TR::CodeGenerator *cg)
: S390RRInstruction(op, n, treg, preced, cg)
{
}
virtual char *description() { return "S390RREInstruction"; }
virtual Kind getKind() { return IsRRE; }
//virtual uint8_t *generateBinaryEncoding();
//virtual int32_t estimateBinaryLength(int32_t currentEstimate);
};
////////////////////////////////////////////////////////////////////////////////
// S390IEInstruction Class Definition
////////////////////////////////////////////////////////////////////////////////
class S390IEInstruction : public TR::Instruction
{
uint8_t _immediate1;
uint8_t _immediate2;
public:
S390IEInstruction(TR::InstOpCode::Mnemonic op,
TR::Node *n,
uint8_t im1,
uint8_t im2,
TR::CodeGenerator *cg)
: TR::Instruction(op, n, cg), _immediate1(im1), _immediate2(im2)
{
}
S390IEInstruction(TR::InstOpCode::Mnemonic op,
TR::Node * n,
uint8_t im1,
uint8_t im2,
TR::Instruction *precedingInstruction,
TR::CodeGenerator *cg)
: TR::Instruction(op, n, precedingInstruction, cg), _immediate1(im1), _immediate2(im2)
{
}
uint8_t getImmediateField1() { return _immediate1; }
uint8_t getImmediateField2() { return _immediate2; }
virtual char *description() { return "S390IEInstruction"; }
virtual Kind getKind() { return IsIE; }
virtual uint8_t *generateBinaryEncoding();
};
////////////////////////////////////////////////////////////////////////////////
// S390RIEInstruction Class Definition
////////////////////////////////////////////////////////////////////////////////
/**
* There are 3 forms of RIE instructions. one which compares Reg-Reg, one
* which compares Reg-Imm8, and one whicn compares Reg-Imm16.
*
* Note that there is no distinction between source and target register for
* a compare, this is just following convention.
*/
class S390RIEInstruction : public TR::S390RegInstruction
{
TR::InstOpCode::S390BranchCondition _branchCondition;
// in the cases where we have an immediate to compare against a register, it
// will be in this member
int8_t _sourceImmediate8;
int8_t _sourceImmediate8One;
int8_t _sourceImmediate8Two;
// in the case where the caller has a 16-bit immediate to compare against,
// it will be in this member
int16_t _sourceImmediate16;
/**
* If the user only knows that they are branching to a label, we'll store
* that in this member
*/
TR::LabelSymbol * _branchDestination;
public:
typedef enum RIEForms { RIE_RR, RIE_RI8, RIE_RI16A, RIE_RI16G, RIE_RRI16, RIE_IMM } RIEForm;
private:
/** This member will determine which form of RIE you have based on how we get constructed */
RIEForm _instructionFormat;
public:
/** Construct a Reg-Reg form RIE with no preceding instruction */
S390RIEInstruction(TR::InstOpCode::Mnemonic op,
TR::Node * n,
TR::Register * targetRegister,
TR::Register * sourceRegister,
TR::LabelSymbol * branchDestination,
TR::InstOpCode::S390BranchCondition branchCondition,
TR::CodeGenerator * cg)
: S390RegInstruction(op, n, targetRegister, cg),
_instructionFormat(RIE_RR),
_branchDestination(branchDestination),
_branchCondition(branchCondition)
{
// note that _targetRegister is registered for use via the
// S390RegInstruction constructor call
useSourceRegister(sourceRegister);
}
/** Construct a Reg-Reg form RIE with preceding instruction */
S390RIEInstruction(TR::InstOpCode::Mnemonic op,
TR::Node * n,
TR::Register * targetRegister,
TR::Register * sourceRegister,
TR::LabelSymbol * branchDestination,
TR::InstOpCode::S390BranchCondition branchCondition,
TR::Instruction * precedingInstruction,
TR::CodeGenerator * cg)
: S390RegInstruction(op, n, targetRegister, precedingInstruction, cg),
_instructionFormat(RIE_RR),
_branchDestination(branchDestination),
_branchCondition(branchCondition)
{
// note that _targetRegister is registered for use via the
// S390RegInstruction constructor call
useSourceRegister(sourceRegister);
}
/** Construct a Reg-Imm8 form RIE with no preceding instruction */
S390RIEInstruction(TR::InstOpCode::Mnemonic op,
TR::Node * n,
TR::Register * targetRegister,
int8_t sourceImmediate,
TR::LabelSymbol * branchDestination,
TR::InstOpCode::S390BranchCondition branchCondition,
TR::CodeGenerator * cg)
: S390RegInstruction(op, n, targetRegister, cg),
_instructionFormat(RIE_RI8),
_branchDestination(branchDestination),
_branchCondition(branchCondition),
_sourceImmediate8(sourceImmediate)
{
// note that _targetRegister is registered for use via the
// S390RegInstruction constructor call
}
/** Construct a Reg-Imm8 form RIE with preceding instruction */
S390RIEInstruction(TR::InstOpCode::Mnemonic op,
TR::Node * n,
TR::Register * targetRegister,
int8_t sourceImmediate,
TR::LabelSymbol * branchDestination,
TR::InstOpCode::S390BranchCondition branchCondition,
TR::Instruction * precedingInstruction,
TR::CodeGenerator * cg)
: S390RegInstruction(op, n, targetRegister, precedingInstruction, cg),
_instructionFormat(RIE_RI8),
_branchDestination(branchDestination),
_branchCondition(branchCondition),
_sourceImmediate8(sourceImmediate)
{
// note that _targetRegister is registered for use via the
// S390RegInstruction constructor call
}
/** Construct a Reg-Reg-Imm8-Imm8-Imm8 form RIE with no preceding instruction */
S390RIEInstruction(TR::InstOpCode::Mnemonic op,
TR::Node * n,
TR::Register * targetRegister,
TR::Register * sourceRegister,
int8_t sourceImmediateOne,
int8_t sourceImmediateTwo,
int8_t sourceImmediate,
TR::CodeGenerator * cg)
: S390RegInstruction(op, n, targetRegister, cg),
_instructionFormat(RIE_IMM),
_branchDestination(0),
_branchCondition(TR::InstOpCode::COND_NOPR),
_sourceImmediate8(sourceImmediate),
_sourceImmediate8One(sourceImmediateOne),
_sourceImmediate8Two(sourceImmediateTwo)
{
useSourceRegister(sourceRegister);
}
/** Construct a Reg-Reg-Imm8-Imm8-Imm8 form RIE with preceding instruction */
S390RIEInstruction(TR::InstOpCode::Mnemonic op,
TR::Node * n,
TR::Register * targetRegister,
TR::Register * sourceRegister,
int8_t sourceImmediateOne,
int8_t sourceImmediateTwo,
int8_t sourceImmediate,
TR::Instruction * precedingInstruction,
TR::CodeGenerator * cg)
: S390RegInstruction(op, n, targetRegister, precedingInstruction, cg),
_instructionFormat(RIE_IMM),
_branchDestination(0),
_branchCondition(TR::InstOpCode::COND_NOPR),
_sourceImmediate8(sourceImmediate),
_sourceImmediate8One(sourceImmediateOne),
_sourceImmediate8Two(sourceImmediateTwo)
{
// note that _targetRegister is registered for use via the
// S390RegInstruction constructor call
useSourceRegister(sourceRegister);
}
/** Construct a Reg-Imm16 form RIE with no preceding instruction */
S390RIEInstruction(TR::InstOpCode::Mnemonic op,
TR::Node * n,
TR::Register * targetRegister,
int16_t sourceImmediate,
TR::InstOpCode::S390BranchCondition branchCondition,
TR::CodeGenerator * cg)
: S390RegInstruction(op, n, targetRegister, cg),
_instructionFormat(RIE_RI16A),
_branchDestination(0),
_branchCondition(branchCondition),
_sourceImmediate16(sourceImmediate)
{
// Note that _targetRegister is registered for use via the S390RegInstruction constructor call
if (op == TR::InstOpCode::LOCGHI || op == TR::InstOpCode::LOCHI || op == TR::InstOpCode::LOCHHI)
_instructionFormat = RIE_RI16G;
}
/** Construct a Reg-Imm16 form RIE with preceding instruction */
S390RIEInstruction(TR::InstOpCode::Mnemonic op,
TR::Node * n,
TR::Register * targetRegister,
int16_t sourceImmediate,
TR::InstOpCode::S390BranchCondition branchCondition,
TR::Instruction * precedingInstruction,
TR::CodeGenerator * cg)
: S390RegInstruction(op, n, targetRegister, precedingInstruction, cg),
_instructionFormat(RIE_RI16A),
_branchDestination(0),
_branchCondition(branchCondition),
_sourceImmediate16(sourceImmediate)
{
if (isTrap())
TR_ASSERT((sourceImmediate >> 8) != 0x00B9, "ASSERTION FAILURE: should not generate RIE trap instruction with imm field = B9XX!\n");
// Note that _targetRegister is registered for use via the S390RegInstruction constructor call
if (op == TR::InstOpCode::LOCGHI || op == TR::InstOpCode::LOCHI || op == TR::InstOpCode::LOCHHI)
_instructionFormat = RIE_RI16G;
}
/** Construct a Reg-Reg-Imm16 form RIE with preceding instruction */
S390RIEInstruction(TR::InstOpCode::Mnemonic op,
TR::Node * n,
TR::Register * targetRegister,
TR::Register * sourceRegister,
int16_t sourceImmediate,
TR::Instruction * precedingInstruction,
TR::CodeGenerator * cg)
: S390RegInstruction(op, n, targetRegister, precedingInstruction, cg),
_instructionFormat(RIE_RRI16),
_branchDestination(0),
_branchCondition(TR::InstOpCode::COND_NOPR),
_sourceImmediate8(0),
_sourceImmediate16(sourceImmediate)
{
// note that _targetRegister is registered for use via the
// S390RegInstruction constructor call
useSourceRegister(sourceRegister);
}
/** Construct a Reg-Reg-Imm16 form RIE with no preceding instruction */
S390RIEInstruction(TR::InstOpCode::Mnemonic op,
TR::Node * n,
TR::Register * targetRegister,
TR::Register * sourceRegister,
int16_t sourceImmediate,
TR::CodeGenerator * cg)
: S390RegInstruction(op, n, targetRegister, cg),
_instructionFormat(RIE_RRI16),
_branchDestination(0),
_branchCondition(TR::InstOpCode::COND_NOPR),
_sourceImmediate8(0),
_sourceImmediate16(sourceImmediate)
{
// note that _targetRegister is registered for use via the
// S390RegInstruction constructor call
useSourceRegister(sourceRegister);
}
uint8_t *splitIntoCompareAndLongBranch(void);
void splitIntoCompareAndBranch(TR::Instruction *insertBranchAfterThis);
/** Determine the form of this instruction */
virtual char *description() { return "S390RIEInstruction"; }
virtual Kind getKind() { return IsRIE; }
virtual RIEForm getRieForm() { return _instructionFormat; }
// get register information
//virtual TR::Register * getSourceRegister() { return (_sourceRegSize!=0) ? (sourceRegBase())[0] : NULL; }
// virtual TR::Register * getTargetRegister() { return S390RegInstruction::getTargetRegister(); }
// set register informtion
// virtual void setSourceRegister(TR::Register * reg) { assume0(_sourceRegSize==1); (sourceRegBase())[0] = reg; }
/** Get immediate value information */
int8_t getSourceImmediate8() { return _sourceImmediate8; }
int8_t getSourceImmediate8One() { return _sourceImmediate8One; }
int8_t getSourceImmediate8Two() { return _sourceImmediate8Two; }
int16_t getSourceImmediate16() { return _sourceImmediate16; }
/** Set immediate value information */
void setSourceImmediate8(int8_t i) {_sourceImmediate8 = i;}
void setSourceImmediate8One(int8_t i) {_sourceImmediate8One = i;}
void setSourceImmediate8Two(int8_t i) {_sourceImmediate8Two = i;}
void setSourceImmediate16(int16_t i) {_sourceImmediate16 = i;}
/** Get branch condition information */
virtual TR::InstOpCode::S390BranchCondition getBranchCondition() {return _branchCondition;}
virtual TR::InstOpCode::S390BranchCondition setBranchCondition(TR::InstOpCode::S390BranchCondition branchCondition) {return _branchCondition = branchCondition;}
uint8_t getMask() {return getMaskForBranchCondition(getBranchCondition()) << 4;}
/** Get branch destination information */
virtual TR::LabelSymbol * getBranchDestinationLabel() { return _branchDestination; }
void setBranchDestinationLabel(TR::LabelSymbol *l) { _branchDestination = l; }
virtual uint8_t * generateBinaryEncoding();
virtual int32_t estimateBinaryLength(int32_t currentEstimate);
virtual TR::LabelSymbol *getLabelSymbol()
{
return _branchDestination;
}
virtual TR::Snippet *getSnippetForGC()
{
if (getLabelSymbol() != NULL)
return getLabelSymbol()->getSnippet();
return NULL;
}
};
////////////////////////////////////////////////////////////////////////////////
// S390SMIInstruction Class Definition
////////////////////////////////////////////////////////////////////////////////
class S390SMIInstruction : public TR::Instruction
{
private:
uint8_t _mask;
TR::LabelSymbol * _branchInstruction;
public:
S390SMIInstruction(TR::InstOpCode::Mnemonic op,
TR::Node *n,
uint8_t mask,
TR::LabelSymbol *inst,
TR::MemoryReference *mf3,
TR::CodeGenerator *cg)
: TR::Instruction(op, n, cg), _mask(mask), _branchInstruction(inst)
{
useSourceMemoryReference(mf3);
}
S390SMIInstruction(TR::InstOpCode::Mnemonic op,
TR::Node *n,
uint8_t mask,
TR::LabelSymbol *inst,
TR::MemoryReference *mf3,
TR::Instruction *precedingInstruction,
TR::CodeGenerator *cg)
: TR::Instruction(op, n, precedingInstruction, cg), _mask(mask), _branchInstruction(inst)
{
useSourceMemoryReference(mf3);
}
S390SMIInstruction(TR::InstOpCode::Mnemonic op,
TR::Node * n,
uint8_t mask,
TR::LabelSymbol *inst,
TR::MemoryReference *mf3,
TR::RegisterDependencyConditions *cond,
TR::CodeGenerator *cg)
: TR::Instruction(op, n, cond, cg), _mask(mask), _branchInstruction(inst)
{
useSourceMemoryReference(mf3);
}
S390SMIInstruction(TR::InstOpCode::Mnemonic op,
TR::Node *n,
uint8_t mask,
TR::LabelSymbol *inst,
TR::MemoryReference *mf3,
TR::RegisterDependencyConditions *cond,
TR::Instruction *precedingInstruction,
TR::CodeGenerator *cg)
: TR::Instruction(op, n, cond, precedingInstruction, cg), _mask(mask), _branchInstruction(inst)
{
useSourceMemoryReference(mf3);
}
virtual uint8_t *generateBinaryEncoding();
virtual int32_t estimateBinaryLength(int32_t currentEstimate);
uint8_t getMask() {return _mask;}
uint8_t setMask(uint8_t mask) {return _mask = mask;}
virtual char *description() { return "S390SMIInstruction"; }
virtual Kind getKind() { return IsSMI; }
virtual TR::LabelSymbol *getLabelSymbol()
{
return _branchInstruction;
}
virtual TR::MemoryReference* getMemoryReference() { return (_sourceMemSize!=0) ? (sourceMemBase())[0] : NULL; }
};
////////////////////////////////////////////////////////////////////////////////
// S390MIIInstruction Class Definition
////////////////////////////////////////////////////////////////////////////////
class S390MIIInstruction : public TR::Instruction
{
private:
uint8_t _mask;
TR::LabelSymbol * _branchInstruction;
TR::SymbolReference * _callSymRef;
public:
S390MIIInstruction(TR::InstOpCode::Mnemonic op, TR::Node * n,
uint8_t mask,
TR::LabelSymbol *inst2,
TR::SymbolReference *inst3,
TR::CodeGenerator *cg)
: TR::Instruction(op, n, cg), _mask(mask), _callSymRef(inst3), _branchInstruction(inst2)
{
}
S390MIIInstruction(TR::InstOpCode::Mnemonic op, TR::Node * n,
uint8_t mask,
TR::LabelSymbol *inst2,
TR::SymbolReference *inst3,
TR::Instruction *precedingInstruction,
TR::CodeGenerator *cg)
: TR::Instruction(op, n, precedingInstruction, cg), _mask(mask), _callSymRef(inst3), _branchInstruction(inst2)
{
}
S390MIIInstruction(TR::InstOpCode::Mnemonic op, TR::Node * n,
uint8_t mask,
TR::LabelSymbol *inst2,
TR::SymbolReference *inst3,
TR::RegisterDependencyConditions *cond,
TR::CodeGenerator *cg)
: TR::Instruction(op, n, cond, cg), _mask(mask), _callSymRef(inst3), _branchInstruction(inst2)
{
}
S390MIIInstruction(TR::InstOpCode::Mnemonic op, TR::Node * n,
uint8_t mask,
TR::LabelSymbol *inst2,
TR::SymbolReference *inst3,
TR::RegisterDependencyConditions *cond,
TR::Instruction *precedingInstruction,
TR::CodeGenerator *cg)
: TR::Instruction(op, n, cond, precedingInstruction, cg), _mask(mask), _callSymRef(inst3), _branchInstruction(inst2)
{
}
virtual uint8_t *generateBinaryEncoding();
virtual int32_t estimateBinaryLength(int32_t currentEstimate);
uint8_t getMask() {return _mask;}
uint8_t setMask(uint8_t mask) {return _mask = mask;}
virtual char *description() { return "S390MIIInstruction"; }
virtual Kind getKind() { return IsMII; }
virtual TR::LabelSymbol *getLabelSymbol()
{
return _branchInstruction;
}
virtual TR::SymbolReference * getSymRef() {return _callSymRef;}
};
////////////////////////////////////////////////////////////////////////////////
// S390RISInstruction Class Definition
////////////////////////////////////////////////////////////////////////////////
class S390RISInstruction : public TR::S390RIInstruction
{
TR::MemoryReference * _branchDestination;
TR::InstOpCode::S390BranchCondition _branchCondition;
public:
/** Construct a new RIS instruction with no preceding instruction */
S390RISInstruction(TR::InstOpCode::Mnemonic op,
TR::Node * n,
TR::Register * targetRegister,
int8_t sourceImmediate,
TR::MemoryReference * branchDestination,
TR::InstOpCode::S390BranchCondition branchCondition,
TR::CodeGenerator *cg)
: S390RIInstruction(op, n, targetRegister, sourceImmediate, cg),
_branchDestination(branchDestination),
_branchCondition(branchCondition)
{
setupThrowsImplicitNullPointerException(n,branchDestination);
}
/** Construct a new RIS instruction with preceding instruction */
S390RISInstruction(TR::InstOpCode::Mnemonic op,
TR::Node * n,
TR::Register * targetRegister,
int8_t sourceImmediate,
TR::MemoryReference * branchDestination,
TR::InstOpCode::S390BranchCondition branchCondition,
TR::Instruction * precedingInstruction,
TR::CodeGenerator *cg)
: S390RIInstruction(op, n, targetRegister, sourceImmediate, precedingInstruction, cg),
_branchDestination(branchDestination),
_branchCondition(branchCondition)
{
setupThrowsImplicitNullPointerException(n,branchDestination);
}
virtual char *description() { return "S390RISInstruction"; }
virtual Kind getKind() { return IsRIS; }
/** Get branch condition information */
virtual TR::InstOpCode::S390BranchCondition getBranchCondition() {return _branchCondition;}
virtual TR::InstOpCode::S390BranchCondition setBranchCondition(TR::InstOpCode::S390BranchCondition branchCondition) {return _branchCondition = branchCondition;}
uint8_t getMask() {return getMaskForBranchCondition(getBranchCondition()) << 4;}
/** Get branch destination information */
virtual TR::MemoryReference * getBranchDestinationLabel() { return _branchDestination; }
virtual uint8_t * generateBinaryEncoding();
};
////////////////////////////////////////////////////////////////////////////////
// S390MemInstruction Class Definition
////////////////////////////////////////////////////////////////////////////////
class S390MemInstruction : public TR::Instruction
{
int8_t _memAccessMode;
int8_t _constantField;
TR::MemoryReference *_memref;
public:
S390MemInstruction(TR::InstOpCode::Mnemonic op,
TR::Node *n,
TR::MemoryReference *mf,
TR::CodeGenerator *cg,
bool use = true)
: TR::Instruction(op, n, cg), _memAccessMode(-1), _constantField(-1), _memref(mf)
{
if (use)
useSourceMemoryReference(mf);
setupThrowsImplicitNullPointerException(n,mf);
if (mf->getUnresolvedSnippet() != NULL)
(mf->getUnresolvedSnippet())->setDataReferenceInstruction(this);
}
S390MemInstruction(TR::InstOpCode::Mnemonic op,
TR::Node *n,
TR::MemoryReference *mf,
TR::RegisterDependencyConditions *cond,
TR::CodeGenerator *cg,
bool use = true)
: TR::Instruction(op, n, cond, cg), _memAccessMode(-1), _constantField(-1), _memref(mf)
{
if (use)
useSourceMemoryReference(mf);
setupThrowsImplicitNullPointerException(n,mf);
if (mf->getUnresolvedSnippet() != NULL)
(mf->getUnresolvedSnippet())->setDataReferenceInstruction(this);
}
S390MemInstruction(TR::InstOpCode::Mnemonic op,
TR::Node *n,
int8_t memAccessMode,
TR::MemoryReference *mf,
TR::CodeGenerator *cg,
bool use = true)
: TR::Instruction(op, n, cg), _memAccessMode(memAccessMode), _constantField(-1), _memref(mf)
{
if (use)
useSourceMemoryReference(mf);
setupThrowsImplicitNullPointerException(n,mf);
if (mf->getUnresolvedSnippet() != NULL)
(mf->getUnresolvedSnippet())->setDataReferenceInstruction(this);
}
S390MemInstruction(TR::InstOpCode::Mnemonic op,
TR::Node *n,
int8_t constantField,
int8_t memAccessMode,
TR::MemoryReference *mf,
TR::CodeGenerator *cg,
bool use = true)
: TR::Instruction(op, n, cg), _memAccessMode(memAccessMode), _constantField(constantField), _memref(mf)
{
if (use)
useSourceMemoryReference(mf);
setupThrowsImplicitNullPointerException(n,mf);
if (mf->getUnresolvedSnippet() != NULL)
(mf->getUnresolvedSnippet())->setDataReferenceInstruction(this);
}
S390MemInstruction(TR::InstOpCode::Mnemonic op,
TR::Node *n,
TR::MemoryReference *mf,
TR::Instruction *precedingInstruction,
TR::CodeGenerator *cg,
bool use = true)
: TR::Instruction(op, n, precedingInstruction, cg), _memAccessMode(-1), _constantField(-1), _memref(mf)
{
if (use)
useSourceMemoryReference(mf);
setupThrowsImplicitNullPointerException(n,mf);
if (mf->getUnresolvedSnippet() != NULL)
(mf->getUnresolvedSnippet())->setDataReferenceInstruction(this);
}
S390MemInstruction(TR::InstOpCode::Mnemonic op,
TR::Node *n,
TR::MemoryReference *mf,
TR::RegisterDependencyConditions *cond,
TR::Instruction *precedingInstruction,
TR::CodeGenerator *cg,
bool use = true)
: TR::Instruction(op, n, cond, precedingInstruction, cg), _memAccessMode(-1), _constantField(-1), _memref(mf)
{
if (use)
useSourceMemoryReference(mf);
setupThrowsImplicitNullPointerException(n,mf);
if (mf->getUnresolvedSnippet() != NULL)
(mf->getUnresolvedSnippet())->setDataReferenceInstruction(this);
}
S390MemInstruction(TR::InstOpCode::Mnemonic op,
TR::Node *n,
int8_t memAccessMode,
TR::MemoryReference *mf,
TR::Instruction *precedingInstruction,
TR::CodeGenerator *cg,
bool use = true)
: TR::Instruction(op, n, precedingInstruction, cg), _memAccessMode(memAccessMode), _constantField(-1), _memref(mf)
{
if (use)
useSourceMemoryReference(mf);
setupThrowsImplicitNullPointerException(n,mf);
if (mf->getUnresolvedSnippet() != NULL)
(mf->getUnresolvedSnippet())->setDataReferenceInstruction(this);
}
S390MemInstruction(TR::InstOpCode::Mnemonic op,
TR::Node *n,
int8_t constantField,
int8_t memAccessMode,
TR::MemoryReference *mf,
TR::Instruction *precedingInstruction,
TR::CodeGenerator *cg,
bool use = true)
: TR::Instruction(op, n, precedingInstruction, cg), _memAccessMode(memAccessMode), _constantField(constantField), _memref(mf)
{
if (use)
useSourceMemoryReference(mf);
setupThrowsImplicitNullPointerException(n,mf);
if (mf->getUnresolvedSnippet() != NULL)
(mf->getUnresolvedSnippet())->setDataReferenceInstruction(this);
}
virtual char *description() { return "S390MemInstruction"; }
virtual Kind getKind() { return IsMem; }
virtual TR::MemoryReference *getMemoryReference() { return _memref; }
int16_t getMemAccessMode() {return _memAccessMode;}
int16_t getConstantField() {return _constantField;}
virtual uint8_t *generateBinaryEncoding();
virtual bool refsRegister(TR::Register *reg);
};
////////////////////////////////////////////////////////////////////////////////
// S390SIInstruction Class Definition
////////////////////////////////////////////////////////////////////////////////
class S390SIInstruction : public TR::S390MemInstruction
{
uint8_t _sourceImmediate;
public:
S390SIInstruction(TR::InstOpCode::Mnemonic op, TR::Node * n, TR::MemoryReference *mf,
uint8_t imm,
TR::CodeGenerator *cg)
: S390MemInstruction(op, n, mf, cg, false), _sourceImmediate(imm)
{
useSourceMemoryReference(mf); // need to call this *after* S390SIInstruction constructor
}
S390SIInstruction(TR::InstOpCode::Mnemonic op, TR::Node * n, TR::MemoryReference *mf,
uint8_t imm,
TR::Instruction *precedingInstruction,
TR::CodeGenerator *cg)
: S390MemInstruction(op, n, mf, precedingInstruction, cg, false), _sourceImmediate(imm)
{
useSourceMemoryReference(mf);
};
virtual char *description() { return "S390SIInstruction"; }
virtual Kind getKind() { return IsSI; }
uint8_t getSourceImmediate() { return _sourceImmediate; }
uint8_t setSourceImmediate(uint8_t si) { return _sourceImmediate = si; }
virtual uint8_t *generateBinaryEncoding();
virtual int32_t estimateBinaryLength(int32_t currentEstimate);
};
////////////////////////////////////////////////////////////////////////////////
// S390SIYInstruction Class Definition
////////////////////////////////////////////////////////////////////////////////
class S390SIYInstruction : public TR::S390SIInstruction
{
public:
S390SIYInstruction(TR::InstOpCode::Mnemonic op, TR::Node * n, TR::MemoryReference *mf,
uint8_t imm,
TR::CodeGenerator *cg)
: S390SIInstruction(op, n, mf, imm, cg) {};
S390SIYInstruction(TR::InstOpCode::Mnemonic op, TR::Node * n, TR::MemoryReference *mf,
uint8_t imm,
TR::Instruction *precedingInstruction,
TR::CodeGenerator *cg)
: S390SIInstruction(op, n, mf, imm, precedingInstruction, cg) {};
virtual char *description() { return "S390SIYInstruction"; }
virtual Kind getKind() { return IsSIY; }
virtual uint8_t *generateBinaryEncoding();
virtual int32_t estimateBinaryLength(int32_t currentEstimate);
};
////////////////////////////////////////////////////////////////////////////////
// S390SILInstruction Class Definition
////////////////////////////////////////////////////////////////////////////////
class S390SILInstruction : public TR::S390MemInstruction
{
uint16_t _sourceImmediate;
public:
S390SILInstruction(TR::InstOpCode::Mnemonic op, TR::Node * n,
TR::MemoryReference *mf,
uint16_t imm,
TR::CodeGenerator *cg)
: S390MemInstruction(op, n, mf, cg, false), _sourceImmediate(imm)
{
if (op != TR::InstOpCode::TBEGINC)
useSourceMemoryReference(mf);
}
S390SILInstruction(TR::InstOpCode::Mnemonic op, TR::Node * n,
TR::MemoryReference *mf,
uint16_t imm,
TR::Instruction *precedingInstruction,
TR::CodeGenerator *cg)
: S390MemInstruction(op, n, mf, precedingInstruction, cg, false), _sourceImmediate(imm)
{
if (op != TR::InstOpCode::TBEGINC)
useSourceMemoryReference(mf);
}
virtual char *description() { return "S390SILInstruction"; }
virtual Kind getKind() { return IsSIL; }
uint16_t getSourceImmediate() { return _sourceImmediate; }
uint16_t setSourceImmediate(uint16_t si) { return _sourceImmediate = si; }
virtual uint8_t *generateBinaryEncoding();
virtual int32_t estimateBinaryLength(int32_t currentEstimate);
};
////////////////////////////////////////////////////////////////////////////////
// S390SInstruction Class Definition
////////////////////////////////////////////////////////////////////////////////
class S390SInstruction : public TR::S390MemInstruction
{
public:
S390SInstruction(TR::InstOpCode::Mnemonic op, TR::Node * n, TR::MemoryReference *mf,
TR::CodeGenerator *cg)
: S390MemInstruction(op, n, mf, cg) {};
S390SInstruction(TR::InstOpCode::Mnemonic op, TR::Node * n, TR::MemoryReference *mf,
TR::Instruction *precedingInstruction,
TR::CodeGenerator *cg)
: S390MemInstruction(op, n, mf, precedingInstruction, cg) {};
virtual char *description() { return "S390SInstruction"; }
virtual Kind getKind() { return IsS; }
virtual uint8_t *generateBinaryEncoding();
virtual int32_t estimateBinaryLength(int32_t currentEstimate);
};
/**
* S390RSLInstruction Class Definition
* ________ _______ _________________________________
* |Op Code | L1 | | B1 | D1 | | 'C0' |
* |________|_______|____|_____|_______|______|_______|
* 0 8 12 16 20 32 40 47
*
* First memory reference operand is inherited from base class 390MemInstruction
*/
class S390RSLInstruction : public TR::S390MemInstruction
{
uint16_t _len; ///< length field
public:
S390RSLInstruction(TR::InstOpCode::Mnemonic op, TR::Node * n,
uint16_t len,
TR::MemoryReference *mf1,
TR::CodeGenerator *cg)
: S390MemInstruction(op, n, mf1, cg), _len(len)
{
}
S390RSLInstruction(TR::InstOpCode::Mnemonic op, TR::Node * n,
uint16_t len,
TR::MemoryReference *mf1,
TR::Instruction *precedingInstruction,
TR::CodeGenerator *cg)
: S390MemInstruction(op, n, mf1, precedingInstruction, cg), _len(len)
{
}
virtual char *description() { return "S390RSLInstruction"; }
virtual Kind getKind() { return IsRSL; }
uint16_t getLen() {return _len;}
uint16_t setLen(uint16_t len) {return _len = len;}
virtual uint8_t *generateBinaryEncoding();
virtual int32_t estimateBinaryLength(int32_t currentEstimate);
};
/**
* S390RSLInstruction Class Definition
* ________ _______________________________________________
* | op | L1 | B2 | D2 | R1 | M3 | op |
* |________|____________|_____|_______|_____|_____|________|
* 0 8 16 20 32 36 40 47
*
*
* RSLb is actually very different in encoding and use then RSL so creating a new class
*/
class S390RSLbInstruction : public TR::S390RegInstruction
{
uint16_t _length;
uint8_t _mask;
public:
S390RSLbInstruction(TR::InstOpCode::Mnemonic op,
TR::Node * n,
TR::Register *reg,
uint16_t length,
TR::MemoryReference *mf,
uint8_t mask,
TR::CodeGenerator *cg)
: S390RegInstruction(op, n, reg, cg), _length(length), _mask(mask)
{
useSourceMemoryReference(mf);
setupThrowsImplicitNullPointerException(n,mf);
if (mf->getUnresolvedSnippet() != NULL)
(mf->getUnresolvedSnippet())->setDataReferenceInstruction(this);
}
S390RSLbInstruction(TR::InstOpCode::Mnemonic op,
TR::Node * n,
TR::Register *reg,
int16_t length,
TR::MemoryReference *mf,
int8_t mask,
TR::Instruction * preced,
TR::CodeGenerator *cg)
: S390RegInstruction(op, n, reg, preced, cg), _length(length), _mask(mask)
{
useSourceMemoryReference(mf);
setupThrowsImplicitNullPointerException(n,mf);
if (mf->getUnresolvedSnippet() != NULL)
(mf->getUnresolvedSnippet())->setDataReferenceInstruction(this);
}
virtual char *description() { return "S390RSLbInstruction"; }
virtual Kind getKind() { return IsRSLb; }
uint16_t getLen() {return _length;}
uint16_t setLen(uint16_t len) {return _length = len;}
uint8_t getMask() {return _mask;}
uint8_t setMask(uint8_t mask) {return _mask = mask;}
virtual TR::MemoryReference* getMemoryReference() { return (_sourceMemSize!=0) ? (sourceMemBase())[0] : NULL; }
virtual uint8_t *generateBinaryEncoding();
virtual int32_t estimateBinaryLength(int32_t currentEstimate);
};
/**
* Common base class for instructions with two memory references (except SSF as this is also like an RX format instruction)
*/
class S390MemMemInstruction : public TR::S390MemInstruction
{
public:
S390MemMemInstruction(TR::InstOpCode::Mnemonic op, TR::Node * n,
TR::MemoryReference *mf1,
TR::MemoryReference *mf2,
TR::CodeGenerator *cg)
: S390MemInstruction(op, n, mf1, cg)
{
if (mf2)
{
useTargetMemoryReference(mf2, mf1);
mf2->setIs2ndMemRef();
}
setupThrowsImplicitNullPointerException(n,mf2);
}
S390MemMemInstruction(TR::InstOpCode::Mnemonic op, TR::Node * n,
TR::MemoryReference *mf1,
TR::MemoryReference *mf2,
TR::Instruction *precedingInstruction,
TR::CodeGenerator *cg)
: S390MemInstruction(op, n, mf1, precedingInstruction, cg)
{
if (mf2)
{
useTargetMemoryReference(mf2, mf1);
mf2->setIs2ndMemRef();
}
setupThrowsImplicitNullPointerException(n,mf2);
}
S390MemMemInstruction(TR::InstOpCode::Mnemonic op, TR::Node * n,
TR::MemoryReference *mf1,
TR::MemoryReference *mf2,
TR::RegisterDependencyConditions *cond,
TR::CodeGenerator *cg)
: S390MemInstruction(op, n, mf1, cond, cg)
{
if (mf2)
{
useTargetMemoryReference(mf2, mf1);
mf2->setIs2ndMemRef();
}
setupThrowsImplicitNullPointerException(n,mf2);
}
S390MemMemInstruction(TR::InstOpCode::Mnemonic op, TR::Node * n,
TR::MemoryReference *mf1,
TR::MemoryReference *mf2,
TR::RegisterDependencyConditions *cond,
TR::Instruction *precedingInstruction,
TR::CodeGenerator *cg)
: S390MemInstruction(op, n, mf1, cond, precedingInstruction, cg)
{
if (mf2)
{
useTargetMemoryReference(mf2, mf1);
mf2->setIs2ndMemRef();
}
setupThrowsImplicitNullPointerException(n,mf2);
}
virtual char *description() { return "S390MemMemInstruction"; }
virtual Kind getKind() { return IsMemMem; }
virtual TR::MemoryReference *getMemoryReference2() { return (_targetMemSize!=0) ? (targetMemBase())[0] : NULL;}
virtual uint8_t *generateBinaryEncoding();
virtual int32_t estimateBinaryLength(int32_t currentEstimate);
};
/**
* S390SS1Instruction Class Definition
* ________ _______ ____________________________
* |Op Code | L | B1 | D1 | B2 | D2 |
* |________|_______|____|_______|____|__________|
* 0 8 16 20 32 36 47
*
*/
class S390SS1Instruction : public TR::S390MemMemInstruction
{
uint16_t _len; ///< length field
TR::LabelSymbol * _symbol;
public:
S390SS1Instruction(TR::InstOpCode::Mnemonic op, TR::Node * n,
uint16_t len,
TR::MemoryReference *mf1,
TR::MemoryReference *mf2,
TR::CodeGenerator *cg)
: S390MemMemInstruction(op, n, mf1, mf2, cg), _symbol(NULL), _len(len)
{
}
S390SS1Instruction(TR::InstOpCode::Mnemonic op, TR::Node * n,
uint16_t len,
TR::MemoryReference *mf1,
TR::MemoryReference *mf2,
TR::Instruction *precedingInstruction,
TR::CodeGenerator *cg)
: S390MemMemInstruction(op, n, mf1, mf2, precedingInstruction, cg), _symbol(NULL), _len(len)
{
}
S390SS1Instruction(TR::InstOpCode::Mnemonic op, TR::Node * n,
uint16_t len,
TR::MemoryReference *mf1,
TR::MemoryReference *mf2,
TR::RegisterDependencyConditions *cond,
TR::CodeGenerator *cg)
: S390MemMemInstruction(op, n, mf1, mf2, cond, cg), _symbol(NULL), _len(len)
{
}
S390SS1Instruction(TR::InstOpCode::Mnemonic op, TR::Node * n,
uint16_t len,
TR::MemoryReference *mf1,
TR::MemoryReference *mf2,
TR::RegisterDependencyConditions *cond,
TR::Instruction *precedingInstruction,
TR::CodeGenerator *cg)
: S390MemMemInstruction(op, n, mf1, mf2, cond, precedingInstruction, cg), _symbol(NULL), _len(len)
{
}
virtual char *description() { return "S390SS1Instruction"; }
virtual Kind getKind() { return IsSS1; }
uint32_t getLen() {return _len;}
TR::LabelSymbol * getLabel() {return _symbol;}
void setLabel(TR::LabelSymbol * symbol) {_symbol = symbol;}
uint32_t setLen(uint16_t len) {return _len = len;}
virtual uint8_t *generateBinaryEncoding();
virtual int32_t estimateBinaryLength(int32_t currentEstimate);
};
class S390SS1WithImplicitGPRsInstruction : public TR::S390SS1Instruction
{
public:
S390SS1WithImplicitGPRsInstruction(TR::InstOpCode::Mnemonic op, TR::Node * n,
uint16_t len,
TR::MemoryReference *mf1,
TR::MemoryReference *mf2,
TR::RegisterDependencyConditions *cond,
TR::Register * implicitRegSrc0,
TR::Register * implicitRegSrc1,
TR::Register * implicitRegTrg0,
TR::Register * implicitRegTrg1,
TR::CodeGenerator *cg) :
S390SS1Instruction(op, n, len, mf1, mf2, cond, cg)
{
// Make sure memory references appear after registers in operands array
int32_t i;
int32_t nm=_sourceMemSize+_targetMemSize;
void *vp[2]={_operands[0],_operands[1]};
if (implicitRegTrg0 != NULL) useTargetRegister(implicitRegTrg0);
if (implicitRegTrg1 != NULL) useTargetRegister(implicitRegTrg1);
if (implicitRegSrc0 != NULL) useSourceRegister(implicitRegSrc0);
if (implicitRegSrc1 != NULL) useSourceRegister(implicitRegSrc1);
int32_t nr=_targetRegSize+_sourceRegSize;
for (i=0; i<nr; i++)
_operands[i]=_operands[i+nm];
for (i=0; i<nm; i++)
_operands[i+nr]=vp[i];
}
S390SS1WithImplicitGPRsInstruction(TR::InstOpCode::Mnemonic op, TR::Node * n,
uint16_t len,
TR::MemoryReference *mf1,
TR::MemoryReference *mf2,
TR::RegisterDependencyConditions *cond,
TR::Instruction *precedingInstruction,
TR::Register * implicitRegSrc0,
TR::Register * implicitRegSrc1,
TR::Register * implicitRegTrg0,
TR::Register * implicitRegTrg1,
TR::CodeGenerator *cg) :
S390SS1Instruction(op, n, len, mf1, mf2, cond, precedingInstruction, cg)
{
// Make sure memory references appear after registers in operands array
int32_t i;
int32_t nm=_sourceMemSize+_targetMemSize;
void *vp[2]={_operands[0],_operands[1]};
if (implicitRegTrg0 != NULL) useTargetRegister(implicitRegTrg0);
if (implicitRegTrg1 != NULL) useTargetRegister(implicitRegTrg1);
if (implicitRegSrc0 != NULL) useSourceRegister(implicitRegSrc0);
if (implicitRegSrc1 != NULL) useSourceRegister(implicitRegSrc1);
int32_t nr=_targetRegSize+_sourceRegSize;
for (i=0; i<nr; i++)
_operands[i]=_operands[i+nm];
for (i=0; i<nm; i++)
_operands[i+nr]=vp[i];
}
private:
};
/**
* S390SS2Instruction Class Definition
* ________ _____________ ______________________________
* |Op Code | L1 | L2 | B1 | D1 | B2 | D2 |
* |________|______|______|____|_______|______|__________|
* 0 8 12 16 20 32 36 47
*
* Also used for SS3 where L2 is called I3
*/
class S390SS2Instruction : public TR::S390SS1Instruction
{
uint16_t _len2; ///< length field, also used as imm3 for SS3 encoded SRP
int32_t _shiftAmount; ///< For SS3 encoded SRP
public:
S390SS2Instruction(TR::InstOpCode::Mnemonic op, TR::Node * n,
uint16_t len1,
TR::MemoryReference *mf1,
uint16_t len2,
TR::MemoryReference *mf2,
TR::CodeGenerator *cg)
: S390SS1Instruction(op, n, len1, mf1, mf2, cg), _len2(len2), _shiftAmount(0)
{
}
S390SS2Instruction(TR::InstOpCode::Mnemonic op, TR::Node * n,
uint16_t len1,
TR::MemoryReference *mf1,
uint16_t len2,
TR::MemoryReference *mf2,
TR::Instruction *precedingInstruction,
TR::CodeGenerator *cg)
: S390SS1Instruction(op, n, len1, mf1, mf2, precedingInstruction, cg), _len2(len2), _shiftAmount(0)
{
}
S390SS2Instruction(TR::InstOpCode::Mnemonic op, TR::Node * n,
uint32_t len1,
TR::MemoryReference *mf1,
int32_t shiftAmount,
uint32_t roundAmount,
TR::CodeGenerator *cg)
: S390SS1Instruction(op, n, len1, mf1, NULL, cg), _shiftAmount(shiftAmount), _len2(roundAmount)
{
}
S390SS2Instruction(TR::InstOpCode::Mnemonic op, TR::Node * n,
uint32_t len1,
TR::MemoryReference *mf1,
int32_t shiftAmount,
uint32_t roundAmount,
TR::Instruction *precedingInstruction,
TR::CodeGenerator *cg)
: S390SS1Instruction(op, n, len1, mf1, NULL, precedingInstruction, cg), _shiftAmount(shiftAmount), _len2(roundAmount)
{
}
virtual char *description() { return "S390SS2Instruction"; }
virtual Kind getKind() { return IsSS2; }
uint32_t getLen2() { return _len2; }
uint32_t setLen2(uint16_t len2) { return _len2 = len2; }
/** For SS3 encoded SRP */
uint32_t getImm3() { return _len2; }
uint32_t setImm3(uint16_t len2) { return _len2 = len2; }
int32_t getShiftAmount() { return _shiftAmount; }
int32_t setShiftAmount(uint32_t s) { return _shiftAmount = s; }
virtual uint8_t *generateBinaryEncoding();
};
/**
* S390SS4Instruction Class Definition
* ________ _____________ ______________________________
* |Op Code | R1 | R3 | B1 | D1 | B2 | D2 |
* |________|______|______|____|_______|______|__________|
* 0 8 12 16 20 32 36 47
*
*
* Also used for an SS5 where B1(D1) is called B2(D2) and B2(D2) is called B4(D4)
*/
class S390SS4Instruction : public TR::S390SS1Instruction
{
int8_t _ss4_lenidx;
int8_t _ss4_keyidx;
public:
S390SS4Instruction(TR::InstOpCode::Mnemonic op, TR::Node * n,
TR::Register * lengthReg,
TR::MemoryReference *mf1,
TR::MemoryReference *mf2,
TR::Register * sourceKeyReg,
TR::CodeGenerator *cg)
: S390SS1Instruction(op, n, 0, mf1, mf2, cg), _ss4_lenidx(-1), _ss4_keyidx(-1)
{
// Make sure memory references appear after registers in operands array
int32_t i;
int32_t nm=_sourceMemSize+_targetMemSize;
void *vp[2]={_operands[0],_operands[1]};
if (lengthReg) { _ss4_lenidx=useSourceRegister(lengthReg); }
if (sourceKeyReg) { _ss4_keyidx=useSourceRegister(sourceKeyReg); }
int32_t nr=_targetRegSize+_sourceRegSize;
for (i=0; i<nr; i++)
_operands[i]=_operands[i+nm];
for (i=0; i<nm; i++)
_operands[i+nr]=vp[i];
}
S390SS4Instruction(TR::InstOpCode::Mnemonic op, TR::Node * n,
TR::Register * lengthReg,
TR::MemoryReference *mf1,
TR::MemoryReference *mf2,
TR::Register * sourceKeyReg,
TR::Instruction * precedingInstruction,
TR::CodeGenerator *cg)
: S390SS1Instruction(op, n, 0, mf1, mf2, precedingInstruction, cg), _ss4_lenidx(-1), _ss4_keyidx(-1)
{
// Make sure memory references appear after registers in operands array
int32_t i;
int32_t nm=_sourceMemSize+_targetMemSize;
void *vp[2]={_operands[0],_operands[1]};
if (lengthReg) { _ss4_lenidx=useSourceRegister(lengthReg); }
if (sourceKeyReg) { _ss4_keyidx=useSourceRegister(sourceKeyReg); }
int32_t nr=_targetRegSize+_sourceRegSize;
for (i=0; i<nr; i++)
_operands[i]=_operands[i+nm];
for (i=0; i<nm; i++)
_operands[i+nr]=vp[i];
}
virtual char *description() { return "S390SS4Instruction"; }
virtual Kind getKind() { return IsSS4; }
TR::Register * getLengthReg() { return (_ss4_lenidx!=-1) ? (sourceRegBase())[_ss4_lenidx] : NULL; }
void setLengthReg(TR::Register *lengthReg) { (sourceRegBase())[_ss4_lenidx] = lengthReg; }
TR::Register * getSourceKeyReg() { return (_ss4_keyidx!=-1) ? (sourceRegBase())[_ss4_keyidx] : NULL; }
void setSourceKeyReg(TR::Register * sourceKeyReg) { (sourceRegBase())[_ss4_keyidx] = sourceKeyReg; }
virtual uint8_t *generateBinaryEncoding();
};
/**
* S390SS5WithImplicitGPRsInstruction Class Definition
* ________ _____________ ______________________________
* |Op Code | R1 | R3 | B2 | D2 | B4 | D4 |
* |________|______|______|____|_______|______|__________|
* 0 8 12 16 20 32 36 47
*
* Implicit GPR0 and/or GPR1
*/
class S390SS5WithImplicitGPRsInstruction : public TR::S390SS4Instruction
{
public:
S390SS5WithImplicitGPRsInstruction(TR::InstOpCode::Mnemonic op, TR::Node * n,
TR::Register * op1,
TR::MemoryReference *mf2,
TR::Register * op3,
TR::MemoryReference *mf4,
TR::Register * implicitRegSrc0,
TR::Register * implicitRegSrc1,
TR::Register * implicitRegTrg0,
TR::Register * implicitRegTrg1,
TR::CodeGenerator *cg) :
S390SS4Instruction(op, n, op1, mf2, mf4, op3, cg)
{
// Make sure memory references appear after registers in operands array
int32_t i;
int32_t nm=_sourceMemSize+_targetMemSize;
int32_t explicitSourceRegSize=_sourceRegSize;
void *vp[2]={_operands[_sourceRegSize],_operands[_sourceRegSize+1]};
if (implicitRegSrc0 != NULL) useSourceRegister(implicitRegSrc0);
if (implicitRegSrc1 != NULL) useSourceRegister(implicitRegSrc1);
// Because op1 and op3 are source registers let all source registers be first. Infrastructure can handle target after source but as long as they are contiguous
if (implicitRegTrg0 != NULL) useTargetRegister(implicitRegTrg0);
if (implicitRegTrg1 != NULL) useTargetRegister(implicitRegTrg1);
// The first 2 (explictSourceRegSize) register operands are in place followed by the up to two memory operands
// Move all the added implicit registers adjacents to the first two register operands
int32_t nr=_targetRegSize+_sourceRegSize-explicitSourceRegSize;
for (i=0; i<nr; i++)
_operands[i+explicitSourceRegSize]=_operands[i+explicitSourceRegSize+nm];
for (i=0; i<nm; i++)
_operands[i+explicitSourceRegSize+nr]=vp[i];
}
S390SS5WithImplicitGPRsInstruction(TR::InstOpCode::Mnemonic op, TR::Node * n,
TR::Register * op1,
TR::MemoryReference *mf2,
TR::Register * op3,
TR::MemoryReference *mf4,
TR::Instruction *precedingInstruction,
TR::Register * implicitRegSrc0,
TR::Register * implicitRegSrc1,
TR::Register * implicitRegTrg0,
TR::Register * implicitRegTrg1,
TR::CodeGenerator *cg) :
S390SS4Instruction(op, n, op1, mf2, mf4, op3, precedingInstruction, cg)
{
// Make sure memory references appear after registers in operands array
int32_t i;
int32_t nm=_sourceMemSize+_targetMemSize;
int32_t explicitSourceRegSize=_sourceRegSize;
void *vp[2]={_operands[_sourceRegSize],_operands[_sourceRegSize+1]};
if (implicitRegSrc0 != NULL) useSourceRegister(implicitRegSrc0);
if (implicitRegSrc1 != NULL) useSourceRegister(implicitRegSrc1);
// Because op1 and op3 are source registers let all source registers be first. Infrastructure can handle target after source but as long as they are contiguous
if (implicitRegTrg0 != NULL) useTargetRegister(implicitRegTrg0);
if (implicitRegTrg1 != NULL) useTargetRegister(implicitRegTrg1);
// The first 2 (explictSourceRegSize) register operands are in place followed by the up to two memory operands
// Move all the added implicit registers adjacents to the first two register operands
int32_t nr=_targetRegSize+_sourceRegSize-explicitSourceRegSize;
for (i=0; i<nr; i++)
_operands[i+explicitSourceRegSize]=_operands[i+explicitSourceRegSize+nm];
for (i=0; i<nm; i++)
_operands[i+explicitSourceRegSize+nr]=vp[i];
}
};
/**
* S390SSEInstruction Class Definition
* ______________ ____________________________
* |Op Code | B1 | D1 | B2 | D2 |
* |______________|____|_______|____|__________|
* 0 16 20 32 36 47
*
*/
class S390SSEInstruction : public TR::S390MemMemInstruction
{
public:
S390SSEInstruction(TR::InstOpCode::Mnemonic op, TR::Node * n,
TR::MemoryReference *mf1,
TR::MemoryReference *mf2,
TR::CodeGenerator *cg)
: S390MemMemInstruction(op, n, mf1, mf2, cg)
{
}
S390SSEInstruction(TR::InstOpCode::Mnemonic op, TR::Node * n,
TR::MemoryReference *mf1,
TR::MemoryReference *mf2,
TR::Instruction *precedingInstruction,
TR::CodeGenerator *cg)
: S390MemMemInstruction(op, n, mf1, mf2, precedingInstruction, cg)
{
}
virtual char *description() { return "S390SSEInstruction"; }
virtual Kind getKind() { return IsSSE; }
};
////////////////////////////////////////////////////////////////////////////////
// S390RXInstruction Class Definition
////////////////////////////////////////////////////////////////////////////////
class S390RXInstruction : public TR::S390RegInstruction
{
public:
S390RXInstruction(TR::InstOpCode::Mnemonic op, TR::Node * n,
TR::Register *treg,
TR::MemoryReference *mf,
TR::CodeGenerator *cg)
: S390RegInstruction(op, n, treg, cg)
{
useSourceMemoryReference(mf);
setupThrowsImplicitNullPointerException(n,mf);
if (mf->getUnresolvedSnippet() != NULL)
(mf->getUnresolvedSnippet())->setDataReferenceInstruction(this);
}
S390RXInstruction(TR::InstOpCode::Mnemonic op, TR::Node * n,
TR::Register *treg,
TR::MemoryReference *mf,
TR::Instruction *precedingInstruction,
TR::CodeGenerator *cg)
: S390RegInstruction(op, n, treg, precedingInstruction, cg)
{
useSourceMemoryReference(mf);
setupThrowsImplicitNullPointerException(n,mf);
if (mf->getUnresolvedSnippet() != NULL)
(mf->getUnresolvedSnippet())->setDataReferenceInstruction(this);
}
S390RXInstruction(TR::InstOpCode::Mnemonic op, TR::Node * n,
TR::RegisterPair *regp,
TR::MemoryReference *mf,
TR::CodeGenerator *cg)
: S390RegInstruction(op, n, regp, cg)
{
useSourceMemoryReference(mf);
setupThrowsImplicitNullPointerException(n,mf);
if (mf->getUnresolvedSnippet() != NULL)
(mf->getUnresolvedSnippet())->setDataReferenceInstruction(this);
}
S390RXInstruction(TR::InstOpCode::Mnemonic op, TR::Node * n,
TR::RegisterPair *regp,
TR::MemoryReference *mf,
TR::Instruction *precedingInstruction,
TR::CodeGenerator *cg)
: S390RegInstruction(op, n, regp, precedingInstruction, cg)
{
useSourceMemoryReference(mf);
setupThrowsImplicitNullPointerException(n,mf);
if (mf->getUnresolvedSnippet() != NULL)
(mf->getUnresolvedSnippet())->setDataReferenceInstruction(this);
}
virtual char *description() { return "S390RXInstruction"; }
virtual Kind getKind() { return IsRX; }
virtual TR::MemoryReference *getMemoryReference() { return (_sourceMemSize!=0) ? (sourceMemBase())[0] : NULL;}
virtual uint8_t *generateBinaryEncoding();
virtual bool refsRegister(TR::Register *reg);
virtual int32_t estimateBinaryLength(int32_t currentEstimate);
};
/**
* S390RXEInstruction Class Definition
*
* RXE
* ________________________________________________________
* |Op Code | R1 | X2 | B2 | D2 | M3*| |Op Code|
* |________|____|____|____|______________|____|____|_______|
* 0 8 12 16 20 32 36 40 47
*
*/
class S390RXEInstruction : public TR::S390RXInstruction
{
uint8_t mask3;
public:
S390RXEInstruction(TR::InstOpCode::Mnemonic op, TR::Node * n,
TR::Register *treg,
TR::MemoryReference *mf,
uint8_t m3,
TR::CodeGenerator *cg)
: S390RXInstruction(op, n, treg, mf, cg)
{
mask3 = m3;
}
S390RXEInstruction(TR::InstOpCode::Mnemonic op, TR::Node * n,
TR::Register *treg,
TR::MemoryReference *mf,
uint8_t m3,
TR::Instruction *precedingInstruction,
TR::CodeGenerator *cg)
: S390RXInstruction(op, n, treg, mf, precedingInstruction, cg)
{
mask3 = m3;
}
uint8_t getM3() {return mask3;}
virtual char *description() { return "S390RXEInstruction"; }
virtual Kind getKind() { return IsRXE; }
virtual uint8_t *generateBinaryEncoding();
virtual int32_t estimateBinaryLength(int32_t currentEstimate);
};
////////////////////////////////////////////////////////////////////////////////
// S390RXYInstruction Class Definition
////////////////////////////////////////////////////////////////////////////////
class S390RXYInstruction : public TR::S390RXInstruction
{
public:
S390RXYInstruction(TR::InstOpCode::Mnemonic op, TR::Node * n,
TR::Register *treg,
TR::MemoryReference *mf,
TR::CodeGenerator *cg)
: S390RXInstruction(op, n, treg, mf, cg)
{
}
S390RXYInstruction(TR::InstOpCode::Mnemonic op, TR::Node * n,
TR::Register *treg,
TR::MemoryReference *mf,
TR::Instruction *precedingInstruction,
TR::CodeGenerator *cg)
: S390RXInstruction(op, n, treg, mf, precedingInstruction, cg)
{
}
S390RXYInstruction(TR::InstOpCode::Mnemonic op, TR::Node * n,
TR::RegisterPair *regp,
TR::MemoryReference *mf,
TR::CodeGenerator *cg)
: S390RXInstruction(op, n, regp, mf, cg)
{
}
S390RXYInstruction(TR::InstOpCode::Mnemonic op, TR::Node * n,
TR::RegisterPair *regp,
TR::MemoryReference *mf,
TR::Instruction *precedingInstruction,
TR::CodeGenerator *cg)
: S390RXInstruction(op, n, regp, mf, precedingInstruction, cg)
{
}
virtual char *description() { return "S390RXYInstruction"; }
virtual Kind getKind() { return IsRXY; }
virtual uint8_t *generateBinaryEncoding();
virtual int32_t estimateBinaryLength(int32_t currentEstimate);
};
////////////////////////////////////////////////////////////////////////////////
// S390RXYInstruction Class Definition
////////////////////////////////////////////////////////////////////////////////
class S390RXYbInstruction : public TR::S390MemInstruction
{
public:
S390RXYbInstruction(TR::InstOpCode::Mnemonic op, TR::Node * n,
uint8_t mask,
TR::MemoryReference *mf,
TR::CodeGenerator *cg)
: S390MemInstruction(op, n, mask, mf, cg)
{
}
S390RXYbInstruction(TR::InstOpCode::Mnemonic op, TR::Node * n,
uint8_t mask,
TR::MemoryReference *mf,
TR::Instruction *precedingInstruction,
TR::CodeGenerator *cg)
: S390MemInstruction(op, n, mask, mf, precedingInstruction, cg)
{
}
virtual char *description() { return "S390RXYbInstruction"; }
virtual Kind getKind() { return IsRXYb; }
virtual void setKind(Kind kind) { return; }
};
/**
* S390SSFInstruction Class Definition
* ________ _____________ ______________________________
* |Op Code | R3 | Op | B1 | D1 | B2 | D2 |
* |________|______|______|____|_______|______|__________|
* 0 8 12 16 20 32 36 47
*
*/
class S390SSFInstruction : public TR::S390RXInstruction
{
// TR::MemoryReference *_memoryReference2; // second memory reference operand
public:
S390SSFInstruction(TR::InstOpCode::Mnemonic op,
TR::Node * n,
TR::Register *reg,
TR::MemoryReference *mf1,
TR::MemoryReference *mf2,
TR::CodeGenerator *cg)
: S390RXInstruction(op, n, reg, mf1, cg)
{
useSourceMemoryReference(mf2);
mf2->setIs2ndMemRef();
setupThrowsImplicitNullPointerException(n,mf2);
}
S390SSFInstruction(TR::InstOpCode::Mnemonic op,
TR::Node * n,
TR::Register *reg,
TR::MemoryReference *mf1,
TR::MemoryReference *mf2,
TR::Instruction *precedingInstruction,
TR::CodeGenerator *cg)
: S390RXInstruction(op, n, reg, mf1, precedingInstruction, cg)
{
useSourceMemoryReference(mf2);
mf2->setIs2ndMemRef();
setupThrowsImplicitNullPointerException(n,mf2);
}
S390SSFInstruction(TR::InstOpCode::Mnemonic op,
TR::Node * n,
TR::RegisterPair *regp,
TR::MemoryReference *mf1,
TR::MemoryReference *mf2,
TR::CodeGenerator *cg)
: S390RXInstruction(op, n, regp, mf1, cg)
{
useSourceMemoryReference(mf2);
mf2->setIs2ndMemRef();
setupThrowsImplicitNullPointerException(n,mf2);
}
S390SSFInstruction(TR::InstOpCode::Mnemonic op,
TR::Node * n,
TR::RegisterPair *regp,
TR::MemoryReference *mf1,
TR::MemoryReference *mf2,
TR::Instruction *precedingInstruction,
TR::CodeGenerator *cg)
: S390RXInstruction(op, n, regp, mf1, precedingInstruction, cg)
{
useSourceMemoryReference(mf2);
mf2->setIs2ndMemRef();
setupThrowsImplicitNullPointerException(n,mf2);
}
virtual char *description() { return "S390SSFInstruction"; }
virtual Kind getKind() { return IsSSF; }
virtual TR::MemoryReference *getMemoryReference2() { return (_sourceMemSize==2) ? (sourceMemBase())[1] : NULL; }
virtual int32_t estimateBinaryLength(int32_t currentEstimate);
virtual bool refsRegister(TR::Register *reg);
virtual uint8_t *generateBinaryEncoding();
};
////////////////////////////////////////////////////////////////////////////////
// S390RXFInstruction Class Definition
////////////////////////////////////////////////////////////////////////////////
class S390RXFInstruction : public TR::S390RRInstruction
{
public:
S390RXFInstruction(TR::InstOpCode::Mnemonic op, TR::Node * n,
TR::Register *treg,
TR::Register *sreg,
TR::MemoryReference *mf,
TR::CodeGenerator *cg)
: S390RRInstruction(op, n, treg, sreg, cg)
{
useSourceMemoryReference(mf);
setupThrowsImplicitNullPointerException(n,mf);
}
S390RXFInstruction(TR::InstOpCode::Mnemonic op, TR::Node * n,
TR::Register *treg,
TR::Register *sreg,
TR::MemoryReference *mf,
TR::Instruction *precedingInstruction,
TR::CodeGenerator *cg)
: S390RRInstruction(op, n, treg, sreg, precedingInstruction, cg)
{
useSourceMemoryReference(mf);
setupThrowsImplicitNullPointerException(n,mf);
}
S390RXFInstruction(TR::InstOpCode::Mnemonic op, TR::Node * n,
TR::Register *treg,
TR::Register *sreg,
TR::MemoryReference *mf,
TR::RegisterDependencyConditions * cond,
TR::CodeGenerator *cg)
: S390RRInstruction(op, n, treg, sreg, cond, cg)
{
useSourceMemoryReference(mf);
setupThrowsImplicitNullPointerException(n,mf);
}
S390RXFInstruction(TR::InstOpCode::Mnemonic op, TR::Node * n,
TR::Register *treg,
TR::Register *sreg,
TR::MemoryReference *mf,
TR::RegisterDependencyConditions * cond,
TR::Instruction *precedingInstruction,
TR::CodeGenerator *cg)
: S390RRInstruction(op, n, treg, sreg, cond, precedingInstruction, cg)
{
useSourceMemoryReference(mf);
setupThrowsImplicitNullPointerException(n,mf);
}
virtual char *description() { return "S390RXFInstruction"; }
virtual Kind getKind() { return IsRXF; }
virtual TR::MemoryReference *getMemoryReference() {return (_sourceMemSize!=0) ? (sourceMemBase())[0] : NULL;}
virtual uint8_t *generateBinaryEncoding();
virtual bool refsRegister(TR::Register *reg);
virtual int32_t estimateBinaryLength(int32_t currentEstimate);
};
/**
* S390VInstruction Class Definition
*
* Vector operation Generic class
* Six subtypes: VRI, VRR, VRS, VRV, VRX, VSI
*/
class S390VInstruction : public S390RegInstruction
{
char *_opCodeBuffer;
protected:
S390VInstruction(
TR::CodeGenerator * cg,
TR::InstOpCode::Mnemonic op,
TR::Node * n,
TR::Register * reg1)
: S390RegInstruction(op, n, reg1, cg)
{
_opCodeBuffer = NULL;
}
S390VInstruction(
TR::CodeGenerator * cg,
TR::InstOpCode::Mnemonic op,
TR::Node * n,
TR::Register * reg1,
TR::Instruction * precedingInstruction)
: S390RegInstruction(op, n, reg1, precedingInstruction, cg)
{
_opCodeBuffer = NULL;
}
S390VInstruction(
TR::CodeGenerator * cg,
TR::InstOpCode::Mnemonic op,
TR::Node * n)
: S390RegInstruction(op, n, cg)
{
_opCodeBuffer = NULL;
}
~S390VInstruction();
/**
* Set mask field
* <p>
* field 0 to 3 corresponding to bit 20 to bit 35, 4 bits for each field
* These fields cover all bytes that can potenailly hold instruction masks.
* Applicable to all Vector instructions
*/
virtual void setMaskField(uint32_t *instruction, uint8_t mask, int nField)
{
TR_ASSERT(nField >= 0 && nField <= 3, "Field index out of range.");
int nibbleIndex = (nField < 3) ? (2 - nField) : (7);
instruction = (nField < 3) ? instruction : (instruction + 1);
TR::Instruction::setMaskField(instruction, mask, nibbleIndex);
}
virtual int32_t estimateBinaryLength(int32_t currentEstimate);
virtual char *description() { return "S390VInstruction"; }
virtual Kind getKind() = 0;
virtual uint8_t * generateBinaryEncoding() = 0;
virtual char *setOpCodeBuffer(char *c);
virtual char *getOpCodeBuffer() { return _opCodeBuffer; }
public:
virtual const char *getExtendedMnemonicName() = 0;
};
/**
* S390VRIInstruction Class Definition
*
* Vector register-and-immediate operation with extended op-code field
* Nine subtypes: VRI-a to VRI-i
*/
class S390VRIInstruction : public S390VInstruction
{
private:
// masks starting from bit 28 to bit 35, 4 bits each field
uint8_t _mask3;
uint8_t _mask4;
uint8_t _mask5;
// VRI formats' Immediate can have one/two of the following: I2, I3, I4
// each can be 8, 12, or 16 bit long, not necessarily consecutive in each instruction
// combined length can be up to 20 bits. Different sub-types use the following
// two pieces differently
uint16_t _constantImm16;
uint8_t _constantImm8;
bool _printM3;
bool _printM4;
bool _printM5;
/*
*
* We want these to be called only by helper constructors
*/
protected:
S390VRIInstruction(
TR::CodeGenerator * cg = NULL,
TR::InstOpCode::Mnemonic op = TR::InstOpCode::BAD,
TR::Node * n = NULL,
TR::Register * targetReg = NULL,
uint16_t constantImm16 = 0,
uint8_t constantImm8 = 0,
uint8_t m3 = 0, /* 4 bits (28 - 31 bit) */
uint8_t m4 = 0, /* 4 bits (28 - 31 bit) */
uint8_t m5 = 0) /* 4 bits (32 - 35 bit) */
: S390VInstruction(cg, op, n, targetReg),
_constantImm16(constantImm16),
_constantImm8(constantImm8)
{
_mask3 = m3;
_mask4 = m4;
_mask5 = m5;
_printM3 = getOpCode().usesM3();
_printM4 = getOpCode().usesM4();
_printM5 = getOpCode().usesM5();
}
public:
uint8_t getM3() {return _mask3;}
uint8_t getM4() {return _mask4;}
uint8_t getM5() {return _mask5;}
uint16_t getImmediateField16(){ return _constantImm16; }
uint8_t getImmediateField8(){ return _constantImm8; }
virtual char *description() { return "S390VRIInstruction"; }
virtual Kind getKind() = 0;
const char *getExtendedMnemonicName();
bool setPrintM3(bool b = false) { return _printM3 = b; }
bool setPrintM4(bool b = false) { return _printM4 = b; }
bool setPrintM5(bool b = false) { return _printM5 = b; }
bool getPrintM3() { return _printM3; }
bool getPrintM4() { return _printM4; }
bool getPrintM5() { return _printM5; }
protected:
uint8_t* preGenerateBinaryEncoding();
virtual uint8_t * generateBinaryEncoding() = 0;
uint8_t* postGenerateBinaryEncoding(uint8_t*);
};
#define CAT8TO16(val1, val2) ((uint16_t)((((uint16_t)val1) << 8) | ((uint16_t)val2)))
/**
* VRI-a Class
* ________________________________________________________
* |Op Code | V1 | | I2 | M3*|RXB |Op Code|
* |________|____|____|___________________|____|____|_______|
* 0 8 12 16 32 36 40 47
*/
class S390VRIaInstruction : public S390VRIInstruction
{
public:
S390VRIaInstruction(
TR::CodeGenerator * cg = NULL,
TR::InstOpCode::Mnemonic op = TR::InstOpCode::BAD,
TR::Node * n = NULL,
TR::Register * targetReg = NULL,
uint16_t constantImm2 = 0, /* 16 bits */
uint8_t mask3 = 0) /* 4 bits */
: S390VRIInstruction(cg, op, n, targetReg, constantImm2, 0, mask3, 0, 0)
{
}
uint16_t getImmediateField2() { return getImmediateField16(); }
virtual char *description() { return "S390VRIaInstruction"; }
virtual Kind getKind() { return IsVRIa; }
uint8_t * generateBinaryEncoding();
};
/**
* VRI-b Class
* ________________________________________________________
* |Op Code | V1 | | I2 | I3 | M4*|RXB |Op Code|
* |________|____|____|_________|_________|____|____|_______|
* 0 8 12 16 24 28 32 36 40 47
*/
class S390VRIbInstruction : public S390VRIInstruction
{
public:
S390VRIbInstruction(
TR::CodeGenerator * cg = NULL,
TR::InstOpCode::Mnemonic op = TR::InstOpCode::BAD,
TR::Node * n = NULL,
TR::Register * targetReg = NULL,
uint8_t constantImm2 = 0, /* 8 bits */
uint8_t constantImm3 = 0, /* 8 bits */
uint8_t mask4 = 0) /* 4 bits */
: S390VRIInstruction(cg, op, n, targetReg, CAT8TO16(constantImm2, constantImm3), 0, 0, mask4, 0)
{
}
uint8_t getImmediateField2() { return getImmediateField16() >> 8; }
uint8_t getImmediateField3() { return getImmediateField16() & 0xff; }
virtual char *description() { return "S390VRIbInstruction"; }
virtual Kind getKind() { return IsVRIb; }
uint8_t * generateBinaryEncoding();
};
/** VRI-c Class
* ________________________________________________________
* |Op Code | V1 | V3 | I2 | M4 |RXB |Op Code|
* |________|____|____|___________________|____|____|_______|
* 0 8 12 16 32 36 40 47
*/
class S390VRIcInstruction : public S390VRIInstruction
{
public:
S390VRIcInstruction(
TR::CodeGenerator * cg = NULL,
TR::InstOpCode::Mnemonic op = TR::InstOpCode::BAD,
TR::Node * n = NULL,
TR::Register * targetReg = NULL,
TR::Register * sourceReg3 = NULL,
uint16_t constantImm2 = 0, /* 16 bits */
uint8_t mask4 = 0) /* 4 bits */
: S390VRIInstruction(cg, op, n, targetReg, constantImm2, 0, 0, mask4, 0)
{
if(getOpCode().setsOperand2())
useTargetRegister(sourceReg3);
else
useSourceRegister(sourceReg3);
}
uint16_t getImmediateField2() { return getImmediateField16(); }
virtual char *description() { return "S390VRIcInstruction"; }
virtual Kind getKind() { return IsVRIc; }
uint8_t * generateBinaryEncoding();
};
/**
* VRI-d Class
* ________________________________________________________
* |Op Code | V1 | V2 | V3 | | I4 | M5*|RXB |Op Code|
* |________|____|____|____|____|_________|____|____|_______|
* 0 8 12 16 20 24 32 36 40 47
*/
class S390VRIdInstruction : public S390VRIInstruction
{
public:
S390VRIdInstruction(
TR::CodeGenerator * cg = NULL,
TR::InstOpCode::Mnemonic op = TR::InstOpCode::BAD,
TR::Node * n = NULL,
TR::Register * targetReg = NULL,
TR::Register * sourceReg2 = NULL,
TR::Register * sourceReg3 = NULL,
uint8_t constantImm4 = 0, /* 8 bit */
uint8_t mask5 = 0) /* 4 bits */
: S390VRIInstruction(cg, op, n, targetReg, CAT8TO16(0, constantImm4), 0, 0, 0, mask5)
{
if (getOpCode().setsOperand2())
useTargetRegister(sourceReg2);
else
useSourceRegister(sourceReg2);
if (getOpCode().setsOperand3())
useTargetRegister(sourceReg3);
else
useSourceRegister(sourceReg3);
}
uint8_t getImmediateField4() { return getImmediateField16() & 0xff; }
virtual char *description() { return "S390VRIdInstruction"; }
virtual Kind getKind() { return IsVRId; }
uint8_t * generateBinaryEncoding();
};
/**
* VRI-e Class
* ________________________________________________________
* |Op Code | V1 | V2 | I3 | M5 | M4 |RXB |Op Code|
* |________|____|____|______________|____|____|____|_______|
* 0 8 12 16 28 32 36 40 47
*/
class S390VRIeInstruction : public S390VRIInstruction
{
public:
S390VRIeInstruction(
TR::CodeGenerator * cg = NULL,
TR::InstOpCode::Mnemonic op = TR::InstOpCode::BAD,
TR::Node * n = NULL,
TR::Register * targetReg = NULL,
TR::Register * sourceReg2 = NULL,
uint16_t constantImm3 = 0, /* 12 bits */
uint8_t mask5 = 0, /* 4 bits */
uint8_t mask4 = 0) /* 4 bits */
: S390VRIInstruction(cg, op, n, targetReg, (constantImm3 << 4), 0, 0, mask4, mask5)
{
// Error Checking
TR_ASSERT((constantImm3 & 0xf000) == 0, "Incorrect length in immediate 3 value");
if (getOpCode().setsOperand2())
useTargetRegister(sourceReg2);
else
useSourceRegister(sourceReg2);
}
uint16_t getImmediateField3() { return getImmediateField16() >> 4; }
virtual char *description() { return "S390VRIeInstruction"; }
virtual Kind getKind() { return IsVRIe; }
uint8_t * generateBinaryEncoding();
};
/**
* VRI-f Class
* _________________________________________________________
* |Op Code | V1 | V2 | V3 | /// | M5 | I4 |RXB |Op Code|
* |________|____|____|____|______|____|________|____|_______|
* 0 8 12 16 20 24 28 36 40 47
*/
class S390VRIfInstruction : public S390VRIInstruction
{
public:
S390VRIfInstruction(
TR::CodeGenerator * cg = NULL,
TR::InstOpCode::Mnemonic op = TR::InstOpCode::BAD,
TR::Node * n = NULL,
TR::Register * targetReg = NULL,
TR::Register * sourceReg2 = NULL,
TR::Register * sourceReg3 = NULL,
uint8_t constantImm4 = 0, /* 8 bits */
uint8_t mask5 = 0) /* 4 bits */
: S390VRIInstruction(cg, op, n, targetReg, CAT8TO16(0, constantImm4), 0, 0, 0, mask5)
{
if (getOpCode().setsOperand2())
useTargetRegister(sourceReg2);
else
useSourceRegister(sourceReg2);
if (getOpCode().setsOperand3())
useTargetRegister(sourceReg3);
else
useSourceRegister(sourceReg3);
}
uint8_t getImmediateField4() { return getImmediateField16() & 0xff; }
char *description() { return "S390VRIfInstruction"; }
Kind getKind() { return IsVRIf; }
uint8_t * generateBinaryEncoding();
};
/**
* VRI-g Class
* _________________________________________________________
* |Op Code | V1 | V2 | I4 | M5 | I3 |RXB |Op Code|
* |________|____|____|_________|____|__________|____|_______|
* 0 8 12 16 24 28 36 40 47
*/
class S390VRIgInstruction : public S390VRIInstruction
{
public:
S390VRIgInstruction(
TR::CodeGenerator * cg = NULL,
TR::InstOpCode::Mnemonic op = TR::InstOpCode::BAD,
TR::Node * n = NULL,
TR::Register * targetReg = NULL,
TR::Register * sourceReg2 = NULL,
uint8_t constantImm3 = 0, /* 8 bits */
uint8_t constantImm4 = 0, /* 8 bits */
uint8_t mask5 = 0) /* 4 bits */
: S390VRIInstruction(cg, op, n, targetReg, CAT8TO16(0, constantImm3), constantImm4, 0, 0, mask5)
{
if (getOpCode().setsOperand2())
useTargetRegister(sourceReg2);
else
useSourceRegister(sourceReg2);
}
uint16_t getImmediateField3() { return getImmediateField16() & 0xff; }
uint8_t getImmediateField4() { return getImmediateField8(); }
char *description() { return "S390VRIgInstruction"; }
Kind getKind() { return IsVRIg; }
uint8_t * generateBinaryEncoding();
};
/**
* VRI-h Class
* _________________________________________________________
* |Op Code | V1 |/// | I2 | I3 |RXB |Op Code|
* |________|____|____|__________________|______|____|_______|
* 0 8 12 16 32 36 40 47
*/
class S390VRIhInstruction : public S390VRIInstruction
{
public:
S390VRIhInstruction(
TR::CodeGenerator * cg = NULL,
TR::InstOpCode::Mnemonic op = TR::InstOpCode::BAD,
TR::Node * n = NULL,
TR::Register * targetReg = NULL,
uint16_t constantImm2 = 0, /* 16 bits */
uint8_t constantImm3 = 0) /* 4 bits */
: S390VRIInstruction(cg, op, n, targetReg, constantImm2, constantImm3, 0, 0, 0)
{
// Error check constantImm3 is no longer than 4bit
TR_ASSERT((constantImm3 & 0xf0) == 0, "Incorrect length in immediate 3 value");
}
uint16_t getImmediateField2() { return getImmediateField16(); }
uint8_t getImmediateField3() { return getImmediateField8(); }
char *description() { return "S390VRIhInstruction"; }
Kind getKind() { return IsVRIh; }
uint8_t * generateBinaryEncoding();
};
/**
* VRI-i Class
* _________________________________________________________
* |Op Code | V1 | R2 | ///// | M4 | I3 |RXB |Op Code|
* |________|____|____|________|____|__________|____|_______|
* 0 8 12 16 24 28 36 40 47
*/
class S390VRIiInstruction : public S390VRIInstruction
{
public:
S390VRIiInstruction(
TR::CodeGenerator * cg = NULL,
TR::InstOpCode::Mnemonic op = TR::InstOpCode::BAD,
TR::Node * n = NULL,
TR::Register * targetReg = NULL,
TR::Register * sourceReg2 = NULL,
uint8_t constantImm3 = 0, /* 8 bits */
uint8_t mask4 = 0) /* 4 bits */
: S390VRIInstruction(cg, op, n, targetReg, 0, constantImm3, 0, mask4, 0)
{
if (getOpCode().setsOperand2())
useTargetRegister(sourceReg2);
else
useSourceRegister(sourceReg2);
}
uint8_t getImmediateField3() { return getImmediateField8(); }
char *description() { return "S390VRIiInstruction"; }
Kind getKind() { return IsVRIi; }
uint8_t * generateBinaryEncoding();
};
/**
* S390VRRInstruction Class Definition
*
* Vector register-and-register operation with extended op-code field
* Has 9 subtypes: VRR-a to VRR-i
*
*/
class S390VRRInstruction : public S390VInstruction
{
// masks at bit 20 to bit 35 (not necessarily in order), 4 bits each field
uint8_t mask3;
uint8_t mask4;
uint8_t mask5;
uint8_t mask6;
bool _printM3;
bool _printM4;
bool _printM5;
bool _printM6;
public:
virtual char *description() { return "S390VRRInstruction"; }
virtual Kind getKind() = 0;
uint8_t getM3() {return mask3;}
uint8_t getM4() {return mask4;}
uint8_t getM5() {return mask5;}
uint8_t getM6() {return mask6;}
const char *getExtendedMnemonicName();
bool setPrintM3(bool b = false) { return _printM3 = b; }
bool setPrintM4(bool b = false) { return _printM4 = b; }
bool setPrintM5(bool b = false) { return _printM5 = b; }
bool setPrintM6(bool b = false) { return _printM6 = b; }
bool getPrintM3() { return _printM3; }
bool getPrintM4() { return _printM4; }
bool getPrintM5() { return _printM5; }
bool getPrintM6() { return _printM6; }
/* We want these to be called only by helper constructors */
protected:
S390VRRInstruction(
TR::CodeGenerator * cg = NULL,
TR::InstOpCode::Mnemonic op = TR::InstOpCode::BAD,
TR::Node * n = NULL,
TR::Register * targetReg = NULL,
TR::Register * sourceReg2 = NULL,
uint8_t m3 = 0, /* Mask3 */
uint8_t m4 = 0, /* Mask4 */
uint8_t m5 = 0, /* Mask5 */
uint8_t m6 = 0) /* Mask6 */
: S390VInstruction(cg, op, n, targetReg)
{
if(sourceReg2 != NULL)
{
if (getOpCode().setsOperand2())
useTargetRegister(sourceReg2);
else
useSourceRegister(sourceReg2);
}
mask3 = m3;
mask4 = m4;
mask5 = m5;
mask6 = m6;
_printM3 = getOpCode().usesM3();
_printM4 = getOpCode().usesM4();
_printM5 = getOpCode().usesM5();
_printM6 = getOpCode().usesM6();
}
S390VRRInstruction(
TR::CodeGenerator * cg,
TR::InstOpCode::Mnemonic op,
TR::Node * n,
TR::Register * targetReg,
TR::Register * sourceReg2,
uint8_t m3, /* Mask3 */
uint8_t m4, /* Mask4 */
uint8_t m5, /* Mask5 */
uint8_t m6, /* Mask6 */
TR::Instruction * precedingInstruction)
: S390VInstruction(cg, op, n, targetReg, precedingInstruction)
{
if (getOpCode().setsOperand2())
useTargetRegister(sourceReg2);
else
useSourceRegister(sourceReg2);
mask3 = m3;
mask4 = m4;
mask5 = m5;
mask6 = m6;
_printM3 = getOpCode().usesM3();
_printM4 = getOpCode().usesM4();
_printM5 = getOpCode().usesM5();
_printM6 = getOpCode().usesM6();
}
virtual uint8_t * generateBinaryEncoding();
};
/**
* VRR-a
* ________________________________________________________
* |Op Code | V1 | V2 | | M5*| M4*| M3*|RXB |Op Code|
* |________|____|____|_________|____|____|____|____|_______|
* 0 8 12 16 24 28 32 36 40 47
*/
class S390VRRaInstruction: public S390VRRInstruction
{
public:
S390VRRaInstruction(
TR::CodeGenerator * cg = NULL,
TR::InstOpCode::Mnemonic op = TR::InstOpCode::BAD,
TR::Node * n = NULL,
TR::Register * targetReg = NULL,
TR::Register * sourceReg2 = NULL,
uint8_t mask5 = 0, /* 4 bits */
uint8_t mask4 = 0, /* 4 bits */
uint8_t mask3 = 0) /* 4 bits */
: S390VRRInstruction(cg, op, n, targetReg, sourceReg2, mask3, mask4, mask5, 0)
{
}
S390VRRaInstruction(
TR::CodeGenerator * cg,
TR::InstOpCode::Mnemonic op,
TR::Node * n,
TR::Register * targetReg,
TR::Register * sourceReg2,
uint8_t mask5, /* 4 bits */
uint8_t mask4, /* 4 bits */
uint8_t mask3, /* 4 bits */
TR::Instruction * precedingInstruction)
: S390VRRInstruction(cg, op, n, targetReg, sourceReg2, mask3, mask4, mask5, 0, precedingInstruction)
{
}
char *description() { return "S390VRRaInstruction"; }
Kind getKind() { return IsVRRa; }
uint8_t * generateBinaryEncoding();
};
/**
* VRR-b
* ________________________________________________________
* |Op Code | V1 | V2 | V3 | | M5*| | M4*|RXB |Op Code|
* |________|____|____|____|____|____|____|____|____|_______|
* 0 8 12 16 24 28 32 36 40 47
*/
class S390VRRbInstruction: public S390VRRInstruction
{
public:
S390VRRbInstruction(
TR::CodeGenerator * cg = NULL,
TR::InstOpCode::Mnemonic op = TR::InstOpCode::BAS,
TR::Node * n = NULL,
TR::Register * targetReg = NULL,
TR::Register * sourceReg2 = 0,
TR::Register * sourceReg3 = 0,
uint8_t mask5 = 0, /* 4 bits */
uint8_t mask4 = 0) /* 4 bits */
: S390VRRInstruction(cg, op, n, targetReg, sourceReg2, 0, mask4, mask5, 0)
{
if(getOpCode().setsOperand3())
useTargetRegister(sourceReg3);
else
useSourceRegister(sourceReg3);
}
char *description() { return "S390VRRbInstruction"; }
Kind getKind() { return IsVRRb; }
uint8_t * generateBinaryEncoding();
};
/**
* VRR-c
* ________________________________________________________
* |Op Code | V1 | V2 | V3 | | M6*| M5*| M4*|RXB |Op Code|
* |________|____|____|____|____|____|____|____|____|_______|
* 0 8 12 16 24 28 32 36 40 47
*/
class S390VRRcInstruction: public S390VRRInstruction
{
public:
S390VRRcInstruction(
TR::CodeGenerator * cg = NULL,
TR::InstOpCode::Mnemonic op = TR::InstOpCode::BAD,
TR::Node * n = NULL,
TR::Register * targetReg = NULL,
TR::Register * sourceReg2 = NULL,
TR::Register * sourceReg3 = NULL,
uint8_t mask6 = 0, /* 4 bits */
uint8_t mask5 = 0, /* 4 bits */
uint8_t mask4 = 0) /* 4 bits */
: S390VRRInstruction(cg, op, n, targetReg, sourceReg2, 0, mask4, mask5, mask6)
{
if (getOpCode().setsOperand3())
useTargetRegister(sourceReg3);
else
useSourceRegister(sourceReg3);
}
char *description() { return "S390VRRcInstruction"; }
Kind getKind() { return IsVRRc; }
uint8_t * generateBinaryEncoding();
};
/**
* VRR-d
* ________________________________________________________
* |Op Code | V1 | V2 | V3 | M5*| M6*| | V4 |RXB |Op Code|
* |________|____|____|____|____|____|____|____|____|_______|
* 0 8 12 16 20 24 28 32 36 40 47
*/
class S390VRRdInstruction: public S390VRRInstruction
{
public:
S390VRRdInstruction(
TR::CodeGenerator * cg = NULL,
TR::InstOpCode::Mnemonic op = TR::InstOpCode::BAD,
TR::Node * n = NULL,
TR::Register * targetReg = NULL,
TR::Register * sourceReg2 = NULL,
TR::Register * sourceReg3 = NULL,
TR::Register * sourceReg4 = NULL,
uint8_t mask6 = 0, /* 4 bits */
uint8_t mask5 = 0) /* 4 bits */
: S390VRRInstruction(cg, op, n, targetReg, sourceReg2, 0, 0, mask5, mask6)
{
if (getOpCode().setsOperand3())
useTargetRegister(sourceReg3);
else
useSourceRegister(sourceReg3);
if (getOpCode().setsOperand4())
useTargetRegister(sourceReg4);
else
useSourceRegister(sourceReg4);
}
char *description() { return "S390VRRdInstruction"; }
Kind getKind() { return IsVRRd; }
uint8_t * generateBinaryEncoding();
};
/**
* VRR-e
* ________________________________________________________
* |Op Code | V1 | V2 | V3 | M6*| | M5*| V4 |RXB |Op Code|
* |________|____|____|____|____|____|____|____|____|_______|
* 0 8 12 16 20 28 32 36 40 47
*/
class S390VRReInstruction: public S390VRRInstruction
{
public:
S390VRReInstruction(
TR::CodeGenerator * cg = NULL,
TR::InstOpCode::Mnemonic op = TR::InstOpCode::BAD,
TR::Node * n = NULL,
TR::Register * targetReg = NULL,
TR::Register * sourceReg2 = NULL,
TR::Register * sourceReg3 = NULL,
TR::Register * sourceReg4 = NULL,
uint8_t mask6 = 0, /* 4 bits */
uint8_t mask5 = 0) /* 4 bits */
: S390VRRInstruction(cg, op, n, targetReg, sourceReg2, 0, 0, mask5, mask6)
{
if (getOpCode().setsOperand3())
useTargetRegister(sourceReg3);
else
useSourceRegister(sourceReg3);
if (getOpCode().setsOperand4())
useTargetRegister(sourceReg4);
else
useSourceRegister(sourceReg4);
}
char *description() { return "S390VRReInstruction"; }
Kind getKind() { return IsVRRe; }
uint8_t * generateBinaryEncoding();
};
/**
* VRR-f
* ________________________________________________________
* |Op Code | V1 | R2 | R3 | ///////////////// |RXB |Op Code|
* |________|____|____|____|___________________|____|_______|
* 0 8 12 16 20 36 40 47
*/
class S390VRRfInstruction: public S390VRRInstruction
{
public:
S390VRRfInstruction(
TR::CodeGenerator * cg = NULL,
TR::InstOpCode::Mnemonic op = TR::InstOpCode::BAD,
TR::Node * n = NULL,
TR::Register * targetReg = NULL,
TR::Register * sourceReg2 = NULL, /* GPR */
TR::Register * sourceReg3 = NULL) /* GPR */
: S390VRRInstruction(cg, op, n, targetReg, sourceReg2, 0, 0, 0, 0)
{
if (getOpCode().setsOperand3())
useTargetRegister(sourceReg3);
else
useSourceRegister(sourceReg3);
}
char *description() { return "S390VRRfInstruction"; }
Kind getKind() { return IsVRRf; }
uint8_t * generateBinaryEncoding();
};
/**
* VRR-g
* ________________________________________________________
* |Op Code | // | V1 | /////////////////// |RXB |Op Code|
* |________|____|____|________________________|____|_______|
* 0 8 12 16 36 40 47
*/
class S390VRRgInstruction: public S390VRRInstruction
{
public:
S390VRRgInstruction(
TR::CodeGenerator * cg = NULL,
TR::InstOpCode::Mnemonic op = TR::InstOpCode::BAD,
TR::Node * n = NULL,
TR::Register * v1Reg = NULL)
: S390VRRInstruction(cg, op, n, v1Reg, NULL, 0, 0, 0, 0)
{
}
char *description() { return "S390VRRgInstruction"; }
Kind getKind() { return IsVRRg; }
uint8_t * generateBinaryEncoding();
};
/**
* VRR-h
* _________________________________________________________
* |Op Code | // | V1 | V2 | /// | M3*| ////// |RXB |Op Code|
* |________|____|____|_____|_____|____|________|____|_______|
* 0 8 12 16 20 24 28 36 40 47
*/
class S390VRRhInstruction: public S390VRRInstruction
{
public:
S390VRRhInstruction(
TR::CodeGenerator * cg = NULL,
TR::InstOpCode::Mnemonic op = TR::InstOpCode::BAD,
TR::Node * n = NULL,
TR::Register * v1Reg = NULL,
TR::Register * v2Reg = NULL,
uint8_t mask3 = 0)
: S390VRRInstruction(cg, op, n, v1Reg, v2Reg, mask3, 0, 0, 0)
{
}
char *description() { return "S390VRRhInstruction"; }
Kind getKind() { return IsVRRh; }
uint8_t * generateBinaryEncoding();
};
/**
* VRR-i
* ___________________________________________________________
* |Op Code | R1 | V2 | ///////// | M3 | M4 |/// |RXB |Op Code|
* |________|____|____|___________|_____|____|____|____|_______|
* 0 8 12 16 24 28 36 40 47
*
* z15 and above have an optional M4 if the vector-packed-decimal-enhancement facility
* is installed.
*/
class S390VRRiInstruction: public S390VRRInstruction
{
public:
S390VRRiInstruction(
TR::CodeGenerator * cg = NULL,
TR::InstOpCode::Mnemonic op = TR::InstOpCode::BAD,
TR::Node * n = NULL,
TR::Register * r1Reg = NULL, /* GPR */
TR::Register * v2Reg = NULL,
uint8_t mask3 = 0,
uint8_t mask4 = 0)
: S390VRRInstruction(cg, op, n, r1Reg, v2Reg, mask3, mask4, 0, 0)
{
}
char *description() { return "S390VRRiInstruction"; }
Kind getKind() { return IsVRRi; }
uint8_t * generateBinaryEncoding();
};
/**
* S390VStorageInstruction Class Definition
*
* Vector Storage related operation with extended op-code field
* Has the following subtypes: VRS(a-d) VRX, VRV, and VSI
*
*/
class S390VStorageInstruction: public S390VInstruction
{
protected:
uint8_t _maskField; // VStorage instructions have at most 1 mask at bit 32-35
bool _printMaskField;
S390VStorageInstruction(
TR::CodeGenerator * cg,
TR::InstOpCode::Mnemonic op,
TR::Node * n,
TR::Register * targetReg, /* VRF or GPR */
TR::Register * sourceReg, /* VRF or GPR */
TR::MemoryReference * mr,
uint8_t mask) /* 4 bits */
: S390VInstruction(cg, op, n, targetReg), _maskField(mask)
{
if (sourceReg)
{
useSourceRegister(sourceReg);
}
useSourceMemoryReference(mr);
setupThrowsImplicitNullPointerException(n, mr);
if (mr->getUnresolvedSnippet() != NULL)
{
(mr->getUnresolvedSnippet())->setDataReferenceInstruction(this);
}
}
S390VStorageInstruction(
TR::CodeGenerator * cg,
TR::InstOpCode::Mnemonic op,
TR::Node * n,
TR::Register * targetReg, /* VRF or GPR */
TR::Register * sourceReg, /* VRF or GPR */
TR::MemoryReference * mr,
uint8_t mask, /* 4 bits */
TR::Instruction * precedingInstruction)
: S390VInstruction(cg, op, n, targetReg, precedingInstruction), _maskField(mask)
{
if (sourceReg)
useSourceRegister(sourceReg);
useSourceMemoryReference(mr);
setupThrowsImplicitNullPointerException(n,mr);
if (mr->getUnresolvedSnippet() != NULL)
{
(mr->getUnresolvedSnippet())->setDataReferenceInstruction(this);
}
}
/**
* This S390VStorageInstruction contructor does not take target/source registers nor mask bits.
* It is useful for vector storage formats that uses registers and immediates only: VSI.
*/
S390VStorageInstruction(
TR::CodeGenerator * cg,
TR::InstOpCode::Mnemonic op,
TR::Node * n)
: S390VInstruction(cg, op, n),
_maskField(0)
{
}
virtual uint8_t * generateBinaryEncoding();
virtual int32_t estimateBinaryLength(int32_t currentEstimate);
public:
virtual TR::MemoryReference* getMemoryReference() { return (_sourceMemSize!=0) ? (sourceMemBase())[0] : NULL; }
virtual char *description() { return "S390VStorageInstruction"; }
virtual Kind getKind() = 0;
uint8_t getMaskField() { return _maskField; }
const char *getExtendedMnemonicName();
bool setPrintMaskField(bool b = false) { return _printMaskField = b; }
bool getPrintMaskField() { return _printMaskField; }
};
/**
* S390VRSInstruction Class Definition
*
* Vector register-and-storage operation with extended op-code field
* Has 4 subtypes: VRS-a to VRS-d
*
*/
class S390VRSInstruction : public S390VInstruction
{
public:
TR::Register* getFirstRegister() { return isTargetPair()? S390RegInstruction::getFirstRegister() : getRegisterOperand(1); }
TR::Register* getLastRegister() { return isTargetPair()? S390RegInstruction::getLastRegister() : getRegisterOperand(2); }
TR::Register* getSecondRegister() {return getRegisterOperand(2); }
/* We want these to be called only by helper constructors */
protected:
S390VRSInstruction(
TR::CodeGenerator * cg = NULL,
TR::InstOpCode::Mnemonic op = TR::InstOpCode::BAD,
TR::Node * n = NULL,
TR::Register * targetReg = NULL, /* VRF */
TR::Register * sourceReg = NULL, /* VRF or GPR */
uint16_t displacement2= 0, /* 12 bits */
uint8_t mask4 = 0, /* 4 bits */
uint8_t bitSet2 = 0) /* 4 bits */
: S390VInstruction(cg, op, n)
{
}
};
/**
* VRS-a
* _________________________________________________________
* |Op Code | V1 | V3 | B2 | D2 | M4*|RXB |Op Code|
* |________|____|____|____|_______________|____|____|_______|
* 0 8 12 16 20 32 36 40 47
*/
class S390VRSaInstruction : public S390VStorageInstruction
{
public:
S390VRSaInstruction(
TR::CodeGenerator * cg = NULL,
TR::InstOpCode::Mnemonic op = TR::InstOpCode::BAD,
TR::Node * n = NULL,
TR::Register * targetReg = NULL, /* VRF */
TR::Register * sourceReg = NULL, /* VRF */
TR::MemoryReference * mr = NULL,
uint8_t mask4 = 0) /* 4 bits */
: S390VStorageInstruction(cg, op, n, targetReg, sourceReg, mr, mask4)
{
setPrintMaskField(getOpCode().usesM4());
}
S390VRSaInstruction(
TR::CodeGenerator * cg ,
TR::InstOpCode::Mnemonic op ,
TR::Node * n ,
TR::Register * targetReg, /* VRF */
TR::Register * sourceReg, /* VRF */
TR::MemoryReference * mr ,
uint8_t mask4 , /* 4 bits */
TR::Instruction * preced)
: S390VStorageInstruction(cg, op, n, targetReg, sourceReg, mr, mask4, preced)
{
setPrintMaskField(getOpCode().usesM4());
}
Kind getKind() { return IsVRSa; }
virtual char *description() { return "S390VRSaInstruction"; }
};
/**
* VRS-b
* _________________________________________________________
* |Op Code | V1 | R3 | B2 | D2 | M4*|RXB |Op Code|
* |________|____|____|____|_______________|____|____|_______|
* 0 8 12 16 20 32 36 40 47
*/
class S390VRSbInstruction : public S390VStorageInstruction
{
public:
S390VRSbInstruction(
TR::CodeGenerator * cg = NULL,
TR::InstOpCode::Mnemonic op = TR::InstOpCode::BAD,
TR::Node * n = NULL,
TR::Register * targetReg = NULL, /* VRF */
TR::Register * sourceReg = NULL, /* GPR */
TR::MemoryReference * mr = NULL,
uint8_t mask4 = 0) /* 4 bits */
: S390VStorageInstruction(cg, op, n, targetReg, sourceReg, mr, mask4)
{
setPrintMaskField(getOpCode().usesM4());
}
S390VRSbInstruction(
TR::CodeGenerator * cg ,
TR::InstOpCode::Mnemonic op ,
TR::Node * n ,
TR::Register * targetReg, /* VRF */
TR::Register * sourceReg, /* GPR */
TR::MemoryReference * mr ,
uint8_t mask4 , /* 4 bits */
TR::Instruction * preced)
: S390VStorageInstruction(cg, op, n, targetReg, sourceReg, mr, mask4, preced)
{
setPrintMaskField(getOpCode().usesM4());
}
Kind getKind() { return IsVRSb; }
virtual char *description() { return "S390VRSbInstruction"; }
};
/**
* VRS-c
* _________________________________________________________
* |Op Code | R1 | V3 | B2 | D2 | M4 |RXB |Op Code|
* |________|____|____|____|_______________|____|____|_______|
* 0 8 12 16 20 32 36 40 47
*/
class S390VRScInstruction : public S390VStorageInstruction
{
public:
S390VRScInstruction(
TR::CodeGenerator * cg = NULL,
TR::InstOpCode::Mnemonic op = TR::InstOpCode::BAD,
TR::Node * n = NULL,
TR::Register * targetReg = NULL, /* GPR */
TR::Register * sourceReg = NULL, /* VRF */
TR::MemoryReference * mr = NULL,
uint8_t mask4 = 0) /* 4 bits */
: S390VStorageInstruction(cg, op, n, targetReg, sourceReg, mr, mask4)
{
setPrintMaskField(getOpCode().usesM4());
}
S390VRScInstruction(
TR::CodeGenerator * cg ,
TR::InstOpCode::Mnemonic op ,
TR::Node * n ,
TR::Register * targetReg, /* GPR */
TR::Register * sourceReg, /* VRF */
TR::MemoryReference * mr ,
uint8_t mask4 , /* 4 bits */
TR::Instruction * preced)
: S390VStorageInstruction(cg, op, n, targetReg, sourceReg, mr, mask4, preced)
{
setPrintMaskField(getOpCode().usesM4());
}
Kind getKind() { return IsVRSc; }
virtual char *description() { return "S390VRScInstruction"; }
};
/**
* VRS-d
* _________________________________________________________
* |Op Code | | R3 | B2 | D2 | V1 |RXB |Op Code|
* |________|____|____|____|_______________|____|____|_______|
* 0 8 12 16 20 32 36 40 47
*
* Assume VRS-d instructions are either load or store
*
* The operand order in the _operands array is:
* --[V1, R3, memRef] for load instructions, and
* --[R3, V1, memRef] for store instructions
*
*/
class S390VRSdInstruction : public S390VStorageInstruction
{
public:
S390VRSdInstruction(
TR::CodeGenerator * cg = NULL,
TR::InstOpCode::Mnemonic op = TR::InstOpCode::BAD,
TR::Node * n = NULL,
TR::Register * r3Reg = NULL, /* GPR */
TR::Register * v1Reg = NULL, /* VRF */
TR::MemoryReference * mr = NULL)
: S390VStorageInstruction(cg, op, n)
{
initVRSd(r3Reg, v1Reg, mr);
}
S390VRSdInstruction(
TR::CodeGenerator * cg ,
TR::InstOpCode::Mnemonic op,
TR::Node * n ,
TR::Register * r3Reg, /* GPR */
TR::Register * v1Reg, /* VRF */
TR::MemoryReference * mr ,
TR::Instruction* preced )
: S390VStorageInstruction(cg, op, n, r3Reg, NULL, mr, 0, preced)
{
initVRSd(r3Reg, v1Reg, mr);
}
Kind getKind() { return IsVRSd; }
uint8_t * generateBinaryEncoding();
char *description() { return "S390VRSdInstruction"; }
private:
void initVRSd(TR::Register* r3Reg, TR::Register* v1Reg, TR::MemoryReference* mr)
{
if(getOpCode().isStore())
{
useTargetRegister(r3Reg);
useSourceRegister(v1Reg);
// In the current design, memRef is always the source for non-Mem-Mem instructions
useSourceMemoryReference(mr);
}
else
{
useTargetRegister(v1Reg);
useSourceRegister(r3Reg);
useSourceMemoryReference(mr);
}
setPrintMaskField(false);
}
};
/**
* S390VRVInstruction Class Definition
* _________________________________________________________
* |Op Code | V1 | V2 | B2 | D2 | M3*|RXB |Op Code|
* |________|____|____|____|_______________|____|____|_______|
* 0 8 12 16 20 32 36 40 47
*
* Vector register-and-vector-index-storage operation with ext. op-code field
*/
class S390VRVInstruction : public S390VStorageInstruction
{
public:
S390VRVInstruction(
TR::CodeGenerator * cg = NULL,
TR::InstOpCode::Mnemonic op = TR::InstOpCode::BAD,
TR::Node * n = NULL,
TR::Register * sourceReg = NULL, /* VRF */
TR::MemoryReference * mr = NULL,
uint8_t mask3 = 0) /* 4 bits */
: S390VStorageInstruction(cg, op, n, sourceReg, sourceReg, mr, mask3)
{
setPrintMaskField(getOpCode().usesM3());
}
S390VRVInstruction(
TR::CodeGenerator * cg ,
TR::InstOpCode::Mnemonic op ,
TR::Node * n ,
TR::Register * sourceReg, /* VRF */
TR::MemoryReference * mr ,
uint8_t mask3 , /* 4 bits */
TR::Instruction * preced)
: S390VStorageInstruction(cg, op, n, sourceReg, sourceReg, mr, mask3, preced)
{
setPrintMaskField(getOpCode().usesM3());
}
Kind getKind() { return IsVRV; }
uint8_t * generateBinaryEncoding();
};
/**
* S390VRXInstruction Class Definition
* ___________________________________________________________
* |Op Code | V1 | X2 | B2 | D2 | M3* | RXB | Op Code |
* |________|______|_____|____|________|_____|______|__________|
* 0 8 12 16 20 32 36 40 47
*
* Vector register-and-index-storage operation with extended op-code field
*/
class S390VRXInstruction : public S390VStorageInstruction
{
public:
S390VRXInstruction(
TR::CodeGenerator * cg = NULL,
TR::InstOpCode::Mnemonic op = TR::InstOpCode::BAD,
TR::Node * n = NULL,
TR::Register * reg = NULL, /* GPR */
TR::MemoryReference * mr = NULL,
uint8_t mask3 = 0) /* 4 bits */
: S390VStorageInstruction(cg, op, n, reg, NULL, mr, mask3)
{
setPrintMaskField(getOpCode().usesM3());
}
S390VRXInstruction(
TR::CodeGenerator * cg,
TR::InstOpCode::Mnemonic op,
TR::Node * n,
TR::Register * reg, /* GPR */
TR::MemoryReference * mr,
uint8_t mask3, /* 4 bits */
TR::Instruction * precedingInstruction)
: S390VStorageInstruction(cg, op, n, reg, NULL, mr, mask3, precedingInstruction)
{
setPrintMaskField(getOpCode().usesM3());
}
Kind getKind() { return IsVRX; }
};
/**
* S390VSIInstruction Class Definition
* __________________________________________________________
* |Op Code | I3 | B2 | D2 | V1 | RXB | Op Code |
* |________|___________|____|________|_____|______|__________|
* 0 8 16 20 32 36 40 47
*
* Vector register-and-storage operation with extended op-code field
*
*/
class S390VSIInstruction : public S390VStorageInstruction
{
public:
S390VSIInstruction(TR::CodeGenerator * cg = NULL,
TR::InstOpCode::Mnemonic op = TR::InstOpCode::BAD,
TR::Node * n = NULL,
TR::Register * v1Reg = NULL,
TR::MemoryReference * memRef = NULL,
uint8_t constantImm3 = 0)
: S390VStorageInstruction(cg, op, n),
_constantImm3(constantImm3)
{
initVSI(n, v1Reg, memRef);
}
S390VSIInstruction(TR::CodeGenerator * cg ,
TR::InstOpCode::Mnemonic op ,
TR::Node * n ,
TR::Register * v1Reg ,
TR::MemoryReference * memRef,
uint8_t constantImm3,
TR::Instruction * preced)
: S390VStorageInstruction(cg, op, n, v1Reg, NULL, memRef, 0, preced),
_constantImm3(constantImm3)
{
}
Kind getKind() { return IsVSI; }
uint8_t getImmediateField3() { return _constantImm3; }
char *description() { return "S390VSIInstruction"; }
uint8_t * generateBinaryEncoding();
private:
uint8_t _constantImm3;
void initVSI(TR::Node* n, TR::Register* v1Reg, TR::MemoryReference* memRef)
{
if(getOpCode().setsOperand1())
{
useTargetRegister(v1Reg);
}
else
{
useSourceRegister(v1Reg);
}
// memrefs are always named source memory reference regardless of what they actually are.
useSourceMemoryReference(memRef);
setupThrowsImplicitNullPointerException(n, memRef);
if (memRef->getUnresolvedSnippet() != NULL)
{
(memRef->getUnresolvedSnippet())->setDataReferenceInstruction(this);
}
setPrintMaskField(false);
}
};
////////////////////////////////////////////////////////////////////////////////
// S390NOPInstruction Class Definition
////////////////////////////////////////////////////////////////////////////////
class S390NOPInstruction : public TR::Instruction
{
public:
S390NOPInstruction(TR::InstOpCode::Mnemonic op,
int32_t numbytes,
TR::Node *n,
TR::CodeGenerator *cg)
: TR::Instruction(op, n, cg)
{
setBinaryLength(numbytes);
setEstimatedBinaryLength(numbytes);
}
S390NOPInstruction(TR::InstOpCode::Mnemonic op,
int32_t numbytes,
TR::Node * n,
TR::Instruction *precedingInstruction,
TR::CodeGenerator *cg)
: TR::Instruction(op, n, precedingInstruction, cg)
{
setBinaryLength(numbytes);
setEstimatedBinaryLength(numbytes);
}
virtual char *description() { return "S390NOPInstruction"; }
virtual Kind getKind() { return IsNOP; }
virtual int32_t estimateBinaryLength(int32_t currentEstimate);
virtual uint8_t *generateBinaryEncoding();
};
////////////////////////////////////////////////////////////////////////////////
// S390IInstruction Class Definition
////////////////////////////////////////////////////////////////////////////////
class S390IInstruction : public TR::Instruction
{
uint8_t _immediate;
public:
S390IInstruction(TR::InstOpCode::Mnemonic op,
TR::Node *n,
uint8_t im,
TR::CodeGenerator *cg)
: TR::Instruction(op, n, cg), _immediate(im)
{
}
S390IInstruction(TR::InstOpCode::Mnemonic op,
TR::Node * n,
uint8_t im,
TR::Instruction *precedingInstruction,
TR::CodeGenerator *cg)
: TR::Instruction(op, n, precedingInstruction, cg), _immediate(im)
{
}
virtual char *description() { return "S390IInstruction"; }
virtual Kind getKind() { return IsI; }
uint32_t getImmediateField() { return _immediate; }
};
////////////////////////////////////////////////////////////////////////////////
// S390EInstruction Class Definition
////////////////////////////////////////////////////////////////////////////////
class S390EInstruction : public TR::Instruction
{
public:
S390EInstruction(TR::InstOpCode::Mnemonic op,
TR::Node *n,
TR::CodeGenerator *cg)
: TR::Instruction(op, n, cg)
{
setBinaryLength(2);
setEstimatedBinaryLength(2);
}
S390EInstruction(TR::InstOpCode::Mnemonic op,
TR::Node * n,
TR::Instruction *precedingInstruction,
TR::CodeGenerator *cg)
: TR::Instruction(op, n, precedingInstruction, cg)
{
setBinaryLength(2);
setEstimatedBinaryLength(2);
}
/**
* Following constructor is for PFPO instructino, where FPR0/FPR2 and GPR1 are target registers;
* FPR4/FPR6 and GPR0 are source registers;
* they are implied by the opcode, purpose of adding these is to notify RA the reg use/def dependencies
*/
S390EInstruction(TR::InstOpCode::Mnemonic op,
TR::Node *n,
TR::CodeGenerator *cg,
TR::Register * tgt,
TR::Register * tgt2,
TR::Register * src,
TR::Register * src2,
TR::RegisterDependencyConditions * cond)
: TR::Instruction(op, n, cond, cg)
{
useTargetRegister(tgt);
useTargetRegister(tgt2);
useSourceRegister(src);
useSourceRegister(src2);
setBinaryLength(2);
setEstimatedBinaryLength(2);
}
S390EInstruction(TR::InstOpCode::Mnemonic op,
TR::Node * n,
TR::Instruction *precedingInstruction,
TR::CodeGenerator *cg,
TR::Register * tgt,
TR::Register * tgt2,
TR::Register * src,
TR::Register * src2,
TR::RegisterDependencyConditions *cond)
: TR::Instruction(op, n, cond, precedingInstruction, cg)
{
useTargetRegister(tgt);
useTargetRegister(tgt2);
useSourceRegister(src);
useSourceRegister(src2);
setBinaryLength(2);
setEstimatedBinaryLength(2);
}
virtual char *description() { return "S390EInstruction"; }
virtual Kind getKind() { return IsE; }
virtual uint8_t *generateBinaryEncoding();
};
////////////////////////////////////////////////////////////////////////////////
// S390OpCodeOnlyInstruction Class Definition
////////////////////////////////////////////////////////////////////////////////
class S390OpCodeOnlyInstruction : public TR::Instruction
{
public:
S390OpCodeOnlyInstruction(TR::InstOpCode::Mnemonic op,
TR::Node *n,
TR::CodeGenerator *cg)
: TR::Instruction(op, n, cg)
{
}
S390OpCodeOnlyInstruction(TR::InstOpCode::Mnemonic op,
TR::Node * n,
TR::Instruction *precedingInstruction,
TR::CodeGenerator *cg)
: TR::Instruction(op, n, precedingInstruction, cg)
{
}
virtual char *description() { return "S390OpCodeOnlyInstruction"; }
virtual Kind getKind() { return IsOpCodeOnly; }
};
}
////////////////////////////////////////////////////////////////////////////////
/*************************************************************************
* Pseudo-safe downcast functions
*
*************************************************************************/
inline TR::S390MemInstruction * toS390MemInstruction(TR::Instruction *i)
{
return (TR::S390MemInstruction *)i;
}
inline TR::S390RIEInstruction * toS390RIEInstruction(TR::Instruction *i)
{
return (TR::S390RIEInstruction *)i;
}
inline TR::S390RRInstruction * toS390RRInstruction(TR::Instruction *i)
{
return (TR::S390RRInstruction *)i;
}
inline TR::S390RXInstruction * toS390RXInstruction(TR::Instruction *i)
{
return (TR::S390RXInstruction *)i;
}
inline TR::S390RXFInstruction * toS390RXFInstruction(TR::Instruction *i)
{
return (TR::S390RXFInstruction *)i;
}
inline TR::S390LabelInstruction * toS390LabelInstruction(TR::Instruction *i)
{
return (TR::S390LabelInstruction *)i;
}
inline TR::S390RIInstruction * toS390RIInstruction(TR::Instruction *i)
{
return (TR::S390RIInstruction *)i;
}
inline TR::S390RILInstruction * toS390RILInstruction(TR::Instruction *i)
{
return (TR::S390RILInstruction *)i;
}
inline TR::S390SS1Instruction * toS390SS1Instruction(TR::Instruction *i)
{
return (TR::S390SS1Instruction *)i;
}
inline TR::S390SSEInstruction * toS390SSEInstruction(TR::Instruction *i)
{
return (TR::S390SSEInstruction *)i;
}
inline TR::S390SS2Instruction * toS390SS2Instruction(TR::Instruction *i)
{
return (TR::S390SS2Instruction *)i;
}
inline TR::S390SS4Instruction * toS390SS4Instruction(TR::Instruction *i)
{
return (TR::S390SS4Instruction *)i;
}
inline TR::S390SSFInstruction * toS390SSFInstruction(TR::Instruction *i)
{
return (TR::S390SSFInstruction *)i;
}
inline TR::S390RSInstruction * toS390RSInstruction(TR::Instruction *i)
{
return (TR::S390RSInstruction *)i;
}
inline TR::S390VRSInstruction * toS390VRSInstruction(TR::Instruction *i)
{
return (TR::S390VRSInstruction *)i;
}
inline TR::S390VRRaInstruction * toS390VRRaInstruction(TR::Instruction *i)
{
return (TR::S390VRRaInstruction *)i;
}
inline TR::S390VRIaInstruction * toS390VRIaInstruction(TR::Instruction *i)
{
return (TR::S390VRIaInstruction *)i;
}
inline TR::S390RSLInstruction * toS390RSLInstruction(TR::Instruction *i)
{
return (TR::S390RSLInstruction *)i;
}
inline TR::S390RSLbInstruction * toS390RSLbInstruction(TR::Instruction *i)
{
return (TR::S390RSLbInstruction *)i;
}
inline TR::S390RRFInstruction * toS390RRFInstruction(TR::Instruction *i)
{
return (TR::S390RRFInstruction *)i;
}
inline TR::S390ImmInstruction * toS390ImmInstruction(TR::Instruction *i)
{
#if defined(DEBUG) || defined(PROD_WITH_ASSUMES)
TR_ASSERT(i->getS390ImmInstruction() != NULL, "trying to downcast to an S390ImmInstruction");
#endif
return (TR::S390ImmInstruction *)i;
}
inline TR::S390SMIInstruction * toS390SMIInstruction(TR::Instruction *i)
{
return (TR::S390SMIInstruction *)i;
}
inline TR::S390VRSaInstruction * toS390VRSaInstruction(TR::Instruction *i)
{
return (TR::S390VRSaInstruction *)i;
}
inline TR::S390VRSbInstruction * toS390VRSbInstruction(TR::Instruction *i)
{
return (TR::S390VRSbInstruction *)i;
}
inline TR::S390VRScInstruction * toS390VRScInstruction(TR::Instruction *i)
{
return (TR::S390VRScInstruction *)i;
}
inline TR::S390VRVInstruction * toS390VRVInstruction(TR::Instruction *i)
{
return (TR::S390VRVInstruction *)i;
}
inline TR::S390VRXInstruction * toS390VRXInstruction(TR::Instruction *i)
{
return (TR::S390VRXInstruction *)i;
}
TR::MemoryReference *getFirstReadWriteMemoryReference(TR::Instruction *i);
#endif
| 41.917214 | 220 | 0.530377 | [
"object",
"vector"
] |
ed58a47194afd6c8594ebda412b1ef461d1440e9 | 6,770 | hpp | C++ | libraries/chain/include/graphene/chain/exchange_object.hpp | finteh/crowdwiz-core | d0d2b5e2294c74da5b7304fd76ddab9cc87c18e5 | [
"MIT"
] | 8 | 2020-11-29T20:19:52.000Z | 2021-11-02T21:01:41.000Z | libraries/chain/include/graphene/chain/exchange_object.hpp | finteh/crowdwiz-core | d0d2b5e2294c74da5b7304fd76ddab9cc87c18e5 | [
"MIT"
] | 5 | 2021-03-06T10:58:34.000Z | 2021-08-07T09:51:09.000Z | libraries/chain/include/graphene/chain/exchange_object.hpp | finteh/crowdwiz-core | d0d2b5e2294c74da5b7304fd76ddab9cc87c18e5 | [
"MIT"
] | 5 | 2020-10-22T17:01:27.000Z | 2022-02-02T12:53:47.000Z | /*
* Copyright (c) 2019 CrowdWiz., and contributors.
*
* The MIT License
*/
#pragma once
#include <graphene/chain/protocol/asset.hpp>
#include <graphene/chain/protocol/types.hpp>
#include <graphene/chain/protocol/operations.hpp>
#include <graphene/db/object.hpp>
#include <graphene/db/generic_index.hpp>
#include <boost/multi_index/composite_key.hpp>
namespace graphene { namespace chain {
using namespace graphene::db;
class p2p_adv_object : public abstract_object<p2p_adv_object>
{
public:
static const uint8_t space_id = protocol_ids;
static const uint8_t type_id = p2p_adv_object_type;
account_id_type p2p_gateway;
bool adv_type = true;
string adv_description;
share_type max_cwd;
share_type min_cwd;
share_type price;
set<account_id_type> black_list;
uint8_t status = 1;
uint32_t min_p2p_complete_deals = 0;
uint8_t min_account_status = 0;
uint32_t timelimit_for_approve = 3600;
uint32_t timelimit_for_reply = 3600;
string geo;
string currency;
};
struct by_id;
struct by_status;
struct by_gateway_status;
using p2p_adv_multi_index_type = multi_index_container<
p2p_adv_object,
indexed_by<
ordered_unique< tag<by_id>,
member<object, object_id_type, &object::id>
>,
ordered_non_unique< tag<by_status>,
composite_key<
p2p_adv_object,
member<p2p_adv_object, uint8_t, &p2p_adv_object::status>,
member< object, object_id_type, &object::id>
>
>,
ordered_non_unique< tag<by_gateway_status>,
composite_key< p2p_adv_object,
member<p2p_adv_object, account_id_type, &p2p_adv_object::p2p_gateway>,
member<p2p_adv_object, uint8_t, &p2p_adv_object::status>,
member< object, object_id_type, &object::id >
>
>
>
>;
using p2p_adv_index = generic_index<p2p_adv_object, p2p_adv_multi_index_type>;
class p2p_order_object : public abstract_object<p2p_order_object>
{
public:
static const uint8_t space_id = protocol_ids;
static const uint8_t type_id = p2p_order_object_type;
p2p_adv_id_type p2p_adv;
bool order_type;
asset amount;
share_type price;
string currency;
account_id_type p2p_gateway;
account_id_type p2p_client;
uint8_t status = 1;
time_point_sec time_for_approve;
time_point_sec time_for_reply;
optional<memo_data> payment_details;
optional<memo_data> file_hash;
optional<account_id_type> arbitrage_initiator;
};
struct by_id;
struct by_status;
struct by_client_status;
struct by_client;
struct by_gateway_status;
struct by_client_gateway;
struct by_client_gateway_status;
struct by_time_for_approve;
struct by_time_for_reply;
struct by_status_time_for_approve;
struct by_status_time_for_reply;
using p2p_order_multi_index_type = multi_index_container<
p2p_order_object,
indexed_by<
ordered_unique< tag<by_id>,
member<object, object_id_type, &object::id>
>,
ordered_non_unique< tag<by_status>,
composite_key<
p2p_order_object,
member<p2p_order_object, uint8_t, &p2p_order_object::status>,
member< object, object_id_type, &object::id>
>
>,
ordered_non_unique< tag<by_client>,
composite_key< p2p_order_object,
member<p2p_order_object, account_id_type, &p2p_order_object::p2p_client>,
member< object, object_id_type, &object::id >
>
>,
ordered_non_unique< tag<by_client_status>,
composite_key< p2p_order_object,
member<p2p_order_object, account_id_type, &p2p_order_object::p2p_client>,
member<p2p_order_object, uint8_t, &p2p_order_object::status>,
member< object, object_id_type, &object::id >
>
>,
ordered_non_unique< tag<by_gateway_status>,
composite_key< p2p_order_object,
member<p2p_order_object, account_id_type, &p2p_order_object::p2p_gateway>,
member<p2p_order_object, uint8_t, &p2p_order_object::status>,
member< object, object_id_type, &object::id >
>
>,
ordered_non_unique< tag<by_client_gateway>,
composite_key< p2p_order_object,
member<p2p_order_object, account_id_type, &p2p_order_object::p2p_client>,
member<p2p_order_object, account_id_type, &p2p_order_object::p2p_gateway>,
member< object, object_id_type, &object::id >
>
>,
ordered_non_unique< tag<by_client_gateway_status>,
composite_key< p2p_order_object,
member<p2p_order_object, account_id_type, &p2p_order_object::p2p_client>,
member<p2p_order_object, account_id_type, &p2p_order_object::p2p_gateway>,
member<p2p_order_object, uint8_t, &p2p_order_object::status>,
member< object, object_id_type, &object::id >
>
>,
ordered_non_unique< tag<by_time_for_approve>,
composite_key< p2p_order_object,
member<p2p_order_object, time_point_sec, &p2p_order_object::time_for_approve>,
member< object, object_id_type, &object::id >
>
>,
ordered_non_unique< tag<by_time_for_reply>,
composite_key< p2p_order_object,
member<p2p_order_object, time_point_sec, &p2p_order_object::time_for_reply>,
member< object, object_id_type, &object::id >
>
>,
ordered_non_unique< tag<by_status_time_for_approve>,
composite_key< p2p_order_object,
member<p2p_order_object, uint8_t, &p2p_order_object::status>,
member<p2p_order_object, time_point_sec, &p2p_order_object::time_for_approve>,
member< object, object_id_type, &object::id >
>
>,
ordered_non_unique< tag<by_status_time_for_reply>,
composite_key< p2p_order_object,
member<p2p_order_object, uint8_t, &p2p_order_object::status>,
member<p2p_order_object, time_point_sec, &p2p_order_object::time_for_reply>,
member< object, object_id_type, &object::id >
>
>
>
>;
using p2p_order_index = generic_index<p2p_order_object, p2p_order_multi_index_type>;
} } // graphene::chain
FC_REFLECT_DERIVED( graphene::chain::p2p_adv_object, (graphene::db::object),
(p2p_gateway)
(adv_type)
(adv_description)
(max_cwd)
(min_cwd)
(price)
(black_list)
(status)
(min_p2p_complete_deals)
(min_account_status)
(timelimit_for_approve)
(timelimit_for_reply)
(geo)
(currency)
)
FC_REFLECT_DERIVED( graphene::chain::p2p_order_object, (graphene::db::object),
(p2p_adv)
(order_type)
(amount)
(price)
(currency)
(p2p_gateway)
(p2p_client)
(status)
(time_for_approve)
(time_for_reply)
(payment_details)
(file_hash)
(arbitrage_initiator)
)
| 31.635514 | 85 | 0.698966 | [
"object"
] |
ed5c3ca25e53ca9e9f9a31771b1e9d4bd8c8bbe0 | 1,195 | cpp | C++ | PAT/advanced/A1103.cpp | sptuan/PAT-Practice | 68e1ca329190264fdeeef1a2a1d4c2a56caa27f6 | [
"MIT"
] | null | null | null | PAT/advanced/A1103.cpp | sptuan/PAT-Practice | 68e1ca329190264fdeeef1a2a1d4c2a56caa27f6 | [
"MIT"
] | null | null | null | PAT/advanced/A1103.cpp | sptuan/PAT-Practice | 68e1ca329190264fdeeef1a2a1d4c2a56caa27f6 | [
"MIT"
] | null | null | null | #include <iostream>
#include <algorithm>
#include <cstdio>
#include <vector>
#include <cmath>
using namespace std;
vector<long long> ans;
vector<long long> temp;
long long N,K,P;
long long max_sum = -1;
long long display(vector<long long> temp){
vector<long long>::iterator i;
for(i=temp.begin();i!=temp.end();i++){
cout<<*i<<" ";
}
cout<<endl;
return 0;
}
bool cmp_int(long long a, long long b){
return a>b;
}
void DFS(long long a, long long sum, long long sum_k, long long depth){
if((depth>=K) || (sum>=N) || (a > N)){
if(sum == N && depth == K){
//sort(temp.begin(),temp.end(),cmp_int);
//ans.push_back(temp);
//display(temp);
if(sum_k > max_sum){
max_sum = sum_k;
ans = temp;
}
}
return;
}
temp.push_back(a);
//cout<<"Select "<<a<<endl;
DFS(a, sum + pow(a,P), sum_k + a, depth+1);
temp.pop_back();
if(a-1>0){
DFS(a-1, sum, sum_k, depth);
}
return;
}
int main(){
cin>>N>>K>>P;
DFS(N,0,0,0);
if(max_sum == -1){
cout<<"Impossible"<<endl;
}
else{
long long j;
cout<<N<<" = ";
for(j=0;j<K;j++){
cout<<ans[j]<<"^"<<P;
if(j!=K-1){
cout<<" + ";
}
}
cout<<endl;
}
return 0;
}
| 14.058824 | 71 | 0.548954 | [
"vector"
] |
ed5c609c098329050acd75fbd183b6b2b7cad98e | 4,928 | cpp | C++ | Lumos/Source/Lumos/Core/OS/Input.cpp | jmorton06/UntitledEngine | eabeb8b5b43c6b5039c0c3b9ab2bd7e3af03e7f4 | [
"MIT"
] | null | null | null | Lumos/Source/Lumos/Core/OS/Input.cpp | jmorton06/UntitledEngine | eabeb8b5b43c6b5039c0c3b9ab2bd7e3af03e7f4 | [
"MIT"
] | null | null | null | Lumos/Source/Lumos/Core/OS/Input.cpp | jmorton06/UntitledEngine | eabeb8b5b43c6b5039c0c3b9ab2bd7e3af03e7f4 | [
"MIT"
] | null | null | null | #include "Precompiled.h"
#include "Input.h"
namespace Lumos
{
Input::Input()
: m_MouseMode(MouseMode::Visible)
{
Reset();
}
void Input::Reset()
{
memset(m_KeyHeld, 0, MAX_KEYS);
memset(m_KeyPressed, 0, MAX_KEYS);
memset(m_MouseClicked, 0, MAX_BUTTONS);
memset(m_MouseHeld, 0, MAX_BUTTONS);
m_MouseOnScreen = true;
m_ScrollOffset = 0.0f;
}
void Input::ResetPressed()
{
memset(m_KeyPressed, 0, MAX_KEYS);
memset(m_MouseClicked, 0, MAX_BUTTONS);
m_ScrollOffset = 0;
}
void Input::OnEvent(Event& e)
{
EventDispatcher dispatcher(e);
dispatcher.Dispatch<KeyPressedEvent>(BIND_EVENT_FN(Input::OnKeyPressed));
dispatcher.Dispatch<KeyReleasedEvent>(BIND_EVENT_FN(Input::OnKeyReleased));
dispatcher.Dispatch<MouseButtonPressedEvent>(BIND_EVENT_FN(Input::OnMousePressed));
dispatcher.Dispatch<MouseButtonReleasedEvent>(BIND_EVENT_FN(Input::OnMouseReleased));
dispatcher.Dispatch<MouseScrolledEvent>(BIND_EVENT_FN(Input::OnMouseScrolled));
dispatcher.Dispatch<MouseMovedEvent>(BIND_EVENT_FN(Input::OnMouseMoved));
dispatcher.Dispatch<MouseEnterEvent>(BIND_EVENT_FN(Input::OnMouseEnter));
}
bool Input::OnKeyPressed(KeyPressedEvent& e)
{
SetKeyPressed(Lumos::InputCode::Key(e.GetKeyCode()), e.GetRepeatCount() < 1);
SetKeyHeld(Lumos::InputCode::Key(e.GetKeyCode()), true);
return false;
}
bool Input::OnKeyReleased(KeyReleasedEvent& e)
{
SetKeyPressed(Lumos::InputCode::Key(e.GetKeyCode()), false);
SetKeyHeld(Lumos::InputCode::Key(e.GetKeyCode()), false);
return false;
}
bool Input::OnMousePressed(MouseButtonPressedEvent& e)
{
SetMouseClicked(Lumos::InputCode::MouseKey(e.GetMouseButton()), true);
SetMouseHeld(Lumos::InputCode::MouseKey(e.GetMouseButton()), true);
return false;
}
bool Input::OnMouseReleased(MouseButtonReleasedEvent& e)
{
SetMouseClicked(Lumos::InputCode::MouseKey(e.GetMouseButton()), false);
SetMouseHeld(Lumos::InputCode::MouseKey(e.GetMouseButton()), false);
return false;
}
bool Input::OnMouseScrolled(MouseScrolledEvent& e)
{
SetScrollOffset(e.GetYOffset());
return false;
}
bool Input::OnMouseMoved(MouseMovedEvent& e)
{
StoreMousePosition(e.GetX(), e.GetY());
return false;
}
bool Input::OnMouseEnter(MouseEnterEvent& e)
{
SetMouseOnScreen(e.GetEntered());
return false;
}
bool Input::IsControllerPresent(int id)
{
return s_Controllers.find(id) != s_Controllers.end();
}
std::vector<int> Input::GetConnectedControllerIDs()
{
std::vector<int> ids;
ids.reserve(s_Controllers.size());
for(auto [id, controller] : s_Controllers)
ids.emplace_back(id);
return ids;
}
Controller* Input::GetController(int id)
{
if(!Input::IsControllerPresent(id))
return nullptr;
return &s_Controllers.at(id);
}
Controller* Input::GetOrAddController(int id)
{
return &(s_Controllers[id]);
}
std::string Input::GetControllerName(int id)
{
if(!Input::IsControllerPresent(id))
return {};
return s_Controllers.at(id).Name;
}
bool Input::IsControllerButtonPressed(int controllerID, int button)
{
if(!Input::IsControllerPresent(controllerID))
return false;
const Controller& controller = s_Controllers.at(controllerID);
if(controller.ButtonStates.find(button) == controller.ButtonStates.end())
return false;
return controller.ButtonStates.at(button);
}
float Input::GetControllerAxis(int controllerID, int axis)
{
if(!Input::IsControllerPresent(controllerID))
return 0.0f;
const Controller& controller = s_Controllers.at(controllerID);
if(controller.AxisStates.find(axis) == controller.AxisStates.end())
return 0.0f;
return controller.AxisStates.at(axis);
}
uint8_t Input::GetControllerHat(int controllerID, int hat)
{
if(!Input::IsControllerPresent(controllerID))
return 0;
const Controller& controller = s_Controllers.at(controllerID);
if(controller.HatStates.find(hat) == controller.HatStates.end())
return 0;
return controller.HatStates.at(hat);
}
void Input::RemoveController(int id)
{
for(auto it = s_Controllers.begin(); it != s_Controllers.end();)
{
int currentID = it->first;
if(currentID == id)
{
s_Controllers.erase(it);
return;
}
else
it++;
}
}
}
| 28.16 | 93 | 0.622362 | [
"vector"
] |
ed60d4cb3129d42b9bb14c129ffadc6412fea4e9 | 2,370 | cpp | C++ | src/DPPDiversity.cpp | veryVegetable-dev/rDppDiversity | 16e0553025eaaef556c0809c50471eba8807c7a5 | [
"MIT"
] | null | null | null | src/DPPDiversity.cpp | veryVegetable-dev/rDppDiversity | 16e0553025eaaef556c0809c50471eba8807c7a5 | [
"MIT"
] | null | null | null | src/DPPDiversity.cpp | veryVegetable-dev/rDppDiversity | 16e0553025eaaef556c0809c50471eba8807c7a5 | [
"MIT"
] | null | null | null | #include "DPPDiversity.h"
#include <cmath>
#include <unordered_set>
void DPPDiversity::init(
const std::vector<std::vector<float> > &item_representations,
const std::vector<float> &item_ratings) {
N = item_representations.size();
if (N == 0 || item_ratings.size() != N)
return;
d = item_representations[0].size();
item_mat.resize(N, d);
rating_vec.resize(N);
corr_mat.resize(N, N);
for (int i = 0; i < N; i++) {
rating_vec(i) = item_ratings[i];
if (item_representations[i].size() != d) return;
for (int j = 0; j < d; j++)
item_mat(i, j) = item_representations[i][j];
}
Mat weighted_corr_mat = item_mat.transpose() * rating_vec.asDiagonal();
corr_mat = weighted_corr_mat.transpose() * weighted_corr_mat;
}
void DPPDiversity::select(int n, std::vector<std::pair<int, float> >* res) {
if (n > N || N <= 0) return;
std::unordered_set<int> selected;
// init
int init_elem = 0;
for (int i = init_elem + 1; i < N; i++) {
if (corr_mat(i, i) > corr_mat(init_elem, init_elem))
init_elem = i;
}
res->emplace_back(init_elem, log(corr_mat(init_elem, init_elem)));
selected.insert(init_elem);
n--;
// iter
std::unordered_map<int, std::vector<float> > cond_prob_mp;
int last_added_elem = init_elem;
while (n-- > 0) {
int i = 0, curr_added_elem = 0;
for (; i < N; i++) {
if (selected.find(i) != selected.end()) {
if (curr_added_elem == i)
curr_added_elem++;
continue;
}
float curr_cond_prob = (corr_mat(last_added_elem,i) - dot_product(cond_prob_mp[last_added_elem], cond_prob_mp[i])) / (sqrt(corr_mat(last_added_elem, last_added_elem)) + 1e-4);
cond_prob_mp[i].emplace_back(curr_cond_prob);
corr_mat(i, i) -= curr_cond_prob * curr_cond_prob;
if (corr_mat(i, i) > corr_mat(curr_added_elem, curr_added_elem)) {
curr_added_elem = i;
}
}
float log_det = log(corr_mat(curr_added_elem, curr_added_elem));
if (log_det < 0) break;
else {
res->emplace_back(curr_added_elem, log_det);
selected.insert(curr_added_elem);
last_added_elem = curr_added_elem;
}
}
}
| 36.461538 | 187 | 0.581857 | [
"vector"
] |
ed677b538c0b9cfdbab5b7b199ebf4179d0890f4 | 4,824 | cpp | C++ | src/FalconEngine/Graphics/Renderer/Scene/Visual.cpp | LiuYiZhou95/FalconEngine | b798f20e9dbd01334a4e4cdbbd9a5bec74966418 | [
"MIT"
] | null | null | null | src/FalconEngine/Graphics/Renderer/Scene/Visual.cpp | LiuYiZhou95/FalconEngine | b798f20e9dbd01334a4e4cdbbd9a5bec74966418 | [
"MIT"
] | null | null | null | src/FalconEngine/Graphics/Renderer/Scene/Visual.cpp | LiuYiZhou95/FalconEngine | b798f20e9dbd01334a4e4cdbbd9a5bec74966418 | [
"MIT"
] | 1 | 2021-08-25T07:39:02.000Z | 2021-08-25T07:39:02.000Z | #include <FalconEngine/Graphics/Renderer/Scene/Visual.h>
#include <FalconEngine/Graphics/Renderer/Primitive.h>
#include <FalconEngine/Graphics/Renderer/VisualEffectInstance.h>
#include <FalconEngine/Graphics/Renderer/Resource/VertexFormat.h>
#include <FalconEngine/Graphics/Renderer/Resource/VertexGroup.h>
namespace FalconEngine
{
FALCON_ENGINE_RTTI_IMPLEMENT(Visual, Spatial);
/************************************************************************/
/* Constructors and Destructor */
/************************************************************************/
Visual::Visual(const std::shared_ptr<Mesh>& mesh) :
mMesh(mesh)
{
// NOTE(Wuxiang): By default Visual "inherit" from Primitives' vertex
// information. You could override those vertex information by using the
// setter in Visual API.
auto primitive = mesh->GetPrimitive();
mVertexFormat = primitive->GetVertexFormat();
mVertexGroup = primitive->GetVertexGroup();
}
Visual::Visual()
{
}
Visual::~Visual()
{
}
/************************************************************************/
/* Public Members */
/************************************************************************/
/************************************************************************/
/* Effect Management */
/************************************************************************/
int
Visual::GetEffectInstanceNum() const
{
return int(mEffectInstances.size());
}
void
Visual::PushEffectInstance(std::shared_ptr<VisualEffectInstance> effectInstance)
{
// NOTE(Wuxiang): Don't allow
FALCON_ENGINE_CHECK_NULLPTR(effectInstance);
mEffectInstances.push_back(effectInstance);
}
void
Visual::RemoveEffectInstance(std::shared_ptr<VisualEffectInstance> effectInstance)
{
FALCON_ENGINE_CHECK_NULLPTR(effectInstance);
auto iter = find(mEffectInstances.begin(), mEffectInstances.end(), effectInstance);
if (iter != mEffectInstances.end())
{
mEffectInstances.erase(iter);
}
}
int
Visual::GetEffectParamsNum() const
{
return int(mEffectParamses.size());
}
void
Visual::PushEffectParams(std::shared_ptr<VisualEffectParams> effectParmas)
{
FALCON_ENGINE_CHECK_NULLPTR(effectParmas);
mEffectParamses.push_back(effectParmas);
}
void
Visual::RemoveEffectParams(std::shared_ptr<VisualEffectParams> effectParmas)
{
FALCON_ENGINE_CHECK_NULLPTR(effectParmas);
auto iter = find(mEffectParamses.begin(), mEffectParamses.end(), effectParmas);
if (iter != mEffectParamses.end())
{
mEffectParamses.erase(iter);
}
}
const VertexFormat *
Visual::GetVertexFormat() const
{
return mVertexFormat.get();
}
std::shared_ptr<const VertexFormat>
Visual::GetVertexFormat()
{
return mVertexFormat;
}
void
Visual::SetVertexFormat(std::shared_ptr<VertexFormat> vertexFormat)
{
mVertexFormat = vertexFormat;
}
const VertexGroup *
Visual::GetVertexGroup() const
{
return mVertexGroup.get();
}
std::shared_ptr<const VertexGroup>
Visual::GetVertexGroup()
{
return mVertexGroup;
}
void
Visual::SetVertexGroup(std::shared_ptr<VertexGroup> vertexGroup)
{
mVertexGroup = vertexGroup;
}
/************************************************************************/
/* Mesh Management */
/************************************************************************/
const Mesh *
Visual::GetMesh() const
{
return mMesh.get();
}
std::shared_ptr<Mesh>
Visual::GetMesh()
{
return mMesh;
}
void
Visual::SetMesh(std::shared_ptr<Mesh> mesh)
{
FALCON_ENGINE_CHECK_NULLPTR(mesh);
mMesh = mesh;
}
/************************************************************************/
/* Spatial Management */
/************************************************************************/
void
Visual::UpdateWorldTransform(double elapsed)
{
Spatial::UpdateWorldTransform(elapsed);
}
/************************************************************************/
/* Deep and Shallow Copy */
/************************************************************************/
void
Visual::CopyTo(Visual *lhs) const
{
Spatial::CopyTo(lhs);
lhs->mEffectInstances = mEffectInstances;
lhs->mEffectParamses = mEffectParamses;
lhs->mVertexFormat = mVertexFormat;
lhs->mVertexGroup = mVertexGroup;
lhs->mMesh = mMesh;
}
Visual *
Visual::GetClone() const
{
auto clone = new Visual();
CopyTo(clone);
return clone;
}
Visual *
Visual::GetClone(std::function<void(Visual *lhs, Visual *rhs)> copyTo)
{
auto clone = new Visual();
copyTo(clone, this);
return clone;
}
}
| 24.612245 | 87 | 0.547678 | [
"mesh"
] |
ed67b56099e1714d8004d4c258835b2ea0a3ccd9 | 5,408 | cpp | C++ | projects/Sample5/Sources/Sample5.cpp | Daniel-Mietchen/kigs | 92ab6deaf3e947465781a400c5a791ee171876c8 | [
"MIT"
] | null | null | null | projects/Sample5/Sources/Sample5.cpp | Daniel-Mietchen/kigs | 92ab6deaf3e947465781a400c5a791ee171876c8 | [
"MIT"
] | null | null | null | projects/Sample5/Sources/Sample5.cpp | Daniel-Mietchen/kigs | 92ab6deaf3e947465781a400c5a791ee171876c8 | [
"MIT"
] | null | null | null | #include <Sample5.h>
#include <FilePathManager.h>
#include <NotificationCenter.h>
#include "CoreItem.h"
#include "CoreVector.h"
#include "JSonFileParser.h"
#include <iostream>
// Kigs framework Sample5 project
// CoreItem features :
// - import / export JSON objects
// - create/evaluate mathematical expression
// - animate values (UIItem / XML files)
IMPLEMENT_CLASS_INFO(Sample5);
IMPLEMENT_CONSTRUCTOR(Sample5)
{
}
float Sample5::randomNumber(float min, float max)
{
float rnd = ((float)rand()) / (float)RAND_MAX;
rnd *= max - min;
return min + rnd;
}
void Sample5::ProtectedInit()
{
// Base modules have been created at this point
// lets say that the update will sleep 1ms
SetUpdateSleepTime(1);
SP<FilePathManager> pathManager = KigsCore::GetSingleton("FilePathManager");
pathManager->AddToPath(".", "xml");
// CoreItem can be used to manage JSon slyle objects
// main CoreItem types are CoreValue, CoreMap and CoreVector
// A CoreItem hierarchy can be created from json file (or json string)
JSonFileParser L_JsonParser;
CoreItemSP item = L_JsonParser.Get_JsonDictionaryFromString(R"====(
{
"obj1" : { "obj3": [0.4, 0.9, 0.0, "str"] },
"val1" : 15
}
)====");
// check if val2 exist
if (item["val2"].isNil())
{
std::cout << "val 2 not found " << std::endl;
}
else
{
std::cout << "val 2 : " << (int)item["val2"] << std::endl;
}
// create a CoreValue<int> with value 52
CoreItemSP toInsert = CoreItemSP::getCoreValue(52);
// add it to item with key val2
item->set("val2", toInsert);
// print values accessing map at val1 and val2
std::cout << "val 1 : " << (int)item["val1"] << std::endl;
std::cout << "val 2 : " << (int)item["val2"] << std::endl;
// retreive obj1
CoreItemSP obj1 = item["obj1"];
// obj3 is an array, add a CoreValue<std::string> at the end of the array (for an array, set with no key <=> push_back)
obj1["obj3"]->set("", CoreItemSP::getCoreValue("lastElem"));
// print all obj 3 values
bool first = true;
std::cout << "obj 3 : [";
for (auto tst : obj1["obj3"])
{
if (!first)
{
std::cout << " , ";
}
first = false;
std::cout << (std::string)tst;
}
std::cout << "]" << std::endl;
// push back another vector on obj3, created from a Point3D
Point3D toPush(5.0f, 4.0f, 3.0f);
obj1["obj3"]->set("", CoreItemSP(toPush));
// Export JSON item as attribute of an empty object
CMSP donothing = KigsCore::GetInstanceOf("useless", "DoNothing");
donothing->AddDynamicAttribute(ATTRIBUTE_TYPE::COREITEM, "item");
donothing->setValue("item", item.get());
#ifdef KIGS_TOOLS
Export("testCoreItemExport.xml", donothing.get());
#endif
// CoreItem can also be used to evaluate mathematical expressions
// with the eval keywork
// (basic string operation are also available with evalStr keyword)
// create a mathematic expression :
CoreItemSP tsteval("eval(12.0*sin(4.0))");
// evaluate the expression and print it
std::cout << "Expression : 12.0*sin(4.0) = " << (float)tsteval << std::endl;
// for maCoreItem, or using absolute path, you can use CoreModifiable attributes in more complex expressions
mFunction.setValue("eval(12.0*sin(#TestFloat#+#/Timer:ApplicationTimer->Time#))");
std::cout << "Expression : eval(12.0*sin(#TestFloat#+#/Timer:ApplicationTimer->Time#)) = " << (float)(CoreItem&)mFunction << std::endl;
// expression is evaluated again at each cast to float
std::cout << "Expression : eval(12.0*sin(#TestFloat#+#/Timer:ApplicationTimer->Time#)) = " << (float)(CoreItem&)mFunction << std::endl;
// it's also possible to call CoreModifiable methods, set CoreModifiable attributes and make some tests
tsteval = std::string("eval(if(([/Sample5->randomNumber(0.0,2.0)]>1.0),#/Sample5->EvalResult.x#=(#/Sample5->EvalResult.x#+1);1,#/Sample5->EvalResult.y#=(#/Sample5->EvalResult.y#+1);2))");
std::cout << "tsteval result = " << (float)tsteval << std::endl;
std::cout << "EvalResult = [ " << mEvalResult[0] << "," << mEvalResult[1] << " ]" << std::endl;
std::cout << "tsteval result = " << (float)tsteval << std::endl;
std::cout << "EvalResult = [ " << mEvalResult[0] << "," << mEvalResult[1] << " ]" << std::endl;
std::cout << "tsteval result = " << (float)tsteval << std::endl;
std::cout << "EvalResult = [ " << mEvalResult[0] << "," << mEvalResult[1] << " ]" << std::endl;
std::cout << "tsteval result = " << (float)tsteval << std::endl;
std::cout << "EvalResult = [ " << mEvalResult[0] << "," << mEvalResult[1] << " ]" << std::endl;
std::cout << "tsteval result = " << (float)tsteval << std::endl;
std::cout << "EvalResult = [ " << mEvalResult[0] << "," << mEvalResult[1] << " ]" << std::endl;
// It's also possible to compute 2D or 3D expressions
tsteval = std::string("eval2D(#/Sample5->EvalResult#+{1.0,#/Sample5->EvalResult.x#})");
Point2D checkresult = tsteval;
std::cout << "checkresult = [ " << checkresult[0] << "," << checkresult[1] << " ]" << std::endl;
// Load AppInit, GlobalConfig then launch first sequence
DataDrivenBaseApplication::ProtectedInit();
}
void Sample5::ProtectedUpdate()
{
DataDrivenBaseApplication::ProtectedUpdate();
}
void Sample5::ProtectedClose()
{
DataDrivenBaseApplication::ProtectedClose();
}
void Sample5::ProtectedInitSequence(const kstl::string& sequence)
{
if (sequence == "sequencemain")
{
}
}
void Sample5::ProtectedCloseSequence(const kstl::string& sequence)
{
if (sequence == "sequencemain")
{
}
}
| 32 | 188 | 0.660318 | [
"object",
"vector",
"3d"
] |
ed759be7e8a5203077f1704446b88111c6cefc0c | 6,923 | cpp | C++ | remodet_repository_wdh_part/src/caffe/tracker/example_generator.cpp | UrwLee/Remo_experience | a59d5b9d6d009524672e415c77d056bc9dd88c72 | [
"MIT"
] | null | null | null | remodet_repository_wdh_part/src/caffe/tracker/example_generator.cpp | UrwLee/Remo_experience | a59d5b9d6d009524672e415c77d056bc9dd88c72 | [
"MIT"
] | null | null | null | remodet_repository_wdh_part/src/caffe/tracker/example_generator.cpp | UrwLee/Remo_experience | a59d5b9d6d009524672e415c77d056bc9dd88c72 | [
"MIT"
] | null | null | null | #include "caffe/tracker/example_generator.hpp"
#include "caffe/tracker/basic.hpp"
#include "caffe/tracker/image_proc.hpp"
#include "caffe/tracker/bounding_box.hpp"
#include <string>
namespace caffe {
using std::string;
// Choose whether to shift boxes using the motion model or using a uniform distribution.
const bool shift_motion_model = true;
template <typename Dtype>
ExampleGenerator<Dtype>::ExampleGenerator(const Dtype lambda_shift,
const Dtype lambda_scale,
const Dtype min_scale,
const Dtype max_scale)
: lambda_shift_(lambda_shift), lambda_scale_(lambda_scale), min_scale_(min_scale), max_scale_(max_scale) {
}
template <typename Dtype>
void ExampleGenerator<Dtype>::Init(const Dtype lambda_shift, const Dtype lambda_scale,
const Dtype min_scale, const Dtype max_scale) {
lambda_shift_ = lambda_shift;
lambda_scale_ = lambda_scale;
min_scale_ = min_scale;
max_scale_ = max_scale;
}
template <typename Dtype>
void ExampleGenerator<Dtype>::Reset(const BoundingBox<Dtype>& bbox_prev,
const BoundingBox<Dtype>& bbox_curr,
const cv::Mat& image_prev,
const cv::Mat& image_curr) {
CropPadImage(bbox_prev, image_prev, &target_pad_);
image_curr_ = image_curr;
bbox_curr_gt_ = bbox_curr;
bbox_prev_gt_ = bbox_prev;
}
template <typename Dtype>
void ExampleGenerator<Dtype>::MakeTrainingExamples(const int num_examples,
std::vector<cv::Mat>* images,
std::vector<cv::Mat>* targets,
std::vector<BoundingBox<Dtype> >* bboxes_gt_scaled) {
// 创建N个样本对
for (int i = 0; i < num_examples; ++i) {
cv::Mat image_rand_focus;
cv::Mat target_pad;
BoundingBox<Dtype> bbox_gt_scaled;
// 生成训练样本
MakeTrainingExampleBBShift(&image_rand_focus, &target_pad, &bbox_gt_scaled);
images->push_back(image_rand_focus);
targets->push_back(target_pad);
bboxes_gt_scaled->push_back(bbox_gt_scaled);
}
}
template <typename Dtype>
void ExampleGenerator<Dtype>::MakeTrueExample(cv::Mat* curr_search_region,
cv::Mat* target_pad,
BoundingBox<Dtype>* bbox_gt_scaled) const {
*target_pad = target_pad_;
// TODO - use a motion model?
const BoundingBox<Dtype>& curr_prior_tight = bbox_prev_gt_;
BoundingBox<Dtype> curr_search_location;
Dtype edge_spacing_x, edge_spacing_y;
// 在当前帧的历史位置处进行裁剪
CropPadImage(curr_prior_tight, image_curr_, curr_search_region, &curr_search_location, &edge_spacing_x, &edge_spacing_y);
BoundingBox<Dtype> bbox_gt_recentered;
// 将gt在裁剪后的patch中进行定位
bbox_curr_gt_.Recenter(curr_search_location, edge_spacing_x, edge_spacing_y, &bbox_gt_recentered);
// 获取输出结果
bbox_gt_recentered.Scale(*curr_search_region, bbox_gt_scaled);
}
template <typename Dtype>
void ExampleGenerator<Dtype>::get_default_bb_params(BBParams<Dtype>* default_params) const {
default_params->lambda_scale = lambda_scale_;
default_params->lambda_shift = lambda_shift_;
default_params->min_scale = min_scale_;
default_params->max_scale = max_scale_;
}
template <typename Dtype>
void ExampleGenerator<Dtype>::MakeTrainingExampleBBShift(cv::Mat* image_rand_focus,
cv::Mat* target_pad,
BoundingBox<Dtype>* bbox_gt_scaled) const {
BBParams<Dtype> default_bb_params;
get_default_bb_params(&default_bb_params);
const bool visualize_example = false;
MakeTrainingExampleBBShift(visualize_example, default_bb_params,
image_rand_focus, target_pad, bbox_gt_scaled);
}
template <typename Dtype>
void ExampleGenerator<Dtype>::MakeTrainingExampleBBShift(
const bool visualize_example, cv::Mat* image_rand_focus,
cv::Mat* target_pad, BoundingBox<Dtype>* bbox_gt_scaled) const {
BBParams<Dtype> default_bb_params;
get_default_bb_params(&default_bb_params);
MakeTrainingExampleBBShift(visualize_example, default_bb_params,
image_rand_focus, target_pad, bbox_gt_scaled);
}
template <typename Dtype>
void ExampleGenerator<Dtype>::MakeTrainingExampleBBShift(const bool visualize_example,
const BBParams<Dtype>& bbparams,
cv::Mat* rand_search_region,
cv::Mat* target_pad,
BoundingBox<Dtype>* bbox_gt_scaled) const {
// 将prev裁剪后的pad图像定义为target_pad
*target_pad = target_pad_;
BoundingBox<Dtype> bbox_curr_shift;
// 将当前帧的box进行随机增强,获得新的box
bbox_curr_gt_.Shift(image_curr_, bbparams.lambda_scale, bbparams.lambda_shift,
bbparams.min_scale, bbparams.max_scale,
shift_motion_model,
&bbox_curr_shift);
// Crop the image based at the new location (after applying translation and scale changes).
Dtype edge_spacing_x, edge_spacing_y;
BoundingBox<Dtype> rand_search_location;
// 在当前帧中,以新的随机box:bbox_curr_shift进行ROI裁剪,输出图像: rand_search_region
// 有效的图片区域: rand_search_location, 左上角定位:edge_spacing_x/edge_spacing_y
CropPadImage(bbox_curr_shift, image_curr_, rand_search_region, &rand_search_location,
&edge_spacing_x, &edge_spacing_y);
// 重新定位gt在裁剪后的patch中的坐标
BoundingBox<Dtype> bbox_gt_recentered;
bbox_curr_gt_.Recenter(rand_search_location, edge_spacing_x, edge_spacing_y, &bbox_gt_recentered);
// 计算归一化坐标: 首先使用裁剪patch的w/h进行归一化,再使用scale进行统一放大: 为了与Net的输出值范围匹配
bbox_gt_recentered.Scale(*rand_search_region, bbox_gt_scaled);
// 可视化增广结果
if (visualize_example) {
VisualizeExample(*target_pad, *rand_search_region, *bbox_gt_scaled);
}
}
template <typename Dtype>
void ExampleGenerator<Dtype>::VisualizeExample(const cv::Mat& target_pad,
const cv::Mat& image_rand_focus,
const BoundingBox<Dtype>& bbox_gt_scaled) const {
cv::Mat target_resize;
cv::resize(target_pad, target_resize, cv::Size(227,227));
cv::namedWindow("Target object", cv::WINDOW_AUTOSIZE );
cv::imshow("Target object", target_resize);
cv::Mat image_resize;
cv::resize(image_rand_focus, image_resize, cv::Size(227, 227));
// Draw gt bbox.
BoundingBox<Dtype> bbox_gt_unscaled;
bbox_gt_scaled.Unscale(image_resize, &bbox_gt_unscaled);
bbox_gt_unscaled.Draw(0, 255, 0, &image_resize);
// Show image with bbox.
cv::namedWindow("Search_region_gt", cv::WINDOW_AUTOSIZE );
cv::imshow("Search_region_gt", image_resize);
cv::waitKey(0);
}
INSTANTIATE_CLASS(ExampleGenerator);
}
| 40.723529 | 123 | 0.67803 | [
"object",
"vector",
"model"
] |
ed785333aa812a98da4f538875338b97e70ea677 | 762 | cpp | C++ | Online Judges/CodeForces/1015BObtainingTheString.cpp | NelsonGomesNeto/ProgramC | e743b1b869f58f7f3022d18bac00c5e0b078562e | [
"MIT"
] | 3 | 2018-12-18T13:39:42.000Z | 2021-06-23T18:05:18.000Z | Online Judges/CodeForces/1015BObtainingTheString.cpp | NelsonGomesNeto/ProgramC | e743b1b869f58f7f3022d18bac00c5e0b078562e | [
"MIT"
] | 1 | 2018-11-02T21:32:40.000Z | 2018-11-02T22:47:12.000Z | Online Judges/CodeForces/1015BObtainingTheString.cpp | NelsonGomesNeto/ProgramC | e743b1b869f58f7f3022d18bac00c5e0b078562e | [
"MIT"
] | 6 | 2018-10-27T14:07:52.000Z | 2019-11-14T13:49:29.000Z | #include <bits/stdc++.h>
using namespace std;
void swap(char *a, char *b)
{
char aux = *a;
*a = *b;
*b = aux;
}
int main()
{
int n; scanf("%d", &n);
char s[n + 1], t[n + 1]; scanf("\n%s\n%s", s, t);
vector<int> movements;
for (int i = 0; i < n; i ++)
{
if (s[i] != t[i])
{
for (int j = i + 1; j < n; j ++)
if (s[j] == t[i])
{
while (j > i)
{
swap(&s[j], &s[j - 1]);
movements.push_back(j);
j --;
}
break;
}
}
if (s[i] != t[i])
{
printf("-1\n");
return(0);
}
}
printf("%d\n", (int) movements.size());
for (int i = 0; i < movements.size(); i ++)
printf("%d ", movements[i]);
return(0);
}
| 16.212766 | 51 | 0.380577 | [
"vector"
] |
ed79d3d7a371dd2e2262838113bdd566528c2b48 | 6,123 | cpp | C++ | third_party/WebKit/Source/modules/payments/PaymentResponseTest.cpp | google-ar/chromium | 2441c86a5fd975f09a6c30cddb57dfb7fc239699 | [
"Apache-2.0",
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | 777 | 2017-08-29T15:15:32.000Z | 2022-03-21T05:29:41.000Z | third_party/WebKit/Source/modules/payments/PaymentResponseTest.cpp | harrymarkovskiy/WebARonARCore | 2441c86a5fd975f09a6c30cddb57dfb7fc239699 | [
"Apache-2.0",
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | 66 | 2017-08-30T18:31:18.000Z | 2021-08-02T10:59:35.000Z | third_party/WebKit/Source/modules/payments/PaymentResponseTest.cpp | harrymarkovskiy/WebARonARCore | 2441c86a5fd975f09a6c30cddb57dfb7fc239699 | [
"Apache-2.0",
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | 123 | 2017-08-30T01:19:34.000Z | 2022-03-17T22:55:31.000Z | // Copyright 2016 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 "modules/payments/PaymentResponse.h"
#include "bindings/core/v8/ExceptionState.h"
#include "bindings/core/v8/ScriptState.h"
#include "bindings/core/v8/ScriptValue.h"
#include "bindings/core/v8/V8Binding.h"
#include "bindings/core/v8/V8BindingForTesting.h"
#include "modules/payments/PaymentAddress.h"
#include "modules/payments/PaymentCompleter.h"
#include "modules/payments/PaymentTestHelper.h"
#include "testing/gmock/include/gmock/gmock.h"
#include "testing/gtest/include/gtest/gtest.h"
#include <memory>
#include <utility>
namespace blink {
namespace {
class MockPaymentCompleter
: public GarbageCollectedFinalized<MockPaymentCompleter>,
public PaymentCompleter {
USING_GARBAGE_COLLECTED_MIXIN(MockPaymentCompleter);
WTF_MAKE_NONCOPYABLE(MockPaymentCompleter);
public:
MockPaymentCompleter() {
ON_CALL(*this, complete(testing::_, testing::_))
.WillByDefault(testing::ReturnPointee(&m_dummyPromise));
}
~MockPaymentCompleter() override {}
MOCK_METHOD2(complete, ScriptPromise(ScriptState*, PaymentComplete result));
DEFINE_INLINE_TRACE() {}
private:
ScriptPromise m_dummyPromise;
};
TEST(PaymentResponseTest, DataCopiedOver) {
V8TestingScope scope;
payments::mojom::blink::PaymentResponsePtr input =
buildPaymentResponseForTest();
input->method_name = "foo";
input->stringified_details = "{\"transactionId\": 123}";
input->shipping_option = "standardShippingOption";
input->payer_name = "Jon Doe";
input->payer_email = "abc@gmail.com";
input->payer_phone = "0123";
MockPaymentCompleter* completeCallback = new MockPaymentCompleter;
PaymentResponse output(std::move(input), completeCallback);
EXPECT_EQ("foo", output.methodName());
EXPECT_EQ("standardShippingOption", output.shippingOption());
EXPECT_EQ("Jon Doe", output.payerName());
EXPECT_EQ("abc@gmail.com", output.payerEmail());
EXPECT_EQ("0123", output.payerPhone());
ScriptValue details =
output.details(scope.getScriptState(), scope.getExceptionState());
ASSERT_FALSE(scope.getExceptionState().hadException());
ASSERT_TRUE(details.v8Value()->IsObject());
ScriptValue transactionId(
scope.getScriptState(),
details.v8Value().As<v8::Object>()->Get(
v8String(scope.getScriptState()->isolate(), "transactionId")));
ASSERT_TRUE(transactionId.v8Value()->IsNumber());
EXPECT_EQ(123, transactionId.v8Value().As<v8::Number>()->Value());
}
TEST(PaymentResponseTest, PaymentResponseDetailsJSONObject) {
V8TestingScope scope;
payments::mojom::blink::PaymentResponsePtr input =
buildPaymentResponseForTest();
input->stringified_details = "transactionId";
MockPaymentCompleter* completeCallback = new MockPaymentCompleter;
PaymentResponse output(std::move(input), completeCallback);
ScriptValue details =
output.details(scope.getScriptState(), scope.getExceptionState());
ASSERT_TRUE(scope.getExceptionState().hadException());
}
TEST(PaymentResponseTest, CompleteCalledWithSuccess) {
V8TestingScope scope;
payments::mojom::blink::PaymentResponsePtr input =
buildPaymentResponseForTest();
input->method_name = "foo";
input->stringified_details = "{\"transactionId\": 123}";
MockPaymentCompleter* completeCallback = new MockPaymentCompleter;
PaymentResponse output(std::move(input), completeCallback);
EXPECT_CALL(*completeCallback,
complete(scope.getScriptState(), PaymentCompleter::Success));
output.complete(scope.getScriptState(), "success");
}
TEST(PaymentResponseTest, CompleteCalledWithFailure) {
V8TestingScope scope;
payments::mojom::blink::PaymentResponsePtr input =
buildPaymentResponseForTest();
input->method_name = "foo";
input->stringified_details = "{\"transactionId\": 123}";
MockPaymentCompleter* completeCallback = new MockPaymentCompleter;
PaymentResponse output(std::move(input), completeCallback);
EXPECT_CALL(*completeCallback,
complete(scope.getScriptState(), PaymentCompleter::Fail));
output.complete(scope.getScriptState(), "fail");
}
TEST(PaymentResponseTest, JSONSerializerTest) {
V8TestingScope scope;
payments::mojom::blink::PaymentResponsePtr input =
payments::mojom::blink::PaymentResponse::New();
input->method_name = "foo";
input->stringified_details = "{\"transactionId\": 123}";
input->shipping_option = "standardShippingOption";
input->payer_email = "abc@gmail.com";
input->payer_phone = "0123";
input->payer_name = "Jon Doe";
input->shipping_address = payments::mojom::blink::PaymentAddress::New();
input->shipping_address->country = "US";
input->shipping_address->language_code = "en";
input->shipping_address->script_code = "Latn";
input->shipping_address->address_line.push_back("340 Main St");
input->shipping_address->address_line.push_back("BIN1");
input->shipping_address->address_line.push_back("First floor");
PaymentResponse output(std::move(input), new MockPaymentCompleter);
ScriptValue jsonObject = output.toJSONForBinding(scope.getScriptState());
EXPECT_TRUE(jsonObject.isObject());
String jsonString = v8StringToWebCoreString<String>(
v8::JSON::Stringify(scope.context(),
jsonObject.v8Value().As<v8::Object>())
.ToLocalChecked(),
DoNotExternalize);
String expected =
"{\"methodName\":\"foo\",\"details\":{\"transactionId\":123},"
"\"shippingAddress\":{\"country\":\"US\",\"addressLine\":[\"340 Main "
"St\","
"\"BIN1\",\"First "
"floor\"],\"region\":\"\",\"city\":\"\",\"dependentLocality\":"
"\"\",\"postalCode\":\"\",\"sortingCode\":\"\",\"languageCode\":\"en-"
"Latn\","
"\"organization\":\"\",\"recipient\":\"\",\"phone\":\"\"},"
"\"shippingOption\":"
"\"standardShippingOption\",\"payerName\":\"Jon Doe\","
"\"payerEmail\":\"abc@gmail.com\",\"payerPhone\":\"0123\"}";
EXPECT_EQ(expected, jsonString);
}
} // namespace
} // namespace blink
| 36.446429 | 78 | 0.719909 | [
"object"
] |
ed7dad27efcf47be12c75df9c6e27143ea582bdf | 2,872 | cc | C++ | tree/IsFull.cc | raining888/leetcode | e9e8ac51d49e0c5f1450a6b76ba9777b89f7e25b | [
"MIT"
] | null | null | null | tree/IsFull.cc | raining888/leetcode | e9e8ac51d49e0c5f1450a6b76ba9777b89f7e25b | [
"MIT"
] | null | null | null | tree/IsFull.cc | raining888/leetcode | e9e8ac51d49e0c5f1450a6b76ba9777b89f7e25b | [
"MIT"
] | null | null | null | #include <iostream>
#include <vector>
#include <queue>
#include <random>
#include <stdbool.h>
// 验证树是不是满二叉树
#define MAX_SEED 1024
#define HALF_SEED (MAX_SEED >> 1)
using namespace std;
class IsFull
{
public:
class Node
{
public:
int value;
Node* left;
Node* right;
Node(int data)
{
this->value = data;
}
};
static int h(Node* head)
{
if (head == nullptr)
{
return 0;
}
return std::max(h(head->left), h(head->right)) + 1;
}
static int n(Node* head)
{
if (head == nullptr)
{
return 0;
}
return n(head->left) + n(head->right) + 1;
}
static bool isFull1(Node* head)
{
if (head == nullptr)
{
return true;
}
int height = h(head);
int nodes = n(head);
return (1 << height) - 1 == nodes; // 满二叉树的条件是2^h - 1 = n
}
class Info
{
public:
int height;
int nodes;
Info(int h, int n)
{
height = h;
nodes = n;
}
};
static Info process(Node* head)
{
if (head == nullptr)
{
return Info(0, 0);
}
Info leftInfo = process(head->left);
Info rightInfo = process(head->right);
int height = std::max(leftInfo.height, rightInfo.height) + 1;
int nodes = leftInfo.nodes + rightInfo.nodes + 1;
return Info(height, nodes);
}
static bool isFull2(Node* head)
{
if (head == nullptr)
{
return true;
}
Info all = process(head);
return (1 << all.height) - 1 == all.nodes;
}
static int getRandom(int min, int max)
{
random_device seed; // 硬件生成随机数种子
ranlux48 engine(seed()); // 利用种子生成随机数引
uniform_int_distribution<> distrib(min, max); // 设置随机数范围,并为均匀分布
int res = distrib(engine); // 随机数
return res;
}
// for test
static Node* generateRandomBST(int maxLevel, int maxValue)
{
return generate(1, maxLevel, maxValue);
}
// for test
static Node* generate(int level, int maxLevel, int maxValue)
{
if (level > maxLevel || getRandom(0, MAX_SEED) < HALF_SEED)
{
return nullptr;
}
Node* head = new Node(getRandom(0, maxValue));
head->left = generate(level + 1, maxLevel, maxValue);
head->right = generate(level + 1, maxLevel, maxValue);
return head;
}
static void test()
{
int maxLevel = 5;
int maxValue = 100;
int testTimes = 10000;
for (int i = 0; i < testTimes; i++)
{
Node* head = generateRandomBST(maxLevel, maxValue);
if (isFull1(head) != isFull2(head))
{
cout << "Oops!" << endl;
}
}
cout << "finish!" << endl;
}
};
int main()
{
IsFull::test();
return 0;
}
| 19.806897 | 70 | 0.517758 | [
"vector"
] |
14367ec25d5c5912c949bacfe8b273b7e1b23492 | 2,287 | cpp | C++ | atcoder/abc242/g.cpp | polylogarithm/cp | 426cb6f6ba389ff5f492e5bc2e957aac128781b5 | [
"MIT"
] | null | null | null | atcoder/abc242/g.cpp | polylogarithm/cp | 426cb6f6ba389ff5f492e5bc2e957aac128781b5 | [
"MIT"
] | null | null | null | atcoder/abc242/g.cpp | polylogarithm/cp | 426cb6f6ba389ff5f492e5bc2e957aac128781b5 | [
"MIT"
] | null | null | null | #include <bits/stdc++.h>
using namespace std;
#define pb push_back
#define all(x) (x).begin(), (x).end()
#define um unordered_map
#define pq priority_queue
#define sz(x) ((int)(x).size())
#define fi first
#define se second
#define endl '\n'
typedef vector<int> vi;
typedef long long ll;
typedef unsigned long long ull;
typedef pair<int, int> pii;
mt19937 mrand(random_device{}());
const ll mod = 1000000007;
int rnd(int x) { return mrand() % x;}
ll mulmod(ll a, ll b) {ll res = 0; a %= mod; assert(b >= 0); for (; b; b >>= 1) {if (b & 1)res = (res + a) % mod; a = 2 * a % mod;} return res;}
ll powmod(ll a, ll b) {ll res = 1; a %= mod; assert(b >= 0); for (; b; b >>= 1) {if (b & 1)res = res * a % mod; a = a * a % mod;} return res;}
ll gcd(ll a, ll b) { return b ? gcd(b, a % b) : a;}
//head
//这裸莫队我为啥一个点一直RE
//给我整不会了。。。
//不知道啥原因RE
//upd: 板子出锅了,len被大数据可能为0 比如下面,所以len小于1时候改为1就过了
/*
2
2 2
114514
*/
// #define int long long
const int N = 1010000, M = 1010000, S = 1010000;
int w[N], ans[M];
int cnt[S]; //哈希数组 每个数出现的次数
int n, m, len;
struct Query {
int id, l, r;
} q[M];
int get(int x) {
return x / len;
}
bool cmp(const Query& a, const Query& b) {
int i = get(a.l), j = get(b.l);
if (i != j) return i < j;
return a.r < b.r;
}
void add(int x, int &res) {
cnt[x] ++;
if (cnt[x] % 2 == 0) res++;
}
void del(int x, int &res) {
if (cnt[x] % 2 == 0) res --;
cnt[x] --;
}
void solve() {
cin >> n;
for (int i = 1; i <= n; i++) {
cin >> w[i];
}
cin >> m;
len = sqrt((long double)1.0 * n * n / m);
if (len < 1) len = 1; //注意 len 不要为0
// cout << "LEN = " << len << endl;
for (int i = 0; i < m; i++) {
int l, r;
cin >> l >> r;
q[i] = {i, l, r};
}
sort(q, q + m, cmp);
//j是左边界指针 i是右边界指针 w[]下标都是从1开始
//初始i=0,j=1是为了正确计算[1,1]的结果
for (int k = 0, i = 0, j = 1, res = 0; k < m; k ++) {
int id = q[k].id, l = q[k].l, r = q[k].r;
while (i < r) add(w[++i], res);
while (i > r) del(w[i--], res);
while (j < l) del(w[j++], res);
while (j > l) add(w[--j], res);
ans[id] = res;
}
for (int i = 0; i < m; i++) cout << ans[i] << endl;
}
signed main() {
int t = 1;
// cin >> t;
while (t --) solve();
return 0;
} | 23.10101 | 144 | 0.498032 | [
"vector"
] |
143f3c53bf26f5a158c0b5c79ae75c55157edbc4 | 73,789 | cpp | C++ | src/qt-console/restore/restoretree.cpp | tech-niche-biz/bacula-9.4.4 | 5e74458b612354f6838652dac9ddff94be1bbce6 | [
"BSD-2-Clause"
] | null | null | null | src/qt-console/restore/restoretree.cpp | tech-niche-biz/bacula-9.4.4 | 5e74458b612354f6838652dac9ddff94be1bbce6 | [
"BSD-2-Clause"
] | null | null | null | src/qt-console/restore/restoretree.cpp | tech-niche-biz/bacula-9.4.4 | 5e74458b612354f6838652dac9ddff94be1bbce6 | [
"BSD-2-Clause"
] | null | null | null | /*
Bacula(R) - The Network Backup Solution
Copyright (C) 2000-2016 Kern Sibbald
The original author of Bacula is Kern Sibbald, with contributions
from many others, a complete list can be found in the file AUTHORS.
You may use this file and others of this release according to the
license defined in the LICENSE file, which includes the Affero General
Public License, v3.0 ("AGPLv3") and some additional permissions and
terms pursuant to its AGPLv3 Section 7.
This notice must be preserved when any source code is
conveyed and/or propagated.
Bacula(R) is a registered trademark of Kern Sibbald.
*/
/*
*
* Restore Class
*
* Kern Sibbald, February MMVII
*
*/
#include "bat.h"
#include "restoretree.h"
#include "pages.h"
restoreTree::restoreTree() : Pages()
{
setupUi(this);
m_name = tr("Version Browser");
pgInitialize();
QTreeWidgetItem* thisitem = mainWin->getFromHash(this);
thisitem->setIcon(0, QIcon(QString::fromUtf8(":images/browse.png")));
m_populated = false;
m_debugCnt = 0;
m_debugTrap = true;
QGridLayout *gridLayout = new QGridLayout(this);
gridLayout->setSpacing(6);
gridLayout->setMargin(9);
gridLayout->setObjectName(QString::fromUtf8("gridLayout"));
m_splitter = new QSplitter(Qt::Vertical, this);
QScrollArea *area = new QScrollArea();
area->setObjectName(QString::fromUtf8("area"));
area->setWidget(widget);
area->setWidgetResizable(true);
m_splitter->addWidget(area);
m_splitter->addWidget(splitter);
splitter->setChildrenCollapsible(false);
gridLayout->addWidget(m_splitter, 0, 0, 1, 1);
/* progress widgets */
prBar1->setVisible(false);
prBar2->setVisible(false);
prLabel1->setVisible(false);
prLabel2->setVisible(false);
/* Set Defaults for check and spin for limits */
limitCheckBox->setCheckState(mainWin->m_recordLimitCheck ? Qt::Checked : Qt::Unchecked);
limitSpinBox->setValue(mainWin->m_recordLimitVal);
daysCheckBox->setCheckState(mainWin->m_daysLimitCheck ? Qt::Checked : Qt::Unchecked);
daysSpinBox->setValue(mainWin->m_daysLimitVal);
readSettings();
m_nullFileNameId = -1;
dockPage();
setCurrent();
}
restoreTree::~restoreTree()
{
writeSettings();
}
/*
* Called from the constructor to set up the page widgets and connections.
*/
void restoreTree::setupPage()
{
connect(refreshButton, SIGNAL(pressed()), this, SLOT(refreshButtonPushed()));
connect(restoreButton, SIGNAL(pressed()), this, SLOT(restoreButtonPushed()));
connect(jobCombo, SIGNAL(currentIndexChanged(int)), this, SLOT(jobComboChanged(int)));
connect(jobCombo, SIGNAL(currentIndexChanged(int)), this, SLOT(updateRefresh()));
connect(clientCombo, SIGNAL(currentIndexChanged(int)), this, SLOT(updateRefresh()));
connect(fileSetCombo, SIGNAL(currentIndexChanged(int)), this, SLOT(updateRefresh()));
connect(limitCheckBox, SIGNAL(stateChanged(int)), this, SLOT(updateRefresh()));
connect(daysCheckBox, SIGNAL(stateChanged(int)), this, SLOT(updateRefresh()));
connect(daysSpinBox, SIGNAL(valueChanged(int)), this, SLOT(updateRefresh()));
connect(limitSpinBox, SIGNAL(valueChanged(int)), this, SLOT(updateRefresh()));
connect(directoryTree, SIGNAL(currentItemChanged(QTreeWidgetItem *, QTreeWidgetItem *)),
this, SLOT(directoryCurrentItemChanged(QTreeWidgetItem *, QTreeWidgetItem *)));
connect(directoryTree, SIGNAL(itemExpanded(QTreeWidgetItem *)),
this, SLOT(directoryItemExpanded(QTreeWidgetItem *)));
connect(directoryTree, SIGNAL(itemChanged(QTreeWidgetItem *, int)),
this, SLOT(directoryItemChanged(QTreeWidgetItem *, int)));
connect(fileTable, SIGNAL(currentItemChanged(QTableWidgetItem *, QTableWidgetItem *)),
this, SLOT(fileCurrentItemChanged(QTableWidgetItem *, QTableWidgetItem *)));
connect(jobTable, SIGNAL(cellClicked(int, int)),
this, SLOT(jobTableCellClicked(int, int)));
QStringList titles = QStringList() << tr("Directories");
directoryTree->setHeaderLabels(titles);
clientCombo->addItems(m_console->client_list);
fileSetCombo->addItem(tr("Any"));
fileSetCombo->addItems(m_console->fileset_list);
jobCombo->addItem(tr("Any"));
jobCombo->addItems(m_console->job_list);
directoryTree->setContextMenuPolicy(Qt::ActionsContextMenu);
}
void restoreTree::updateRefresh()
{
if (mainWin->m_rtPopDirDebug) Pmsg2(000, "testing prev=\"%s\" current=\"%s\"\n", m_prevJobCombo.toUtf8().data(), jobCombo->currentText().toUtf8().data());
m_dropdownChanged = (m_prevJobCombo != jobCombo->currentText())
|| (m_prevClientCombo != clientCombo->currentText())
|| (m_prevFileSetCombo != fileSetCombo->currentText()
|| (m_prevLimitSpinBox != limitSpinBox->value())
|| (m_prevDaysSpinBox != daysSpinBox->value())
|| (m_prevLimitCheckState != limitCheckBox->checkState())
|| (m_prevDaysCheckState != daysCheckBox->checkState())
);
if (m_dropdownChanged) {
if (mainWin->m_rtPopDirDebug) Pmsg0(000, "In restoreTree::updateRefresh Is CHANGED\n");
refreshLabel->setText(tr("Refresh From Re-Select"));
} else {
if (mainWin->m_rtPopDirDebug) Pmsg0(000, "In restoreTree::updateRefresh Is not Changed\n");
refreshLabel->setText(tr("Refresh From JobChecks"));
}
}
/*
* When refresh button is pushed, perform a query getting the directories and
* use parseDirectory and addDirectory to populate the directory tree with items.
*/
void restoreTree::populateDirectoryTree()
{
m_debugTrap = true;
m_debugCnt = 0;
m_slashTrap = false;
m_dirPaths.clear();
directoryTree->clear();
fileTable->clear();
fileTable->setRowCount(0);
fileTable->setColumnCount(0);
versionTable->clear();
versionTable->setRowCount(0);
versionTable->setColumnCount(0);
m_fileExceptionHash.clear();
m_fileExceptionMulti.clear();
m_versionExceptionHash.clear();
m_directoryIconStateHash.clear();
updateRefresh();
int taskcount = 3, ontask = 1;
if (m_dropdownChanged) taskcount += 1;
/* Set progress bars and repaint */
prBar1->setVisible(true);
prBar1->setRange(0,taskcount);
prBar1->setValue(0);
prLabel1->setText(tr("Task %1 of %2").arg(ontask).arg(taskcount));
prLabel1->setVisible(true);
prBar2->setVisible(true);
prBar2->setRange(0,0);
prLabel2->setText(tr("Querying Database"));
prLabel2->setVisible(true);
repaint();
if (m_dropdownChanged) {
m_prevJobCombo = jobCombo->currentText();
m_prevClientCombo = clientCombo->currentText();
m_prevFileSetCombo = fileSetCombo->currentText();
m_prevLimitSpinBox = limitSpinBox->value();
m_prevDaysSpinBox = daysSpinBox->value();
m_prevLimitCheckState = limitCheckBox->checkState();
m_prevDaysCheckState = daysCheckBox->checkState();
updateRefresh();
prBar1->setValue(ontask++);
prLabel1->setText(tr("Task %1 of %2").arg(ontask).arg(taskcount));
prBar2->setValue(0);
prBar2->setRange(0,0);
prLabel2->setText(tr("Querying Jobs"));
repaint();
populateJobTable();
}
setJobsCheckedList();
if (mainWin->m_rtPopDirDebug) Pmsg0(000, "Repopulating from checks in Job Table\n");
if (m_checkedJobs != "") {
/* First get the filenameid of where the nae is null. These will be the directories
* This could be done in a subquery but postgres's query analyzer won't do the right
* thing like I want */
if (m_nullFileNameId == -1) {
QString cmd = "SELECT FilenameId FROM Filename WHERE name=''";
if (mainWin->m_sqlDebug)
Pmsg1(000, "Query cmd : %s\n", cmd.toUtf8().data());
QStringList qres;
if (m_console->sql_cmd(cmd, qres)) {
if (qres.count()) {
QStringList fieldlist = qres[0].split("\t");
QString field = fieldlist[0];
bool ok;
int val = field.toInt(&ok, 10);
if (ok) m_nullFileNameId = val;
}
}
}
/* now create the query to get the list of paths */
QString cmd =
"SELECT DISTINCT Path.Path AS Path, File.PathId AS PathId"
" FROM File"
" INNER JOIN Path ON (File.PathId=Path.PathId)";
if (m_nullFileNameId != -1)
cmd += " WHERE File.FilenameId=" + QString("%1").arg(m_nullFileNameId);
else
cmd += " WHERE File.FilenameId IN (SELECT FilenameId FROM Filename WHERE Name='')";
cmd += " AND File.Jobid IN (" + m_checkedJobs + ")";
if (mainWin->m_sqlDebug)
Pmsg1(000, "Query cmd : %s\n", cmd.toUtf8().data());
prBar1->setValue(ontask++);
prLabel1->setText(tr("Task %1 of %2").arg(ontask).arg(taskcount));
prBar2->setValue(0);
prBar2->setRange(0,0);
prLabel2->setText(tr("Querying for Directories"));
repaint();
QStringList results;
m_directoryPathIdHash.clear();
bool querydone = false;
if (m_console->sql_cmd(cmd, results)) {
if (!querydone) {
querydone = true;
prLabel2->setText(tr("Processing Directories"));
prBar2->setRange(0,results.count());
repaint();
}
if (mainWin->m_miscDebug)
Pmsg1(000, "Done with query %i results\n", results.count());
QStringList fieldlist;
foreach(const QString &resultline, results) {
/* Update progress bar periodically */
if ((++m_debugCnt && 0x3FF) == 0) {
prBar2->setValue(m_debugCnt);
}
fieldlist = resultline.split("\t");
int fieldcnt = 0;
/* Iterate through fields in the record */
foreach (const QString &field, fieldlist) {
if (fieldcnt == 0 ) {
parseDirectory(field);
} else if (fieldcnt == 1) {
bool ok;
int pathid = field.toInt(&ok, 10);
if (ok)
m_directoryPathIdHash.insert(fieldlist[0], pathid);
}
fieldcnt += 1;
}
}
} else {
return;
}
} else {
QMessageBox::warning(this, "Bat",
tr("No jobs were selected in the job query !!!.\n"
"Press OK to continue"),
QMessageBox::Ok );
}
prBar1->setVisible(false);
prBar2->setVisible(false);
prLabel1->setVisible(false);
prLabel2->setVisible(false);
}
/*
* Function to set m_checkedJobs from the jobs that are checked in the table
* of jobs
*/
void restoreTree::setJobsCheckedList()
{
m_JobsCheckedList = "";
bool first = true;
/* Update the items in the version table */
int cnt = jobTable->rowCount();
for (int row=0; row<cnt; row++) {
QTableWidgetItem* jobItem = jobTable->item(row, 0);
if (jobItem->checkState() == Qt::Checked) {
if (!first)
m_JobsCheckedList += ",";
m_JobsCheckedList += jobItem->text();
first = false;
jobItem->setBackground(Qt::green);
} else {
if (jobItem->flags())
jobItem->setBackground(Qt::gray);
else
jobItem->setBackground(Qt::darkYellow);
}
}
m_checkedJobs = m_JobsCheckedList;
}
/*
* Function to parse a directory into all possible subdirectories, then add to
* The tree.
*/
void restoreTree::parseDirectory(const QString &dir_in)
{
// bail out if already processed
if (m_dirPaths.contains(dir_in))
return;
// search for parent...
int pos=dir_in.lastIndexOf("/",-2);
if (pos != -1)
{
QString parent=dir_in.left(pos+1);
QString subdir=dir_in.mid(pos+1);
QTreeWidgetItem *item = NULL;
QTreeWidgetItem *parentItem = m_dirPaths.value(parent);
if (parentItem==0) {
// recurse to build parent...
parseDirectory(parent);
parentItem = m_dirPaths.value(parent);
}
/* new directories to add */
item = new QTreeWidgetItem(parentItem);
item->setText(0, subdir);
item->setData(0, Qt::UserRole, QVariant(dir_in));
item->setCheckState(0, Qt::Unchecked);
/* Store the current state of the check status in column 1, which at
* this point has no text*/
item->setData(1, Qt::UserRole, QVariant(Qt::Unchecked));
m_dirPaths.insert(dir_in,item);
}
else
{
QTreeWidgetItem *item = new QTreeWidgetItem(directoryTree);
item->setText(0, dir_in);
item->setData(0, Qt::UserRole, QVariant(dir_in));
item->setData(1, Qt::UserRole, QVariant(Qt::Unchecked));
item->setIcon(0, QIcon(QString::fromUtf8(":images/folder.png")));
m_dirPaths.insert(dir_in,item);
}
}
/*
* Virtual function which is called when this page is visible on the stack
*/
void restoreTree::currentStackItem()
{
if(!m_populated) {
setupPage();
m_populated = true;
}
}
/*
* Populate the tree when refresh button pushed.
*/
void restoreTree::refreshButtonPushed()
{
populateDirectoryTree();
}
/*
* Set the values of non-job combo boxes to the job defaults
*/
void restoreTree::jobComboChanged(int)
{
if (jobCombo->currentText() == tr("Any")) {
fileSetCombo->setCurrentIndex(fileSetCombo->findText(tr("Any"), Qt::MatchExactly));
return;
}
job_defaults job_defs;
//(void)index;
job_defs.job_name = jobCombo->currentText();
if (m_console->get_job_defaults(job_defs)) {
fileSetCombo->setCurrentIndex(fileSetCombo->findText(job_defs.fileset_name, Qt::MatchExactly));
clientCombo->setCurrentIndex(clientCombo->findText(job_defs.client_name, Qt::MatchExactly));
}
}
/*
* Function to populate the file list table
*/
void restoreTree::directoryCurrentItemChanged(QTreeWidgetItem *item, QTreeWidgetItem *)
{
if (item == NULL)
return;
fileTable->clear();
/* Also clear the version table here */
versionTable->clear();
versionFileLabel->setText("");
versionTable->setRowCount(0);
versionTable->setColumnCount(0);
QStringList headerlist = (QStringList() << tr("File Name") << tr("Filename Id"));
fileTable->setColumnCount(headerlist.size());
fileTable->setHorizontalHeaderLabels(headerlist);
fileTable->setRowCount(0);
m_fileCheckStateList.clear();
disconnect(fileTable, SIGNAL(itemChanged(QTableWidgetItem *)),
this, SLOT(fileTableItemChanged(QTableWidgetItem *)));
QBrush blackBrush(Qt::black);
QString directory = item->data(0, Qt::UserRole).toString();
directoryLabel->setText(tr("Present Working Directory: %1").arg(directory));
int pathid = m_directoryPathIdHash.value(directory, -1);
if (pathid != -1) {
QString cmd =
"SELECT DISTINCT Filename.Name AS FileName, Filename.FilenameId AS FilenameId"
" FROM File "
" INNER JOIN Filename on (Filename.FilenameId=File.FilenameId)"
" WHERE File.PathId=" + QString("%1").arg(pathid) +
" AND File.Jobid IN (" + m_checkedJobs + ")"
" AND Filename.Name!=''"
" ORDER BY FileName";
if (mainWin->m_sqlDebug) Pmsg1(000, "Query cmd : %s\n", cmd.toUtf8().data());
QStringList results;
if (m_console->sql_cmd(cmd, results)) {
QTableWidgetItem* tableItem;
QString field;
QStringList fieldlist;
fileTable->setRowCount(results.size());
int row = 0;
/* Iterate through the record returned from the query */
foreach (QString resultline, results) {
/* Iterate through fields in the record */
int column = 0;
fieldlist = resultline.split("\t");
foreach (field, fieldlist) {
field = field.trimmed(); /* strip leading & trailing spaces */
tableItem = new QTableWidgetItem(field, 1);
/* Possible flags are Qt::ItemFlags flag = Qt::ItemIsSelectable | Qt::ItemIsEditablex
* | Qt::ItemIsDragEnabled | Qt::ItemIsDropEnabled | Qt::ItemIsUserCheckable
* | Qt::ItemIsEnabled | Qt::ItemIsTristate; */
tableItem->setForeground(blackBrush);
/* Just in case a column ever gets added */
if (mainWin->m_sqlDebug) Pmsg1(000, "Column=%d\n", column);
if (column == 0) {
Qt::ItemFlags flag = Qt::ItemIsUserCheckable | Qt::ItemIsEnabled | Qt::ItemIsTristate;
tableItem->setFlags(flag);
tableItem->setData(Qt::UserRole, QVariant(directory));
fileTable->setItem(row, column, tableItem);
m_fileCheckStateList.append(Qt::Unchecked);
tableItem->setCheckState(Qt::Unchecked);
} else if (column == 1) {
Qt::ItemFlags flag = Qt::ItemIsEnabled;
tableItem->setFlags(flag);
bool ok;
int filenameid = field.toInt(&ok, 10);
if (!ok) filenameid = -1;
tableItem->setData(Qt::UserRole, QVariant(filenameid));
fileTable->setItem(row, column, tableItem);
}
column++;
}
row++;
}
fileTable->setRowCount(row);
}
fileTable->resizeColumnsToContents();
fileTable->resizeRowsToContents();
fileTable->verticalHeader()->hide();
fileTable->hideColumn(1);
if (mainWin->m_rtDirCurICDebug) Pmsg0(000, "will update file table checks\n");
updateFileTableChecks();
} else if (mainWin->m_sqlDebug)
Pmsg1(000, "did not perform query, pathid=%i not found\n", pathid);
connect(fileTable, SIGNAL(itemChanged(QTableWidgetItem *)),
this, SLOT(fileTableItemChanged(QTableWidgetItem *)));
}
/*
* Function to populate the version table
*/
void restoreTree::fileCurrentItemChanged(QTableWidgetItem *currentFileTableItem, QTableWidgetItem *)
{
if (currentFileTableItem == NULL)
return;
int currentRow = fileTable->row(currentFileTableItem);
QTableWidgetItem *fileTableItem = fileTable->item(currentRow, 0);
QTableWidgetItem *fileNameIdTableItem = fileTable->item(currentRow, 1);
int fileNameId = fileNameIdTableItem->data(Qt::UserRole).toInt();
m_versionCheckStateList.clear();
disconnect(versionTable, SIGNAL(itemChanged(QTableWidgetItem *)),
this, SLOT(versionTableItemChanged(QTableWidgetItem *)));
QString file = fileTableItem->text();
versionFileLabel->setText(file);
QString directory = fileTableItem->data(Qt::UserRole).toString();
QBrush blackBrush(Qt::black);
QStringList headerlist = (QStringList()
<< tr("Job Id") << tr("Type") << tr("End Time") << tr("Hash") << tr("FileId") << tr("Job Type") << tr("First Volume"));
versionTable->clear();
versionTable->setColumnCount(headerlist.size());
versionTable->setHorizontalHeaderLabels(headerlist);
versionTable->setRowCount(0);
int pathid = m_directoryPathIdHash.value(directory, -1);
if ((pathid != -1) && (fileNameId != -1)) {
QString cmd =
"SELECT Job.JobId AS JobId, Job.Level AS Type,"
" Job.EndTime AS EndTime, File.MD5 AS MD5,"
" File.FileId AS FileId, Job.Type AS JobType,"
" (SELECT Media.VolumeName FROM JobMedia JOIN Media ON JobMedia.MediaId=Media.MediaId WHERE JobMedia.JobId=Job.JobId ORDER BY JobMediaId LIMIT 1) AS FirstVolume"
" FROM File"
" INNER JOIN Filename on (Filename.FilenameId=File.FilenameId)"
" INNER JOIN Path ON (Path.PathId=File.PathId)"
" INNER JOIN Job ON (File.JobId=Job.JobId)"
" WHERE Path.PathId=" + QString("%1").arg(pathid) +
//" AND Filename.Name='" + file + "'"
" AND Filename.FilenameId=" + QString("%1").arg(fileNameId) +
" AND Job.Jobid IN (" + m_checkedJobs + ")"
" ORDER BY Job.EndTime DESC";
if (mainWin->m_sqlDebug) Pmsg1(000, "Query cmd : %s\n", cmd.toUtf8().data());
QStringList results;
if (m_console->sql_cmd(cmd, results)) {
QTableWidgetItem* tableItem;
QString field;
QStringList fieldlist;
versionTable->setRowCount(results.size());
int row = 0;
/* Iterate through the record returned from the query */
foreach (QString resultline, results) {
fieldlist = resultline.split("\t");
int column = 0;
/* remove directory */
if (fieldlist[0].trimmed() != "") {
/* Iterate through fields in the record */
foreach (field, fieldlist) {
field = field.trimmed(); /* strip leading & trailing spaces */
if (column == 5 ) {
QByteArray jtype(field.trimmed().toLatin1());
if (jtype.size()) {
field = job_type_to_str(jtype[0]);
}
}
tableItem = new QTableWidgetItem(field, 1);
tableItem->setFlags(0);
tableItem->setForeground(blackBrush);
tableItem->setData(Qt::UserRole, QVariant(directory));
versionTable->setItem(row, column, tableItem);
if (mainWin->m_sqlDebug) Pmsg1(000, "Column=%d\n", column);
if (column == 0) {
Qt::ItemFlags flag = Qt::ItemIsUserCheckable | Qt::ItemIsEnabled | Qt::ItemIsTristate;
tableItem->setFlags(flag);
m_versionCheckStateList.append(Qt::Unchecked);
tableItem->setCheckState(Qt::Unchecked);
}
column++;
}
row++;
}
}
}
versionTable->resizeColumnsToContents();
versionTable->resizeRowsToContents();
versionTable->verticalHeader()->hide();
updateVersionTableChecks();
} else {
if (mainWin->m_sqlDebug)
Pmsg2(000, "not querying : pathid=%i fileNameId=%i\n", pathid, fileNameId);
}
connect(versionTable, SIGNAL(itemChanged(QTableWidgetItem *)),
this, SLOT(versionTableItemChanged(QTableWidgetItem *)));
}
/*
* Save user settings associated with this page
*/
void restoreTree::writeSettings()
{
QSettings settings(m_console->m_dir->name(), "bat");
settings.beginGroup(m_groupText);
settings.setValue(m_splitText1, m_splitter->saveState());
settings.setValue(m_splitText2, splitter->saveState());
settings.endGroup();
}
/*
* Read and restore user settings associated with this page
*/
void restoreTree::readSettings()
{
m_groupText = tr("RestoreTreePage");
m_splitText1 = "splitterSizes1_3";
m_splitText2 = "splitterSizes2_3";
QSettings settings(m_console->m_dir->name(), "bat");
settings.beginGroup(m_groupText);
if (settings.contains(m_splitText1)) { m_splitter->restoreState(settings.value(m_splitText1).toByteArray()); }
if (settings.contains(m_splitText2)) { splitter->restoreState(settings.value(m_splitText2).toByteArray()); }
settings.endGroup();
}
/*
* This is a funcion to accomplish the one thing I struggled to figure out what
* was taking so long. It add the icons, but after the tree is made. Seemed to
* work fast after changing from png to png file for graphic.
*/
void restoreTree::directoryItemExpanded(QTreeWidgetItem *item)
{
int childCount = item->childCount();
for (int i=0; i<childCount; i++) {
QTreeWidgetItem *child = item->child(i);
if (child->icon(0).isNull())
child->setIcon(0, QIcon(QString::fromUtf8(":images/folder.png")));
}
}
/*
* Show what jobs meet the criteria and are being used to
* populate the directory tree and file and version tables.
*/
void restoreTree::populateJobTable()
{
QBrush blackBrush(Qt::black);
if (mainWin->m_rtPopDirDebug) Pmsg0(000, "Repopulating the Job Table\n");
QStringList headerlist = (QStringList()
<< tr("Job Id") << tr("End Time") << tr("Level") << tr("Type")
<< tr("Name") << tr("Purged") << tr("TU") << tr("TD"));
m_toggleUpIndex = headerlist.indexOf(tr("TU"));
m_toggleDownIndex = headerlist.indexOf(tr("TD"));
int purgedIndex = headerlist.indexOf(tr("Purged"));
int typeIndex = headerlist.indexOf(tr("Type"));
jobTable->clear();
jobTable->setColumnCount(headerlist.size());
jobTable->setHorizontalHeaderLabels(headerlist);
QString jobQuery =
"SELECT Job.Jobid AS Id, Job.EndTime AS EndTime,"
" Job.Level AS Level, Job.Type AS Type,"
" Job.Name AS JobName, Job.purgedfiles AS Purged"
" FROM Job"
/* INNER JOIN FileSet eliminates all restore jobs */
" INNER JOIN Client ON (Job.ClientId=Client.ClientId)"
" INNER JOIN FileSet ON (Job.FileSetId=FileSet.FileSetId)"
" WHERE"
" Job.JobStatus IN ('T','W') AND Job.Type='B' AND"
" Client.Name='" + clientCombo->currentText() + "'";
if ((jobCombo->currentIndex() >= 0) && (jobCombo->currentText() != tr("Any"))) {
jobQuery += " AND Job.name = '" + jobCombo->currentText() + "'";
}
if ((fileSetCombo->currentIndex() >= 0) && (fileSetCombo->currentText() != tr("Any"))) {
jobQuery += " AND FileSet.FileSet='" + fileSetCombo->currentText() + "'";
}
/* If Limit check box For limit by days is checked */
if (daysCheckBox->checkState() == Qt::Checked) {
QDateTime stamp = QDateTime::currentDateTime().addDays(-daysSpinBox->value());
QString since = stamp.toString(Qt::ISODate);
jobQuery += " AND Job.Starttime>'" + since + "'";
}
//jobQuery += " AND Job.purgedfiles=0";
jobQuery += " ORDER BY Job.EndTime DESC";
/* If Limit check box for limit records returned is checked */
if (limitCheckBox->checkState() == Qt::Checked) {
QString limit;
limit.setNum(limitSpinBox->value());
jobQuery += " LIMIT " + limit;
}
if (mainWin->m_sqlDebug) Pmsg1(000, "Query cmd : %s\n", jobQuery.toUtf8().data());
QStringList results;
if (m_console->sql_cmd(jobQuery, results)) {
QTableWidgetItem* tableItem;
QString field;
QStringList fieldlist;
jobTable->setRowCount(results.size());
int row = 0;
/* Iterate through the record returned from the query */
foreach (QString resultline, results) {
fieldlist = resultline.split("\t");
int column = 0;
/* remove directory */
if (fieldlist[0].trimmed() != "") {
/* Iterate through fields in the record */
foreach (field, fieldlist) {
field = field.trimmed(); /* strip leading & trailing spaces */
if (field != "") {
if (column == typeIndex) {
QByteArray jtype(field.trimmed().toLatin1());
if (jtype.size()) {
field = job_type_to_str(jtype[0]);
}
}
tableItem = new QTableWidgetItem(field, 1);
tableItem->setFlags(0);
tableItem->setForeground(blackBrush);
jobTable->setItem(row, column, tableItem);
if (mainWin->m_sqlDebug) Pmsg1(000, "Column=%d\n", column);
if (column == 0) {
bool ok;
int purged = fieldlist[purgedIndex].toInt(&ok, 10);
if (!((ok) && (purged == 1))) {
Qt::ItemFlags flag = Qt::ItemIsUserCheckable | Qt::ItemIsEnabled | Qt::ItemIsTristate;
tableItem->setFlags(flag);
tableItem->setCheckState(Qt::Checked);
tableItem->setBackground(Qt::green);
} else {
tableItem->setFlags(0);
tableItem->setCheckState(Qt::Unchecked);
}
}
column++;
}
}
tableItem = new QTableWidgetItem(QIcon(QString::fromUtf8(":images/go-up.png")), "", 1);
tableItem->setFlags(0);
tableItem->setForeground(blackBrush);
jobTable->setItem(row, column, tableItem);
column++;
tableItem = new QTableWidgetItem(QIcon(QString::fromUtf8(":images/go-down.png")), "", 1);
tableItem->setFlags(0);
tableItem->setForeground(blackBrush);
jobTable->setItem(row, column, tableItem);
row++;
}
}
}
jobTable->resizeColumnsToContents();
jobTable->resizeRowsToContents();
jobTable->verticalHeader()->hide();
jobTable->hideColumn(purgedIndex);
}
void restoreTree::jobTableCellClicked(int row, int column)
{
if (column == m_toggleUpIndex){
int cnt;
for (cnt=0; cnt<row+1; cnt++) {
QTableWidgetItem *item = jobTable->item(cnt, 0);
if (item->flags()) {
Qt::CheckState state = item->checkState();
if (state == Qt::Checked)
item->setCheckState(Qt::Unchecked);
else if (state == Qt::Unchecked)
item->setCheckState(Qt::Checked);
}
}
}
if (column == m_toggleDownIndex){
int cnt, max = jobTable->rowCount();
for (cnt=row; cnt<max; cnt++) {
QTableWidgetItem *item = jobTable->item(cnt, 0);
if (item->flags()) {
Qt::CheckState state = item->checkState();
if (state == Qt::Checked)
item->setCheckState(Qt::Unchecked);
else if (state == Qt::Unchecked)
item->setCheckState(Qt::Checked);
}
}
}
}
/*
* When a directory item is "changed" check the state of the checkable item
* to see if it is different than what it was which is stored in Qt::UserRole
* of the 2nd column, column 1, of the tree widget.
*/
void restoreTree::directoryItemChanged(QTreeWidgetItem *item, int /*column*/)
{
Qt::CheckState prevState = (Qt::CheckState)item->data(1, Qt::UserRole).toInt();
Qt::CheckState curState = item->checkState(0);
QTreeWidgetItem* parent = item->parent();
Qt::CheckState parState;
if (parent) parState = parent->checkState(0);
else parState = (Qt::CheckState)3;
if (mainWin->m_rtDirICDebug) {
QString msg = QString("directory item OBJECT has changed prev=%1 cur=%2 par=%3 dir=%4\n")
.arg(prevState).arg(curState).arg(parState).arg(item->text(0));
Pmsg1(000, "%s", msg.toUtf8().data()); }
/* I only care when the check state changes */
if (prevState == curState) {
if (mainWin->m_rtDirICDebug) Pmsg0(000, "Returning Early\n");
return;
}
if ((prevState == Qt::Unchecked) && (curState == Qt::Checked) && (parState != Qt::Unchecked)) {
if (mainWin->m_rtDirICDebug) Pmsg0(000, "Disconnected Setting to Qt::PartiallyChecked\n");
directoryTreeDisconnectedSet(item, Qt::PartiallyChecked);
curState = Qt::PartiallyChecked;
}
if ((prevState == Qt::PartiallyChecked) && (curState == Qt::Checked)) {
if (mainWin->m_rtDirICDebug) Pmsg0(000, "Disconnected Setting to Qt::Unchecked\n");
directoryTreeDisconnectedSet(item, Qt::Unchecked);
curState = Qt::Unchecked;
}
if (mainWin->m_rtDirICDebug) {
QString msg = QString("directory item CHECKSTATE has changed prev=%1 cur=%2 par=%3 dir=%4\n")
.arg(prevState).arg(curState).arg(parState).arg(item->text(0));
Pmsg1(000, "%s", msg.toUtf8().data()); }
item->setData(1, Qt::UserRole, QVariant(curState));
Qt::CheckState childState = curState;
if (childState == Qt::Checked)
childState = Qt::PartiallyChecked;
setCheckofChildren(item, childState);
/* Remove items from the exception lists. The multi exception list is my index
* of what exceptions can be removed when the directory is known*/
QString directory = item->data(0, Qt::UserRole).toString();
QStringList fullPathList = m_fileExceptionMulti.values(directory);
int fullPathListCount = fullPathList.count();
if ((mainWin->m_rtDirICDebug) && fullPathListCount) Pmsg2(000, "Will attempt to remove file exceptions for %s count %i\n", directory.toUtf8().data(), fullPathListCount);
foreach (QString fullPath, fullPathList) {
/* If there is no value in the hash for the key fullPath a value of 3 will be returned
* which will match no Qt::xxx values */
Qt::CheckState hashState = m_fileExceptionHash.value(fullPath, (Qt::CheckState)3);
if (mainWin->m_rtDirICDebug) Pmsg2(000, "hashState=%i childState=%i\n", hashState, childState);
if (hashState == Qt::Unchecked) {
fileExceptionRemove(fullPath, directory);
m_versionExceptionHash.remove(fullPath);
if (mainWin->m_rtDirICDebug) Pmsg0(000, "Attempted Removal A\n");
}
if (hashState == Qt::Checked) {
fileExceptionRemove(fullPath, directory);
m_versionExceptionHash.remove(fullPath);
if (mainWin->m_rtDirICDebug) Pmsg0(000, "Attempted Removal B\n");
}
}
if (item == directoryTree->currentItem()) {
if (mainWin->m_rtDirICDebug) Pmsg0(000, "Will attempt to update File Table Checks\n");
updateFileTableChecks();
versionTable->clear();
versionTable->setRowCount(0);
versionTable->setColumnCount(0);
}
if (mainWin->m_rtDirICDebug) Pmsg0(000, "Returning At End\n");
}
/*
* When a directory item check state is changed, this function iterates through
* all subdirectories and sets all to the passed state, which is either partially
* checked or unchecked.
*/
void restoreTree::setCheckofChildren(QTreeWidgetItem *item, Qt::CheckState state)
{
int childCount;
childCount = item->childCount();
for (int i=0; i<childCount; i++) {
QTreeWidgetItem *child = item->child(i);
child->setData(1, Qt::UserRole, QVariant(state));
child->setCheckState(0, state);
setCheckofChildren(child, state);
}
}
/*
* When a File Table Item is "changed" check to see if the state of the checkable
* item has changed which is stored in m_fileCheckStateList
* If changed store in a hash m_fileExceptionHash that whether this file should be
* restored or not.
* Called as a slot, connected after populated (after directory current changed called)
*/
void restoreTree::fileTableItemChanged(QTableWidgetItem *item)
{
/* get the previous and current check states */
int row = fileTable->row(item);
Qt::CheckState prevState;
/* prevent a segfault */
prevState = m_fileCheckStateList[row];
Qt::CheckState curState = item->checkState();
/* deterimine the default state from the state of the directory */
QTreeWidgetItem *dirTreeItem = directoryTree->currentItem();
Qt::CheckState dirState = (Qt::CheckState)dirTreeItem->data(1, Qt::UserRole).toInt();
Qt::CheckState defState = Qt::PartiallyChecked;
if (dirState == Qt::Unchecked) defState = Qt::Unchecked;
/* determine if it is already in the m_fileExceptionHash */
QString directory = directoryTree->currentItem()->data(0, Qt::UserRole).toString();
QString file = item->text();
QString fullPath = directory + file;
Qt::CheckState hashState = m_fileExceptionHash.value(fullPath, (Qt::CheckState)3);
int verJobNum = m_versionExceptionHash.value(fullPath, 0);
if (mainWin->m_rtFileTabICDebug) {
QString msg = QString("filerow=%1 prev=%2 cur=%3 def=%4 hash=%5 dir=%6 verJobNum=%7\n")
.arg(row).arg(prevState).arg(curState).arg(defState).arg(hashState).arg(dirState).arg(verJobNum);
Pmsg1(000, "%s", msg.toUtf8().data()); }
/* Remove the hash if currently checked previously unchecked and directory is checked or partial */
if ((prevState == Qt::Checked) && (curState == Qt::Unchecked) && (dirState == Qt::Unchecked)) {
/* it can behave as defaulted so current of unchecked is fine */
if (mainWin->m_rtFileTabICDebug) Pmsg0(000, "Will fileExceptionRemove and m_versionExceptionHash.remove here\n");
fileExceptionRemove(fullPath, directory);
m_versionExceptionHash.remove(fullPath);
} else if ((prevState == Qt::PartiallyChecked) && (curState == Qt::Checked) && (dirState != Qt::Unchecked) && (verJobNum == 0)) {
if (mainWin->m_rtFileTabICDebug) Pmsg0(000, "Will fileExceptionInsert here\n");
fileExceptionInsert(fullPath, directory, Qt::Unchecked);
} else if ((prevState == Qt::Unchecked) && (curState == Qt::Checked) && (dirState != Qt::Unchecked) && (verJobNum == 0) && (defState == Qt::PartiallyChecked)) {
/* filerow=2 prev=0 cur=2 def=1 hash=0 dir=2 verJobNum=0 */
if (mainWin->m_rtFileTabICDebug) Pmsg0(000, "Will fileExceptionRemove here\n");
fileExceptionRemove(fullPath, directory);
} else if ((prevState == Qt::Checked) && (curState == Qt::Unchecked) && (defState == Qt::PartiallyChecked) && (verJobNum != 0) && (hashState == Qt::Checked)) {
/* Check dir, check version, attempt uncheck in file
* filerow=4 prev=2 cur=0 def=1 hash=2 dir=2 verJobNum=53 */
if (mainWin->m_rtFileTabICDebug) Pmsg0(000, "Will fileExceptionRemove and m_versionExceptionHash.remove here\n");
fileExceptionRemove(fullPath, directory);
m_versionExceptionHash.remove(fullPath);
} else if ((prevState == Qt::Unchecked) && (curState == Qt::Checked) && (dirState != Qt::Unchecked) && (verJobNum == 0)) {
/* filerow=0 prev=0 cur=2 def=1 hash=0 dirState=2 verJobNum */
if (mainWin->m_rtFileTabICDebug) Pmsg0(000, "Will Not remove here\n");
} else if (prevState != curState) {
if (mainWin->m_rtFileTabICDebug) Pmsg2(000, " THE STATE OF THE Check has changed, Setting StateList[%i] to %i\n", row, curState);
/* A user did not set the check state to Partially checked, ignore if so */
if (curState != Qt::PartiallyChecked) {
if ((defState == Qt::Unchecked) && (prevState == Qt::PartiallyChecked) && (curState == Qt::Unchecked)) {
if (mainWin->m_rtFileTabICDebug) Pmsg0(000, " got here\n");
} else {
if (mainWin->m_rtFileTabICDebug) Pmsg2(000, " Inserting into m_fileExceptionHash %s, %i\n", fullPath.toUtf8().data(), curState);
fileExceptionInsert(fullPath, directory, curState);
}
} else {
if (mainWin->m_rtFileTabICDebug) Pmsg1(000, "Removing version hash for %s\n", fullPath.toUtf8().data());
/* programattically been changed back to a default state of Qt::PartiallyChecked remove the version hash here */
m_versionExceptionHash.remove(fullPath);
}
}
updateFileTableChecks();
updateVersionTableChecks();
}
/*
* function to insert keys and values to both m_fileExceptionHash and m_fileExceptionMulti
*/
void restoreTree::fileExceptionInsert(QString &fullPath, QString &direcotry, Qt::CheckState state)
{
m_fileExceptionHash.insert(fullPath, state);
m_fileExceptionMulti.insert(direcotry, fullPath);
directoryIconStateInsert(fullPath, state);
}
/*
* function to remove keys from both m_fileExceptionHash and m_fileExceptionMulti
*/
void restoreTree::fileExceptionRemove(QString &fullPath, QString &directory)
{
m_fileExceptionHash.remove(fullPath);
/* pull the list of values in the multi */
QStringList fullPathList = m_fileExceptionMulti.values(directory);
/* get the index of the fullpath to remove */
int index = fullPathList.indexOf(fullPath);
if (index != -1) {
/* remove the desired item in the list */
fullPathList.removeAt(index);
/* remove the entire list from the multi */
m_fileExceptionMulti.remove(directory);
/* readd the remaining */
foreach (QString fp, fullPathList) {
m_fileExceptionMulti.insert(directory, fp);
}
}
directoryIconStateRemove();
}
/*
* Overloaded function to be called from the slot and from other places to set the state
* of the check marks in the version table
*/
void restoreTree::versionTableItemChanged(QTableWidgetItem *item)
{
/* get the previous and current check states */
int row = versionTable->row(item);
QTableWidgetItem *colZeroItem = versionTable->item(row, 0);
Qt::CheckState prevState = m_versionCheckStateList[row];
Qt::CheckState curState = (Qt::CheckState)colZeroItem->checkState();
m_versionCheckStateList[row] = curState;
/* deterimine the default state from the state of the file */
QTableWidgetItem *fileTableItem = fileTable->currentItem();
Qt::CheckState fileState = (Qt::CheckState)fileTableItem->checkState();
/* determine the default state */
Qt::CheckState defState;
if (mainWin->m_sqlDebug) Pmsg1(000, "row=%d\n", row);
if (row == 0) {
defState = Qt::PartiallyChecked;
if (fileState == Qt::Unchecked)
defState = Qt::Unchecked;
} else {
defState = Qt::Unchecked;
}
/* determine if it is already in the versionExceptionHash */
QString directory = directoryTree->currentItem()->data(0, Qt::UserRole).toString();
Qt::CheckState dirState = directoryTree->currentItem()->checkState(0);
QString file = fileTableItem->text();
QString fullPath = directory + file;
int thisJobNum = colZeroItem->text().toInt();
int hashJobNum = m_versionExceptionHash.value(fullPath, 0);
if (mainWin->m_rtVerTabICDebug) {
QString msg = QString("versrow=%1 prev=%2 cur=%3 def=%4 dir=%5 hashJobNum=%6 thisJobNum=%7 filestate=%8 fec=%9 vec=%10\n")
.arg(row).arg(prevState).arg(curState).arg(defState).arg(dirState).arg(hashJobNum).arg(thisJobNum).arg(fileState)
.arg(m_fileExceptionHash.count()).arg(m_versionExceptionHash.count());
Pmsg1(000, "%s", msg.toUtf8().data()); }
/* if changed from partially checked to checked, make it unchecked */
if ((curState == Qt::Checked) && (row == 0) && (fileState == Qt::Unchecked)) {
if (mainWin->m_rtVerTabICDebug) Pmsg0(000, "Setting to Qt::Checked\n");
fileTableItem->setCheckState(Qt::Checked);
} else if ((prevState == Qt::PartiallyChecked) && (curState == Qt::Checked) && (row == 0) && (fileState == Qt::Checked) && (dirState == Qt::Unchecked)) {
//versrow=0 prev=1 cur=2 def=1 dir=0 hashJobNum=0 thisJobNum=64 filestate=2 fec=1 vec=0
if (mainWin->m_rtVerTabICDebug) Pmsg1(000, "fileExceptionRemove %s, %i\n", fullPath.toUtf8().data());
fileExceptionRemove(fullPath, directory);
} else if ((curState == Qt::Checked) && (row == 0) && (hashJobNum != 0) && (dirState != Qt::Unchecked)) {
//versrow=0 prev=0 cur=2 def=1 dir=2 hashJobNum=53 thisJobNum=64 filestate=2 fec=1 vec=1
if (mainWin->m_rtVerTabICDebug) Pmsg1(000, "m_versionExceptionHash.remove %s\n", fullPath.toUtf8().data());
m_versionExceptionHash.remove(fullPath);
fileExceptionRemove(fullPath, directory);
} else if ((curState == Qt::Checked) && (row == 0)) {
if (mainWin->m_rtVerTabICDebug) Pmsg1(000, "m_versionExceptionHash.remove %s\n", fullPath.toUtf8().data());
m_versionExceptionHash.remove(fullPath);
} else if (prevState != curState) {
if (mainWin->m_rtVerTabICDebug) Pmsg2(000, " THE STATE OF THE version Check has changed, Setting StateList[%i] to %i\n", row, curState);
if ((curState == Qt::Checked) || (curState == Qt::PartiallyChecked)) {
if (mainWin->m_rtVerTabICDebug) Pmsg2(000, "Inserting into m_versionExceptionHash %s, %i\n", fullPath.toUtf8().data(), thisJobNum);
m_versionExceptionHash.insert(fullPath, thisJobNum);
if (fileState != Qt::Checked) {
if (mainWin->m_rtVerTabICDebug) Pmsg2(000, "Inserting into m_fileExceptionHash %s, %i\n", fullPath.toUtf8().data(), curState);
fileExceptionInsert(fullPath, directory, curState);
}
} else {
if (mainWin->m_rtVerTabICDebug) Pmsg0(000, "got here\n");
}
} else {
if (mainWin->m_rtVerTabICDebug) Pmsg0(000, "no conditions met\n");
}
updateFileTableChecks();
updateVersionTableChecks();
}
/*
* Simple function to set the check state in the file table by disconnecting the
* signal/slot the setting then reconnecting the signal/slot
*/
void restoreTree::fileTableDisconnectedSet(QTableWidgetItem *item, Qt::CheckState state, bool color)
{
disconnect(fileTable, SIGNAL(itemChanged(QTableWidgetItem *)),
this, SLOT(fileTableItemChanged(QTableWidgetItem *)));
item->setCheckState(state);
if (color) item->setBackground(Qt::yellow);
else item->setBackground(Qt::white);
connect(fileTable, SIGNAL(itemChanged(QTableWidgetItem *)),
this, SLOT(fileTableItemChanged(QTableWidgetItem *)));
}
/*
* Simple function to set the check state in the version table by disconnecting the
* signal/slot the setting then reconnecting the signal/slot
*/
void restoreTree::versionTableDisconnectedSet(QTableWidgetItem *item, Qt::CheckState state)
{
disconnect(versionTable, SIGNAL(itemChanged(QTableWidgetItem *)),
this, SLOT(versionTableItemChanged(QTableWidgetItem *)));
item->setCheckState(state);
connect(versionTable, SIGNAL(itemChanged(QTableWidgetItem *)),
this, SLOT(versionTableItemChanged(QTableWidgetItem *)));
}
/*
* Simple function to set the check state in the directory tree by disconnecting the
* signal/slot the setting then reconnecting the signal/slot
*/
void restoreTree::directoryTreeDisconnectedSet(QTreeWidgetItem *item, Qt::CheckState state)
{
disconnect(directoryTree, SIGNAL(itemChanged(QTreeWidgetItem *, int)),
this, SLOT(directoryItemChanged(QTreeWidgetItem *, int)));
item->setCheckState(0, state);
connect(directoryTree, SIGNAL(itemChanged(QTreeWidgetItem *, int)),
this, SLOT(directoryItemChanged(QTreeWidgetItem *, int)));
}
/*
* Simplify the updating of the check state in the File table by iterating through
* each item in the file table to determine it's appropriate state.
* !! Will probably want to concoct a way to do this without iterating for the possibility
* of the very large directories.
*/
void restoreTree::updateFileTableChecks()
{
/* deterimine the default state from the state of the directory */
QTreeWidgetItem *dirTreeItem = directoryTree->currentItem();
Qt::CheckState dirState = dirTreeItem->checkState(0);
QString dirName = dirTreeItem->data(0, Qt::UserRole).toString();
/* Update the items in the version table */
int rcnt = fileTable->rowCount();
for (int row=0; row<rcnt; row++) {
QTableWidgetItem* item = fileTable->item(row, 0);
if (!item) { return; }
Qt::CheckState curState = item->checkState();
Qt::CheckState newState = Qt::PartiallyChecked;
if (dirState == Qt::Unchecked) newState = Qt::Unchecked;
/* determine if it is already in the m_fileExceptionHash */
QString file = item->text();
QString fullPath = dirName + file;
Qt::CheckState hashState = m_fileExceptionHash.value(fullPath, (Qt::CheckState)3);
int hashJobNum = m_versionExceptionHash.value(fullPath, 0);
if (hashState != 3) newState = hashState;
if (mainWin->m_rtUpdateFTDebug) {
QString msg = QString("file row=%1 cur=%2 hash=%3 new=%4 dirState=%5\n")
.arg(row).arg(curState).arg(hashState).arg(newState).arg(dirState);
Pmsg1(000, "%s", msg.toUtf8().data());
}
bool docolor = false;
if (hashJobNum != 0) docolor = true;
bool isyellow = item->background().color() == QColor(Qt::yellow);
if ((newState != curState) || (hashState == 3) || ((isyellow && !docolor) || (!isyellow && docolor)))
fileTableDisconnectedSet(item, newState, docolor);
m_fileCheckStateList[row] = newState;
}
}
/*
* Simplify the updating of the check state in the Version table by iterating through
* each item in the file table to determine it's appropriate state.
*/
void restoreTree::updateVersionTableChecks()
{
/* deterimine the default state from the state of the directory */
QTreeWidgetItem *dirTreeItem = directoryTree->currentItem();
Qt::CheckState dirState = dirTreeItem->checkState(0);
QString dirName = dirTreeItem->data(0, Qt::UserRole).toString();
/* deterimine the default state from the state of the file */
QTableWidgetItem *fileTableItem = fileTable->item(fileTable->currentRow(), 0);
if (!fileTableItem) { return; }
Qt::CheckState fileState = fileTableItem->checkState();
QString file = fileTableItem->text();
QString fullPath = dirName + file;
int hashJobNum = m_versionExceptionHash.value(fullPath, 0);
/* Update the items in the version table */
int cnt = versionTable->rowCount();
for (int row=0; row<cnt; row++) {
QTableWidgetItem* item = versionTable->item(row, 0);
if (!item) { break; }
Qt::CheckState curState = item->checkState();
Qt::CheckState newState = Qt::Unchecked;
if ((row == 0) && (fileState != Qt::Unchecked) && (hashJobNum == 0))
newState = Qt::PartiallyChecked;
/* determine if it is already in the versionExceptionHash */
if (hashJobNum) {
int thisJobNum = item->text().toInt();
if (thisJobNum == hashJobNum)
newState = Qt::Checked;
}
if (mainWin->m_rtChecksDebug) {
QString msg = QString("ver row=%1 cur=%2 hashJobNum=%3 new=%4 dirState=%5\n")
.arg(row).arg(curState).arg(hashJobNum).arg(newState).arg(dirState);
Pmsg1(000, "%s", msg.toUtf8().data());
}
if (newState != curState)
versionTableDisconnectedSet(item, newState);
m_versionCheckStateList[row] = newState;
}
}
/*
* Quick subroutine to "return via subPaths" a list of subpaths when passed a fullPath
*/
void restoreTree::fullPathtoSubPaths(QStringList &subPaths, QString &fullPath_in)
{
int index;
bool done = false;
QString fullPath = fullPath_in;
QString direct, path;
while (((index = fullPath.lastIndexOf("/", -2)) != -1) && (!done)) {
direct = path = fullPath;
path.replace(index+1, fullPath.length()-index-1, "");
direct.replace(0, index+1, "");
if (false) {
QString msg = QString("length = \"%1\" index = \"%2\" Considering \"%3\" \"%4\"\n")
.arg(fullPath.length()).arg(index).arg(path).arg(direct);
Pmsg0(000, msg.toUtf8().data());
}
fullPath = path;
subPaths.append(fullPath);
}
}
/*
* A Function to set the icon state and insert a record into
* m_directoryIconStateHash when an exception is added by the user
*/
void restoreTree::directoryIconStateInsert(QString &fullPath, Qt::CheckState excpState)
{
QStringList paths;
fullPathtoSubPaths(paths, fullPath);
/* an exception that causes the item in the file table to be "Checked" has occured */
if (excpState == Qt::Checked) {
bool foundAsUnChecked = false;
QTreeWidgetItem *firstItem = m_dirPaths.value(paths[0]);
if (firstItem) {
if (firstItem->checkState(0) == Qt::Unchecked)
foundAsUnChecked = true;
}
if (foundAsUnChecked) {
/* as long as directory item is Unchecked, set icon state to "green check" */
bool done = false;
QListIterator<QString> siter(paths);
while (siter.hasNext() && !done) {
QString path = siter.next();
QTreeWidgetItem *item = m_dirPaths.value(path);
if (item) {
if (item->checkState(0) != Qt::Unchecked)
done = true;
else {
directorySetIcon(1, FolderGreenChecked, path, item);
if (mainWin->m_rtIconStateDebug) Pmsg1(000, "In restoreTree::directoryIconStateInsert inserting %s\n", path.toUtf8().data());
}
}
}
} else {
/* if it is partially checked or fully checked insert green Check until a unchecked is found in the path */
if (mainWin->m_rtIconStateDebug) Pmsg1(000, "In restoreTree::directoryIconStateInsert Aqua %s\n", paths[0].toUtf8().data());
bool done = false;
QListIterator<QString> siter(paths);
while (siter.hasNext() && !done) {
QString path = siter.next();
QTreeWidgetItem *item = m_dirPaths.value(path);
if (item) { /* if the directory item is checked, set icon state to unchecked "green check" */
if (item->checkState(0) == Qt::Checked)
done = true;
directorySetIcon(1, FolderGreenChecked, path, item);
if (mainWin->m_rtIconStateDebug) Pmsg1(000, "In restoreTree::directoryIconStateInsert boogie %s\n", path.toUtf8().data());
}
}
}
}
/* an exception that causes the item in the file table to be "Unchecked" has occured */
if (excpState == Qt::Unchecked) {
bool done = false;
QListIterator<QString> siter(paths);
while (siter.hasNext() && !done) {
QString path = siter.next();
QTreeWidgetItem *item = m_dirPaths.value(path);
if (item) { /* if the directory item is checked, set icon state to unchecked "white check" */
if (item->checkState(0) == Qt::Checked)
done = true;
directorySetIcon(1, FolderWhiteChecked, path, item);
if (mainWin->m_rtIconStateDebug) Pmsg1(000, "In restoreTree::directoryIconStateInsert boogie %s\n", path.toUtf8().data());
}
}
}
}
/*
* A function to set the icon state back to "folder" and to remove a record from
* m_directoryIconStateHash when an exception is removed by a user.
*/
void restoreTree::directoryIconStateRemove()
{
QHash<QString, int> shouldBeIconStateHash;
/* First determine all paths with icons that should be checked with m_fileExceptionHash */
/* Use iterator tera to iterate through m_fileExceptionHash */
QHashIterator<QString, Qt::CheckState> tera(m_fileExceptionHash);
while (tera.hasNext()) {
tera.next();
if (mainWin->m_rtIconStateDebug) Pmsg2(000, "Alpha Key %s value %i\n", tera.key().toUtf8().data(), tera.value());
QString keyPath = tera.key();
Qt::CheckState state = tera.value();
QStringList paths;
fullPathtoSubPaths(paths, keyPath);
/* if the state of the item in m_fileExceptionHash is checked
* each of the subpaths should be "Checked Green" */
if (state == Qt::Checked) {
bool foundAsUnChecked = false;
QTreeWidgetItem *firstItem = m_dirPaths.value(paths[0]);
if (firstItem) {
if (firstItem->checkState(0) == Qt::Unchecked)
foundAsUnChecked = true;
}
if (foundAsUnChecked) {
/* The right most directory is Unchecked, iterate leftwards
* as long as directory item is Unchecked, set icon state to "green check" */
bool done = false;
QListIterator<QString> siter(paths);
while (siter.hasNext() && !done) {
QString path = siter.next();
QTreeWidgetItem *item = m_dirPaths.value(path);
if (item) {
if (item->checkState(0) != Qt::Unchecked)
done = true;
else {
shouldBeIconStateHash.insert(path, FolderGreenChecked);
if (mainWin->m_rtIconStateDebug) Pmsg1(000, "In restoreTree::directoryIconStateInsert inserting %s\n", path.toUtf8().data());
}
}
}
}
else {
/* The right most directory is Unchecked, iterate leftwards
* until directory item is Checked, set icon state to "green check" */
bool done = false;
QListIterator<QString> siter(paths);
while (siter.hasNext() && !done) {
QString path = siter.next();
QTreeWidgetItem *item = m_dirPaths.value(path);
if (item) {
if (item->checkState(0) == Qt::Checked)
done = true;
shouldBeIconStateHash.insert(path, FolderGreenChecked);
}
}
}
}
/* if the state of the item in m_fileExceptionHash is UNChecked
* each of the subpaths should be "Checked white" until the tree item
* which represents that path is Qt::Checked */
if (state == Qt::Unchecked) {
bool done = false;
QListIterator<QString> siter(paths);
while (siter.hasNext() && !done) {
QString path = siter.next();
QTreeWidgetItem *item = m_dirPaths.value(path);
if (item) {
if (item->checkState(0) == Qt::Checked)
done = true;
shouldBeIconStateHash.insert(path, FolderWhiteChecked);
}
}
}
}
/* now iterate through m_directoryIconStateHash which are the items that are checked
* and remove all of those that are not in shouldBeIconStateHash */
QHashIterator<QString, int> iter(m_directoryIconStateHash);
while (iter.hasNext()) {
iter.next();
if (mainWin->m_rtIconStateDebug) Pmsg2(000, "Beta Key %s value %i\n", iter.key().toUtf8().data(), iter.value());
QString keyPath = iter.key();
if (shouldBeIconStateHash.value(keyPath)) {
if (mainWin->m_rtIconStateDebug) Pmsg1(000, "WAS found in shouldBeStateHash %s\n", keyPath.toUtf8().data());
//newval = m_directoryIconStateHash.value(path, FolderUnchecked) & (~change);
int newval = shouldBeIconStateHash.value(keyPath);
newval = ~newval;
newval = newval & FolderBothChecked;
QTreeWidgetItem *item = m_dirPaths.value(keyPath);
if (item)
directorySetIcon(0, newval, keyPath, item);
} else {
if (mainWin->m_rtIconStateDebug) Pmsg1(000, "NOT found in shouldBeStateHash %s\n", keyPath.toUtf8().data());
QTreeWidgetItem *item = m_dirPaths.value(keyPath);
if (item)
directorySetIcon(0, FolderBothChecked, keyPath, item);
//item->setIcon(0,QIcon(QString::fromUtf8(":images/folder.png")));
//m_directoryIconStateHash.remove(keyPath);
}
}
}
void restoreTree::directorySetIcon(int operation, int change, QString &path, QTreeWidgetItem* item) {
int newval;
/* we are adding a check type white or green */
if (operation > 0) {
/* get the old val and "bitwise OR" with the change */
newval = m_directoryIconStateHash.value(path, FolderUnchecked) | change;
if (mainWin->m_rtIconStateDebug) Pmsg2(000, "Inserting into m_directoryIconStateHash path=%s newval=%i\n", path.toUtf8().data(), newval);
m_directoryIconStateHash.insert(path, newval);
} else {
/* we are removing a check type white or green */
newval = m_directoryIconStateHash.value(path, FolderUnchecked) & (~change);
if (newval == 0) {
if (mainWin->m_rtIconStateDebug) Pmsg2(000, "Removing from m_directoryIconStateHash path=%s newval=%i\n", path.toUtf8().data(), newval);
m_directoryIconStateHash.remove(path);
}
else {
if (mainWin->m_rtIconStateDebug) Pmsg2(000, "Inserting into m_directoryIconStateHash path=%s newval=%i\n", path.toUtf8().data(), newval);
m_directoryIconStateHash.insert(path, newval);
}
}
if (newval == FolderUnchecked)
item->setIcon(0, QIcon(QString::fromUtf8(":images/folder.png")));
else if (newval == FolderGreenChecked)
item->setIcon(0, QIcon(QString::fromUtf8(":images/folderchecked.png")));
else if (newval == FolderWhiteChecked)
item->setIcon(0, QIcon(QString::fromUtf8(":images/folderunchecked.png")));
else if (newval == FolderBothChecked)
item->setIcon(0, QIcon(QString::fromUtf8(":images/folderbothchecked.png")));
}
/*
* Restore Button
*/
void restoreTree::restoreButtonPushed()
{
/* Set progress bars and repaint */
prLabel1->setVisible(true);
prLabel1->setText(tr("Task 1 of 3"));
prLabel2->setVisible(true);
prLabel2->setText(tr("Processing Checked directories"));
prBar1->setVisible(true);
prBar1->setRange(0, 3);
prBar1->setValue(0);
prBar2->setVisible(true);
prBar2->setRange(0, 0);
repaint();
QMultiHash<int, QString> versionFilesMulti;
int vFMCounter = 0;
QHash <QString, bool> fullPathDone;
QHash <QString, int> fileIndexHash;
if ((mainWin->m_rtRestore1Debug) || (mainWin->m_rtRestore2Debug) || (mainWin->m_rtRestore3Debug))
Pmsg0(000, "In restoreTree::restoreButtonPushed\n");
/* Use a tree widget item iterator to count directories for the progress bar */
QTreeWidgetItemIterator diterc(directoryTree, QTreeWidgetItemIterator::Checked);
int ditcount = 0;
while (*diterc) {
ditcount += 1;
++diterc;
} /* while (*diterc) */
prBar2->setRange(0, ditcount);
prBar2->setValue(0);
ditcount = 0;
/* Use a tree widget item iterator filtering for Checked Items */
QTreeWidgetItemIterator diter(directoryTree, QTreeWidgetItemIterator::Checked);
while (*diter) {
QString directory = (*diter)->data(0, Qt::UserRole).toString();
int pathid = m_directoryPathIdHash.value(directory, -1);
if (pathid != -1) {
if (mainWin->m_rtRestore1Debug)
Pmsg1(000, "Directory Checked=\"%s\"\n", directory.toUtf8().data());
/* With a checked directory, query for the files in the directory */
QString cmd =
"SELECT Filename.Name AS Filename, t1.JobId AS JobId, File.FileIndex AS FileIndex"
" FROM"
" ( SELECT File.FilenameId AS FilenameId, MAX(Job.JobId) AS JobId"
" FROM File"
" INNER JOIN Job ON (Job.JobId=File.JobId)"
" WHERE File.PathId=" + QString("%1").arg(pathid) +
" AND Job.Jobid IN (" + m_checkedJobs + ")"
" GROUP BY File.FilenameId"
") t1, File "
" INNER JOIN Filename on (Filename.FilenameId=File.FilenameId)"
" INNER JOIN Job ON (Job.JobId=File.JobId)"
" WHERE File.PathId=" + QString("%1").arg(pathid) +
" AND File.FilenameId=t1.FilenameId"
" AND Job.Jobid=t1.JobId"
" ORDER BY Filename";
if (mainWin->m_sqlDebug) Pmsg1(000, "Query cmd : %s\n", cmd.toUtf8().data());
QStringList results;
if (m_console->sql_cmd(cmd, results)) {
QStringList fieldlist;
int row = 0;
/* Iterate through the record returned from the query */
foreach (QString resultline, results) {
/* Iterate through fields in the record */
int column = 0;
QString fullPath = "";
Qt::CheckState fileExcpState = (Qt::CheckState)4;
fieldlist = resultline.split("\t");
int version = 0;
int fileIndex = 0;
foreach (QString field, fieldlist) {
if (column == 0) {
fullPath = directory + field;
}
if (column == 1) {
version = field.toInt();
}
if (column == 2) {
fileIndex = field.toInt();
}
column++;
}
fileExcpState = m_fileExceptionHash.value(fullPath, (Qt::CheckState)3);
int excpVersion = m_versionExceptionHash.value(fullPath, 0);
if (fileExcpState != Qt::Unchecked) {
QString debugtext;
if (excpVersion != 0) {
debugtext = QString("*E* version=%1").arg(excpVersion);
version = excpVersion;
fileIndex = queryFileIndex(fullPath, excpVersion);
} else
debugtext = QString("___ version=%1").arg(version);
if (mainWin->m_rtRestore1Debug)
Pmsg2(000, "Restoring %s File %s\n", debugtext.toUtf8().data(), fullPath.toUtf8().data());
fullPathDone.insert(fullPath, 1);
fileIndexHash.insert(fullPath, fileIndex);
versionFilesMulti.insert(version, fullPath);
vFMCounter += 1;
}
row++;
}
}
}
ditcount += 1;
prBar2->setValue(ditcount);
++diter;
} /* while (*diter) */
prBar1->setValue(1);
prLabel1->setText( tr("Task 2 of 3"));
prLabel2->setText(tr("Processing Exceptions"));
prBar2->setRange(0, 0);
repaint();
/* There may be some exceptions not accounted for yet with fullPathDone */
QHashIterator<QString, Qt::CheckState> ftera(m_fileExceptionHash);
while (ftera.hasNext()) {
ftera.next();
QString fullPath = ftera.key();
Qt::CheckState state = ftera.value();
if (state != 0) {
/* now we don't want the ones already done */
if (fullPathDone.value(fullPath, 0) == 0) {
int version = m_versionExceptionHash.value(fullPath, 0);
int fileIndex = 0;
QString debugtext = "";
if (version != 0) {
fileIndex = queryFileIndex(fullPath, version);
debugtext = QString("E1* version=%1 fileid=%2").arg(version).arg(fileIndex);
} else {
version = mostRecentVersionfromFullPath(fullPath);
if (version) {
fileIndex = queryFileIndex(fullPath, version);
debugtext = QString("E2* version=%1 fileid=%2").arg(version).arg(fileIndex);
} else
debugtext = QString("Error det vers").arg(version);
}
if (mainWin->m_rtRestore1Debug)
Pmsg2(000, "Restoring %s file %s\n", debugtext.toUtf8().data(), fullPath.toUtf8().data());
versionFilesMulti.insert(version, fullPath);
vFMCounter += 1;
fileIndexHash.insert(fullPath, fileIndex);
} /* if fullPathDone.value(fullPath, 0) == 0 */
} /* if state != 0 */
} /* while ftera.hasNext */
/* The progress bars for the next step */
prBar1->setValue(2);
prLabel1->setText(tr("Task 3 of 3"));
prLabel2->setText(tr("Filling Database Table"));
prBar2->setRange(0, vFMCounter);
vFMCounter = 0;
prBar2->setValue(vFMCounter);
repaint();
/* now for the final spit out of the versions and lists of files for each version */
QHash<int, int> doneKeys;
QHashIterator<int, QString> vFMiter(versionFilesMulti);
QString tempTable = "";
QList<int> jobList;
while (vFMiter.hasNext()) {
vFMiter.next();
int fversion = vFMiter.key();
/* did not succeed in getting an iterator to work as expected on versionFilesMulti so use doneKeys */
if (doneKeys.value(fversion, 0) == 0) {
if (tempTable == "") {
QSettings settings("www.bacula.org", "bat");
settings.beginGroup("Restore");
int counter = settings.value("Counter", 1).toInt();
settings.setValue("Counter", counter+1);
settings.endGroup();
tempTable = "restore_" + QString("%1").arg(qrand()) + "_" + QString("%1").arg(counter);
QString sqlcmd = "CREATE TEMPORARY TABLE " + tempTable + " (JobId INTEGER, FileIndex INTEGER)";
if (mainWin->m_sqlDebug)
Pmsg1(000, "Query cmd : %s ;\n", sqlcmd.toUtf8().data());
QStringList results;
if (!m_console->sql_cmd(sqlcmd, results))
Pmsg1(000, "CREATE TABLE FAILED!!!! %s\n", sqlcmd.toUtf8().data());
}
if (mainWin->m_rtRestore2Debug) Pmsg1(000, "Version->%i\n", fversion);
QStringList fullPathList = versionFilesMulti.values(fversion);
/* create the command to perform the restore */
foreach(QString ffullPath, fullPathList) {
int fileIndex = fileIndexHash.value(ffullPath);
if (mainWin->m_rtRestore2Debug) Pmsg2(000, " file->%s id %i\n", ffullPath.toUtf8().data(), fileIndex);
QString sqlcmd = "INSERT INTO " + tempTable + " (JobId, FileIndex) VALUES (" + QString("%1").arg(fversion) + ", " + QString("%1").arg(fileIndex) + ")";
if (mainWin->m_rtRestore3Debug)
Pmsg1(000, "Insert cmd : %s\n", sqlcmd.toUtf8().data());
QStringList results;
if (!m_console->sql_cmd(sqlcmd, results))
Pmsg1(000, "INSERT INTO FAILED!!!! %s\n", sqlcmd.toUtf8().data());
prBar2->setValue(++vFMCounter);
} /* foreach fullPathList */
doneKeys.insert(fversion,1);
jobList.append(fversion);
} /* if (doneKeys.value(fversion, 0) == 0) */
} /* while (vFMiter.hasNext()) */
if (tempTable != "") {
/* a table was made, lets run the job */
QString jobOption = " jobid=\"";
bool first = true;
/* create a list of jobs comma separated */
foreach (int job, jobList) {
if (first) first = false;
else jobOption += ",";
jobOption += QString("%1").arg(job);
}
jobOption += "\"";
QString cmd = QString("restore");
cmd += jobOption +
" client=\"" + m_prevClientCombo + "\"" +
" file=\"?" + tempTable + "\" done";
if (mainWin->m_commandDebug)
Pmsg1(000, "preRestore command \'%s\'\n", cmd.toUtf8().data());
consoleCommand(cmd);
}
/* turn off the progress widgets */
prBar1->setVisible(false);
prBar2->setVisible(false);
prLabel1->setVisible(false);
prLabel2->setVisible(false);
}
int restoreTree::mostRecentVersionfromFullPath(QString &fullPath)
{
int qversion = 0;
QString directory, fileName;
int index = fullPath.lastIndexOf("/", -2);
if (index != -1) {
directory = fileName = fullPath;
directory.replace(index+1, fullPath.length()-index-1, "");
fileName.replace(0, index+1, "");
if (false) {
QString msg = QString("length = \"%1\" index = \"%2\" Considering \"%3\" \"%4\"\n")
.arg(fullPath.length()).arg(index).arg(fileName).arg(directory);
Pmsg0(000, msg.toUtf8().data());
}
int pathid = m_directoryPathIdHash.value(directory, -1);
if (pathid != -1) {
/* so now we need the latest version from the database */
QString cmd =
"SELECT MAX(Job.JobId)"
" FROM File "
" INNER JOIN Filename on (Filename.FilenameId=File.FilenameId)"
" INNER JOIN Job ON (File.JobId=Job.JobId)"
" WHERE File.PathId=" + QString("%1").arg(pathid) +
" AND Job.Jobid IN (" + m_checkedJobs + ")"
" AND Filename.Name='" + fileName + "'"
" AND File.FilenameId!=" + QString("%1").arg(m_nullFileNameId) +
" GROUP BY Filename.Name";
if (mainWin->m_sqlDebug) Pmsg1(000, "Query cmd : %s\n", cmd.toUtf8().data());
QStringList results;
if (m_console->sql_cmd(cmd, results)) {
QStringList fieldlist;
int row = 0;
/* Iterate through the record returned from the query */
foreach (QString resultline, results) {
/* Iterate through fields in the record */
int column = 0;
fieldlist = resultline.split("\t");
foreach (QString field, fieldlist) {
if (column == 0) {
qversion = field.toInt();
}
column++;
}
row++;
}
}
}
} /* if (index != -1) */
return qversion;
}
int restoreTree::queryFileIndex(QString &fullPath, int jobId)
{
int qfileIndex = 0;
QString directory, fileName;
int index = fullPath.lastIndexOf("/", -2);
if (mainWin->m_sqlDebug) Pmsg1(000, "Index=%d\n", index);
if (index != -1) {
directory = fileName = fullPath;
directory.replace(index+1, fullPath.length()-index-1, "");
fileName.replace(0, index+1, "");
if (false) {
QString msg = QString("length = \"%1\" index = \"%2\" Considering \"%3\" \"%4\"\n")
.arg(fullPath.length()).arg(index).arg(fileName).arg(directory);
Pmsg0(000, msg.toUtf8().data());
}
int pathid = m_directoryPathIdHash.value(directory, -1);
if (pathid != -1) {
/* so now we need the latest version from the database */
QString cmd =
"SELECT"
" File.FileIndex"
" FROM File"
" INNER JOIN Filename on (Filename.FilenameId=File.FilenameId)"
" INNER JOIN Job ON (File.JobId=Job.JobId)"
" WHERE File.PathId=" + QString("%1").arg(pathid) +
" AND Filename.Name='" + fileName + "'"
" AND Job.Jobid='" + QString("%1").arg(jobId) + "'"
" GROUP BY File.FileIndex";
if (mainWin->m_sqlDebug) Pmsg1(000, "Query cmd : %s\n", cmd.toUtf8().data());
QStringList results;
if (m_console->sql_cmd(cmd, results)) {
QStringList fieldlist;
int row = 0;
/* Iterate through the record returned from the query */
foreach (QString resultline, results) {
/* Iterate through fields in the record */
int column = 0;
fieldlist = resultline.split("\t");
foreach (QString field, fieldlist) {
if (column == 0) {
qfileIndex = field.toInt();
}
column++;
}
row++;
}
}
}
} /* if (index != -1) */
if (mainWin->m_sqlDebug) Pmsg1(000, "qfileIndex=%d\n", qfileIndex);
return qfileIndex;
}
void restoreTree::PgSeltreeWidgetClicked()
{
if (!isOnceDocked()) {
dockPage();
}
}
| 41.783126 | 172 | 0.618805 | [
"object"
] |
143f49d6190d8b1d963adb7c012c49900391b63d | 674 | hpp | C++ | DemoProject/Kameleon/kPlayer.hpp | spywhere/Legacy-ParticlePlay | 0c1ec6e4706f72b64e0408cc79cdeffce535b484 | [
"BSD-3-Clause"
] | null | null | null | DemoProject/Kameleon/kPlayer.hpp | spywhere/Legacy-ParticlePlay | 0c1ec6e4706f72b64e0408cc79cdeffce535b484 | [
"BSD-3-Clause"
] | null | null | null | DemoProject/Kameleon/kPlayer.hpp | spywhere/Legacy-ParticlePlay | 0c1ec6e4706f72b64e0408cc79cdeffce535b484 | [
"BSD-3-Clause"
] | null | null | null | #ifndef KPLAYER_HEADER
#define KPLAYER_HEADER
#include <ParticlePlay/ParticlePlay.hpp>
#include "PhysicsObject.hpp"
#include "AnimateImage.hpp"
class kPlayer : public PhysicsObject {
protected:
AnimateImage* idlePose;
AnimateImage* runPose;
AnimateImage* swimPose;
AnimateImage* jumpPose;
AnimateImage* fallPose;
AnimateImage* currentPose;
SDL_RendererFlip playerFlip;
b2Body* circleBody;
float health;
bool isAttack;
public:
b2Body* boxBody;
kPlayer(ppPhysics* physics, int x, int y);
float GetWaterLevel();
float GetHealth();
int GetX();
int GetY();
void Attack();
void Render(ppGraphics* graphics);
void Update(ppInput* input, int delta);
};
#endif
| 20.424242 | 43 | 0.764095 | [
"render"
] |
1444dbf1643694cf51c3b7f55ef1d2479abea13c | 893 | cpp | C++ | problemsets/Codeforces/C++/A948.cpp | juarezpaulino/coderemite | a4649d3f3a89d234457032d14a6646b3af339ac1 | [
"Apache-2.0"
] | null | null | null | problemsets/Codeforces/C++/A948.cpp | juarezpaulino/coderemite | a4649d3f3a89d234457032d14a6646b3af339ac1 | [
"Apache-2.0"
] | null | null | null | problemsets/Codeforces/C++/A948.cpp | juarezpaulino/coderemite | a4649d3f3a89d234457032d14a6646b3af339ac1 | [
"Apache-2.0"
] | null | null | null | /**
*
* Author: Juarez Paulino(coderemite)
* Email: juarez.paulino@gmail.com
*
*/
#include <bits/stdc++.h>
using namespace std;
int main() {
int dy[] = { -1, 0, 1, 0 };
int dx[] = { 0, -1, 0, 1 };
int r, c; scanf("%d %d ", &r, &c);
vector<string> F = vector<string>(r+10, string(c+10, '.'));
for (int i = 1; i <= r; i++) cin >> &F[i][1];
auto check = [&](int y, int x) {
for (int i = 0; i < 4; i++)
if (F[y+dy[i]][x+dx[i]] == 'S') return 0;
return 1;
};
auto dog = [&](int y, int x) {
for (int i = 0; i < 4; i++) {
char &c = F[y+dy[i]][x+dx[i]];
if (c == '.') c = 'D';
}
};
for (int i = 1; i <= r; i++) for (int j = 1; j <= c; j++)
if (F[i][j]=='W') { if (!check(i,j)) { cout << "No"; return 0; } }
else if (F[i][j]=='S') dog(i,j);
cout << "Yes" << endl;
for (int i = 1; i <= r; i++) cout << F[i].substr(1,c) << endl;
}
| 27.060606 | 70 | 0.431131 | [
"vector"
] |
1445a70eac3e1be70cf69f69ec9fb51b583a73b4 | 1,593 | cpp | C++ | ros2/ros_ws/src/simulation/src/Rose_DisplayPublisher.cpp | ros-e/ros-e-software | f35cf79e97f0c675c8169e0d6769cdbcf957c0ae | [
"MIT"
] | null | null | null | ros2/ros_ws/src/simulation/src/Rose_DisplayPublisher.cpp | ros-e/ros-e-software | f35cf79e97f0c675c8169e0d6769cdbcf957c0ae | [
"MIT"
] | 3 | 2021-01-23T16:37:03.000Z | 2021-01-23T16:50:38.000Z | ros2/ros_ws/src/simulation/src/Rose_DisplayPublisher.cpp | ros-e/ros-e-software | f35cf79e97f0c675c8169e0d6769cdbcf957c0ae | [
"MIT"
] | null | null | null |
#include <sstream>
#include "Rose_DisplayPublisher.h"
Rose_DisplayPublisher::Rose_DisplayPublisher(uint8_t w, uint8_t h) : GFX_Buffer(h, w)
{
}
/*!
@brief Destructor for Rose_DisplayPublisher object.
*/
Rose_DisplayPublisher::~Rose_DisplayPublisher(void) {
delete(this);
}
uint8_t *Rose_DisplayPublisher::getBuffer(void) {
return buffer;
}
void Rose_DisplayPublisher::display() {
systemcore::RedisMessage redisMsg;
// std::stringstream ssKey;
// ssKey << "simulation/eyes/left";
redisMsg.key = this->redisTopic;
std::stringstream ssJson;
ssJson << "{\"rows\": 128, \"cols\": 64, \"bitMap\": [";
int colsInBuffer = (this->width() + 7) / 8;
for (int r = 0; r < this->height(); r++ ) {
for (int c = 0; c < colsInBuffer; c++ ) {
if (r > 0 || c > 0) ssJson << ", ";
int index = r * colsInBuffer + c;
//ROS_INFO("[%i, %i]: %i %i", c * colsInBuffer, r, index, this->buffer[index]);
ssJson << std::to_string(this->buffer[index]);
}
}
/*
for (int i = 0; i < this->width() * ((this->height() + 7) / 8); i++)
{
if (i != 0) ssJson << ", ";
//this->getPixel()
ssJson << std::to_string(this->buffer[i]);
}*/
ssJson << "]}";
redisMsg.json = ssJson.str();
this->redisPublisher->publish(redisMsg);
}
void Rose_DisplayPublisher::linkGenericRosPublisher(ros::Publisher * redisPublisher, std::string redisTopic) {
this->redisPublisher = redisPublisher;
this->redisTopic = redisTopic;
} | 21.24 | 110 | 0.574388 | [
"object"
] |
14482dc3de1d26fd52c5bb1f6150495f3ff6c964 | 8,123 | cpp | C++ | src/path_planner.cpp | bsirang/CarND-Path-Planning-Project | 7e1cdbc346a8387e0852ecd0b222e6abc0d35e30 | [
"MIT"
] | null | null | null | src/path_planner.cpp | bsirang/CarND-Path-Planning-Project | 7e1cdbc346a8387e0852ecd0b222e6abc0d35e30 | [
"MIT"
] | null | null | null | src/path_planner.cpp | bsirang/CarND-Path-Planning-Project | 7e1cdbc346a8387e0852ecd0b222e6abc0d35e30 | [
"MIT"
] | null | null | null | #include "path_planner.hpp"
#include "utilities.hpp"
#include "helpers.h"
#include <string>
#include <sstream>
#include <stdexcept>
#include <iostream>
using namespace Common::Utilities;
using namespace Common;
PathPlanner::PathPlanner(const points_2d_t & map_xy, const points_2d_t & map_dxdy, const points_1d_t & map_s, double delta_t) : map_xy_{map_xy}, map_dxdy_{map_dxdy}, map_s_{map_s}, delta_t_{delta_t} {}
PathPlanner::points_2d_t PathPlanner::getNextPath(const points_2d_t & previous_path, const point_2d_t & path_end, const Pose & current_pose, sensor_fusion_t fusion_results) {
sanityCheckPreviousPath(previous_path);
std::vector<Object> other_cars = getObjectVectorFromSensorFusion(fusion_results);
// First run the proximity detector to adjust our velocity if need be
proximityDetector(last_target_lane_, other_cars, current_pose);
auto target_lane = bp_.getDesiredLane(current_pose, other_cars);
// Then generate a spline based on where our previous path left off
// and projecting forward into our desired lane
auto spline = generateSpline(previous_path, current_pose, target_lane);
points_2d_t new_points = generateNextPathFromSpline(spline, previous_path, current_pose);
last_target_lane_ = target_lane;
return new_points;
}
void PathPlanner::sanityCheckPreviousPath(const points_2d_t & previous_path) {
if (previous_path.first.size() != previous_path.second.size()) {
std::stringstream msg;
msg << "Previous path vectors must be of equal length! (" << previous_path.first.size() <<
" != " << previous_path.second.size() << ")";
throw std::runtime_error(msg.str());
}
size_t prev_path_size = previous_path.first.size();
if (prev_path_size > kNumPoints) {
std::stringstream msg;
msg << "Previous path has more points than expected! " << prev_path_size << " > " << kNumPoints;
throw std::runtime_error(msg.str());
}
}
tk::spline PathPlanner::generateSpline(const points_2d_t & previous_path, const Pose & current_pose, lane_t target_lane) {
// First let's gather some points for our spline. We'll use the previous two
// points and then project a few more points out into the distance along
// our current lane
static constexpr size_t num_prev_points{2};
points_2d_t input_points_xy;
auto prev_path_size = previous_path.first.size();
const auto & x = previous_path.first;
const auto & y = previous_path.second;
if (prev_path_size >= num_prev_points) {
for (size_t i = num_prev_points; i > 0; --i) {
input_points_xy.first.push_back(x[prev_path_size-i]);
input_points_xy.second.push_back(y[prev_path_size-i]);
}
} else {
// Use two points that make the path tangent to the car's current pose
double prev_car_x = current_pose.x - ::cos(current_pose.yaw);
double prev_car_y = current_pose.y - ::sin(current_pose.yaw);
input_points_xy.first.push_back(prev_car_x);
input_points_xy.first.push_back(current_pose.x);
input_points_xy.second.push_back(prev_car_y);
input_points_xy.second.push_back(current_pose.y);
}
// At this point we have our first two points, let's generate some more
for (size_t i = 0; i < kSplineNumPoints; ++i) {
auto lane = (i == 0) ? last_target_lane_ : target_lane;
double s = current_pose.s + (i + 1) * kSplineAnchorDistanceInterval;
double d = getCenterPositionOfLane(last_target_lane_);
point_2d_t point{s, d};
auto waypoint = getXYFromFrenet(point);
input_points_xy.first.push_back(waypoint.first);
input_points_xy.second.push_back(waypoint.second);
}
// Now we have all of our points, let's transform to car coordinate frame
// to make the spline generation much simpler...
for (size_t i = 0; i < input_points_xy.first.size(); ++i) {
auto x = input_points_xy.first[i];
auto y = input_points_xy.second[i];
auto xy_transform = mapFrameToCarFrame({x, y}, current_pose);
input_points_xy.first[i] = xy_transform.first;
input_points_xy.second[i] = xy_transform.second;
}
tk::spline s;
s.set_points(input_points_xy.first, input_points_xy.second);
return s;
}
void PathPlanner::proximityDetector(lane_t target_lane, const std::vector<Object> & objects, const Pose & current_pose) {
unsigned int current_lane = target_lane;
double new_speed = kMaxVelocity;
double speed_reduction_factor = 1.0;
for (const auto & object : objects) {
Pose p{object};
unsigned int lane = getCurrentLaneNo(p);
if (lane == current_lane) {
double distance = p.s - current_pose.s;
double braking_distance = std::max(calculateBrakingDistance() + kBrakingMargin, 0.0);
if (distance > 0.0 && distance < braking_distance) {
speed_reduction_factor = (braking_distance - distance) / braking_distance;
double speed = speed_reduction_factor * p.speed;
if (speed < new_speed) {
new_speed = speed;
}
}
}
}
target_velocity_ = new_speed;
}
PathPlanner::points_2d_t PathPlanner::generateNextPathFromSpline(const tk::spline & s, const points_2d_t & previous_path, const Pose & current_pose) {
points_2d_t next_path;
next_path.first.insert(next_path.first.begin(), previous_path.first.begin(), previous_path.first.end());
next_path.second.insert(next_path.second.begin(), previous_path.second.begin(), previous_path.second.end());
size_t prev_path_size = previous_path.first.size();
size_t num_new_points = kNumPoints - prev_path_size;
if (!num_new_points) {
return next_path;
}
// We are in car reference frame, so our heading is along the x axis.
// We want to choose an arbitrary distance horizon along
// our X axis, which we will then use to find a target points along the spline.
double target_x = kSplineDistanceHorizon;
double target_y = s(target_x);
double distance = ::sqrt(target_x*target_x + target_y*target_y);
double next_x = 0.0;
if (prev_path_size > 0) {
// let's start where we last left off
point_2d_t last{previous_path.first[prev_path_size-1], previous_path.second[prev_path_size-1]};
last = mapFrameToCarFrame(last, current_pose);
next_x = last.first;
}
for (size_t i = 0; i < num_new_points; ++i) {
// Update our current velocities and accelerations based on our targets
current_acceleration_ = updateKinematics(current_acceleration_, target_acceleration_, kMaxJerk, delta_t_);
current_velocity_ = updateKinematics(current_velocity_, target_velocity_, current_acceleration_, delta_t_);
// Now that we have our target point, we can figure out the length of our
// discrete distance increments to reach the point at our desired velocity.
double N = distance / (delta_t_ * current_velocity_);
// Distance of each increment along the X axis
double x_dist_increment = target_x / N;
// double last_x = next_x;
// double last_y = s(last_x);
next_x += x_dist_increment;
double next_y = s(next_x);
// double delta_x = next_x - last_x;
// double delta_y = next_y - last_y;
// double dist = ::sqrt(delta_x*delta_x + delta_y*delta_y);
// if ( dist > (delta_t_ * current_velocity_)) {
// double reduction = (delta_t_ * current_velocity_) / dist;
// next_x *= reduction;
// next_y = s(next_x);
// // std::cout << "Reduced next_x by " << reduction << std::endl;
// }
auto xy_transform = carFrameToMapFrame({next_x, next_y}, current_pose);
next_path.first.push_back(xy_transform.first);
next_path.second.push_back(xy_transform.second);
}
return next_path;
}
PathPlanner::point_2d_t PathPlanner::generatePointAheadFrenet(point_2d_t point, double velocity) const {
// Simply adjust s value by distance given by velocity and delta_t while keeping d constant
return {point.first + velocity * delta_t_, point.second};
}
PathPlanner::point_2d_t PathPlanner::getXYFromFrenet(point_2d_t frenet) const {
auto xy = getXY(frenet.first, frenet.second, map_s_, map_xy_.first, map_xy_.second);
return {xy[0], xy[1]};
}
double PathPlanner::calculateBrakingDistance() {
return (current_velocity_ * current_velocity_) / (2.0 * kMaxAcceleration);
}
| 40.412935 | 201 | 0.724117 | [
"object",
"vector",
"transform"
] |
145311dcc71e2e068a8c49a684c6dfc88144a1b8 | 1,766 | hpp | C++ | driver/filesystem/devfs/devfs.hpp | Edgaru089/helos1 | 8dd27c421bdf1d55e3a62b61927d2f0db6f94d01 | [
"Apache-2.0"
] | null | null | null | driver/filesystem/devfs/devfs.hpp | Edgaru089/helos1 | 8dd27c421bdf1d55e3a62b61927d2f0db6f94d01 | [
"Apache-2.0"
] | null | null | null | driver/filesystem/devfs/devfs.hpp | Edgaru089/helos1 | 8dd27c421bdf1d55e3a62b61927d2f0db6f94d01 | [
"Apache-2.0"
] | null | null | null | #pragma once
#include "../filesystem.hpp"
#include "../../block/blockdevice.hpp"
#include "../../../cppruntime/string.hpp"
#include "../../../cppruntime/vector.hpp"
namespace helos {
namespace filesystem {
// DeviceFilesystem is a folder for mounting block and character devices.
// It is usually mounted to /dev.
class DeviceFilesystem: public Filesystem {
public:
DeviceFilesystem();
~DeviceFilesystem();
virtual const char *GetFilesystemType() override { return "devfs"; }
virtual Capability Capabilities() override { return Capability_NoOpen; }
public:
// OpenFile* file might be NULL.
typedef uintptr_t (*IoctlCallback)(const char *path, void *user, uintptr_t cmd, void *arg, OpenFile *file);
// Mounts a character device at the given name, with only Ioctl() operations.
int MountCharacterIoctl(const char *path, void *user, IoctlCallback ioctl);
// Mounts a block device at the given name.
int MountBlock(const char *path, block::BlockDevice *block);
// Unmounts a device at the given path.
int Umount(const char *path);
public:
virtual int Readdir(const char *path, void *user, Readdir_Callback callback, OpenFile *file) override;
virtual uintptr_t Ioctl(const char *path, uintptr_t cmd, void *arg, OpenFile *file) override;
private:
struct __DeviceFilesystem_Mount {
runtime::String path; // begin with '/'
IoctlCallback ioctl;
void *user;
mode_t type; // Either S_IFCHR or S_IFBLK
};
// Try to mount a new device. Returns negative errno on error.
int __InsertMount(__DeviceFilesystem_Mount *m);
private:
runtime::Vector<__DeviceFilesystem_Mount *> mounts;
};
// The global device filesystem, mounted to /dev
extern DeviceFilesystem *DevFS;
} // namespace filesystem
} // namespace helos
| 29.932203 | 109 | 0.729332 | [
"vector"
] |
145320eb8adb28a0987c9d8846ea540a7e226816 | 12,704 | cpp | C++ | src/net/Net.cpp | mtilgner/another-sidescroller | 5cabeb250a1dd6772a51d29ecd0b3f5ec432ac08 | [
"MIT"
] | null | null | null | src/net/Net.cpp | mtilgner/another-sidescroller | 5cabeb250a1dd6772a51d29ecd0b3f5ec432ac08 | [
"MIT"
] | null | null | null | src/net/Net.cpp | mtilgner/another-sidescroller | 5cabeb250a1dd6772a51d29ecd0b3f5ec432ac08 | [
"MIT"
] | null | null | null | #include <memory>
#include <list>
#include <map>
#include <string.h>
#include <assert.h>
#include <SDL2/SDL_net.h>
//#include <SDL2/SDL.h>
#ifndef MATE_COMPILE
#include "Net.h"
#endif
namespace net
{
static bool was_init = false;
int netinit();
void netquit();
class SocketHolder
{
static SDLNet_SocketSet sockset_;
static size_t maxsockets_;
TCPsocket tcpsocket_;
public:
SocketHolder(TCPsocket sock) : tcpsocket_(sock)
{
if(sockset_)
{
SDLNet_TCP_AddSocket(sockset_, tcpsocket_);
}
else
{
tcpsocket_ = 0;
}
}
~SocketHolder()
{
if(tcpsocket_)
{
if(sockset_)
{
SDLNet_TCP_DelSocket(sockset_, tcpsocket_);
}
SDLNet_TCP_Close(tcpsocket_);
tcpsocket_ = 0;
}
}
TCPsocket tcp_socket() const
{
return tcpsocket_;
}
static int check_sockets(unsigned timeout = 0)
{
if(sockset_)
return SDLNet_CheckSockets(sockset_, timeout);
return 0;
}
static size_t maxsockets()
{
return maxsockets_;
}
static void init(size_t max)
{
maxsockets_ = max;
if(sockset_)
{
SDLNet_FreeSocketSet(sockset_);
sockset_ = 0;
}
sockset_ = SDLNet_AllocSocketSet(maxsockets_);
}
static void quit()
{
SDLNet_FreeSocketSet(sockset_);
}
};
SDLNet_SocketSet SocketHolder::sockset_ = 0;
size_t SocketHolder::maxsockets_ = 0;
void swap_msg(Message& src, Message& dst)
{
dst.from = src.from;
dst.header = src.header;
dst.data.swap(src.data);
}
typedef std::list<Message> MessageList;
static MessageList msglist_;
bool poll_message(Message& msg)
{
if(!msglist_.empty())
{
swap_msg(msglist_.front(), msg);
msglist_.pop_front();
return true;
}
return false;
}
Address conv_addr(IPaddress* ia)
{
Address ad;
int ip = SDLNet_Read32(&ia->host);
ad.a = (ip & 0xff000000) >> 24;
ad.b = (ip & 0xff0000) >> 16;
ad.c = (ip & 0xff00) >> 8;
ad.d = (ip & 0xff);
ad.port = SDLNet_Read16(&ia->port);
return ad;
}
void conv_addr(const Address& ad, IPaddress* ia)
{
int ip = ad.a;
ip = (ip << 8) | ad.b;
ip = (ip << 8) | ad.c;
ip = (ip << 8) | ad.d;
SDLNet_Write32(ip, &ia->host);
SDLNet_Write16(ad.port, &ia->port);
}
const char* to_string(const Address& ad)
{
static char buf[256];
sprintf(buf, "%d.%d.%d.%d:%d",
ad.a, ad.b, ad.c, ad.d, ad.port);
return buf;
}
Address from_string(const char* str)
{
static char buf[256];
static char delim[] = ".:";
char* subs = 0;
Address ad;
strcpy(buf, str);
subs = strtok(buf, delim);
if(subs) ad.a = atoi(subs);
subs = strtok(0, delim);
if(subs) ad.b = atoi(subs);
subs = strtok(0, delim);
if(subs) ad.c = atoi(subs);
subs = strtok(0, delim);
if(subs) ad.d = atoi(subs);
subs = strtok(0, delim);
if(subs) ad.port = atoi(subs);
return ad;
}
// ****************************** tcp ******************************
namespace tcp
{
static State state_ = DISCONNECTED;
int getstate()
{
return state_;
}
// ******************** tcp::MessageBuf ********************
class MessageBuf
{
Message msg_;
char headbuf_[sizeof(MessageHeader)];
unsigned
headerbytes_,
msgbytes_;
void sys_msg(int m)
{
msg_ = Message(m);
headerbytes_ = sizeof(MessageHeader);
msgbytes_ = 0;
}
public:
MessageBuf() : msg_(0), headerbytes_(0), msgbytes_(0)
{
for(char& c : headbuf_) c = 0;
}
bool done() const
{
return sizeof(MessageHeader) == headerbytes_ && msg_.header.size == msgbytes_;
}
bool poll_msg(Message& dst)
{
if(!done()) return false;
swap_msg(msg_, dst);
msg_ = Message();
headerbytes_ = msgbytes_ = 0;
return true;
}
const Message& message() const
{
return msg_;
}
bool receive(TCPsocket sock)
{
if(!done())
{
int r = 0;
if(headerbytes_ < sizeof(MessageHeader))
{
r = SDLNet_TCP_Recv(sock, headbuf_ + headerbytes_, sizeof(MessageHeader) - headerbytes_);
if(r < 0)
{
sys_msg(ERROR);
}
else
{
headerbytes_ += r;
if(sizeof(MessageHeader) == headerbytes_)
{
memcpy(&msg_.header, headbuf_, sizeof(msg_.header));
msg_.data.resize(msg_.header.size);
}
}
}
if(msgbytes_ < msg_.header.size)
{
r = SDLNet_TCP_Recv(sock, &msg_.data[msgbytes_], msg_.header.size - msgbytes_);
if(r < 0)
{
sys_msg(ERROR);
}
else
{
msgbytes_ += r;
}
}
}
return done();
}
};
// ******************** tcp::Socket ********************
class Socket
{
std::unique_ptr<SocketHolder> psock_;
MessageBuf msgbuf_;
public:
bool closed() const
{
return psock_.get() ? false : true;
}
void close()
{
msgbuf_ = MessageBuf();
psock_.reset(0);
}
void accept_connection(const Socket& server)
{
close();
if(server.closed()) return;
TCPsocket remote = 0;
remote = SDLNet_TCP_Accept(server.psock_->tcp_socket());
if(remote)
{
psock_.reset(new SocketHolder(remote));
}
}
void start_server(Uint16 port)
{
close();
IPaddress ip;
ip.host = INADDR_ANY;
SDLNet_Write16(port, &ip.port);
TCPsocket local = SDLNet_TCP_Open(&ip);
if(local)
{
psock_.reset(new SocketHolder(local));
}
}
void connect(const char* ip_addr, Uint16 port)
{
close();
IPaddress ip;
Address ad = from_string(ip_addr);
ad.port = port;
conv_addr(ad, &ip);
TCPsocket local = SDLNet_TCP_Open(&ip);
if(local)
{
psock_.reset(new SocketHolder(local));
}
}
bool has_activity() const
{
if(closed()) return false;
return SDLNet_SocketReady(psock_->tcp_socket()) ? true : false;
}
Address get_address() const
{
static Address ad;
if(!closed())
{
IPaddress* ia = SDLNet_TCP_GetPeerAddress(psock_->tcp_socket());
if(ia)
{
return conv_addr(ia);
}
}
return ad;
}
bool receive()
{
if(closed()) return false;
return msgbuf_.receive(psock_->tcp_socket());
}
bool send(Message& m)
{
if(closed()) return false;
TCPsocket socket = psock_->tcp_socket();
m.header.size = m.data.size();
int result = SDLNet_TCP_Send(socket, &m.header, sizeof(MessageHeader));
if(result < (int) sizeof(MessageHeader))
return false;
if(!m.data.empty())
{
result = SDLNet_TCP_Send(socket, (void*) &m.data.front(), m.data.size());
if(result < (int) m.data.size())
return false;
}
return true;
}
bool poll_msg(Message& dst)
{
if(msgbuf_.poll_msg(dst))
{
if(dst.header.type < 0)
{
close();
}
return true;
}
return false;
}
};
// ******************************
typedef std::vector<Socket> SocketList;
static Socket local_, server_;
static SocketList socketlist_;
// ****************************** tcp functions
void disconnect()
{
local_.close();
server_.close();
for(Socket& s : socketlist_) s.close();
state_ = DISCONNECTED;
}
void disconnect(int client)
{
if(client >= 0 && client < (int) socketlist_.size())
{
socketlist_[client].close();
}
}
int net_abort()
{
disconnect();
return -1;
}
int start_server(Uint16 port)
{
if(-1 == netinit()) return ERROR;
disconnect();
server_.start_server(port);
if(server_.closed()) return ERROR;
state_ = SERVER;
return 0;
}
int start_client(const char* ip_addr, Uint16 port)
{
if(-1 == netinit()) return ERROR;
disconnect();
local_.connect(ip_addr, port);
if(local_.closed()) return ERROR;
state_ = CLIENT;
return 0;
}
void poll_socket(Socket& sock, int num)
{
if(sock.has_activity())
{
if(sock.receive())
{
Message msg;
if(sock.poll_msg(msg))
{
msg.from = num;
msglist_.push_back(msg);
}
}
}
}
int receive()
{
SocketHolder::check_sockets();
if(SERVER == state_)
{
if(server_.has_activity())
{
int i = 0;
for(Socket& s : socketlist_)
{
if(s.closed())
{
s.accept_connection(server_);
if(!s.closed())
{
Message m(CONNECTION_ACCEPTED);
m.from = i;
msglist_.push_back(m);
}
break;
}
++i;
}
}
int i = 0;
for(Socket& s : socketlist_)
{
poll_socket(s, i);
++i;
}
}
else if (CLIENT == state_)
{
poll_socket(local_, 0);
}
return msglist_.size();
}
Address getaddr(int client)
{
if(SERVER == state_)
{
return socketlist_[client].get_address();
}
else if(CLIENT == state_)
{
return local_.get_address();
}
static Address ad;
return ad;
}
int sendmsg(Message& m, int to)
{
if(-1 == netinit()) return ERROR;
if(SERVER == state_)
{
if(to >= 0 && to < (int) socketlist_.size())
{
Socket& s = socketlist_[to];
if(!s.closed())
{
if(s.send(m))
{
return 0;
}
else
{
Message mlost(CONNECTION_LOST);
mlost.from = to;
msglist_.push_back(mlost);
s.close();
}
}
}
}
else if(CLIENT == state_ && 0 == to)
{
if(!local_.closed())
{
if(local_.send(m)) return 0;
}
}
return ERROR;
}
int sendmsg(Message& m)
{
if(-1 == netinit()) return ERROR;
if(SERVER == state_)
{
for(int i = 0; i < MAX_CLIENTS; ++i)
{
Socket& s = socketlist_[i];
if(!s.closed())
{
if(!s.send(m))
{
Message mlost(CONNECTION_LOST);
mlost.from = i;
msglist_.push_back(mlost);
s.close();
}
}
}
return 0;
}
else if(CLIENT == state_)
{
if(!local_.closed())
{
if(local_.send(m))
{
return 0;
}
else
{
Message mlost(CONNECTION_LOST);
mlost.from = 0;
msglist_.push_back(mlost);
local_.close();
}
}
}
return ERROR;
}
bool is_connected(int num)
{
if(SERVER == state_)
{
if(num >= 0 && num < (int) socketlist_.size())
{
return !socketlist_[num].closed();
}
return false;
}
else if(CLIENT == state_ && 0 == num)
{
return true;
}
return false;
}
} // namespace tcp
int netinit()
{
if(!was_init)
{
if(-1 == SDLNet_Init())
{
return -1;
}
SocketHolder::init(MAX_CLIENTS + 3);
tcp::socketlist_.resize(MAX_CLIENTS);
atexit(netquit);
was_init = true;
}
return 0;
}
void netquit()
{
// disconnect();
tcp::local_.close();
tcp::server_.close();
for(tcp::Socket& s : tcp::socketlist_)
s.close();
SocketHolder::quit();
SDLNet_Quit();
was_init = false;
}
} // namespace network
| 18.932936 | 105 | 0.476464 | [
"vector"
] |
145907a5655449920571932bf5f482e4fef23282 | 8,559 | cpp | C++ | samples/snippets/cpp/VS_Snippets_Winforms/System.Drawing.Drawing2D.ClassicPathGradientBrush/CPP/form1.cpp | hamarb123/dotnet-api-docs | 6aeb55784944a2f1f5e773b657791cbd73a92dd4 | [
"CC-BY-4.0",
"MIT"
] | 421 | 2018-04-01T01:57:50.000Z | 2022-03-28T15:24:42.000Z | samples/snippets/cpp/VS_Snippets_Winforms/System.Drawing.Drawing2D.ClassicPathGradientBrush/CPP/form1.cpp | hamarb123/dotnet-api-docs | 6aeb55784944a2f1f5e773b657791cbd73a92dd4 | [
"CC-BY-4.0",
"MIT"
] | 5,797 | 2018-04-02T21:12:23.000Z | 2022-03-31T23:54:38.000Z | samples/snippets/cpp/VS_Snippets_Winforms/System.Drawing.Drawing2D.ClassicPathGradientBrush/CPP/form1.cpp | hamarb123/dotnet-api-docs | 6aeb55784944a2f1f5e773b657791cbd73a92dd4 | [
"CC-BY-4.0",
"MIT"
] | 1,482 | 2018-03-31T11:26:20.000Z | 2022-03-30T22:36:45.000Z | #using <System.Data.dll>
#using <System.dll>
#using <System.Drawing.dll>
#using <System.Windows.Forms.dll>
using namespace System;
using namespace System::Drawing;
using namespace System::Drawing::Drawing2D;
using namespace System::Collections;
using namespace System::ComponentModel;
using namespace System::Windows::Forms;
using namespace System::Data;
/// <summary>
/// Summary description for Form1.
/// </summary>
public ref class Form1: public System::Windows::Forms::Form
{
private:
/// <summary>
/// Required designer variable.
/// </summary>
System::ComponentModel::Container^ components;
public:
Form1()
{
//
// Required for Windows Form Designer support
//
InitializeComponent();
//
// TODO: Add any constructor code after InitializeComponent call
//
}
protected:
/// <summary>
/// Clean up any resources being used.
/// </summary>
~Form1()
{
if ( components != nullptr )
{
delete components;
}
}
private:
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
void InitializeComponent()
{
this->components = gcnew System::ComponentModel::Container;
this->Size = System::Drawing::Size( 300, 300 );
this->Text = "Form1";
}
// Snippet for: M:System.Drawing.Drawing2D.PathGradientBrush.MultiplyTransform(System.Drawing.Drawing2D.Matrix,System.Drawing.Drawing2D.MatrixOrder)
// <snippet1>
public:
void MultiplyTransformExample( PaintEventArgs^ e )
{
// Create a graphics path and add an rectangle.
GraphicsPath^ myPath = gcnew GraphicsPath;
Rectangle rect = Rectangle(20,20,100,50);
myPath->AddRectangle( rect );
// Get the path's array of points.
array<PointF>^myPathPointArray = myPath->PathPoints;
// Create a path gradient brush.
PathGradientBrush^ myPGBrush = gcnew PathGradientBrush( myPathPointArray );
// Set the color span.
myPGBrush->CenterColor = Color::Red;
array<Color>^ mySurroundColor = {Color::Blue};
myPGBrush->SurroundColors = mySurroundColor;
// Draw the brush to the screen prior to transformation.
e->Graphics->FillRectangle( myPGBrush, 10, 10, 200, 200 );
// Create a new matrix that rotates by 90 degrees, and
// translates by 100 in each direction.
Matrix^ myMatrix = gcnew Matrix( 0,1,-1,0,100,100 );
// Apply the transform to the brush.
myPGBrush->MultiplyTransform( myMatrix, MatrixOrder::Append );
// Draw the brush to the screen again after applying the
// transform.
e->Graphics->FillRectangle( myPGBrush, 10, 10, 200, 300 );
}
// </snippet1>
// Snippet for: M:System.Drawing.Drawing2D.PathGradientBrush.RotateTransform(System.Single,System.Drawing.Drawing2D.MatrixOrder)
// <snippet2>
public:
void RotateTransformExample( PaintEventArgs^ e )
{
// Create a graphics path and add an ellipse.
GraphicsPath^ myPath = gcnew GraphicsPath;
Rectangle rect = Rectangle(100,20,100,50);
myPath->AddRectangle( rect );
// Get the path's array of points.
array<PointF>^myPathPointArray = myPath->PathPoints;
// Create a path gradient brush.
PathGradientBrush^ myPGBrush = gcnew PathGradientBrush( myPathPointArray );
// Set the color span.
myPGBrush->CenterColor = Color::Red;
array<Color>^ mySurroundColor = {Color::Blue};
myPGBrush->SurroundColors = mySurroundColor;
// Draw the brush to the screen prior to transformation.
e->Graphics->FillRectangle( myPGBrush, 10, 10, 200, 200 );
// Apply the rotate transform to the brush.
myPGBrush->RotateTransform( 45, MatrixOrder::Append );
// Draw the brush to the screen again after applying the
// transform.
e->Graphics->FillRectangle( myPGBrush, 10, 10, 200, 300 );
}
// </snippet2>
// Snippet for: M:System.Drawing.Drawing2D.PathGradientBrush.ScaleTransform(System.Single,System.Single,System.Drawing.Drawing2D.MatrixOrder)
// <snippet3>
public:
void ScaleTransformExample( PaintEventArgs^ e )
{
// Create a graphics path and add a rectangle.
GraphicsPath^ myPath = gcnew GraphicsPath;
Rectangle rect = Rectangle(100,20,100,50);
myPath->AddRectangle( rect );
// Get the path's array of points.
array<PointF>^myPathPointArray = myPath->PathPoints;
// Create a path gradient brush.
PathGradientBrush^ myPGBrush = gcnew PathGradientBrush( myPathPointArray );
// Set the color span.
myPGBrush->CenterColor = Color::Red;
array<Color>^ mySurroundColor = {Color::Blue};
myPGBrush->SurroundColors = mySurroundColor;
// Draw the brush to the screen prior to transformation.
e->Graphics->FillRectangle( myPGBrush, 10, 10, 200, 200 );
// Scale by a factor of 2 in the x-axis by applying the scale
// transform to the brush.
myPGBrush->ScaleTransform( 2, 1, MatrixOrder::Append );
// Move the brush down by 100 by Applying the translate
// transform to the brush.
myPGBrush->TranslateTransform( -100, 100, MatrixOrder::Append );
// Draw the brush to the screen again after applying the
// transforms.
e->Graphics->FillRectangle( myPGBrush, 10, 10, 300, 300 );
}
// </snippet3>
// Snippet for: M:System.Drawing.Drawing2D.PathGradientBrush.SetBlendTriangularShape(System.Single,System.Single)
// <snippet4>
public:
void SetBlendTriangularShapeExample( PaintEventArgs^ e )
{
// Create a graphics path and add a rectangle.
GraphicsPath^ myPath = gcnew GraphicsPath;
Rectangle rect = Rectangle(100,20,100,50);
myPath->AddRectangle( rect );
// Get the path's array of points.
array<PointF>^myPathPointArray = myPath->PathPoints;
// Create a path gradient brush.
PathGradientBrush^ myPGBrush = gcnew PathGradientBrush( myPathPointArray );
// Set the color span.
myPGBrush->CenterColor = Color::Red;
array<Color>^ mySurroundColor = {Color::Blue};
myPGBrush->SurroundColors = mySurroundColor;
// Draw the brush to the screen prior to the blend.
e->Graphics->FillRectangle( myPGBrush, 10, 10, 200, 200 );
// Set the Blend factors.
myPGBrush->SetBlendTriangularShape( 0.5f, 1.0f );
// Move the brush down by 100 by Applying the translate
// transform to the brush.
myPGBrush->TranslateTransform( 0, 100, MatrixOrder::Append );
// Draw the brush to the screen again after applying the
// transforms.
e->Graphics->FillRectangle( myPGBrush, 10, 10, 300, 300 );
}
// </snippet4>
// Snippet for: M:System.Drawing.Drawing2D.PathGradientBrush.SetSigmaBellShape(System.Single,System.Single)
// <snippet5>
public:
void SetSigmaBellShapeExample( PaintEventArgs^ e )
{
// Create a graphics path and add a rectangle.
GraphicsPath^ myPath = gcnew GraphicsPath;
Rectangle rect = Rectangle(100,20,100,50);
myPath->AddRectangle( rect );
// Get the path's array of points.
array<PointF>^myPathPointArray = myPath->PathPoints;
// Create a path gradient brush.
PathGradientBrush^ myPGBrush = gcnew PathGradientBrush( myPathPointArray );
// Set the color span.
myPGBrush->CenterColor = Color::Red;
array<Color>^ mySurroundColor = {Color::Blue};
myPGBrush->SurroundColors = mySurroundColor;
// Draw the brush to the screen prior to blend.
e->Graphics->FillRectangle( myPGBrush, 10, 10, 200, 200 );
// Set the Blend factors and transform the brush.
myPGBrush->SetSigmaBellShape( 0.5f, 1.0f );
// Move the brush down by 100 by applying the translate
// transform to the brush.
myPGBrush->TranslateTransform( 0, 100, MatrixOrder::Append );
// Draw the brush to the screen again after setting the
// blend and applying the transform.
e->Graphics->FillRectangle( myPGBrush, 10, 10, 300, 300 );
}
// </snippet5>
};
/// <summary>
/// The main entry point for the application.
/// </summary>
[STAThread]
int main()
{
Application::Run( gcnew Form1 );
}
| 33.303502 | 152 | 0.647038 | [
"transform"
] |
1465bc9ed7de54a90e4cadf15beb3b43c212064f | 43,239 | cc | C++ | media/video/ffmpeg_video_decode_engine.cc | meego-tablet-ux/meego-app-browser | 0f4ef17bd4b399c9c990a2f6ca939099495c2b9c | [
"BSD-3-Clause"
] | 1 | 2015-10-12T09:14:22.000Z | 2015-10-12T09:14:22.000Z | media/video/ffmpeg_video_decode_engine.cc | meego-tablet-ux/meego-app-browser | 0f4ef17bd4b399c9c990a2f6ca939099495c2b9c | [
"BSD-3-Clause"
] | null | null | null | media/video/ffmpeg_video_decode_engine.cc | meego-tablet-ux/meego-app-browser | 0f4ef17bd4b399c9c990a2f6ca939099495c2b9c | [
"BSD-3-Clause"
] | 1 | 2020-11-04T07:22:28.000Z | 2020-11-04T07:22:28.000Z | // Copyright (c) 2011 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "media/video/ffmpeg_video_decode_engine.h"
#include "base/command_line.h"
#include "base/string_number_conversions.h"
#include "base/task.h"
#include "media/base/buffers.h"
#include "media/base/callback.h"
#include "media/base/limits.h"
#include "media/base/media_switches.h"
#include "media/base/pipeline.h"
#include "media/ffmpeg/ffmpeg_common.h"
#include "media/filters/ffmpeg_demuxer.h"
#include "media/video/ffmpeg_video_allocator.h"
#if defined (TOOLKIT_MEEGOTOUCH)
/*
_DEV2_OPT_
*/
#include <sys/syscall.h>
#include <sys/shm.h>
/*XA_WINDOW*/
#include <X11/X.h>
/*us*/
double GetTick(void)
{
struct timeval tv;
if (gettimeofday(&tv, NULL))
return 0;
return tv.tv_usec+tv.tv_sec*1000000.0;
}
Display *mDisplay = NULL;
unsigned int CodecID = 0;
#endif
namespace media {
#if defined (TOOLKIT_MEEGOTOUCH)
// _DEV2_H264_
#ifdef _DEV2_DEBUG_
struct VappiEqualizer {
VADisplayAttribute brightness;
VADisplayAttribute contrast;
VADisplayAttribute hue;
VADisplayAttribute saturation;
};
static VAImageFormat *hw_image_formats_;
static int hw_num_image_formats_;
static int hw_num_profiles_;
static int hw_num_entrypoints_;
static VAEntrypoint *hw_entrypoints_;
static VAImageFormat *hw_subpic_formats_;
static unsigned int *hw_subpic_flags_;
static int hw_num_subpic_formats_;
static struct VappiEqualizer hw_equalizer_;
static VAProfile *hw_profiles_;
#endif
#endif
FFmpegVideoDecodeEngine::FFmpegVideoDecodeEngine()
: codec_context_(NULL),
event_handler_(NULL),
frame_rate_numerator_(0),
frame_rate_denominator_(0),
direct_rendering_(false),
pending_input_buffers_(0),
pending_output_buffers_(0),
output_eos_reached_(false),
flush_pending_(false) {
}
FFmpegVideoDecodeEngine::~FFmpegVideoDecodeEngine() {
if (codec_context_) {
av_free(codec_context_->extradata);
avcodec_close(codec_context_);
av_free(codec_context_);
}
}
void FFmpegVideoDecodeEngine::Initialize(
MessageLoop* message_loop,
VideoDecodeEngine::EventHandler* event_handler,
VideoDecodeContext* context,
const VideoCodecConfig& config) {
allocator_.reset(new FFmpegVideoAllocator());
// Always try to use three threads for video decoding. There is little reason
// not to since current day CPUs tend to be multi-core and we measured
// performance benefits on older machines such as P4s with hyperthreading.
//
// Handling decoding on separate threads also frees up the pipeline thread to
// continue processing. Although it'd be nice to have the option of a single
// decoding thread, FFmpeg treats having one thread the same as having zero
// threads (i.e., avcodec_decode_video() will execute on the calling thread).
// Yet another reason for having two threads :)
static const int kDecodeThreads = 2;
static const int kMaxDecodeThreads = 16;
// Initialize AVCodecContext structure.
codec_context_ = avcodec_alloc_context();
// TODO(scherkus): should video format get passed in via VideoCodecConfig?
codec_context_->pix_fmt = PIX_FMT_YUV420P;
codec_context_->codec_type = AVMEDIA_TYPE_VIDEO;
codec_context_->codec_id = VideoCodecToCodecID(config.codec());
codec_context_->coded_width = config.width();
codec_context_->coded_height = config.height();
frame_rate_numerator_ = config.frame_rate_numerator();
frame_rate_denominator_ = config.frame_rate_denominator();
if (config.extra_data() != NULL) {
codec_context_->extradata_size = config.extra_data_size();
codec_context_->extradata =
reinterpret_cast<uint8_t*>(av_malloc(config.extra_data_size()));
memcpy(codec_context_->extradata, config.extra_data(),
config.extra_data_size());
}
// Enable motion vector search (potentially slow), strong deblocking filter
// for damaged macroblocks, and set our error detection sensitivity.
codec_context_->error_concealment = FF_EC_GUESS_MVS | FF_EC_DEBLOCK;
codec_context_->error_recognition = FF_ER_CAREFUL;
AVCodec* codec = avcodec_find_decoder(codec_context_->codec_id);
if (codec) {
#ifdef FF_THREAD_FRAME // Only defined in FFMPEG-MT.
direct_rendering_ = codec->capabilities & CODEC_CAP_DR1 ? true : false;
#endif
#if defined (TOOLKIT_MEEGOTOUCH)
/*disable direct_rendering for H264.*/
/*because Chromium Media Engine only support YV12, and YV16 format.*/
/*add */
CodecID = codec_context_->codec_id;
/*FIXME : To Benchmark here for further optmization*/
// _DEV2_H264_
if((codec_context_->codec_id == CODEC_ID_H264) ){
int ret = -1;
/*Serveral things do here:
a> do InitializeHwEngine
b> reset GetFormatAndConfig function.
c> pass vaapi_ctx to codec internal.
*/
DEV2_TRACE();
ret = InitializeHwEngine();
if(0 == ret){
//if(0 ){ force sw decoding
/*support VAAPI Hw acceleration*/
/*pass hw_context to codec internal.*/
codec_context_->hwaccel_context = hw_context_;
/*reset GetFormatAndConfig to enable hw accelerated*/
codec_context_->get_format = GetFormatAndConfig;
codec_context_->thread_count = 1;
codec_context_->slice_flags = SLICE_FLAG_CODED_ORDER|SLICE_FLAG_ALLOW_FIELD;
codec_context_->get_buffer = GetBufferAndSurface;
codec_context_->reget_buffer = GetBufferAndSurface;
codec_context_->release_buffer = ReleaseBufferAndSurface;
codec_context_->context_model = (int)this;
//VA_RT_FORMAT_YUV420;
hw_accel_ = 1;
direct_rendering_ = 0;
//DLOG(INFO) << "disable direct rendering for H264 codec";
}else{
if(mDisplay){
XCloseDisplay(mDisplay);
mDisplay = NULL;
}
/* we are not support sw H264 decoding*/
codec = NULL;
LOG(ERROR) << "No H264 Support on this platform" ;
}
}
#endif
if (direct_rendering_) {
DVLOG(1) << "direct rendering is used";
allocator_->Initialize(codec_context_, GetSurfaceFormat());
}
}
// TODO(fbarchard): Improve thread logic based on size / codec.
// TODO(fbarchard): Fix bug affecting video-cookie.html
int decode_threads = (codec_context_->codec_id == CODEC_ID_THEORA) ?
1 : kDecodeThreads;
const CommandLine* cmd_line = CommandLine::ForCurrentProcess();
std::string threads(cmd_line->GetSwitchValueASCII(switches::kVideoThreads));
if ((!threads.empty() &&
!base::StringToInt(threads, &decode_threads)) ||
decode_threads < 0 || decode_threads > kMaxDecodeThreads) {
decode_threads = kDecodeThreads;
}
#if defined (TOOLKIT_MEEGOTOUCH)
{
if((CODEC_ID_H264 == codec_context_->codec_id) && hw_accel_){
decode_threads = 1;
}
}
#endif
// We don't allocate AVFrame on the stack since different versions of FFmpeg
// may change the size of AVFrame, causing stack corruption. The solution is
// to let FFmpeg allocate the structure via avcodec_alloc_frame().
av_frame_.reset(avcodec_alloc_frame());
VideoCodecInfo info;
info.success = false;
info.provides_buffers = true;
info.stream_info.surface_type = VideoFrame::TYPE_SYSTEM_MEMORY;
info.stream_info.surface_format = GetSurfaceFormat();
info.stream_info.surface_width = config.width();
info.stream_info.surface_height = config.height();
// If we do not have enough buffers, we will report error too.
bool buffer_allocated = true;
frame_queue_available_.clear();
if (!direct_rendering_) {
// Create output buffer pool when direct rendering is not used.
for (size_t i = 0; i < Limits::kMaxVideoFrames; ++i) {
scoped_refptr<VideoFrame> video_frame;
VideoFrame::CreateFrame(VideoFrame::YV12,
config.width(),
config.height(),
kNoTimestamp,
kNoTimestamp,
&video_frame);
if (!video_frame.get()) {
buffer_allocated = false;
break;
}
frame_queue_available_.push_back(video_frame);
}
}
if (codec &&
avcodec_thread_init(codec_context_, decode_threads) >= 0 &&
avcodec_open(codec_context_, codec) >= 0 &&
av_frame_.get() &&
buffer_allocated) {
info.success = true;
}
event_handler_ = event_handler;
event_handler_->OnInitializeComplete(info);
}
#if defined (TOOLKIT_MEEGOTOUCH)
// _DEV2_H264_
int FFmpegVideoDecodeEngine::CheckStatus(VAStatus status, const char *msg)
{
if (status != VA_STATUS_SUCCESS) {
LOG(ERROR) << " " << msg << vaErrorStr(status);
return 1;
}
return 0;
}
#if 1
/*optimize Output to pixmap with VAAPI*/
int FFmpegVideoDecodeEngine::CopyBufferFrmSurface(scoped_refptr<VideoFrame> video_frame,
const AVFrame* frame)
{
int ret = 0;
VAStatus status;
VASurfaceID surface_id = (VASurfaceID)frame->data[3];
DEV2_TRACE();
#if 0
/* return Surface to Render Engine */
video_frame->data_[0] = (uint8_t*)mDisplay; /*VaapiSurface, structure*/
//video_frame->data_[0] = frame->data[0]; /*VaapiSurface, structure*/
video_frame->data_[1] = frame->data[1]; /*Reserved*/
video_frame->data_[2] = frame->data[2]; /*Reserved*/
video_frame->idx_ = (int)frame->data[3]; /*Surface Id*/
/*video_frame->data_[1]: reserved to check in render engine for only FFMPEG/LIBVA */
video_frame->data_[1] = (uint8_t*)0x264;
/*hw_context*/
video_frame->data_[2] = (uint8_t*)hw_context_->display;
#endif
if(video_frame->data_[1]){
VA_Buffer *pVaBuf = (VA_Buffer*)video_frame->data_[1];
pVaBuf->mDisplay = (uint8_t*)mDisplay; /*display handler*/
pVaBuf->IsH264 = 0x264;
pVaBuf->hwDisplay = (uint8_t*)hw_context_->display;
video_frame->idx_ = (int)frame->data[3]; /*Surface Id*/
}
return ret;
}
#else
int FFmpegVideoDecodeEngine::CopyBufferFrmSurface(scoped_refptr<VideoFrame> video_frame,
const AVFrame* frame)
{
struct VaapiSurface *surface = (VaapiSurface *)frame->data[0];
VASurfaceID surface_id = (uintptr_t)frame->data[3];
VAStatus status;
VAImage va_image;
uint8_t *image_data = NULL;
DEV2_TRACE();
status = vaDeriveImage(hw_context_->display, surface_id, &va_image);
if(status != VA_STATUS_SUCCESS){
DEV2_TRACE();
LOG(INFO) << "vaDeriveImage called error";
return -1;
}
status = vaMapBuffer(hw_context_->display, va_image.buf,
(void **)&image_data);
if(status != VA_STATUS_SUCCESS){
DEV2_TRACE();
LOG(INFO) << "vaMapBuffer called error";
return -1;
}
#if 0
LOG(INFO) << "surface : " << surface << "\n" << "surface id : "<< surface_id;
LOG(INFO) << "pitches.0: "<< va_image.pitches[0];
LOG(INFO) << "pitches.1: "<< va_image.pitches[1];
LOG(INFO) << "pitches.2: "<< va_image.pitches[2];
LOG(INFO) << "offsets.0: "<< va_image.offsets[0];
LOG(INFO) << "offsets.1: "<< va_image.offsets[1];
LOG(INFO) << "offsets.2: "<< va_image.offsets[2];
LOG(INFO) << "buf id : "<< va_image.buf;
LOG(INFO) << "buf addr : "<< (int)image_data;
LOG(INFO) << "width : "<< va_image.width;
LOG(INFO) << "height : "<< va_image.height;
LOG(INFO)<< "format : "<< va_image.format.fourcc;
LOG(INFO)<< "NV12 : "<< VA_FOURCC('N','V','1','2');
LOG(INFO)<< "YV12 : "<< VA_FOURCC('Y','V','1','2');
LOG(INFO)<< "YV16 : "<< VA_FOURCC('Y','V','1','6');
LOG(INFO)<< "I420 : "<< VA_FOURCC('I','4','2','0');
LOG(INFO)<< "IYUV : "<< VA_FOURCC('I','Y','U','V');
#endif
/*simulate what a I420 layer-out.*/
/*because hw supports NV12 formats:*/
/*need copy and re-assignment.*/
uint8_t *psrcY = image_data;
uint8_t *psrcU = image_data + va_image.offsets[1];
uint8_t *psrcV = image_data + va_image.offsets[1] + 1;
uint8_t *pdestY = video_frame->data_[0];
uint8_t *pdestU = video_frame->data_[1];
uint8_t *pdestV = video_frame->data_[2];
int i = 0;
int j = 0;
int height = video_frame->height();
int width = video_frame->width();
#if 0
LOG(INFO) << "pSrcY " << (int)psrcY;
LOG(INFO) << "pSrcU " << (int)psrcU;
LOG(INFO) << "pSrcV " << (int)psrcV;
LOG (INFO) << "render surface ID " << frame->linesize[3];
{
/*dump va_image to file, only for testing.*/
static FILE* pfile = NULL;
pfile = fopen("d1.yuv", "ab");
uint8_t *pY = psrcY;
uint8_t *pU = psrcU;
uint8_t *pV = psrcV;
int ii , jj ;
/*Y*/
for(ii = 0; ii < va_image.height; ii ++){
fwrite (pY, 1, va_image.width, pfile);
pY += va_image.pitches[0];
}
/*U*/
for(ii = 0; ii < (va_image.height>>1); ii ++){
for(jj = 0; jj < (va_image.width); jj+=2){
fwrite (pU + jj, 1, 1 , pfile);
}
pU += va_image.pitches[1];
}
/*V*/
for(ii = 0; ii < (va_image.height>>1); ii ++){
for(jj = 0; jj < (va_image.width); jj+=2){
fwrite (pV + jj, 1, 1 , pfile);
}
pV += va_image.pitches[1];
}
fclose(pfile);
}
#endif
video_frame->idx_ = frame->linesize[3];
//LOG(INFO) << "Part Copy: Green";
/*Y*/
for(i = 0 ; i < height; i ++){
//for(i = 0 ; i < va_image.height; i ++){
memcpy(pdestY, psrcY, width);
pdestY += video_frame->strides_[0];
psrcY += va_image.pitches[0];
}
/*UV*/
for(i = 0 ; i < (height>>1); i ++){
/*one row of UV is copyed.*/
for(j = 0; j < (width); j +=2){
*(pdestU + (j>>1)) = *(psrcU + j);
*(pdestV + (j>>1)) = *(psrcV + j);
}
psrcU += va_image.pitches[0];
psrcV += va_image.pitches[0];
pdestV += video_frame->strides_[1];
pdestU += video_frame->strides_[1];
}
status = vaUnmapBuffer(hw_context_->display, va_image.buf);
if(CheckStatus(status, "vaUnmapBuffer is failed")){
DEV2_TRACE();
return -1;
}
status = vaDestroyImage(hw_context_->display, va_image.image_id);
if(CheckStatus(status, "vaDestroyImage is failed ")){
DEV2_TRACE();
return -1;
}
return 0;
}
#endif
#endif /*MEEGO TOUCH*/
static void CopyPlane(size_t plane,
scoped_refptr<VideoFrame> video_frame,
const AVFrame* frame,
size_t source_height) {
DCHECK_EQ(video_frame->width() % 2, 0u);
const uint8* source = frame->data[plane];
const size_t source_stride = frame->linesize[plane];
uint8* dest = video_frame->data(plane);
const size_t dest_stride = video_frame->stride(plane);
// Calculate amounts to copy and clamp to minium frame dimensions.
size_t bytes_per_line = video_frame->width();
size_t copy_lines = std::min(video_frame->height(), source_height);
if (plane != VideoFrame::kYPlane) {
bytes_per_line /= 2;
if (video_frame->format() == VideoFrame::YV12) {
copy_lines = (copy_lines + 1) / 2;
}
}
bytes_per_line = std::min(bytes_per_line, source_stride);
// Copy!
for (size_t i = 0; i < copy_lines; ++i) {
memcpy(dest, source, bytes_per_line);
source += source_stride;
dest += dest_stride;
}
}
void FFmpegVideoDecodeEngine::ConsumeVideoSample(
scoped_refptr<Buffer> buffer) {
pending_input_buffers_--;
if (flush_pending_) {
TryToFinishPendingFlush();
} else {
// Otherwise try to decode this buffer.
DecodeFrame(buffer);
}
}
void FFmpegVideoDecodeEngine::ProduceVideoFrame(
scoped_refptr<VideoFrame> frame) {
// We should never receive NULL frame or EOS frame.
DCHECK(frame.get() && !frame->IsEndOfStream());
// Increment pending output buffer count.
pending_output_buffers_++;
// Return this frame to available pool or allocator after display.
if (direct_rendering_)
allocator_->DisplayDone(codec_context_, frame);
else
frame_queue_available_.push_back(frame);
if (flush_pending_) {
TryToFinishPendingFlush();
} else if (!output_eos_reached_) {
// If we already deliver EOS to renderer, we stop reading new input.
ReadInput();
}
}
// Try to decode frame when both input and output are ready.
void FFmpegVideoDecodeEngine::DecodeFrame(scoped_refptr<Buffer> buffer) {
scoped_refptr<VideoFrame> video_frame;
// Create a packet for input data.
// Due to FFmpeg API changes we no longer have const read-only pointers.
AVPacket packet;
av_init_packet(&packet);
packet.data = const_cast<uint8*>(buffer->GetData());
packet.size = buffer->GetDataSize();
PipelineStatistics statistics;
statistics.video_bytes_decoded = buffer->GetDataSize();
// Let FFmpeg handle presentation timestamp reordering.
codec_context_->reordered_opaque = buffer->GetTimestamp().InMicroseconds();
// This is for codecs not using get_buffer to initialize
// |av_frame_->reordered_opaque|
av_frame_->reordered_opaque = codec_context_->reordered_opaque;
int frame_decoded = 0;
int result = avcodec_decode_video2(codec_context_,
av_frame_.get(),
&frame_decoded,
&packet);
#if defined (TOOLKIT_MEEGOTOUCH)
av_frame_->reordered_opaque = codec_context_->reordered_opaque;
#endif
// Log the problem if we can't decode a video frame and exit early.
if (result < 0) {
VLOG(1) << "Error decoding a video frame with timestamp: "
<< buffer->GetTimestamp().InMicroseconds() << " us, duration: "
<< buffer->GetDuration().InMicroseconds() << " us, packet size: "
<< buffer->GetDataSize() << " bytes";
// TODO(jiesun): call event_handler_->OnError() instead.
#if defined (TOOLKIT_MEEGOTOUCH)
if((CODEC_ID_H264 == codec_context_->codec_id) && hw_accel_){
return;
}
#endif
event_handler_->ConsumeVideoFrame(video_frame, statistics);
return;
}
// If frame_decoded == 0, then no frame was produced.
// In this case, if we already begin to flush codec with empty
// input packet at the end of input stream, the first time we
// encounter frame_decoded == 0 signal output frame had been
// drained, we mark the flag. Otherwise we read from demuxer again.
if (frame_decoded == 0) {
if (buffer->IsEndOfStream()) { // We had started flushing.
LOG(ERROR) << "End Of Stream Event";
#if 0//defined (TOOLKIT_MEEGOTOUCH)
// _DEV2_H264_
event_handler_->ConsumeVideoFrame(video_frame, statistics);
#else
event_handler_->ConsumeVideoFrame(video_frame, statistics);
#endif
output_eos_reached_ = true;
} else {
LOG(ERROR) << "Loading Again.";
ReadInput();
}
LOG(INFO) << " ";
return;
}
#if defined (TOOLKIT_MEEGOTOUCH)
// _DEV2_H264_
/*force to exit for performance evaluation*/
if(!hw_accel_){
/*run here only for no hw accelerated codec*/
#endif
// TODO(fbarchard): Work around for FFmpeg http://crbug.com/27675
// The decoder is in a bad state and not decoding correctly.
// Checking for NULL avoids a crash in CopyPlane().
if (!av_frame_->data[VideoFrame::kYPlane] ||
!av_frame_->data[VideoFrame::kUPlane] ||
!av_frame_->data[VideoFrame::kVPlane]) {
// TODO(jiesun): call event_handler_->OnError() instead.
event_handler_->ConsumeVideoFrame(video_frame, statistics);
return;
}
#if defined (TOOLKIT_MEEGOTOUCH)
// _DEV2_H264_
}
#endif
// Determine timestamp and calculate the duration based on the repeat picture
// count. According to FFmpeg docs, the total duration can be calculated as
// follows:
// fps = 1 / time_base
//
// duration = (1 / fps) + (repeat_pict) / (2 * fps)
// = (2 + repeat_pict) / (2 * fps)
// = (2 + repeat_pict) / (2 * (1 / time_base))
DCHECK_LE(av_frame_->repeat_pict, 2); // Sanity check.
AVRational doubled_time_base;
doubled_time_base.num = frame_rate_denominator_;
doubled_time_base.den = frame_rate_numerator_ * 2;
base::TimeDelta timestamp =
base::TimeDelta::FromMicroseconds(av_frame_->reordered_opaque);
base::TimeDelta duration =
ConvertFromTimeBase(doubled_time_base, 2 + av_frame_->repeat_pict);
if (!direct_rendering_) {
// Available frame is guaranteed, because we issue as much reads as
// available frame, except the case of |frame_decoded| == 0, which
// implies decoder order delay, and force us to read more inputs.
DCHECK(frame_queue_available_.size());
video_frame = frame_queue_available_.front();
frame_queue_available_.pop_front();
#if defined (TOOLKIT_MEEGOTOUCH)
// _DEV2_H264_
//LOG(INFO) << "not Direct rendering: format : "<< video_frame->format() << " surface idx_: " << av_frame_.get()->linesize[3];
if((CODEC_ID_H264 == codec_context_->codec_id) && hw_accel_){
CopyBufferFrmSurface(video_frame.get(), av_frame_.get());
}else
#endif
{
// Copy the frame data since FFmpeg reuses internal buffers for AVFrame
// output, meaning the data is only valid until the next
// avcodec_decode_video() call.
size_t height = codec_context_->height;
CopyPlane(VideoFrame::kYPlane, video_frame.get(), av_frame_.get(), height);
CopyPlane(VideoFrame::kUPlane, video_frame.get(), av_frame_.get(), height);
CopyPlane(VideoFrame::kVPlane, video_frame.get(), av_frame_.get(), height);
}
} else {
// Get the VideoFrame from allocator which associate with av_frame_.
video_frame = allocator_->DecodeDone(codec_context_, av_frame_.get());
#if defined (TOOLKIT_MEEGOTOUCH)
// _DEV2_H264_
if((CODEC_ID_H264 == codec_context_->codec_id) && hw_accel_){
/* direct rendering , no memory copy, theoretically, maybe cause playing jittering,
* because current buffer management is only simple 21-buf FIFO, it may
* cause buffer data dirty if previous frame buffer is still holded
* by rendering process
* low propability case.
*/
/*get pointers from VAAPI surface*/
}
#endif
}
video_frame->SetTimestamp(timestamp);
video_frame->SetDuration(duration);
pending_output_buffers_--;
event_handler_->ConsumeVideoFrame(video_frame, statistics);
}
void FFmpegVideoDecodeEngine::Uninitialize() {
#if defined (TOOLKIT_MEEGOTOUCH)
// _DEV2_H264_
if((codec_context_->codec_id == CODEC_ID_H264) && hw_accel_)
{
/*FREE what VAAPI allcoate*/
UnInitializeHwEngine();
hw_accel_ = 0;
codec_context_->codec_id = CODEC_ID_NONE ;
}
/* LOGERR << syscall(__NR_gettid));*/
if(mDisplay){
XCloseDisplay(mDisplay);
mDisplay = NULL;
}
#endif
if (direct_rendering_) {
allocator_->Stop(codec_context_);
}
event_handler_->OnUninitializeComplete();
}
void FFmpegVideoDecodeEngine::Flush() {
avcodec_flush_buffers(codec_context_);
flush_pending_ = true;
TryToFinishPendingFlush();
}
void FFmpegVideoDecodeEngine::TryToFinishPendingFlush() {
DCHECK(flush_pending_);
// We consider ourself flushed when there is no pending input buffers
// and output buffers, which implies that all buffers had been returned
// to its owner.
if (!pending_input_buffers_ && !pending_output_buffers_) {
// Try to finish flushing and notify pipeline.
flush_pending_ = false;
event_handler_->OnFlushComplete();
}
}
void FFmpegVideoDecodeEngine::Seek() {
// After a seek, output stream no longer considered as EOS.
output_eos_reached_ = false;
// The buffer provider is assumed to perform pre-roll operation.
for (unsigned int i = 0; i < Limits::kMaxVideoFrames; ++i)
ReadInput();
event_handler_->OnSeekComplete();
}
void FFmpegVideoDecodeEngine::ReadInput() {
DCHECK_EQ(output_eos_reached_, false);
pending_input_buffers_++;
event_handler_->ProduceVideoSample(NULL);
}
VideoFrame::Format FFmpegVideoDecodeEngine::GetSurfaceFormat() const {
// J (Motion JPEG) versions of YUV are full range 0..255.
// Regular (MPEG) YUV is 16..240.
// For now we will ignore the distinction and treat them the same.
switch (codec_context_->pix_fmt) {
case PIX_FMT_YUV420P:
case PIX_FMT_YUVJ420P:
LOG(INFO) << "Supported Format : "<< codec_context_->pix_fmt;
return VideoFrame::YV12;
case PIX_FMT_YUV422P:
case PIX_FMT_YUVJ422P:
LOG(INFO) << "Supported Format : "<< codec_context_->pix_fmt;
return VideoFrame::YV16;
default:
// TODO(scherkus): More formats here?
return VideoFrame::INVALID;
}
}
#if defined (TOOLKIT_MEEGOTOUCH)
// _DEV2_H264_
/*
* func: ReleaseBufferAndSurface
*
* description:
* free a surface and return it to free_surfaces pool with unused status
*
*/
void FFmpegVideoDecodeEngine::ReleaseBufferAndSurface(AVCodecContext * ctx, AVFrame * pic)
{
int i = 0;
struct VaapiSurface *surface = NULL;
DEV2_TRACE();
surface = (VaapiSurface *)pic->data[0];
if(surface){
/*status reset*/
surface->used = 0;
}
//LOG(INFO) << "ReleaseBufferAndSurface: be impl ok : idx: " << pic->linesize[3] << " addr pic "<< (int)pic;
for(i=0; i<4; i++){
pic->data[i]= NULL;
pic->linesize[i] = 0;
}
}
/*
* func: GetBufferAndSurface
*
* description:
* get a surface from free_surfaces pool with FIFO strategy, and assign to AVFrame
* provided by FFMPEG/LIBVA wrapping code.
*
*/
int FFmpegVideoDecodeEngine::GetBufferAndSurface(AVCodecContext * ctx, AVFrame * pic)
{
int width = (ctx->width + 15 ) & (~15);
int height = (ctx->height + 15) & (~15);
struct VaapiSurface *surface = NULL;
int i = 0, idx = 0;
FFmpegVideoDecodeEngine* engine = reinterpret_cast<FFmpegVideoDecodeEngine*>(ctx->context_model);
DEV2_TRACE();
if(!engine){
LOG(INFO) << "No this engine class \n";
return -1;
}
if(ctx->pix_fmt != PIX_FMT_VAAPI_VLD){
LOG(INFO) << "Not Supported Format \n";
return -1;
}
/* Pop the least recently used free surface : FIFO*/
assert(engine->hw_free_surfaces_[engine->hw_free_surfaces_head_index_]);
surface = engine->hw_free_surfaces_[engine->hw_free_surfaces_head_index_];
if (!surface){
DEV2_TRACE();
return -1;
}
while(surface->used){
/*low percent cases: to seach whole surface lists*/
/*all is used: use next one*/
/*else: use unused one*/
if(i++ < engine->hw_num_surfaces_){
/*next one*/
engine->hw_free_surfaces_head_index_ = (engine->hw_free_surfaces_head_index_ + 1) % engine->hw_num_surfaces_;
surface = engine->hw_free_surfaces_[engine->hw_free_surfaces_head_index_];
}else{
LOG(INFO) << "GetBufferAndSurface: warning no buffer conflict " ;
break;
}
}
/*FIXME*/
//LOG(INFO) << "GetBufferAndSurface: surface num " << hw_num_surfaces_ << " idx: " << hw_free_surfaces_head_index_ << " addr pic " << (int)pic;
surface->used = 1;
pic->data[0] = (unsigned char *)surface;
pic->data[1] = pic->data[2] = NULL;
pic->data[3] = (unsigned char *)(uintptr_t)surface->id;
/*I420, VAAPI support NV12 format.*/
pic->linesize[0]= width;
pic->linesize[1]= width>>1;
pic->linesize[2]= width>>1;
/*cur surface idx*/
pic->linesize[3]= engine->hw_free_surfaces_head_index_ ;
pic->type= 2;//FF_BUFFER_TYPE_USER;
/*pointer to next one*/
engine->hw_free_surfaces_head_index_ = (engine->hw_free_surfaces_head_index_ + 1) % engine->hw_num_surfaces_;
/*align to next 16*/
#if 0
LOG(INFO) << "fmt is " << ctx->pix_fmt;
LOG(INFO) << "w= " << width;
LOG(INFO) << "h= " << height;
LOG(INFO) << "Get Surface idx_ : " << pic->linesize[3];
LOG(INFO) << "AVFrame: 0: " << pic->data[0]
<< " id-3: " << (uintptr_t)pic->data[3];
#endif
pic->opaque = NULL;
pic->age= 256*256;
return 0;
}
#ifdef _DEV2_DEBUG_
static const char *VAImageFormat2String(VAImageFormat *imgfmt)
{
static char str_[5];
DEV2_TRACE();
*(unsigned int*)str_ = imgfmt->fourcc ;
str_[4] = '\0';
return str_;
}
#define DEV2SwitchCase(x) case x: return #x;
static const char *VAProfile2String(VAProfile profile)
{
DEV2_TRACE();
switch (profile) {
DEV2SwitchCase(VAProfileMPEG2Simple);
DEV2SwitchCase(VAProfileMPEG2Main);
DEV2SwitchCase(VAProfileMPEG4Simple);
DEV2SwitchCase(VAProfileMPEG4AdvancedSimple);
DEV2SwitchCase(VAProfileMPEG4Main);
DEV2SwitchCase(VAProfileH264Baseline);
DEV2SwitchCase(VAProfileH264Main);
DEV2SwitchCase(VAProfileH264High);
DEV2SwitchCase(VAProfileVC1Simple);
DEV2SwitchCase(VAProfileVC1Main);
DEV2SwitchCase(VAProfileVC1Advanced);
}
return "<Unknown VAProfile>";
}
static int ProfileSupport(VAProfile profile)
{
DEV2_TRACE();
if (hw_profiles_ && hw_num_profiles_ > 0) {
int i;
for (i = 0; i < hw_num_profiles_; i++) {
if (hw_profiles_[i] == profile)
return 1;
}
}
return 0;
}
/* only H264
*/
static VAProfile CheckVAProfile()
{
static const VAProfile H264_Profile[] =
{ VAProfileH264High, VAProfileH264Main, VAProfileH264Baseline, (VAProfile)-1 };
DEV2_TRACE();
for (int i = 0; H264_Profile[i] != -1; i++) {
if (ProfileSupport(H264_Profile[i]))
return H264_Profile[i];
}
return (VAProfile)-1;
}
static const char *VAEntryPoint2String(VAEntrypoint entrypoint)
{
switch (entrypoint) {
DEV2SwitchCase(VAEntrypointVLD);
DEV2SwitchCase(VAEntrypointIZZ);
DEV2SwitchCase(VAEntrypointIDCT);
DEV2SwitchCase(VAEntrypointMoComp);
DEV2SwitchCase(VAEntrypointDeblocking);
}
return "<Unknown VAEntryPoint>";
}
static int HasEntryPoint(VAEntrypoint entrypoint)
{
if (hw_entrypoints_ && hw_num_entrypoints_ > 0) {
int i;
for (i = 0; i < hw_num_entrypoints_; i++) {
if (hw_entrypoints_[i] == entrypoint)
return 1;
}
}
return 0;
}
/* only H264
*/
static int CheckVAEntryPoint()
{
int ret = -1;
ret = HasEntryPoint(VAEntrypointVLD);
return ret;
}
#endif
/*
* func: get_format callback function.
*
* description:
* is called to search a supported VAAPI codec for given format,
* and well config it before real slice decoding
* pix_fmt :
* PIX_FMT_DXVA2_VLD,
* PIX_FMT_VAAPI_VLD,
* PIX_FMT_YUV420P,
* PIX_FMT_NONE
*
*/
enum PixelFormat FFmpegVideoDecodeEngine::GetFormatAndConfig(struct AVCodecContext *avctx, const enum PixelFormat *pix_fmt)
{
int ret = 0;
FFmpegVideoDecodeEngine* engine = reinterpret_cast<FFmpegVideoDecodeEngine*>(avctx->context_model);
DEV2_TRACE();
while (*pix_fmt != PIX_FMT_NONE ){
if( PIX_FMT_VAAPI_VLD == *pix_fmt){
LOG(INFO) << "found VAAPI VLD format supported ";
//LOG(INFO) << "w= "<< avctx->width << ", h= " << avctx->height;
/* we need to config while first time launch VAAPI engine.
* this is a callback , which is invoked by h264.c before
* decoding a real slice
*/
ret = engine->ConfigHwEngine(avctx->width , avctx->height, VAAPI_H264, avctx->refs);
if(0 != ret){
LOG(INFO) << "func : <ConfigHwEngine> return err " << ret;
return PIX_FMT_NONE;
}
//LOG(INFO) << "func : <ConfigHwEngine> return ok ";
return *pix_fmt;
}
LOG(INFO) << "Unsupported format "<< *pix_fmt << "\n";
pix_fmt ++;
}
return pix_fmt[0];
}
/*
* func: initialization function.
*
* description:
* is called to do basic initilization for VAAPI calling.
* and also query hw capability for decoding.
*
*/
int FFmpegVideoDecodeEngine::InitializeHwEngine(void)
{
VADisplayAttribute *display_attrs;
VAStatus status;
int va_major_version, va_minor_version;
int i, max_image_formats, max_subpic_formats, max_profiles;
int num_display_attrs, max_display_attrs;
DEV2_TRACE();
hw_context_ = (hw_context*)calloc(1, sizeof(hw_context));
if (!hw_context_){
DEV2_TRACE();
return -1;
}
#if 0
/*enable for player_x11 to use player_x11 display*/
mDisplay = g_display;
#else
mDisplay = XOpenDisplay(":0.0");
#endif
hw_context_->display = vaGetDisplay(mDisplay);
if (!hw_context_->display)
return -1;
/*vaInitialize*/
#ifdef _DEV2_DEBUG_
LOG(INFO)<< " InitializeHwEngine(): VA display " << hw_context_->display;
#endif
status = vaInitialize(hw_context_->display, &va_major_version, &va_minor_version);
if (CheckStatus(status, "vaInitialize()")){
DEV2_TRACE();
return -1;
}
#ifdef _DEV2_DEBUG_
/*Query Image Formats*/
LOG(INFO) << " InitializeHwEngine(): VA API version " << va_major_version << va_minor_version;
max_image_formats = vaMaxNumImageFormats(hw_context_->display);
hw_image_formats_ = (VAImageFormat*)calloc(max_image_formats, sizeof(VAImageFormat));
if (!hw_image_formats_){
return -1;
}
status = vaQueryImageFormats(hw_context_->display, hw_image_formats_, &hw_num_image_formats_);
if (CheckStatus(status, "vaQueryImageFormats()")){
DEV2_TRACE();
return -1;
}
LOG(INFO) << " InitializeHwEngine():" << hw_num_image_formats_ << "image formats available";
for (i = 0; i < hw_num_image_formats_; i++){
LOG(INFO) << " VAIMAGE FORMAT : " << VAImageFormat2String(&hw_image_formats_[i]);
}
/*Query Sub Picture Formats.*/
max_subpic_formats = (int)vaMaxNumSubpictureFormats(hw_context_->display);
hw_subpic_formats_ = (VAImageFormat*)calloc(max_subpic_formats, sizeof(VAImageFormat));
if (!hw_subpic_formats_){
return -1;
}
hw_subpic_flags_ = (unsigned int*)calloc(max_subpic_formats, sizeof(unsigned int));
if (!hw_subpic_flags_){
return -1;
}
status = vaQuerySubpictureFormats(hw_context_->display, hw_subpic_formats_, hw_subpic_flags_, (unsigned int*)&hw_num_subpic_formats_);
if (CheckStatus(status, "vaQuerySubpictureFormats()")){
hw_num_subpic_formats_ = 0; /* XXX: don't error out for IEGD */
}
LOG(INFO) << " InitializeHwEngine(): "<< hw_num_subpic_formats_ << " Subpicture Formats Available\n" ;
for (i = 0; i < hw_num_subpic_formats_; i++){
LOG(INFO) << " Subpic Formats " << VAImageFormat2String(&hw_subpic_formats_[i]) << " flags 0x" << hw_subpic_flags_[i];
}
DEV2FreeCalloc(hw_subpic_formats_);
/*Query Config Profiles*/
max_profiles = vaMaxNumProfiles(hw_context_->display);
hw_profiles_ = (VAProfile*)calloc(max_profiles, sizeof(*hw_profiles_));
if (!hw_profiles_)
return -1;
status = vaQueryConfigProfiles(hw_context_->display, hw_profiles_, &hw_num_profiles_);
if (CheckStatus(status, "vaQueryConfigProfiles()")){
DEV2_TRACE();
return -1;
}
LOG(INFO) << "InitializeHwEngine(): " << hw_num_profiles_ << " Profiles Available" ;
for (i = 0; i < hw_num_profiles_; i++){
LOG(INFO) << " Profiles " << VAProfile2String(hw_profiles_[i]);
}
/*Query Displayer Attributes*/
max_display_attrs = vaMaxNumDisplayAttributes(hw_context_->display);
display_attrs = (VADisplayAttribute *)calloc(max_display_attrs, sizeof(*display_attrs));
if (display_attrs) {
num_display_attrs = 0;
status = vaQueryDisplayAttributes(hw_context_->display, display_attrs, &num_display_attrs);
if (CheckStatus(status, "vaQueryDisplayAttributes()") == 0) {
LOG(INFO) << " vaQueryDisplayAttributes(): " << num_display_attrs ;
#if 0
for (i = 0; i < num_display_attrs; i++) {
VADisplayAttribute *attr;
switch (display_attrs[i].type) {
case VADisplayAttribBrightness:
attr = &hw_equalizer_.brightness;
break;
case VADisplayAttribContrast:
attr = &hw_equalizer_.contrast;
break;
case VADisplayAttribHue:
attr = &hw_equalizer_.hue;
break;
case VADisplayAttribSaturation:
attr = &hw_equalizer_.saturation;
break;
default:
attr = NULL;
break;
}
if (attr)
*attr = display_attrs[i];
}
#endif
}
free(display_attrs);
}
#endif
return 0;
}
/*
* func: config hw engine
*
* description:
* create surfaces , config, context, only H264 here, so no "format" parameters
*
*/
int FFmpegVideoDecodeEngine::ConfigHwEngine(uint32_t width, uint32_t height, uint32_t format, uint32_t refs)
{
VAConfigAttrib attrib;
VAStatus status;
int i, j, max_entrypoints ;
struct VaapiSurface *surface = NULL;
VAEntrypoint entrypoint = VAEntrypointVLD;
VAProfile profile = VAProfileH264High;
/*reset */
//hw_num_surfaces_ = NUM_VIDEO_SURFACES_H264;
hw_num_surfaces_ = ((refs + 5) < NUM_VIDEO_SURFACES_H264) ? (refs + 5) : NUM_VIDEO_SURFACES_H264;
hw_free_surfaces_head_index_ = 0;
hw_free_surfaces_[hw_num_surfaces_] = NULL;
/*FIXED : H264 only, alignment input is needed, I do not why add limitation to this API??*/
width = (width + 3) & (~3);
/* Create video surfaces */
status = vaCreateSurfaces(hw_context_->display, width, height, VA_RT_FORMAT_YUV420,
hw_num_surfaces_, hw_surface_ids_);
if (CheckStatus(status, "vaCreateSurfaces():")){
DEV2_TRACE();
return -1;
}
for(i = 0; i < (hw_num_surfaces_); i ++){
/*surface structure used by wrapping code*/
surface = (VaapiSurface *)calloc(1, sizeof(*surface));
if(surface == NULL){
DEV2_TRACE();
return -1;
}
hw_free_surfaces_[i] = surface;
surface->id = hw_surface_ids_[i];
surface->used = 0;
surface->image.image_id = VA_INVALID_ID;
surface->image.buf = VA_INVALID_ID;
}
/*indicate surface allocate/unallocate status*/
hw_surface_ids_[hw_num_surfaces_] = 1;
hw_free_surfaces_[hw_num_surfaces_] = (VaapiSurface *)0x1;
/* Allocate VA images */
#ifdef _DEV2_DEBUG_
/*IMG FMT IS VAAPI*/
LOG(INFO) << " FFmpegVideoDecodeEngine::ConfigHwEngine , all surface:"<< hw_num_surfaces_;
/* Check entry-point (only VLD for now) */
max_entrypoints = vaMaxNumEntrypoints(hw_context_->display);
hw_entrypoints_ = (VAEntrypoint*)calloc(max_entrypoints, sizeof(*hw_entrypoints_));
if (!hw_entrypoints_){
DEV2_TRACE();
return -1;
}
/*check profile*/
profile = CheckVAProfile();
if(-1 == (int)profile){
DEV2_TRACE();
return -1;
}
status = vaQueryConfigEntrypoints(hw_context_->display, profile,
hw_entrypoints_, &hw_num_entrypoints_);
if (CheckStatus(status, "vaQueryConfigEntrypoints()")){
DEV2_TRACE();
return -1;
}
LOG(INFO) << " ConfigHwEngine("<< VAProfile2String(profile) << "): "<< hw_num_entrypoints_ << " entrypoints available";
for (i = 0; i < hw_num_entrypoints_; i++){
LOG(INFO) << " num entrypoints ", VAEntryPoint2String(hw_entrypoints_[i]);
}
#endif
/* Config VA HW , profile, entrypoint, and render format--------------- */
/* Check chroma format (only 4:2:0 for now) */
attrib.type = VAConfigAttribRTFormat;
status = vaGetConfigAttributes(hw_context_->display, profile, entrypoint, &attrib, 1);
if (CheckStatus(status, "vaGetConfigAttributes()")){
DEV2_TRACE();
return -1;
}
#ifdef _DEV2_DEBUG_
LOG(INFO) << " ConfigHwEngine: Render Format:" << attrib.value ;
#endif
if ((attrib.value & VA_RT_FORMAT_YUV420) == 0){
DEV2_TRACE();
return -1;
}
/* Create a configuration for the decode pipeline for h264*/
status = vaCreateConfig(hw_context_->display, (VAProfile)profile, entrypoint, &attrib, 1, &hw_context_->config_id);
if (CheckStatus(status, "vaCreateConfig()")){
DEV2_TRACE();
return -1;
}
/* Create a context for the decode pipeline */
status = vaCreateContext(hw_context_->display, hw_context_->config_id,
width, height, VA_PROGRESSIVE,
hw_surface_ids_, hw_num_surfaces_,
&hw_context_->context_id);
if (CheckStatus(status, "vaCreateContext()")){
DEV2_TRACE();
return -1;
}
return 0;
}
/*
* func: UnInitializeHwEngine
*
* description:
* free hw resource, such as context, surfaces, images,config and etc.
*
*/
void FFmpegVideoDecodeEngine::UnInitializeHwEngine(void)
{
int i;
DEV2_TRACE();
if (hw_context_ && hw_context_->context_id) {
vaDestroyContext(hw_context_->display, hw_context_->context_id);
hw_context_->context_id = 0;
}
if (hw_free_surfaces_[hw_num_surfaces_]) {
struct VaapiSurface *surface;
for (i = 0; i < hw_num_surfaces_; i++) {
if (!hw_free_surfaces_[i])
continue;
/*free VA surfaces*/
if (hw_free_surfaces_[i]->image.image_id != VA_INVALID_ID) {
vaDestroyImage(hw_context_->display,
hw_free_surfaces_[i]->image.image_id);
hw_free_surfaces_[i]->image.image_id = VA_INVALID_ID;
}
/*free VA surfaces structure outside of VAAPI*/
free(hw_free_surfaces_[i]);
hw_free_surfaces_[i] = NULL;
}
/*freed by calloc*/
hw_free_surfaces_head_index_ = 0;
hw_free_surfaces_[hw_num_surfaces_] = NULL;
}
if (hw_surface_ids_[hw_num_surfaces_]) {
vaDestroySurfaces(hw_context_->display, hw_surface_ids_, hw_num_surfaces_);
hw_surface_ids_[hw_num_surfaces_] = 0;
hw_num_surfaces_ = 0;
}
if (hw_context_ && hw_context_->config_id) {
vaDestroyConfig(hw_context_->display, hw_context_->config_id);
hw_context_->config_id = 0;
}
if (hw_context_ && hw_context_->display) {
/*free all internal resource of VA*/
vaTerminate(hw_context_->display);
}
DEV2FreeCalloc(hw_context_);
#ifdef _DEV2_DEBUG_
DEV2FreeCalloc(hw_image_formats_);
DEV2FreeCalloc(hw_subpic_flags_);
DEV2FreeCalloc(hw_profiles_);
DEV2FreeCalloc(hw_entrypoints_);
LOG(INFO) << "UnInitializeHwEngine: END";
#endif
}
#endif
} // namespace media
// Disable refcounting for this object because this object only lives
// on the video decoder thread and there's no need to refcount it.
DISABLE_RUNNABLE_METHOD_REFCOUNT(media::FFmpegVideoDecodeEngine);
| 31.446545 | 148 | 0.647309 | [
"render",
"object",
"vector"
] |
14693065eaa79aab4b6a7b7065d4a34d62685047 | 2,709 | hpp | C++ | src/kvalue.hpp | Tebaks/Korlang-yacc | 599c86acee9e5cc04f94b37ba196743f96f876b5 | [
"MIT"
] | 2 | 2021-02-21T12:15:22.000Z | 2021-02-21T12:32:31.000Z | src/kvalue.hpp | Tebaks/Korlang | 599c86acee9e5cc04f94b37ba196743f96f876b5 | [
"MIT"
] | null | null | null | src/kvalue.hpp | Tebaks/Korlang | 599c86acee9e5cc04f94b37ba196743f96f876b5 | [
"MIT"
] | null | null | null | #include <iostream>
#include <cstdlib>
#include <map>
#include <vector>
#include <string>
using namespace std;
enum ValueTypes
{
NUMBER,
STRING,
NIL,
};
class KValue
{
public:
ValueTypes type;
float number;
string str;
KValue() : str(""), number(0.0), type(ValueTypes(NIL)) {}
/*OPERATOR OVERLOADINGS*/
KValue *operator+(KValue *kval)
{
KValue *res = new KValue();
if (type == ValueTypes(STRING) && kval->type == ValueTypes(STRING))
{
res->type = ValueTypes(STRING);
res->str = str + kval->str;
}
else if (type == ValueTypes(STRING) && kval->type == ValueTypes(NUMBER))
{
res->type = ValueTypes(STRING);
string s = to_string(kval->number);
res->str = str + s;
}
else
{
res->type = ValueTypes(NIL);
}
return res;
}
KValue *operator-(KValue *kval)
{
KValue *res = new KValue();
if (type == ValueTypes(NUMBER) && kval->type == ValueTypes(NUMBER))
{
res->type = ValueTypes(NUMBER);
res->number = number + kval->number;
}
else
{
res->type = ValueTypes(NIL);
}
return res;
}
KValue *operator*(KValue *kval)
{
KValue *res = new KValue();
if (type == ValueTypes(NUMBER) && kval->type == ValueTypes(NUMBER))
{
res->type = ValueTypes(NUMBER);
res->number = number * kval->number;
}
else
{
res->type = ValueTypes(NIL);
}
return res;
}
KValue *operator/(KValue *kval)
{
KValue *res = new KValue();
if (type == ValueTypes(NUMBER) && kval->type == ValueTypes(NUMBER))
{
res->type = ValueTypes(NUMBER);
res->number = number / kval->number;
}
else
{
res->type = ValueTypes(NIL);
}
return res;
}
KValue *operator+(float f)
{
if (type == ValueTypes(NUMBER))
{
this->number += f;
}
return this;
}
KValue *operator-(float f)
{
if (type == ValueTypes(NUMBER))
{
this->number -= f;
}
return this;
}
KValue *operator*(float f)
{
if (type == ValueTypes(NUMBER))
{
this->number *= f;
}
return this;
}
KValue *operator/(float f)
{
if (type == ValueTypes(NUMBER))
{
this->number /= f;
}
return this;
}
KValue *operator+(string s)
{
if (type == ValueTypes(STRING))
{
this->type = ValueTypes(STRING);
this->str = str + s;
}
else if (type == ValueTypes(NUMBER))
{
this->type = ValueTypes(STRING);
this->str = to_string(this->number) + s;
}
return this;
}
}; | 19.919118 | 77 | 0.520118 | [
"vector"
] |
1477095b36410406ac43335b94e49d6cd4c2a98f | 4,250 | cc | C++ | chrome/browser/hid/hid_chooser_context_unittest.cc | sarang-apps/darshan_browser | 173649bb8a7c656dc60784d19e7bb73e07c20daa | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | null | null | null | chrome/browser/hid/hid_chooser_context_unittest.cc | sarang-apps/darshan_browser | 173649bb8a7c656dc60784d19e7bb73e07c20daa | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | null | null | null | chrome/browser/hid/hid_chooser_context_unittest.cc | sarang-apps/darshan_browser | 173649bb8a7c656dc60784d19e7bb73e07c20daa | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | null | null | null | // Copyright 2019 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome/browser/hid/hid_chooser_context.h"
#include "base/run_loop.h"
#include "chrome/browser/content_settings/host_content_settings_map_factory.h"
#include "chrome/browser/hid/hid_chooser_context_factory.h"
#include "chrome/test/base/testing_profile.h"
#include "components/content_settings/core/browser/host_content_settings_map.h"
#include "components/permissions/test/chooser_context_base_mock_permission_observer.h"
#include "content/public/test/browser_task_environment.h"
#include "services/device/public/mojom/hid.mojom.h"
#include "testing/gtest/include/gtest/gtest.h"
namespace {
class HidChooserContextTest : public testing::Test {
public:
HidChooserContextTest() = default;
~HidChooserContextTest() override = default;
Profile* profile() { return &profile_; }
permissions::MockPermissionObserver& observer() { return mock_observer_; }
HidChooserContext* GetContext(Profile* profile) {
auto* context = HidChooserContextFactory::GetForProfile(profile);
context->AddObserver(&mock_observer_);
return context;
}
private:
content::BrowserTaskEnvironment task_environment_;
TestingProfile profile_;
permissions::MockPermissionObserver mock_observer_;
};
} // namespace
TEST_F(HidChooserContextTest, GrantAndRevokeEphemeralPermission) {
const auto origin = url::Origin::Create(GURL("https://google.com"));
auto device = device::mojom::HidDeviceInfo::New();
device->guid = "test-guid";
HidChooserContext* context = GetContext(profile());
EXPECT_FALSE(context->HasDevicePermission(origin, origin, *device));
EXPECT_CALL(observer(), OnChooserObjectPermissionChanged(
ContentSettingsType::HID_GUARD,
ContentSettingsType::HID_CHOOSER_DATA));
context->GrantDevicePermission(origin, origin, *device);
EXPECT_TRUE(context->HasDevicePermission(origin, origin, *device));
std::vector<std::unique_ptr<permissions::ChooserContextBase::Object>>
origin_objects = context->GetGrantedObjects(origin, origin);
ASSERT_EQ(1u, origin_objects.size());
std::vector<std::unique_ptr<permissions::ChooserContextBase::Object>>
objects = context->GetAllGrantedObjects();
ASSERT_EQ(1u, objects.size());
EXPECT_EQ(origin.GetURL(), objects[0]->requesting_origin);
EXPECT_EQ(origin.GetURL(), objects[0]->embedding_origin);
EXPECT_EQ(origin_objects[0]->value, objects[0]->value);
EXPECT_EQ(content_settings::SettingSource::SETTING_SOURCE_USER,
objects[0]->source);
EXPECT_FALSE(objects[0]->incognito);
EXPECT_CALL(observer(), OnChooserObjectPermissionChanged(
ContentSettingsType::HID_GUARD,
ContentSettingsType::HID_CHOOSER_DATA));
EXPECT_CALL(observer(), OnPermissionRevoked(origin, origin));
context->RevokeObjectPermission(origin, origin, objects[0]->value);
EXPECT_FALSE(context->HasDevicePermission(origin, origin, *device));
origin_objects = context->GetGrantedObjects(origin, origin);
EXPECT_EQ(0u, origin_objects.size());
objects = context->GetAllGrantedObjects();
EXPECT_EQ(0u, objects.size());
}
TEST_F(HidChooserContextTest, GuardPermission) {
const auto origin = url::Origin::Create(GURL("https://google.com"));
auto device = device::mojom::HidDeviceInfo::New();
device->guid = "test-guid";
HidChooserContext* context = GetContext(profile());
context->GrantDevicePermission(origin, origin, *device);
EXPECT_TRUE(context->HasDevicePermission(origin, origin, *device));
auto* map = HostContentSettingsMapFactory::GetForProfile(profile());
map->SetContentSettingDefaultScope(origin.GetURL(), origin.GetURL(),
ContentSettingsType::HID_GUARD,
std::string(), CONTENT_SETTING_BLOCK);
EXPECT_FALSE(context->HasDevicePermission(origin, origin, *device));
auto objects = context->GetGrantedObjects(origin, origin);
EXPECT_EQ(0u, objects.size());
auto all_origin_objects = context->GetAllGrantedObjects();
EXPECT_EQ(0u, all_origin_objects.size());
}
| 40.09434 | 86 | 0.737412 | [
"object",
"vector"
] |
1477ab01ee4951dc4830b0e32d210eab00bd7993 | 199,911 | cpp | C++ | src/CDocScriptProcess.cpp | colinw7/CDoc | 56aa99315c27fdc47c92bcc7e28cd51618ae493f | [
"MIT"
] | 1 | 2021-12-23T02:21:45.000Z | 2021-12-23T02:21:45.000Z | src/CDocScriptProcess.cpp | colinw7/CDoc | 56aa99315c27fdc47c92bcc7e28cd51618ae493f | [
"MIT"
] | null | null | null | src/CDocScriptProcess.cpp | colinw7/CDoc | 56aa99315c27fdc47c92bcc7e28cd51618ae493f | [
"MIT"
] | 1 | 2019-04-01T13:21:34.000Z | 2019-04-01T13:21:34.000Z | #include <CDocI.h>
#include <COSTime.h>
/*---------------------------------------------------------------------------*/
#define MAX_LISTS 50
/*---------------------------------------------------------------------------*/
/* Define Header Parameter Definition */
#define DH_OFFSET(a) CDocOffset(CDHeaderControl*,a)
struct CDHeaderControl {
int new_page;
int section_breaks;
int alignment;
int space_before;
int skip_before;
int space_after;
int underscored;
int capitalised;
int break_header;
int toc_entry;
int toc_only;
int skip_before_toc_entry;
int toc_indentation;
int number_header;
char *font;
char *toc_font;
};
static CDParameterData
dh_parameter_data[] = {
{"br" , PARM_FLAG , NULL, DH_OFFSET(break_header ),},
{"nbr" , PARM_NFLAG , NULL, DH_OFFSET(break_header ),},
{"pa" , PARM_FLAG , NULL, DH_OFFSET(new_page ),},
{"npa" , PARM_NFLAG , NULL, DH_OFFSET(new_page ),},
{"tc" , PARM_FLAG , NULL, DH_OFFSET(toc_entry ),},
{"ntc" , PARM_NFLAG , NULL, DH_OFFSET(toc_entry ),},
{"to" , PARM_FLAG , NULL, DH_OFFSET(toc_only ),},
{"nto" , PARM_NFLAG , NULL, DH_OFFSET(toc_only ),},
{"ts" , PARM_FLAG , NULL, DH_OFFSET(skip_before_toc_entry),},
{"nts" , PARM_NFLAG , NULL, DH_OFFSET(skip_before_toc_entry),},
{"up" , PARM_FLAG , NULL, DH_OFFSET(capitalised ),},
{"nup" , PARM_NFLAG , NULL, DH_OFFSET(capitalised ),},
{"us" , PARM_FLAG , NULL, DH_OFFSET(underscored ),},
{"nus" , PARM_NFLAG , NULL, DH_OFFSET(underscored ),},
{"num" , PARM_FLAG , NULL, DH_OFFSET(number_header ),},
{"nonum" , PARM_NFLAG , NULL, DH_OFFSET(number_header ),},
{"sect" , PARM_FLAG , NULL, DH_OFFSET(section_breaks ),},
{"nosect" , PARM_NFLAG , NULL, DH_OFFSET(section_breaks ),},
{"dot" , PARM_IGNORE , NULL, 0 ,},
{"ndot" , PARM_IGNORE , NULL, 0 ,},
{"autohy" , PARM_IGNORE , NULL, 0 ,},
{"nohy" , PARM_IGNORE , NULL, 0 ,},
{"nohang" , PARM_IGNORE , NULL, 0 ,},
{"hang" , PARM_IGNORE , NULL, 0 ,},
{"font" , PARM_NEW_STR, NULL, DH_OFFSET(font ),},
{"spbf" , PARM_INT , NULL, DH_OFFSET(space_before ),},
{"skbf" , PARM_INT , NULL, DH_OFFSET(skip_before ),},
{"spaf" , PARM_INT , NULL, DH_OFFSET(space_after ),},
{"tcin" , PARM_INT , NULL, DH_OFFSET(toc_indentation ),},
{"tfont" , PARM_NEW_STR, NULL, DH_OFFSET(toc_font ),},
{"center" , PARM_VALUE , (char *) CHALIGN_TYPE_CENTRE , DH_OFFSET(alignment),},
{"centre" , PARM_VALUE , (char *) CHALIGN_TYPE_CENTRE , DH_OFFSET(alignment),},
{"left" , PARM_VALUE , (char *) CHALIGN_TYPE_LEFT , DH_OFFSET(alignment),},
{"inside" , PARM_VALUE , (char *) CHALIGN_TYPE_INSIDE , DH_OFFSET(alignment),},
{"outside", PARM_VALUE , (char *) CHALIGN_TYPE_OUTSIDE, DH_OFFSET(alignment),},
{"right" , PARM_VALUE , (char *) CHALIGN_TYPE_RIGHT , DH_OFFSET(alignment),},
{NULL, 0, NULL, 0,},
};
/*---------------------------------------------------------------------------*/
/* Definition List Parameter Definition */
#define DL_OFFSET(a) CDocOffset(CDDefinitionList*,a)
static CDParameterData
dl_parameter_data[] = {
{"break" , PARM_FLAG , NULL, DL_OFFSET(break_up ),},
{"compact", PARM_FLAG , NULL, DL_OFFSET(compact ),},
{"headhi" , PARM_INT , NULL, DL_OFFSET(heading_highlight),},
{"termhi" , PARM_INT , NULL, DL_OFFSET(term_highlight ),},
{"tsize" , PARM_CLENSTR, NULL, DL_OFFSET(depth ),},
{NULL , 0 , NULL, 0 ,},
};
/*---------------------------------------------------------------------------*/
/* Figure Parameter Definition */
#define FIG_OFFSET(a) CDocOffset(CDFigureData*,a)
struct CDFigureData {
int depth;
char *frame;
char *ident;
int indent;
int place;
int width;
};
static CDParameterChoiceData
fig_frame_data[] = {
{"rule", (char *) FRAME_RULE ,},
{"box" , (char *) FRAME_BOX ,},
{"none", (char *) FRAME_NONE ,},
{"" , (char *) PARM_NEW_STR,},
{NULL , (char *) 0 ,},
};
static CDParameterChoiceData
fig_place_data[] = {
{"top" , (char *) PLACE_TOP ,},
{"bottom", (char *) PLACE_BOTTOM,},
{"inline", (char *) PLACE_INLINE,},
{NULL , (char *) 0 ,},
};
static CDParameterChoiceData
fig_width_data[] = {
{"page" , (char *) WIDTH_PAGE ,},
{"column", (char *) WIDTH_COLUMN,},
{"" , (char *) PARM_CLENSTR,},
{NULL , (char *) 0 ,},
};
static CDParameterData
fig_parameter_data[] = {
{"depth" , PARM_LLENSTR, NULL , FIG_OFFSET(depth ),},
{"frame" , PARM_CHOICE , (char *) fig_frame_data, FIG_OFFSET(frame ),},
{"id" , PARM_NEW_STR, NULL , FIG_OFFSET(ident ),},
{"indent", PARM_CLENSTR, NULL , FIG_OFFSET(indent),},
{"place" , PARM_CHOICE , (char *) fig_place_data, FIG_OFFSET(place ),},
{"width" , PARM_CHOICE , (char *) fig_width_data, FIG_OFFSET(width ),},
{NULL , 0 , NULL , 0 ,},
};
/*---------------------------------------------------------------------------*/
/* Footnote Parameter Definition */
#define FN_OFFSET(a) CDocOffset(CDFootnoteData*,a)
struct CDFootnoteData {
char *ident;
};
static CDParameterData
fn_parameter_data[] = {
{"id", PARM_NEW_STR, NULL, FN_OFFSET(ident),},
{NULL, 0 , NULL, 0 ,},
};
/*---------------------------------------------------------------------------*/
/* General and Stairs Document Parameter Definition */
#define DOC_OFFSET(a) CDocOffset(CDDocData*,a)
struct CDDocData {
char *security;
char *language;
};
static CDParameterData
gdoc_parameter_data[] = {
{"sec" , PARM_NEW_STR, NULL, DOC_OFFSET(security),},
{"language", PARM_NEW_STR, NULL, DOC_OFFSET(language),},
{NULL , 0 , NULL, 0 ,},
};
static CDParameterData
sdoc_parameter_data[] = {
{"sec" , PARM_NEW_STR, NULL, DOC_OFFSET(security),},
{"language", PARM_NEW_STR, NULL, DOC_OFFSET(language),},
{NULL , 0 , NULL, 0 ,},
};
/*---------------------------------------------------------------------------*/
/* Glossary List Parameter Definition */
#define GL_OFFSET(a) CDocOffset(CDGlossaryList*,a)
static CDParameterData
gl_parameter_data[] = {
{"compact", PARM_FLAG, NULL, GL_OFFSET(compact ),},
{"termhi" , PARM_INT , NULL, GL_OFFSET(term_highlight),},
{NULL , 0 , NULL, 0 ,},
};
/*---------------------------------------------------------------------------*/
/* Headings Parameter Definition */
#define HX_OFFSET(a) CDocOffset(CDHeading*,a)
struct CDHeading {
char *ident;
char *stitle;
};
static CDParameterData
h01_parameter_data[] = {
{"id" , PARM_STR, NULL, HX_OFFSET(ident ),},
{"stitle", PARM_STR, NULL, HX_OFFSET(stitle),},
{NULL , 0 , NULL, 0 ,},
};
static CDParameterData
h26_parameter_data[] = {
{"id", PARM_STR, NULL, HX_OFFSET(ident),},
{NULL, 0 , NULL, 0 ,},
};
/*---------------------------------------------------------------------------*/
/* Index Heading Parameter Definition */
#define IHX_OFFSET(a) CDocOffset(CDIndexEntryHeading*,a)
struct CDIndexEntryHeading {
char *ident;
char *print;
char *see;
char *seeid;
};
static CDParameterData
ih_parameter_data[] = {
{"id" , PARM_STR, NULL, IHX_OFFSET(ident),},
{"print", PARM_STR, NULL, IHX_OFFSET(print),},
{"see" , PARM_STR, NULL, IHX_OFFSET(see ),},
{"seeid", PARM_STR, NULL, IHX_OFFSET(seeid),},
{NULL , 0 , NULL, 0 ,},
};
/*---------------------------------------------------------------------------*/
/* Index Heading Parameter Definition */
#define IX_OFFSET(a) CDocOffset(CDIndexEntry*,a)
#define IREF_OFFSET(a) CDocOffset(CDIndexRef*,a)
struct CDIndexEntry {
char *ident;
char *refid;
char *page;
};
struct CDIndexRef {
char *refid;
char *pg;
char *see;
char *seeid;
};
static CDParameterChoiceData
index_pg_data[] = {
{"start", (char *) PG_START ,},
{"end" , (char *) PG_END ,},
{"major", (char *) PG_MAJOR ,},
{"" , (char *) PARM_NEW_STR,},
{NULL , (char *) 0 ,},
};
static CDParameterData
i1_parameter_data[] = {
{"id" , PARM_STR , NULL , IX_OFFSET(ident) ,},
{"pg" , PARM_CHOICE , (char *) index_pg_data, IX_OFFSET(page ) ,},
{NULL , 0 , NULL , 0 ,},
};
static CDParameterData
i23_parameter_data[] = {
{"id" , PARM_STR , NULL , IX_OFFSET(ident) ,},
{"refid", PARM_STR , NULL , IX_OFFSET(refid) ,},
{"pg" , PARM_CHOICE , (char *) index_pg_data, IX_OFFSET(page ) ,},
{NULL , 0 , NULL , 0 ,},
};
static CDParameterData
iref_parameter_data[] = {
{"refid", PARM_NEW_STR, NULL , IREF_OFFSET(refid),},
{"pg" , PARM_CHOICE , (char *) index_pg_data, IREF_OFFSET(pg ),},
{"see" , PARM_NEW_STR, NULL , IREF_OFFSET(see ),},
{"seeid", PARM_NEW_STR, NULL , IREF_OFFSET(seeid),},
{NULL , 0 , NULL , 0 ,},
};
/*---------------------------------------------------------------------------*/
/* List Item Parameter Definition */
#define LI_OFFSET(a) CDocOffset(CDListItem*,a)
struct CDListItem {
char *ident;
};
static CDParameterData
li_parameter_data[] = {
{"id", PARM_STR, NULL, LI_OFFSET(ident),},
{NULL, 0 , NULL, 0 ,},
};
/*---------------------------------------------------------------------------*/
/* List Parameter Definition */
#define LIST_OFFSET(a) CDocOffset(CDGeneralList*,a)
static CDParameterData
ol_parameter_data[] = {
{"compact", PARM_FLAG, NULL, LIST_OFFSET(compact),},
{NULL , 0 , NULL, 0 ,},
};
static CDParameterData
sl_parameter_data[] = {
{"compact", PARM_FLAG, NULL, LIST_OFFSET(compact),},
{NULL , 0 , NULL, 0 ,},
};
static CDParameterData
ul_parameter_data[] = {
{"compact", PARM_FLAG, NULL, LIST_OFFSET(compact),},
{NULL , 0 , NULL, 0 ,},
};
/*---------------------------------------------------------------------------*/
/* Row Parameter Definition */
#define ROW_OFFSET(a) CDocOffset(CDTableRowData*,a)
struct CDTableRowData {
char *refid;
int split;
};
static CDParameterData
row_parameter_data[] = {
{"refid", PARM_NEW_STR, NULL, ROW_OFFSET(refid),},
{"split", PARM_BOOLEAN, NULL, ROW_OFFSET(split),},
{NULL , 0 , NULL, 0 ,},
};
/*---------------------------------------------------------------------------*/
/* Table Parameter Definition */
#define TABLE_OFFSET(a) CDocOffset(CDTableData*,a)
struct CDTableData {
int column;
char *id;
int page;
char *refid;
int split;
int rotate;
int width;
};
static CDParameterData
table_parameter_data[] = {
{"column", PARM_VALUE , (char *) WIDTH_COLUMN, TABLE_OFFSET(column),},
{"id" , PARM_NEW_STR, NULL , TABLE_OFFSET(id ),},
{"page" , PARM_VALUE , (char *) WIDTH_PAGE , TABLE_OFFSET(page ),},
{"refid" , PARM_NEW_STR, NULL , TABLE_OFFSET(refid ),},
{"split" , PARM_BOOLEAN, NULL , TABLE_OFFSET(split ),},
{"rotate", PARM_INT , NULL , TABLE_OFFSET(rotate),},
{"width" , PARM_CLENSTR, NULL , TABLE_OFFSET(width ),},
{NULL , 0 , NULL , 0 ,},
};
/*---------------------------------------------------------------------------*/
/* Table Footer Parameter Definition */
static CDParameterData
tft_parameter_data[] = {
{"refid", PARM_NEW_STR, NULL, ROW_OFFSET(refid),},
{NULL , 0 , NULL, 0 ,},
};
/*---------------------------------------------------------------------------*/
/* Table Header Parameter Definition */
static CDParameterData
thd_parameter_data[] = {
{"refid", PARM_NEW_STR, NULL, ROW_OFFSET(refid),},
{NULL , 0 , NULL, 0 ,},
};
/*---------------------------------------------------------------------------*/
/* Example Parameter Definition */
#define XMP_OFFSET(a) CDocOffset(CDExample*,a)
static CDParameterData
xmp_parameter_data[] = {
{"depth", PARM_LLENSTR, NULL, XMP_OFFSET(depth),},
{NULL , 0 , NULL, 0 ,},
};
/*---------------------------------------------------------------------------*/
/* Cross Reference Parameter Definitions */
#define CREF_OFFSET(a) CDocOffset(CDCrossRef*,a)
static CDParameterData
figref_parameter_data[] = {
{"refid", PARM_NEW_STR, NULL, CREF_OFFSET(refid),},
{"page" , PARM_BOOLEAN, NULL, CREF_OFFSET(page ),},
{NULL , 0 , NULL, 0 ,},
};
static CDParameterData
fnref_parameter_data[] = {
{"refid", PARM_NEW_STR, NULL, CREF_OFFSET(refid),},
{NULL , 0 , NULL, 0 ,},
};
static CDParameterData
hdref_parameter_data[] = {
{"refid", PARM_NEW_STR, NULL, CREF_OFFSET(refid),},
{"page" , PARM_BOOLEAN, NULL, CREF_OFFSET(page ),},
{NULL , 0 , NULL, 0 ,},
};
static CDParameterData
liref_parameter_data[] = {
{"refid", PARM_NEW_STR, NULL, CREF_OFFSET(refid),},
{"page" , PARM_BOOLEAN, NULL, CREF_OFFSET(page ),},
{NULL , 0 , NULL, 0 ,},
};
static CDParameterData
tref_parameter_data[] = {
{"refid", PARM_NEW_STR, NULL, CREF_OFFSET(refid),},
{"page" , PARM_BOOLEAN, NULL, CREF_OFFSET(page ),},
{NULL , 0 , NULL, 0 ,},
};
/*---------------------------------------------------------------------------*/
/* Hook Parameter Definitions */
struct CDHookParameterData {
char *id;
char *data;
char *text;
};
#define HOOK_OFFSET(a) CDocOffset(CDHookParameterData*,a)
static CDParameterData
hook_parameter_data[] = {
{"id" , PARM_NEW_STR, NULL, HOOK_OFFSET(id ),},
{"data", PARM_NEW_STR, NULL, HOOK_OFFSET(data),},
{"text", PARM_NEW_STR, NULL, HOOK_OFFSET(text),},
{NULL , 0 , NULL, 0 ,},
};
/*---------------------------------------------------------------------------*/
static CDHeaderControl
default_header_control[CDOC_MAX_HEADERS] = {
/* Header 0 */
{
/* New Page */ true,
/* Section Breaks */ true,
/* Alignment */ CHALIGN_TYPE_LEFT,
/* Space Before */ 0,
/* Skip Before */ 0,
/* Space after */ 0,
/* Underscored */ true,
/* Capitalised */ true,
/* Break header */ true,
/* TOC entry */ true,
/* TOC only */ false,
/* Skip before TOC Entry */ true,
/* TOC Indentation */ 0,
/* Number Header */ false,
/* Font */ NULL,
/* TOC Font */ NULL,
},
/* Header 1 */
{
/* New Page */ true,
/* Section Breaks */ true,
/* Alignment */ CHALIGN_TYPE_LEFT,
/* Space Before */ 0,
/* Skip Before */ 0,
/* Space after */ 5,
/* Underscored */ false,
/* Capitalised */ true,
/* Break header */ true,
/* TOC entry */ true,
/* TOC only */ false,
/* Skip before TOC Entry */ true,
/* TOC Indentation */ 0,
/* Number Header */ true,
/* Font */ NULL,
/* TOC Font */ NULL,
},
/* Header 2 */
{
/* New Page */ false,
/* Section Breaks */ false,
/* Alignment */ CHALIGN_TYPE_LEFT,
/* Space Before */ 0,
/* Skip Before */ 3,
/* Space after */ 2,
/* Underscored */ false,
/* Capitalised */ true,
/* Break header */ true,
/* TOC entry */ true,
/* TOC only */ false,
/* Skip before TOC Entry */ false,
/* TOC Indentation */ 0,
/* Number Header */ true,
/* Font */ NULL,
/* TOC Font */ NULL,
},
/* Header 3 */
{
/* New Page */ false,
/* Section Breaks */ false,
/* Alignment */ CHALIGN_TYPE_LEFT,
/* Space Before */ 0,
/* Skip Before */ 3,
/* Space after */ 2,
/* Underscored */ false,
/* Capitalised */ false,
/* Break header */ true,
/* TOC entry */ true,
/* TOC only */ false,
/* Skip before TOC Entry */ false,
/* TOC Indentation */ 2,
/* Number Header */ true,
/* Font */ NULL,
/* TOC Font */ NULL,
},
/* Header 4 */
{
/* New Page */ false,
/* Section Breaks */ false,
/* Alignment */ CHALIGN_TYPE_LEFT,
/* Space Before */ 0,
/* Skip Before */ 3,
/* Space after */ 2,
/* Underscored */ true,
/* Capitalised */ false,
/* Break header */ true,
/* TOC entry */ false,
/* TOC only */ false,
/* Skip before TOC Entry */ false,
/* TOC Indentation */ 4,
/* Number Header */ true,
/* Font */ NULL,
/* TOC Font */ NULL,
},
/* Header 5 */
{
/* New Page */ false,
/* Section Breaks */ false,
/* Alignment */ CHALIGN_TYPE_LEFT,
/* Space Before */ 0,
/* Skip Before */ 1,
/* Space after */ 0,
/* Underscored */ false,
/* Capitalised */ true,
/* Break header */ false,
/* TOC entry */ false,
/* TOC only */ false,
/* Skip before TOC Entry */ false,
/* TOC Indentation */ 6,
/* Number Header */ false,
/* Font */ NULL,
/* TOC Font */ NULL,
},
/* Header 6 */
{
/* New Page */ false,
/* Section Breaks */ false,
/* Alignment */ CHALIGN_TYPE_LEFT,
/* Space Before */ 0,
/* Skip Before */ 1,
/* Space after */ 0,
/* Underscored */ true,
/* Capitalised */ false,
/* Break header */ false,
/* TOC entry */ false,
/* TOC only */ false,
/* Skip before TOC Entry */ false,
/* TOC Indentation */ 8,
/* Number Header */ false,
/* Font */ NULL,
/* TOC Font */ NULL,
},
};
static const char *
ileaf_header[] = {
"<!OPS, Version = 8.0>",
"",
"<!Page Number Stream,",
" Name = \"page\",",
" Starting Page # = Inherit>",
"",
"<!Document,",
" Final Output Device = \"ileaf\",",
" Default Printer = \"nearest-ileaf\",",
" Default Page Stream Name = \"page\">",
"",
"<!Font Definitions,",
" F2 = Thames 12,",
" F3 = Times 12,",
" F4 = Times 6,",
" F5 = Times 10,",
" F6 = Times 12 Bold,",
" F7 = Helvetica 14 Bold,",
" F8 = Symbols 12,",
" F9 = Thames 6,",
" F10 = Times 12 Italic,",
" F11 = Times 12 Bold Italic>",
"",
"<!Page,",
" Bottom Margin = 1 Inches,",
" Left Margin = 1 Inches,",
" Right Margin = 1 Inches,",
" Hyphenation = on,",
" Consecutive Hyphens = 3,",
" Revision Bar Placement = Left,",
" Feathering = off>",
"",
"<!Autonumber Stream, \"footnote\", 1,",
" Level 1 Suffix = \"\">",
"",
"<!Autonumber Stream, \"list\", 1>",
"",
"<!Class, \"bullet\",",
" Top Margin = 0.04 Inches,",
" Bottom Margin = 0.04 Inches,",
" Left Margin = 0.75 Inches,",
" Right Margin = 0.75 Inches,",
" First Indent = -0.25 Inches,",
" Alignment = Left,",
" Font = F3@Z7@Lam,",
" Line Spacing = 1.1606 lines,",
" Left Tab = 0/0.5/1/2/3 Inches,",
" Composition = Optimum,",
" Contents = Prefix>",
"",
"<\"|:bullet\",",
" Hidden = yes,",
" Font = @i*,",
" Subcomponent = yes,",
" Contents = Shared><F8@Z7@Lam>S<F0><Tab>",
"<End Sub><F0>",
"",
"<!Class, \"head\",",
" Top Margin = 0.1777775 Inches,",
" Bottom Margin = 0.05 Inches,",
" Alignment = Left,",
" Font = F7@Z7@Lam,",
" Line Spacing = 1.1434 lines,",
" Allow Page Break Within = no,",
" Allow Page Break After = no,",
" Left Tab = 0/1*3 Inches,",
" Composition = Optimum>",
"",
"<!Class, \"list\",",
" Top Margin = 0.04 Inches,",
" Bottom Margin = 0.04 Inches,",
" Left Margin = 0.75 Inches,",
" Right Margin = 0.75 Inches,",
" First Indent = -0.50 Inches,",
" Alignment = Left,",
" Font = F3@Z7@Lam,",
" Line Spacing = 1.1606 lines,",
" Left Tab = 0/1*3 Inches,",
" Decimal Tab = -0.15 Inches,",
" Composition = Optimum,",
" Contents = Prefix>",
"",
"<\"|:list\",",
" Hidden = yes,",
" Font = @i*,",
" Subcomponent = yes,",
" Contents = Shared><F0><Tab><Autonum, \"list\", 1><Tab>",
"<End Sub><F0>",
"",
"<!Class, \"micro:caption\",",
" Top Margin = 0.03 Inches,",
" Bottom Margin = 0.03 Inches,",
" Alignment = Left,",
" Font = F5@Z7@Lam,",
" Line Spacing = 1.1124 lines,",
" Left Tab = 0/0.5*3 Inches,",
" Composition = Optimum>",
"",
"<!Class, \"micro:ftnote\",",
" Top Margin = 0.0295272 Inches,",
" Bottom Margin = 0.0295272 Inches,",
" Alignment = Left,",
" Font = F5@Z7@Lam,",
" Line Spacing = 1.1124 lines,",
" Left Tab = 0/0.25 Inches,",
" Composition = Optimum>",
"",
"<!Class, \"para\",",
" Top Margin = 0.04 Inches,",
" Bottom Margin = 0.04 Inches,",
" Font = F3@Z7@Lam,",
" Line Spacing = 1.1606 lines,",
" Left Tab = 0/1*3 Inches,",
" Composition = Optimum>",
"",
"<!Class, \"subhead\",",
" Top Margin = 0.06 Inches,",
" Bottom Margin = 0.05 Inches,",
" Alignment = Left,",
" Font = F6@Z7@Lam,",
" Line Spacing = 1.1606 lines,",
" Allow Page Break Within = no,",
" Allow Page Break After = no,",
" Left Tab = 0/1*3 Inches,",
" Composition = Optimum>",
"",
"<!Class, \"|:bullet\",",
" Top Margin = 0.0266667 Inches,",
" Bottom Margin = 0.0266667 Inches,",
" Font = F3@Z7@Lnl@i*,",
" Line Spacing = 1.162 lines,",
" Left Tab = 0/1*3 Inches,",
" Composition = Optimum,",
" Contents = Shared>",
"",
"<F8@Z7@Lnl>S<F0><Tab>",
"",
"<!Class, \"|:list\",",
" Top Margin = 0.0266667 Inches,",
" Bottom Margin = 0.0266667 Inches,",
" Font = F3@Z7@Lnl@i*,",
" Line Spacing = 1.162 lines,",
" Left Tab = 0/1*3 Inches,",
" Composition = Optimum,",
" Contents = Shared>",
"",
"<Tab><Autonum, \"list\", 1><Tab>",
"",
"<!Master Frame,",
" Name = \"floating\",",
" Placement = Following Anchor,",
" Horizontal Alignment = Center,",
" Width = 2 Inches,",
" Width = Page Without Margins,",
" Height = 1 Inches,",
" Height = Page Without Margins * 0.33,",
" Diagram =",
"V11,",
"(g9,0,0,",
" (E16,0,0,,5,1,1,0.0533333,1,15,0,0,1,0,0,0,1,5,127,7,0,0,7,0,1,1,0.0666667,0.06",
" 66667,6,6,0,0.0666667,6))>",
"",
"<!Master Frame,",
" Name = \"footnote:numbered\",",
" Placement = Bottom of Page,",
" Horizontal Alignment = Left,",
" Same Page = yes,",
" Width = 6.2992125 Inches,",
" Width = Column,",
" Size Contents To Width = yes,",
" Height = 0.20 Inches,",
" Height = Contents,",
" Auto Edit = yes,",
" Numbered = '<Autonum, \"footnote\", 1, Tagname = \"EiXYY2e4vr\">',",
" Superscript = yes,",
" Diagram =",
"V11,",
"(g9,1,0,",
" (T15,1,12,,0,0,5,127,5,7,127,1,0,2,",
"<!Page, Width = 6.28 Inches, Height = 0.19837 Inches,",
" Top Margin = 0.03 Inches,",
" Bottom Margin = 0.03 Inches,",
" Revision Bar Placement = Left>",
"<\"micro:ftnote\",",
" Hidden = yes>",
"",
"<Ref, Auto #, Tag = \"EiXYY2e4vr\">.<Tab>",
"",
"<End Text>)",
" (E16,0,0,,5,1,1,0.0533333,1,15,0,0,1,0,0,0,1,5,127,7,0,0,7,0,1,1,0.0666667,0.06",
" 66667,6,6,0,0.0666667,6))>",
"",
"<!Master Frame,",
" Name = \"footnote:unnumbered\",",
" Placement = Bottom of Page,",
" Horizontal Alignment = Left,",
" Same Page = yes,",
" Width = 6.2992125 Inches,",
" Width = Column,",
" Size Contents To Width = yes,",
" Height = 0.1466667 Inches,",
" Height = Contents,",
" Auto Edit = yes,",
" Diagram =",
"V11,",
"(g9,1,0,",
" (T15,1,12,,0.0266667,0.0266667,5,127,5,7,127,1,0,2,",
"<!Page, Width = 6.28 Inches, Height = 0.1383699 Inches,",
" Revision Bar Placement = Left>",
"<\"micro:ftnote\",",
" Hidden = yes>",
"",
"<End Text>)",
" (E16,0,0,,5,1,1,0.0533333,1,15,0,0,1,-0.0266667,-0.0266667,0,1,5,127,7,0,0,7,0,",
" 1,1,0.0666667,0.0666667,6,6,0,0.0666667,6))>",
"",
"<!Master Frame,",
" Name = \"fullpage\",",
" Placement = Overlay,",
" Horizontal Alignment = Center,",
" Vertical Alignment = Center,",
" Horizontal Reference = Page With Both Margins,",
" Vertical Reference = Page With Both Margins,",
" Width = 2 Inches,",
" Width = Page With Both Margins,",
" Height = 1 Inches,",
" Height = Page With Both Margins,",
" Diagram =",
"V11,",
"(g9,0,0,",
" (E16,0,0,,5,1,1,0.0533333,1,15,0,0,1,0,0,0,1,5,127,7,0,0,7,0,1,1,0.0666667,0.06",
" 66667,6,6,0,0.0666667,6))>",
"",
"<!Master Frame,",
" Name = \"inline\",",
" Placement = At Anchor,",
" Width = 0.50 Inches,",
" Height = 0.1655558 Inches,",
" Diagram =",
"V11,",
"(g9,0,0,",
" (E16,0,0,,5,1,1,0.0533333,1,15,0,0,1,0,0,0,1,5,127,7,0,0,7,0,1,1,0.0666667,0.06",
" 66667,6,6,0,0.0666667,6))>",
"",
"<!Master Frame,",
" Name = \"page\",",
" Placement = At Anchor,",
" Vertical Alignment = Top,",
" Width = 2 Inches,",
" Width = Page Without Margins,",
" Height = 1 Inches,",
" Height = Page Without Margins,",
" Diagram =",
"V11,",
"(g9,0,0,",
" (E16,0,0,,5,1,1,0.0533333,1,15,0,0,1,0,0,0,1,5,127,7,0,0,7,0,1,1,0.0666667,0.06",
" 66667,6,6,0,0.0666667,6))>",
"",
"<Page Header, Frame =",
"V11,",
"(g9,1,0,",
" (t14,1,4,,6.4933333,0.4387817,2,7,0,0,,wst:timsps10,)",
" (t14,2,4,,3.2466667,0.4387817,1,7,0,0,,wst:timsps10,)",
" (t14,3,4,,0,0.4387817,0,7,0,0,,wst:timsps10,)",
" (E16,0,0,,5,1,1,0.0533333,1,15,0,0,1,0,0,0,1,5,127,7,0,0,7,0,1,1,0.0666667,0.06",
" 66667,6,6,0,0.0666667,6))>",
"",
"<Page Footer, Frame =",
"V11,",
"(g9,1,0,",
" (t14,1,4,,6.4933333,0.478772,2,7,0,0,,wst:timsps10,)",
" (t14,2,4,,3.2466667,0.478772,1,7,0,0,,wst:timsps10,\\X80a0)",
" (t14,3,4,,0,0.478772,0,7,0,0,,wst:timsps10,)",
" (E16,0,0,,5,1,1,0.0533333,1,15,0,0,1,0,0,0,1,5,127,7,0,0,7,0,1,1,0.0666667,0.06",
" 66667,6,6,0,0.0666667,6))>",
"",
"<!End Declarations>",
};
/*---------------------------------------------------------------------------*/
CDDocument cdoc_document;
int cdoc_pass_no = 0;
FILE *cdoc_input_fp = NULL;
FILEList cdoc_input_fp_list;
int cdoc_input_line_no = 0;
FILE *cdoc_output_fp = NULL;
std::string cdoc_current_section;
int cdoc_indent = 0;
int cdoc_no_centred = 0;
int cdoc_no_uscore = 0;
int cdoc_no_cap = 0;
int cdoc_formatting = true;
CDDefinitionList *cdoc_definition_list = NULL;
CDGeneralList *cdoc_general_list = NULL;
CDGlossaryList *cdoc_glossary_list = NULL;
std::string cdoc_date;
std::string cdoc_footer;
std::string cdoc_line;
int cdoc_line_len;
int cdoc_continuation_char = (int) '\0';
/*---------------------------------------------------------------------------*/
static char cdoc_a_to_z[] = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
static int long_quotation_depth = 0;
static int appendix_depth = 0;
static int header_number[CDOC_MAX_HEADERS];
static CDHeaderControl header_control[CDOC_MAX_HEADERS];
/* Lists */
static char definition_prefix[CDOC_MAX_LINE] = "";
static char list_prefix[CDOC_MAX_LINE] = "";
static std::string glossary_prefix;
/* Tables */
static CDTable *current_table = NULL;
static int table_number = 0;
static CDTableRow *current_row = NULL;
static CDTableCell *current_cell = NULL;
/* Figures */
static CDFigure *current_figure = NULL;
static int figure_number = 0;
/* Examples */
static CDExample *current_example = NULL;
/* Footnotes */
static CDFootnote *current_footnote = NULL;
static int current_footnote_number = 0;
/*---------------------------------------------------------------------------*/
static void CDocScriptInitPass1
();
static int CDocProcessFilePass1
(const std::string &);
static void CDocProcessCommentLinePass1
(const std::string &);
static void CDocProcessDotCommandPass1
(CDDotCommand *);
static void CDocProcessColonCommandPass1
(CDColonCommand *);
static void CDocScriptInitPass2
();
static void CDocProcessFilePass2
(const std::string &);
static void CDocInitialiseOutputPass2
();
static void CDocProcessCommentLinePass2
(const std::string &);
static void CDocProcessPass2Line
(CDScriptLine *);
static void CDocProcessDotCommandPass2
(CDDotCommand *);
static void CDocProcessColonCommandPass2
(CDColonCommand *);
static void CDocReplaceEmbeddedColonCommands
(CDScriptLine *);
static void CDocScriptTerm
();
static void CDocScriptInitHeaders
();
static int CDocScriptHighlightToFont
(int);
static std::string CDocScriptAddHighlightEscapes
(const std::string &, int);
// Converts the input file containing IBM Script commands to the output format
// defined using the CDoc::setOutputFormat() routine and to the file defined
// by CDoc::setOutputFilename().
//
// The output can be customized using the control routines :-
//
// CDocSetScriptMargins()
// CDocSetScriptHeaderNumbering()
// CDocSetScriptWarnings()
// CDocSetScriptParagraphIndent()
extern void
CDocScriptProcessFile(const std::string &filename)
{
/* Save Script Options */
CDocScriptSaveOptions();
/* Initialise State for Pass 1 Processing */
CDocScriptInitPass1();
/* Do Pass 1 of the Script File Processing to Add References
and Set up the Table of Contents. */
int error = CDocProcessFilePass1(filename);
if (error != 0)
goto ProcessFile_1;
/* Initialise State for Pass 2 Processing */
CDocScriptInitPass2();
/* Do Pass 2 of the Script File Processing to actually
* output the processed Script File text */
CDocProcessFilePass2(filename);
/* Terminate Script Processing */
CDocScriptTerm();
ProcessFile_1:
CDocScriptRestoreOptions();
}
// Initialises CDoc ready for Pass 1 Processing of the Script File.
//
// Should set all Static Variables to their Initial Values.
static void
CDocScriptInitPass1()
{
/* Initialise the Document */
cdoc_document.security = "";
cdoc_document.language = "";
cdoc_document.type = CDOC_NO_DOCUMENT;
cdoc_document.part = CDOC_NO_PART;
cdoc_document.sub_part = CDOC_NO_SUB_PART;
/* Initialise Spell Checker if Required */
if (cdoc_spell_check)
cdoc_spell_check = CSpellInit();
if (cdoc_spell_check)
cdoc_spell_active = true;
/* Set Pass Number */
cdoc_pass_no = 1;
/* Initialise Current Input Line Number */
cdoc_input_line_no = 0;
/* Initialise Output File Pointer */
cdoc_output_fp = stdout;
/* Initialise Current Section */
cdoc_current_section = "";
/* Initialise Indent and Formatting */
cdoc_indent = 0;
cdoc_formatting = true;
/* Initialise Lists */
cdoc_definition_list = NULL;
cdoc_general_list = NULL;
cdoc_glossary_list = NULL;
/* Initialise Footer and Current Line */
cdoc_footer = "";
cdoc_line = "";
cdoc_line_len = 0;
/* Initialise Long Quotation Depth */
long_quotation_depth = 0;
/* If Output Filename has been set then open the file
(if possible) and set the Output File Pointer to it */
if (CDocInst->getOutputFilename() != "") {
FILE *fp = fopen(CDocInst->getOutputFilename().c_str(), "w");
if (fp != NULL)
cdoc_output_fp = fp;
}
/* If Page Numbers are required then write to a temporary
file first */
if (cdoc_page_numbering)
CDocScriptPageNoInit();
/* Initialise the References defined in an Extra File */
CDocScriptInitReferences();
/* Initialise Page/Line and Character Counts */
cdoc_page_no = 1;
cdoc_page_no_offset = 0;
cdoc_line_no = 0;
cdoc_char_no = 0;
cdoc_line_fiddle = 0;
cdoc_page_header_output = false;
/* Initialise Processing Control */
CDocScriptInitPCtrl();
/* Reset Dot Command Control Variables */
cdoc_no_centred = 0;
cdoc_no_cap = 0;
cdoc_no_uscore = 0;
/* Initialise Paragraph Data */
CDocScriptInitParagraphs();
/* Initialise the Footnote Variables */
current_footnote_number = 0;
/* Initialise Current Header Level for each of the Levels */
CDocScriptInitHeaders();
/* Initialise Current Figure and Table Details */
current_figure = NULL;
current_table = NULL;
current_row = NULL;
current_cell = NULL;
table_number = 0;
figure_number = 0;
/* Set Current Date String */
time_t current_time = time(¤t_time);
cdoc_date = COSTime::getTimeString(current_time, "%d %h %y");
/* Initialise Current Appendix Depth */
appendix_depth = 0;
/* Set Header Control from Default Header Control */
memcpy(header_control, default_header_control,
CDOC_MAX_HEADERS*sizeof(CDHeaderControl));
/* Set Continuation Character */
cdoc_continuation_char = (int) '\0';
/* Initialise Translations */
CDocScriptInitTranslations();
}
// Perform Pass 1 of the processing of the Script File.
//
// This performs the following functions :-
//
// . Records Information about Commands with Identifiers
// . Builds the Table of Contents
// . Records Information about Figures
// . Process Commands which alter the Initial State
static int
CDocProcessFilePass1(const std::string &filename)
{
CDScriptLine *script_line;
CDDotCommand *dot_command;
CDColonCommand *colon_command;
/* Initialise Error Return Code and Current List Depth */
int error = 0;
/* Open the Script File (Fail if can't be opened) */
cdoc_input_fp = fopen(filename.c_str(), "r");
if (cdoc_input_fp == NULL) {
cdoc_input_fp = stdin;
CDocScriptError("Dataset '%s' cannot be read", filename.c_str());
error = 1;
return(error);
}
/* Read and Process each Line from the File */
while ((script_line = CDocScriptGetNextLine()) != NULL) {
if (script_line->getType() == CDOC_DOT_COMMAND)
dot_command = script_line->getDotCommand();
else if (script_line->getType() == CDOC_COLON_COMMAND)
colon_command = script_line->getColonCommand();
/* Output Line if Debug */
if (CDocInst->getDebug() & CDOC_DEBUG_PASS_1) {
if (! CDocScriptProcessing())
printf("# ");
script_line->print();
}
if (CDocScriptProcessing()) {
/* Check for Comment Line (not a Normal Dot Command)
in which we hide CDoc Specific Commands */
if (script_line->getType() == CDOC_DOT_COMMAND &&
dot_command->getCommand() == "*") {
CDocProcessCommentLinePass1(dot_command->getText());
delete script_line;
continue;
}
/* Replace embedded Symbols in Text */
if (script_line->getType() == CDOC_DOT_COMMAND) {
std::string text = CDocScriptReplaceSymbolsInString(dot_command->getText());
dot_command->setText(text);
}
else if (script_line->getType() == CDOC_COLON_COMMAND) {
std::string text = CDocScriptReplaceSymbolsInString(colon_command->getText());
colon_command->setText(text);
}
/* Process a Line consisting of a Dot Command */
if (script_line->getType() == CDOC_DOT_COMMAND)
CDocProcessDotCommandPass1(dot_command);
/* Process Colon Command */
else if (script_line->getType() == CDOC_COLON_COMMAND)
CDocProcessColonCommandPass1(colon_command);
}
else {
if (script_line->getType() == CDOC_COLON_COMMAND &&
colon_command->getCommand() == "epsc")
CDocScriptEndPCtrl();
}
delete script_line;
}
/* Close File */
fclose(cdoc_input_fp);
cdoc_input_fp_list.clear();
return error;
}
// Process a Script Comment Line on the First Pass through the input IBM Script File.
//
// Looks for CDoc specific commands embedded in the comment and processes them accordingly.
static void
CDocProcessCommentLinePass1(const std::string &comment)
{
if (comment == "")
return;
char *p1 = (char *) comment.c_str();
CStrUtil::skipSpace(&p1);
/* Process CDoc Script Options */
if (strncmp(p1, "cdocopts ", 9) == 0) {
/* Save Initial State of Page Numbering and Spell Check */
int save_page_numbering = cdoc_page_numbering;
int save_spell_check = cdoc_spell_check;
/**********/
/* Parse Options String */
std::vector<std::string> words;
CDocStringToWords(&p1[9], words);
uint no_words = words.size();
if (no_words > 0) {
int no_words1 = no_words;
const char **words1 = new const char * [no_words1];
for (int i = 0; i < no_words1; i++)
words1[i] = words[i].c_str();
CDocScriptProcessOptions(words1, &no_words1);
if (no_words1 != 0)
CDocScriptWarning("Some Options have not been Processed");
delete [] words1;
}
/**********/
/* Initialise Page Numbering and Spell Checking if they have
been turned on inside the document */
if (! save_page_numbering && cdoc_page_numbering)
CDocScriptPageNoInit();
if (! save_spell_check && cdoc_spell_check) {
cdoc_spell_check = CSpellInit();
if (cdoc_spell_check)
cdoc_spell_active = true;
}
}
}
// Process a parsed Dot Command on the First Pass through the input IBM Script File.
static void
CDocProcessDotCommandPass1(CDDotCommand *dot_command)
{
int i;
int j;
int level;
/* If not Processing then ignore command */
if (! CDocScriptProcessing())
return;
/* Process a Header Command (for Table of Contents) */
if (dot_command->getCommand() == "h0" || dot_command->getCommand() == "h1" ||
dot_command->getCommand() == "h2" || dot_command->getCommand() == "h3" ||
dot_command->getCommand() == "h4" || dot_command->getCommand() == "h5" ||
dot_command->getCommand() == "h6") {
/* Create the Header String depending on Header Level and
position in the Document */
std::string temp_string;
/* Calculate the Header Level */
level = (dot_command->getCommand().c_str()[1] - '0') % CDOC_MAX_HEADERS;
/* If header of this level is numbered then precede header
with its header number */
if (header_control[level].number_header) {
int header_no;
CDocScriptStartHeader(level);
/* Create Header Number String */
for (j = 1; j <= level; j++) {
header_no = CDocScriptGetHeader(j);
/* If in Appendix then first Level is a letter otherwise just use a number */
std::string temp_string1;
if (j == 1) {
if (appendix_depth > 0)
CStrUtil::sprintf(temp_string1, "Appendix %c",
cdoc_a_to_z[(header_no - appendix_depth - 1) % 26]);
else
temp_string1 = CStrUtil::toString(header_no);
}
/* All other levels are numbers */
else
temp_string1 = "." + CStrUtil::toString(header_no);
temp_string += temp_string1;
}
/* Add '.0' for First Level Normal Headers and '.'
for First Level Appendix Headers */
if (level == 1) {
if (appendix_depth == 0)
temp_string += ".0";
else
temp_string += ".";
}
/* Add blanks to separate number and header string */
if (level > 0)
temp_string += " ";
}
/* If heading requires a line before it in table of contents
then add it */
if (header_control[level].skip_before_toc_entry)
CDocScriptAddTOCSkip();
/* Add any preceding blanks */
std::string temp_string1;
temp_string1 = temp_string;
temp_string = "";
for (i = 0; i < header_control[level].toc_indentation; i++)
temp_string += " ";
/* If heading causes a section break then make it bold */
if (header_control[level].section_breaks)
temp_string += CDocStartBold();
temp_string += temp_string1;
/* Use Header Number if Global Switch is On */
if (cdoc_number_headers)
temp_string1 = temp_string + dot_command->getText();
else
temp_string1 = dot_command->getText();
if (header_control[level].section_breaks)
temp_string1 + CDocEndBold();
/* Add header string as a content in the table of contents if required */
if (header_control[level].toc_entry)
CDocScriptAddTOCEntry(temp_string1);
}
/* Process a Heading Definition */
else if (dot_command->getCommand() == "dh") {
std::vector<std::string> words;
CDocStringToWords(dot_command->getText(), words);
uint no_words = words.size();
if (no_words >= 2) {
level = CStrUtil::toInteger(words[0]) % CDOC_MAX_HEADERS;
CStrUtil::toLower(words[1]);
std::vector<std::string>::iterator p = words.begin();
std::vector<std::string> words1(++p, words.end());
CDocExtractParameters(words1, dh_parameter_data,
(char *) &header_control[level]);
}
else if (no_words == 1) {
/* Set Header Control from Default Header Control */
level = CStrUtil::toInteger(words[0]) % CDOC_MAX_HEADERS;
memcpy(&header_control[level], &default_header_control[level],
sizeof(CDHeaderControl));
}
else {
/* Set All Header Controls from Default Header Control */
memcpy(header_control, default_header_control,
CDOC_MAX_HEADERS*sizeof(CDHeaderControl));
}
}
/* Macros */
else if (dot_command->getCommand() == "dm") {
CDScriptLine *script_line;
std::vector<std::string> words;
CDocStringToWords(dot_command->getText(), words);
uint no_words = words.size();
if (no_words == 1 && CStrUtil::casecmp(words[0], "off") == 0)
CDocScriptError("End Macro when not in Macro");
else if (no_words == 1 || (no_words == 2 && CStrUtil::casecmp(words[1], "on") == 0)) {
/* Set to Null State (no processing of input test) */
int save_no_uscore = cdoc_no_uscore;
int save_no_cap = cdoc_no_cap;
int save_no_centred = cdoc_no_centred;
int save_formatting = cdoc_formatting;
cdoc_no_uscore = 0;
cdoc_no_cap = 0;
cdoc_no_centred = 0;
cdoc_formatting = false;
CDMacro *macro = CDocScriptCreateMacro(words[0]);
while ((script_line = CDocScriptGetNextLine()) != NULL) {
if (script_line->getType() == CDOC_DOT_COMMAND) {
dot_command = script_line->getDotCommand();
if (dot_command->getCommand() == "dm") {
std::vector<std::string> words1;
CDocStringToWords(dot_command->getText(), words1);
uint no_words1 = words1.size();
if (no_words1 != 1 || CStrUtil::casecmp(words1[0], "off") != 0)
CDocScriptError("Nested Macro Definitions not allowed");
delete script_line;
break;
}
CDocScriptAddMacroLine(macro, script_line);
}
else
CDocScriptAddMacroLine(macro, script_line);
}
/* Restore Original State */
cdoc_no_uscore = save_no_uscore;
cdoc_no_cap = save_no_cap;
cdoc_no_centred = save_no_centred;
cdoc_formatting = save_formatting;
}
}
/* Process Label */
else if (dot_command->getCommand() == "..")
CDocScriptAddLabel(dot_command->getText());
/* Symbols */
else if (dot_command->getCommand() == "se")
CDocScriptParseSymbol(dot_command->getText());
else if (dot_command->getCommand() == "dv")
CDocScriptParseDefineVariable(dot_command->getText());
/* Translations */
else if (dot_command->getCommand() == "ti")
CDocScriptParseTranslation(dot_command->getText());
/* Define Character */
else if (dot_command->getCommand() == "dc") {
std::vector<std::string> words;
CDocStringToWords(dot_command->getText(), words);
uint no_words = words.size();
if (no_words > 0) {
CStrUtil::toLower(words[0]);
if (words[0] == "cont") {
if (no_words == 2) {
if (CStrUtil::casecmp(words[1], "off") == 0)
cdoc_continuation_char = (int) '\0';
else if (words[1].size() == 1)
cdoc_continuation_char = (int) words[1][0];
else
CDocScriptError("Invalid Continuation Character '%s'", words[1].c_str());
}
else
CDocScriptError("Invalid Continuation Character Definition");
}
else
CDocScriptError("Define Character not Supported for '%s'", words[0].c_str());
}
else
CDocScriptError("Invalid Define Character Command");
}
/* External Datasets */
else if (dot_command->getCommand() == "dd") {
std::vector<std::string> words;
CDocStringToWords(dot_command->getText(), words);
uint no_words = words.size();
if (no_words != 2) {
CDocScriptError("Invalid CDoc Define Dataset Command .%s %s",
dot_command->getCommand().c_str(), dot_command->getText().c_str());
return;
}
CDocScriptDefineDataset(words[0], words[1]);
}
else if (dot_command->getCommand() == "im") {
std::vector<std::string> words;
CDocStringToWords(dot_command->getText(), words);
uint no_words = words.size();
if (no_words != 1) {
CDocScriptError("Invalid CDoc Imbed Dataset Command .%s %s",
dot_command->getCommand().c_str(), dot_command->getText().c_str());
return;
}
FILE *fp = CDocScriptImbedDataset(words[0]);
if (fp != NULL) {
cdoc_input_fp_list.push_back(cdoc_input_fp);
cdoc_input_fp = fp;
}
else
CDocScriptError("Failed to Open Imbed File '%s'", words[0].c_str());
}
}
// Process a parsed Colon Command on the First Pass through the input IBM Script File.
static void
CDocProcessColonCommandPass1(CDColonCommand *colon_command)
{
static int list_no = 0;
static int list_type[MAX_LISTS];
static int list_depth[MAX_LISTS];
int i;
int j;
int level;
/* Process Specific Control Blocks */
if (colon_command->getCommand() == "psc")
CDocScriptStartPCtrl(colon_command);
else if (colon_command->getCommand() == "epsc")
CDocScriptEndPCtrl();
/* Process a Header Command */
else if (colon_command->getCommand()[0] == 'h' &&
isdigit(colon_command->getCommand()[1])) {
CDHeading heading;
heading.ident = NULL;
heading.stitle = NULL;
/* Calculate the Header Level */
level = (colon_command->getCommand()[1] - '0') % CDOC_MAX_HEADERS;
/* Get Parameter/Value pairs */
if (level == 0 || level == 1)
CDocExtractParameterValues(colon_command->getParameters(),
colon_command->getValues(),
h01_parameter_data,
(char *) &heading);
else
CDocExtractParameterValues(colon_command->getParameters(),
colon_command->getValues(),
h26_parameter_data,
(char *) &heading);
/* If we have a reference identifier then add it to the
reference list */
if (heading.ident != NULL)
CDocScriptAddReference(HEADER_REF, heading.ident, colon_command->getText(), "");
/* Create the Header String depending on Header Level and
position in the Document */
std::string temp_string;
/* If header of this level is numbered and in the body
or appendix section then precede header with its header number */
if (header_control[level].number_header &&
(cdoc_document.part == CDOC_BODY_PART || cdoc_document.part == CDOC_APPENDIX_PART)) {
int header_no;
CDocScriptStartHeader(level);
/* Create Header Number String */
for (j = 1; j <= level; j++) {
header_no = CDocScriptGetHeader(j);
/* If in Appendix then first Level is a letter
otherwise just use a number */
std::string temp_string1;
if (j == 1) {
if (appendix_depth > 0)
CStrUtil::sprintf(temp_string1, "Appendix %c",
cdoc_a_to_z[(header_no - appendix_depth - 1) % 26]);
else
temp_string1 = CStrUtil::toString(header_no);
}
/* All other levels are numbers */
else
temp_string1 = "." + CStrUtil::toString(header_no);
temp_string += temp_string1;
}
/* Add '.0' for First Level Normal Headers and '.'
for First Level Appendix Headers */
if (level == 1) {
if (appendix_depth == 0)
temp_string += ".0";
else
temp_string += ".";
}
/* Add blanks to separate number and header string */
if (level > 0)
temp_string += " ";
}
/* If heading requires a line before it in table of contents
then add it */
if (header_control[level].skip_before_toc_entry)
CDocScriptAddTOCSkip();
/* Add any preceding blanks */
std::string temp_string1;
temp_string1 = temp_string;
temp_string = "";
for (i = 0; i < header_control[level].toc_indentation; i++)
temp_string += " ";
/* If heading causes a section break then make it bold */
if (header_control[level].section_breaks)
temp_string += CDocStartBold();
temp_string += temp_string1;
/* Use Header Number if Global Switch is On */
if (cdoc_number_headers)
temp_string1 = temp_string + colon_command->getText();
else
temp_string1 = colon_command->getText();
if (header_control[level].section_breaks)
temp_string1 += CDocEndBold();
/* Add header string as a content in the table of contents if required */
if (header_control[level].toc_entry)
CDocScriptAddTOCEntry(temp_string1);
}
/* Footnotes */
else if (colon_command->getCommand() == "fn") {
/* Get Footnote Parameter Values */
CDFootnoteData footnote_data;
footnote_data.ident = NULL;
CDocExtractParameterValues(colon_command->getParameters(),
colon_command->getValues(),
fn_parameter_data,
(char *) &footnote_data);
CDFootnote footnote;
footnote.ident = (footnote_data.ident ? std::string(footnote_data.ident) : "");
footnote.number = ++current_footnote_number;
std::string temp_string;
if (CDocInst->getOutputFormat() == CDOC_OUTPUT_HTML)
CStrUtil::sprintf(temp_string, "{%d}", footnote.number);
else
CStrUtil::sprintf(temp_string, "%s{%d}%s",
CDocStartBold(), footnote.number, CDocEndBold());
if (footnote.ident != "")
CDocScriptAddReference(FOOTNOTE_REF, footnote.ident, temp_string, "");
}
/* Set the list type and current item number in this list
for the start of an ordered, simple or unordered list
and increment the list number */
else if (colon_command->getCommand() == "ol") {
list_type [list_no] = ORDERED_LIST;
list_depth[list_no] = 0;
list_no++;
}
else if (colon_command->getCommand() == "sl") {
list_type [list_no] = SIMPLE_LIST;
list_depth[list_no] = 0;
list_no++;
}
else if (colon_command->getCommand() == "ul") {
list_type [list_no] = UNORDERED_LIST;
list_depth[list_no] = 0;
list_no++;
}
/* Decrement the list number for the end of an ordered,
simple or unordered list */
else if (colon_command->getCommand() == "eol") {
if (list_no > 0)
list_no--;
}
else if (colon_command->getCommand() == "esl") {
if (list_no > 0)
list_no--;
}
else if (colon_command->getCommand() == "eul") {
if (list_no > 0)
list_no--;
}
/* Increment the item number of the current list and add a
reference to this list item if a reference identifier is present */
else if (colon_command->getCommand() == "li") {
CDListItem list_item;
if (list_no > 0)
list_depth[list_no - 1]++;
/* Get Parameter/Value pairs */
list_item.ident = NULL;
CDocExtractParameterValues(colon_command->getParameters(),
colon_command->getValues(),
li_parameter_data,
(char *) &list_item);
/* If we have a reference identifier and an ordered list then
use the list item number (created from the depths of each
item in each ordered list currently active), otherwise use
a NULL reference to indicate we have no str to use to
reference this item */
if (list_item.ident != NULL) {
std::string temp_string;
if (list_no > 0) {
if (list_type[list_no - 1] == ORDERED_LIST) {
for (j = 0; j < list_no; j++) {
if (list_type[j] == ORDERED_LIST) {
char temp_string1[33];
sprintf(temp_string1, "%d.", list_depth[j]);
temp_string += temp_string1;
}
}
}
}
/* Add the reference to the list */
CDocScriptAddReference(LIST_ITEM_REF, list_item.ident, temp_string,
colon_command->getText());
}
}
/* If we have a Figure List then add it to the Table of
Contents for Stairs Document */
else if (colon_command->getCommand() == "figlist") {
if (cdoc_document.type == CDOC_STAIRS_DOCUMENT) {
CDocScriptStartHeader(1);
std::string temp_string;
CStrUtil::sprintf(temp_string,
"%s%d.0 List of Illustrations%s",
CDocStartBold(), CDocScriptGetHeader(1), CDocEndBold());
CDocScriptAddTOCSkip();
CDocScriptAddTOCEntry(temp_string);
}
}
/* If we have a figure then save its details in a structure
added to the figure list (for later output in the figure
list in Pass 2). */
else if (colon_command->getCommand() == "fig") {
/* Create the figure details structure to store
the details in */
current_figure = CDocScriptCreateFigure();
CDFigureData figure_data;
figure_data.depth = 0;
figure_data.frame = NULL;
figure_data.ident = NULL;
figure_data.indent = 0;
figure_data.place = 0;
figure_data.width = 0;
/* Process the Parameter/Value pairs to fill in the
rest of the data in the figure details structure */
CDocExtractParameterValues(colon_command->getParameters(),
colon_command->getValues(),
fig_parameter_data,
(char *) &figure_data);
current_figure->depth = figure_data.depth;
current_figure->frame = figure_data.frame;
current_figure->ident = (figure_data.ident ? std::string(figure_data.ident) : "");
current_figure->indent = figure_data.indent;
current_figure->place = figure_data.place;
current_figure->width = figure_data.width;
}
/* If we have a figure caption then set this value in the
figure details structure (if we have one) and if there
if a reference identification for this figure use the
caption as the reference str */
else if (colon_command->getCommand() == "figcap") {
if (current_figure != NULL) {
current_figure->caption = colon_command->getText();
if (current_figure->count == -1)
current_figure->count = ++figure_number;
if (current_figure->ident != "") {
/* Create the reference string */
std::string temp_string;
CStrUtil::sprintf(temp_string, "Figure %d.", current_figure->count);
/* Create the reference structure */
CDocScriptAddReference(FIGURE_REF, current_figure->ident, temp_string, "");
}
}
}
/* If we have a figure description then set this value in the
figure details structure (if we have one). */
else if (colon_command->getCommand() == "figdesc") {
if (current_figure != NULL) {
if (current_figure->count == -1)
current_figure->count = ++figure_number;
current_figure->description = colon_command->getText();
}
}
/* If we have reached the end of the figure deactivate it */
else if (colon_command->getCommand() == "efig") {
current_figure = NULL;
}
/* If we have a Table List then add it to the Table of
Contents for Stairs Document */
else if (colon_command->getCommand() == "tlist") {
if (cdoc_document.type == CDOC_STAIRS_DOCUMENT) {
CDocScriptStartHeader(1);
std::string temp_string;
CStrUtil::sprintf(temp_string,
"%s%d.0 List of Tables%s",
CDocStartBold(), CDocScriptGetHeader(1), CDocEndBold());
CDocScriptAddTOCSkip();
CDocScriptAddTOCEntry(temp_string);
}
}
/* If we have a table then save its details in a structure
added to the table list (for later output in the table
list in Pass 2). */
else if (colon_command->getCommand() == "table") {
/* Create the table details structure to store the details in */
current_table = CDocScriptCreateTable();
/* Process the Parameter/Value pairs to fill in the
rest of the data in the table details structure */
CDTableData table_data;
table_data.column = 0;
table_data.id = NULL;
table_data.page = 0;
table_data.refid = NULL;
table_data.split = 0;
table_data.rotate = 0;
table_data.width = 0;
CDocExtractParameterValues(colon_command->getParameters(),
colon_command->getValues(),
table_parameter_data,
(char *) &table_data);
current_table->refid = (table_data.refid ? table_data.refid : "");
current_table->id = (table_data.id ? table_data.id : "");
//current_table->column = table_data.column;
//current_table->page = table_data.page;
current_table->split = table_data.split;
current_table->rotate = table_data.rotate;
current_table->width = table_data.width;
/* Check Parameter/Value pairs */
if (current_table->rotate != 0 && current_table->rotate != 90 &&
current_table->rotate != 180 && current_table->rotate != 270 &&
current_table->rotate != -90 && current_table->rotate != -180 &&
current_table->rotate != -270) {
CDocScriptWarning("Invalid Value for Table Rotation %d", current_table->rotate);
current_table->rotate = 0;
}
}
/* If we have a table caption then set this value in the
table details structure (if we have one) and if there
if a reference identification for this table use the
caption as the reference str */
else if (colon_command->getCommand() == "tcap") {
if (current_table != NULL) {
current_table->caption = CStrUtil::strdup(colon_command->getText().c_str());
if (current_table->count == -1)
current_table->count = ++table_number;
if (current_table->id != "") {
/* Create the reference string */
std::string temp_string;
CStrUtil::sprintf(temp_string, "Table %d.", current_table->count);
/* Create the reference structure */
CDocScriptAddReference(TABLE_REF, current_table->id, temp_string, "");
}
}
}
/* If we have a table description then set this value in the
table details structure (if we have one). */
else if (colon_command->getCommand() == "tdesc") {
if (current_table != NULL) {
if (current_table->count == -1)
current_table->count = ++table_number;
current_table->description = CStrUtil::strdup(colon_command->getText().c_str());
}
}
/* If we have reached the end of the table deactivate it */
else if (colon_command->getCommand() == "etable") {
current_table = NULL;
}
/* Index */
else if (colon_command->getCommand() == "index") {
if (cdoc_index) {
CDocScriptAddTOCSkip();
std::string temp_string;
CStrUtil::sprintf(temp_string, "%sIndex%s", CDocStartBold(), CDocEndBold());
CDocScriptAddTOCEntry(temp_string);
}
}
else if (colon_command->getCommand()[0] == 'i' &&
(colon_command->getCommand()[1] == '1' ||
colon_command->getCommand()[1] == '2' ||
colon_command->getCommand()[1] == '3')) {
if (cdoc_index) {
CDIndexEntry index_entry;
index_entry.ident = NULL;
index_entry.page = NULL;
index_entry.refid = NULL;
if (colon_command->getCommand()[1] == '1')
CDocExtractParameterValues(colon_command->getParameters(),
colon_command->getValues(),
i1_parameter_data,
(char *) &index_entry);
else
CDocExtractParameterValues(colon_command->getParameters(),
colon_command->getValues(),
i23_parameter_data,
(char *) &index_entry);
std::string ident = (index_entry.ident ? std::string(index_entry.ident) : "");
std::string refid = (index_entry.refid ? std::string(index_entry.refid) : "");
if (colon_command->getCommand()[1] == '1')
CDocScriptAddIndex1(colon_command->getText(), ident, refid);
else if (colon_command->getCommand()[1] == '2')
CDocScriptAddIndex2(colon_command->getText(), ident, refid);
else
CDocScriptAddIndex3(colon_command->getText(), ident, refid);
}
}
else if (colon_command->getCommand()[0] == 'i' &&
colon_command->getCommand()[1] == 'h' &&
(colon_command->getCommand()[2] == '1' ||
colon_command->getCommand()[2] == '2' ||
colon_command->getCommand()[2] == '3')) {
if (cdoc_index) {
CDIndexEntryHeading index_entry_heading;
index_entry_heading.ident = NULL;
index_entry_heading.print = NULL;
index_entry_heading.see = NULL;
index_entry_heading.seeid = NULL;
CDocExtractParameterValues(colon_command->getParameters(),
colon_command->getValues(),
ih_parameter_data,
(char *) &index_entry_heading);
std::string ident = (index_entry_heading.ident ? std::string(index_entry_heading.ident) : "");
std::string print = (index_entry_heading.print ? std::string(index_entry_heading.print) : "");
std::string see = (index_entry_heading.see ? std::string(index_entry_heading.see ) : "");
std::string seeid = (index_entry_heading.seeid ? std::string(index_entry_heading.seeid) : "");
if (colon_command->getCommand()[2] == '1')
CDocScriptAddIndexHeader1(colon_command->getText(), ident, print, see, seeid);
else if (colon_command->getCommand()[2] == '2')
CDocScriptAddIndexHeader2(colon_command->getText(), ident, print, see, seeid);
else
CDocScriptAddIndexHeader3(colon_command->getText(), ident, print, see, seeid);
}
}
/* If we are in the appendix then record the current header
depth as the appendix header start depth */
else if (colon_command->getCommand() == "appendix") {
cdoc_document.part = CDOC_APPENDIX_PART;
appendix_depth = CDocScriptGetHeader(1);
}
/* If we are out of the appendix then reset the appendix
header start depth to unset */
else if (colon_command->getCommand() == "eappendix") {
cdoc_document.part = CDOC_NO_PART;
appendix_depth = 0;
}
/* If we are starting a new document section (effectively
ending the appendix then reset the appendix header
start depth to unset */
else if (colon_command->getCommand() == "frontm") {
cdoc_document.part = CDOC_FRONT_MATTER_PART;
appendix_depth = 0;
}
else if (colon_command->getCommand() == "body") {
cdoc_document.part = CDOC_BODY_PART;
appendix_depth = 0;
}
else if (colon_command->getCommand() == "backm") {
cdoc_document.part = CDOC_BACK_MATTER_PART;
appendix_depth = 0;
}
/* If we are setting the document type then save it */
else if (colon_command->getCommand() == "gdoc")
cdoc_document.type = CDOC_GENERAL_DOCUMENT;
else if (colon_command->getCommand() == "sdoc")
cdoc_document.type = CDOC_STAIRS_DOCUMENT;
else if (colon_command->getCommand() == "memo")
cdoc_document.type = CDOC_MEMO_DOCUMENT;
}
// Initialises CDoc ready for Pass 2 Processing of the Script File.
// This routines restores variables corrupted by Pass 1.
static void
CDocScriptInitPass2()
{
/* Set Pass Number */
cdoc_pass_no = 2;
/* Initialise Current Input Line Number */
cdoc_input_line_no = 0;
/* Initialise Page/Line and Character Counts */
cdoc_page_no = 1;
cdoc_page_no_offset = 0;
cdoc_line_no = 0;
cdoc_char_no = 0;
cdoc_line_fiddle = 0;
cdoc_page_header_output = false;
/* Initialise Processing Control */
CDocScriptInitPCtrl();
/* Reset Dot Command Control Variables */
cdoc_no_centred = 0;
cdoc_no_cap = 0;
cdoc_no_uscore = 0;
/* Re-Initialise Current Header Level for each of the Levels */
CDocScriptInitHeaders();
/* Initialise Footnote Variables */
current_footnote = NULL;
/* Re-Initialise Current Figure and Table Details */
current_figure = NULL;
current_table = NULL;
current_cell = NULL;
figure_number = 0;
table_number = 0;
/* Set Header Control from Default Header Control */
memcpy(header_control, default_header_control,
CDOC_MAX_HEADERS*sizeof(CDHeaderControl));
/* Set Continuation Character */
cdoc_continuation_char = (int) '\0';
/* Initialise Translations */
CDocScriptInitTranslations();
}
// Perform Pass 2 of the processing of the Script File.
//
// This pass actually processes and outputs the text built from the Script
// commands using the information collected in Pass 1.
static void
CDocProcessFilePass2(const std::string &filename)
{
/* Open File (fail if can't be opened) */
cdoc_input_fp = fopen(filename.c_str(), "r");
if (cdoc_input_fp == NULL) {
cdoc_input_fp = stdin;
return;
}
/* Output Initialisation Code required by the current output format */
CDocInitialiseOutputPass2();
/* Read and process each line from the dataset */
CDScriptLine *script_line = NULL;
while ((script_line = CDocScriptGetNextLine()) != NULL) {
CDDotCommand *dot_command = NULL;
CDColonCommand *colon_command = NULL;
if (script_line->getType() == CDOC_DOT_COMMAND)
dot_command = script_line->getDotCommand();
else if (script_line->getType() == CDOC_COLON_COMMAND)
colon_command = script_line->getColonCommand();
/* Output Line if Debug */
if (CDocInst->getDebug() & CDOC_DEBUG_PASS_2) {
if (! CDocScriptProcessing())
printf("# ");
script_line->print();
}
if (CDocScriptProcessing()) {
/* Check for Comment Line (not a Normal Dot Command)
in which we hide CDoc Specific Commands */
if (script_line->getType() == CDOC_DOT_COMMAND &&
dot_command->getCommand() == "*") {
CDocProcessCommentLinePass2(dot_command->getText());
delete script_line;
continue;
}
/* Replace embedded Colon Commands with the required Text */
CDocReplaceEmbeddedColonCommands(script_line);
/* Replace embedded Symbols in Text */
if (script_line->getType() == CDOC_DOT_COMMAND) {
std::string text = CDocScriptReplaceSymbolsInString(dot_command->getText());
dot_command->setText(text);
}
else if (script_line->getType() == CDOC_COLON_COMMAND) {
std::string text = CDocScriptReplaceSymbolsInString(colon_command->getText());
colon_command->setText(text);
}
else
script_line->setData(script_line->getType(),
CDocScriptReplaceSymbolsInString(script_line->getData()));
/* Process the converted line */
CDocProcessPass2Line(script_line);
}
else {
if (script_line->getType() == CDOC_COLON_COMMAND &&
colon_command->getCommand() == "epsc")
CDocScriptEndPCtrl();
}
/* Delete the Script Line */
delete script_line;
}
/* Make Sure Script Block Commands are Terminated */
if (cdoc_document.part == CDOC_FRONT_SHEET_PART) {
CDocScriptWarning("Unterminated Front Sheet");
CDocScriptOutputFrontSheet();
}
else if (cdoc_document.part == CDOC_MEMO_HEADER_PART) {
CDocScriptWarning("Unterminated Memo Header");
CDocScriptOutputMemoHeader();
}
else if (cdoc_document.part == CDOC_AMENDMENTS_PART) {
CDocScriptWarning("Unterminated Amendments");
CDocScriptTermAmendments();
}
if (current_table != NULL) {
CDocScriptWarning("Unterminated Table");
CDocScriptOutputTable(current_table);
if (current_table->id != "")
CDocScriptSetReferencePageNumber(TABLE_REF, current_table->id);
CDocScriptSetTablePage(current_table);
}
if (current_figure != NULL) {
CDocScriptWarning("Unterminated Figure");
CDocScriptFigureEnd(current_figure);
}
if (current_footnote != NULL) {
CDocScriptWarning("Unterminated Footnote");
CDocScriptEndFootnote(current_footnote);
if (current_footnote->ident != "")
CDocScriptSetReferencePageNumber(FOOTNOTE_REF, current_footnote->ident);
}
if (long_quotation_depth != 0)
CDocScriptWarning("Unterminated Long Quotation");
/* Ensure any unfinished paragraphs are output as we have reached
the end of the file */
if (cdoc_in_paragraph)
CDocScriptOutputParagraph();
/* Output any Footnotes */
CDocScriptOutputFootnotes(true);
/* Output any Top Figures */
while (CDocScriptIsTopFigure()) {
CDocScriptStartNewPage();
CDocScriptOutputTopFigure();
}
/* Close the File */
fclose(cdoc_input_fp);
cdoc_input_fp_list.clear();
/* Free off allocated Paragraph Buffer */
cdoc_paragraph->setText("");
/* If we have any unterminated ordered, simple or unordered
lists then output a warning message */
if (CDocScriptIsCurrentList()) {
if (CDocScriptIsCurrentListType(ORDERED_LIST))
CDocScriptWarning("Unterminated Ordered List");
else if (CDocScriptIsCurrentListType(SIMPLE_LIST))
CDocScriptWarning("Unterminated Simple List");
else if (CDocScriptIsCurrentListType(UNORDERED_LIST))
CDocScriptWarning("Unterminated Unordered List");
else if (CDocScriptIsCurrentListType(GLOSSARY_LIST))
CDocScriptWarning("Unterminated Glossary List");
else
CDocScriptWarning("Unterminated List");
}
/* If we have any unterminated definition lists then
output a warning message */
if (cdoc_definition_list != NULL)
CDocScriptWarning("Unterminated Definition List");
}
// Output setup commands required to correctly initialise the output for the
// specified format.
static void
CDocInitialiseOutputPass2()
{
/* Initialise Troff */
if (CDocInst->getOutputFormat() == CDOC_OUTPUT_TROFF) {
/* Set Line Length, Page Length and Point Size */
CDocScriptWriteCommand(".ll 5.8i\n");
CDocScriptWriteCommand(".pl 10.0i\n");
CDocScriptWriteCommand(".ps 11\n");
/* Define Underscore Macro */
CDocScriptWriteCommand(".de US\n");
CDocScriptWriteCommand("\\\\$1\\l\'|0\\(ul\'\n");
CDocScriptWriteCommand("..\n");
/* Define Bold Macro */
CDocScriptWriteCommand(".de BD\n");
CDocScriptWriteCommand("\\fB\\\\$1\\fP\n");
CDocScriptWriteCommand("..\n");
/* Define Bold Underscore Macro */
CDocScriptWriteCommand(".de BU\n");
CDocScriptWriteCommand("\\fB\\\\$1\\l\'|0\\(ul\'\\fP\n");
CDocScriptWriteCommand("..\n");
/* Define Right Justify Macro */
CDocScriptWriteCommand(".de RN\n");
CDocScriptWriteCommand(".ti 5.8i\n");
CDocScriptWriteCommand("\\h\'-(\\w\'\\\\$1\'u)'\\\\$1\n");
CDocScriptWriteCommand("..\n");
/* Define Right Justify Underscore Macro */
CDocScriptWriteCommand(".de RU\n");
CDocScriptWriteCommand(".ti 5.8i\n");
CDocScriptWriteCommand(
"\\h\'-(\\w\'\\\\$1\'u)\'\\\\$1\\l\'-(\\w\'\\\\$1\'u)\\(ul\'\n");
CDocScriptWriteCommand("..\n");
/* Define Right Justify Bold Macro */
CDocScriptWriteCommand(".de RB\n");
CDocScriptWriteCommand(".ti 5.8i\n");
CDocScriptWriteCommand("\\fB\\h\'-(\\w\'\\\\$1\'u)\'\\\\$1\\fP\n");
CDocScriptWriteCommand("..\n");
/* Define Right Justify Bold Underscore Macro */
CDocScriptWriteCommand(".de RE\n");
CDocScriptWriteCommand(".ti 5.8i\n");
CDocScriptWriteCommand(
"\\fB\\h\'-(\\w\'\\\\$1\'u)\'\\\\$1\\l\'-(\\w\'\\\\$1\'u)\\(ul\'\\fP\n");
CDocScriptWriteCommand("..\n");
CDocScriptWriteCommand("\n");
}
/* Initialise CDoc */
else if (CDocInst->getOutputFormat() == CDOC_OUTPUT_CDOC) {
CDocScriptWriteCommand(CDOC_LEFT_MARGIN_TMPL , cdoc_left_margin );
CDocScriptWriteCommand(CDOC_RIGHT_MARGIN_TMPL, cdoc_right_margin );
CDocScriptWriteCommand(CDOC_PAGE_LENGTH_TMPL , cdoc_lines_per_page);
CDocScriptWriteCommand(CDOC_DEF_FONT_TMPL , "cdocsym",
"-*-symbol-*-*-*-*-13-*-*-*-*-*-*-*");
}
/* Initialise HTML */
else if (CDocInst->getOutputFormat() == CDOC_OUTPUT_HTML) {
CDocScriptWriteCommand("<html>\n");
CDocScriptWriteCommand("<head>\n");
CDocScriptWriteCommand("<title>%s</title>\n", "HTML Document");
CDocScriptWriteCommand("</head>\n");
CDocScriptWriteCommand("<body>\n");
}
/* Initialise Interleaf */
else if (CDocInst->getOutputFormat() == CDOC_OUTPUT_ILEAF) {
for (uint i = 0; i < sizeof(ileaf_header)/sizeof(char *); i++)
CDocScriptWriteCommand("%s\n", ileaf_header[i]);
}
}
// Process a Script Comment Line on the Second Pass through the input IBM
// Script File.
//
// Looks for CDoc specific commands embedded in the comment and processes
// them accordingly.
static void
CDocProcessCommentLinePass2(const std::string &comment)
{
char *p1 = (char *) comment.c_str();
if (*p1 == '\0')
return;
CStrUtil::skipSpace(&p1);
/* Check for CDoc Control Word */
if (strncmp(p1, "cdoc", 4) == 0) {
/* Flush Paragraph to ensure any CDoc Controlled
output appears in the correct position */
if (cdoc_in_paragraph)
CDocScriptOutputParagraph();
/* Output CDoc specific control line */
if (strncmp(&p1[4], "cdoc ", 5) == 0) {
if (CDocInst->getOutputFormat() == CDOC_OUTPUT_CDOC)
CDocScriptWriteCommand("%s\n", &p1[9]);
}
/* Output Troff specific control line */
else if (strncmp(&p1[4], "troff ", 6) == 0) {
if (CDocInst->getOutputFormat() == CDOC_OUTPUT_TROFF)
CDocScriptWriteCommand("%s\n", &p1[10]);
}
/* Output HTML specific control line */
else if (strncmp(&p1[4], "html ", 5) == 0) {
if (CDocInst->getOutputFormat() == CDOC_OUTPUT_HTML)
CDocScriptWriteCommand("%s\n", &p1[9]);
}
/* Output Interleaf specific control line */
else if (strncmp(&p1[4], "ileaf ", 6) == 0) {
if (CDocInst->getOutputFormat() == CDOC_OUTPUT_ILEAF)
CDocScriptWriteCommand("%s\n", &p1[9]);
}
/* Output Raw with Control Codes specific control line */
else if (strncmp(&p1[4], "rawcc ", 6) == 0) {
if (CDocInst->getOutputFormat() == CDOC_OUTPUT_RAW_CC)
CDocScriptWriteCommand("%s\n", &p1[10]);
}
/* Output Raw specific control line */
else if (strncmp(&p1[4], "raw ", 4) == 0) {
if (CDocInst->getOutputFormat() == CDOC_OUTPUT_RAW)
CDocScriptWriteCommand("%s\n", &p1[8]);
}
/* Process CDoc Script Options */
else if (strncmp(&p1[4], "opts ", 5) == 0) {
std::vector<std::string> words;
CDocStringToWords(&p1[9], words);
uint no_words = words.size();
if (no_words > 0) {
int no_words1 = no_words;
const char **words1 = new const char * [no_words1];
for (int i = 0; i < no_words1; i++)
words1[i] = words[i].c_str();
CDocScriptProcessOptions(words1, &no_words1);
delete [] words1;
}
}
/* Output Generic control line */
else if (p1[4] != '\0' && isspace(p1[4])) {
CDocScriptWriteCommand("%s\n", &p1[5]);
}
/* Any other Format is an Error */
else
CDocScriptError("Invalid CDoc Control Line %s", p1);
}
}
// Process the Commands defined by the supplied Script Line structure.
static void
CDocProcessPass2Line(CDScriptLine *script_line)
{
/* Process Dot Command */
if (script_line->getType() == CDOC_DOT_COMMAND)
CDocProcessDotCommandPass2(script_line->getDotCommand());
/* Process Colon Command */
else if (script_line->getType() == CDOC_COLON_COMMAND)
CDocProcessColonCommandPass2(script_line->getColonCommand());
/* Process Ordinary Text */
else if (script_line->getType() == CDOC_CENTRED_TEXT) {
if (cdoc_in_paragraph) {
if (cdoc_paragraph->getFormatted() ||
cdoc_paragraph->getJustification() != CENTRE_JUSTIFICATION) {
CDocScriptOutputParagraph();
if (script_line->getData()[0] != '\0') {
if (CDocScriptIsCurrentList())
CDocScriptNewParagraph(script_line->getData(), SUB_LIST_PARAGRAPH1,
false, CENTRE_JUSTIFICATION);
else
CDocScriptNewParagraph(script_line->getData(), NORMAL_PARAGRAPH,
false, CENTRE_JUSTIFICATION);
}
}
else {
CDocScriptAddStringToParagraph("\n");
CDocScriptAddStringToParagraph(script_line->getData());
}
}
else {
if (CDocScriptIsCurrentList())
CDocScriptNewParagraph(script_line->getData(), SUB_LIST_PARAGRAPH1,
false, CENTRE_JUSTIFICATION);
else
CDocScriptNewParagraph(script_line->getData(), NORMAL_PARAGRAPH,
false, CENTRE_JUSTIFICATION);
}
}
else if (script_line->getType() == CDOC_RAW_TEXT) {
/* If in a paragraph then add as a new line */
if (cdoc_in_paragraph) {
if (cdoc_paragraph->getFormatted() ||
cdoc_paragraph->getJustification() != LEFT_JUSTIFICATION) {
CDocScriptOutputParagraph();
if (script_line->getData()[0] != '\0') {
if (CDocScriptIsCurrentList())
CDocScriptNewParagraph(script_line->getData(), SUB_LIST_PARAGRAPH1,
false, LEFT_JUSTIFICATION);
else
CDocScriptNewParagraph(script_line->getData(), NORMAL_PARAGRAPH,
false, LEFT_JUSTIFICATION);
}
}
else {
CDocScriptAddStringToParagraph("\n");
CDocScriptAddStringToParagraph(script_line->getData());
}
}
/* If not in a paragraph then start a new unformatted
paragraph */
else {
if (CDocScriptIsCurrentList())
CDocScriptNewParagraph(script_line->getData(), SUB_LIST_PARAGRAPH1,
false, LEFT_JUSTIFICATION);
else
CDocScriptNewParagraph(script_line->getData(), NORMAL_PARAGRAPH,
false, LEFT_JUSTIFICATION);
}
}
else if (cdoc_formatting) {
/* If in a paragraph and formatting then add to end of
paragraph, otherwise add as a new line */
if (cdoc_in_paragraph) {
if (! cdoc_paragraph->getFormatted() ||
cdoc_paragraph->getJustification() != LEFT_JUSTIFICATION) {
CDocScriptOutputParagraph();
if (script_line->getData()[0] != '\0') {
if (CDocScriptIsCurrentList())
CDocScriptNewParagraph(script_line->getData(), SUB_LIST_PARAGRAPH1,
true, LEFT_JUSTIFICATION);
else
CDocScriptNewParagraph(script_line->getData(), NORMAL_PARAGRAPH,
true, LEFT_JUSTIFICATION);
}
}
else {
int len = cdoc_paragraph->getTextLen();
if (script_line->getData()[0] != '\0' &&
len > 0 && cdoc_paragraph->getTextChar(len - 1) != '\n')
CDocScriptAddStringToParagraph(" ");
CDocScriptAddStringToParagraph(script_line->getData());
}
}
/* If not in a paragraph then start a new normal paragraph */
else {
if (CDocScriptIsCurrentList())
CDocScriptNewParagraph(script_line->getData(), SUB_LIST_PARAGRAPH1,
true, LEFT_JUSTIFICATION);
else
CDocScriptNewParagraph(script_line->getData(), NORMAL_PARAGRAPH,
true, LEFT_JUSTIFICATION);
}
}
else {
/* If in a paragraph then add as a new line */
if (cdoc_in_paragraph) {
if (cdoc_paragraph->getFormatted() ||
cdoc_paragraph->getJustification() != LEFT_JUSTIFICATION) {
CDocScriptOutputParagraph();
if (script_line->getData()[0] != '\0') {
if (CDocScriptIsCurrentList())
CDocScriptNewParagraph(script_line->getData(), SUB_LIST_PARAGRAPH1,
false, LEFT_JUSTIFICATION);
else
CDocScriptNewParagraph(script_line->getData(), NORMAL_PARAGRAPH,
false, LEFT_JUSTIFICATION);
}
}
else {
CDocScriptAddStringToParagraph("\n");
CDocScriptAddStringToParagraph(script_line->getData());
}
}
/* If not in a paragraph then start a new unformatted
paragraph */
else {
if (CDocScriptIsCurrentList())
CDocScriptNewParagraph(script_line->getData(), SUB_LIST_PARAGRAPH1,
false, LEFT_JUSTIFICATION);
else
CDocScriptNewParagraph(script_line->getData(), NORMAL_PARAGRAPH,
false, LEFT_JUSTIFICATION);
}
}
}
// Process a Dot Command
static void
CDocProcessDotCommandPass2(CDDotCommand *dot_command)
{
int i;
int level;
int no_spaces;
int ignore_error;
char temp_string[256];
if (dot_command->getCommandData() == NULL ||
dot_command->getCommandData()->flush) {
if (cdoc_in_paragraph)
CDocScriptOutputParagraph();
}
/* Fonts */
if (dot_command->getCommand() == "bf") {
std::vector<std::string> words;
CDocStringToWords(dot_command->getText(), words);
uint no_words = words.size();
if (no_words > 1 && words[no_words - 1] == "=") {
no_words--;
ignore_error = true;
}
else
ignore_error = false;
if (no_words == 0)
CDocScriptBeginFont(NULL);
else {
uint i = 0;
for (i = 0; i < no_words; i++)
if (CDocScriptIsValidFont(words[i])) {
CDocScriptBeginFont(words[i]);
break;
}
if (! ignore_error && i == no_words)
CDocScriptError("Font List is Invalid - '%s'", dot_command->getText().c_str());
}
}
else if (dot_command->getCommand() == "df") {
std::vector<std::string> words;
CDocStringToWords(dot_command->getText(), words);
uint no_words = words.size();
if (CDocInst->getOutputFormat() == CDOC_OUTPUT_CDOC) {
if (no_words != 2) {
CDocScriptError("Invalid CDoc Define Font Command .%s %s",
dot_command->getCommand().c_str(), dot_command->getText().c_str());
return;
}
CDocScriptDefineFont(words[0], words[1]);
}
else
CDocScriptError("Define Font not supported for this Format");
}
else if (dot_command->getCommand() == "pf")
CDocScriptPreviousFont();
/* Macros */
else if (dot_command->getCommand() == "dm") {
std::vector<std::string> words;
CDocStringToWords(dot_command->getText(), words);
uint no_words = words.size();
if (no_words == 1 && CStrUtil::casecmp(words[0], "off") == 0)
CDocScriptWarning("Not in Macro");
else if (no_words == 1 || (no_words == 2 && CStrUtil::casecmp(words[1], "on") == 0)) {
CDScriptLine *script_line;
while ((script_line = CDocScriptGetNextLine()) != NULL) {
if (script_line->getType() == CDOC_DOT_COMMAND) {
dot_command = script_line->getDotCommand();
std::vector<std::string> words1;
CDocStringToWords(dot_command->getText(), words1);
uint no_words1 = words1.size();
delete script_line;
if (no_words1 == 1 && CStrUtil::casecmp(words1[0], "off") == 0)
break;
}
else {
delete script_line;
}
}
}
}
/* External Datasets */
else if (dot_command->getCommand() == "dd")
;
else if (dot_command->getCommand() == "im") {
std::vector<std::string> words;
CDocStringToWords(dot_command->getText(), words);
uint no_words = words.size();
if (no_words != 1) {
CDocScriptError("Invalid CDoc Imbed Dataset Command .%s %s",
dot_command->getCommand().c_str(), dot_command->getText().c_str());
return;
}
FILE *fp = CDocScriptImbedDataset(words[0]);
if (fp != NULL) {
cdoc_input_fp_list.push_back(cdoc_input_fp);
cdoc_input_fp = fp;
}
}
/* Formatting */
else if (dot_command->getCommand() == "fo") {
std::vector<std::string> words;
CDocStringToWords(dot_command->getText(), words);
uint no_words = words.size();
for (uint i = 0; i < no_words; i++) {
if (CStrUtil::casecmp(words[i], "on") == 0)
CDocScriptFormattingOn();
else if (CStrUtil::casecmp(words[i], "off") == 0)
CDocScriptFormattingOff();
else
CDocScriptWarning("Formatting Type '%s' not Supported", words[i].c_str());
}
}
/* Page Throws */
else if (dot_command->getCommand() == "pa")
CDocScriptNewPage();
/* Indenting */
else if (dot_command->getCommand() == "in") {
int sign = 0;
std::string str = dot_command->getText();
if (str[0] == '+') {
str = str.substr(1);
sign = -1;
}
else if (str[0] == '-') {
str = str.substr(1);
sign = -1;
}
int indent = 0;
if (CStrUtil::isInteger(str))
indent -= CStrUtil::toInteger(str);
if (sign == 0)
cdoc_indent = indent + sign*indent;
else
cdoc_indent += sign*indent;
if (cdoc_left_margin + cdoc_indent < 1) {
CDocScriptWarning("Indent %d Puts Left Margin Outside Page Bounds", cdoc_indent);
cdoc_indent = -cdoc_left_margin + 1;
}
}
/* Spacing */
else if (dot_command->getCommand() == "bl")
CDocScriptSkipLine();
else if (dot_command->getCommand() == "sp") {
if (dot_command->getText() == "")
no_spaces = 1;
else {
no_spaces = CStrUtil::toInteger(dot_command->getText());
if (no_spaces == 0 || no_spaces > cdoc_lines_per_page) {
CDocScriptWarning("Invalid Number of Spaces '%s'", dot_command->getText().c_str());
no_spaces = 1;
}
}
if (cdoc_in_paragraph) {
if (cdoc_paragraph->getFormatted())
CDocScriptAddStringToParagraph("\n");
for (i = 0; i < no_spaces; i++)
CDocScriptAddStringToParagraph("\n");
}
else {
for (i = 0; i < no_spaces; i++)
CDocScriptSkipLine();
}
}
/* Revision Control */
else if (dot_command->getCommand() == "rc") {
if (isdigit(dot_command->getText()[0])) {
int i = 0;
int j = 0;
char no_string[32];
while (dot_command->getText()[i] != '\0' && isdigit(dot_command->getText()[i]))
no_string[j++] = dot_command->getText()[i++];
no_string[j] = '\0';
int no = CStrUtil::toInteger(no_string);
if (no <= 0) {
CDocScriptWarning("Invalid Revision Control Line '%s'",
dot_command->getText().c_str());
return;
}
CStrUtil::skipSpace(dot_command->getText(), &i);
if (CStrUtil::casecmp(&dot_command->getText()[i], "on") == 0)
CDocScriptStartRevisionControl(no);
else if (CStrUtil::casecmp(&dot_command->getText()[i], "off") == 0)
CDocScriptEndRevisionControl(no);
else
CDocScriptSetRevisionControlChar(no, dot_command->getText()[i]);
}
else if (dot_command->getText()[0] == '*') {
CDocScriptSetRevisionControlChar(0, dot_command->getText()[0]);
CDocScriptStartRevisionControl(0);
}
else {
CDocScriptWarning("Invalid Revision Control Line '%s'",
dot_command->getText().c_str());
return;
}
}
/* Line Breaks */
else if (strncmp(dot_command->getCommand().c_str(), "br", 2) == 0) {
if (cdoc_in_paragraph) {
CDocScriptAddStringToParagraph("\n");
CDocScriptAddStringToParagraph(dot_command->getText());
}
else
CDocScriptNewParagraph(dot_command->getText(), NORMAL_PARAGRAPH, true, LEFT_JUSTIFICATION);
}
/* If ... Then ... Else */
else if (dot_command->getCommand() == "if")
CDocScriptWarning("If not Supported");
else if (dot_command->getCommand() == "th")
CDocScriptWarning("Then not Supported");
else if (dot_command->getCommand() == "el")
CDocScriptWarning("Else not Supported");
/* Page Control */
else if (dot_command->getCommand() == "cp")
CDocScriptWarning("Condition Page Eject not Supported");
/* Comments */
else if (dot_command->getCommand() == "cm")
;
/* Centering */
else if (dot_command->getCommand() == "ce") {
std::vector<std::string> words;
CDocStringToWords(dot_command->getText(), words);
uint no_words = words.size();
if (no_words == 1 && CStrUtil::casecmp(words[0], "on") == 0)
cdoc_no_centred = -1;
else if (no_words == 1 && CStrUtil::casecmp(words[0], "off") == 0)
cdoc_no_centred = 0;
else if (no_words == 1 && isdigit(words[0][0]))
cdoc_no_centred = CStrUtil::toInteger(words[0]);
else
cdoc_no_centred = 1;
}
/* Underscores and Capitalization */
else if (dot_command->getCommand() == "uc") {
std::vector<std::string> words;
CDocStringToWords(dot_command->getText(), words);
uint no_words = words.size();
if (no_words == 1 && CStrUtil::casecmp(words[0], "on") == 0)
cdoc_no_uscore = -1;
else if (no_words == 1 && CStrUtil::casecmp(words[0], "off") == 0)
cdoc_no_uscore = 0;
else if (no_words == 1 && isdigit(words[0][0]))
cdoc_no_uscore = CStrUtil::toInteger(words[0]);
else
cdoc_no_uscore = 1;
cdoc_no_cap = cdoc_no_uscore;
}
else if (dot_command->getCommand() == "up") {
std::vector<std::string> words;
CDocStringToWords(dot_command->getText(), words);
uint no_words = words.size();
if (no_words == 1 && CStrUtil::casecmp(words[0], "on") == 0)
cdoc_no_cap = -1;
else if (no_words == 1 && CStrUtil::casecmp(words[0], "off") == 0)
cdoc_no_cap = 0;
else if (no_words == 1 && isdigit(words[0][0]))
cdoc_no_cap = CStrUtil::toInteger(words[0]);
else
cdoc_no_cap = 1;
}
else if (dot_command->getCommand() == "us") {
std::vector<std::string> words;
CDocStringToWords(dot_command->getText(), words);
uint no_words = words.size();
if (no_words == 1 && CStrUtil::casecmp(words[0], "on") == 0)
cdoc_no_uscore = -1;
else if (no_words == 1 && CStrUtil::casecmp(words[0], "off") == 0)
cdoc_no_uscore = 0;
else if (no_words == 1) {
std::string str;
int i = 0;
int len = words[0].size();
while (i < len && isdigit(words[0][i]))
str += words[0][i++];
if (str != "")
cdoc_no_uscore = CStrUtil::toInteger(str);
else
cdoc_no_uscore = 1;
}
else
cdoc_no_uscore = 1;
}
/* Process a Heading Definition */
else if (dot_command->getCommand() == "dh") {
std::vector<std::string> words;
CDocStringToWords(dot_command->getText(), words);
uint no_words = words.size();
if (no_words >= 2) {
level = CStrUtil::toInteger(words[0]) % CDOC_MAX_HEADERS;
CStrUtil::toLower(words[1]);
std::vector<std::string>::iterator p = words.begin();
std::vector<std::string> words1(++p, words.end());
CDocExtractParameters(words1, dh_parameter_data,
(char *) &header_control[level]);
}
else if (no_words == 1) {
/* Set Header Control from Default Header Control */
level = CStrUtil::toInteger(words[0]) % CDOC_MAX_HEADERS;
memcpy(&header_control[level], &default_header_control[level],
sizeof(CDHeaderControl));
}
else {
/* Set All Header Controls from Default Header Control */
memcpy(header_control, default_header_control,
CDOC_MAX_HEADERS*sizeof(CDHeaderControl));
}
}
/* Headings */
else if (dot_command->getCommand() == "h0" ||
dot_command->getCommand() == "h1" ||
dot_command->getCommand() == "h2" ||
dot_command->getCommand() == "h3" ||
dot_command->getCommand() == "h4" ||
dot_command->getCommand() == "h5" ||
dot_command->getCommand() == "h6") {
/* Spell Check if Required */
if (cdoc_spell_check && cdoc_spell_active)
CSpellCheckString(dot_command->getText());
/* Calculate the Heading Level */
level = (dot_command->getCommand()[1] - '0') % CDOC_MAX_HEADERS;
/* Set the left margin for this Heading Level if the
Heading will be output */
if (! header_control[level].toc_only) {
if (level <= 1)
cdoc_left_margin = cdoc_save_left_margin;
else if (level < 5)
cdoc_left_margin = cdoc_save_left_margin + 2*(level - 1);
}
/* Add Space before Header Text */
strcpy(temp_string, "");
for (i = 0; i < header_control[level].space_before; i++)
strcat(temp_string, " ");
/* If the Header is numbered then add the number text */
if (header_control[level].number_header) {
int header_no;
CDocScriptStartHeader(level);
/* Create Header number from the Depth of each Header Level
below and equal to the current Header Level's Depth */
for (i = 1; i <= level; i++) {
header_no = CDocScriptGetHeader(i);
/* Use Alphabetic Characters for the Appendix */
char temp_string1[256];
if (i == 1) {
if (cdoc_document.part == CDOC_APPENDIX_PART)
sprintf(temp_string1, "Appendix %c",
cdoc_a_to_z[(header_no - appendix_depth - 1) % 26]);
else
sprintf(temp_string1, "%d", header_no);
}
else
sprintf(temp_string1, ".%d", header_no);
strcat(temp_string, temp_string1);
}
/* Add '.0' for First Level Normal Headers and '.'
for First Level Appendix Headers */
if (level == 1) {
if (cdoc_document.part != CDOC_APPENDIX_PART)
strcat(temp_string, ".0");
else
strcat(temp_string, ".");
}
/* Add spacing between Number Text and Header Text */
if (level > 0)
strcat(temp_string, " ");
}
/* Convert to Upper Case if Header is Capitalised */
if (header_control[level].capitalised)
CStrUtil::toUpper(dot_command->getText());
/* Use Header Number if Global Switch is On */
std::string temp_string1;
if (cdoc_number_headers)
temp_string1 = temp_string + dot_command->getText();
else
temp_string1 = dot_command->getText();
/* Add any space required after header */
for (i = 0; i < header_control[level].space_after; i++)
temp_string1 += " ";
/* If Header appears on its own then output as a title,
otherwise add to the current text */
if (header_control[level].break_header) {
/* If new page required start a new section of the
document (also causes a page throw), otherwise
output header on separate line as a sub-section */
if (header_control[level].new_page)
CDocScriptStartSection(dot_command->getText());
else {
if (CDocIsPagedOutput()) {
//int lines_per_page = CDocScriptGetLinesPerPage();
int new_page = CDocScriptFindSpace(header_control[level].skip_before + 3);
if (! new_page) {
if (cdoc_paragraph_done)
CDocScriptSkipLine();
/* Output required number of blank lines
before header */
for (i = 0; i < header_control[level].skip_before - 1; i++)
CDocScriptSkipLine();
}
}
else {
if (cdoc_paragraph_done)
CDocScriptSkipLine();
/* Output required number of blank lines before header */
for (i = 0; i < header_control[level].skip_before - 1; i++)
CDocScriptSkipLine();
}
std::string temp_string = " " + dot_command->getText();
CDocScriptStartSubSection(temp_string);
}
/* If header only appears in table of contents then
don't output the header in the main text */
if (! header_control[level].toc_only) {
CDocScriptWriteIndent(cdoc_left_margin + cdoc_indent);
if (header_control[level].underscored)
CDocScriptWriteText("%s%s%s\n", CDocStartUnderline(),
temp_string1.c_str(), CDocEndUnderline());
else
CDocScriptWriteText("%s\n", temp_string1.c_str());
CDocScriptSkipLine();
cdoc_paragraph_done = false;
cdoc_left_margin++;
}
}
else {
/* If header only appears in table of contents then
don't add the header as a new paragraph */
if (! header_control[level].toc_only) {
std::string temp_string = temp_string1 + " ";
if (header_control[level].underscored)
CDocScriptSetParagraphPrefix(temp_string, CDOC_BOLD_UNDERLINE_FONT, false);
else
CDocScriptSetParagraphPrefix(temp_string, CDOC_BOLD_FONT, false);
}
}
CDocScriptSetTOCPage();
}
/* Running Heading */
else if (dot_command->getCommand() == "rh")
CDocScriptWarning("Running Heading not Supported");
/* Postscript Inclusion */
else if (dot_command->getCommand() == "po")
CDocScriptWarning("Postscript Inclusion not Supported");
/* Goto */
else if (dot_command->getCommand() == "go")
CDocScriptGotoLabel(dot_command->getText());
/* Label (Processed in Pass 1) */
else if (dot_command->getCommand() == "..")
;
/* Symbol (Processed in Pass 1) */
else if (dot_command->getCommand() == "se")
;
else if (dot_command->getCommand() == "dv")
;
/* Translations */
else if (dot_command->getCommand() == "ti")
CDocScriptParseTranslation(dot_command->getText());
/* Dictionary */
else if (dot_command->getCommand() == "du") {
if (cdoc_spell_check) {
std::vector<std::string> words;
CDocStringToWords(dot_command->getText(), words);
uint no_words = words.size();
if (no_words > 1) {
if (CStrUtil::casecmp(words[0], "add") == 0) {
for (uint i = 1; i < no_words; i++)
CSpellAddWord(words[i]);
}
else if (CStrUtil::casecmp(words[0], "del") == 0)
CDocScriptWarning("Dictionary Deletion not Supported");
else
CDocScriptWarning("Invalid Dictionary Update Command");
}
}
}
/* Spell Check */
else if (dot_command->getCommand() == "sv") {
std::vector<std::string> words;
CDocStringToWords(dot_command->getText(), words);
uint no_words = words.size();
if (no_words == 1 && CStrUtil::casecmp(words[0], "on") == 0)
cdoc_spell_active = true;
else if (no_words == 1 && CStrUtil::casecmp(words[0], "off") == 0)
cdoc_spell_active = false;
else
CDocScriptWarning("Invalid Spelling Verification Options");
}
/* Hyphenation */
else if (dot_command->getCommand() == "hy")
CDocScriptWarning("Hyphenation not Supported");
/* Define Character (Error Checking Done in Pass 1) */
else if (dot_command->getCommand() == "dc") {
std::vector<std::string> words;
CDocStringToWords(dot_command->getText(), words);
uint no_words = words.size();
if (no_words > 0) {
CStrUtil::toLower(words[0]);
if (words[0] == "cont") {
if (no_words == 2) {
if (CStrUtil::casecmp(words[1], "off") == 0)
cdoc_continuation_char = (int) '\0';
else if (words[1].size() == 1)
cdoc_continuation_char = (int) words[1][0];
}
}
}
}
/* Invalid or Unsupported Commands */
else {
if (dot_command->getCommandData() != NULL)
CDocScriptWarning("Unsupported Dot Command - %s %s",
dot_command->getCommand().c_str(), dot_command->getText().c_str());
else
CDocScriptWarning("Invalid Dot Command - %s %s",
dot_command->getCommand().c_str(), dot_command->getText().c_str());
}
}
// Process a Colon Command
static void
CDocProcessColonCommandPass2(CDColonCommand *colon_command)
{
int i;
int j;
int level;
int no_spaces;
char temp_string[CDOC_MAX_LINE];
if (colon_command->getCommandData() == NULL ||
colon_command->getCommandData()->flush ||
(colon_command->getCommandData()->end_command != NULL &&
colon_command->getCommand() == colon_command->getCommandData()->end_command)) {
if (cdoc_in_paragraph)
CDocScriptOutputParagraph();
}
/* Process Specific Control Blocks */
if (colon_command->getCommand() == "psc")
CDocScriptStartPCtrl(colon_command);
else if (colon_command->getCommand() == "epsc")
CDocScriptEndPCtrl();
/* Process Front Sheet Colon Commands */
else if (cdoc_document.part == CDOC_FRONT_SHEET_PART) {
if (! CDocScriptProcessFrontSheetCommand(colon_command)) {
/* Set the Document Part to Unspecified while processing
the Colon Command otherwise we will end up in an endless
loop */
cdoc_document.part = CDOC_NO_PART;
CDocProcessColonCommandPass2(colon_command);
cdoc_document.part = CDOC_FRONT_SHEET_PART;
}
}
/* Process Amendments Colon Commands */
else if (cdoc_document.part == CDOC_AMENDMENTS_PART)
CDocScriptProcessAmendmentsCommand(colon_command);
/* Process Memo Header Colon Commands */
else if (cdoc_document.part == CDOC_MEMO_HEADER_PART)
CDocScriptProcessMemoHeaderCommand(colon_command);
/* Process Title Page Colon Commands */
else if (cdoc_document.sub_part == CDOC_TITLE_PAGE_SUB_PART)
CDocScriptProcessTitlePageCommand(colon_command);
/* Process Basic Colon Commands */
else if ((cdoc_document.part == CDOC_FRONT_MATTER_PART &&
(cdoc_document.sub_part == CDOC_ABSTRACT_SUB_PART ||
cdoc_document.sub_part == CDOC_PREFACE_SUB_PART ||
cdoc_document.sub_part == CDOC_NO_SUB_PART )) ||
cdoc_document.part == CDOC_BODY_PART ||
cdoc_document.part == CDOC_APPENDIX_PART ||
cdoc_document.part == CDOC_BACK_MATTER_PART ||
cdoc_document.part == CDOC_NO_PART) {
/* Document Types */
if (colon_command->getCommand() == "sdoc") {
CDDocData doc_data;
doc_data.security = NULL;
doc_data.language = NULL;
CDocExtractParameterValues(colon_command->getParameters(),
colon_command->getValues(),
sdoc_parameter_data,
(char *) &doc_data);
if (doc_data.security) cdoc_document.security = doc_data.security;
if (doc_data.language) cdoc_document.language = doc_data.language;
CStrUtil::toUpper(cdoc_document.security);
cdoc_document.type = CDOC_STAIRS_DOCUMENT;
cdoc_document.part = CDOC_NO_PART;
cdoc_document.sub_part = CDOC_NO_SUB_PART;
}
else if (colon_command->getCommand() == "esdoc")
cdoc_document.type = CDOC_NO_DOCUMENT;
else if (colon_command->getCommand() == "gdoc") {
CDDocData doc_data;
doc_data.security = NULL;
doc_data.language = NULL;
CDocExtractParameterValues(colon_command->getParameters(),
colon_command->getValues(),
gdoc_parameter_data,
(char *) &doc_data);
if (doc_data.security) cdoc_document.security = doc_data.security;
if (doc_data.language) cdoc_document.language = doc_data.language;
cdoc_document.type = CDOC_GENERAL_DOCUMENT;
cdoc_document.part = CDOC_NO_PART;
cdoc_document.sub_part = CDOC_NO_SUB_PART;
}
else if (colon_command->getCommand() == "egdoc")
cdoc_document.type = CDOC_NO_DOCUMENT;
else if (colon_command->getCommand() == "memo")
cdoc_document.type = CDOC_MEMO_DOCUMENT;
/* Document Parts */
else if (colon_command->getCommand() == "frontm") {
cdoc_document.part = CDOC_FRONT_MATTER_PART;
cdoc_document.sub_part = CDOC_NO_SUB_PART;
}
else if (colon_command->getCommand() == "body") {
cdoc_document.part = CDOC_BODY_PART;
cdoc_document.sub_part = CDOC_NO_SUB_PART;
}
else if (colon_command->getCommand() == "appendix") {
cdoc_document.part = CDOC_APPENDIX_PART;
cdoc_document.sub_part = CDOC_NO_SUB_PART;
appendix_depth = CDocScriptGetHeader(1);
}
else if (colon_command->getCommand() == "eappendix") {
cdoc_document.part = CDOC_NO_PART;
cdoc_document.sub_part = CDOC_NO_SUB_PART;
appendix_depth = 0;
}
else if (colon_command->getCommand() == "backm") {
cdoc_document.part = CDOC_BACK_MATTER_PART;
cdoc_document.sub_part = CDOC_NO_SUB_PART;
}
else if (colon_command->getCommand() == "fronts")
CDocScriptInitFrontSheet();
else if (colon_command->getCommand() == "amends")
CDocScriptInitAmendments();
else if (colon_command->getCommand() == "mh")
CDocScriptInitMemoHeader();
/* Front Matter Sub Parts */
else if (colon_command->getCommand() == "titlep")
CDocScriptInitTitlePage();
else if (colon_command->getCommand() == "abstract") {
cdoc_document.part = CDOC_FRONT_MATTER_PART;
cdoc_document.sub_part = CDOC_ABSTRACT_SUB_PART;
CDocScriptWriteLeftJustifiedPageHeader("Abstract");
}
else if (colon_command->getCommand() == "preface") {
cdoc_document.part = CDOC_FRONT_MATTER_PART;
cdoc_document.sub_part = CDOC_PREFACE_SUB_PART;
CDocScriptWriteLeftJustifiedPageHeader("Preface");
}
/* Table of Contents */
else if (colon_command->getCommand() == "toc")
CDocScriptOutputTableOfContents();
/* Figure List */
else if (colon_command->getCommand() == "figlist")
CDocScriptOutputFigureList();
/* Table List */
else if (colon_command->getCommand() == "tlist")
CDocScriptOutputTableList();
/* Index */
else if (colon_command->getCommand() == "index") {
if (cdoc_index)
CDocScriptOutputIndex();
}
else if (colon_command->getCommand()[0] == 'i' &&
(colon_command->getCommand()[1] == '1' ||
colon_command->getCommand()[1] == '2' ||
colon_command->getCommand()[1] == '3')) {
if (cdoc_index) {
CDIndexEntry index_entry;
index_entry.ident = NULL;
index_entry.page = NULL;
index_entry.refid = NULL;
if (colon_command->getCommand()[1] == '1')
CDocExtractParameterValues(colon_command->getParameters(),
colon_command->getValues(),
i1_parameter_data,
(char *) &index_entry);
else
CDocExtractParameterValues(colon_command->getParameters(),
colon_command->getValues(),
i23_parameter_data,
(char *) &index_entry);
std::string see_text;
std::string page;
if (index_entry.page == PG_START)
page = PG_START_STR;
else if (index_entry.page == PG_END)
page = PG_END_STR;
else if (index_entry.page == PG_MAJOR)
page = PG_MAJOR_STR;
else
page = (index_entry.page ? std::string(index_entry.page ) : "");
std::string refid = (index_entry.refid ? std::string(index_entry.refid) : "");
if (colon_command->getCommand()[1] == '1') {
see_text = CDocScriptGetIndex1SeeText(colon_command->getText(), refid);
CDocScriptSetIndex1Page(colon_command->getText(), page, refid);
}
else if (colon_command->getCommand()[1] == '2') {
see_text = CDocScriptGetIndex2SeeText(colon_command->getText(), refid);
CDocScriptSetIndex2Page(colon_command->getText(), page, refid);
}
else {
see_text = CDocScriptGetIndex3SeeText(colon_command->getText(), refid);
CDocScriptSetIndex3Page(colon_command->getText(), page, refid);
}
if (CDocInst->getOutputFormat() == CDOC_OUTPUT_HTML)
CDocScriptWriteCommand("<a name='%s'></a>\n", see_text.c_str());
}
}
else if (colon_command->getCommand()[0] == 'i' &&
colon_command->getCommand()[1] == 'h' &&
(colon_command->getCommand()[2] == '1' ||
colon_command->getCommand()[2] == '2' ||
colon_command->getCommand()[2] == '3')) {
if (cdoc_index) {
CDIndexEntryHeading index_entry_heading;
index_entry_heading.ident = NULL;
index_entry_heading.print = NULL;
index_entry_heading.see = NULL;
index_entry_heading.seeid = NULL;
CDocExtractParameterValues(colon_command->getParameters(),
colon_command->getValues(),
ih_parameter_data,
(char *) &index_entry_heading);
std::string see_text;
if (colon_command->getCommand()[2] == '1')
see_text = CDocScriptGetIndex1SeeText(colon_command->getText(), "");
else if (colon_command->getCommand()[2] == '2')
see_text = CDocScriptGetIndex2SeeText(colon_command->getText(), "");
else
see_text = CDocScriptGetIndex3SeeText(colon_command->getText(), "");
if (CDocInst->getOutputFormat() == CDOC_OUTPUT_HTML)
CDocScriptWriteCommand("<a name='%s'></a>\n", see_text.c_str());
}
}
/* Title */
else if (colon_command->getCommand() == "title") {
/* Spell Check if Required */
if (cdoc_spell_check && cdoc_spell_active)
CSpellCheckString(colon_command->getText());
/* Output Title Line */
if (CDocStringDisplayLength(colon_command->getText()) > 0)
CDocScriptWriteLeftJustifiedHeader(colon_command->getText());
}
/* Signature */
else if (colon_command->getCommand() == "sig")
CDocScriptOutputMemoSignature();
/* Process Table Commands */
/* Table Row */
else if (colon_command->getCommand() == "row") {
if (current_table != NULL) {
/* Set structure values from Parameter/Value pairs */
CDTableRowData row_data;
row_data.refid = NULL;
row_data.split = false;
CDocExtractParameterValues(colon_command->getParameters(),
colon_command->getValues(),
row_parameter_data,
(char *) &row_data);
CDTableRow *row = CDocScriptCreateTableRow(current_table);
row->refid = (row_data.refid ? row_data.refid : "");
row->split = row_data.split;
CDocScriptSetTableRowRowDef(row);
current_row = row;
if (CDocInst->getOutputFormat() == CDOC_OUTPUT_HTML) {
CDocScriptWriteCommand("<tr>\n");
return;
}
}
else
CDocScriptError("Table Row outside Table");
}
/* Table End Row */
else if (colon_command->getCommand() == "erow") {
if (current_table != NULL) {
current_row = NULL;
if (CDocInst->getOutputFormat() == CDOC_OUTPUT_HTML) {
CDocScriptWriteCommand("</tr>\n");
return;
}
}
else
CDocScriptError("Table End Row outside Table");
}
/* Table Cell */
else if (colon_command->getCommand() == "c") {
/* Spell Check if Required */
if (cdoc_spell_check && cdoc_spell_active)
CSpellCheckString(colon_command->getText());
if (current_table != NULL) {
if (current_row != NULL) {
CDTableCell *cell = CDocScriptCreateTableCell(current_row);
if (colon_command->getNumParameters() == 0)
;
else if (colon_command->getNumParameters() == 1 && colon_command->getValue(0) == "") {
cell->number = CStrUtil::toInteger(colon_command->getParameter(0));
if (cell->number <= 0) {
cell->number = 0;
CDocScriptError("Invalid Cell Number '%s'",
colon_command->getParameter(0).c_str());
}
else
current_row->cell_number = cell->number;
}
else
CDocScriptError("Invalid Cell Parameter List");
cell->text = CStrUtil::strdup(colon_command->getText().c_str());
cell->no_breaks = colon_command->getNumBreaks();
if (cell->no_breaks > 0) {
cell->breaks = new int [cell->no_breaks];
for (j = 0; j < cell->no_breaks; j++)
cell->breaks[j] = colon_command->getBreak(j);
}
else
cell->breaks = NULL;
if (cell->number == 0)
cell->number = ++current_row->cell_number;
if (CDocInst->getOutputFormat() == CDOC_OUTPUT_HTML) {
CDocScriptWriteCommand("<td>%s</td>\n", CDocEncodeHtmlString(cell->text));
return;
}
else if (CDocInst->getOutputFormat() == CDOC_OUTPUT_ILEAF) {
CDocScriptWriteCommand("<\"para\">\n");
CDocScriptWriteCommand("%s\n",
CDocEncodeILeafString(cell->text));
return;
}
}
else
CDocScriptError("Cell outside Row Block");
}
else
CDocScriptError("Table End Row outside Table");
}
/* Table Caption */
else if (colon_command->getCommand() == "tcap") {
if (current_table == NULL)
CDocScriptError("Table Caption outside Table");
}
/* Table Description */
else if (colon_command->getCommand() == "tdesc") {
if (current_table == NULL)
CDocScriptError("Table Description outside Table");
}
/* Table Footer */
else if (colon_command->getCommand() == "tft") {
if (current_table != NULL) {
CDTableRow *row = CDocScriptCreateTableFooterRow(current_table);
/* Set structure values from Parameter/Value pairs */
CDocExtractParameterValues(colon_command->getParameters(),
colon_command->getValues(),
tft_parameter_data,
(char *) row);
CDocScriptSetTableRowRowDef(row);
current_row = row;
}
else
CDocScriptError("Table Footer outside Table");
}
/* Table End Footer */
else if (colon_command->getCommand() == "etft") {
if (current_table != NULL)
current_row = NULL;
else
CDocScriptError("Table End Footer outside Table");
}
/* Table Heading */
else if (colon_command->getCommand() == "thd") {
if (current_table != NULL) {
CDTableRow *row = CDocScriptCreateTableHeaderRow(current_table);
/* Set structure values from Parameter/Value pairs */
CDocExtractParameterValues(colon_command->getParameters(),
colon_command->getValues(),
thd_parameter_data,
(char *) row);
CDocScriptSetTableRowRowDef(row);
current_row = row;
}
else
CDocScriptError("Table Header outside Table");
}
/* Table End Heading */
else if (colon_command->getCommand() == "ethd") {
if (current_table != NULL)
current_row = NULL;
else
CDocScriptError("Table End Header outside Table");
}
/* Table Note */
else if (colon_command->getCommand() == "tnote") {
/* Spell Check if Required */
if (cdoc_spell_check && cdoc_spell_active)
CSpellCheckString(colon_command->getText());
if (current_table != NULL) {
current_row = NULL;
CDocScriptAddTableNote(current_table, colon_command->getText());
}
else
CDocScriptError("Table Note outside Table");
}
else if (colon_command->getCommand() == "etnote") {
if (current_table != NULL)
;
else
CDocScriptError("End Table Note outside Table");
}
/* End Table */
else if (colon_command->getCommand() == "etable") {
if (current_table != NULL) {
if (CDocInst->getOutputFormat() == CDOC_OUTPUT_HTML)
CDocScriptWriteCommand("</table>\n");
else
CDocScriptOutputTable(current_table);
if (current_table->id != "")
CDocScriptSetReferencePageNumber(TABLE_REF, current_table->id);
CDocScriptSetTablePage(current_table);
}
else
CDocScriptWarning("Invalid Table Colon Command - %s %s",
colon_command->getCommand().c_str(), colon_command->getText().c_str());
current_table = NULL;
}
/* Figures */
else if (colon_command->getCommand() == "fig") {
if (current_figure != NULL) {
CDocScriptWarning("Unterminated Figure");
CDocScriptFigureEnd(current_figure);
}
/* Process Figure (Details already recorded in Pass 1) */
figure_number++;
/* Get Pass 1 Figure Details */
current_figure = CDocScriptGetFigure(figure_number);
if (current_figure != NULL)
CDocScriptFigureBegin(current_figure);
else
CDocScriptError("Figure Not Found - Internal Error");
}
else if (colon_command->getCommand() == "figcap") {
if (current_figure == NULL)
CDocScriptWarning("Figure Caption outside Figure");
}
else if (colon_command->getCommand() == "figdesc") {
if (current_figure == NULL)
CDocScriptWarning("Figure Description outside Figure");
}
else if (colon_command->getCommand() == "efig") {
/* End of Figure */
if (current_figure != NULL)
CDocScriptFigureEnd(current_figure);
else
CDocScriptWarning("End Figure outside Figure");
current_figure = NULL;
}
/* Definition Lists */
else if (colon_command->getCommand() == "dl") {
if (CDocInst->getOutputFormat() != CDOC_OUTPUT_HTML &&
CDocInst->getOutputFormat() != CDOC_OUTPUT_ILEAF) {
if (CDocScriptGetCurrentListCompact())
CDocScriptSkipLine();
}
/* Create and store Definition List Structure */
cdoc_definition_list = CDocScriptCreateDefinitionList();
/* Set structure values from Parameter/Value pairs */
CDocExtractParameterValues(colon_command->getParameters(),
colon_command->getValues(),
dl_parameter_data,
(char *) cdoc_definition_list);
cdoc_definition_list->heading_highlight %= 4;
cdoc_definition_list->term_highlight %= 4;
/* Add Definition List Structure as the Current List */
CDocScriptStartDefinitionList(cdoc_definition_list);
if (CDocInst->getOutputFormat() == CDOC_OUTPUT_HTML) {
if (CDocScriptGetCurrentListCompact())
CDocScriptWriteCommand("<dl compact>\n");
else
CDocScriptWriteCommand("<dl>\n");
}
}
/* Definition Term Header */
else if (colon_command->getCommand() == "dthd") {
/* Spell Check if Required */
if (cdoc_spell_check && cdoc_spell_active)
CSpellCheckString(colon_command->getText());
if (cdoc_definition_list != NULL) {
if (CDocInst->getOutputFormat() == CDOC_OUTPUT_HTML) {
CDocScriptWriteCommand("<dt><b>%s</b></dt>\n",
CDocEncodeHtmlString(colon_command->getText()));
return;
}
else if (CDocInst->getOutputFormat() == CDOC_OUTPUT_ILEAF) {
CDocScriptWriteCommand("<\"para\">\n");
CDocScriptWriteCommand("%s\n",
CDocEncodeILeafString(colon_command->getText()));
return;
}
strcpy(temp_string, "");
/* If term exceeds space allowed */
if (CDocStringDisplayLength(colon_command->getText()) + 2 >
cdoc_definition_list->depth) {
/* If break up flag set then output on a separate
line as the definition text using the paragraph
prefix, otherwise output on the same line as the
definition text */
if (cdoc_definition_list->break_up) {
std::string temp_string;
if (CDocInst->getOutputFormat() == CDOC_OUTPUT_RAW_CC ||
CDocInst->getOutputFormat() == CDOC_OUTPUT_CDOC ||
CDocInst->getOutputFormat() == CDOC_OUTPUT_TROFF) {
temp_string =
CDocScriptAddHighlightEscapes(colon_command->getText(),
cdoc_definition_list->heading_highlight) + "\n";
}
/*
else if (CDocInst->getOutputFormat() == CDOC_OUTPUT_TROFF) {
if (cdoc_definition_list->heading_highlight == 0)
temp_string = "";
else
temp_string = ".ft B\n";
temp_string += colon_command->getText();
temp_string += "\n";
if (cdoc_definition_list->heading_highlight != 0)
temp_string += ".ft P\n";
}
*/
else
temp_string = colon_command->getText() + "\n";
cdoc_paragraph->setHeader(temp_string);
int i = 0;
for (i = 0; i < cdoc_definition_list->depth; i++)
definition_prefix[i] = ' ';
definition_prefix[i] = '\0';
CDocScriptSetParagraphPrefix(definition_prefix, CDOC_NORMAL_FONT, true);
}
else {
uint i = 0;
for (i = 0; i < colon_command->getText().size(); i++)
definition_prefix[i] = colon_command->getText()[i];
definition_prefix[i++] = ' ';
definition_prefix[i++] = ' ';
definition_prefix[i] = '\0';
CDocScriptSetParagraphPrefix(definition_prefix,
CDocScriptHighlightToFont(cdoc_definition_list->heading_highlight),
true);
}
}
/* If term is within space allowed then pad out to the
required length with spaces and set the paragraph
prefix */
else {
uint i = 0;
for (i = 0; i < colon_command->getText().size(); i++)
definition_prefix[i] = colon_command->getText()[i];
for ( ; i < uint(cdoc_definition_list->depth); i++)
definition_prefix[i] = ' ';
definition_prefix[i] = '\0';
CDocScriptSetParagraphPrefix(definition_prefix,
CDocScriptHighlightToFont(cdoc_definition_list->heading_highlight),
true);
}
cdoc_definition_list->prefix_length = CDocStringDisplayLength(definition_prefix);
}
}
/* Definition Description Header */
else if (colon_command->getCommand() == "ddhd") {
if (cdoc_definition_list != NULL) {
if (CDocInst->getOutputFormat() == CDOC_OUTPUT_HTML) {
CDocScriptWriteCommand("<dd>%s</dd>\n",
CDocEncodeHtmlString(colon_command->getText().c_str()));
return;
}
else if (CDocInst->getOutputFormat() == CDOC_OUTPUT_ILEAF) {
CDocScriptWriteCommand("<\"para\">\n");
CDocScriptWriteCommand("%s\n", CDocEncodeILeafString(colon_command->getText().c_str()));
return;
}
/* Add the text as a New Paragraph */
std::string temp_string =
CDocScriptAddHighlightEscapes(colon_command->getText(),
cdoc_definition_list->heading_highlight);
CDocScriptNewParagraph(temp_string, DEFINITION_PARAGRAPH,
true, LEFT_JUSTIFICATION);
}
else
CDocScriptWarning("Definition Data outside Definition List - %s %s",
colon_command->getCommand().c_str(), colon_command->getText().c_str());
}
/* Definition Term */
else if (colon_command->getCommand() == "dt") {
/* Spell Check if Required */
if (cdoc_spell_check && cdoc_spell_active)
CSpellCheckString(colon_command->getText());
if (cdoc_definition_list != NULL) {
if (cdoc_definition_list->term_flag)
CDocScriptWarning("No Definition Data for Definition Term");
else
cdoc_definition_list->term_flag = true;
if (CDocInst->getOutputFormat() == CDOC_OUTPUT_HTML) {
CDocScriptWriteCommand("<dt><b>%s</b></dt>\n",
CDocEncodeHtmlString(colon_command->getText().c_str()));
return;
}
else if (CDocInst->getOutputFormat() == CDOC_OUTPUT_ILEAF) {
CDocScriptWriteCommand("<\"para\">\n");
CDocScriptWriteCommand("%s%s%s\n", ILEAF_BOLD_FONT,
CDocEncodeILeafString(colon_command->getText()),
ILEAF_NORMAL_FONT);
return;
}
strcpy(temp_string, "");
/* If term exceeds space allowed */
if (CDocStringDisplayLength(colon_command->getText()) + 2 >
cdoc_definition_list->depth) {
/* If break up flag set then output on a separate
line as the definition text using the paragraph
prefix, otherwise output on the same line as the
definition text */
if (cdoc_definition_list->break_up) {
std::string temp_string;
if (CDocInst->getOutputFormat() == CDOC_OUTPUT_RAW_CC ||
CDocInst->getOutputFormat() == CDOC_OUTPUT_CDOC ||
CDocInst->getOutputFormat() == CDOC_OUTPUT_TROFF) {
temp_string =
CDocScriptAddHighlightEscapes(colon_command->getText(),
cdoc_definition_list->term_highlight) + "\n";
}
/*
else if (CDocInst->getOutputFormat() == CDOC_OUTPUT_TROFF) {
if (cdoc_definition_list->term_highlight == 0)
temp_string = "";
else
temp_string = ".ft B\n";
temp_string += colon_command->getText();
temp_string += "\n";
if (cdoc_definition_list->term_highlight != 0)
temp_string += ".ft P\n";
}
*/
else
temp_string = colon_command->getText() + "\n";
cdoc_paragraph->setHeader(temp_string);
int i = 0;
for (i = 0; i < cdoc_definition_list->depth; i++)
definition_prefix[i] = ' ';
definition_prefix[i] = '\0';
CDocScriptSetParagraphPrefix(definition_prefix, CDOC_NORMAL_FONT, true);
}
else {
uint i = 0;
for (i = 0; i < colon_command->getText().size(); i++)
definition_prefix[i] = colon_command->getText()[i];
definition_prefix[i++] = ' ';
definition_prefix[i++] = ' ';
definition_prefix[i] = '\0';
CDocScriptSetParagraphPrefix(definition_prefix,
CDocScriptHighlightToFont(cdoc_definition_list->term_highlight),
true);
}
}
/* If term is within space allowed then pad out to the
required length with spaces and set the paragraph
prefix */
else {
int i = 0;
for (i = 0; i < int(colon_command->getText().size()); i++)
definition_prefix[i] = colon_command->getText()[i];
for (; i < cdoc_definition_list->depth; i++)
definition_prefix[i] = ' ';
definition_prefix[i] = '\0';
CDocScriptSetParagraphPrefix(definition_prefix,
CDocScriptHighlightToFont(cdoc_definition_list->term_highlight),
true);
}
cdoc_definition_list->prefix_length = CDocStringDisplayLength(definition_prefix);
}
}
/* Definition Description */
else if (colon_command->getCommand() == "dd") {
/* Add the text as a New Paragraph */
if (cdoc_definition_list != NULL) {
if (! cdoc_definition_list->term_flag)
CDocScriptWarning("Definition Data without Definition Term");
else
cdoc_definition_list->term_flag = false;
if (CDocInst->getOutputFormat() == CDOC_OUTPUT_HTML) {
CDocScriptWriteCommand("<dd>%s</dd>\n", CDocEncodeHtmlString(colon_command->getText()));
return;
}
else if (CDocInst->getOutputFormat() == CDOC_OUTPUT_ILEAF) {
CDocScriptWriteCommand("<\"para\">\n");
CDocScriptWriteCommand("%s\n", CDocEncodeILeafString(colon_command->getText()));
return;
}
/* Add the text as a New Paragraph */
CDocScriptNewParagraph(colon_command->getText(), DEFINITION_PARAGRAPH,
true, LEFT_JUSTIFICATION);
}
else
CDocScriptWarning("Definition Data outside Definition List - %s %s",
colon_command->getCommand().c_str(), colon_command->getText().c_str());
}
/* End of Definition List */
else if (colon_command->getCommand() == "edl") {
if (cdoc_definition_list != NULL &&
CDocScriptIsCurrentListType(DEFINITION_LIST)) {
/* If the list was compact then add a Newline
at then end */
if (CDocInst->getOutputFormat() == CDOC_OUTPUT_HTML)
CDocScriptWriteCommand("</dl>\n");
else if (CDocInst->getOutputFormat() == CDOC_OUTPUT_ILEAF)
;
else {
if (cdoc_definition_list->compact)
CDocScriptSkipLine();
}
/* Remove the Definition List and reset the current
Definition List */
cdoc_definition_list = CDocScriptEndDefinitionList();
}
else
CDocScriptWarning("Invalid End Definition List");
}
/* Lists */
/* Ordered List */
else if (colon_command->getCommand() == "ol") {
if (CDocInst->getOutputFormat() != CDOC_OUTPUT_HTML &&
CDocInst->getOutputFormat() != CDOC_OUTPUT_ILEAF) {
if (CDocScriptGetCurrentListCompact())
CDocScriptSkipLine();
}
/* Create and Store List Structure */
cdoc_general_list = CDocScriptCreateGeneralList(ORDERED_LIST);
/* Set structure values from Parameter/Value pairs */
CDocExtractParameterValues(colon_command->getParameters(),
colon_command->getValues(),
ol_parameter_data,
(char *) cdoc_general_list);
/* Add List Structure as the Current List */
CDocScriptStartGeneralList(cdoc_general_list);
if (CDocInst->getOutputFormat() == CDOC_OUTPUT_HTML) {
if (CDocScriptGetCurrentListCompact())
CDocScriptWriteCommand("<ol compact>\n");
else
CDocScriptWriteCommand("<ol>\n");
}
}
/* Simple List */
else if (colon_command->getCommand() == "sl") {
if (CDocInst->getOutputFormat() != CDOC_OUTPUT_HTML &&
CDocInst->getOutputFormat() != CDOC_OUTPUT_ILEAF) {
if (CDocScriptGetCurrentListCompact())
CDocScriptSkipLine();
}
/* Create and Store List Structure */
cdoc_general_list = CDocScriptCreateGeneralList(SIMPLE_LIST);
/* Set structure values from Parameter/Value pairs */
CDocExtractParameterValues(colon_command->getParameters(),
colon_command->getValues(),
sl_parameter_data,
(char *) cdoc_general_list);
/* Add List Structure as the Current List */
CDocScriptStartGeneralList(cdoc_general_list);
if (CDocInst->getOutputFormat() == CDOC_OUTPUT_HTML) {
if (CDocScriptGetCurrentListCompact())
CDocScriptWriteCommand("<ul compact>\n");
else
CDocScriptWriteCommand("<ul>\n");
}
}
/* Unordered List */
else if (colon_command->getCommand() == "ul") {
if (CDocInst->getOutputFormat() != CDOC_OUTPUT_HTML &&
CDocInst->getOutputFormat() != CDOC_OUTPUT_ILEAF) {
if (CDocScriptGetCurrentListCompact())
CDocScriptSkipLine();
}
/* Create and Store List Structure */
cdoc_general_list = CDocScriptCreateGeneralList(UNORDERED_LIST);
/* Set structure values from Parameter/Value pairs */
CDocExtractParameterValues(colon_command->getParameters(),
colon_command->getValues(),
ul_parameter_data,
(char *) cdoc_general_list);
/* Add List Structure as the Current List */
CDocScriptStartGeneralList(cdoc_general_list);
if (CDocInst->getOutputFormat() == CDOC_OUTPUT_HTML) {
if (CDocScriptGetCurrentListCompact())
CDocScriptWriteCommand("<ul compact>\n");
else
CDocScriptWriteCommand("<ul>\n");
}
}
/* List Item */
else if (colon_command->getCommand() == "li") {
CDListItem list_item;
/* Process Parameter/Value pairs */
list_item.ident = NULL;
CDocExtractParameterValues(colon_command->getParameters(),
colon_command->getValues(),
li_parameter_data,
(char *) &list_item);
/* Add reference if List has Identifier */
if (list_item.ident != NULL) {
if (CDocInst->getOutputFormat() == CDOC_OUTPUT_HTML)
CDocScriptWriteCommand("<a name='%s'></a>\n",
colon_command->getText().c_str());
}
/* Output Text dependant on List Type */
if (cdoc_general_list != NULL) {
if (CDocInst->getOutputFormat() == CDOC_OUTPUT_HTML) {
CDocScriptWriteCommand("<li>%s\n",
CDocEncodeHtmlString(colon_command->getText().c_str()));
return;
}
else if (CDocInst->getOutputFormat() == CDOC_OUTPUT_ILEAF) {
if (cdoc_general_list->type == ORDERED_LIST) {
CDocScriptWriteCommand("<\"list\">\n");
CDocScriptWriteCommand("<\"|:list\", Font = @i*, Subcomponent = yes><F0><Tab>"
"<Autonum, \"list\", 1, Value = \"%d.\"><Tab><End Sub><F0>%s\n",
cdoc_general_list->number,
CDocEncodeILeafString(colon_command->getText().c_str()));
}
else {
CDocScriptWriteCommand("<\"bullet\">\n");
CDocScriptWriteCommand("<\"|:bullet\", Font = @i*, Subcomponent = yes>"
"<F8@Z7@Lam>S<F0><Tab><Tab><End Sub><F0>%s\n",
CDocEncodeILeafString(colon_command->getText().c_str()));
}
return;
}
/* Set current Paragraph to the List Item Text */
CDocScriptNewParagraph(colon_command->getText(), LIST_PARAGRAPH,
true, LEFT_JUSTIFICATION);
/* Ordered List requires preceding Number */
if (cdoc_general_list->type == ORDERED_LIST) {
CDGeneralList *temp_general_list;
/* Set current list item Number */
cdoc_general_list->number++;
/* Create List Item Number from a concatenation
of the depth of this and all lower level
Ordered List Items */
strcpy(list_prefix, "");
for (i = 1; i <= CDocScriptGetNoGeneralLists(); i++) {
temp_general_list = CDocScriptGetNthGeneralList(i);
if (temp_general_list->number > 0) {
char temp_string1[33];
sprintf(temp_string1, "%d.", temp_general_list->number);
strcat(list_prefix, temp_string1);
}
}
strcat(list_prefix, " ");
/* Set the Number String as the Paragraph Prefix */
CDocScriptSetParagraphPrefix(list_prefix, CDOC_NORMAL_FONT, true);
}
/* Simple List requires preceding Spaces */
else if (cdoc_general_list->type == SIMPLE_LIST) {
/* Set the Space String as the Paragraph Prefix */
if (CDocInst->getOutputFormat() == CDOC_OUTPUT_TROFF)
strcpy(list_prefix, "\\ \\ ");
else
strcpy(list_prefix, " ");
CDocScriptSetParagraphPrefix(list_prefix, CDOC_NORMAL_FONT, true);
}
/* Unordered List requires preceding Bullet */
else if (cdoc_general_list->type == UNORDERED_LIST) {
/* Set the Bullet String as the Paragraph Prefix */
if (CDocInst->getOutputFormat() == CDOC_OUTPUT_TROFF)
strcpy(list_prefix, "\\(bu ");
else if (CDocInst->getOutputFormat() == CDOC_OUTPUT_CDOC)
strcpy(list_prefix, "B@cdocsym@\267E ");
else
strcpy(list_prefix, ". ");
CDocScriptSetParagraphPrefix(list_prefix, CDOC_NORMAL_FONT, true);
}
}
else
CDocScriptWarning("List Item outside List - %s %s",
colon_command->getCommand().c_str(), colon_command->getText().c_str());
if (list_item.ident != NULL)
CDocScriptSetReferencePageNumber(LIST_ITEM_REF, list_item.ident);
}
/* End Ordered List */
else if (colon_command->getCommand() == "eol") {
if (cdoc_general_list != NULL && cdoc_general_list->type == ORDERED_LIST &&
CDocScriptIsCurrentListType(ORDERED_LIST)) {
/* If the list was compact then add a Newline
at then end */
if (CDocInst->getOutputFormat() == CDOC_OUTPUT_HTML)
CDocScriptWriteCommand("</ol>\n");
else if (CDocInst->getOutputFormat() == CDOC_OUTPUT_ILEAF)
;
else {
if (cdoc_general_list->compact)
CDocScriptSkipLine();
}
/* Remove the List and reset the current List */
cdoc_general_list = CDocScriptEndGeneralList(ORDERED_LIST);
}
else
CDocScriptWarning("Invalid End Ordered List");
}
/* End Simple List */
else if (colon_command->getCommand() == "esl") {
if (cdoc_general_list != NULL && cdoc_general_list->type == SIMPLE_LIST &&
CDocScriptIsCurrentListType(SIMPLE_LIST)) {
/* If the list was compact then add a Newline
at then end */
if (CDocInst->getOutputFormat() == CDOC_OUTPUT_HTML)
CDocScriptWriteCommand("</ul>\n");
else if (CDocInst->getOutputFormat() == CDOC_OUTPUT_ILEAF)
;
else {
if (cdoc_general_list->compact)
CDocScriptSkipLine();
}
/* Remove the List and reset the current List */
cdoc_general_list = CDocScriptEndGeneralList(SIMPLE_LIST);
}
else
CDocScriptWarning("Invalid End Ordered List");
}
/* End Unordered List */
else if (colon_command->getCommand() == "eul") {
if (cdoc_general_list != NULL && cdoc_general_list->type == UNORDERED_LIST &&
CDocScriptIsCurrentListType(UNORDERED_LIST)) {
/* If the list was compact then add a Newline
at then end */
if (CDocInst->getOutputFormat() == CDOC_OUTPUT_HTML)
CDocScriptWriteCommand("</ul>\n");
else if (CDocInst->getOutputFormat() == CDOC_OUTPUT_ILEAF)
;
else {
if (cdoc_general_list->compact)
CDocScriptSkipLine();
}
/* Remove the List and reset the current List */
cdoc_general_list =
CDocScriptEndGeneralList(UNORDERED_LIST);
}
else
CDocScriptWarning("Invalid End Unordered List");
}
/* Glossary List */
else if (colon_command->getCommand() == "gl") {
if (CDocInst->getOutputFormat() != CDOC_OUTPUT_HTML &&
CDocInst->getOutputFormat() != CDOC_OUTPUT_ILEAF) {
if (CDocScriptGetCurrentListCompact())
CDocScriptSkipLine();
}
/* Create and Store Glossary List Structure */
cdoc_glossary_list = CDocScriptCreateGlossaryList();
/* Set structure values from Parameter/Value pairs */
CDocExtractParameterValues(colon_command->getParameters(),
colon_command->getValues(),
gl_parameter_data,
(char *) cdoc_glossary_list);
cdoc_glossary_list->term_highlight %= 4;
/* Add Glossary List Structure as the Current List */
CDocScriptStartGlossaryList(cdoc_glossary_list);
if (CDocInst->getOutputFormat() == CDOC_OUTPUT_HTML) {
if (CDocScriptGetCurrentListCompact())
CDocScriptWriteCommand("<dl compact>\n");
else
CDocScriptWriteCommand("<dl>\n");
}
}
/* Glossary Term */
else if (colon_command->getCommand() == "gt") {
/* Spell Check if Required */
if (cdoc_spell_check && cdoc_spell_active)
CSpellCheckString(colon_command->getText());
/* Set Glossary Prefix to Text String */
if (cdoc_glossary_list != NULL) {
if (CDocInst->getOutputFormat() == CDOC_OUTPUT_HTML) {
CDocScriptWriteCommand("<dt><b>%s</b></dt>\n",
CDocEncodeHtmlString(colon_command->getText()));
return;
}
else if (CDocInst->getOutputFormat() == CDOC_OUTPUT_ILEAF) {
CDocScriptWriteCommand("<\"para\">\n");
CDocScriptWriteCommand("%s%s%s\n",
ILEAF_BOLD_FONT,
CDocEncodeILeafString(colon_command->getText()),
ILEAF_NORMAL_FONT);
return;
}
glossary_prefix =
CDocScriptAddHighlightEscapes(colon_command->getText(),
cdoc_glossary_list->term_highlight);
}
else
CDocScriptWarning("Glossary Term outside Glossary List - %s %s",
colon_command->getCommand().c_str(), colon_command->getText().c_str());
}
/* Glossary Description */
else if (colon_command->getCommand() == "gd") {
if (cdoc_glossary_list != NULL) {
if (CDocInst->getOutputFormat() == CDOC_OUTPUT_HTML) {
CDocScriptWriteCommand("<dd>%s</dd>\n",
CDocEncodeHtmlString(colon_command->getText()));
return;
}
else if (CDocInst->getOutputFormat() == CDOC_OUTPUT_ILEAF) {
CDocScriptWriteCommand("<\"para\">\n");
CDocScriptWriteCommand("%s\n",
CDocEncodeILeafString(colon_command->getText()));
return;
}
/* Set paragraph to Glossary Term (if specified) and
Glossary Description Text */
if (glossary_prefix != "") {
CDocScriptNewParagraph(glossary_prefix, GLOSSARY_PARAGRAPH, true, LEFT_JUSTIFICATION);
CDocScriptAddStringToParagraph(": ");
CDocScriptAddStringToParagraph(colon_command->getText());
glossary_prefix = "";
}
else {
CDocScriptNewParagraph("???: ", GLOSSARY_PARAGRAPH, true, LEFT_JUSTIFICATION);
CDocScriptAddStringToParagraph(colon_command->getText());
}
}
else
CDocScriptWarning("Glossary Data outside Glossary List - %s %s",
colon_command->getCommand().c_str(), colon_command->getText().c_str());
}
/* End Glossary List */
else if (colon_command->getCommand() == "egl") {
if (cdoc_glossary_list != NULL &&
CDocScriptIsCurrentListType(GLOSSARY_LIST)) {
/* If the list was compact then add a Newline
at then end */
if (CDocInst->getOutputFormat() == CDOC_OUTPUT_HTML)
CDocScriptWriteCommand("</dl>\n");
else if (CDocInst->getOutputFormat() == CDOC_OUTPUT_ILEAF)
;
else {
if (cdoc_glossary_list->compact)
CDocScriptSkipLine();
}
/* Remove the Glossary List and reset the current
Glossary List */
cdoc_glossary_list = CDocScriptEndGlossaryList();
}
else
CDocScriptWarning("Invalid End Glossary List");
}
/* Headings */
else if (colon_command->getCommand()[0] == 'h' &&
isdigit(colon_command->getCommand()[1])) {
CDHeading heading;
heading.ident = NULL;
heading.stitle = NULL;
/* Spell Check if Required */
if (cdoc_spell_check && cdoc_spell_active)
CSpellCheckString(colon_command->getText());
/* Calculate the Heading Level */
level = (colon_command->getCommand()[1] - '0') % CDOC_MAX_HEADERS;
/* Process Parameter List */
heading.ident = NULL;
heading.stitle = NULL;
if (level == 0 || level == 1)
CDocExtractParameterValues(colon_command->getParameters(),
colon_command->getValues(),
h01_parameter_data,
(char *) &heading);
else
CDocExtractParameterValues(colon_command->getParameters(),
colon_command->getValues(),
h26_parameter_data,
(char *) &heading);
if (CDocInst->getOutputFormat() == CDOC_OUTPUT_HTML) {
if (header_control[level].new_page)
CDocScriptStartSection(colon_command->getText());
CDocScriptWriteCommand("<h%d>%s</h%d>\n",
level, CDocEncodeHtmlString(colon_command->getText()), level);
return;
}
else if (CDocInst->getOutputFormat() == CDOC_OUTPUT_ILEAF) {
if (header_control[level].new_page)
CDocScriptStartSection(colon_command->getText());
CDocScriptWriteCommand("<\"head\">\n");
CDocScriptWriteCommand("<|,\"%d\">%s\n", level,
CDocEncodeILeafString(colon_command->getText()));
return;
}
/* Set Left Margin */
if (! header_control[level].toc_only) {
if (level <= 1)
cdoc_left_margin = cdoc_save_left_margin;
else if (level < 5)
cdoc_left_margin = cdoc_save_left_margin + 2*(level - 1);
}
/* Add Space before Header Text */
strcpy(temp_string, "");
for (i = 0; i < header_control[level].space_before; i++)
strcat(temp_string, " ");
/* If the Header is numbered and is in the body or
appendix section then add the number text */
if (header_control[level].number_header &&
(cdoc_document.part == CDOC_BODY_PART ||
cdoc_document.part == CDOC_APPENDIX_PART)) {
int header_no;
CDocScriptStartHeader(level);
/* Create Header number from the Depth of each Header Level
below and equal to the current Header Level's Depth */
for (i = 1; i <= level; i++) {
header_no = CDocScriptGetHeader(i);
/* Use Alphabetic Characters for the Appendix */
char temp_string1[256];
if (i == 1) {
if (cdoc_document.part == CDOC_APPENDIX_PART)
sprintf(temp_string1, "Appendix %c",
cdoc_a_to_z[(header_no - appendix_depth - 1) % 26]);
else
sprintf(temp_string1, "%d", header_no);
}
else
sprintf(temp_string1, ".%d", header_no);
strcat(temp_string, temp_string1);
}
/* Add '.0' for First Level Normal Headers and '.'
for First Level Appendix Headers */
if (level == 1) {
if (cdoc_document.part != CDOC_APPENDIX_PART)
strcat(temp_string, ".0");
else
strcat(temp_string, ".");
}
/* Add spacing between Number Text and Header Text */
if (level > 0)
strcat(temp_string, " ");
}
/* Convert to Upper Case if Header is Capitalised */
if (header_control[level].capitalised)
CStrUtil::toUpper(colon_command->getText());
/* Use Header Number if Global Switch is On */
std::string temp_string1;
if (cdoc_number_headers)
temp_string1 = temp_string + colon_command->getText();
else
temp_string1 = colon_command->getText();
/* Add any space required after header */
for (i = 0; i < header_control[level].space_after; i++)
temp_string1 += " ";
/* If Header appears on its own then output as a title,
otherwise add to the current text */
if (header_control[level].break_header) {
/* Reset Indentation */
cdoc_indent = 0;
/* If new page required start a new section of the
document (also causes a page throw), otherwise
output header on separate line as a sub-section */
if (header_control[level].new_page)
CDocScriptStartSection(colon_command->getText());
else {
if (CDocIsPagedOutput()) {
//int lines_per_page = CDocScriptGetLinesPerPage();
int new_page = CDocScriptFindSpace(header_control[level].skip_before + 3);
if (! new_page) {
if (cdoc_paragraph_done)
CDocScriptSkipLine();
/* Output required number of blank lines
before header */
for (i = 0; i < header_control[level].skip_before - 1; i++)
CDocScriptSkipLine();
}
}
else {
if (cdoc_paragraph_done)
CDocScriptSkipLine();
/* Output required number of blank lines before header */
for (i = 0; i < header_control[level].skip_before - 1; i++)
CDocScriptSkipLine();
}
std::string temp_string = " " + colon_command->getText();
CDocScriptStartSubSection(temp_string);
}
/* If header only appears in table of contents then
don't output the header in the main text */
if (! header_control[level].toc_only) {
CDocScriptWriteIndent(cdoc_left_margin + cdoc_indent);
CStrUtil::stripSpaces(temp_string1);
if (header_control[level].underscored)
CDocScriptWriteText("%s%s%s\n",
CDocStartUnderline(), temp_string1.c_str(), CDocEndUnderline());
else
CDocScriptWriteText("%s%s%s\n",
CDocStartBold(), temp_string1.c_str(), CDocEndBold());
if (header_control[level].underscored &&
CDocInst->getOutputFormat() == CDOC_OUTPUT_RAW)
CDocScriptDrawHLine(cdoc_indent,
CDocStringDisplayLength(temp_string1) - cdoc_indent - 1);
CDocScriptSkipLine();
cdoc_paragraph_done = false;
}
cdoc_left_margin++;
}
else {
/* If header only appears in table of contents then
don't add the header as a new paragraph */
if (! header_control[level].toc_only) {
std::string temp_string = temp_string1 + " ";
if (header_control[level].underscored)
CDocScriptSetParagraphPrefix(temp_string, CDOC_BOLD_UNDERLINE_FONT, false);
else
CDocScriptSetParagraphPrefix(temp_string, CDOC_BOLD_FONT, false);
}
}
/* If we have a reference identifier then set its
Page Number */
if (heading.ident != NULL)
CDocScriptSetReferencePageNumber(HEADER_REF, heading.ident);
CDocScriptSetTOCPage();
}
/* Notes */
else if (colon_command->getCommand() == "note") {
if (CDocInst->getOutputFormat() == CDOC_OUTPUT_HTML) {
CDocScriptWriteCommand("<p><b>Note:</b> %s\n",
CDocEncodeHtmlString(colon_command->getText()));
return;
}
else if (CDocInst->getOutputFormat() == CDOC_OUTPUT_ILEAF) {
CDocScriptWriteCommand("<\"para\">\n");
CDocScriptWriteCommand("%s\n",
CDocEncodeILeafString(colon_command->getText()));
return;
}
/* Set Paragraph Prefix to 'Note:' Text */
strcpy(temp_string, "Note: ");
CDocScriptSetParagraphPrefix(temp_string, CDOC_BOLD_FONT, true);
/* Set Paragraph to Note Text */
if (CDocScriptGetCurrentListCompact())
CDocScriptSkipLine();
if (CDocScriptIsCurrentList())
CDocScriptNewParagraph(colon_command->getText(), SUB_LIST_PARAGRAPH1,
true, LEFT_JUSTIFICATION);
else
CDocScriptNewParagraph(colon_command->getText(), NORMAL_PARAGRAPH,
true, LEFT_JUSTIFICATION);
}
/* Table Row Definition (does not use CDocExtractParameterValues
as this cannot handle arrays of values) */
else if (colon_command->getCommand() == "rdef") {
/* Allocate Row Definition Structure */
CDTableRowDef *row_definition = CDocScriptCreateTableRowDef();
/* Set structure values from Parameter/Value pairs */
for (uint i = 0; i < colon_command->getNumParameters(); i++) {
if (colon_command->getParameter(i) == "id")
row_definition->name = CStrUtil::strdup(colon_command->getValue(i));
else if (colon_command->getParameter(i) == "hp") {
std::vector<std::string> words;
CDocStringToWords(colon_command->getValue(i), words);
uint no_words = words.size();
if (no_words > 0)
row_definition->highlights = new int [no_words];
else
row_definition->highlights = NULL;
row_definition->no_highlights = no_words;
for (uint j = 0; j < no_words; j++)
row_definition->highlights[j] = CStrUtil::toInteger(words[j]) % 4;
}
else if (colon_command->getParameter(i) == "align") {
std::vector<std::string> words;
CDocStringToWords(colon_command->getValue(i), words);
uint no_words = words.size();
if (no_words > 0)
row_definition->aligns = new int [no_words];
else
row_definition->aligns = NULL;
row_definition->no_aligns = no_words;
for (uint j = 0; j < no_words; j++) {
CStrUtil::toLower(words[j]);
if (words[j] == "left")
row_definition->aligns[j] = CHALIGN_TYPE_LEFT;
else if (words[j] == "center")
row_definition->aligns[j] = CHALIGN_TYPE_CENTRE;
else if (words[j] == "centre")
row_definition->aligns[j] = CHALIGN_TYPE_CENTRE;
else if (words[j] == "right")
row_definition->aligns[j] = CHALIGN_TYPE_RIGHT;
else if (words[j] == "inside")
row_definition->aligns[j] = CHALIGN_TYPE_INSIDE;
else if (words[j] == "outside")
row_definition->aligns[j] = CHALIGN_TYPE_OUTSIDE;
else if (words[j] == "justify")
row_definition->aligns[j] = CHALIGN_TYPE_JUSTIFY;
else {
CDocScriptWarning("Invalid Value for Row Definition Align '%s'", words[j].c_str());
row_definition->aligns[j] = CHALIGN_TYPE_LEFT;
}
}
}
else if (colon_command->getParameter(i) == "concat") {
std::vector<std::string> words;
CDocStringToWords(colon_command->getValue(i), words);
uint no_words = words.size();
if (no_words > 0)
row_definition->concats = new int [no_words];
else
row_definition->concats = NULL;
row_definition->no_concats = no_words;
for (uint j = 0; j < no_words; j++) {
CStrUtil::toLower(words[j]);
if (words[j] == "yes")
row_definition->concats[j] = true;
else if (words[j] == "no")
row_definition->concats[j] = false;
else {
CDocScriptWarning( "Invalid Value for Row Definition Concat '%s'", words[j].c_str());
row_definition->concats[j] = true;
}
}
}
else if (colon_command->getParameter(i) == "valign") {
std::vector<std::string> words;
CDocStringToWords(colon_command->getValue(i), words);
uint no_words = words.size();
if (no_words > 0)
row_definition->valigns = new int [no_words];
else
row_definition->valigns = NULL;
row_definition->no_valigns = no_words;
for (uint j = 0; j < no_words; j++) {
CStrUtil::toLower(words[j]);
if (words[j] == "top")
row_definition->valigns[j] = CVALIGN_TYPE_TOP;
else if (words[j] == "center")
row_definition->valigns[j] = CVALIGN_TYPE_CENTRE;
else if (words[j] == "centre")
row_definition->valigns[j] = CVALIGN_TYPE_CENTRE;
else if (words[j] == "bottom")
row_definition->valigns[j] = CVALIGN_TYPE_BOTTOM;
else {
CDocScriptWarning( "Invalid Value for Row Definition Align '%s'", words[j].c_str());
row_definition->valigns[j] = CVALIGN_TYPE_TOP;
}
}
}
else if (colon_command->getParameter(i) == "rotate") {
std::vector<std::string> words;
CDocStringToWords(colon_command->getValue(i), words);
uint no_words = words.size();
if (no_words > 0)
row_definition->rotates = new int [no_words];
else
row_definition->rotates = NULL;
row_definition->no_rotates = no_words;
for (uint j = 0; j < no_words; j++) {
row_definition->rotates[j] = CStrUtil::toInteger(words[j]) % 360;
if (row_definition->rotates[j] != 0 && row_definition->rotates[j] != 90 &&
row_definition->rotates[j] != 180 && row_definition->rotates[j] != 270 &&
row_definition->rotates[j] != -90 && row_definition->rotates[j] != -180 &&
row_definition->rotates[j] != -270) {
CDocScriptWarning("Invalid Value for Row Definition Rotation '%s'",
words[j].c_str());
row_definition->rotates[j] = 0;
}
}
}
else if (colon_command->getParameter(i) == "mindepth") {
std::vector<std::string> words;
CDocStringToWords(colon_command->getValue(i), words);
uint no_words = words.size();
if (no_words > 0)
row_definition->mindepths = new int [no_words];
else
row_definition->mindepths = NULL;
row_definition->no_mindepths = no_words;
for (uint j = 0; j < no_words; j++)
row_definition->mindepths[j] = CStrUtil::toInteger(words[j]);
}
else if (colon_command->getParameter(i) == "arrange") {
std::vector<std::string> words;
CDocStringToWords(colon_command->getValue(i), words);
uint no_words = words.size();
if (no_words > 0) {
int no_arrange = 0;
int *arrange = new int [no_words];
for (uint j = 0; j < no_words; j++) {
if (words[j] == "/") {
row_definition->arrange_list .push_back(arrange);
row_definition->no_arrange_list.push_back(no_arrange);
no_arrange = 0;
arrange = new int [no_words - j - 1];
}
else
arrange[no_arrange++] = CStrUtil::toInteger(words[j]);
}
row_definition->arrange_list .push_back(arrange);
row_definition->no_arrange_list.push_back(no_arrange);
}
}
else if (colon_command->getParameter(i) == "cwidths") {
std::vector<std::string> words;
CDocStringToWords(colon_command->getValue(i), words);
uint no_words = words.size();
if (no_words > 0)
row_definition->cwidths = new int [no_words];
else
row_definition->cwidths = NULL;
row_definition->no_cwidths = no_words;
for (uint j = 0; j < no_words; j++) {
if (words[j][words[j].size() - 1] == '*') {
words[j] = words[j].substr(0, words[j].size() - 1);
if (words[j].size() == 0)
row_definition->cwidths[j] = -1;
else
row_definition->cwidths[j] = -CStrUtil::toInteger(words[j]);
if (row_definition->cwidths[j] == 0)
row_definition->cwidths[j] = -1;
}
else
row_definition->cwidths[j] =
CDocLengthStringToChars(words[j]);
}
}
else if (colon_command->getParameter(i) == "shade") {
if (CStrUtil::casecmp(colon_command->getValue(i), "xlight") == 0)
row_definition->shade = SHADE_XLIGHT;
else if (CStrUtil::casecmp(colon_command->getValue(i), "light") == 0)
row_definition->shade = SHADE_LIGHT;
else if (CStrUtil::casecmp(colon_command->getValue(i), "medium") == 0)
row_definition->shade = SHADE_MEDIUM;
else if (CStrUtil::casecmp(colon_command->getValue(i), "dark") == 0)
row_definition->shade = SHADE_DARK;
else if (CStrUtil::casecmp(colon_command->getValue(i), "xdark") == 0)
row_definition->shade = SHADE_XDARK;
else
CDocScriptWarning("Invalid Value '%s' for Shade",
colon_command->getValue(i).c_str());
}
else
CDocScriptWarning("Invalid Parameter '%s' for Command '%s'",
colon_command->getParameter(i).c_str(),
colon_command->getCommand().c_str());
}
if (row_definition->name != "" && row_definition->no_cwidths > 0) {
/* Set Width of Non-Free Cells and Count of Free Cells
and Total Cells in Free Cells */
row_definition->width = 1;
row_definition->free_cells1 = 0;
row_definition->free_cells2 = 0;
for (j = 0; j < row_definition->no_cwidths; j++) {
if (row_definition->cwidths[j] < 0) {
row_definition->free_cells1++;
row_definition->free_cells2 += -row_definition->cwidths[j];
row_definition->width += 2;
}
else
row_definition->width += row_definition->cwidths[j] + 1;
}
CDocScriptAddTableRowDef(row_definition);
}
else {
delete row_definition;
if (row_definition->name == "")
CDocScriptError("Invalid Row Definition - No Name");
else
CDocScriptError("Invalid Row Definition - No Cell Widths");
}
}
/* Table */
else if (colon_command->getCommand() == "table") {
if (current_table != NULL) {
CDocScriptWarning("Unterminated Table");
CDocScriptOutputTable(current_table);
if (current_table->id != "")
CDocScriptSetReferencePageNumber(TABLE_REF, current_table->id);
CDocScriptSetTablePage(current_table);
}
/* Process Table (Details already recorded in Pass 1) */
table_number++;
/* Get Pass 1 Table Details */
current_table = CDocScriptGetTable(table_number);
if (current_table != NULL) {
/* Set the Table's Row Definition */
CDocScriptSetTableRowDef(current_table);
if (current_table->row_definition == NULL) {
CDocScriptError("Table has no Row Definition");
current_table = NULL;
}
if (CDocInst->getOutputFormat() == CDOC_OUTPUT_HTML) {
CDocScriptWriteCommand("<table border>\n");
return;
}
}
else
CDocScriptError("Table Not Found - Internal Error");
}
/* Long Quote */
else if (colon_command->getCommand() == "lq") {
if (CDocInst->getOutputFormat() == CDOC_OUTPUT_HTML) {
CDocScriptWriteCommand("<blockquote>\n");
return;
}
long_quotation_depth++;
if (cdoc_right_margin - cdoc_left_margin >= 8) {
cdoc_left_margin += 2;
cdoc_right_margin -= 2;
}
}
else if (colon_command->getCommand() == "elq") {
if (CDocInst->getOutputFormat() == CDOC_OUTPUT_HTML) {
CDocScriptWriteCommand("</blockquote>\n");
return;
}
if (long_quotation_depth == 0)
CDocScriptWarning("End Long Quotation outside Long Quotation");
else {
long_quotation_depth--;
if (cdoc_right_margin - cdoc_left_margin >= 4) {
cdoc_left_margin -= 2;
cdoc_right_margin += 2;
}
}
}
/* Paragraph */
else if (colon_command->getCommand() == "p") {
if (CDocInst->getOutputFormat() == CDOC_OUTPUT_HTML) {
CDocScriptWriteCommand("<p>%s\n",
CDocEncodeHtmlString(colon_command->getText()));
return;
}
else if (CDocInst->getOutputFormat() == CDOC_OUTPUT_ILEAF) {
CDocScriptWriteCommand("<\"para\">\n");
CDocScriptWriteCommand("%s\n",
CDocEncodeILeafString(colon_command->getText()));
return;
}
if (cdoc_paragraph->getPrefix() != "") {
std::string temp_string = cdoc_paragraph->getPrefix();
no_spaces = 0;
j = temp_string.size() - 1;
while (j >= 0 && isspace(temp_string[j])) {
++no_spaces;
temp_string = temp_string.substr(0, j--);
}
temp_string += ":";
for (j = 0; j < no_spaces; j++)
temp_string += " ";
cdoc_paragraph->setPrefix(temp_string);
}
if (CDocScriptIsCurrentList())
CDocScriptNewParagraph(colon_command->getText(), SUB_LIST_PARAGRAPH1,
true, LEFT_JUSTIFICATION);
else
CDocScriptNewParagraph(colon_command->getText(), NORMAL_PARAGRAPH,
true, LEFT_JUSTIFICATION);
}
/* Paragraph Continuation */
else if (colon_command->getCommand() == "pc") {
if (CDocInst->getOutputFormat() == CDOC_OUTPUT_HTML) {
CDocScriptWriteCommand("<p>%s\n",
CDocEncodeHtmlString(colon_command->getText()));
return;
}
else if (CDocInst->getOutputFormat() == CDOC_OUTPUT_ILEAF) {
CDocScriptWriteCommand("<\"para\">\n");
CDocScriptWriteCommand("%s\n",
CDocEncodeILeafString(colon_command->getText()));
return;
}
CDocScriptNewParagraph(colon_command->getText(), NORMAL_PARAGRAPH,
true, LEFT_JUSTIFICATION);
}
/* List Paragraph */
else if (colon_command->getCommand() == "lp") {
if (CDocInst->getOutputFormat() == CDOC_OUTPUT_HTML) {
CDocScriptWriteCommand("<p>%s\n",
CDocEncodeHtmlString(colon_command->getText()));
return;
}
else if (CDocInst->getOutputFormat() == CDOC_OUTPUT_ILEAF) {
CDocScriptWriteCommand("<\"para\">\n");
CDocScriptWriteCommand("%s\n",
CDocEncodeILeafString(colon_command->getText()));
return;
}
/* Label this Paragraph as a List Paragraph so it
can be formatted correctly */
if (CDocScriptIsCurrentList())
CDocScriptNewParagraph(colon_command->getText(), SUB_LIST_PARAGRAPH2,
true, LEFT_JUSTIFICATION);
else {
CDocScriptError("List Paragraph Outside List");
CDocScriptNewParagraph(colon_command->getText(), NORMAL_PARAGRAPH,
true, LEFT_JUSTIFICATION);
}
}
/* Footnotes */
else if (colon_command->getCommand() == "fn") {
if (current_footnote != NULL) {
CDocScriptWarning("Unterminated Footnote");
CDocScriptEndFootnote(current_footnote);
if (current_footnote->ident != "")
CDocScriptSetReferencePageNumber(FOOTNOTE_REF, current_footnote->ident);
}
current_footnote = CDocScriptCreateFootnote();
/* Get Footnote Parameter Values */
CDocExtractParameterValues(colon_command->getParameters(),
colon_command->getValues(),
fn_parameter_data,
(char *) current_footnote);
/* Start Footnote Processing */
CDocScriptStartFootnote(current_footnote);
/* Add Command Text (if any) */
CDocScriptAddStringToParagraph(colon_command->getText());
}
else if (colon_command->getCommand() == "efn") {
if (current_footnote != NULL) {
/* End Footnote Processing */
CDocScriptEndFootnote(current_footnote);
if (current_footnote->ident != "")
CDocScriptSetReferencePageNumber(FOOTNOTE_REF, current_footnote->ident);
current_footnote = NULL;
}
else
CDocScriptError("End Footnote outside Footnote");
}
/* Examples */
else if (colon_command->getCommand() == "xmp") {
if (current_example == NULL) {
current_example = CDocScriptCreateExample();
/* Get Parameter Values */
CDocExtractParameterValues(colon_command->getParameters(),
colon_command->getValues(),
xmp_parameter_data,
(char *) current_example);
/* Start Example */
CDocScriptExampleBegin(current_example);
}
else
CDocScriptError("Cannot have Example inside Example");
}
else if (colon_command->getCommand() == "exmp") {
if (current_example != NULL) {
/* End Example */
CDocScriptExampleEnd(current_example);
current_example = NULL;
}
else
CDocScriptError("End Example when not in Example");
}
/* Page Throws */
else if (colon_command->getCommand() == "pa")
CDocScriptNewPage();
/* Ignore EDS setup tag */
else if (colon_command->getCommand() == "doceds")
;
else
CDocScriptWarning("Invalid Colon Command - %s %s",
colon_command->getCommand().c_str(), colon_command->getText().c_str());
}
/* Ignore EDS setup tag */
else if (colon_command->getCommand() == "doceds")
;
/* Unrecognized Command */
else
CDocScriptWarning("Invalid Colon Command - %s %s",
colon_command->getCommand().c_str(), colon_command->getText().c_str());
}
// Process any inline colon commands and replace then with the required text
// or control characters.
static void
CDocReplaceEmbeddedColonCommands(CDScriptLine *script_line)
{
/* Get Script Line's Text */
std::string text;
if (script_line->getType() == CDOC_DOT_COMMAND)
text = script_line->getDotCommand()->getText();
else if (script_line->getType() == CDOC_COLON_COMMAND)
text = script_line->getColonCommand()->getText();
else
text = script_line->getData();
const char *p1 = text.c_str();
/* Get Length of New Line */
bool changed = false;
int i = 0;
while (*p1 != '\0') {
/* Citation */
if (CStrUtil::casencmp(p1, ":cit", 4) == 0 &&
(p1[4] == '.' || isspace(p1[4]) || p1[4] == '\0')) {
/* Insert Bold Escape Code if Output Format can handle it */
if (CDocInst->getOutputFormat() == CDOC_OUTPUT_RAW_CC ||
CDocInst->getOutputFormat() == CDOC_OUTPUT_CDOC ||
CDocInst->getOutputFormat() == CDOC_OUTPUT_TROFF ||
CDocInst->getOutputFormat() == CDOC_OUTPUT_HTML ||
CDocInst->getOutputFormat() == CDOC_OUTPUT_ILEAF)
i += strlen(CDocStartBold());
/* Skip Command */
if (p1[4] == '.')
p1 += 5;
else
p1 += 4;
changed = true;
}
/* End Citation */
else if (CStrUtil::casencmp(p1, ":ecit", 5) == 0 &&
(p1[5] == '.' || isspace(p1[5]) || p1[5] == '\0')) {
if (CDocInst->getOutputFormat() == CDOC_OUTPUT_RAW_CC ||
CDocInst->getOutputFormat() == CDOC_OUTPUT_CDOC ||
CDocInst->getOutputFormat() == CDOC_OUTPUT_TROFF ||
CDocInst->getOutputFormat() == CDOC_OUTPUT_HTML ||
CDocInst->getOutputFormat() == CDOC_OUTPUT_ILEAF)
i += strlen(CDocEndBold());
/* Skip Command */
if (p1[5] == '.')
p1 += 6;
else
p1 += 5;
changed = true;
}
/* Highlighting */
else if (CStrUtil::casencmp(p1, ":hp", 3) == 0 && isdigit(p1[3]) &&
(p1[4] == '.' || isspace(p1[4]) || p1[4] == '\0')) {
int level = (p1[3] - '0') % 4;
const char *str = CDocScriptStartParagraphHighlight(level);
if (CDocInst->getOutputFormat() == CDOC_OUTPUT_RAW_CC ||
CDocInst->getOutputFormat() == CDOC_OUTPUT_CDOC ||
CDocInst->getOutputFormat() == CDOC_OUTPUT_TROFF ||
CDocInst->getOutputFormat() == CDOC_OUTPUT_HTML ||
CDocInst->getOutputFormat() == CDOC_OUTPUT_ILEAF)
i += strlen(str);
/* Skip Command */
if (p1[4] == '.')
p1 += 5;
else
p1 += 4;
changed = true;
}
/* End Highlighting */
else if (CStrUtil::casencmp(p1, ":ehp", 4) == 0 && isdigit(p1[4]) &&
(p1[5] == '.' || isspace(p1[5]) || p1[5] == '\0')) {
int level = (p1[4] - '0') % 4;
const char *str = CDocScriptEndParagraphHighlight(level);
if (CDocInst->getOutputFormat() == CDOC_OUTPUT_RAW_CC ||
CDocInst->getOutputFormat() == CDOC_OUTPUT_CDOC ||
CDocInst->getOutputFormat() == CDOC_OUTPUT_TROFF ||
CDocInst->getOutputFormat() == CDOC_OUTPUT_HTML ||
CDocInst->getOutputFormat() == CDOC_OUTPUT_ILEAF)
i += strlen(str);
/* Skip Command */
if (p1[5] == '.')
p1 += 6;
else
p1 += 5;
changed = true;
}
/* Cross References */
else if (CStrUtil::casencmp(p1, ":figref", 7) == 0 ||
CStrUtil::casencmp(p1, ":fnref" , 6) == 0 ||
CStrUtil::casencmp(p1, ":hdref" , 6) == 0 ||
CStrUtil::casencmp(p1, ":iref" , 5) == 0 ||
CStrUtil::casencmp(p1, ":liref" , 6) == 0 ||
CStrUtil::casencmp(p1, ":tref" , 5) == 0) {
int type = 0;
CDParameterData *parameter_data;
const char *p2 = p1;
if (CStrUtil::casencmp(p1, ":figref", 7) == 0) {
type = FIGURE_REF;
parameter_data = figref_parameter_data;
p1 += 7;
}
else if (CStrUtil::casencmp(p1, ":fnref" , 6) == 0) {
type = FOOTNOTE_REF;
parameter_data = fnref_parameter_data;
p1 += 6;
}
else if (CStrUtil::casencmp(p1, ":hdref" , 6) == 0) {
type = HEADER_REF;
parameter_data = hdref_parameter_data;
p1 += 6;
}
else if (CStrUtil::casencmp(p1, ":iref" , 5) == 0) {
type = INDEX_REF;
parameter_data = iref_parameter_data;
p1 += 5;
}
else if (CStrUtil::casencmp(p1, ":liref" , 6) == 0) {
type = LIST_ITEM_REF;
parameter_data = liref_parameter_data;
p1 += 6;
}
else if (CStrUtil::casencmp(p1, ":tref" , 5) == 0) {
type = TABLE_REF;
parameter_data = tref_parameter_data;
p1 += 5;
}
/* Skip Spaces after Command */
CStrUtil::skipSpace(&p1);
/* Extract Reference Values */
bool reference_done = false;
CDCrossRef cross_ref;
CDIndexRef index_ref;
if (type == INDEX_REF) {
index_ref.refid = NULL;
index_ref.pg = NULL;
index_ref.see = NULL;
index_ref.seeid = NULL;
}
else {
cross_ref.type = type;
cross_ref.refid = NULL;
cross_ref.page = true;
}
int j = 0;
while (! reference_done && *p1 != '\0' &&
parameter_data[j].name != NULL) {
int len = strlen(parameter_data[j].name);
if (CStrUtil::casencmp(p1, parameter_data[j].name, len) == 0 &&
p1[len] == '=') {
p1 += len + 1;
/* Get Reference Value (may be quoted) */
int k = 0;
char temp_string[256];
if (*p1 == '\'') {
p1++;
while (*p1 != '\0' && *p1 != '\'')
temp_string[k++] = *p1++;
if (*p1 == '\'')
p1++;
}
else {
while (*p1 != '\0' && *p1 != '.' && isalnum(*p1))
temp_string[k++] = *p1++;
}
temp_string[k] = '\0';
std::string temp_string1 = CDocScriptReplaceSymbolsInString(temp_string);
if (type == INDEX_REF)
CDocExtractParameterValue(temp_string1, ¶meter_data[j], (char *) &index_ref);
else
CDocExtractParameterValue(temp_string1, ¶meter_data[j], (char *) &cross_ref);
/* Skip Space after Reference Value */
CStrUtil::skipSpace(&p1);
/* Reference Terminated */
if (*p1 == '\0' || *p1 == '.') {
reference_done = true;
if (*p1 == '.')
p1++;
}
j = 0;
}
else
j++;
}
if (type == INDEX_REF && index_ref.refid != NULL) {
changed = true;
delete [] index_ref.refid;
}
else if (cross_ref.refid != NULL) {
/* Make sure Reference Identifier is in Lower Case */
CStrUtil::toLower(cross_ref.refid);
/* Get Reference Text for this Identifier */
std::string reference = CDocScriptGetParagraphReferenceText(&cross_ref);
/* Add Reference Text to Paragraph */
i += reference.size();
if (! reference_done)
i++;
changed = true;
delete [] cross_ref.refid;
}
else {
p1 = p2;
i++;
p1++;
}
}
/* Hook */
else if (CStrUtil::casencmp(p1, ":hook", 5) == 0) {
CDHookParameterData hook_data;
const char *p2 = p1;
p1 += 5;
/* Skip Spaces after Command */
CStrUtil::skipSpace(&p1);
/* Extract Hook Values */
bool done = false;
int j = 0;
while (! done && *p1 != '\0' &&
hook_parameter_data[j].name != NULL) {
int len = strlen(hook_parameter_data[j].name);
if (CStrUtil::casencmp(p1, hook_parameter_data[j].name, len) == 0 &&
p1[len] == '=') {
p1 += len + 1;
/* Get Hook Value (may be quoted) */
int k = 0;
char temp_string[256];
if (*p1 == '\'') {
p1++;
while (*p1 != '\0' && *p1 != '\'')
temp_string[k++] = *p1++;
if (*p1 == '\'')
p1++;
}
else {
while (*p1 != '\0' && *p1 != '.' && isalnum(*p1))
temp_string[k++] = *p1++;
}
temp_string[k] = '\0';
std::string temp_string1 = CDocScriptReplaceSymbolsInString(temp_string);
CDocExtractParameterValue(temp_string1, &hook_parameter_data[j], (char *) &hook_data);
/* Skip Space after Reference Value */
CStrUtil::skipSpace(&p1);
/* Hook Terminated */
if (*p1 == '\0' || *p1 == '.') {
done = true;
if (*p1 == '.')
p1++;
}
j = 0;
}
else
j++;
}
if (hook_data.id != NULL) {
CDHookData hook_data1(hook_data.id, hook_data.data, hook_data.text);
/* Add Hook Text to Paragraph */
std::string text = CDocScriptGetHookText(&hook_data1);
i += text.size();
if (! done)
i++;
changed = true;
}
else {
p1 = p2;
i++;
p1++;
}
}
/* Start Quotation */
else if (CStrUtil::casencmp(p1, ":q", 2) == 0 &&
(p1[2] == '.' || isspace(p1[2]) || p1[2] == '\0')) {
/* Opening Quotation Mark */
i++;
/* Skip Command */
if (p1[2] == '.')
p1 += 3;
else
p1 += 2;
changed = true;
}
/* End Citation */
else if (CStrUtil::casencmp(p1, ":eq", 3) == 0 &&
(p1[3] == '.' || isspace(p1[3]) || p1[3] == '\0')) {
/* Closing Quotation Mark */
i++;
/* Skip Command */
if (p1[3] == '.')
p1 += 4;
else
p1 += 3;
changed = true;
}
/* New Line */
else if (CStrUtil::casencmp(p1, ":nl", 3) == 0 &&
(p1[3] == '.' || isspace(p1[3]) || p1[3] == '\0')) {
/* Newline Character */
i++;
/* Skip Command */
if (p1[3] == '.')
p1 += 4;
else
p1 += 3;
changed = true;
}
/* Break */
else if (CStrUtil::casencmp(p1, ":br", 3) == 0 &&
(p1[3] == '.' || isspace(p1[3]) || p1[3] == '\0')) {
/* Newline Character */
i++;
/* Skip Command */
if (p1[3] == '.')
p1 += 4;
else
p1 += 3;
changed = true;
}
else {
i++;
p1++;
}
}
/* If the line hasn't changed then just return */
if (! changed)
return;
/* Allocate line big enough to take new text */
char *line1 = new char [i + 2];
/* Get Script Line's Text */
if (script_line->getType() == CDOC_DOT_COMMAND)
p1 = (char *) script_line->getDotCommand()->getText().c_str();
else if (script_line->getType() == CDOC_COLON_COMMAND)
p1 = (char *) script_line->getColonCommand()->getText().c_str();
else
p1 = (char *) script_line->getData().c_str();
/* Set New Line */
i = 0;
while (*p1 != '\0') {
/* Citation */
if (CStrUtil::casencmp(p1, ":cit", 4) == 0 &&
(p1[4] == '.' || isspace(p1[4]) || p1[4] == '\0')) {
/* Insert Bold Escape Code if Output Format can handle it */
if (CDocInst->getOutputFormat() == CDOC_OUTPUT_RAW_CC ||
CDocInst->getOutputFormat() == CDOC_OUTPUT_CDOC ||
CDocInst->getOutputFormat() == CDOC_OUTPUT_TROFF ||
CDocInst->getOutputFormat() == CDOC_OUTPUT_HTML ||
CDocInst->getOutputFormat() == CDOC_OUTPUT_ILEAF) {
strcpy(&line1[i], CDocStartBold());
i += strlen(CDocStartBold());
}
/* Skip Command */
if (p1[4] == '.')
p1 += 5;
else
p1 += 4;
}
/* End Citation */
else if (CStrUtil::casencmp(p1, ":ecit", 5) == 0 &&
(p1[5] == '.' || isspace(p1[5]) || p1[5] == '\0')) {
if (CDocInst->getOutputFormat() == CDOC_OUTPUT_RAW_CC ||
CDocInst->getOutputFormat() == CDOC_OUTPUT_CDOC ||
CDocInst->getOutputFormat() == CDOC_OUTPUT_TROFF ||
CDocInst->getOutputFormat() == CDOC_OUTPUT_HTML ||
CDocInst->getOutputFormat() == CDOC_OUTPUT_ILEAF) {
strcpy(&line1[i], CDocEndBold());
i += strlen(CDocEndBold());
}
/* Skip Command */
if (p1[5] == '.')
p1 += 6;
else
p1 += 5;
}
/* Highlighting */
else if (CStrUtil::casencmp(p1, ":hp", 3) == 0 && isdigit(p1[3]) &&
(p1[4] == '.' || isspace(p1[4]) || p1[4] == '\0')) {
int level = (p1[3] - '0') % 4;
const char *str = CDocScriptStartParagraphHighlight(level);
if (CDocInst->getOutputFormat() == CDOC_OUTPUT_RAW_CC ||
CDocInst->getOutputFormat() == CDOC_OUTPUT_CDOC ||
CDocInst->getOutputFormat() == CDOC_OUTPUT_TROFF ||
CDocInst->getOutputFormat() == CDOC_OUTPUT_HTML ||
CDocInst->getOutputFormat() == CDOC_OUTPUT_ILEAF) {
for (uint j = 0; j < strlen(str); j++)
line1[i++] = str[j];
}
/* Skip Command */
if (p1[4] == '.')
p1 += 5;
else
p1 += 4;
}
/* End Highlighting */
else if (CStrUtil::casencmp(p1, ":ehp", 4) == 0 && isdigit(p1[4]) &&
(p1[5] == '.' || isspace(p1[5]) || p1[5] == '\0')) {
int level = (p1[4] - '0') % 4;
const char *str = CDocScriptEndParagraphHighlight(level);
if (CDocInst->getOutputFormat() == CDOC_OUTPUT_RAW_CC ||
CDocInst->getOutputFormat() == CDOC_OUTPUT_CDOC ||
CDocInst->getOutputFormat() == CDOC_OUTPUT_TROFF ||
CDocInst->getOutputFormat() == CDOC_OUTPUT_HTML ||
CDocInst->getOutputFormat() == CDOC_OUTPUT_ILEAF) {
for (uint j = 0; j < strlen(str); j++)
line1[i++] = str[j];
}
/* Skip Command */
if (p1[5] == '.')
p1 += 6;
else
p1 += 5;
}
/* Cross References */
else if (CStrUtil::casencmp(p1, ":figref", 7) == 0 ||
CStrUtil::casencmp(p1, ":fnref" , 6) == 0 ||
CStrUtil::casencmp(p1, ":hdref" , 6) == 0 ||
CStrUtil::casencmp(p1, ":iref" , 5) == 0 ||
CStrUtil::casencmp(p1, ":liref" , 6) == 0 ||
CStrUtil::casencmp(p1, ":tref" , 5) == 0) {
int type = 0;
CDParameterData *parameter_data;
const char *p2 = p1;
if (CStrUtil::casencmp(p1, ":figref", 7) == 0) {
type = FIGURE_REF;
parameter_data = figref_parameter_data;
p1 += 7;
}
else if (CStrUtil::casencmp(p1, ":fnref" , 6) == 0) {
type = FOOTNOTE_REF;
parameter_data = fnref_parameter_data;
p1 += 6;
}
else if (CStrUtil::casencmp(p1, ":hdref" , 6) == 0) {
type = HEADER_REF;
parameter_data = hdref_parameter_data;
p1 += 6;
}
else if (CStrUtil::casencmp(p1, ":iref" , 5) == 0) {
type = INDEX_REF;
parameter_data = iref_parameter_data;
p1 += 5;
}
else if (CStrUtil::casencmp(p1, ":liref" , 6) == 0) {
type = LIST_ITEM_REF;
parameter_data = liref_parameter_data;
p1 += 6;
}
else if (CStrUtil::casencmp(p1, ":tref" , 5) == 0) {
type = TABLE_REF;
parameter_data = tref_parameter_data;
p1 += 5;
}
/* Skip Spaces after Command */
CStrUtil::skipSpace(&p1);
/* Extract Reference Values */
bool reference_done = false;
CDCrossRef cross_ref;
CDIndexRef index_ref;
if (type == INDEX_REF) {
index_ref.refid = NULL;
index_ref.pg = NULL;
index_ref.see = NULL;
index_ref.seeid = NULL;
}
else {
cross_ref.type = type;
cross_ref.refid = NULL;
cross_ref.page = true;
}
int j = 0;
while (! reference_done && *p1 != '\0' &&
parameter_data[j].name != NULL) {
int len = strlen(parameter_data[j].name);
if (CStrUtil::casencmp(p1, parameter_data[j].name, len) == 0 &&
p1[len] == '=') {
p1 += len + 1;
/* Get Reference Value (may be quoted) */
int k = 0;
char temp_string[256];
if (*p1 == '\'') {
p1++;
while (*p1 != '\0' && *p1 != '\'')
temp_string[k++] = *p1++;
if (*p1 == '\'')
p1++;
}
else {
while (*p1 != '\0' && *p1 != '.' && isalnum(*p1))
temp_string[k++] = *p1++;
}
temp_string[k] = '\0';
std::string temp_string1 = CDocScriptReplaceSymbolsInString(temp_string);
if (type == INDEX_REF)
CDocExtractParameterValue(temp_string1, ¶meter_data[j], (char *) &index_ref);
else
CDocExtractParameterValue(temp_string1, ¶meter_data[j], (char *) &cross_ref);
/* Skip Space after Reference Value */
CStrUtil::skipSpace(&p1);
/* Reference Terminated */
if (*p1 == '\0' || *p1 == '.') {
reference_done = true;
if (*p1 == '.')
p1++;
}
j = 0;
}
else
j++;
}
if (type == INDEX_REF && index_ref.refid != NULL) {
CDocScriptAddIndexRef(index_ref.refid, index_ref.pg, index_ref.see, index_ref.seeid);
delete [] index_ref.refid;
}
else if (cross_ref.refid != NULL) {
/* Make sure Reference Identifier is in Lower Case */
CStrUtil::toLower(cross_ref.refid);
/* Get Reference Text for Paragraph for this Identifier */
std::string reference = CDocScriptGetParagraphReferenceText(&cross_ref);
/* Add Reference Text to the Paragraph */
int len = reference.size();
for (int k = 0; k < len; k++)
line1[i++] = reference[k];
if (! reference_done)
line1[i++] = ' ';
/* Update the Reference Command List to be output
at the end of the File for CDoc Format */
CDocScriptUpdateReferenceCommands(&cross_ref);
delete [] cross_ref.refid;
}
else {
p1 = p2;
line1[i++] = *p1++;
}
}
else if (CStrUtil::casencmp(p1, ":hook", 5) == 0) {
CDHookParameterData hook_data;
const char *p2 = p1;
p1 += 5;
/* Skip Spaces after Command */
CStrUtil::skipSpace(&p1);
/* Extract Hook Values */
bool done = false;
int j = 0;
while (! done && *p1 != '\0' && hook_parameter_data[j].name != NULL) {
int len = strlen(hook_parameter_data[j].name);
if (CStrUtil::casencmp(p1, hook_parameter_data[j].name, len) == 0 &&
p1[len] == '=') {
p1 += len + 1;
/* Get Hook Value (may be quoted) */
int k = 0;
char temp_string[256];
if (*p1 == '\'') {
p1++;
while (*p1 != '\0' && *p1 != '\'')
temp_string[k++] = *p1++;
if (*p1 == '\'')
p1++;
}
else {
while (*p1 != '\0' && *p1 != '.' && isalnum(*p1))
temp_string[k++] = *p1++;
}
temp_string[k] = '\0';
std::string temp_string1 = CDocScriptReplaceSymbolsInString(temp_string);
CDocExtractParameterValue(temp_string1, &hook_parameter_data[j], (char *) &hook_data);
/* Skip Space after Hook Value */
CStrUtil::skipSpace(&p1);
/* Hook Terminated */
if (*p1 == '\0' || *p1 == '.') {
done = true;
if (*p1 == '.')
p1++;
}
j = 0;
}
else
j++;
}
if (hook_data.id != NULL) {
CDHookData hook_data1(hook_data.id, hook_data.data, hook_data.text);
/* Add Reference Text to the Paragraph */
std::string text = CDocScriptGetHookText(&hook_data1);
int len = text.size();
for (int k = 0; k < len; k++)
line1[i++] = text[k];
if (! done)
line1[i++] = ' ';
}
else {
p1 = p2;
line1[i++] = *p1++;
}
}
/* Start Quotation */
else if (CStrUtil::casencmp(p1, ":q", 2) == 0 &&
(p1[2] == '.' || isspace(p1[2]) || p1[2] == '\0')) {
/* Add Opening Quotation Mark */
line1[i++] = '"';
/* Skip Command */
if (p1[2] == '.')
p1 += 3;
else
p1 += 2;
}
/* End Citation */
else if (CStrUtil::casencmp(p1, ":eq", 3) == 0 &&
(p1[3] == '.' || isspace(p1[3]) || p1[3] == '\0')) {
/* Add Closing Quotation Mark */
line1[i++] = '"';
/* Skip Command */
if (p1[3] == '.')
p1 += 4;
else
p1 += 3;
}
/* New Line */
else if (CStrUtil::casencmp(p1, ":nl", 3) == 0 &&
(p1[3] == '.' || isspace(p1[3]) || p1[3] == '\0')) {
/* Remove Previous Spaces */
while (i > 0 && isspace(line1[i - 1]))
i--;
/* Add Newline Character */
line1[i++] = '\n';
/* Skip Command */
if (p1[3] == '.')
p1 += 4;
else
p1 += 3;
}
/* Break */
else if (CStrUtil::casencmp(p1, ":br", 3) == 0 &&
(p1[3] == '.' || isspace(p1[3]) || p1[3] == '\0')) {
/* Add Newline Character */
line1[i++] = '\n';
/* Skip Command */
if (p1[3] == '.')
p1 += 4;
else
p1 += 3;
}
else
line1[i++] = *p1++;
}
line1[i] = '\0';
/* Reset Script Line's Text */
script_line->setData(script_line->getType(), line1);
delete [] line1;
}
// Terminates Script Processing by Outputting Reference Commands and Closing Output File.
static void
CDocScriptTerm()
{
/* Write Last Page Footer */
if (cdoc_line_no != 0)
CDocScriptWritePageFooter();
/* If we are adding Page Numbers then Replace Forward
references with real values */
CDocScriptPageNoTerm();
/* Terminate the References (this will output any reference
commands used by CDoc to the end of the output) */
CDocScriptTermReferences();
if (CDocInst->getOutputFormat() == CDOC_OUTPUT_HTML) {
CDocScriptWriteCommand("</body>\n");
CDocScriptWriteCommand("</html>\n");
}
/* Close Output File if it was redirected to a Dataset */
if (cdoc_output_fp != stdout) {
fclose(cdoc_output_fp);
cdoc_output_fp = stdout;
}
/* Clean Up */
CDocScriptDeleteTableRowDefs();
CDocScriptDeleteTables();
CDocScriptDeleteFigures();
CDocScriptDeleteFootnotes();
CDocScriptDeleteMacros();
CDocScriptDeleteTOC();
CDocScriptDeleteIndex();
CDocScriptDeleteFonts();
CDocScriptDeleteSymbols();
CDocScriptTermParagraphs();
cdoc_current_section = "";
cdoc_document.security = "";
cdoc_document.language = "";
}
// Initialise Headers ready for the input IBM Script file to be processed.
static void
CDocScriptInitHeaders()
{
for (int i = 0; i < CDOC_MAX_HEADERS; i++)
header_number[i] = cdoc_header_number[i];
}
// Start a Header at the specified level.
//
// Ensures lower and higher level numbers are kept up to date.
extern void
CDocScriptStartHeader(int level)
{
int i;
/* If previous levels have not appeared then set them to 1 */
for (i = 0; i < level; i++)
if (header_number[i] == 0)
header_number[i] = 1;
/* Increment Count for current Header Level */
header_number[level]++;
/* Set higher levels to unset (0) */
for (i = level + 1; i < CDOC_MAX_HEADERS; i++)
header_number[i] = 0;
}
// Get the Current Header Number for the specified Level.
extern int
CDocScriptGetHeader(int level)
{
if (level >= 0 && level < CDOC_MAX_HEADERS)
return(header_number[level]);
else
return(-1);
}
// Turn formatting (i.e. text collection and justification) on.
extern void
CDocScriptFormattingOn()
{
/* Set formatting flag */
cdoc_formatting = true;
/* Inform Troff that formatting is Active */
if (CDocInst->getOutputFormat() == CDOC_OUTPUT_TROFF)
CDocScriptWriteCommand(".fi\n");
else if (CDocInst->getOutputFormat() == CDOC_OUTPUT_CDOC)
CDocScriptWriteCommand(CDOC_FORMAT_TMPL, "on");
else if (CDocInst->getOutputFormat() == CDOC_OUTPUT_HTML)
CDocScriptWriteCommand("</pre>\n");
else if (CDocInst->getOutputFormat() == CDOC_OUTPUT_ILEAF)
CDocScriptWriteCommand("\n");
}
// Turn formatting (i.e. text collection and justification) off.
// Text will now appear as entered.
extern void
CDocScriptFormattingOff()
{
/* Reset formatting flag */
cdoc_formatting = false;
/* Inform Troff that formatting is not Active */
if (CDocInst->getOutputFormat() == CDOC_OUTPUT_TROFF)
CDocScriptWriteCommand(".nf\n");
else if (CDocInst->getOutputFormat() == CDOC_OUTPUT_CDOC)
CDocScriptWriteCommand(CDOC_FORMAT_TMPL, "off");
else if (CDocInst->getOutputFormat() == CDOC_OUTPUT_HTML)
CDocScriptWriteCommand("<pre>\n");
else if (CDocInst->getOutputFormat() == CDOC_OUTPUT_ILEAF)
CDocScriptWriteCommand("\n");
}
// Convert an IBM Script highlight level to a CDoc font type.
static int
CDocScriptHighlightToFont(int highlight)
{
int font;
if (highlight == 0) font = CDOC_NORMAL_FONT;
else if (highlight == 1) font = CDOC_UNDERLINE_FONT;
else if (highlight == 2) font = CDOC_BOLD_FONT;
else if (highlight == 3) font = CDOC_BOLD_UNDERLINE_FONT;
else font = CDOC_NORMAL_FONT;
return font;
}
// Surround supplied str with the Escape Codes required to display it in the
// specified IBM Script highlight.
static std::string
CDocScriptAddHighlightEscapes(const std::string &str, int highlight)
{
std::string highlight_string;
if (highlight == 0)
highlight_string = str;
else if (highlight == 1)
highlight_string = CDocStartUnderline() + str + CDocEndUnderline();
else if (highlight == 2)
highlight_string = CDocStartBold() + str + CDocEndBold();
else if (highlight == 3)
highlight_string = CDocStartBoldUnderline() + str + CDocEndBoldUnderline();
else
highlight_string = str;
return highlight_string;
}
| 29.154295 | 100 | 0.568913 | [
"vector"
] |
147a399fcf793286714eac010cf28e5856193b54 | 4,006 | hpp | C++ | vm/gc/root.hpp | larrytheliquid/rubinius | 5af42280ab95626f33517ca5f6330e17be04ec64 | [
"BSD-3-Clause"
] | null | null | null | vm/gc/root.hpp | larrytheliquid/rubinius | 5af42280ab95626f33517ca5f6330e17be04ec64 | [
"BSD-3-Clause"
] | 1 | 2022-03-12T14:09:00.000Z | 2022-03-12T14:09:00.000Z | vm/gc/root.hpp | isabella232/rubinius | 5af42280ab95626f33517ca5f6330e17be04ec64 | [
"BSD-3-Clause"
] | 1 | 2022-03-12T12:08:44.000Z | 2022-03-12T12:08:44.000Z | #ifndef RBX_GC_ROOT_HPP
#define RBX_GC_ROOT_HPP
#include <stdexcept>
#include "linkedlist.hpp"
#include "oop.hpp"
#include "prelude.hpp"
#include "util/thread.hpp"
namespace rubinius {
class Root;
/**
* Roots is a structure comprising of Root objects.
*
* @todo Add more information about class. --rue
* @todo Document methods. --rue
*/
class Roots : public LinkedList {
thread::SpinLock lock_;
public: /* Ctors */
Roots()
: LinkedList()
{}
public: /* Interface */
Root* front();
typedef LinkedList::Iterator<Roots, Root> Iterator;
void add(Root*);
void remove(Root*);
};
/**
* A Root envelops an Object.
*
* Each Root is also associated with a certain Roots structure
* and could be used to access its other members. The Root can
* be associated with (or "migrated to") a different Roots.
*
* @todo Document remaining methods. --rue
*/
class Root : public LinkedList::Node {
/** The Roots structure this Root belongs to. */
Roots* roots_;
protected:
/** Enveloped Object. */
Object* object_;
public: /** Constructors */
Root()
: LinkedList::Node()
, roots_(NULL)
, object_(NULL)
{}
Root(Roots* roots)
: LinkedList::Node()
, roots_(roots)
, object_(NULL)
{}
Root(Roots* roots, Object* obj)
: LinkedList::Node()
, roots_(roots)
, object_(obj)
{
roots_->add(this);
}
Root(STATE);
Root(STATE, Object* obj);
/** Copy construction uses set() semantics. */
Root(const Root& other)
: LinkedList::Node()
, roots_(NULL)
, object_(NULL)
{
set(other.object_, other.roots_);
}
~Root() {
if(roots_ && object_) roots_->remove(this);
}
public: /** Methods */
/** Assignment uses set() semantics. */
Root& operator=(Root& other) {
set(other.object_, other.roots_);
return *this;
}
/** Obtain the enveloped Object or Qnil if none. */
Object* get() {
assert(object_ && "Using an unassigned root!");
return object_;
}
/** Envelope the given Object. Must have roots already. */
void set(Object* obj) {
assert(roots_ && "invalid Root usage. Cannot set object before roots");
set(obj, roots_);
}
/** Envelope the given Object, migrating to given Roots if it is new. */
void set(Object* obj, Roots* r);
// Used in the JIT to allow for loading of Roots directly.
Object** object_address() {
return &object_;
}
};
/**
* TypedRoot is a Root that knows the type of its Object.
*
* @todo Use base type of object rather than pointer type
* as ObjType and change usage accordingly? This
* allows, among other things, using `as()` rather
* than a direct C++ cast. --rue
*/
template <typename ObjType>
class TypedRoot : public Root {
public:
TypedRoot()
: Root()
{}
/** As Root::Root(roots), but retains object's type. */
TypedRoot(Roots* roots)
: Root(roots)
{}
/** As Root::Root(STATE), but retains object's type. */
TypedRoot(STATE)
: Root(state)
{}
/** As Root::Root(STATE, Object*), but retains object's type. */
TypedRoot(STATE, ObjType obj)
: Root(state, (Object*)obj)
{}
/** Transparently delegate dereferencing to enveloped object. */
/** @todo Use as<ObjType>() when using base type instead of pointer. --rue */
ObjType operator->() {
assert(object_ && "Using an unassigned root!");
return reinterpret_cast<ObjType>(object_);
}
/** Return the enveloped object as the real ObjType. */
/** @todo Use as<ObjType>() when using base type instead of pointer. --rue */
ObjType get() {
assert(object_ && "Using an unassigned root!");
return reinterpret_cast<ObjType>(object_);
}
};
}
#endif
| 23.564706 | 83 | 0.585871 | [
"object"
] |
147b49ef8ed51b0b3126d6a481d9136d090fa884 | 43,893 | cpp | C++ | Engine/Source/FishEditor/FBXImporter.cpp | ValtoGameEngines/Fish-Engine | a4b9fb9b0a6dc202f7990e75f4b7d8d5163209d9 | [
"MIT"
] | 240 | 2017-02-17T10:08:19.000Z | 2022-03-25T14:45:29.000Z | Engine/Source/FishEditor/FBXImporter.cpp | ValtoGameEngines/Fish-Engine | a4b9fb9b0a6dc202f7990e75f4b7d8d5163209d9 | [
"MIT"
] | 2 | 2016-10-12T07:08:38.000Z | 2017-04-05T01:56:30.000Z | Engine/Source/FishEditor/FBXImporter.cpp | yushroom/FishEngine | a4b9fb9b0a6dc202f7990e75f4b7d8d5163209d9 | [
"MIT"
] | 39 | 2017-03-02T09:40:07.000Z | 2021-12-04T07:28:53.000Z | #include "FBXImporter.hpp"
#include <unordered_set>
#include <fbxsdk.h>
#include <fbxsdk/utils/fbxgeometryconverter.h>
#include <boost/algorithm/string/case_conv.hpp>
#include <FishEngine/Debug.hpp>
#include <FishEngine/GameObject.hpp>
#include <FishEngine/MeshFilter.hpp>
#include <FishEngine/MeshRenderer.hpp>
#include <FishEngine/SkinnedMeshRenderer.hpp>
#include <FishEngine/Texture.hpp>
#include <FishEngine/Texture2D.hpp>
#include <FishEngine/Application.hpp>
#include "AssetDataBase.hpp"
#include "FBXImporter/RawMesh.hpp"
//#include <Animation/AnimationUtility.hpp>
//#include <Animation/AnimationClip.hpp>
////#include <Animation/AnimationClipInfo.hpp>
//#include <Animation/AnimationSplitInfo.hpp>
#include <FishEngine/Animation.hpp>
#include <FishEngine/AnimationClip.hpp>
#include <FishEngine/Animation/AnimationCurve.hpp>
#include <FishEngine/Animation/AnimationCurveUtility.hpp>
using namespace FishEngine;
using namespace FishEditor;
Matrix4x4 FBXToNativeType(fbxsdk::FbxAMatrix const & fmatrix)
{
float f44[4][4];
auto d44 = fmatrix.Double44();
for (int i = 0; i < 4; ++i)
{
for (int j = 0; j < 4; ++j)
{
f44[i][j] = static_cast<float>(d44[j][i]);
}
}
return Matrix4x4(f44);
}
Vector3 FBXToNativeType(const FbxVector4& value)
{
Vector3 native;
native.x = (float)value[0];
native.y = (float)value[1];
native.z = (float)value[2];
return native;
}
Vector3 FBXToNativeType(const FbxDouble3& value)
{
return Vector3(static_cast<float>(value[0]),
static_cast<float>(value[1]),
static_cast<float>(value[2]));
}
Vector2 FBXToNativeType(const FbxVector2& value)
{
Vector2 native;
native.x = (float)value[0];
native.y = (float)value[1];
return native;
}
Color FBXToNativeType(const FbxColor& value)
{
Color native;
native.r = (float)value[0];
native.g = (float)value[1];
native.b = (float)value[2];
native.a = (float)value[3];
return native;
}
FbxSurfaceMaterial* FBXToNativeType(FbxSurfaceMaterial* const& value)
{
return value;
}
RotationOrder FBXToNativeType(EFbxRotationOrder order)
{
RotationOrder rotationOrder;
//EFbxRotationOrder order;
//node->GetRotationOrder(FbxNode::eDestinationPivot, order);
switch (order)
{
case eEulerXYZ:
rotationOrder = RotationOrder::XYZ; break;
case eEulerXZY:
rotationOrder = RotationOrder::XZY; break;
case eEulerYXZ:
rotationOrder = RotationOrder::YXZ; break;
case eEulerYZX:
rotationOrder = RotationOrder::YZX; break;
case eEulerZXY:
rotationOrder = RotationOrder::ZXY; break;
case eEulerZYX:
rotationOrder = RotationOrder::ZYX; break;
default: // do not support eSphericXYZ
abort();
}
return rotationOrder;
}
int FBXToNativeType(const int & value)
{
return value;
}
inline Vector3 FbxVector4ToVector3WithXFlipped(FbxVector4 const & v)
{
return Vector3(static_cast<float>(v[0]),
static_cast<float>(v[1]),
static_cast<float>(v[2]) );
}
// skinned data
void FishEditor::FBXImporter::GetLinkData(FbxMesh* pMesh, MeshPtr mesh, std::map<uint32_t, uint32_t> const & vertexIndexRemapping)
{
int lSkinCount = pMesh->GetDeformerCount(FbxDeformer::eSkin);
if (lSkinCount <= 0)
{
mesh->m_skinned = false;
return;
}
if (lSkinCount != 1)
{
// TODO: multiple skin
abort();
}
mesh->m_skinned = true;
int n_vertices = mesh->vertexCount();
mesh->m_boneWeights.resize(n_vertices);
//FbxCluster::ELinkMode lClusterMode = ((FbxSkin*)pMesh->GetDeformer(0, FbxDeformer::eSkin))->GetCluster(0)->GetLinkMode();
FbxSkin * lSkinDeformer = (FbxSkin *)pMesh->GetDeformer(0, FbxDeformer::eSkin);
//FbxSkin::EType lSkinningType = lSkinDeformer->GetSkinningType();
// cluser == bone
int lClusterCount = lSkinDeformer->GetClusterCount();
std::vector<uint32_t> boneIndices(lClusterCount);
mesh->m_boneNames.resize(lClusterCount);
float scale = m_fileScale * m_globalScale;
for (int lClusterIndex = 0; lClusterIndex != lClusterCount; ++lClusterIndex)
{
FbxCluster* lCluster= lSkinDeformer->GetCluster(lClusterIndex);
int lIndexCount = lCluster->GetControlPointIndicesCount();
int* lIndices = lCluster->GetControlPointIndices();
double* lWeights = lCluster->GetControlPointWeights();
auto & boneToIndex = m_model.m_avatar->m_boneToIndex;
std::string boneName = (char *) lCluster->GetLink()->GetName();
mesh->m_boneNames[lClusterIndex] = boneName;
//fbxsdk::FbxAMatrix bindPoseMatrix;
//lCluster->GetTransformLinkMatrix(bindPoseMatrix); // this bind pose is in world(global) space
////m_model.m_bindposes.push_back(FbxAMatrixToMatrix4x4(bindPoseMatrix));
int boneId;
auto it = boneToIndex.find(boneName);
if ( it != boneToIndex.end() )
{
boneId = it->second;
}
else
{
// bone not in skeletion;
abort();
//boneId = m_boneCount;
//m_model.m_avatar->m_boneToIndex[boneName] = boneId;
//m_model.m_avatar->m_indexToBone[boneId] = boneName;
////fbxsdk::FbxAMatrix transformMatrix;
////lCluster->GetTransformMatrix(transformMatrix);
//m_boneCount++;
}
fbxsdk::FbxAMatrix bindPoseMatrix;
lCluster->GetTransformLinkMatrix(bindPoseMatrix); // this bind pose is in world(global) space
auto mat = FBXToNativeType(bindPoseMatrix);
mat.m[0][3] *= scale;
mat.m[1][3] *= scale;
mat.m[2][3] *= scale;
m_model.m_bindposes[boneId] = mat;
boneIndices[lClusterIndex] = boneId;
for ( int k = 0; k < lIndexCount; k++ )
{
int vertexId = lIndices[k];
float weight = static_cast<float>(lWeights[k]);
mesh->m_boneWeights[vertexId].AddBoneData(lClusterIndex, weight);
auto it = vertexIndexRemapping.find(vertexId);
while (it != vertexIndexRemapping.end())
{
vertexId = it->second;
mesh->m_boneWeights[vertexId].AddBoneData(lClusterIndex, weight);
it = vertexIndexRemapping.find(vertexId);
}
}
}
m_model.m_boneIndicesForEachMesh.emplace(mesh, std::move(boneIndices));
}
void FishEditor::FBXImporter::ImportSkeleton(fbxsdk::FbxScene* scene)
{
std::deque<FbxNode*> todo;
todo.push_back(scene->GetRootNode());
while (!todo.empty())
{
FbxNode* node = todo.front();
todo.pop_front();
for (int i = 0; i < node->GetChildCount(); ++i)
{
auto child = node->GetChild(i);
todo.push_back(child);
}
const char* nodeName = node->GetName();
auto nodeAttributeCount = node->GetNodeAttributeCount();
for (int i = 0; i < nodeAttributeCount; ++i)
{
auto nodeAttribute = node->GetNodeAttributeByIndex(i);
auto type = nodeAttribute->GetAttributeType();
if (type == FbxNodeAttribute::eSkeleton)
{
//FbxSkeleton* lSkeleton = (FbxSkeleton*)nodeAttribute;
std::string boneName = nodeName;
auto it = m_model.m_avatar->m_boneToIndex.find(boneName);
if (it != m_model.m_avatar->m_boneToIndex.end())
{
// handle same name
abort();
}
m_model.m_avatar->m_boneToIndex[boneName] = m_boneCount;
m_model.m_avatar->m_indexToBone[m_boneCount] = boneName;
m_boneCount++;
}
}
}
m_model.m_bindposes.resize(m_boneCount);
}
void FishEditor::FBXImporter::UpdateBones(FishEngine::TransformPtr const & node)
{
auto boneName = node->gameObject()->name();
auto & boneToIndex = m_model.m_avatar->m_boneToIndex;
auto it = boneToIndex.find(boneName);
if (it != boneToIndex.end())
{
int id = it->second;
m_model.m_bones[id] = node;
// world(global) space -> parent's local space
if (node->parent() == nullptr)
{
node->setLocalToWorldMatrix(m_model.m_bindposes[id]);
}
else
{
auto l2w = node->parent()->worldToLocalMatrix() * m_model.m_bindposes[id];
//bindPoses[id] = l2w.inverse();
node->setLocalToWorldMatrix(l2w);
m_model.m_bindposes[id] = node->worldToLocalMatrix();
}
}
for (auto & child : node->children())
{
UpdateBones(child);
}
}
MeshPtr FishEditor::FBXImporter::ParseMesh(FbxMesh* fbxMesh)
{
assert(fbxMesh->IsTriangleMesh());
auto it = m_model.m_fbxMeshLookup.find(fbxMesh);
if (it != m_model.m_fbxMeshLookup.end())
{
auto meshIndex = it->second;
return m_model.m_meshes[meshIndex];
}
fbxMesh->RemoveBadPolygons();
fbxMesh->GenerateNormals(false, true, false);
fbxMesh->GenerateTangentsDataForAllUVSets();
//auto name1 = fbxMesh->GetName();
//auto name2 = fbxMesh->GetNode()->GetName();
// http://help.autodesk.com/view/FBX/2017/ENU/?guid=__cpp_ref_class_fbx_mesh_html
// A control point is an XYZ coordinate, it is synonym of vertex.
// A polygon vertex is an index to a control point(the same control point can be referenced by multiple polygon vertices).
// A polygon is a group of polygon vertices.The minimum valid number of polygon vertices to define a polygon is 3.
int polygonCount = fbxMesh->GetPolygonCount();
int vertexCount = fbxMesh->GetControlPointsCount();
FbxVector4* controlPoints = fbxMesh->GetControlPoints();
// auto attributeCount = fbxMesh->GetNode()->GetNodeAttributeCount();
// std::vector<FbxMesh*> submeshes;
// for (int attributeIndex = 1; attributeIndex < attributeCount; ++attributeIndex)
// {
// auto nodeAttribute = fbxMesh->GetNode()->GetNodeAttributeByIndex(attributeIndex);
// if (nodeAttribute->GetAttributeType() == FbxNodeAttribute::eMesh)
// {
// FbxMesh* lMesh = (FbxMesh*)nodeAttribute;
// submeshes.push_back(lMesh);
// int submeshPolygonCount = lMesh->GetPolygonCount();
// int submeshVertexCount = lMesh->GetControlPointsCount();
// }
// }
if (fbxMesh->GetElementUVCount() == 0)
{
abort();
}
// get material info
int lMaterialCount = fbxMesh->GetNode()->GetMaterialCount();
if (lMaterialCount == 0)
{
// no material from fbx, set default material
abort();
}
// use RawMesh to construct Mesh
RawMesh rawMesh;
rawMesh.SetFaceCount(polygonCount);
rawMesh.SetVertexCount(vertexCount);
int subMeshCount = lMaterialCount;
int hasSubMesh = subMeshCount > 1;
// TODO:
// if this mesh only has one material, we assume this material applies to all polygons.
// Better choice is to apply default material to polygons without materials.
// use material info to split submeshes
//std::vector<std::vector<int>> submeshPolygonIds;
if (hasSubMesh)
{
rawMesh.m_subMeshCount = subMeshCount;
rawMesh.m_submeshMap.resize(polygonCount);
//rawMesh.m_submeshPolygonIds.resize(subMeshCount);
//Debug::LogError("eByPolygon mapping material");
//auto lMaterialElement = fbxMesh->GetElementMaterial(l);
for (int l = 0; l < fbxMesh->GetElementMaterialCount(); l++)
{
auto lMaterialElement = fbxMesh->GetElementMaterial(l);
if (lMaterialElement->GetMappingMode() == FbxLayerElement::eByPolygon)
{
//int lMatId = lMaterialElement->GetIndexArray().GetAt(0);
//if (lMatId >= 0)
//{
// auto lMaterial = fbxMesh->GetNode()->GetMaterial(lMatId);
// ParseMaterial(lMaterial);
//}
//else
//{
// abort();
//}
if (lMaterialElement->GetReferenceMode() == FbxLayerElement::eIndex ||
lMaterialElement->GetReferenceMode() == FbxLayerElement::eIndexToDirect)
{
int lIndexArrayCount = lMaterialElement->GetIndexArray().GetCount();
if (lIndexArrayCount != polygonCount)
{
abort();
}
for (int i = 0; i < polygonCount; i++)
{
int lMatId = lMaterialElement->GetIndexArray().GetAt(i);
rawMesh.m_submeshMap[i] = lMatId;
//rawMesh.m_submeshPolygonIds[lMatId].push_back(i);
}
}
else
{
abort();
}
}
else
{
abort();
}
}
}
// positions
for (int controlPointIndex = 0; controlPointIndex < vertexCount; ++controlPointIndex)
{
auto & p = controlPoints[controlPointIndex];
float scale = m_fileScale * m_globalScale;
// float x = -p[0] * scale;
// float y = p[1] * scale;
// float z = p[2] * scale;
auto pp = FbxVector4ToVector3WithXFlipped(p);
rawMesh.m_vertexPositions.emplace_back(pp * scale);
}
// indices(triangles)
for (int polygonIndex = 0; polygonIndex < polygonCount; ++polygonIndex)
{
rawMesh.m_wedgeIndices.push_back( fbxMesh->GetPolygonVertex(polygonIndex, 0) );
rawMesh.m_wedgeIndices.push_back( fbxMesh->GetPolygonVertex(polygonIndex, 1) );
rawMesh.m_wedgeIndices.push_back( fbxMesh->GetPolygonVertex(polygonIndex, 2) );
}
int vertexId = 0;
for (int i = 0; i < polygonCount; i++) // for each triangle
{
int lPolygonSize = fbxMesh->GetPolygonSize(i); // should be 3
assert(lPolygonSize == 3);
for (int j = 0; j < lPolygonSize; j++)
{
int lControlPointIndex = fbxMesh->GetPolygonVertex(i, j);
// UV
// for (int l = 0; l < fbxMesh->GetElementUVCount(); ++l)
// {
FbxGeometryElementUV* leUV = fbxMesh->GetElementUV(0);
int lTextureUVIndex = fbxMesh->GetTextureUVIndex(i, j);
if (leUV->GetMappingMode() == FbxGeometryElement::eByPolygonVertex)
{
auto mode = leUV->GetReferenceMode();
if (mode == FbxGeometryElement::eDirect || mode == FbxGeometryElement::eIndexToDirect)
{
auto uv = leUV->GetDirectArray().GetAt(lTextureUVIndex);
rawMesh.m_wedgeTexCoords.emplace_back((float)uv[0], (float)uv[1]);
}
else
{
abort();
}
}
else
{
abort();
}
// }
// Normal
//for (int l = 0; l < fbxMesh->GetElementNormalCount(); ++l)
//{
FbxGeometryElementNormal* leNormal = fbxMesh->GetElementNormal(0);
//FBXSDK_sprintf(header, 100, " Normal: ");
if (leNormal->GetMappingMode() == FbxGeometryElement::eByPolygonVertex)
{
auto mode = leNormal->GetReferenceMode();
if (mode == FbxGeometryElement::eDirect)
{
//Display3DVector(header, leNormal->GetDirectArray().GetAt(vertexId));
auto n = leNormal->GetDirectArray().GetAt(vertexId);
rawMesh.m_wedgeNormals.emplace_back(FbxVector4ToVector3WithXFlipped(n));
}
else if (mode == FbxGeometryElement::eIndexToDirect)
{
int id = leNormal->GetIndexArray().GetAt(vertexId);
//Display3DVector(header, leNormal->GetDirectArray().GetAt(id));
auto n = leNormal->GetDirectArray().GetAt(id);
rawMesh.m_wedgeNormals.emplace_back(FbxVector4ToVector3WithXFlipped(n));
}
else
{
abort();
}
}
else if (leNormal->GetMappingMode() == FbxGeometryElement::eByControlPoint)
{
auto mode = leNormal->GetReferenceMode();
if (mode == FbxGeometryElement::eDirect)
{
auto n = leNormal->GetDirectArray().GetAt(lControlPointIndex);
rawMesh.m_wedgeNormals.emplace_back(FbxVector4ToVector3WithXFlipped(n));
}
else if (mode == FbxGeometryElement::eIndexToDirect)
{
int id = leNormal->GetIndexArray().GetAt(lControlPointIndex);
auto n = leNormal->GetDirectArray().GetAt(id);
rawMesh.m_wedgeNormals.emplace_back(FbxVector4ToVector3WithXFlipped(n));
}
else
{
abort();
}
}
else
{
abort();
}
//}
// Tangent
//for (int l = 0; l < fbxMesh->GetElementTangentCount(); ++l)
//{
FbxGeometryElementTangent* leTangent = fbxMesh->GetElementTangent(0);
//FBXSDK_sprintf(header, 100, " Tangent: ");
if (leTangent->GetMappingMode() == FbxGeometryElement::eByPolygonVertex)
{
auto mode = leTangent->GetReferenceMode();
if (mode == FbxGeometryElement::eDirect)
{
//Display3DVector(header, leTangent->GetDirectArray().GetAt(vertexId));
auto t = leTangent->GetDirectArray().GetAt(vertexId);
rawMesh.m_wedgeTangents.emplace_back(FbxVector4ToVector3WithXFlipped(t));
}
else if (mode == FbxGeometryElement::eIndexToDirect)
{
int id = leTangent->GetIndexArray().GetAt(vertexId);
//Display3DVector(header, leTangent->GetDirectArray().GetAt(id));
auto t = leTangent->GetDirectArray().GetAt(id);
rawMesh.m_wedgeTangents.emplace_back(FbxVector4ToVector3WithXFlipped(t));
}
else
{
abort();
}
}
else if (leTangent->GetMappingMode() == FbxGeometryElement::eByControlPoint)
{
auto mode = leTangent->GetReferenceMode();
if (mode == FbxGeometryElement::eDirect)
{
auto t = leTangent->GetDirectArray().GetAt(lControlPointIndex);
rawMesh.m_wedgeTangents.emplace_back(FbxVector4ToVector3WithXFlipped(t));
}
else if (mode == FbxGeometryElement::eIndexToDirect)
{
int id = leTangent->GetIndexArray().GetAt(lControlPointIndex);
auto t = leTangent->GetDirectArray().GetAt(id);
rawMesh.m_wedgeTangents.emplace_back(FbxVector4ToVector3WithXFlipped(t));
}
else
{
abort();
}
}
else
{
abort();
}
//}
#if 0
// Binormal
for (int l = 0; l < fbxMesh->GetElementBinormalCount(); ++l)
{
FbxGeometryElementBinormal* leBinormal = fbxMesh->GetElementBinormal(l);
//FBXSDK_sprintf(header, 100, " Binormal: ");
if (leBinormal->GetMappingMode() == FbxGeometryElement::eByPolygonVertex)
{
switch (leBinormal->GetReferenceMode())
{
case FbxGeometryElement::eDirect:
//Display3DVector(header, leBinormal->GetDirectArray().GetAt(vertexId));
break;
case FbxGeometryElement::eIndexToDirect:
{
int id = leBinormal->GetIndexArray().GetAt(vertexId);
//Display3DVector(header, leBinormal->GetDirectArray().GetAt(id));
}
break;
default:
break; // other reference modes not shown here!
}
}
}
#endif
vertexId++;
} // for polygonSize
} // for polygonCount
auto mesh = rawMesh.ToMesh();
GetLinkData(fbxMesh, mesh, rawMesh.m_vertexIndexRemapping);
m_model.m_fbxMeshLookup[fbxMesh] = m_model.m_meshes.size();
m_model.m_meshes.push_back(mesh);
return mesh;
}
FishEngine::MaterialPtr FishEditor::FBXImporter::ParseMaterial(fbxsdk::FbxSurfaceMaterial * pMaterial)
{
auto it = m_model.m_fbxMaterialLookup.find(pMaterial);
if (it != m_model.m_fbxMaterialLookup.end())
{
// already parsed
return m_model.m_materials[it->second];
}
FbxProperty lProperty;
//Diffuse Textures
lProperty = pMaterial->FindProperty(FbxSurfaceMaterial::sDiffuse);
//DisplayTextureNames(lProperty, lConnectionString);
std::string diffuseTexturePath;
int lNbTextures = lProperty.GetSrcObjectCount<FbxTexture>();
for (int j = 0; j < lNbTextures; ++j)
{
FbxTexture* lTexture = lProperty.GetSrcObject<FbxTexture>(j);
if (lTexture)
{
std::string textureName = lTexture->GetName();
auto * lFileTexture = FbxCast<FbxFileTexture>(lTexture);
if (lFileTexture == nullptr)
{
// do not support non-file texture
//abort();
continue;
}
diffuseTexturePath = lFileTexture->GetFileName();
//Debug::LogWarning("diffuse texture: %s", texturePath.c_str());
break;
}
}
MaterialPtr ret_material = Material::defaultMaterial();
if (!diffuseTexturePath.empty())
{
auto textureName = Path(diffuseTexturePath).filename();
// auto texturePath = Application::dataPath() / "textures" / textureName;
// auto diffuseTexture = AssetDatabase::LoadAssetAtPath2<Texture>(texturePath);
auto diffuseTexture = AssetDatabase::FindAssetByFilename<Texture>(textureName.string());
ret_material = Material::InstantiateBuiltinMaterial("Diffuse");
ret_material->setName(textureName.string());
if (diffuseTexture != nullptr)
{
ret_material->setMainTexture(diffuseTexture);
}
else
{
LogWarning("Texture not found: " + textureName.string());
ret_material->setMainTexture(Texture2D::whiteTexture());
}
}
m_model.m_fbxMaterialLookup[pMaterial] = m_model.m_materials.size();
m_model.m_materials.push_back(ret_material);
return ret_material;
}
void FishEditor::FBXImporter::BakeTransforms(FbxScene * scene)
{
// FBX stores transforms in a more complex way than just translation-rotation-scale as used by Banshee.
// Instead they also support rotations offsets and pivots, scaling pivots and more. We wish to bake all this data
// into a standard transform so we can access it using node's local TRS properties (e.g. FbxNode::LclTranslation).
// fbx sdk doc:
// http://help.autodesk.com/view/FBX/2017/ENU/?guid=__files_GUID_C35D98CB_5148_4B46_82D1_51077D8970EE_htm
double frameRate = FbxTime::GetFrameRate(scene->GetGlobalSettings().GetTimeMode());
std::deque<FbxNode*> todo;
todo.push_back(scene->GetRootNode());
while (todo.size() > 0)
{
FbxNode* node = todo.front();
todo.pop_front();
FbxVector4 zero(0, 0, 0);
FbxVector4 one(1, 1, 1);
// Activate pivot converting
node->SetPivotState(FbxNode::eSourcePivot, FbxNode::ePivotActive);
node->SetPivotState(FbxNode::eDestinationPivot, FbxNode::ePivotActive);
// We want to set all these to 0 (1 for scale) and bake them into the transforms
node->SetPostRotation(FbxNode::eDestinationPivot, zero);
node->SetPreRotation(FbxNode::eDestinationPivot, zero);
node->SetRotationOffset(FbxNode::eDestinationPivot, zero);
node->SetScalingOffset(FbxNode::eDestinationPivot, zero);
node->SetRotationPivot(FbxNode::eDestinationPivot, zero);
node->SetScalingPivot(FbxNode::eDestinationPivot, zero);
node->SetGeometricTranslation(FbxNode::eDestinationPivot, zero);
node->SetGeometricRotation(FbxNode::eDestinationPivot, zero);
node->SetGeometricScaling(FbxNode::eDestinationPivot, one);
// FishEngine assumes euler angles are in ZXY order
// do not use this line, since it will mess up animation curves
//node->SetRotationOrder(FbxNode::eDestinationPivot, eEulerZXY);
EFbxRotationOrder lRotationOrder;
node->GetRotationOrder(FbxNode::eSourcePivot , lRotationOrder);
node->SetRotationOrder(FbxNode::eDestinationPivot , lRotationOrder);
// Keep interpolation as is
node->SetQuaternionInterpolation(FbxNode::eDestinationPivot, node->GetQuaternionInterpolation(FbxNode::eSourcePivot));
for (int i = 0; i < node->GetChildCount(); i++)
{
FbxNode* childNode = node->GetChild(i);
todo.push_back(childNode);
}
}
scene->GetRootNode()->ConvertPivotAnimationRecursive(nullptr, FbxNode::eDestinationPivot, frameRate);
//scene->GetRootNode()->ResetPivotSetAndConvertAnimation();
}
/**
* Print a node, its attributes, and all its children recursively.
*/
GameObjectPtr FishEditor::FBXImporter::ParseNodeRecursively(FbxNode* pNode)
{
const char* nodeName = pNode->GetName();
auto go = GameObject::Create();
go->setName(nodeName);
go->setPrefabInternal(m_model.m_modelPrefab);
go->transform()->setPrefabInternal(m_model.m_modelPrefab);
FbxDouble3 t = pNode->LclTranslation.Get();
FbxDouble3 r = pNode->LclRotation.Get();
FbxDouble3 s = pNode->LclScaling.Get();
float scale = m_fileScale * m_globalScale;
go->transform()->setLocalPosition(t[0] * scale, t[1] * scale, t[2] * scale);
go->transform()->setLocalScale(s[0], s[1], s[2]);
EFbxRotationOrder rotationOrder;
pNode->GetRotationOrder(FbxNode::eSourcePivot, rotationOrder);
RotationOrder order = FBXToNativeType(rotationOrder);
Quaternion rot = Quaternion::Euler(order, r[0], r[1], r[2]);
go->transform()->setLocalRotation(rot);
m_model.m_fbxNodeLookup[pNode] = go->transform();
FishEditor::AssetDatabase::s_allAssetObjects.insert(go);
auto nodeAttributeCount = pNode->GetNodeAttributeCount();
for (int i = 0; i < nodeAttributeCount; ++i)
{
auto nodeAttribute = pNode->GetNodeAttributeByIndex(i);
auto type = nodeAttribute->GetAttributeType();
if (type == FbxNodeAttribute::eMesh)
{
FbxMesh* lMesh = (FbxMesh*)nodeAttribute;
auto mesh = ParseMesh(lMesh);
m_model.m_meshes.push_back(mesh);
if (mesh->name().empty())
{
mesh->setName(nodeName);
}
if (IsNewlyCreated())
{
m_recycleNameToFileID[mesh->name()] = m_nextMeshFileID;
m_fileIDToRecycleName[m_nextMeshFileID] = mesh->name();
m_nextMeshFileID += 2;
}
int lMaterialCount = pNode->GetMaterialCount();
MaterialPtr material;
if (lMaterialCount == 0)
{
material = Material::defaultMaterial();
}
else
{
auto lMaterial = pNode->GetMaterial(0);
material = ParseMaterial(lMaterial);
}
RendererPtr renderer;
if (mesh->m_skinned)
{
auto srenderer = go->AddComponent<SkinnedMeshRenderer>();
m_model.m_skinnedMeshRenderers.push_back(srenderer);
srenderer->SetMaterial(material);
srenderer->setSharedMesh(mesh);
srenderer->setAvatar(m_model.m_avatar);
srenderer->setRootBone(m_model.m_rootNode->transform());
renderer = srenderer;
}
else
{
go->AddComponent<MeshFilter>()->SetMesh(mesh);
renderer = go->AddComponent<MeshRenderer>();
renderer->SetMaterial(material);
}
for (int i = 1; i < lMaterialCount; ++i)
{
auto lMaterial = pNode->GetMaterial(i);
material = ParseMaterial(lMaterial);
renderer->AddMaterial(material);
}
}
}
// Recursively print the children.
for (int j = 0; j < pNode->GetChildCount(); j++)
{
auto child = ParseNodeRecursively(pNode->GetChild(j));
child->transform()->SetParent(go->transform(), false);
}
//boost::algorithm::is_iless compare;
go->transform()->children().sort([](std::weak_ptr<Transform> const & lhs, std::weak_ptr<Transform> const & rhs) {
return boost::algorithm::to_lower_copy(lhs.lock()->name()) < boost::algorithm::to_lower_copy(rhs.lock()->name());
});
return go;
}
void FishEditor::FBXImporter::ImportTo(FishEngine::GameObjectPtr & model)
{
abort();
}
void FishEditor::FBXImporter::Reimport()
{
Load(m_assetPath);
}
PrefabPtr FishEditor::FBXImporter::Load(FishEngine::Path const & path)
{
if (m_model.m_modelPrefab == nullptr)
{
m_model.m_modelPrefab = MakeShared<Prefab>();
m_model.m_modelPrefab->setIsPrefabParent(true);
}
if (m_model.m_avatar == nullptr)
{
m_model.m_avatar = MakeShared<Avatar>();
}
// http://help.autodesk.com/view/FBX/2017/ENU/?guid=__files_GUID_29C09995_47A9_4B49_9535_2F6BDC5C4107_htm
// Initialize the SDK manager. This object handles memory management.
FbxManager * lSdkManager = FbxManager::Create();
// Create the IO settings object.
FbxIOSettings * ios = FbxIOSettings::Create(lSdkManager, IOSROOT);
lSdkManager->SetIOSettings(ios);
// Create an importer using the SDK manager.
FbxImporter* lImporter = FbxImporter::Create(lSdkManager, "");
// Use the first argument as the filename for the importer.
if (!lImporter->Initialize(path.string().c_str(), -1, lSdkManager->GetIOSettings()))
{
LogError("Call to FbxImporter::Initialize() failed.");
LogError(std::string( "Error returned: ") + lImporter->GetStatus().GetErrorString() );
abort();
}
auto name = path.stem().string();
// Create a new scene so that it can be populated by the imported file.
FbxScene * lScene = FbxScene::Create(lSdkManager, name.c_str());
// Import the contents of the file into the scene.
lImporter->Import(lScene);
// The file is imported, so get rid of the importer.
lImporter->Destroy();
//FbxAxisSystem::MayaYUp.ConvertScene(lScene);
//FbxAxisSystem::DirectX.ConvertScene(lScene); // wrong!
// FbxSystemUnit::m.ConvertScene(lScene);
// http://help.autodesk.com/view/FBX/2017/ENU/?guid=__files_GUID_CC93340E_C4A1_49EE_B048_E898F856CFBF_htm
// do NOT use FbxSystemUnit::ConvertScene(lScene), which just simply set transform.scale of root nodes.
if ( lScene->GetGlobalSettings().GetSystemUnit() == FbxSystemUnit::mm )
{
m_fileScale = 0.001f;
}
else if ( lScene->GetGlobalSettings().GetSystemUnit() == FbxSystemUnit::dm)
{
m_fileScale = 0.1f;
}
else if (lScene->GetGlobalSettings().GetSystemUnit() == FbxSystemUnit::m)
{
m_fileScale = 1.0f;
}
else if (lScene->GetGlobalSettings().GetSystemUnit() == FbxSystemUnit::cm)
{
m_fileScale = 0.01f;
}
else
{
abort();
}
// auto sceneSystemUnit = lScene->GetGlobalSettings().GetSystemUnit();
// if (sceneSystemUnit.GetScaleFactor() != 1.0f)
// {
// FbxSystemUnit::m.ConvertScene(lScene);
// }
FbxGeometryConverter converter(lSdkManager);
converter.Triangulate(lScene, true);
//converter.SplitMeshesPerMaterial(lScene, true);
BakeTransforms(lScene);
ImportSkeleton(lScene);
// Print the nodes of the scene and their attributes recursively.
// Note that we are not printing the root node because it should
// not contain any attributes.
FbxNode* lRootNode = lScene->GetRootNode();
auto & root = m_model.m_rootNode;
root = FishEngine::GameObject::Create();
root->setName(name);
root->setPrefabInternal(m_model.m_modelPrefab);
root->transform()->setPrefabInternal(m_model.m_modelPrefab);
AssetDatabase::s_allAssetObjects.insert(root);
if (lRootNode)
{
for (int i = 0; i < lRootNode->GetChildCount(); i++)
{
auto child = ParseNodeRecursively(lRootNode->GetChild(i));
child->transform()->SetParent(root->transform(), false);
}
}
ImportAnimations(lScene);
// Destroy the SDK manager and all the other objects it was handling.
lSdkManager->Destroy();
m_model.m_bones.resize(m_boneCount);
UpdateBones(root->transform());
for (auto & renderer : m_model.m_skinnedMeshRenderers)
{
auto mesh = renderer->sharedMesh();
renderer->bones().reserve(mesh->m_boneNames.size());
//mesh->m_bindposes = m_model.m_bindposes;
for (auto & boneName : mesh->m_boneNames)
{
int boneId = m_model.m_avatar->m_boneToIndex[boneName];
renderer->bones().push_back(m_model.m_bones[boneId]);
}
}
for (auto & mesh : m_model.m_meshes)
{
AssetImporter::s_objectInstanceIDToPath[mesh->GetInstanceID()] = path;
if (mesh->m_skinned)
{
mesh->m_bindposes.reserve(mesh->m_boneNames.size());
//mesh->m_bones.reserve(mesh->m_boneNames.size());
//mesh->m_bindposes = m_model.m_bindposes;
for (auto & boneName : mesh->m_boneNames)
{
int boneId = m_model.m_avatar->m_boneToIndex[boneName];
mesh->m_bindposes.push_back(m_model.m_bindposes[boneId]);
//mesh->m_bones.push_back(m_model.m_bones[boneId]);
}
// make sure all the weights sum to 1.
for (auto & bw : mesh->m_boneWeights)
{
if (bw.weight[0] > 0)
{
float boneWeightScale = 0.0f;
for (float w : bw.weight)
{
boneWeightScale += w;
}
if ( Mathf::Abs(boneWeightScale - 1.0f) > 1E-5f)
{
boneWeightScale = 1.0f / boneWeightScale;
for (float & w : bw.weight)
{
w *= boneWeightScale;
}
}
}
}
}
}
//std::deque<TransformPtr> transforms;
//transforms.push_back(m_model.m_rootNode->transform());
//while (!transforms.empty())
//{
// auto current = transforms.front();
// transforms.pop_front();
// for (auto & child : current->children())
// {
// transforms.push_back(child.lock());
// }
//
// auto srenderer = current->gameObject()->GetComponent<SkinnedMeshRenderer>();
// if (srenderer != nullptr)
// {
// srenderer.
// }
//}
//for (int i = 0; i < m_boneCount; ++i)
//{
// Debug::LogWarning("%s", m_model.m_avatar->m_indexToBone[i].c_str());
// PrintMatrix(m_bindPoses[i]);
//}
//m_model.m_rootNode = root;
if (m_model.m_animationClips.size() > 0)
{
auto animation = root->AddComponent<Animation>();
animation->m_clip = m_model.m_animationClips.front();
}
m_model.m_modelPrefab->setRootGameObject(root);
if (IsNewlyCreated())
{
BuildFileIDToRecycleName();
}
m_asset->Add(m_model.m_modelPrefab->rootGameObject());
for (auto & mesh : m_model.m_meshes)
m_asset->Add(mesh);
for (auto & clip : m_model.m_animationClips)
m_asset->Add(clip);
m_asset->Add(m_model.m_avatar);
return m_model.m_modelPrefab;
}
int IncreaseMapValue(std::map<int, int> & dict, int key)
{
auto it = dict.find(key);
if (it == dict.end())
{
dict[key] = 1;
return 0;
}
int ret = it->second;
it->second++;
return ret;
}
void FishEditor::FBXImporter::RecursivelyBuildFileIDToRecycleName(FishEngine::TransformPtr const & transform)
{
auto gameObject = transform->gameObject();
{
constexpr int classID = FishEngine::ClassID<GameObject>();
int id = IncreaseMapValue(m_classIDCount, classID);
id = classID * 100000 + id*2;
m_fileIDToRecycleName[id] = gameObject->name();
}
{
constexpr int classID = FishEngine::ClassID<Transform>();
int id = IncreaseMapValue(m_classIDCount, classID);
id = classID * 100000 + id*2;
m_fileIDToRecycleName[id] = gameObject->name();
}
for (auto & component : gameObject->Components())
{
int classID = component->ClassID();
int id = IncreaseMapValue(m_classIDCount, classID);
id = classID * 100000 + id*2;
m_fileIDToRecycleName[id] = component->name();
}
for (auto & child : transform->children())
{
RecursivelyBuildFileIDToRecycleName(child);
}
}
void FishEditor::FBXImporter::BuildFileIDToRecycleName()
{
RecursivelyBuildFileIDToRecycleName(m_model.m_modelPrefab->rootGameObject()->transform());
}
AnimationClipPtr FishEditor::FBXImporter::ConvertAnimationClip(const FBXAnimationClip& fbxClip)
{
auto result = MakeShared<AnimationClip>();
result->setName(fbxClip.name);
result->frameRate = fbxClip.sampleRate;
result->length = fbxClip.end - fbxClip.start;
auto IsBone = [this](std::string const& name) {
auto it = m_model.m_avatar->m_boneToIndex.find(name);
return it != m_model.m_avatar->m_boneToIndex.end();
};
for (auto & animation : fbxClip.boneAnimations)
{
// TODO: move
//std::string path = "";
auto node = animation.node;
std::string path = node->name();
node = node->parent();
while (node != nullptr)
{
if (!IsBone(node->name()))
break;
path = node->name() + "/" + path;
node = node->parent();
}
if (animation.translation.keyframeCount() > 0)
result->m_positionCurve.emplace_back(Vector3Curve{ path, animation.translation });
if (animation.rotation.keyframeCount() > 0)
result->m_rotationCurves.emplace_back(QuaternionCurve{ path, animation.rotation });
// if (animation.eulers.keyframeCount() > 0)
// result->m_eulersCurves.emplace_back(Vector3Curve{ path, animation.eulers});
if (animation.scale.keyframeCount() > 0)
result->m_scaleCurves.emplace_back(Vector3Curve{ path, animation.scale });
}
return result;
}
void FishEditor::FBXImporter::ImportAnimations(fbxsdk::FbxScene* scene)
{
FbxNode * root = scene->GetRootNode();
int numAnimStacks = scene->GetSrcObjectCount<FbxAnimStack>();
for (int i = 0; i < numAnimStacks; ++i)
{
FbxAnimStack* animStack = scene->GetSrcObject<FbxAnimStack>(i);
m_model.m_clips.emplace_back();
auto & clip = m_model.m_clips.back();
clip.name = animStack->GetName();
FbxTimeSpan timeSpan = animStack->GetLocalTimeSpan();
clip.start = (float)timeSpan.GetStart().GetSecondDouble();
clip.end = (float)timeSpan.GetStop().GetSecondDouble();
clip.sampleRate = (uint32_t)FbxTime::GetFrameRate(scene->GetGlobalSettings().GetTimeMode());
int layerCount = animStack->GetMemberCount<FbxAnimLayer>();
if (layerCount == 1)
{
FbxAnimLayer* animLayer = animStack->GetMember<FbxAnimLayer>(0);
ImportAnimations(animLayer, root, clip);
}
else
{
//abort();
LogError(Format("multiple animation clip in model: %1%", this->m_assetPath.string()));
}
}
for (auto clip : m_model.m_clips)
{
auto animationClip = ConvertAnimationClip(clip);
m_model.m_animationClips.push_back(animationClip);
animationClip->m_avatar = m_model.m_avatar;
}
}
TAnimationCurve<Vector3> reduceKeyframes(TAnimationCurve<Vector3>& curve)
{
uint32_t keyCount = (uint32_t)curve.keyframeCount();
std::vector<TKeyframe<Vector3>> newKeyframes;
bool lastWasEqual = false;
for (uint32_t i = 0; i < keyCount; i++)
{
bool isEqual = true;
const TKeyframe<Vector3>& curKey = curve.keyframeAt(i);
if (i > 0)
{
TKeyframe<Vector3>& prevKey = newKeyframes.back();
isEqual = isEqual && (prevKey.value == curKey.value) && (prevKey.outTangent == curKey.inTangent);
}
else
isEqual = false;
// More than two keys in a row are equal, remove previous key by replacing it with this one
if (lastWasEqual && isEqual)
{
TKeyframe<Vector3>& prevKey = newKeyframes.back();
// Other properties are guaranteed unchanged
prevKey.time = curKey.time;
prevKey.outTangent = curKey.outTangent;
continue;
}
newKeyframes.push_back(curKey);
lastWasEqual = isEqual;
}
return TAnimationCurve<Vector3>(newKeyframes);
}
void SetKeyframeValues(TKeyframe<Vector3>& keyFrame, int idx, float value, float inTangent, float outTangent)
{
keyFrame.value[idx] = value;
keyFrame.inTangent[idx] = inTangent;
keyFrame.outTangent[idx] = outTangent;
}
template<class T, int C>
TAnimationCurve<T> ImportCurve(FbxAnimCurve*(&fbxCurve)[C], float(&defaultValues)[C], float start, float end)
{
int keyCounts[C];
for (int i = 0; i < C; i++)
{
if (fbxCurve[i] != nullptr)
keyCounts[i] = fbxCurve[i]->KeyGetCount();
else
keyCounts[i] = 0;
}
// If curve key-counts don't match, we need to force resampling
bool forceResample = false;
if (!forceResample)
{
for (int i = 1; i < C; i++)
{
forceResample |= keyCounts[i - 1] != keyCounts[i];
if (forceResample)
break;
}
}
// Read keys directly
if (!forceResample)
{
bool foundMismatch = false;
int keyCount = keyCounts[0];
std::vector<TKeyframe<T>> keyframes;
for (int i = 0; i < keyCount; i++)
{
FbxTime fbxTime = fbxCurve[0]->KeyGetTime(i);
float time = (float)fbxTime.GetSecondDouble();
// Ensure times from other curves match
for (int j = 1; j < C; j++)
{
fbxTime = fbxCurve[j]->KeyGetTime(i);
float otherTime = (float)fbxTime.GetSecondDouble();
if (!Mathf::CompareApproximately(time, otherTime))
{
foundMismatch = true;
break;
}
}
if (foundMismatch)
break;
if (time < start || time > end)
continue;
keyframes.push_back(TKeyframe<T>());
TKeyframe<T>& keyFrame = keyframes.back();
keyFrame.time = time;
for (int j = 0; j < C; j++)
{
SetKeyframeValues(keyFrame, j,
fbxCurve[j]->KeyGetValue(i),
fbxCurve[j]->KeyGetLeftDerivative(i),
fbxCurve[j]->KeyGetRightDerivative(i));
}
}
if (!foundMismatch)
return TAnimationCurve<T>(keyframes);
else
forceResample = true;
}
//if (!importOptions.animResample && forceResample)
// LOGWRN("Animation has different keyframes for different curve components, forcing resampling.");
// Resample keys
float curveStart = std::numeric_limits<float>::infinity();
float curveEnd = -std::numeric_limits<float>::infinity();
for (uint32_t i = 0; i < C; i++)
{
if (fbxCurve[i] == nullptr)
{
curveStart = std::min(0.0f, curveStart);
curveEnd = std::max(0.0f, curveEnd);
continue;
}
int keyCount = keyCounts[i];
for (int j = 0; j < keyCount; j++)
{
FbxTime fbxTime = fbxCurve[i]->KeyGetTime(j);
float time = (float)fbxTime.GetSecondDouble();
curveStart = std::min(time, curveStart);
curveEnd = std::max(time, curveEnd);
}
}
curveStart = Mathf::Clamp(curveStart, start, end);
curveEnd = Mathf::Clamp(curveEnd, start, end);
float curveLength = curveEnd - curveStart;
constexpr float animSampleRate = 1.0f / 30.0f;
int numSamples = Mathf::CeilToInt(curveLength / animSampleRate);
// We don't use the exact provided sample rate but instead modify it slightly so it
// completely covers the curve range including start/end points while maintaining
// constant time step between keyframes.
float dt = curveLength / (float)numSamples;
int lastKeyframe[] = { 0, 0, 0 };
int lastLeftTangent[] = { 0, 0, 0 };
int lastRightTangent[] = { 0, 0, 0 };
std::vector<TKeyframe<T>> keyframes(numSamples);
for (int i = 0; i < numSamples; i++)
{
float sampleTime = std::min(curveStart + i * dt, curveEnd);
FbxTime fbxSampleTime;
fbxSampleTime.SetSecondDouble(sampleTime);
TKeyframe<T>& keyFrame = keyframes[i];
keyFrame.time = sampleTime;
for (int j = 0; j < C; j++)
{
if (fbxCurve[j] != nullptr)
{
SetKeyframeValues(keyFrame, j,
fbxCurve[j]->Evaluate(fbxSampleTime, &lastKeyframe[j]),
fbxCurve[j]->EvaluateLeftDerivative(fbxSampleTime, &lastLeftTangent[j]),
fbxCurve[j]->EvaluateRightDerivative(fbxSampleTime, &lastRightTangent[j]));
}
else
{
SetKeyframeValues(keyFrame, j, defaultValues[C], 0.0f, 0.0f);
}
}
}
return TAnimationCurve<T>(keyframes);
}
void FishEditor::FBXImporter::ImportAnimations(fbxsdk::FbxAnimLayer* layer, fbxsdk::FbxNode * node, FBXAnimationClip & clip)
{
FbxAnimCurve* translation[3];
translation[0] = node->LclTranslation.GetCurve(layer, FBXSDK_CURVENODE_COMPONENT_X);
translation[1] = node->LclTranslation.GetCurve(layer, FBXSDK_CURVENODE_COMPONENT_Y);
translation[2] = node->LclTranslation.GetCurve(layer, FBXSDK_CURVENODE_COMPONENT_Z);
FbxAnimCurve* rotation[3];
rotation[0] = node->LclRotation.GetCurve(layer, FBXSDK_CURVENODE_COMPONENT_X);
rotation[1] = node->LclRotation.GetCurve(layer, FBXSDK_CURVENODE_COMPONENT_Y);
rotation[2] = node->LclRotation.GetCurve(layer, FBXSDK_CURVENODE_COMPONENT_Z);
FbxAnimCurve* scale[3];
scale[0] = node->LclScaling.GetCurve(layer, FBXSDK_CURVENODE_COMPONENT_X);
scale[1] = node->LclScaling.GetCurve(layer, FBXSDK_CURVENODE_COMPONENT_Y);
scale[2] = node->LclScaling.GetCurve(layer, FBXSDK_CURVENODE_COMPONENT_Z);
Vector3 defaultTranslation = FBXToNativeType(node->LclTranslation.Get());
Vector3 defaultRotation = FBXToNativeType(node->LclRotation.Get());
Vector3 defaultScale = FBXToNativeType(node->LclScaling.Get());
auto hasCurveValues = [](FbxAnimCurve* curves[3])
{
for (int i = 0; i < 3; i++)
{
if (curves[i] != nullptr && curves[i]->KeyGetCount() > 0)
return true;
}
return false;
};
EFbxRotationOrder order;
node->GetRotationOrder(FbxNode::eDestinationPivot, order);
RotationOrder rotationOrder = FBXToNativeType(order);
bool hasBoneAnimation = hasCurveValues(translation) || hasCurveValues(rotation) || hasCurveValues(scale);
if (order != eEulerXYZ && hasBoneAnimation)
{
LogWarning("here");
}
if (hasBoneAnimation)
{
clip.boneAnimations.push_back(FBXBoneAnimation());
FBXBoneAnimation& boneAnim = clip.boneAnimations.back();
boneAnim.node = m_model.m_fbxNodeLookup[node];
if (hasCurveValues(translation))
{
float defaultValues[3];
memcpy(defaultValues, &defaultTranslation, sizeof(defaultValues));
boneAnim.translation = ImportCurve<Vector3, 3>(translation, defaultValues,
clip.start, clip.end);
}
//else
//{
// std::vector<TKeyframe<Vector3>> keyframes(1);
// keyframes[0].value = defaultTranslation;
// keyframes[0].inTangent = Vector3::zero;
// keyframes[0].outTangent = Vector3::zero;
// boneAnim.translation = TAnimationCurve<Vector3>(keyframes);
//}
if (hasCurveValues(scale))
{
float defaultValues[3];
memcpy(defaultValues, &defaultScale, sizeof(defaultValues));
boneAnim.scale = ImportCurve<Vector3, 3>(scale, defaultValues, clip.start, clip.end);
}
//else
//{
// std::vector<TKeyframe<Vector3>> keyframes(1);
// keyframes[0].value = defaultScale;
// keyframes[0].inTangent = Vector3::zero;
// keyframes[0].outTangent = Vector3::zero;
// boneAnim.scale = TAnimationCurve<Vector3>(keyframes);
//}
TAnimationCurve<Vector3> eulerAnimation;
if (hasCurveValues(rotation))
{
float defaultValues[3];
memcpy(defaultValues, &defaultRotation, sizeof(defaultValues));
eulerAnimation = ImportCurve<Vector3, 3>(rotation, defaultValues, clip.start, clip.end);
}
//else
//{
// std::vector<TKeyframe<Vector3>> keyframes(1);
// keyframes[0].value = defaultRotation;
// keyframes[0].inTangent = Vector3::zero;
// keyframes[0].outTangent = Vector3::zero;
// eulerAnimation = TAnimationCurve<Vector3>(keyframes);
//}
//if(importOptions.reduceKeyframes)
//{
// boneAnim.translation = reduceKeyframes(boneAnim.translation);
// boneAnim.scale = reduceKeyframes(boneAnim.scale);
// eulerAnimation = reduceKeyframes(eulerAnimation);
//}
boneAnim.translation = AnimationCurveUtility::ScaleCurve(boneAnim.translation, m_fileScale * m_globalScale);
//boneAnim.eulers = eulerAnimation;
boneAnim.rotation = AnimationCurveUtility::EulerToQuaternionCurve(eulerAnimation, rotationOrder);
}
int childCount = node->GetChildCount();
for (int i = 0; i < childCount; i++)
{
FbxNode* child = node->GetChild(i);
ImportAnimations(layer, child, clip);
}
}
| 29.087475 | 130 | 0.698927 | [
"mesh",
"object",
"vector",
"model",
"transform"
] |
147c81635c8adb92b40f45c4a64e606166cd2bb5 | 7,617 | hpp | C++ | src/jsoncons/parse_error_handler.hpp | avacore/jsoncons | 0fa3104b6237b3323a749c38ebeaaaebf55e9e48 | [
"BSL-1.0"
] | null | null | null | src/jsoncons/parse_error_handler.hpp | avacore/jsoncons | 0fa3104b6237b3323a749c38ebeaaaebf55e9e48 | [
"BSL-1.0"
] | null | null | null | src/jsoncons/parse_error_handler.hpp | avacore/jsoncons | 0fa3104b6237b3323a749c38ebeaaaebf55e9e48 | [
"BSL-1.0"
] | null | null | null | /// Copyright 2013 Daniel Parker
// Distributed under the Boost license, Version 1.0.
// (See accompanying file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
// See https://sourceforge.net/projects/jsoncons/files/ for latest version
// See https://sourceforge.net/p/jsoncons/wiki/Home/ for documentation.
#ifndef JSONCONS_PARSE_ERROR_HANDLER_HPP
#define JSONCONS_PARSE_ERROR_HANDLER_HPP
#include "jsoncons/jsoncons.hpp"
#include <system_error>
namespace jsoncons {
class json_parse_exception : public json_exception
{
public:
json_parse_exception(std::error_code ec,
unsigned long line,
unsigned long column)
: error_code_(ec),
line_number_(line),
column_number_(column)
{
}
json_parse_exception(const json_parse_exception& other)
: error_code_(other.error_code_),
line_number_(other.line_number_),
column_number_(other.column_number_)
{
}
const char* what() const JSONCONS_NOEXCEPT
{
std::ostringstream os;
os << error_code_.message() << " detected at line " << line_number_ << " and column " << column_number_;
const_cast<std::string&>(buffer_) = os.str();
return buffer_.c_str();
}
const std::error_code code() const
{
return error_code_;
}
unsigned long line_number() const
{
return line_number_;
}
unsigned long column_number() const
{
return column_number_;
}
private:
std::error_code error_code_;
std::string buffer_;
unsigned long line_number_;
unsigned long column_number_;
};
template<typename Char>
class basic_parsing_context
{
public:
virtual ~basic_parsing_context() {}
bool eof() const
{
return do_eof();
}
unsigned long line_number() const
{
return do_line_number();
}
unsigned long column_number() const
{
return do_column_number();
}
Char last_char() const
{
return do_last_char();
}
size_t minimum_structure_capacity() const
{
return do_minimum_structure_capacity();
}
private:
virtual unsigned long do_line_number() const = 0;
virtual unsigned long do_column_number() const = 0;
virtual bool do_eof() const = 0;
virtual size_t do_minimum_structure_capacity() const = 0;
virtual Char do_last_char() const = 0;
};
typedef basic_parsing_context<char> parsing_context;
typedef basic_parsing_context<wchar_t> wparsing_context;
template <typename Char>
class basic_parse_error_handler
{
public:
virtual ~basic_parse_error_handler()
{
}
void warning(std::error_code ec,
const basic_parsing_context<Char>& context) throw (json_parse_exception)
{
do_warning(ec,context);
}
void error(std::error_code ec,
const basic_parsing_context<Char>& context) throw (json_parse_exception)
{
do_error(ec,context);
}
private:
virtual void do_warning(std::error_code,
const basic_parsing_context<Char>& context) throw (json_parse_exception) = 0;
virtual void do_error(std::error_code,
const basic_parsing_context<Char>& context) throw (json_parse_exception) = 0;
};
template <typename Char>
class default_basic_parse_error_handler : public basic_parse_error_handler<Char>
{
public:
static basic_parse_error_handler<Char>& instance()
{
static default_basic_parse_error_handler<Char> instance;
return instance;
}
private:
virtual void do_warning(std::error_code,
const basic_parsing_context<Char>& context) throw (json_parse_exception)
{
}
virtual void do_error(std::error_code ec,
const basic_parsing_context<Char>& context) throw (json_parse_exception)
{
throw json_parse_exception(ec,context.line_number(),context.column_number());
}
};
typedef basic_parse_error_handler<char> parse_error_handler;
typedef basic_parse_error_handler<wchar_t> wparse_error_handler;
typedef default_basic_parse_error_handler<char> default_parse_error_handler;
typedef default_basic_parse_error_handler<wchar_t> wdefault_parse_error_handler;
typedef basic_parsing_context<char> parsing_context;
typedef basic_parsing_context<wchar_t> wparsing_context;
namespace json_parser_errc
{
enum json_parser_errc_t
{
expected_value_separator,
unexpected_value_separator,
unexpected_end_of_object,
unexpected_end_of_array,
expected_name,
expected_value,
expected_name_separator,
unexpected_name_separator,
illegal_control_character,
illegal_escaped_character,
invalid_codepoint_surrogate_pair,
invalid_hex_escape_sequence,
invalid_unicode_escape_sequence,
invalid_number,
unexpected_eof,
eof_reading_string_value,
eof_reading_numeric_value
};
}
class json_parser_category_impl
: public std::error_category
{
public:
virtual const char* name() const JSONCONS_NOEXCEPT
{
return "json_input";
}
virtual std::string message(int ev) const
{
switch (ev)
{
case json_parser_errc::unexpected_value_separator:
return "Unexpected value separator ','";
case json_parser_errc::expected_value_separator:
return "Expected value separator ','";
case json_parser_errc::unexpected_end_of_object:
return "Unexpected end of object '}'";
case json_parser_errc::unexpected_end_of_array:
return "Unexpected end of array ']'";
case json_parser_errc::expected_name:
return "Expected name";
case json_parser_errc::expected_value:
return "Expected value";
case json_parser_errc::unexpected_name_separator:
return "Unexpected name separator ':'";
case json_parser_errc::expected_name_separator:
return "Expected name separator ':'";
case json_parser_errc::illegal_control_character:
return "Illegal control character in string";
case json_parser_errc::illegal_escaped_character:
return "Illegal escaped character in string";
case json_parser_errc::invalid_codepoint_surrogate_pair:
return "Invalid codepoint, expected another \\u token to begin the second half of a codepoint surrogate pair.";
case json_parser_errc::invalid_hex_escape_sequence:
return "Invalid codepoint, expected hexadecimal digit.";
case json_parser_errc::invalid_unicode_escape_sequence:
return "Invalid codepoint, expected four hexadecimal digits.";
case json_parser_errc::invalid_number:
return "Invalid number";
case json_parser_errc::unexpected_eof:
return "Unexpected end of file";
case json_parser_errc::eof_reading_string_value:
return "Reached end of file while reading string value";
case json_parser_errc::eof_reading_numeric_value:
return "Reached end of file while reading numeric value";
default:
return "Unknown JSON parser error";
}
}
};
inline
const std::error_category& json_parser_category()
{
static json_parser_category_impl instance;
return instance;
}
inline
std::error_code make_error_code(json_parser_errc::json_parser_errc_t e)
{
return std::error_code(
static_cast<int>(e),
json_parser_category());
}
}
#endif
| 30.22619 | 123 | 0.684128 | [
"object"
] |
14851650625cde4d6b2435f6d5bf627983f36ca7 | 5,806 | hpp | C++ | libcore/include/sirikata/core/transfer/TransferPool.hpp | sirikata/sirikata | 3a0d54a8c4778ad6e25ef031d461b2bc3e264860 | [
"BSD-3-Clause"
] | 31 | 2015-01-28T17:01:10.000Z | 2021-11-04T08:30:37.000Z | libcore/include/sirikata/core/transfer/TransferPool.hpp | sirikata/sirikata | 3a0d54a8c4778ad6e25ef031d461b2bc3e264860 | [
"BSD-3-Clause"
] | null | null | null | libcore/include/sirikata/core/transfer/TransferPool.hpp | sirikata/sirikata | 3a0d54a8c4778ad6e25ef031d461b2bc3e264860 | [
"BSD-3-Clause"
] | 9 | 2015-08-02T18:39:49.000Z | 2019-10-11T10:32:30.000Z | /* Sirikata Transfer -- Content Transfer management system
* TransferPool.hpp
*
* Copyright (c) 2010, Jeff Terrace
* 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.
*/
/* Created on: Jan 20th, 2010 */
#ifndef SIRIKATA_TransferPool_HPP__
#define SIRIKATA_TransferPool_HPP__
#include <sirikata/core/transfer/Defs.hpp>
#include <sirikata/core/queue/ThreadSafeQueue.hpp>
#include <sirikata/core/transfer/TransferRequest.hpp>
namespace Sirikata {
namespace Transfer {
/*
* Abstract class for providing an algorithm for aggregating priorities from
* one or more clients for a request
*/
class PriorityAggregationAlgorithm {
public:
// Return an aggregated priority given a list of priorities
virtual Priority aggregate(
const std::vector<Priority> &) const = 0;
//Return an aggregated priority given the list of priorities
virtual Priority aggregate(
const std::map<std::string, TransferRequestPtr> &) const = 0;
virtual Priority aggregate(
const std::vector<TransferRequestPtr>&) const = 0;
virtual ~PriorityAggregationAlgorithm() {
}
};
/** Pools are the conduits for requests to get into the
* TransferMediator for processing. Pools interact carefully with the
* TransferMediator, which has stricter rules (e.g. only one
* outstanding request for a resource at a time with a single
* priority), but provide more convenient interfaces to the
* user. Implementations might do very little, almost directly
* passing requests on, or might provide an additional layer of
* aggregation of requests and multiplexing of callbacks. This
* intermediate layer allows individual requests to remain simple
* but provides a layer for coordination (e.g. for aggregation).
*/
class TransferPool {
public:
virtual ~TransferPool() {}
/// Returns client identifier
inline const std::string& getClientID() const {
return mClientID;
}
/// Puts a request into the pool
virtual void addRequest(TransferRequestPtr req) = 0;
/// Updates priority of a request in the pool
virtual void updatePriority(TransferRequestPtr req, Priority p) = 0;
/// Updates priority of a request in the pool
virtual void deleteRequest(TransferRequestPtr req) = 0;
protected:
// Friend in TransferMediator so it can construct, call getRequest
friend class TransferMediator;
TransferPool(const std::string& clientID)
: mClientID(clientID)
{}
virtual TransferRequestPtr getRequest() = 0;
// Utility methods because they require being friended by
// TransferRequest but that doesn't extend to subclasses
void setRequestClientID(TransferRequestPtr req) {
req->setClientID(mClientID);
}
void setRequestPriority(TransferRequestPtr req, Priority p) {
req->setPriority(p);
}
void setRequestDeletion(TransferRequestPtr req) {
req->setDeletion();
}
const std::string mClientID;
};
typedef std::tr1::shared_ptr<TransferPool> TransferPoolPtr;
/** Simplest implementation of TransferPool. The user *must only have
* one outstanding request for any given resource at a time*.
*/
class SimpleTransferPool : public TransferPool {
public:
virtual ~SimpleTransferPool() {}
//Puts a request into the pool
virtual void addRequest(TransferRequestPtr req) {
if (req)
setRequestClientID(req);
mDeltaQueue.push(req);
}
//Updates priority of a request in the pool
virtual void updatePriority(TransferRequestPtr req, Priority p) {
setRequestPriority(req, p);
mDeltaQueue.push(req);
}
//Updates priority of a request in the pool
inline void deleteRequest(TransferRequestPtr req) {
setRequestDeletion(req);
mDeltaQueue.push(req);
}
private:
// Friend in TransferMediator so it can construct, call getRequest
friend class TransferMediator;
ThreadSafeQueue<TransferRequestPtr> mDeltaQueue;
SimpleTransferPool(const std::string &clientID)
: TransferPool(clientID)
{
}
//Returns an item from the pool. Blocks if pool is empty.
inline std::tr1::shared_ptr<TransferRequest> getRequest() {
std::tr1::shared_ptr<TransferRequest> retval;
mDeltaQueue.blockingPop(retval);
return retval;
}
};
}
}
#endif
| 34.559524 | 76 | 0.726662 | [
"vector"
] |
14926751d56ce44159ecce67a0da78f394c5426d | 1,548 | cpp | C++ | cpp/src/meta-fetcher.cpp | jujanda/ndnrtc_arc | f152e56c5181775b0db899c33d86e19669c35b9a | [
"BSD-2-Clause"
] | null | null | null | cpp/src/meta-fetcher.cpp | jujanda/ndnrtc_arc | f152e56c5181775b0db899c33d86e19669c35b9a | [
"BSD-2-Clause"
] | null | null | null | cpp/src/meta-fetcher.cpp | jujanda/ndnrtc_arc | f152e56c5181775b0db899c33d86e19669c35b9a | [
"BSD-2-Clause"
] | null | null | null | //
// meta-fetcher.cpp
//
// Created by Peter Gusev on 17 June 2016.
// Copyright 2013-2016 Regents of the University of California
//
#include "meta-fetcher.hpp"
#include <boost/thread.hpp>
#include <ndn-cpp/face.hpp>
#include <ndn-cpp/security/key-chain.hpp>
#include "name-components.hpp"
using namespace ndn;
using namespace ndnrtc;
void MetaFetcher::fetch(boost::shared_ptr<ndn::Face> f, boost::shared_ptr<ndn::KeyChain> kc,
const ndn::Name &prefix, const OnMeta &onMeta, const OnError &onError)
{
LogTraceC << "fetching meta for " << prefix << std::endl;
Interest i(prefix, 3000);
isPending_ = true;
boost::shared_ptr<MetaFetcher> me = boost::dynamic_pointer_cast<MetaFetcher>(shared_from_this());
// uses ndnrtc implementation of SegmentFetcher, NOT the one from NDN-CPP
SegmentFetcher::fetch(*f, i, kc.get(),
[onMeta, me, f, kc, this](const Blob &content, const std::vector<ValidationErrorInfo> &info) {
isPending_ = false;
ImmutableHeaderPacket<DataSegmentHeader> packet(content);
NetworkData nd(packet.getPayload().size(), packet.getPayload().data());
onMeta(nd, info);
},
[onError, me, f, kc, this](SegmentFetcher::ErrorCode code, const std::string &msg) {
isPending_ = false;
onError(msg);
});
}
| 38.7 | 120 | 0.578165 | [
"vector"
] |
149286a0c6f73067b529d412a4ec7bf56affe22b | 100,735 | cpp | C++ | Official Windows Driver Kit Sample/Windows Driver Kit (WDK) 8.0 Samples/[C++]-Windows Driver Kit (WDK) 8.0 Samples/C++/WDK 8.0 Samples/Sensors HID sample driver/Solution/SensorManager.cpp | zzgchina888/msdn-code-gallery-microsoft | 21cb9b6bc0da3b234c5854ecac449cb3bd261f29 | [
"MIT"
] | 2 | 2022-01-21T01:40:58.000Z | 2022-01-21T01:41:10.000Z | Official Windows Driver Kit Sample/Windows Driver Kit (WDK) 8.0 Samples/[C++]-Windows Driver Kit (WDK) 8.0 Samples/C++/WDK 8.0 Samples/Sensors HID sample driver/Solution/SensorManager.cpp | zzgchina888/msdn-code-gallery-microsoft | 21cb9b6bc0da3b234c5854ecac449cb3bd261f29 | [
"MIT"
] | 1 | 2022-03-15T04:21:41.000Z | 2022-03-15T04:21:41.000Z | Official Windows Driver Kit Sample/Windows Driver Kit (WDK) 8.0 Samples/[C++]-Windows Driver Kit (WDK) 8.0 Samples/C++/WDK 8.0 Samples/Sensors HID sample driver/Solution/SensorManager.cpp | zzgchina888/msdn-code-gallery-microsoft | 21cb9b6bc0da3b234c5854ecac449cb3bd261f29 | [
"MIT"
] | 2 | 2020-10-19T23:36:26.000Z | 2020-10-22T12:59:37.000Z | //
// Copyright (C) Microsoft. All rights reserved.
//
/*
// THIS CODE AND INFORMATION IS PROVIDED "AS IS" WITHOUT WARRANTY OF
// ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO
// THE IMPLIED WARRANTIES OF MERCHANTABILITY AND/OR FITNESS FOR A
// PARTICULAR PURPOSE.
Module Name:
SensorManager.cpp
Abstract:
Implements the CSensorManager container class
--*/
#include "internal.h"
#include "SensorDDI.h"
#include "SensorManager.h"
#include "Sensor.h"
#include "Accelerometer.h"
#include "AmbientLight.h"
#include "Presence.h"
#include "Compass.h"
#include "Gyrometer.h"
#include "Inclinometer.h"
#include "AtmosPressure.h"
#include "Humidity.h"
#include "Thermometer.h"
#include "Potentiometer.h"
#include "Distance.h"
#include "Switches.h"
#include "Voltage.h"
#include "Current.h"
#include "Power.h"
#include "Frequency.h"
#include "Orientation.h"
#include "Custom.h"
#include "Generic.h"
#include "Unsupported.h"
#include "Device.h"
#include "SensorManager.tmh"
/////////////////////////////////////////////////////////////////////////
//
// CSensorManager::CSensorManager
//
// Object constructor function
//
/////////////////////////////////////////////////////////////////////////
CSensorManager::CSensorManager() :
m_spWdfDevice(NULL),
m_spClassExtension(NULL),
m_pSensorDDI(NULL),
m_hSensorEvent(NULL),
m_hSensorManagerEventingThread(NULL),
m_fSensorManagerInitialized(FALSE),
m_fThreadActive(FALSE),
m_pDevice(NULL)
{
}
/////////////////////////////////////////////////////////////////////////
//
// CSensorManager::~CSensorManager
//
// Object destructor function
//
/////////////////////////////////////////////////////////////////////////
CSensorManager::~CSensorManager()
{
SAFE_RELEASE(m_pSensorDDI);
SAFE_RELEASE(m_pDevice);
}
/////////////////////////////////////////////////////////////////////////
//
// CSensorManager::Initialize
//
// Merely store the device pointer. The rest of the init will be done
// in Start(). This is because init depends on communication with the
// device.
//
//
/////////////////////////////////////////////////////////////////////////
HRESULT CSensorManager::Initialize(_In_ IWDFDevice* pWdfDevice, _In_ CMyDevice* pDevice)
{
HRESULT hr = (FALSE == IsInitialized()) ? S_OK : E_UNEXPECTED;
if(SUCCEEDED(hr))
{
// Store the IWDF Device pointer
m_spWdfDevice = pWdfDevice;
m_fInitializationComplete = FALSE;
m_NumMappedSensors = 0;
m_pDevice = pDevice;
m_pDevice->AddRef();
}
return hr;
}
/////////////////////////////////////////////////////////////////////////
//
// CSensorManager::Uninitialize
//
//
//
//
/////////////////////////////////////////////////////////////////////////
void CSensorManager::Uninitialize()
{
// Free all the sensor objects
for(DWORD i = 0; i < m_pSensorList.GetCount(); i++)
{
CSensor *pSensor = m_pSensorList.GetAt(m_pSensorList.FindIndex(i));
if (nullptr != pSensor)
{
pSensor->Uninitialize();
delete pSensor;
}
}
// Clear the Sensor list and Sensor, client and subscriber maps
m_pSensorList.RemoveAll();
m_AvailableSensorsIDs.RemoveAll();
m_AvailableSensorsTypes.RemoveAll();
m_AvailableSensorsUsages.RemoveAll();
m_AvailableSensorsLinkCollections.RemoveAll();
// Release Sensor Class Extension and Sensor DDI
if(NULL != m_spClassExtension)
{
m_spClassExtension->Uninitialize();
m_spClassExtension.Release();
}
SAFE_RELEASE(m_pSensorDDI);
m_fSensorManagerInitialized = FALSE;
return;
}
/////////////////////////////////////////////////////////////////////////
//
// CSensorManager::InitializeClassExtension
//
//
//
//
/////////////////////////////////////////////////////////////////////////
HRESULT CSensorManager::InitializeClassExtension()
{
HRESULT hr = (NULL == m_spClassExtension) ? S_OK : E_UNEXPECTED;
if(SUCCEEDED(hr))
{
// CoCreate the Sensor ClassExtension
if(SUCCEEDED(hr))
{
hr = CoCreateInstance(CLSID_SensorClassExtension,
NULL,
CLSCTX_INPROC_SERVER,
IID_PPV_ARGS(&m_spClassExtension));
if (REGDB_E_CLASSNOTREG == hr)
{
Trace(TRACE_LEVEL_ERROR, "Class is not registered, hr = %!HRESULT!", hr);
hr = E_UNEXPECTED;
m_spClassExtension = NULL;
}
}
// Initialize Sensor ClassExtension
if(SUCCEEDED(hr))
{
CComPtr<IUnknown> spIUnknown;
hr = m_pSensorDDI->QueryInterface(IID_IUnknown, (void**)&spIUnknown);
if(SUCCEEDED(hr))
{
if ( NULL != m_spClassExtension )
{
if (nullptr != m_spWdfDevice)
{
hr = m_spClassExtension->Initialize(m_spWdfDevice, spIUnknown);
}
else
{
hr = E_POINTER;
}
}
}
}
}
return hr;
}
/////////////////////////////////////////////////////////////////////////////////
//
// CSensorManager::Start
//
//
//
//
//////////////////////////////////////////////////////////////////////////////////
HRESULT CSensorManager::Start()
{
Trace(TRACE_LEVEL_INFORMATION, "%!FUNC! Entry");
HRESULT hr;
// Create the sensor DDI if not done already
if (NULL == m_pSensorDDI)
{
//
// Create the SensorDDI object that implements ISensorDriver
//
hr = CComObject<CSensorDDI>::CreateInstance(&m_pSensorDDI);
if ((SUCCEEDED(hr)) && (NULL != m_pSensorDDI))
{
m_pSensorDDI->AddRef();
}
}
// Always initialize the sensor DDI on Start()
if(NULL != m_pSensorDDI)
{
m_pSensorDDI->m_pSensorManager = this;
hr = m_pSensorDDI->InitSensorDevice(m_spWdfDevice);
}
else
{
hr = E_UNEXPECTED;
Trace(TRACE_LEVEL_ERROR, "SensorDDI pointer is NULL, hr = %!HRESULT!", hr);
}
// Init sensor driver the first time Start() is called. This is done
// here vs. in Initialize() because we need to contact the device to
// determine its type before init.
if (SUCCEEDED(hr) && FALSE == IsInitialized())
{
// Get the device's report description to determine
// the sensor and report type
SensorType sensType = SensorTypeNone;
WCHAR* tempStr = nullptr;
WCHAR* sensorID = nullptr;
WCHAR* deviceID = nullptr;
WCHAR* pwszManufacturer = nullptr;
WCHAR* pwszProduct = nullptr;
WCHAR* pwszSerialNumber = nullptr;
try
{
tempStr = new WCHAR[HID_USB_DESCRIPTOR_MAX_LENGTH];
}
catch(...)
{
hr = E_UNEXPECTED;
Trace(TRACE_LEVEL_ERROR, "Failed to allocate memory for temp string, hr = %!HRESULT!", hr);
if (nullptr != tempStr)
{
delete[] tempStr;
}
}
try
{
sensorID = new WCHAR[HID_USB_DESCRIPTOR_MAX_LENGTH];
}
catch(...)
{
hr = E_UNEXPECTED;
Trace(TRACE_LEVEL_ERROR, "Failed to allocate memory for sensor ID string, hr = %!HRESULT!", hr);
if (nullptr != sensorID)
{
delete[] sensorID;
}
}
try
{
deviceID = new WCHAR[HID_USB_DESCRIPTOR_MAX_LENGTH];
}
catch(...)
{
hr = E_UNEXPECTED;
Trace(TRACE_LEVEL_ERROR, "Failed to allocate memory for device ID string, hr = %!HRESULT!", hr);
if (nullptr != deviceID)
{
delete[] deviceID;
}
}
try
{
pwszManufacturer = new WCHAR[HID_USB_DESCRIPTOR_MAX_LENGTH];
}
catch(...)
{
hr = E_UNEXPECTED;
Trace(TRACE_LEVEL_ERROR, "Failed to allocate memory for manufacturer string, hr = %!HRESULT!", hr);
if (nullptr != pwszManufacturer)
{
delete[] pwszManufacturer;
}
}
try
{
pwszProduct = new WCHAR[HID_USB_DESCRIPTOR_MAX_LENGTH];
}
catch(...)
{
hr = E_UNEXPECTED;
Trace(TRACE_LEVEL_ERROR, "Failed to allocate memory for product string, hr = %!HRESULT!", hr);
if (nullptr != pwszProduct)
{
delete[] pwszProduct;
}
}
try
{
pwszSerialNumber = new WCHAR[HID_USB_DESCRIPTOR_MAX_LENGTH];
}
catch(...)
{
hr = E_UNEXPECTED;
Trace(TRACE_LEVEL_ERROR, "Failed to allocate memory for serial number string, hr = %!HRESULT!", hr);
if (nullptr != pwszSerialNumber)
{
delete[] pwszSerialNumber;
}
}
if (SUCCEEDED(hr))
{
int numSensors = 0;
#pragma warning(push)
#pragma warning(disable:26035)
// the OACR warning is being disabled here because it expects a null-terminated string
// for this particular use. However, string termination happens in the called method
hr = m_pSensorDDI->RequestDeviceInfo(&sensType, pwszManufacturer, pwszProduct, pwszSerialNumber, deviceID);
#pragma warning(pop)
if (SUCCEEDED(hr))
{
CSensor* pSensor = NULL;
CAccelerometer* pAccelerometer = NULL;
CAmbientLight* pAmbientLight = NULL;
CPresence* pPresence = NULL;
CCompass* pCompass = NULL;
CGyrometer* pGyrometer = NULL;
CInclinometer* pInclinometer = NULL;
CBarometer* pBarometer = NULL;
CHygrometer* pHygrometer = NULL;
CThermometer* pThermometer = NULL;
CPotentiometer* pPotentiometer = NULL;
CDistance* pDistance = NULL;
CSwitch* pSwitch = NULL;
CVoltage* pVoltage = NULL;
CCurrent* pCurrent = NULL;
CPower* pPower = NULL;
CFrequency* pFrequency = NULL;
COrientation* pOrientation = NULL;
CCustom* pCustom = NULL;
CGeneric* pGeneric = NULL;
CUnsupported* pUnsupported = NULL;
if (sensType == Collection)
{
numSensors = (int)m_AvailableSensorsTypes.GetCount();
}
else
{
numSensors = 1;
}
m_NumMappedSensors = (ULONG)numSensors;
//Build the sensor objects from the sensor map
if((SUCCEEDED(hr)) && (numSensors > 0))
{
for (int idx = 0; idx < numSensors; idx++)
{
if (((sensType < FirstSensorType) || (sensType > LastSensorType)) && sensType != Collection)
{
hr = E_UNEXPECTED;
Trace(TRACE_LEVEL_ERROR, "Invalid sensor type, hr = %!HRESULT!", hr);
}
else
{
hr = StringCchCopy(sensorID, HID_USB_DESCRIPTOR_MAX_LENGTH, m_wszDeviceId);
if (SUCCEEDED(hr))
{
hr = StringTrim(sensorID);
if (SUCCEEDED(hr))
{
switch (m_AvailableSensorsTypes[idx])
{
case Accelerometer:
hr = StringCchPrintf(tempStr, HID_USB_DESCRIPTOR_MAX_LENGTH, L"#%s-%i", deviceID, idx);
if (SUCCEEDED(hr))
{
hr = StringCchCat(sensorID, HID_USB_DESCRIPTOR_MAX_LENGTH, tempStr);
}
if (SUCCEEDED(hr))
{
m_AvailableSensorsIDs[idx] = sensorID;
try
{
pAccelerometer = new CAccelerometer();
}
catch(...)
{
hr = E_UNEXPECTED;
Trace(TRACE_LEVEL_ERROR, "Failed to create new accelerometer, hr = %!HRESULT!", hr);
if (nullptr != pAccelerometer)
delete pAccelerometer;
}
if (NULL != pAccelerometer)
{
hr = pAccelerometer->Initialize(
Accelerometer,
m_AvailableSensorsUsages[idx],
m_AvailableSensorsLinkCollections[idx],
idx,
pwszManufacturer,
pwszProduct,
pwszSerialNumber,
sensorID,
this);
}
else
{
hr = E_OUTOFMEMORY;
Trace(TRACE_LEVEL_ERROR, "Unable to create accelerometer object, hr = %!HRESULT!", hr);
}
if(SUCCEEDED(hr))
{
pSensor = static_cast<CSensor*>(pAccelerometer);
Trace(TRACE_LEVEL_INFORMATION, "Accelerometer sensor successfully created, Sensor ID = %ls, hr = %!HRESULT!", sensorID, hr);
}
}
break;
case AmbientLight:
hr = StringCchPrintf(tempStr, HID_USB_DESCRIPTOR_MAX_LENGTH, L"#%s-%i", deviceID, idx);
if (SUCCEEDED(hr))
{
hr = StringCchCat(sensorID, HID_USB_DESCRIPTOR_MAX_LENGTH, tempStr);
}
if (SUCCEEDED(hr))
{
m_AvailableSensorsIDs[idx] = sensorID;
try
{
pAmbientLight = new CAmbientLight();
}
catch(...)
{
hr = E_UNEXPECTED;
Trace(TRACE_LEVEL_ERROR, "Failed to create new ambientlight, hr = %!HRESULT!", hr);
if (nullptr != pAmbientLight)
delete pAmbientLight;
}
if (NULL != pAmbientLight)
{
hr = pAmbientLight->Initialize(
AmbientLight,
m_AvailableSensorsUsages[idx],
m_AvailableSensorsLinkCollections[idx],
idx,
pwszManufacturer,
pwszProduct,
pwszSerialNumber,
sensorID,
this);
}
else
{
hr = E_OUTOFMEMORY;
Trace(TRACE_LEVEL_ERROR, "Unable to create ambientlight object, hr = %!HRESULT!", hr);
}
if(SUCCEEDED(hr))
{
pSensor = static_cast<CSensor*>(pAmbientLight);
Trace(TRACE_LEVEL_INFORMATION, "AmbientLight sensor successfully created, Sensor ID = %ls, hr = %!HRESULT!", sensorID, hr);
}
}
break;
case Presence:
hr = StringCchPrintf(tempStr, HID_USB_DESCRIPTOR_MAX_LENGTH, L"#%s-%i", deviceID, idx);
if (SUCCEEDED(hr))
{
hr = StringCchCat(sensorID, HID_USB_DESCRIPTOR_MAX_LENGTH, tempStr);
}
if (SUCCEEDED(hr))
{
m_AvailableSensorsIDs[idx] = sensorID;
try
{
pPresence = new CPresence();
}
catch(...)
{
hr = E_UNEXPECTED;
Trace(TRACE_LEVEL_ERROR, "Failed to create new presence, hr = %!HRESULT!", hr);
if (nullptr != pPresence)
delete pPresence;
}
if (NULL != pPresence)
{
hr = pPresence->Initialize(
Presence,
m_AvailableSensorsUsages[idx],
m_AvailableSensorsLinkCollections[idx],
idx,
pwszManufacturer,
pwszProduct,
pwszSerialNumber,
sensorID,
this);
}
else
{
hr = E_OUTOFMEMORY;
Trace(TRACE_LEVEL_ERROR, "Unable to create presence object, hr = %!HRESULT!", hr);
}
if(SUCCEEDED(hr))
{
pSensor = static_cast<CSensor*>(pPresence);
Trace(TRACE_LEVEL_INFORMATION, "Presence sensor successfully created, Sensor ID = %ls, hr = %!HRESULT!", sensorID, hr);
}
}
break;
case Compass:
hr = StringCchPrintf(tempStr, HID_USB_DESCRIPTOR_MAX_LENGTH, L"#%s-%i", deviceID, idx);
if (SUCCEEDED(hr))
{
hr = StringCchCat(sensorID, HID_USB_DESCRIPTOR_MAX_LENGTH, tempStr);
}
if (SUCCEEDED(hr))
{
m_AvailableSensorsIDs[idx] = sensorID;
try
{
pCompass = new CCompass();
}
catch(...)
{
hr = E_UNEXPECTED;
Trace(TRACE_LEVEL_ERROR, "Failed to create new compass, hr = %!HRESULT!", hr);
if (nullptr != pCompass)
delete pCompass;
}
if (NULL != pCompass)
{
hr = pCompass->Initialize(
Compass,
m_AvailableSensorsUsages[idx],
m_AvailableSensorsLinkCollections[idx],
idx,
pwszManufacturer,
pwszProduct,
pwszSerialNumber,
sensorID,
this);
}
else
{
hr = E_OUTOFMEMORY;
Trace(TRACE_LEVEL_ERROR, "Unable to create compass object, hr = %!HRESULT!", hr);
}
if(SUCCEEDED(hr))
{
pSensor = static_cast<CSensor*>(pCompass);
Trace(TRACE_LEVEL_INFORMATION, "Compass sensor successfully created, Sensor ID = %ls, hr = %!HRESULT!", sensorID, hr);
}
}
break;
case Gyrometer:
hr = StringCchPrintf(tempStr, HID_USB_DESCRIPTOR_MAX_LENGTH, L"#%s-%i", deviceID, idx);
if (SUCCEEDED(hr))
{
hr = StringCchCat(sensorID, HID_USB_DESCRIPTOR_MAX_LENGTH, tempStr);
}
if (SUCCEEDED(hr))
{
m_AvailableSensorsIDs[idx] = sensorID;
try
{
pGyrometer = new CGyrometer();
}
catch(...)
{
hr = E_UNEXPECTED;
Trace(TRACE_LEVEL_ERROR, "Failed to create new gyrometer, hr = %!HRESULT!", hr);
if (nullptr != pGyrometer)
delete pGyrometer;
}
if (NULL != pGyrometer)
{
hr = pGyrometer->Initialize(
Gyrometer,
m_AvailableSensorsUsages[idx],
m_AvailableSensorsLinkCollections[idx],
idx,
pwszManufacturer,
pwszProduct,
pwszSerialNumber,
sensorID,
this);
}
else
{
hr = E_OUTOFMEMORY;
Trace(TRACE_LEVEL_ERROR, "Unable to create gyrometer object, hr = %!HRESULT!", hr);
}
if(SUCCEEDED(hr))
{
pSensor = static_cast<CSensor*>(pGyrometer);
Trace(TRACE_LEVEL_INFORMATION, "Gyrometer sensor successfully created, Sensor ID = %ls, hr = %!HRESULT!", sensorID, hr);
}
}
break;
case Inclinometer:
hr = StringCchPrintf(tempStr, HID_USB_DESCRIPTOR_MAX_LENGTH, L"#%s-%i", deviceID, idx);
if (SUCCEEDED(hr))
{
hr = StringCchCat(sensorID, HID_USB_DESCRIPTOR_MAX_LENGTH, tempStr);
}
if (SUCCEEDED(hr))
{
m_AvailableSensorsIDs[idx] = sensorID;
try
{
pInclinometer = new CInclinometer();
}
catch(...)
{
hr = E_UNEXPECTED;
Trace(TRACE_LEVEL_ERROR, "Failed to create new inclinometer, hr = %!HRESULT!", hr);
if (nullptr != pInclinometer)
delete pInclinometer;
}
if (NULL != pInclinometer)
{
hr = pInclinometer->Initialize(
Inclinometer,
m_AvailableSensorsUsages[idx],
m_AvailableSensorsLinkCollections[idx],
idx,
pwszManufacturer,
pwszProduct,
pwszSerialNumber,
sensorID,
this);
}
else
{
hr = E_OUTOFMEMORY;
Trace(TRACE_LEVEL_ERROR, "Unable to create Inclinometer object, hr = %!HRESULT!", hr);
}
if(SUCCEEDED(hr))
{
pSensor = static_cast<CSensor*>(pInclinometer);
Trace(TRACE_LEVEL_INFORMATION, "Inclinometer sensor successfully created, Sensor ID = %ls, hr = %!HRESULT!", sensorID, hr);
}
}
break;
case Barometer:
hr = StringCchPrintf(tempStr, HID_USB_DESCRIPTOR_MAX_LENGTH, L"#%s-%i", deviceID, idx);
if (SUCCEEDED(hr))
{
hr = StringCchCat(sensorID, HID_USB_DESCRIPTOR_MAX_LENGTH, tempStr);
}
if (SUCCEEDED(hr))
{
m_AvailableSensorsIDs[idx] = sensorID;
try
{
pBarometer = new CBarometer();
}
catch(...)
{
hr = E_UNEXPECTED;
Trace(TRACE_LEVEL_ERROR, "Failed to create new barometer, hr = %!HRESULT!", hr);
if (nullptr != pBarometer)
delete pBarometer;
}
if (NULL != pBarometer)
{
hr = pBarometer->Initialize(
Barometer,
m_AvailableSensorsUsages[idx],
m_AvailableSensorsLinkCollections[idx],
idx,
pwszManufacturer,
pwszProduct,
pwszSerialNumber,
sensorID,
this);
}
else
{
hr = E_OUTOFMEMORY;
Trace(TRACE_LEVEL_ERROR, "Unable to create Barometer object, hr = %!HRESULT!", hr);
}
if(SUCCEEDED(hr))
{
pSensor = static_cast<CSensor*>(pBarometer);
Trace(TRACE_LEVEL_INFORMATION, "Barometer sensor successfully created, Sensor ID = %ls, hr = %!HRESULT!", sensorID, hr);
}
}
break;
case Hygrometer:
hr = StringCchPrintf(tempStr, HID_USB_DESCRIPTOR_MAX_LENGTH, L"#%s-%i", deviceID, idx);
if (SUCCEEDED(hr))
{
hr = StringCchCat(sensorID, HID_USB_DESCRIPTOR_MAX_LENGTH, tempStr);
}
if (SUCCEEDED(hr))
{
m_AvailableSensorsIDs[idx] = sensorID;
try
{
pHygrometer = new CHygrometer();
}
catch(...)
{
hr = E_UNEXPECTED;
Trace(TRACE_LEVEL_ERROR, "Failed to create new hygrometer, hr = %!HRESULT!", hr);
if (nullptr != pHygrometer)
delete pHygrometer;
}
if (NULL != pHygrometer)
{
hr = pHygrometer->Initialize(
Hygrometer,
m_AvailableSensorsUsages[idx],
m_AvailableSensorsLinkCollections[idx],
idx,
pwszManufacturer,
pwszProduct,
pwszSerialNumber,
sensorID,
this);
}
else
{
hr = E_OUTOFMEMORY;
Trace(TRACE_LEVEL_ERROR, "Unable to create Hygrometer object, hr = %!HRESULT!", hr);
}
if(SUCCEEDED(hr))
{
pSensor = static_cast<CSensor*>(pHygrometer);
Trace(TRACE_LEVEL_INFORMATION, "Hygrometer sensor successfully created, Sensor ID = %ls, hr = %!HRESULT!", sensorID, hr);
}
}
break;
case Thermometer:
hr = StringCchPrintf(tempStr, HID_USB_DESCRIPTOR_MAX_LENGTH, L"#%s-%i", deviceID, idx);
if (SUCCEEDED(hr))
{
hr = StringCchCat(sensorID, HID_USB_DESCRIPTOR_MAX_LENGTH, tempStr);
}
if (SUCCEEDED(hr))
{
m_AvailableSensorsIDs[idx] = sensorID;
try
{
pThermometer = new CThermometer();
}
catch(...)
{
hr = E_UNEXPECTED;
Trace(TRACE_LEVEL_ERROR, "Failed to create new thermometer, hr = %!HRESULT!", hr);
if (nullptr != pThermometer)
delete pThermometer;
}
if (NULL != pThermometer)
{
hr = pThermometer->Initialize(
Thermometer,
m_AvailableSensorsUsages[idx],
m_AvailableSensorsLinkCollections[idx],
idx,
pwszManufacturer,
pwszProduct,
pwszSerialNumber,
sensorID,
this);
}
else
{
hr = E_OUTOFMEMORY;
Trace(TRACE_LEVEL_ERROR, "Unable to create Thermometer object, hr = %!HRESULT!", hr);
}
if(SUCCEEDED(hr))
{
pSensor = static_cast<CSensor*>(pThermometer);
Trace(TRACE_LEVEL_INFORMATION, "Thermometer sensor successfully created, Sensor ID = %ls, hr = %!HRESULT!", sensorID, hr);
}
}
break;
case Potentiometer:
hr = StringCchPrintf(tempStr, HID_USB_DESCRIPTOR_MAX_LENGTH, L"#%s-%i", deviceID, idx);
if (SUCCEEDED(hr))
{
hr = StringCchCat(sensorID, HID_USB_DESCRIPTOR_MAX_LENGTH, tempStr);
}
if (SUCCEEDED(hr))
{
m_AvailableSensorsIDs[idx] = sensorID;
try
{
pPotentiometer = new CPotentiometer();
}
catch(...)
{
hr = E_UNEXPECTED;
Trace(TRACE_LEVEL_ERROR, "Failed to create new potentiometer, hr = %!HRESULT!", hr);
if (nullptr != pPotentiometer)
delete pPotentiometer;
}
if (NULL != pPotentiometer)
{
hr = pPotentiometer->Initialize(
Potentiometer,
m_AvailableSensorsUsages[idx],
m_AvailableSensorsLinkCollections[idx],
idx,
pwszManufacturer,
pwszProduct,
pwszSerialNumber,
sensorID,
this);
}
else
{
hr = E_OUTOFMEMORY;
Trace(TRACE_LEVEL_ERROR, "Unable to create Potentiometer object, hr = %!HRESULT!", hr);
}
if(SUCCEEDED(hr))
{
pSensor = static_cast<CSensor*>(pPotentiometer);
Trace(TRACE_LEVEL_INFORMATION, "Potentiometer sensor successfully created, Sensor ID = %ls, hr = %!HRESULT!", sensorID, hr);
}
}
break;
case Distance:
hr = StringCchPrintf(tempStr, HID_USB_DESCRIPTOR_MAX_LENGTH, L"#%s-%i", deviceID, idx);
if (SUCCEEDED(hr))
{
hr = StringCchCat(sensorID, HID_USB_DESCRIPTOR_MAX_LENGTH, tempStr);
}
if (SUCCEEDED(hr))
{
m_AvailableSensorsIDs[idx] = sensorID;
try
{
pDistance = new CDistance();
}
catch(...)
{
hr = E_UNEXPECTED;
Trace(TRACE_LEVEL_ERROR, "Failed to create new distance, hr = %!HRESULT!", hr);
if (nullptr != pDistance)
delete pDistance;
}
if (NULL != pDistance)
{
hr = pDistance->Initialize(
Distance,
m_AvailableSensorsUsages[idx],
m_AvailableSensorsLinkCollections[idx],
idx,
pwszManufacturer,
pwszProduct,
pwszSerialNumber,
sensorID,
this);
}
else
{
hr = E_OUTOFMEMORY;
Trace(TRACE_LEVEL_ERROR, "Unable to create Distance object, hr = %!HRESULT!", hr);
}
if(SUCCEEDED(hr))
{
pSensor = static_cast<CSensor*>(pDistance);
Trace(TRACE_LEVEL_INFORMATION, "Distance sensor successfully created, Sensor ID = %ls, hr = %!HRESULT!", sensorID, hr);
}
}
break;
case Switch:
hr = StringCchPrintf(tempStr, HID_USB_DESCRIPTOR_MAX_LENGTH, L"#%s-%i", deviceID, idx);
if (SUCCEEDED(hr))
{
hr = StringCchCat(sensorID, HID_USB_DESCRIPTOR_MAX_LENGTH, tempStr);
}
if (SUCCEEDED(hr))
{
m_AvailableSensorsIDs[idx] = sensorID;
try
{
pSwitch = new CSwitch();
}
catch(...)
{
hr = E_UNEXPECTED;
Trace(TRACE_LEVEL_ERROR, "Failed to create new switch, hr = %!HRESULT!", hr);
if (nullptr != pSwitch)
delete pSwitch;
}
if (NULL != pSwitch)
{
hr = pSwitch->Initialize(
Switch,
m_AvailableSensorsUsages[idx],
m_AvailableSensorsLinkCollections[idx],
idx,
pwszManufacturer,
pwszProduct,
pwszSerialNumber,
sensorID,
this);
}
else
{
hr = E_OUTOFMEMORY;
Trace(TRACE_LEVEL_ERROR, "Unable to create Switch object, hr = %!HRESULT!", hr);
}
if(SUCCEEDED(hr))
{
pSensor = static_cast<CSensor*>(pSwitch);
Trace(TRACE_LEVEL_INFORMATION, "Switch sensor successfully created, Sensor ID = %ls, hr = %!HRESULT!", sensorID, hr);
}
}
break;
case Voltage:
hr = StringCchPrintf(tempStr, HID_USB_DESCRIPTOR_MAX_LENGTH, L"#%s-%i", deviceID, idx);
if (SUCCEEDED(hr))
{
hr = StringCchCat(sensorID, HID_USB_DESCRIPTOR_MAX_LENGTH, tempStr);
}
if (SUCCEEDED(hr))
{
m_AvailableSensorsIDs[idx] = sensorID;
try
{
pVoltage = new CVoltage();
}
catch(...)
{
hr = E_UNEXPECTED;
Trace(TRACE_LEVEL_ERROR, "Failed to create new voltage, hr = %!HRESULT!", hr);
if (nullptr != pVoltage)
delete pVoltage;
}
if (NULL != pVoltage)
{
hr = pVoltage->Initialize(
Voltage,
m_AvailableSensorsUsages[idx],
m_AvailableSensorsLinkCollections[idx],
idx,
pwszManufacturer,
pwszProduct,
pwszSerialNumber,
sensorID,
this);
}
else
{
hr = E_OUTOFMEMORY;
Trace(TRACE_LEVEL_ERROR, "Unable to create Voltage object, hr = %!HRESULT!", hr);
}
if(SUCCEEDED(hr))
{
pSensor = static_cast<CSensor*>(pVoltage);
Trace(TRACE_LEVEL_INFORMATION, "Voltage sensor successfully created, Sensor ID = %ls, hr = %!HRESULT!", sensorID, hr);
}
}
break;
case Current:
hr = StringCchPrintf(tempStr, HID_USB_DESCRIPTOR_MAX_LENGTH, L"#%s-%i", deviceID, idx);
if (SUCCEEDED(hr))
{
hr = StringCchCat(sensorID, HID_USB_DESCRIPTOR_MAX_LENGTH, tempStr);
}
if (SUCCEEDED(hr))
{
m_AvailableSensorsIDs[idx] = sensorID;
try
{
pCurrent = new CCurrent();
}
catch(...)
{
hr = E_UNEXPECTED;
Trace(TRACE_LEVEL_ERROR, "Failed to create new current, hr = %!HRESULT!", hr);
if (nullptr != pCurrent)
delete pCurrent;
}
if (NULL != pCurrent)
{
hr = pCurrent->Initialize(
Current,
m_AvailableSensorsUsages[idx],
m_AvailableSensorsLinkCollections[idx],
idx,
pwszManufacturer,
pwszProduct,
pwszSerialNumber,
sensorID,
this);
}
else
{
hr = E_OUTOFMEMORY;
Trace(TRACE_LEVEL_ERROR, "Unable to create Current object, hr = %!HRESULT!", hr);
}
if(SUCCEEDED(hr))
{
pSensor = static_cast<CSensor*>(pCurrent);
Trace(TRACE_LEVEL_INFORMATION, "Current sensor successfully created, Sensor ID = %ls, hr = %!HRESULT!", sensorID, hr);
}
}
break;
case Power:
hr = StringCchPrintf(tempStr, HID_USB_DESCRIPTOR_MAX_LENGTH, L"#%s-%i", deviceID, idx);
if (SUCCEEDED(hr))
{
hr = StringCchCat(sensorID, HID_USB_DESCRIPTOR_MAX_LENGTH, tempStr);
}
if (SUCCEEDED(hr))
{
m_AvailableSensorsIDs[idx] = sensorID;
try
{
pPower = new CPower();
}
catch(...)
{
hr = E_UNEXPECTED;
Trace(TRACE_LEVEL_ERROR, "Failed to create new power, hr = %!HRESULT!", hr);
if (nullptr != pPower)
delete pPower;
}
if (NULL != pPower)
{
hr = pPower->Initialize(
Power,
m_AvailableSensorsUsages[idx],
m_AvailableSensorsLinkCollections[idx],
idx,
pwszManufacturer,
pwszProduct,
pwszSerialNumber,
sensorID,
this);
}
else
{
hr = E_OUTOFMEMORY;
Trace(TRACE_LEVEL_ERROR, "Unable to create Power object, hr = %!HRESULT!", hr);
}
if(SUCCEEDED(hr))
{
pSensor = static_cast<CSensor*>(pPower);
Trace(TRACE_LEVEL_INFORMATION, "Power sensor successfully created, Sensor ID = %ls, hr = %!HRESULT!", sensorID, hr);
}
}
break;
case Frequency:
hr = StringCchPrintf(tempStr, HID_USB_DESCRIPTOR_MAX_LENGTH, L"#%s-%i", deviceID, idx);
if (SUCCEEDED(hr))
{
hr = StringCchCat(sensorID, HID_USB_DESCRIPTOR_MAX_LENGTH, tempStr);
}
if (SUCCEEDED(hr))
{
m_AvailableSensorsIDs[idx] = sensorID;
try
{
pFrequency = new CFrequency();
}
catch(...)
{
hr = E_UNEXPECTED;
Trace(TRACE_LEVEL_ERROR, "Failed to create new frequency, hr = %!HRESULT!", hr);
if (nullptr != pFrequency)
delete pFrequency;
}
if (NULL != pFrequency)
{
hr = pFrequency->Initialize(
Frequency,
m_AvailableSensorsUsages[idx],
m_AvailableSensorsLinkCollections[idx],
idx,
pwszManufacturer,
pwszProduct,
pwszSerialNumber,
sensorID,
this);
}
else
{
hr = E_OUTOFMEMORY;
Trace(TRACE_LEVEL_ERROR, "Unable to create Frequency object, hr = %!HRESULT!", hr);
}
if(SUCCEEDED(hr))
{
pSensor = static_cast<CSensor*>(pFrequency);
Trace(TRACE_LEVEL_INFORMATION, "Frequency sensor successfully created, Sensor ID = %ls, hr = %!HRESULT!", sensorID, hr);
}
}
break;
case Orientation:
hr = StringCchPrintf(tempStr, HID_USB_DESCRIPTOR_MAX_LENGTH, L"#%s-%i", deviceID, idx);
if (SUCCEEDED(hr))
{
hr = StringCchCat(sensorID, HID_USB_DESCRIPTOR_MAX_LENGTH, tempStr);
}
if (SUCCEEDED(hr))
{
m_AvailableSensorsIDs[idx] = sensorID;
try
{
pOrientation = new COrientation();
}
catch(...)
{
hr = E_UNEXPECTED;
Trace(TRACE_LEVEL_ERROR, "Failed to create new orientation, hr = %!HRESULT!", hr);
if (nullptr != pOrientation)
delete pOrientation;
}
if (NULL != pOrientation)
{
hr = pOrientation->Initialize(
Orientation,
m_AvailableSensorsUsages[idx],
m_AvailableSensorsLinkCollections[idx],
idx,
pwszManufacturer,
pwszProduct,
pwszSerialNumber,
sensorID,
this);
}
else
{
hr = E_OUTOFMEMORY;
Trace(TRACE_LEVEL_ERROR, "Unable to create Orientation object, hr = %!HRESULT!", hr);
}
if(SUCCEEDED(hr))
{
pSensor = static_cast<CSensor*>(pOrientation);
Trace(TRACE_LEVEL_INFORMATION, "Orientation sensor successfully created, Sensor ID = %ls, hr = %!HRESULT!", sensorID, hr);
}
}
break;
case Custom:
hr = StringCchPrintf(tempStr, HID_USB_DESCRIPTOR_MAX_LENGTH, L"#%s-%i", deviceID, idx);
if (SUCCEEDED(hr))
{
hr = StringCchCat(sensorID, HID_USB_DESCRIPTOR_MAX_LENGTH, tempStr);
}
if (SUCCEEDED(hr))
{
m_AvailableSensorsIDs[idx] = sensorID;
try
{
pCustom = new CCustom();
}
catch(...)
{
hr = E_UNEXPECTED;
Trace(TRACE_LEVEL_ERROR, "Failed to create new custom, hr = %!HRESULT!", hr);
if (nullptr != pCustom)
delete pCustom;
}
if (NULL != pCustom)
{
hr = pCustom->Initialize(
Custom,
m_AvailableSensorsUsages[idx],
m_AvailableSensorsLinkCollections[idx],
idx,
pwszManufacturer,
pwszProduct,
pwszSerialNumber,
sensorID,
this);
}
else
{
hr = E_OUTOFMEMORY;
Trace(TRACE_LEVEL_ERROR, "Unable to create custom sensor object, hr = %!HRESULT!", hr);
}
if(SUCCEEDED(hr))
{
pSensor = static_cast<CSensor*>(pCustom);
Trace(TRACE_LEVEL_INFORMATION, "Custom sensor successfully created, Sensor ID = %ls, hr = %!HRESULT!", sensorID, hr);
}
}
break;
case Generic:
hr = StringCchPrintf(tempStr, HID_USB_DESCRIPTOR_MAX_LENGTH, L"#%s-%i", deviceID, idx);
if (SUCCEEDED(hr))
{
hr = StringCchCat(sensorID, HID_USB_DESCRIPTOR_MAX_LENGTH, tempStr);
}
if (SUCCEEDED(hr))
{
m_AvailableSensorsIDs[idx] = sensorID;
try
{
pGeneric = new CGeneric();
}
catch(...)
{
hr = E_UNEXPECTED;
Trace(TRACE_LEVEL_ERROR, "Failed to create new generic, hr = %!HRESULT!", hr);
if (nullptr != pGeneric)
delete pGeneric;
}
if (NULL != pGeneric)
{
hr = pGeneric->Initialize(
Generic,
m_AvailableSensorsUsages[idx],
m_AvailableSensorsLinkCollections[idx],
idx,
pwszManufacturer,
pwszProduct,
pwszSerialNumber,
sensorID,
this);
}
else
{
hr = E_OUTOFMEMORY;
Trace(TRACE_LEVEL_ERROR, "Unable to create Generic sensor object, hr = %!HRESULT!", hr);
}
if(SUCCEEDED(hr))
{
pSensor = static_cast<CSensor*>(pGeneric);
Trace(TRACE_LEVEL_INFORMATION, "Generic sensor successfully created, Sensor ID = %ls, hr = %!HRESULT!", sensorID, hr);
}
}
break;
case Unsupported:
hr = StringCchPrintf(tempStr, HID_USB_DESCRIPTOR_MAX_LENGTH, L"#%s-%i", deviceID, idx);
if (SUCCEEDED(hr))
{
hr = StringCchCat(sensorID, HID_USB_DESCRIPTOR_MAX_LENGTH, tempStr);
}
if (SUCCEEDED(hr))
{
m_AvailableSensorsIDs[idx] = sensorID;
try
{
pUnsupported = new CUnsupported();
}
catch(...)
{
hr = E_UNEXPECTED;
Trace(TRACE_LEVEL_ERROR, "Failed to create new unsupported, hr = %!HRESULT!", hr);
if (nullptr != pUnsupported)
delete pUnsupported;
}
if (NULL != pUnsupported)
{
hr = pUnsupported->Initialize(
Unsupported,
m_AvailableSensorsUsages[idx],
m_AvailableSensorsLinkCollections[idx],
idx,
pwszManufacturer,
pwszProduct,
pwszSerialNumber,
sensorID,
this);
}
else
{
hr = E_OUTOFMEMORY;
Trace(TRACE_LEVEL_ERROR, "Unable to create Unsupported sensor object, hr = %!HRESULT!", hr);
}
if(SUCCEEDED(hr))
{
pSensor = static_cast<CSensor*>(pUnsupported);
Trace(TRACE_LEVEL_INFORMATION, "Unsupported sensor successfully created, Sensor ID = %ls, hr = %!HRESULT!", sensorID, hr);
}
}
break;
default:
hr = E_UNEXPECTED;
Trace(TRACE_LEVEL_ERROR, "Invalid sensor type = %i, hr = %!HRESULT!", m_AvailableSensorsTypes[idx], hr);
break;
}
}
}
}
// Set the unique persistent ID
if(SUCCEEDED(hr))
{
hr = pSensor->SetUniqueID(m_spWdfDevice);
}
if(SUCCEEDED(hr))
{
m_pSensorList.AddTail(pSensor);
pSensor->m_fReportingState = FALSE;
}
// Update the property values for each sensor
if (SUCCEEDED(hr))
{
hr = m_pSensorDDI->UpdateSensorPropertyValues(m_AvailableSensorsIDs[idx], FALSE);
}
} //end for idx
}
// Create and initialize the Sensor Class Extension
if(SUCCEEDED(hr))
{
hr = InitializeClassExtension();
}
if(SUCCEEDED(hr))
{
m_fInitializationComplete = TRUE;
Trace(TRACE_LEVEL_INFORMATION, "%!FUNC! Sensor Class Extension initialized");
}
}
}
else
{
Trace(TRACE_LEVEL_ERROR, "%!FUNC! Failed to get device info");
}
#pragma warning(suppress: 6001) //uninitialized memory
if (nullptr != tempStr)
{
delete[] tempStr;
}
#pragma warning(suppress: 6001) //uninitialized memory
if (nullptr != sensorID)
{
delete[] sensorID;
}
#pragma warning(suppress: 6001) //uninitialized memory
if (nullptr != deviceID)
{
delete[] deviceID;
}
#pragma warning(suppress: 6001) //uninitialized memory
if (nullptr != pwszManufacturer)
{
delete[] pwszManufacturer;
}
#pragma warning(suppress: 6001) //uninitialized memory
if (nullptr != pwszProduct)
{
delete[] pwszProduct;
}
#pragma warning(suppress: 6001) //uninitialized memory
if (nullptr != pwszSerialNumber)
{
delete[] pwszSerialNumber;
}
}
// Update each sensor state to SENSOR_STATE_NO_DATA
// Note: CSensorManager::_SensorEventThreadProc() will change sensor state to SENSOR_STATE_READY
// whenever a data field is ready.
if (SUCCEEDED(hr))
{
for(DWORD i = 0; i < m_pSensorList.GetCount(); i++)
{
CSensor *pSensor;
POSITION pos = NULL;
pos = m_pSensorList.FindIndex(i);
if (NULL != pos)
{
pSensor = m_pSensorList.GetAt(pos);
if(nullptr != pSensor)
{
SetState(pSensor, SENSOR_STATE_NO_DATA);
}
else
{
hr = E_UNEXPECTED;
}
}
else
{
hr = E_UNEXPECTED;
}
}
}
if (SUCCEEDED(hr))
{
// Step 1: Create the Data Changed Event Handle
m_hSensorEvent = ::CreateEvent( NULL, // No security attributes
FALSE, // Automatic-reset event object
FALSE, // Initial state is non-signaled
NULL ); // Unnamed object
POSITION pos = NULL;
CSensor* pSensor = nullptr;
for(DWORD i = 0; i < m_pSensorList.GetCount(); i++)
{
pos = m_pSensorList.FindIndex(i);
if (NULL != pos)
{
pSensor = m_pSensorList.GetAt(pos);
if (nullptr != pSensor)
{
pSensor->SetDataEventHandle(m_hSensorEvent);
}
else
{
hr = E_UNEXPECTED;
}
}
else
{
hr = E_UNEXPECTED;
}
}
// Step 2: Activate & Create and start the eventing thread
if (SUCCEEDED(hr))
{
Activate();
m_hSensorManagerEventingThread = ::CreateThread(NULL, // Cannot be inherited by child process
0, // Default stack size
&CSensorManager::_SensorEventThreadProc, // Thread proc
(LPVOID)this, // Thread proc argument
0, // Starting state = running
NULL);
if (nullptr == m_hSensorManagerEventingThread)
{
Trace(TRACE_LEVEL_ERROR, "%!FUNC! sensor event thread failed to create");
hr = HRESULT_FROM_WIN32(::GetLastError());
}
else
{
Trace(TRACE_LEVEL_INFORMATION, "%!FUNC! sensor event thread successfully created");
}
}// No thread identifier
if(SUCCEEDED(hr))
{
m_fSensorManagerInitialized = TRUE;
Trace(TRACE_LEVEL_INFORMATION, "%!FUNC! Sensor initialization completed successfully");
}
else
{
Trace(TRACE_LEVEL_INFORMATION, "%!FUNC! Sensor initialization failed");
}
}
return hr;
}
/////////////////////////////////////////////////////////////////////////////////
//
// CSensorManager::Stop
//
//
//
//
//////////////////////////////////////////////////////////////////////////////////
HRESULT CSensorManager::Stop()
{
Trace(TRACE_LEVEL_INFORMATION, "%!FUNC! Entry");
HRESULT hr = S_OK;
// Update each sensor state to SENSOR_STATE_NO_DATA
for(DWORD i = 0; i < m_pSensorList.GetCount(); i++)
{
CSensor *pSensor = nullptr;
CComBSTR objectId;
POSITION pos = NULL;
pos = m_pSensorList.FindIndex(i);
if (NULL != pos)
{
pSensor = m_pSensorList.GetAt(pos);
if(nullptr != pSensor)
{
SetState(pSensor, SENSOR_STATE_NO_DATA);
}
else
{
hr = E_UNEXPECTED;
}
}
else
{
hr = E_UNEXPECTED;
}
}
// DeInitialize the sensor device
if(NULL != m_pSensorDDI)
{
hr = m_pSensorDDI->DeInitSensorDevice();
}
// Step 1: Stop the eventing thread and Close the handle
if (NULL != m_hSensorManagerEventingThread)
{
// De-activate and close the thread
DeActivate();
WaitForSingleObject(m_hSensorManagerEventingThread, INFINITE);
CloseHandle(m_hSensorManagerEventingThread);
}
// Step 2: Close the Data Change Event handle
if (NULL != m_hSensorEvent)
{
CloseHandle(m_hSensorEvent);
}
Trace(TRACE_LEVEL_INFORMATION, "%!FUNC! Exit, hr = %!HRESULT!", hr);
return hr;
}
/////////////////////////////////////////////////////////////////////////////////
//
// CSensorManager::_SensorEventThreadProc
//
//
//
//
//////////////////////////////////////////////////////////////////////////////////
DWORD WINAPI CSensorManager::_SensorEventThreadProc(_In_ LPVOID pvData)
{
CSensorManager* pParent = (CSensorManager*)pvData;
if (NULL == pParent)
{
return 0;
}
// Cast the argument to the correct type.
CSensorManager* pThis = static_cast<CSensorManager*>(pvData);
HRESULT hr = CoInitializeEx(NULL, COINIT_MULTITHREADED);
if (FAILED(hr))
{
Trace(TRACE_LEVEL_ERROR, "Failed to call CoInitialize on _SensorEventThreadProc thread, hr = %!HRESULT!", hr);
return 0;
}
// Create the data event parameters collection if it doesn't exist
CComPtr<IPortableDeviceValues> spDataEventParams;
if (spDataEventParams == NULL)
{
hr = CoCreateInstance(CLSID_PortableDeviceValues,
NULL,
CLSCTX_INPROC_SERVER,
IID_PPV_ARGS(&spDataEventParams));
}
if (FAILED(hr))
{
Trace(TRACE_LEVEL_ERROR, "Failed to CoCreateInstance for Data Event Parameters, hr = %!HRESULT!", hr);
return 0;
}
// Create the shake event parameters collection if it doesn't exist
CComPtr<IPortableDeviceValues> spShakeEventParams;
if (spShakeEventParams == NULL)
{
hr = CoCreateInstance(CLSID_PortableDeviceValues,
NULL,
CLSCTX_INPROC_SERVER,
IID_PPV_ARGS(&spShakeEventParams));
}
if (FAILED(hr))
{
Trace(TRACE_LEVEL_ERROR, "Failed to CoCreateInstance for Shake Event Parameters, hr = %!HRESULT!", hr);
return 0;
}
else
{
while (pParent->IsActive() &&
(WAIT_OBJECT_0 == WaitForSingleObject(pParent->GetSensorEventHandle(), INFINITE)))
{
hr = pThis->EnterProcessing(PROCESSING_ISENSOREVENT);
// Loop through every sensor and post an event for each one if needed
if (S_OK == hr)
{
for (DWORD i = 0; i < pThis->m_pSensorList.GetCount(); i++)
{
CSensor *pSensor = nullptr;
CComBSTR objectId = NULL;
POSITION pos = NULL;
pos = pThis->m_pSensorList.FindIndex(i);
if (NULL != pos)
{
pSensor = pThis->m_pSensorList.GetAt(pos);
if (nullptr != pSensor)
{
// Check if this Sensor has valid data to post
if ( TRUE == pSensor->HasValidDataEvent() )
{
// Initialize the event parameters
spDataEventParams->Clear();
// Populate the event type
hr = spDataEventParams->SetGuidValue(SENSOR_EVENT_PARAMETER_EVENT_ID, SENSOR_EVENT_DATA_UPDATED);
if (SUCCEEDED(hr))
{
// Update sensor state to ready if needed
hr = pParent->SetState(pSensor, SENSOR_STATE_READY);
}
// Get the All the Data Field values
// Populate the event parameters
if (SUCCEEDED(hr))
{
hr = pSensor->GetAllDataFieldValues(spDataEventParams);
}
if ( SUCCEEDED(hr) )
{
objectId = pSensor->GetSensorObjectID();
pParent->PostDataEvent(objectId, spDataEventParams);
}
}
// Check if this is an accelerometer and if there was a shake event
SensorType sensType = pSensor->GetSensorType();
if (Accelerometer == sensType)
{
CAccelerometer* pAccelerometer = static_cast<CAccelerometer*>(pSensor);
if (S_OK == hr)
{
// Initialize the event parameters
spShakeEventParams->Clear();
// Populate the event type
hr = spShakeEventParams->SetGuidValue(SENSOR_EVENT_PARAMETER_EVENT_ID, SENSOR_EVENT_ACCELEROMETER_SHAKE);
}
if (SUCCEEDED(hr))
{
if ( TRUE == pAccelerometer->HasValidShakeEvent() )
{
// Update sensor state to ready if needed
hr = pParent->SetState(pSensor, SENSOR_STATE_READY);
// Get the All the Data Field values
// Populate the event parameters
if (SUCCEEDED(hr))
{
hr = pSensor->GetAllDataFieldValues(spShakeEventParams);
}
if ( SUCCEEDED(hr) )
{
objectId = pSensor->GetSensorObjectID();
if (NULL != objectId)
{
pParent->PostShakeEvent(objectId, spShakeEventParams);
}
else
{
hr = E_UNEXPECTED;
Trace(TRACE_LEVEL_ERROR, "Failed to get sensor objectID for %s, hr = %!HRESULT!", pSensor->m_SensorName, hr);
}
}
}
}
}
}
else
{
//failed to get pSensor
hr = E_UNEXPECTED;
Trace(TRACE_LEVEL_ERROR, "Failed to get pSensor from SensorList, hr = %!HRESULT!", hr);
}
}
else
{
hr = E_UNEXPECTED;
Trace(TRACE_LEVEL_ERROR, "Failed to get sensor index from SensorList, hr = %!HRESULT!", hr);
}
}
}
pThis->ExitProcessing(PROCESSING_ISENSOREVENT);
}
}
CoUninitialize();
return 0;
}
/////////////////////////////////////////////////////////////////////////////////
//
// CSensorManager::SetState
//
//
//
//
//////////////////////////////////////////////////////////////////////////////////
HRESULT CSensorManager::SetState(_In_ LPVOID pvData, _In_ SensorState newState)
{
HRESULT hr = S_OK;
CSensor* pSensor = static_cast<CSensor*>(pvData);
if (nullptr != pSensor)
{
CComBSTR objectId = NULL;
objectId = pSensor->GetSensorObjectID();
if (NULL != objectId)
{
SensorState currentState;
DWORD dwValue = 0;
PROPVARIANT var;
PropVariantInit(&var);
hr = pSensor->GetProperty(SENSOR_PROPERTY_STATE, &var);
if (SUCCEEDED(hr))
{
PropVariantToUInt32(var, &dwValue);
currentState = (SensorState)dwValue;
if ((currentState != newState) || (TRUE == pSensor->m_fSensorStateChanged))
{
PropVariantClear(&var);
InitPropVariantFromUInt32(newState, &var);
hr = pSensor->SetProperty(SENSOR_PROPERTY_STATE, &var, nullptr);
if (SUCCEEDED(hr) && (nullptr != m_spClassExtension))
{
hr = m_spClassExtension->PostStateChange(objectId, newState);
if (SUCCEEDED(hr))
{
switch(newState)
{
case SENSOR_STATE_READY:
Trace(TRACE_LEVEL_INFORMATION, "Setting %s state, State = READY", pSensor->m_SensorName);
if ((FALSE == pSensor->m_fSensorPropertiesPreviouslyUpdated) || (TRUE == pSensor->m_fSensorStateChanged))
{
m_pSensorDDI->UpdateSensorPropertyValues(pSensor->m_SensorID, FALSE);
Trace(TRACE_LEVEL_INFORMATION, "Updating %s property values because of state change -> READY", pSensor->m_SensorName);
}
break;
case SENSOR_STATE_NOT_AVAILABLE:
Trace(TRACE_LEVEL_INFORMATION, "Setting %s state, State = NOT_AVAILABLE", pSensor->m_SensorName);
break;
case SENSOR_STATE_NO_DATA:
Trace(TRACE_LEVEL_INFORMATION, "Setting %s state, State = NO_DATA", pSensor->m_SensorName);
break;
case SENSOR_STATE_INITIALIZING:
Trace(TRACE_LEVEL_INFORMATION, "Setting %s state, State = INITIALIZING", pSensor->m_SensorName);
break;
case SENSOR_STATE_ACCESS_DENIED:
Trace(TRACE_LEVEL_INFORMATION, "Setting %s state, State = ACCESS_DENIED", pSensor->m_SensorName);
break;
case SENSOR_STATE_ERROR:
Trace(TRACE_LEVEL_INFORMATION, "Setting %s state, State = ERROR", pSensor->m_SensorName);
break;
default:
Trace(TRACE_LEVEL_INFORMATION, "Setting %s state, State = UNKNOWN", pSensor->m_SensorName);
break;
}
if (SENSOR_STATE_READY != newState)
{
DWORD cDatafields = 0;
hr = pSensor->m_spSupportedSensorDataFields->GetCount(&cDatafields);
if (SUCCEEDED(hr))
{
PROPERTYKEY pkDfKey = {0};
PROPVARIANT value;
Trace(TRACE_LEVEL_INFORMATION, "Setting %s datafield values = VT_EMPTY", pSensor->m_SensorName);
for (DWORD dwIdx = 0; dwIdx < cDatafields; dwIdx++)
{
if (SUCCEEDED(hr))
{
hr = pSensor->m_spSupportedSensorDataFields->GetAt(dwIdx, &pkDfKey);
}
if (SUCCEEDED(hr))
{
PropVariantInit( &value );
value.vt = VT_EMPTY;
pSensor->m_spSensorDataFieldValues->SetValue(pkDfKey, &value);
PropVariantClear( &value );
}
}
}
pSensor->m_fSensorPropertiesPreviouslyUpdated = FALSE;
}
}
}
}
}
PropVariantClear(&var);
pSensor->m_fSensorStateChanged = FALSE;
}
else
{
hr = E_UNEXPECTED;
Trace(TRACE_LEVEL_ERROR, "Failed to get sensor ObjectID for %s, hr = %!HRESULT!", pSensor->m_SensorName, hr);
}
}
else
{
hr = E_UNEXPECTED;
Trace(TRACE_LEVEL_ERROR, "pSensor == nullptr, hr = %!HRESULT!", hr);
}
return hr;
}
/////////////////////////////////////////////////////////////////////////////////
//
// CSensorManager::PostDataEvent
//
//
//
//
//////////////////////////////////////////////////////////////////////////////////
HRESULT CSensorManager::PostDataEvent(_In_ LPWSTR objectId, IPortableDeviceValues *pValues)
{
HRESULT hr = S_OK;
CComPtr<IPortableDeviceValuesCollection> spEventCollection;
if(spEventCollection == NULL)
{
//*-- CoCreate a collection to store the sensor object identifiers.
hr = CoCreateInstance( CLSID_PortableDeviceValuesCollection,
NULL,
CLSCTX_INPROC_SERVER,
IID_PPV_ARGS(&spEventCollection));
}
if( SUCCEEDED(hr) )
{
hr = spEventCollection->Add( pValues );
if( SUCCEEDED(hr) && (m_spClassExtension != NULL) )
{
hr = m_spClassExtension->PostEvent( objectId, spEventCollection );
}
}
return hr;
}
/////////////////////////////////////////////////////////////////////////////////
//
// CSensorManager::PostShakeEvent
//
//
//
//
//////////////////////////////////////////////////////////////////////////////////
HRESULT CSensorManager::PostShakeEvent(_In_ LPWSTR objectId, IPortableDeviceValues *pValues)
{
Trace(TRACE_LEVEL_VERBOSE, "%!FUNC! Entry");
HRESULT hr = S_OK;
CComPtr<IPortableDeviceValuesCollection> spEventCollection;
if(spEventCollection == NULL)
{
//*-- CoCreate a collection to store the sensor object identifiers.
hr = CoCreateInstance( CLSID_PortableDeviceValuesCollection,
NULL,
CLSCTX_INPROC_SERVER,
IID_PPV_ARGS(&spEventCollection));
}
if( SUCCEEDED(hr) )
{
hr = spEventCollection->Add( pValues );
if( SUCCEEDED(hr) && (m_spClassExtension != NULL) )
{
hr = m_spClassExtension->PostEvent( objectId, spEventCollection );
}
}
return hr;
}
/////////////////////////////////////////////////////////////////////////
//
// CSensorManager::OnCleanupFile
//
// This method is called when the file handle to the device is closed
//
// Parameters:
// pWdfFile - pointer to a file object
//
/////////////////////////////////////////////////////////////////////////
void CSensorManager::CleanupFile(
_In_ IWDFFile* pWdfFile
)
{
if (NULL != m_spClassExtension)
{
m_spClassExtension->CleanupFile(pWdfFile);
}
return;
}
/////////////////////////////////////////////////////////////////////////
//
// CSensorManager::ProcessIoControl
//
// This method is called to process a Device IO Control
//
// Parameters:
// pRequest - [in] pointer to the request
//
/////////////////////////////////////////////////////////////////////////
HRESULT CSensorManager::ProcessIoControl(
_In_ IWDFIoRequest* pRequest
)
{
HRESULT hr = S_OK;
if (NULL != m_spClassExtension)
{
hr = m_spClassExtension->ProcessIoControl(pRequest);
}
return hr;
}
VOID CSensorManager::DeActivate()
{
CComCritSecLock<CComAutoCriticalSection> scopeLock(m_CriticalSection);
m_fThreadActive = FALSE;
SetEvent(m_hSensorEvent);
return;
}
VOID CSensorManager::Activate()
{
CComCritSecLock<CComAutoCriticalSection> scopeLock(m_CriticalSection);
m_fThreadActive = TRUE;
return;
}
/*
Trims spaces and non-printable characters from the start and end of the string
*/
HRESULT CSensorManager::StringTrim(_Inout_updates_(HID_USB_DESCRIPTOR_MAX_LENGTH) LPWSTR pwszString)
{
HRESULT hr = S_OK;
size_t length = 0;
hr = StringCchLength(pwszString, HID_USB_DESCRIPTOR_MAX_LENGTH, &length);
if (SUCCEEDED(hr))
{
ULONG idx = 0;
wchar_t* str = nullptr;
try
{
#pragma warning(suppress: 6014) //OACR does not recognize "delete[] original" below as deleting "str"
str = new wchar_t[length + 1];
}
catch(...)
{
hr = E_UNEXPECTED;
Trace(TRACE_LEVEL_ERROR, "Failed to allocate memory for string trim, hr = %!HRESULT!", hr);
if (nullptr != str)
{
delete[] str;
}
}
if (SUCCEEDED(hr) && (length > 0))
{
wchar_t* original = str;
SecureZeroMemory(str, (length + 1) * sizeof(wchar_t));
hr = StringCchCopy(str, length + 1, pwszString);
if (SUCCEEDED(hr))
{
wchar_t *end;
// Trim leading space
idx = 0;
while(iswspace(*str) && (idx < length))
{
str++;
idx++;
}
if( 0 == *str )
{
hr = StringCchCopy(pwszString, HID_USB_DESCRIPTOR_MAX_LENGTH, L"");
}
else
{
// Trim trailing space
end = str + wcslen(str) - 1;
while(end > str && iswspace(*end))
{
end--;
}
// Write new null terminator
*(end+1) = 0;
hr = StringCchCopy(pwszString, HID_USB_DESCRIPTOR_MAX_LENGTH, str);
}
delete[] original;
}
}
else
{
hr = E_OUTOFMEMORY;
Trace(TRACE_LEVEL_ERROR, "str == nullptr, hr = %!HRESULT!", hr);
}
}
return hr;
}
inline HRESULT CSensorManager::EnterProcessing(DWORD64 dwControlFlag)
{
return m_pDevice->EnterProcessing(dwControlFlag);
}
inline void CSensorManager::ExitProcessing(DWORD64 dwControlFlag)
{
m_pDevice->ExitProcessing(dwControlFlag);
}
| 44.791018 | 172 | 0.319829 | [
"object"
] |
149361938f2f3cc946b633f7b93e593d08f7845d | 2,785 | hpp | C++ | lg/solvers/htd-master/include/htd/PathDecompositionFactory.hpp | vuphan314/dpo | e24fe63fc3321c0cd6d2179c3300596b91082ab5 | [
"MIT"
] | 14 | 2020-01-31T23:02:39.000Z | 2021-12-26T06:00:13.000Z | lg/solvers/htd-master/include/htd/PathDecompositionFactory.hpp | vuphan314/dpo | e24fe63fc3321c0cd6d2179c3300596b91082ab5 | [
"MIT"
] | 3 | 2020-06-27T21:11:46.000Z | 2020-06-27T21:11:47.000Z | lg/solvers/htd-master/include/htd/PathDecompositionFactory.hpp | vuphan314/dpo | e24fe63fc3321c0cd6d2179c3300596b91082ab5 | [
"MIT"
] | 2 | 2020-08-08T03:04:30.000Z | 2021-05-21T04:56:02.000Z | /*
* File: PathDecompositionFactory.hpp
*
* Author: ABSEHER Michael (abseher@dbai.tuwien.ac.at)
*
* Copyright 2015-2017, Michael Abseher
* E-Mail: <abseher@dbai.tuwien.ac.at>
*
* This file is part of htd.
*
* htd is free software: you can redistribute it and/or modify it under
* the terms of the GNU General Public License as published by the Free
* Software Foundation, either version 3 of the License, or (at your
* option) any later version.
*
* htd 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 htd. If not, see <http://www.gnu.org/licenses/>.
*/
#ifndef HTD_HTD_PATHDECOMPOSITIONFACTORY_HPP
#define HTD_HTD_PATHDECOMPOSITIONFACTORY_HPP
#include <htd/Globals.hpp>
#include <htd/GraphTypeFactory.hpp>
#include <htd/IMutablePathDecomposition.hpp>
namespace htd
{
/**
* Factory class for the default implementation of the IMutablePathDecomposition interface.
*/
class PathDecompositionFactory : public htd::GraphTypeFactory<htd::IPathDecomposition, htd::IMutablePathDecomposition>
{
public:
using htd::GraphTypeFactory<htd::IPathDecomposition, htd::IMutablePathDecomposition>::createInstance;
/**
* Constructor for the factory class.
*
* @param[in] manager The management instance to which the new factory class belongs.
*/
HTD_API PathDecompositionFactory(const htd::LibraryInstance * const manager);
/**
* Copy constructor for the factory class.
*
* @param[in] original The original factory class which shall be copied.
*/
HTD_API PathDecompositionFactory(const PathDecompositionFactory & original) = delete;
/**
* Copy assignment operator for the factory class.
*
* @param[in] original The original factory class which shall be copied.
*/
HTD_API PathDecompositionFactory & operator=(const PathDecompositionFactory & original) = delete;
/**
* Destructor of the factory class.
*/
HTD_API virtual ~PathDecompositionFactory();
/**
* Create a new IMutablePathDecomposition object.
*
* @return A new IMutablePathDecomposition object.
*/
HTD_API htd::IMutablePathDecomposition * createInstance(void) const HTD_OVERRIDE;
};
}
#endif /* HTD_HTD_PATHDECOMPOSITIONFACTORY_HPP */
| 35.705128 | 122 | 0.656373 | [
"object"
] |
149b1804e1999831d8ca002ae9549e2883ba633d | 2,457 | cpp | C++ | tests/high-level-api/source/data_view.cpp | hhb584520/DML | 014eb9894e85334f03ec74435933c972f3d05b50 | [
"MIT"
] | null | null | null | tests/high-level-api/source/data_view.cpp | hhb584520/DML | 014eb9894e85334f03ec74435933c972f3d05b50 | [
"MIT"
] | null | null | null | tests/high-level-api/source/data_view.cpp | hhb584520/DML | 014eb9894e85334f03ec74435933c972f3d05b50 | [
"MIT"
] | 1 | 2022-03-28T07:52:21.000Z | 2022-03-28T07:52:21.000Z | /*******************************************************************************
* Copyright (C) 2021 Intel Corporation
*
* SPDX-License-Identifier: MIT
******************************************************************************/
#include "gtest/gtest.h"
#include <dml_test_utils/mem_move.hpp>
#include <dml/dml.hpp>
#include "own/path.hpp"
/**
* @brief Random struct for testing purposes.
*/
struct testing_struct
{
int a; /**< Some field 1 */
int b; /**< Some field 2 */
/**
* @brief Equality operation for testing purposes
*
* @param rhs Other structure instance
*
* @return Boolean result of comparison
*/
bool operator==(const testing_struct &rhs) const { return std::tie(a, b) == std::tie(rhs.a, rhs.b); }
/**
* @brief Non-Equality operation for testing purposes
*
* @param rhs Other structure instance
*
* @return Boolean result of comparison
*/
bool operator!=(const testing_struct &rhs) const { return !(rhs == *this); }
};
template <typename T>
class dmlhl_data_view: public ::testing::Test
{
};
using testing_types = ::testing::Types<char, int, float, testing_struct>;
TYPED_TEST_SUITE(dmlhl_data_view, testing_types);
TYPED_TEST(dmlhl_data_view, pointer_and_size)
{
constexpr auto length = 16u;
const auto src = std::vector<TypeParam>(length, TypeParam{1});
auto dst = std::vector<TypeParam>(length);
auto result = dml::execute<dml::software>(
dml::mem_move, dml::make_view(src.data(), src.size()), dml::make_view(dst.data(), dst.size()));
ASSERT_EQ(result.status, dml::status_code::ok);
ASSERT_EQ(src, dst);
}
TYPED_TEST(dmlhl_data_view, iterators)
{
constexpr auto length = 16u;
const auto src = std::vector<TypeParam>(length, TypeParam{1});
auto dst = std::vector<TypeParam>(length);
auto result = dml::execute<dml::software>(
dml::mem_move, dml::make_view(src.begin(), src.end()), dml::make_view(dst.begin(), dst.end()));
ASSERT_EQ(result.status, dml::status_code::ok);
ASSERT_EQ(src, dst);
}
TYPED_TEST(dmlhl_data_view, range)
{
constexpr auto length = 16u;
const auto src = std::vector<TypeParam>(length, TypeParam{1});
auto dst = std::vector<TypeParam>(length);
auto result = dml::execute<dml::software>(dml::mem_move, dml::make_view(src), dml::make_view(dst));
ASSERT_EQ(result.status, dml::status_code::ok);
ASSERT_EQ(src, dst);
}
| 26.419355 | 105 | 0.617013 | [
"vector"
] |
149b95a26c87265fd705d68be0def40804bb86b4 | 431 | cpp | C++ | atcoder/abc112/b.cpp | Lambda1/atcoder | a4a57ddc21cc29b8b795173630e1d07db4abb559 | [
"MIT"
] | null | null | null | atcoder/abc112/b.cpp | Lambda1/atcoder | a4a57ddc21cc29b8b795173630e1d07db4abb559 | [
"MIT"
] | null | null | null | atcoder/abc112/b.cpp | Lambda1/atcoder | a4a57ddc21cc29b8b795173630e1d07db4abb559 | [
"MIT"
] | null | null | null | #include <iostream>
#include <vector>
#include <string>
#include <algorithm>
#include <cmath>
int main(int argc,char *argv[])
{
int n,T;
std::cin >> n >> T;
std::vector<int> c(n),t(n);
for(int i = 0;i < n;i++) std::cin >> c[i] >> t[i];
int min = 0;
for(int i = 1;i < n;i++) if(c[i] < c[min] && t[i] <= T) min = i;
if(t[min] <= T)
std::cout << c[min] << std::endl;
else std::cout << "TLE" << std::endl;
return 0;
}
| 17.958333 | 65 | 0.526682 | [
"vector"
] |
149bfba7b24baa017dc684d6813a482830f9c195 | 5,281 | cc | C++ | src/util.cc | donaldmunro/PnPTrainer | f37c5048e9e33c77d8cefd8cf7030843b2389566 | [
"MIT"
] | 3 | 2019-07-23T08:20:44.000Z | 2021-06-24T15:46:37.000Z | src/util.cc | donaldmunro/PnPTrainer | f37c5048e9e33c77d8cefd8cf7030843b2389566 | [
"MIT"
] | null | null | null | src/util.cc | donaldmunro/PnPTrainer | f37c5048e9e33c77d8cefd8cf7030843b2389566 | [
"MIT"
] | 1 | 2020-07-03T12:33:44.000Z | 2020-07-03T12:33:44.000Z | #include <regex>
#ifdef USE_GLAD
#if !defined(GLAD_GLAPI_EXPORT)
#define GLAD_GLAPI_EXPORT
#endif
#include <glad/glad.h>
#endif
#ifdef USE_GLEW
#include <GL/glew.h>
#endif
#include <GL/gl.h>
#include <GL/glext.h>
#include <opencv2/imgproc.hpp>
std::string replace_ver(const char *pch, int ver)
//----------------------------------------------------------------
{
if (pch == nullptr)
return "";
std::string s(pch);
std::regex r(R"(\{\{ver\}\})");
std::stringstream ss;
ss << ver;
return std::regex_replace (s, r, ss.str());
}
void create_icosahedron(GLuint& positions, GLuint& indices)
//----------------------------------------------------------
{
const int Faces[] =
{
2, 1, 0,
3, 2, 0,
4, 3, 0,
5, 4, 0,
1, 5, 0,
11, 6, 7,
11, 7, 8,
11, 8, 9,
11, 9, 10,
11, 10, 6,
1, 2, 6,
2, 3, 7,
3, 4, 8,
4, 5, 9,
5, 1, 10,
2, 7, 6,
3, 8, 7,
4, 9, 8,
5, 10, 9,
1, 6, 10
};
const float Verts[] =
{
0.000f, 0.000f, 1.000f,
0.894f, 0.000f, 0.447f,
0.276f, 0.851f, 0.447f,
-0.724f, 0.526f, 0.447f,
-0.724f, -0.526f, 0.447f,
0.276f, -0.851f, 0.447f,
0.724f, 0.526f, -0.447f,
-0.276f, 0.851f, -0.447f,
-0.894f, 0.000f, -0.447f,
-0.276f, -0.851f, -0.447f,
0.724f, -0.526f, -0.447f,
0.000f, 0.000f, -1.000f
};
size_t IndexCount = sizeof(Faces) / sizeof(Faces[0]);
// Create the VBO for positions:
GLsizei stride = 3 * sizeof(float);
glGenBuffers(1, &positions);
glBindBuffer(GL_ARRAY_BUFFER, positions);
glBufferData(GL_ARRAY_BUFFER, sizeof(Verts), Verts, GL_STATIC_DRAW);
glBindBuffer(GL_ARRAY_BUFFER, 0);
glGenBuffers(1, &indices);
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, indices);
glBufferData(GL_ELEMENT_ARRAY_BUFFER, sizeof(Faces), Faces, GL_STATIC_DRAW);
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0);
}
bool checkerboard_texture(GLuint& textureName)
//---------------------------------------------
{
if (textureName == 0)
glGenTextures(1, &textureName);
glBindTexture(GL_TEXTURE_2D, textureName);
GLubyte pixels[4 * 3] =
{
255, 0, 0, // Red
0, 255, 0, // Green
0, 0, 255, // Blue
255, 255, 0 // Yellow
};
// Use tightly packed data
glPixelStorei(GL_UNPACK_ALIGNMENT, 1);
// Load the texture
glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, 2, 2, 0, GL_RGB, GL_UNSIGNED_BYTE, pixels);
// Set the filtering mode
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
glBindTexture(GL_TEXTURE_2D, 0);
return (glIsTexture(textureName));
}
std::string cvtype(cv::InputArray a)
//--------------------------------
{
int numImgTypes = 35; // 7 base types, with five channel options each (none or C1, ..., C4)
int enum_ints[] = {CV_8U, CV_8UC1, CV_8UC2, CV_8UC3, CV_8UC4,
CV_8S, CV_8SC1, CV_8SC2, CV_8SC3, CV_8SC4,
CV_16U, CV_16UC1, CV_16UC2, CV_16UC3, CV_16UC4,
CV_16S, CV_16SC1, CV_16SC2, CV_16SC3, CV_16SC4,
CV_32S, CV_32SC1, CV_32SC2, CV_32SC3, CV_32SC4,
CV_32F, CV_32FC1, CV_32FC2, CV_32FC3, CV_32FC4,
CV_64F, CV_64FC1, CV_64FC2, CV_64FC3, CV_64FC4};
std::string enum_strings[] = {"CV_8U", "CV_8UC1", "CV_8UC2", "CV_8UC3", "CV_8UC4",
"CV_8S", "CV_8SC1", "CV_8SC2", "CV_8SC3", "CV_8SC4",
"CV_16U", "CV_16UC1", "CV_16UC2", "CV_16UC3", "CV_16UC4",
"CV_16S", "CV_16SC1", "CV_16SC2", "CV_16SC3", "CV_16SC4",
"CV_32S", "CV_32SC1", "CV_32SC2", "CV_32SC3", "CV_32SC4",
"CV_32F", "CV_32FC1", "CV_32FC2", "CV_32FC3", "CV_32FC4",
"CV_64F", "CV_64FC1", "CV_64FC2", "CV_64FC3", "CV_64FC4"};
int typ = a.type();
for(int i=0; i<numImgTypes; i++)
if (typ == enum_ints[i]) return enum_strings[i];
return "unknown image type";
}
void plot_circles(const cv::Mat& img, double x, double y, int startRadius, int radiusInc,const std::vector<cv::Scalar>& colors)
//----------------------------------------------------------------------------------------------------------------
{
for (cv::Scalar color : colors)
{
cv::circle(img, cv::Point2i(cvRound(x), cvRound(y)), startRadius, color, 1);
startRadius += radiusInc;
}
}
void plot_rectangles(cv::Mat& img, double x, double y, int width, int height, int increment,
const std::vector<cv::Scalar>& colors)
//----------------------------------------------------------------------------------------------------------------
{
for (cv::Scalar color : colors)
{
cv::Point2d pt1(x, y);
cv::Point2d pt2(x + width, y + height);
cv::rectangle(img, pt1, pt2, color);
width += increment; height += increment;
}
}
| 32.398773 | 127 | 0.503692 | [
"vector"
] |
149f7d181f8e7bd2904442b4b5e557de5ae3b10a | 5,788 | cpp | C++ | shell/lib/cobjsafe.cpp | npocmaka/Windows-Server-2003 | 5c6fe3db626b63a384230a1aa6b92ac416b0765f | [
"Unlicense"
] | 17 | 2020-11-13T13:42:52.000Z | 2021-09-16T09:13:13.000Z | shell/lib/cobjsafe.cpp | sancho1952007/Windows-Server-2003 | 5c6fe3db626b63a384230a1aa6b92ac416b0765f | [
"Unlicense"
] | 2 | 2020-10-19T08:02:06.000Z | 2020-10-19T08:23:18.000Z | shell/lib/cobjsafe.cpp | sancho1952007/Windows-Server-2003 | 5c6fe3db626b63a384230a1aa6b92ac416b0765f | [
"Unlicense"
] | 14 | 2020-11-14T09:43:20.000Z | 2021-08-28T08:59:57.000Z | #include "stock.h"
#pragma hdrstop
#include <comcat.h>
#include <hliface.h>
#include <mshtml.h>
#include <objsafe.h>
#include <perhist.h>
#include "cobjsafe.h"
// a default isafetyobject that we generally would use... marks
// deals with IDispatch
HRESULT CObjectSafety::GetInterfaceSafetyOptions(REFIID riid, DWORD *pdwSupportedOptions, DWORD *pdwEnabledOptions)
{
if (IsEqualIID(riid, IID_IDispatch))
{
if (pdwSupportedOptions)
*pdwSupportedOptions = (INTERFACESAFE_FOR_UNTRUSTED_CALLER | INTERFACESAFE_FOR_UNTRUSTED_DATA);
*pdwEnabledOptions = _dwSafetyOptions;
}
else
{
::DefaultGetSafetyOptions(riid, pdwSupportedOptions, pdwEnabledOptions);
}
return S_OK;
}
HRESULT CObjectSafety::SetInterfaceSafetyOptions(REFIID riid, DWORD dwOptionSetMask, DWORD dwEnabledOptions)
{
if (dwOptionSetMask & ~(INTERFACESAFE_FOR_UNTRUSTED_CALLER |
INTERFACESAFE_FOR_UNTRUSTED_DATA))
{
return E_INVALIDARG;
}
if (IsEqualIID(riid, IID_IDispatch))
{
_dwSafetyOptions = (_dwSafetyOptions & ~dwOptionSetMask) |
(dwEnabledOptions & dwOptionSetMask);
return S_OK;
}
else
{
return ::DefaultSetSafetyOptions(riid, dwOptionSetMask, dwEnabledOptions);
}
}
// *** IObjectSafety
//
// A couple static functions called by sitemap (and webbrowser).
// These are static so anyone else in this dll who has an OC
// that's always safe can just call them.
//
// These functions say we are safe for these three interfaces we implement
// IID_IDispatch
// IID_IPersistStream
// IID_IPersistPropertyBag
//
// The WebBrowser OC handles IDispatch differently.
//
HRESULT DefaultGetSafetyOptions(REFIID riid, DWORD *pdwSupportedOptions, DWORD *pdwEnabledOptions)
{
*pdwSupportedOptions = 0;
*pdwEnabledOptions = 0;
if (IsEqualIID(riid, IID_IDispatch) ||
IsEqualIID(riid, IID_IPersistStream) ||
IsEqualIID(riid, IID_IPersistStreamInit) ||
IsEqualIID(riid, IID_IPersistPropertyBag) ||
IsEqualIID(riid, IID_IPersistHistory))
{
*pdwSupportedOptions = INTERFACESAFE_FOR_UNTRUSTED_CALLER | INTERFACESAFE_FOR_UNTRUSTED_DATA;
*pdwEnabledOptions = INTERFACESAFE_FOR_UNTRUSTED_CALLER | INTERFACESAFE_FOR_UNTRUSTED_DATA;
}
return S_OK;
}
HRESULT DefaultSetSafetyOptions(REFIID riid, DWORD dwOptionSetMask, DWORD dwEnabledOptions)
{
if (dwOptionSetMask & ~(INTERFACESAFE_FOR_UNTRUSTED_CALLER |
INTERFACESAFE_FOR_UNTRUSTED_DATA))
{
return E_INVALIDARG;
}
if (IsEqualIID(riid, IID_IDispatch) ||
IsEqualIID(riid, IID_IPersistStream) ||
IsEqualIID(riid, IID_IPersistStreamInit) ||
IsEqualIID(riid, IID_IPersistHistory) ||
IsEqualIID(riid, IID_IPersistPropertyBag))
{
return S_OK;
}
return E_FAIL;
}
// When CWebBrowserOC is in the safe for scripting mode, we can't give out
// anyone else's IDispatch that is not also safe for scripting.
// This function encapsulates the basic functionality needed by both
// MakeSafeScripting and MakeSafeForInitializing (which we don't use)
BOOL MakeSafeFor(
IUnknown *punk, // object to test for safety
REFCATID catid, // category of safety
REFIID riid, // interface on which safety is desired
DWORD dwXSetMask, // options to set
DWORD dwXOptions // options to make safe for
// (either INTERFACESAFE_FOR_UNTRUSTED_CALLER or
// INTERFACESAFE_FOR_UNTRUSTED_DATA)
)
{
HRESULT hres;
// first try IObjectSafety
IObjectSafety *posafe;
if (SUCCEEDED(punk->QueryInterface(IID_IObjectSafety, (LPVOID*) &posafe)))
{
hres = posafe->SetInterfaceSafetyOptions(riid, dwXSetMask, dwXOptions);
posafe->Release();
if (SUCCEEDED(hres))
return TRUE;
}
// check the registry for "safe for scripting" component category
// we need the classid -- get it thru IPersist
CLSID clsid;
IPersist *ppersist;
hres = punk->QueryInterface(IID_IPersist, (LPVOID*) &ppersist);
if (SUCCEEDED(hres))
{
hres = ppersist->GetClassID(&clsid);
ppersist->Release();
}
if (FAILED(hres))
{
// trace from shdocvw, was TF_SHDCONTROL
TraceMsg(TF_WARNING, "MakeSafeForScripting - object doesn't have IPersist!");
return FALSE;
}
// Create the category manager
ICatInformation *pcatinfo;
hres = CoCreateInstance(CLSID_StdComponentCategoriesMgr,
NULL, CLSCTX_INPROC_SERVER,
IID_ICatInformation, (LPVOID*) &pcatinfo);
if (FAILED(hres))
return FALSE;
// Ask if the object belongs to the specified category
CATID rgcatid[1];
rgcatid[0] = catid;
hres = pcatinfo->IsClassOfCategories(clsid, 1, rgcatid, 0, NULL);
pcatinfo->Release();
return (hres==S_OK) ? TRUE : FALSE;;
}
HRESULT MakeSafeForScripting(IUnknown** ppDisp)
{
HRESULT hres = S_OK;
if (!MakeSafeFor(*ppDisp, CATID_SafeForScripting, IID_IDispatch,
INTERFACESAFE_FOR_UNTRUSTED_CALLER,
INTERFACESAFE_FOR_UNTRUSTED_CALLER))
{
// trace from shdocvw, was TF_SHDCONTROL
TraceMsg(TF_WARNING, "MakeSafeForScripting - IDispatch not safe");
(*ppDisp)->Release();
*ppDisp = NULL;
hres = E_FAIL;
}
return hres;
}
| 30.624339 | 116 | 0.638908 | [
"object"
] |
14a19df50419c222291a86218f449658968b8434 | 23,943 | cpp | C++ | soplex/src/soplex/spxdevexpr.cpp | avrech/scipoptsuite-6.0.2-avrech | bb4ef31b6e84ff7e1e65cee982acf150739cda86 | [
"MIT"
] | null | null | null | soplex/src/soplex/spxdevexpr.cpp | avrech/scipoptsuite-6.0.2-avrech | bb4ef31b6e84ff7e1e65cee982acf150739cda86 | [
"MIT"
] | null | null | null | soplex/src/soplex/spxdevexpr.cpp | avrech/scipoptsuite-6.0.2-avrech | bb4ef31b6e84ff7e1e65cee982acf150739cda86 | [
"MIT"
] | 1 | 2022-01-19T01:15:11.000Z | 2022-01-19T01:15:11.000Z | /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
/* */
/* This file is part of the class library */
/* SoPlex --- the Sequential object-oriented simPlex. */
/* */
/* Copyright (C) 1996-2019 Konrad-Zuse-Zentrum */
/* fuer Informationstechnik Berlin */
/* */
/* SoPlex is distributed under the terms of the ZIB Academic Licence. */
/* */
/* You should have received a copy of the ZIB Academic License */
/* along with SoPlex; see the file COPYING. If not email to soplex@zib.de. */
/* */
/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
#include "soplex/spxdefines.h"
#include "soplex/spxdevexpr.h"
#define DEVEX_REFINETOL 2.0
namespace soplex
{
void SPxDevexPR::load(SPxSolver* base)
{
thesolver = base;
setRep(base->rep());
assert(isConsistent());
}
bool SPxDevexPR::isConsistent() const
{
#ifdef ENABLE_CONSISTENCY_CHECKS
if(thesolver != 0)
if(weights.dim() != thesolver->coDim()
|| coWeights.dim() != thesolver->dim())
return MSGinconsistent("SPxDevexPR");
#endif
return true;
}
void SPxDevexPR::setupWeights(SPxSolver::Type tp)
{
int i;
int coWeightSize = 0;
int weightSize = 0;
DVector& weights = thesolver->weights;
DVector& coWeights = thesolver->coWeights;
if(tp == SPxSolver::ENTER)
{
coWeights.reDim(thesolver->dim(), false);
for(i = thesolver->dim() - 1; i >= coWeightSize; --i)
coWeights[i] = 2.0;
weights.reDim(thesolver->coDim(), false);
for(i = thesolver->coDim() - 1; i >= weightSize; --i)
weights[i] = 2.0;
}
else
{
coWeights.reDim(thesolver->dim(), false);
for(i = thesolver->dim() - 1; i >= coWeightSize; --i)
coWeights[i] = 1.0;
}
thesolver->weightsAreSetup = true;
}
void SPxDevexPR::setType(SPxSolver::Type tp)
{
setupWeights(tp);
refined = false;
bestPrices.clear();
bestPrices.setMax(thesolver->dim());
prices.reMax(thesolver->dim());
if(tp == SPxSolver::ENTER)
{
bestPricesCo.clear();
bestPricesCo.setMax(thesolver->coDim());
pricesCo.reMax(thesolver->coDim());
}
assert(isConsistent());
}
/**@todo suspicious: Shouldn't the relation between dim, coDim, Vecs,
* and CoVecs be influenced by the representation ?
*/
void SPxDevexPR::setRep(SPxSolver::Representation)
{
if(thesolver != 0)
{
// resize weights and initialize new entries
addedVecs(thesolver->coDim());
addedCoVecs(thesolver->dim());
assert(isConsistent());
}
}
Real inline computePrice(Real viol, Real weight, Real tol)
{
if(weight < tol)
return viol * viol / tol;
else
return viol * viol / weight;
}
int SPxDevexPR::buildBestPriceVectorLeave(Real feastol)
{
int idx;
int nsorted;
Real fTesti;
const Real* fTest = thesolver->fTest().get_const_ptr();
const Real* cpen = thesolver->coWeights.get_const_ptr();
IdxElement price;
prices.clear();
bestPrices.clear();
// TODO we should check infeasiblities for duplicates or loop over dimension
// bestPrices may then also contain duplicates!
// construct vector of all prices
for(int i = thesolver->infeasibilities.size() - 1; i >= 0; --i)
{
idx = thesolver->infeasibilities.index(i);
fTesti = fTest[idx];
if(fTesti < -feastol)
{
thesolver->isInfeasible[idx] = VIOLATED;
price.idx = idx;
price.val = computePrice(fTesti, cpen[idx], feastol);
prices.append(price);
}
}
// set up structures for the quicksort implementation
compare.elements = prices.get_const_ptr();
// do a partial sort to move the best ones to the front
// TODO this can be done more efficiently, since we only need the indices
nsorted = SPxQuicksortPart(prices.get_ptr(), compare, 0, prices.size(), HYPERPRICINGSIZE);
// copy indices of best values to bestPrices
for(int i = 0; i < nsorted; ++i)
{
bestPrices.addIdx(prices[i].idx);
thesolver->isInfeasible[prices[i].idx] = VIOLATED_AND_CHECKED;
}
if(nsorted > 0)
return prices[0].idx;
else
return -1;
}
int SPxDevexPR::selectLeave()
{
int retid;
if(thesolver->hyperPricingLeave && thesolver->sparsePricingLeave)
{
if(bestPrices.size() < 2 || thesolver->basis().lastUpdate() == 0)
{
// call init method to build up price-vector and return index of largest price
retid = buildBestPriceVectorLeave(theeps);
}
else
retid = selectLeaveHyper(theeps);
}
else if(thesolver->sparsePricingLeave)
retid = selectLeaveSparse(theeps);
else
retid = selectLeaveX(theeps);
if(retid < 0 && !refined)
{
refined = true;
MSG_INFO3((*thesolver->spxout), (*thesolver->spxout) << "WDEVEX02 trying refinement step..\n";)
retid = selectLeaveX(theeps / DEVEX_REFINETOL);
}
assert(retid < thesolver->dim());
return retid;
}
int SPxDevexPR::selectLeaveX(Real feastol, int start, int incr)
{
Real x;
const Real* fTest = thesolver->fTest().get_const_ptr();
const Real* cpen = thesolver->coWeights.get_const_ptr();
Real best = 0;
int bstI = -1;
int end = thesolver->coWeights.dim();
for(; start < end; start += incr)
{
if(fTest[start] < -feastol)
{
x = computePrice(fTest[start], cpen[start], feastol);
if(x > best)
{
best = x;
bstI = start;
last = cpen[start];
}
}
}
return bstI;
}
int SPxDevexPR::selectLeaveSparse(Real feastol)
{
Real x;
const Real* fTest = thesolver->fTest().get_const_ptr();
const Real* cpen = thesolver->coWeights.get_const_ptr();
Real best = 0;
int bstI = -1;
int idx = -1;
for(int i = thesolver->infeasibilities.size() - 1; i >= 0; --i)
{
idx = thesolver->infeasibilities.index(i);
x = fTest[idx];
if(x < -feastol)
{
x = computePrice(x, cpen[idx], feastol);
if(x > best)
{
best = x;
bstI = idx;
last = cpen[idx];
}
}
else
{
thesolver->infeasibilities.remove(i);
assert(thesolver->isInfeasible[idx] == VIOLATED
|| thesolver->isInfeasible[idx] == VIOLATED_AND_CHECKED);
thesolver->isInfeasible[idx] = NOT_VIOLATED;
}
}
return bstI;
}
int SPxDevexPR::selectLeaveHyper(Real feastol)
{
Real x;
const Real* fTest = thesolver->fTest().get_const_ptr();
const Real* cpen = thesolver->coWeights.get_const_ptr();
Real best = 0;
Real leastBest = infinity;
int bstI = -1;
int idx = -1;
// find the best price from the short candidate list
for(int i = bestPrices.size() - 1; i >= 0; --i)
{
idx = bestPrices.index(i);
x = fTest[idx];
if(x < -feastol)
{
x = computePrice(x, cpen[idx], feastol);
if(x > best)
{
best = x;
bstI = idx;
last = cpen[idx];
}
// get the smallest price of candidate list
if(x < leastBest)
leastBest = x;
}
else
{
bestPrices.remove(i);
thesolver->isInfeasible[idx] = NOT_VIOLATED;
}
}
// make sure we do not skip potential candidates due to a high leastBest value
if(leastBest == infinity)
{
assert(bestPrices.size() == 0);
leastBest = 0;
}
// scan the updated indices for a better price
for(int i = thesolver->updateViols.size() - 1; i >= 0; --i)
{
idx = thesolver->updateViols.index(i);
// only look at indeces that were not checked already
if(thesolver->isInfeasible[idx] == VIOLATED)
{
x = fTest[idx];
assert(x < -feastol);
x = computePrice(x, cpen[idx], feastol);
if(x > leastBest)
{
if(x > best)
{
best = x;
bstI = idx;
last = cpen[idx];
}
// put index into candidate list
thesolver->isInfeasible[idx] = VIOLATED_AND_CHECKED;
bestPrices.addIdx(idx);
}
}
}
return bstI;
}
void SPxDevexPR::left4(int n, SPxId id)
{
DVector& coWeights = thesolver->coWeights;
if(id.isValid())
{
int i, j;
Real x;
const Real* rhoVec = thesolver->fVec().delta().values();
Real rhov_1 = 1 / rhoVec[n];
Real beta_q = thesolver->coPvec().delta().length2() * rhov_1 * rhov_1;
#ifndef NDEBUG
if(spxAbs(rhoVec[n]) < theeps)
{
MSG_INFO3((*thesolver->spxout), (*thesolver->spxout) << "WDEVEX01: rhoVec = "
<< rhoVec[n] << " with smaller absolute value than theeps = " << theeps << std::endl;)
}
#endif // NDEBUG
// Update #coPenalty# vector
const IdxSet& rhoIdx = thesolver->fVec().idx();
int len = thesolver->fVec().idx().size();
for(i = len - 1; i >= 0; --i)
{
j = rhoIdx.index(i);
x = rhoVec[j] * rhoVec[j] * beta_q;
// if(x > coPenalty[j])
coWeights[j] += x;
}
coWeights[n] = beta_q;
}
}
SPxId SPxDevexPR::buildBestPriceVectorEnterDim(Real& best, Real feastol)
{
int idx;
int nsorted;
Real x;
const Real* coTest = thesolver->coTest().get_const_ptr();
const Real* cpen = thesolver->coWeights.get_const_ptr();
IdxElement price;
prices.clear();
bestPrices.clear();
// construct vector of all prices
for(int i = thesolver->infeasibilities.size() - 1; i >= 0; --i)
{
idx = thesolver->infeasibilities.index(i);
x = coTest[idx];
if(x < -feastol)
{
thesolver->isInfeasible[idx] = VIOLATED;
price.idx = idx;
price.val = computePrice(x, cpen[idx], feastol);
prices.append(price);
}
else
{
thesolver->infeasibilities.remove(i);
thesolver->isInfeasible[idx] = NOT_VIOLATED;
}
}
// set up structures for the quicksort implementation
compare.elements = prices.get_const_ptr();
// do a partial sort to move the best ones to the front
// TODO this can be done more efficiently, since we only need the indices
nsorted = SPxQuicksortPart(prices.get_ptr(), compare, 0, prices.size(), HYPERPRICINGSIZE);
// copy indices of best values to bestPrices
for(int i = 0; i < nsorted; ++i)
{
bestPrices.addIdx(prices[i].idx);
thesolver->isInfeasible[prices[i].idx] = VIOLATED_AND_CHECKED;
}
if(nsorted > 0)
{
best = prices[0].val;
return thesolver->coId(prices[0].idx);
}
else
return SPxId();
}
SPxId SPxDevexPR::buildBestPriceVectorEnterCoDim(Real& best, Real feastol)
{
int idx;
int nsorted;
Real x;
const Real* test = thesolver->test().get_const_ptr();
const Real* pen = thesolver->weights.get_const_ptr();
IdxElement price;
pricesCo.clear();
bestPricesCo.clear();
// construct vector of all prices
for(int i = thesolver->infeasibilitiesCo.size() - 1; i >= 0; --i)
{
idx = thesolver->infeasibilitiesCo.index(i);
x = test[idx];
if(x < -feastol)
{
thesolver->isInfeasibleCo[idx] = VIOLATED;
price.idx = idx;
price.val = computePrice(x, pen[idx], feastol);
pricesCo.append(price);
}
else
{
thesolver->infeasibilitiesCo.remove(i);
thesolver->isInfeasibleCo[idx] = NOT_VIOLATED;
}
}
// set up structures for the quicksort implementation
compare.elements = pricesCo.get_const_ptr();
// do a partial sort to move the best ones to the front
// TODO this can be done more efficiently, since we only need the indices
nsorted = SPxQuicksortPart(pricesCo.get_ptr(), compare, 0, pricesCo.size(), HYPERPRICINGSIZE);
// copy indices of best values to bestPrices
for(int i = 0; i < nsorted; ++i)
{
bestPricesCo.addIdx(pricesCo[i].idx);
thesolver->isInfeasibleCo[pricesCo[i].idx] = VIOLATED_AND_CHECKED;
}
if(nsorted > 0)
{
best = pricesCo[0].val;
return thesolver->id(pricesCo[0].idx);
}
else
return SPxId();
}
SPxId SPxDevexPR::selectEnter()
{
assert(thesolver != 0);
SPxId enterId;
enterId = selectEnterX(theeps);
if(!enterId.isValid() && !refined)
{
refined = true;
MSG_INFO3((*thesolver->spxout), (*thesolver->spxout) << "WDEVEX02 trying refinement step..\n";)
enterId = selectEnterX(theeps / DEVEX_REFINETOL);
}
return enterId;
}
// choose the best entering index among columns and rows but prefer sparsity
SPxId SPxDevexPR::selectEnterX(Real tol)
{
SPxId enterId;
SPxId enterCoId;
Real best;
Real bestCo;
best = 0;
bestCo = 0;
last = 1.0;
// avoid uninitialized value later on in entered4X()
last = 1.0;
if(thesolver->hyperPricingEnter && !refined)
{
if(bestPrices.size() < 2 || thesolver->basis().lastUpdate() == 0)
enterCoId = (thesolver->sparsePricingEnter) ? buildBestPriceVectorEnterDim(best,
tol) : selectEnterDenseDim(best, tol);
else
enterCoId = (thesolver->sparsePricingEnter) ? selectEnterHyperDim(best,
tol) : selectEnterDenseDim(best, tol);
if(bestPricesCo.size() < 2 || thesolver->basis().lastUpdate() == 0)
enterId = (thesolver->sparsePricingEnterCo) ? buildBestPriceVectorEnterCoDim(bestCo,
tol) : selectEnterDenseCoDim(bestCo, tol);
else
enterId = (thesolver->sparsePricingEnterCo) ? selectEnterHyperCoDim(bestCo,
tol) : selectEnterDenseCoDim(bestCo, tol);
}
else
{
enterCoId = (thesolver->sparsePricingEnter
&& !refined) ? selectEnterSparseDim(best, tol) : selectEnterDenseDim(best, tol);
enterId = (thesolver->sparsePricingEnterCo
&& !refined) ? selectEnterSparseCoDim(bestCo, tol) : selectEnterDenseCoDim(bestCo, tol);
}
// prefer coIds to increase the number of unit vectors in the basis matrix, i.e., rows in colrep and cols in rowrep
if(enterCoId.isValid() && (best > SPARSITY_TRADEOFF * bestCo || !enterId.isValid()))
return enterCoId;
else
return enterId;
}
SPxId SPxDevexPR::selectEnterHyperDim(Real& best, Real feastol)
{
const Real* cTest = thesolver->coTest().get_const_ptr();
const Real* cpen = thesolver->coWeights.get_const_ptr();
Real leastBest = infinity;
Real x;
int enterIdx = -1;
int idx;
// find the best price from short candidate list
for(int i = bestPrices.size() - 1; i >= 0; --i)
{
idx = bestPrices.index(i);
x = cTest[idx];
if(x < -feastol)
{
x = computePrice(x, cpen[idx], feastol);
if(x > best)
{
best = x;
enterIdx = idx;
last = cpen[idx];
}
if(x < leastBest)
leastBest = x;
}
else
{
bestPrices.remove(i);
thesolver->isInfeasible[idx] = NOT_VIOLATED;
}
}
// make sure we do not skip potential candidates due to a high leastBest value
if(leastBest == infinity)
{
assert(bestPrices.size() == 0);
leastBest = 0;
}
// scan the updated indeces for a better price
for(int i = thesolver->updateViols.size() - 1; i >= 0; --i)
{
idx = thesolver->updateViols.index(i);
// only look at indeces that were not checked already
if(thesolver->isInfeasible[idx] == VIOLATED)
{
x = cTest[idx];
if(x < -feastol)
{
x = computePrice(x, cpen[idx], feastol);
if(x > leastBest)
{
if(x > best)
{
best = x;
enterIdx = idx;
last = cpen[idx];
}
// put index into candidate list
thesolver->isInfeasible[idx] = VIOLATED_AND_CHECKED;
bestPrices.addIdx(idx);
}
}
else
{
thesolver->isInfeasible[idx] = NOT_VIOLATED;
}
}
}
if(enterIdx >= 0)
return thesolver->coId(enterIdx);
else
return SPxId();
}
SPxId SPxDevexPR::selectEnterHyperCoDim(Real& best, Real feastol)
{
const Real* test = thesolver->test().get_const_ptr();
const Real* pen = thesolver->weights.get_const_ptr();
Real leastBest = infinity;
Real x;
int enterIdx = -1;
int idx;
// find the best price from short candidate list
for(int i = bestPricesCo.size() - 1; i >= 0; --i)
{
idx = bestPricesCo.index(i);
x = test[idx];
if(x < -feastol)
{
x = computePrice(x, pen[idx], feastol);
if(x > best)
{
best = x;
enterIdx = idx;
last = pen[idx];
}
if(x < leastBest)
leastBest = x;
}
else
{
bestPricesCo.remove(i);
thesolver->isInfeasibleCo[idx] = NOT_VIOLATED;
}
}
// make sure we do not skip potential candidates due to a high leastBest value
if(leastBest == infinity)
{
assert(bestPricesCo.size() == 0);
leastBest = 0;
}
//scan the updated indeces for a better price
for(int i = thesolver->updateViolsCo.size() - 1; i >= 0; --i)
{
idx = thesolver->updateViolsCo.index(i);
// only look at indeces that were not checked already
if(thesolver->isInfeasibleCo[idx] == VIOLATED)
{
x = test[idx];
if(x < -feastol)
{
x = computePrice(x, pen[idx], feastol);
if(x > leastBest)
{
if(x > best)
{
best = x;
enterIdx = idx;
last = pen[idx];
}
// put index into candidate list
thesolver->isInfeasibleCo[idx] = VIOLATED_AND_CHECKED;
bestPricesCo.addIdx(idx);
}
}
else
{
thesolver->isInfeasibleCo[idx] = NOT_VIOLATED;
}
}
}
if(enterIdx >= 0)
return thesolver->id(enterIdx);
else
return SPxId();
}
SPxId SPxDevexPR::selectEnterSparseDim(Real& best, Real feastol)
{
const Real* cTest = thesolver->coTest().get_const_ptr();
const Real* cpen = thesolver->coWeights.get_const_ptr();
int enterIdx = -1;
int idx;
Real x;
assert(thesolver->coWeights.dim() == thesolver->coTest().dim());
for(int i = thesolver->infeasibilities.size() - 1; i >= 0; --i)
{
idx = thesolver->infeasibilities.index(i);
x = cTest[idx];
if(x < -feastol)
{
x = computePrice(x, cpen[idx], feastol);
if(x > best)
{
best = x;
enterIdx = idx;
last = cpen[idx];
}
}
else
{
thesolver->infeasibilities.remove(i);
thesolver->isInfeasible[idx] = NOT_VIOLATED;
}
}
if(enterIdx >= 0)
return thesolver->coId(enterIdx);
return SPxId();
}
SPxId SPxDevexPR::selectEnterSparseCoDim(Real& best, Real feastol)
{
const Real* test = thesolver->test().get_const_ptr();
const Real* pen = thesolver->weights.get_const_ptr();
int enterIdx = -1;
int idx;
Real x;
assert(thesolver->weights.dim() == thesolver->test().dim());
for(int i = thesolver->infeasibilitiesCo.size() - 1; i >= 0; --i)
{
idx = thesolver->infeasibilitiesCo.index(i);
x = test[idx];
if(x < -feastol)
{
x = computePrice(x, pen[idx], feastol);
if(x > best)
{
best = x;
enterIdx = idx;
last = pen[idx];
}
}
else
{
thesolver->infeasibilitiesCo.remove(i);
thesolver->isInfeasibleCo[idx] = NOT_VIOLATED;
}
}
if(enterIdx >= 0)
return thesolver->id(enterIdx);
return SPxId();
}
SPxId SPxDevexPR::selectEnterDenseDim(Real& best, Real feastol, int start, int incr)
{
const Real* cTest = thesolver->coTest().get_const_ptr();
const Real* cpen = thesolver->coWeights.get_const_ptr();
int end = thesolver->coWeights.dim();
int enterIdx = -1;
Real x;
assert(end == thesolver->coTest().dim());
for(; start < end; start += incr)
{
x = cTest[start];
if(x < -feastol)
{
x = computePrice(x, cpen[start], feastol);
if(x > best)
{
best = x;
enterIdx = start;
last = cpen[start];
}
}
}
if(enterIdx >= 0)
return thesolver->coId(enterIdx);
return SPxId();
}
SPxId SPxDevexPR::selectEnterDenseCoDim(Real& best, Real feastol, int start, int incr)
{
const Real* test = thesolver->test().get_const_ptr();
const Real* pen = thesolver->weights.get_const_ptr();
int end = thesolver->weights.dim();
int enterIdx = -1;
Real x;
assert(end == thesolver->test().dim());
for(; start < end; start += incr)
{
x = test[start];
if(test[start] < -feastol)
{
x = computePrice(x, pen[start], feastol);
if(x > best)
{
best = x;
enterIdx = start;
last = pen[start];
}
}
}
if(enterIdx >= 0)
return thesolver->id(enterIdx);
return SPxId();
}
/**@todo suspicious: the pricer should be informed, that variable id
has entered the basis at position n, but the id is not used here
(this is true for all pricers)
*/
void SPxDevexPR::entered4(SPxId /*id*/, int n)
{
DVector& weights = thesolver->weights;
DVector& coWeights = thesolver->coWeights;
if(n >= 0 && n < thesolver->dim())
{
const Real* pVec = thesolver->pVec().delta().values();
const IdxSet& pIdx = thesolver->pVec().idx();
const Real* coPvec = thesolver->coPvec().delta().values();
const IdxSet& coPidx = thesolver->coPvec().idx();
Real xi_p = 1 / thesolver->fVec().delta()[n];
int i, j;
assert(thesolver->fVec().delta()[n] > thesolver->epsilon()
|| thesolver->fVec().delta()[n] < -thesolver->epsilon());
xi_p = xi_p * xi_p * last;
for(j = coPidx.size() - 1; j >= 0; --j)
{
i = coPidx.index(j);
coWeights[i] += xi_p * coPvec[i] * coPvec[i];
if(coWeights[i] <= 1 || coWeights[i] > 1e+6)
{
setupWeights(SPxSolver::ENTER);
return;
}
}
for(j = pIdx.size() - 1; j >= 0; --j)
{
i = pIdx.index(j);
weights[i] += xi_p * pVec[i] * pVec[i];
if(weights[i] <= 1 || weights[i] > 1e+6)
{
setupWeights(SPxSolver::ENTER);
return;
}
}
}
}
void SPxDevexPR::addedVecs(int n)
{
int initval = (thesolver->type() == SPxSolver::ENTER) ? 2 : 1;
DVector& weights = thesolver->weights;
n = weights.dim();
weights.reDim(thesolver->coDim());
for(int i = weights.dim() - 1; i >= n; --i)
weights[i] = initval;
}
void SPxDevexPR::addedCoVecs(int n)
{
int initval = (thesolver->type() == SPxSolver::ENTER) ? 2 : 1;
DVector& coWeights = thesolver->coWeights;
n = coWeights.dim();
coWeights.reDim(thesolver->dim());
for(int i = coWeights.dim() - 1; i >= n; --i)
coWeights[i] = initval;
}
} // namespace soplex
| 25.525586 | 118 | 0.556112 | [
"object",
"vector"
] |
14a818882cf8265c7efe5b8389d6a868ffbe7292 | 24,406 | cc | C++ | chrome/browser/views/tabs/tab_2.cc | zachlatta/chromium | c4625eefca763df86471d798ee5a4a054b4716ae | [
"BSD-3-Clause"
] | 1 | 2021-09-24T22:49:10.000Z | 2021-09-24T22:49:10.000Z | chrome/browser/views/tabs/tab_2.cc | changbai1980/chromium | c4625eefca763df86471d798ee5a4a054b4716ae | [
"BSD-3-Clause"
] | null | null | null | chrome/browser/views/tabs/tab_2.cc | changbai1980/chromium | c4625eefca763df86471d798ee5a4a054b4716ae | [
"BSD-3-Clause"
] | null | null | null | // Copyright (c) 2009 The Chromium Authors. All rights reserved. Use of this
// source code is governed by a BSD-style license that can be found in the
// LICENSE file.
#include "chrome/browser/views/tabs/tab_2.h"
#include "app/gfx/canvas.h"
#include "app/gfx/font.h"
#include "app/gfx/path.h"
#include "app/l10n_util.h"
#include "app/resource_bundle.h"
#include "app/slide_animation.h"
#include "app/throb_animation.h"
#include "base/string_util.h"
#include "chrome/browser/browser.h" // required for FormatTitleForDisplay.
#include "chrome/browser/browser_theme_provider.h"
#include "grit/app_resources.h"
#include "grit/generated_resources.h"
#include "grit/theme_resources.h"
#include "skia/ext/image_operations.h"
#include "views/animator.h"
#include "views/controls/button/image_button.h"
#include "views/widget/widget.h"
#include "views/window/non_client_view.h"
#include "views/window/window.h"
static const SkScalar kTabCapWidth = 15;
static const SkScalar kTabTopCurveWidth = 4;
static const SkScalar kTabBottomCurveWidth = 3;
// Space between the edges of the tab's bounds and its content.
static const int kLeftPadding = 16;
static const int kTopPadding = 6;
static const int kRightPadding = 15;
static const int kBottomPadding = 5;
// The height of the "drop shadow" drawn across the top of the tab. We allow
// the containing window to consider this region part of the window caption
// rather than the tab, since we are otherwise starved for drag area.
static const int kDropShadowHeight = 2;
// By how much the bottom edge of the tab overlaps the top of the toolbar.
static const int kToolbarOverlap = 1;
// The space between the tab icon and the title.
static const int kIconTitleSpacing = 4;
// The space between the tab title and the close button.
static const int kTitleCloseButtonSpacing = 5;
// The ideal width of a tab, provided sufficient width is available.
static const int kStandardTitleWidth = 175;
// TODO(beng): figure out what these are used for.
static const int kCloseButtonVertFuzz = 0;
static const int kCloseButtonHorzFuzz = 5;
// The size (both width and height) of the tab icon.
static const int kIconSize = 16;
// The color of the text painted in tabs.
static const int kSelectedTitleColor = SK_ColorBLACK;
// How long the hover state takes.
static const int kHoverDurationMs = 90;
// How long the pulse throb takes.
static const int kPulseDurationMs = 200;
// How opaque to make the hover state (out of 1).
static const double kHoverOpacity = 0.33;
// Resources for rendering tabs.
static gfx::Font* title_font = NULL;
static int title_font_height = 0;
static SkBitmap* close_button_n = NULL;
static SkBitmap* close_button_h = NULL;
static SkBitmap* close_button_p = NULL;
static int close_button_height = 0;
static int close_button_width = 0;
static SkBitmap* waiting_animation_frames = NULL;
static SkBitmap* loading_animation_frames = NULL;
static SkBitmap* crashed_icon = NULL;
static int loading_animation_frame_count = 0;
static int waiting_animation_frame_count = 0;
static int waiting_to_loading_frame_count_ratio = 0;
Tab2::TabImage Tab2::tab_alpha_ = {0};
Tab2::TabImage Tab2::tab_active_ = {0};
Tab2::TabImage Tab2::tab_inactive_ = {0};
namespace {
////////////////////////////////////////////////////////////////////////////////
// TabCloseButton
//
// This is a Button subclass that causes middle clicks to be forwarded to the
// parent View by explicitly not handling them in OnMousePressed.
class TabCloseButton : public views::ImageButton {
public:
explicit TabCloseButton(views::ButtonListener* listener)
: views::ImageButton(listener) {
}
virtual ~TabCloseButton() {}
virtual bool OnMousePressed(const views::MouseEvent& event) {
bool handled = ImageButton::OnMousePressed(event);
// Explicitly mark midle-mouse clicks as non-handled to ensure the tab
// sees them.
return event.IsOnlyMiddleMouseButton() ? false : handled;
}
// We need to let the parent know about mouse state so that it
// can highlight itself appropriately. Note that Exit events
// fire before Enter events, so this works.
virtual void OnMouseEntered(const views::MouseEvent& event) {
ImageButton::OnMouseEntered(event);
GetParent()->OnMouseEntered(event);
}
virtual void OnMouseExited(const views::MouseEvent& event) {
ImageButton::OnMouseExited(event);
GetParent()->OnMouseExited(event);
}
private:
DISALLOW_COPY_AND_ASSIGN(TabCloseButton);
};
void InitResources() {
static bool initialized = false;
if (!initialized) {
// TODO(glen): Allow theming of these.
ResourceBundle& rb = ResourceBundle::GetSharedInstance();
title_font = new gfx::Font(rb.GetFont(ResourceBundle::BaseFont));
title_font_height = title_font->height();
close_button_n = rb.GetBitmapNamed(IDR_TAB_CLOSE);
close_button_h = rb.GetBitmapNamed(IDR_TAB_CLOSE_H);
close_button_p = rb.GetBitmapNamed(IDR_TAB_CLOSE_P);
close_button_width = close_button_n->width();
close_button_height = close_button_n->height();
Tab2::LoadTabImages();
// The loading animation image is a strip of states. Each state must be
// square, so the height must divide the width evenly.
loading_animation_frames = rb.GetBitmapNamed(IDR_THROBBER);
DCHECK(loading_animation_frames);
DCHECK(loading_animation_frames->width() %
loading_animation_frames->height() == 0);
loading_animation_frame_count =
loading_animation_frames->width() / loading_animation_frames->height();
waiting_animation_frames = rb.GetBitmapNamed(IDR_THROBBER_WAITING);
DCHECK(waiting_animation_frames);
DCHECK(waiting_animation_frames->width() %
waiting_animation_frames->height() == 0);
waiting_animation_frame_count =
waiting_animation_frames->width() / waiting_animation_frames->height();
waiting_to_loading_frame_count_ratio =
waiting_animation_frame_count / loading_animation_frame_count;
crashed_icon = rb.GetBitmapNamed(IDR_SAD_FAVICON);
initialized = true;
}
}
int GetContentHeight() {
// The height of the content of the Tab is the largest of the icon,
// the title text and the close button graphic.
int content_height = std::max(kIconSize, title_font_height);
return std::max(content_height, close_button_height);
}
} // namespace
////////////////////////////////////////////////////////////////////////////////
// Tab2, public:
Tab2::Tab2(Tab2Model* model)
: model_(model),
dragging_(false),
removing_(false) {
InitResources();
// Add the Close Button.
close_button_ = new TabCloseButton(this);
close_button_->SetImage(views::CustomButton::BS_NORMAL, close_button_n);
close_button_->SetImage(views::CustomButton::BS_HOT, close_button_h);
close_button_->SetImage(views::CustomButton::BS_PUSHED, close_button_p);
AddChildView(close_button_);
hover_animation_.reset(new SlideAnimation(this));
hover_animation_->SetSlideDuration(kHoverDurationMs);
pulse_animation_.reset(new ThrobAnimation(this));
pulse_animation_->SetSlideDuration(kPulseDurationMs);
}
Tab2::~Tab2() {
}
void Tab2::SetRemovingModel(Tab2Model* model) {
removing_model_.reset(model);
model_ = removing_model_.get();
}
bool Tab2::IsAnimating() const {
return animator_.get() && animator_->IsAnimating();
}
views::Animator* Tab2::GetAnimator() {
if (!animator_.get())
animator_.reset(new views::Animator(this, model_->AsAnimatorDelegate()));
return animator_.get();
}
// static
gfx::Size Tab2::GetMinimumUnselectedSize() {
InitResources();
gfx::Size minimum_size;
minimum_size.set_width(kLeftPadding + kRightPadding);
// Since we use bitmap images, the real minimum height of the image is
// defined most accurately by the height of the end cap images.
minimum_size.set_height(tab_active_.image_l->height());
return minimum_size;
}
// static
gfx::Size Tab2::GetMinimumSelectedSize() {
gfx::Size minimum_size = GetMinimumUnselectedSize();
minimum_size.set_width(kLeftPadding + kIconSize + kRightPadding);
return minimum_size;
}
// static
gfx::Size Tab2::GetStandardSize() {
gfx::Size standard_size = GetMinimumUnselectedSize();
standard_size.set_width(
standard_size.width() + kIconTitleSpacing + kStandardTitleWidth);
return standard_size;
}
void Tab2::AddTabShapeToPath(gfx::Path* path) const {
SkScalar h = SkIntToScalar(height());
SkScalar w = SkIntToScalar(width());
path->moveTo(0, h);
// Left end cap.
path->lineTo(kTabBottomCurveWidth, h - kTabBottomCurveWidth);
path->lineTo(kTabCapWidth - kTabTopCurveWidth, kTabTopCurveWidth);
path->lineTo(kTabCapWidth, 0);
// Connect to the right cap.
path->lineTo(w - kTabCapWidth, 0);
// Right end cap.
path->lineTo(w - kTabCapWidth + kTabTopCurveWidth, kTabTopCurveWidth);
path->lineTo(w - kTabBottomCurveWidth, h - kTabBottomCurveWidth);
path->lineTo(w, h);
// Close out the path.
path->lineTo(0, h);
path->close();
}
///////////////////////////////////////////////////////////////////////////////
// Tab2, views::ButtonListener implementation:
void Tab2::ButtonPressed(views::Button* sender) {
if (sender == close_button_)
model_->CloseTab(this);
}
////////////////////////////////////////////////////////////////////////////////
// Tab2, views::View overrides:
void Tab2::Layout() {
gfx::Rect content_rect = GetLocalBounds(false);
if (content_rect.IsEmpty())
return;
content_rect.Inset(kLeftPadding, kTopPadding, kRightPadding, kBottomPadding);
int content_height = GetContentHeight();
LayoutIcon(content_height, content_rect);
LayoutCloseButton(content_height, content_rect);
LayoutTitle(content_height, content_rect);
}
void Tab2::Paint(gfx::Canvas* canvas) {
// Don't paint if we're narrower than we can render correctly. (This should
// only happen during animations).
if (width() < GetMinimumUnselectedSize().width())
return;
PaintTabBackground(canvas);
if (ShouldShowIcon())
PaintIcon(canvas);
PaintTitle(canvas);
}
void Tab2::OnMouseEntered(const views::MouseEvent& e) {
hover_animation_->SetTweenType(SlideAnimation::EASE_OUT);
hover_animation_->Show();
}
void Tab2::OnMouseExited(const views::MouseEvent& e) {
hover_animation_->SetTweenType(SlideAnimation::EASE_IN);
hover_animation_->Hide();
}
bool Tab2::OnMousePressed(const views::MouseEvent& event) {
if (event.IsLeftMouseButton()) {
model_->SelectTab(this);
model_->CaptureDragInfo(this, event);
}
return true;
}
bool Tab2::OnMouseDragged(const views::MouseEvent& event) {
dragging_ = true;
return model_->DragTab(this, event);
}
void Tab2::OnMouseReleased(const views::MouseEvent& event, bool canceled) {
if (dragging_) {
dragging_ = false;
model_->DragEnded(this);
}
}
void Tab2::ThemeChanged() {
LoadTabImages();
View::ThemeChanged();
}
void Tab2::ViewHierarchyChanged(bool is_add, views::View* parent,
views::View* child) {
if (parent->GetThemeProvider())
theme_provider_ = parent->GetThemeProvider();
}
ThemeProvider* Tab2::GetThemeProvider() {
ThemeProvider* provider = View::GetThemeProvider();
if (provider)
return provider;
if (theme_provider_)
return theme_provider_;
// return contents->profile()->GetThemeProvider();
NOTREACHED() << "Unable to find a theme provider";
return NULL;
}
////////////////////////////////////////////////////////////////////////////////
// Tab2, views::AnimationDelegate implementation:
void Tab2::AnimationProgressed(const Animation* animation) {
SchedulePaint();
}
void Tab2::AnimationCanceled(const Animation* animation) {
AnimationEnded(animation);
}
void Tab2::AnimationEnded(const Animation* animation) {
SchedulePaint();
}
////////////////////////////////////////////////////////////////////////////////
// Tab2, private:
void Tab2::LayoutIcon(int content_height, const gfx::Rect& content_rect) {
showing_icon_ = ShouldShowIcon();
if (showing_icon_) {
int icon_y = kTopPadding + (content_height - kIconSize) / 2;
icon_bounds_.SetRect(content_rect.x(), icon_y, kIconSize, kIconSize);
} else {
icon_bounds_.SetRect(content_rect.x(), content_rect.y(), 0, 0);
}
// Since we paint the icon manually instead of using a child view, we need
// to adjust its bounds for RTL.
icon_bounds_.set_x(MirroredLeftPointForRect(icon_bounds_));
}
void Tab2::LayoutCloseButton(int content_height,
const gfx::Rect& content_rect) {
showing_close_button_ = ShouldShowCloseBox();
if (showing_close_button_) {
int close_button_top =
kTopPadding + kCloseButtonVertFuzz +
(content_height - close_button_height) / 2;
// If the ratio of the close button size to tab width exceeds the maximum.
close_button_->SetBounds(content_rect.width() + kCloseButtonHorzFuzz,
close_button_top, close_button_width,
close_button_height);
close_button_->SetVisible(true);
} else {
close_button_->SetBounds(0, 0, 0, 0);
close_button_->SetVisible(false);
}
}
void Tab2::LayoutTitle(int content_height, const gfx::Rect& content_rect) {
// Size the Title text to fill the remaining space.
int title_left = icon_bounds_.right() + kIconTitleSpacing;
int title_top = kTopPadding + (content_height - title_font_height) / 2;
// If the user has big fonts, the title will appear rendered too far down on
// the y-axis if we use the regular top padding, so we need to adjust it so
// that the text appears centered.
gfx::Size minimum_size = GetMinimumUnselectedSize();
int text_height = title_top + title_font_height + kBottomPadding;
if (text_height > minimum_size.height())
title_top -= (text_height - minimum_size.height()) / 2;
int title_width;
if (close_button_->IsVisible()) {
title_width = std::max(close_button_->x() -
kTitleCloseButtonSpacing - title_left, 0);
} else {
title_width = std::max(content_rect.width() - title_left, 0);
}
title_bounds_.SetRect(title_left, title_top, title_width, title_font_height);
// Since we paint the title manually instead of using a child view, we need
// to adjust its bounds for RTL.
title_bounds_.set_x(MirroredLeftPointForRect(title_bounds_));
}
void Tab2::PaintIcon(gfx::Canvas* canvas) {
if (animation_state_ != ANIMATION_NONE) {
PaintLoadingAnimation(canvas);
} else {
canvas->save();
canvas->ClipRectInt(0, 0, width(), height() - 4);
SkBitmap icon = model_->GetIcon(this);
if (!icon.isNull()) {
// TODO(pkasting): Use code in tab_icon_view.cc:PaintIcon() (or switch
// to using that class to render the icon).
canvas->DrawBitmapInt(icon, 0, 0, icon.width(), icon.height(),
icon_bounds_.x(),
icon_bounds_.y() + icon_hiding_offset_,
kIconSize, kIconSize, true);
}
canvas->restore();
}
}
void Tab2::PaintTitle(gfx::Canvas* canvas) {
// Paint the Title.
string16 title = model_->GetTitle(this);
if (title.empty()) {
if (model_->IsLoading(this))
title = l10n_util::GetStringUTF16(IDS_TAB_LOADING_TITLE);
else
title = l10n_util::GetStringUTF16(IDS_TAB_UNTITLED_TITLE);
} else {
Browser::FormatTitleForDisplay(&title);
}
SkColor title_color = GetThemeProvider()->
GetColor(model_->IsSelected(this) ?
BrowserThemeProvider::COLOR_TAB_TEXT :
BrowserThemeProvider::COLOR_BACKGROUND_TAB_TEXT);
canvas->DrawStringInt(UTF16ToWideHack(title), *title_font, title_color,
title_bounds_.x(), title_bounds_.y(),
title_bounds_.width(), title_bounds_.height());
}
void Tab2::PaintTabBackground(gfx::Canvas* canvas) {
if (model_->IsSelected(this)) {
// Sometimes detaching a tab quickly can result in the model reporting it
// as not being selected, so is_drag_clone_ ensures that we always paint
// the active representation for the dragged tab.
PaintActiveTabBackground(canvas);
} else {
// Draw our hover state.
Animation* animation = hover_animation_.get();
if (pulse_animation_->IsAnimating())
animation = pulse_animation_.get();
PaintInactiveTabBackground(canvas);
if (animation->GetCurrentValue() > 0) {
SkRect bounds;
bounds.set(0, 0, SkIntToScalar(width()), SkIntToScalar(height()));
canvas->saveLayerAlpha(&bounds,
static_cast<int>(animation->GetCurrentValue() * kHoverOpacity * 0xff),
SkCanvas::kARGB_ClipLayer_SaveFlag);
canvas->drawARGB(0, 255, 255, 255, SkXfermode::kClear_Mode);
PaintActiveTabBackground(canvas);
canvas->restore();
}
}
}
void Tab2::PaintInactiveTabBackground(gfx::Canvas* canvas) {
bool is_otr = model_->IsIncognito(this);
// The tab image needs to be lined up with the background image
// so that it feels partially transparent. These offsets represent the tab
// position within the frame background image.
int offset = GetX(views::View::APPLY_MIRRORING_TRANSFORMATION) +
background_offset_.x();
int tab_id;
if (GetWidget() &&
GetWidget()->GetWindow()->GetNonClientView()->UseNativeFrame()) {
tab_id = IDR_THEME_TAB_BACKGROUND_V;
} else {
tab_id = is_otr ? IDR_THEME_TAB_BACKGROUND_INCOGNITO :
IDR_THEME_TAB_BACKGROUND;
}
SkBitmap* tab_bg = GetThemeProvider()->GetBitmapNamed(tab_id);
// Draw left edge. Don't draw over the toolbar, as we're not the foreground
// tab.
SkBitmap tab_l = skia::ImageOperations::CreateTiledBitmap(
*tab_bg, offset, background_offset_.y(),
tab_active_.l_width, height());
SkBitmap theme_l = skia::ImageOperations::CreateMaskedBitmap(
tab_l, *tab_alpha_.image_l);
canvas->DrawBitmapInt(theme_l,
0, 0, theme_l.width(), theme_l.height() - kToolbarOverlap,
0, 0, theme_l.width(), theme_l.height() - kToolbarOverlap,
false);
// Draw right edge. Again, don't draw over the toolbar.
SkBitmap tab_r = skia::ImageOperations::CreateTiledBitmap(
*tab_bg,
offset + width() - tab_active_.r_width, background_offset_.y(),
tab_active_.r_width, height());
SkBitmap theme_r = skia::ImageOperations::CreateMaskedBitmap(
tab_r, *tab_alpha_.image_r);
canvas->DrawBitmapInt(theme_r,
0, 0, theme_r.width(), theme_r.height() - kToolbarOverlap,
width() - theme_r.width(), 0, theme_r.width(),
theme_r.height() - kToolbarOverlap, false);
// Draw center. Instead of masking out the top portion we simply skip over it
// by incrementing by kDropShadowHeight, since it's a simple rectangle. And
// again, don't draw over the toolbar.
canvas->TileImageInt(*tab_bg,
offset + tab_active_.l_width, background_offset_.y() + kDropShadowHeight,
tab_active_.l_width, kDropShadowHeight,
width() - tab_active_.l_width - tab_active_.r_width,
height() - kDropShadowHeight - kToolbarOverlap);
// Now draw the highlights/shadows around the tab edge.
canvas->DrawBitmapInt(*tab_inactive_.image_l, 0, 0);
canvas->TileImageInt(*tab_inactive_.image_c,
tab_inactive_.l_width, 0,
width() - tab_inactive_.l_width - tab_inactive_.r_width,
height());
canvas->DrawBitmapInt(*tab_inactive_.image_r,
width() - tab_inactive_.r_width, 0);
}
void Tab2::PaintActiveTabBackground(gfx::Canvas* canvas) {
int offset = GetX(views::View::APPLY_MIRRORING_TRANSFORMATION) +
background_offset_.x();
ThemeProvider* tp = GetThemeProvider();
if (!tp)
NOTREACHED() << "Unable to get theme provider";
SkBitmap* tab_bg = GetThemeProvider()->GetBitmapNamed(IDR_THEME_TOOLBAR);
// Draw left edge.
SkBitmap tab_l = skia::ImageOperations::CreateTiledBitmap(
*tab_bg, offset, 0, tab_active_.l_width, height());
SkBitmap theme_l = skia::ImageOperations::CreateMaskedBitmap(
tab_l, *tab_alpha_.image_l);
canvas->DrawBitmapInt(theme_l, 0, 0);
// Draw right edge.
SkBitmap tab_r = skia::ImageOperations::CreateTiledBitmap(
*tab_bg,
offset + width() - tab_active_.r_width, 0,
tab_active_.r_width, height());
SkBitmap theme_r = skia::ImageOperations::CreateMaskedBitmap(
tab_r, *tab_alpha_.image_r);
canvas->DrawBitmapInt(theme_r, width() - tab_active_.r_width, 0);
// Draw center. Instead of masking out the top portion we simply skip over it
// by incrementing by kDropShadowHeight, since it's a simple rectangle.
canvas->TileImageInt(*tab_bg,
offset + tab_active_.l_width, kDropShadowHeight,
tab_active_.l_width, kDropShadowHeight,
width() - tab_active_.l_width - tab_active_.r_width,
height() - kDropShadowHeight);
// Now draw the highlights/shadows around the tab edge.
canvas->DrawBitmapInt(*tab_active_.image_l, 0, 0);
canvas->TileImageInt(*tab_active_.image_c, tab_active_.l_width, 0,
width() - tab_active_.l_width - tab_active_.r_width, height());
canvas->DrawBitmapInt(*tab_active_.image_r, width() - tab_active_.r_width, 0);
}
void Tab2::PaintHoverTabBackground(gfx::Canvas* canvas, double opacity) {
SkBitmap left = skia::ImageOperations::CreateBlendedBitmap(
*tab_inactive_.image_l, *tab_active_.image_l, opacity);
SkBitmap center = skia::ImageOperations::CreateBlendedBitmap(
*tab_inactive_.image_c, *tab_active_.image_c, opacity);
SkBitmap right = skia::ImageOperations::CreateBlendedBitmap(
*tab_inactive_.image_r, *tab_active_.image_r, opacity);
canvas->DrawBitmapInt(left, 0, 0);
canvas->TileImageInt(center, tab_active_.l_width, 0,
width() - tab_active_.l_width - tab_active_.r_width, height());
canvas->DrawBitmapInt(right, width() - tab_active_.r_width, 0);
}
void Tab2::PaintLoadingAnimation(gfx::Canvas* canvas) {
SkBitmap* frames = (animation_state_ == ANIMATION_WAITING) ?
waiting_animation_frames : loading_animation_frames;
int image_size = frames->height();
int image_offset = animation_frame_ * image_size;
int dst_y = (height() - image_size) / 2;
// Just like with the Tab's title and icon, the position for the page
// loading animation also needs to be mirrored if the View's UI layout is
// right-to-left.
int dst_x;
if (UILayoutIsRightToLeft()) {
dst_x = width() - kLeftPadding - image_size;
} else {
dst_x = kLeftPadding;
}
canvas->DrawBitmapInt(*frames, image_offset, 0, image_size,
image_size, dst_x, dst_y, image_size, image_size,
false);
}
int Tab2::IconCapacity() const {
if (height() < GetMinimumUnselectedSize().height())
return 0;
return (width() - kLeftPadding - kRightPadding) / kIconSize;
}
bool Tab2::ShouldShowIcon() const {
if (!model_->ShouldShowIcon(const_cast<Tab2*>(this))) {
return false;
} else if (model_->IsSelected(const_cast<Tab2*>(this))) {
// The selected tab clips icon before close button.
return IconCapacity() >= 2;
}
// Non-selected tabs clip close button before icon.
return IconCapacity() >= 1;
}
bool Tab2::ShouldShowCloseBox() const {
// The selected tab never clips close button.
return model_->IsSelected(const_cast<Tab2*>(this)) || IconCapacity() >= 3;
}
// static
void Tab2::LoadTabImages() {
// We're not letting people override tab images just yet.
ResourceBundle& rb = ResourceBundle::GetSharedInstance();
tab_alpha_.image_l = rb.GetBitmapNamed(IDR_TAB_ALPHA_LEFT);
tab_alpha_.image_r = rb.GetBitmapNamed(IDR_TAB_ALPHA_RIGHT);
tab_active_.image_l = rb.GetBitmapNamed(IDR_TAB_ACTIVE_LEFT);
tab_active_.image_c = rb.GetBitmapNamed(IDR_TAB_ACTIVE_CENTER);
tab_active_.image_r = rb.GetBitmapNamed(IDR_TAB_ACTIVE_RIGHT);
tab_active_.l_width = tab_active_.image_l->width();
tab_active_.r_width = tab_active_.image_r->width();
tab_inactive_.image_l = rb.GetBitmapNamed(IDR_TAB_INACTIVE_LEFT);
tab_inactive_.image_c = rb.GetBitmapNamed(IDR_TAB_INACTIVE_CENTER);
tab_inactive_.image_r = rb.GetBitmapNamed(IDR_TAB_INACTIVE_RIGHT);
tab_inactive_.l_width = tab_inactive_.image_l->width();
tab_inactive_.r_width = tab_inactive_.image_r->width();
loading_animation_frames = rb.GetBitmapNamed(IDR_THROBBER);
waiting_animation_frames = rb.GetBitmapNamed(IDR_THROBBER_WAITING);
}
| 35.371014 | 80 | 0.702286 | [
"render",
"model"
] |
14a89d652ba2aeb0e949085881c618fbb09b4712 | 6,599 | cpp | C++ | CCured/program-dependence-graph/src/BoundaryAnalysis.cpp | Lightninghkm/DataGuard | 4ac1370f7607cec5fc81c3b57f5a62fb1d40f463 | [
"Apache-2.0"
] | 9 | 2022-02-25T01:48:43.000Z | 2022-03-20T04:48:44.000Z | CCured/program-dependence-graph/src/BoundaryAnalysis.cpp | Lightninghkm/DataGuard | 4ac1370f7607cec5fc81c3b57f5a62fb1d40f463 | [
"Apache-2.0"
] | 1 | 2022-03-19T08:48:07.000Z | 2022-03-21T00:51:51.000Z | CCured/program-dependence-graph/src/BoundaryAnalysis.cpp | Lightninghkm/DataGuard | 4ac1370f7607cec5fc81c3b57f5a62fb1d40f463 | [
"Apache-2.0"
] | null | null | null | #include "BoundaryAnalysis.hh"
char pdg::BoundaryAnalysis::ID = 0;
using namespace llvm;
cl::opt<std::string> BlackListFileName("libfile", cl::desc("Lib file"), cl::value_desc("lib filename"));
void pdg::BoundaryAnalysis::getAnalysisUsage(AnalysisUsage &AU) const
{
AU.setPreservesAll();
}
bool pdg::BoundaryAnalysis::runOnModule(Module &M)
{
setupBlackListFuncNames();
computeDriverImportedFuncs(M);
computeDriverFuncs(M);
computeExportedFuncs(M);
computeExportedFuncSymbols(M);
dumpToFiles();
return false;
}
void pdg::BoundaryAnalysis::setupBlackListFuncNames()
{
if (BlackListFileName.empty())
BlackListFileName = "liblcd_funcs.txt";
std::ifstream black_list_func_file(BlackListFileName);
if (!black_list_func_file)
{
errs() << "fail to locate black list function file!\n";
return;
}
for (std::string line; std::getline(black_list_func_file, line);)
{
_black_list_func_names.insert(line);
}
}
void pdg::BoundaryAnalysis::computeDriverImportedFuncs(Module &M)
{
for (auto &F : M)
{
if (F.isDeclaration())
{
std::string func_name = F.getName().str();
func_name = pdgutils::stripFuncNameVersionNumber(func_name);
if (isBlackListFunc(func_name))
continue;
_imported_funcs.push_back(func_name);
}
}
}
void pdg::BoundaryAnalysis::computeDriverFuncs(Module &M)
{
for (auto &F : M)
{
if (F.isDeclaration())
continue;
std::string func_name = F.getName().str();
func_name = pdgutils::stripFuncNameVersionNumber(func_name);
if (isBlackListFunc(func_name))
continue;
_driver_domain_funcs.push_back(func_name);
}
}
void pdg::BoundaryAnalysis::computeExportedFuncs(Module &M)
{
// read shared struct type names if exist
std::set<std::string> shared_struct_type_names;
std::ifstream shared_struct_name_file("shared_struct_types");
if (shared_struct_name_file.good())
{
// read shared data types
for (std::string line; std::getline(shared_struct_name_file, line);)
{
shared_struct_type_names.insert(line);
}
}
// used to store driver global
std::ofstream driver_global_struct_types("driver_global_struct_types");
for (auto &global_var : M.getGlobalList())
{
SmallVector<DIGlobalVariableExpression *, 4> sv;
if (!global_var.hasInitializer())
continue;
DIGlobalVariable *di_gv = nullptr;
global_var.getDebugInfo(sv);
for (auto di_expr : sv)
{
if (di_expr->getVariable()->getName() == global_var.getName())
di_gv = di_expr->getVariable(); // get global variable from global expression
}
if (!di_gv)
continue;
if (!global_var.isConstant() && global_var.hasInitializer())
_driver_globalvar_names.push_back(global_var.getName().str());
auto gv_di_type = di_gv->getType();
auto gv_lowest_di_type = dbgutils::getLowestDIType(*gv_di_type);
if (!gv_lowest_di_type || gv_lowest_di_type->getTag() != dwarf::DW_TAG_structure_type)
continue;
auto gv_di_type_name = dbgutils::getSourceLevelTypeName(*gv_lowest_di_type, true);
auto gv_name = global_var.getName().str();
gv_di_type_name = pdgutils::stripVersionTag(gv_di_type_name);
if (!shared_struct_type_names.empty() && shared_struct_type_names.find(gv_di_type_name) == shared_struct_type_names.end())
continue;
driver_global_struct_types << gv_di_type_name << "\n";
const auto &typeArrRef = dyn_cast<DICompositeType>(gv_lowest_di_type)->getElements();
Type *global_type = global_var.getType();
if (auto t = dyn_cast<PointerType>(global_type))
global_type = t->getPointerElementType();
if (!global_type->isStructTy())
continue;
if (global_type->getStructNumElements() != typeArrRef.size())
continue;
for (unsigned i = 0; i < global_type->getStructNumElements(); ++i)
{
auto struct_element = global_var.getInitializer()->getAggregateElement(i);
if (struct_element == nullptr)
continue;
if (DIType *struct_field_di_type = dyn_cast<DIType>(typeArrRef[i]))
{
// if the field is a function pointer, directly print it to map
std::string field_type_name = struct_element->getName().str();
if (pdgutils::isUserOfSentinelTypeVal(*struct_element))
_sentinel_fields.push_back(dbgutils::getSourceLevelVariableName(*struct_field_di_type));
if (!field_type_name.empty())
{
std::string field_source_name = dbgutils::getSourceLevelVariableName(*struct_field_di_type);
// concate the ptr name with the outer ops struct name
field_source_name = gv_di_type_name + "_" + field_source_name;
if (dbgutils::isFuncPointerType(*struct_field_di_type))
{
_exported_func_ptrs.push_back(field_source_name);
_exported_funcs.push_back(field_type_name);
_global_op_struct_names.insert(gv_di_type_name);
}
}
// TODO: handle nested structs
}
}
}
}
void pdg::BoundaryAnalysis::computeExportedFuncSymbols(Module &M)
{
for (auto &gv : M.getGlobalList())
{
auto name = gv.getName().str();
// look for global name starts with __ksymtab or __kstrtab
if (name.find("__ksymtab_") == 0 || name.find("__kstrtab_") == 0)
{
std::string func_name = name.erase(0, 10);
Function *f = M.getFunction(StringRef(func_name));
if (f != nullptr)
_exported_func_symbols.insert(func_name);
}
}
}
void pdg::BoundaryAnalysis::dumpToFiles()
{
errs() << "dumping to files\n";
dumpToFile("imported_funcs", _imported_funcs);
dumpToFile("driver_funcs", _driver_domain_funcs);
dumpToFile("exported_funcs", _exported_funcs);
dumpToFile("exported_func_ptrs", _exported_func_ptrs);
dumpToFile("sentinel_fields", _sentinel_fields);
dumpToFile("driver_globalvar_names", _driver_globalvar_names);
std::vector<std::string> exported_func_symbols(_exported_func_symbols.begin(), _exported_func_symbols.end());
dumpToFile("driver_exported_func_symbols", exported_func_symbols);
std::vector<std::string> global_op_struct_names(_global_op_struct_names.begin(), _global_op_struct_names.end());
dumpToFile("global_op_struct_names", global_op_struct_names);
}
void pdg::BoundaryAnalysis::dumpToFile(std::string file_name, std::vector<std::string> &names)
{
std::ofstream output_file(file_name);
for (auto name: names)
{
output_file << name << "\n";
}
output_file.close();
}
static RegisterPass<pdg::BoundaryAnalysis>
BoundaryAnalysis("output-boundary-info", "Compute Isolation Boundary", false, true); | 34.19171 | 126 | 0.703591 | [
"vector"
] |
14aaa8926a595f790e595757c7ee5677ddae4350 | 3,730 | cpp | C++ | design/medium/380.InsertDeleteGetRandomO1.cpp | XiaotaoGuo/Leetcode-Solution-In-Cpp | 8e01e35c742a7afb0c8cdd228a6a5e564375434e | [
"Apache-2.0"
] | null | null | null | design/medium/380.InsertDeleteGetRandomO1.cpp | XiaotaoGuo/Leetcode-Solution-In-Cpp | 8e01e35c742a7afb0c8cdd228a6a5e564375434e | [
"Apache-2.0"
] | null | null | null | design/medium/380.InsertDeleteGetRandomO1.cpp | XiaotaoGuo/Leetcode-Solution-In-Cpp | 8e01e35c742a7afb0c8cdd228a6a5e564375434e | [
"Apache-2.0"
] | null | null | null | /*
* @lc app=leetcode id=380 lang=cpp
*
* [380] Insert Delete GetRandom O(1)
*
* https://leetcode.com/problems/insert-delete-getrandom-o1/description/
*
* algorithms
* Medium (49.44%)
* Likes: 3724
* Dislikes: 215
* Total Accepted: 349.8K
* Total Submissions: 707K
* Testcase Example:
'["RandomizedSet","insert","remove","insert","getRandom","remove","insert","getRandom"]\n'
+
'[[],[1],[2],[2],[],[1],[2],[]]'
*
* Implement the RandomizedSet class:
*
*
* RandomizedSet() Initializes the RandomizedSet object.
* bool insert(int val) Inserts an item val into the set if not present.
* Returns true if the item was not present, false otherwise.
* bool remove(int val) Removes an item val from the set if present. Returns
* true if the item was present, false otherwise.
* int getRandom() Returns a random element from the current set of elements
* (it's guaranteed that at least one element exists when this method is
* called). Each element must have the same probability of being returned.
*
*
* You must implement the functions of the class such that each function works
* in average O(1) time complexity.
*
*
* Example 1:
*
*
* Input
* ["RandomizedSet", "insert", "remove", "insert", "getRandom", "remove",
* "insert", "getRandom"]
* [[], [1], [2], [2], [], [1], [2], []]
* Output
* [null, true, false, true, 2, true, false, 2]
*
* Explanation
* RandomizedSet randomizedSet = new RandomizedSet();
* randomizedSet.insert(1); // Inserts 1 to the set. Returns true as 1 was
* inserted successfully.
* randomizedSet.remove(2); // Returns false as 2 does not exist in the set.
* randomizedSet.insert(2); // Inserts 2 to the set, returns true. Set now
* contains [1,2].
* randomizedSet.getRandom(); // getRandom() should return either 1 or 2
* randomly.
* randomizedSet.remove(1); // Removes 1 from the set, returns true. Set now
* contains [2].
* randomizedSet.insert(2); // 2 was already in the set, so return false.
* randomizedSet.getRandom(); // Since 2 is the only number in the set,
* getRandom() will always return 2.
*
*
*
* Constraints:
*
*
* -2^31 <= val <= 2^31 - 1
* At most 2 * 10^5 calls will be made to insert, remove, and getRandom.
* There will be at least one element in the data structure when getRandom is
* called.
*
*
*/
// @lc code=start
#include <unordered_map>
#include <vector>
class RandomizedSet {
public:
/** Initialize your data structure here. */
RandomizedSet() {}
/** Inserts a value to the set. Returns true if the set did not already
* contain the specified element. */
bool insert(int val) {
if (num_index.find(val) == num_index.end()) {
nums.push_back(val);
num_index[val] = nums.size() - 1;
return true;
}
return false;
}
/** Removes a value from the set. Returns true if the set contained the
* specified element. */
bool remove(int val) {
if (num_index.find(val) != num_index.end()) {
int index = num_index[val];
num_index[nums[nums.size() - 1]] = index;
std::swap(nums[index], nums[nums.size() - 1]);
nums.pop_back();
num_index.erase(val);
return true;
}
return false;
}
/** Get a random element from the set. */
int getRandom() { return nums[rand() % nums.size()]; }
private:
std::unordered_map<int, int> num_index;
std::vector<int> nums;
};
/**
* Your RandomizedSet object will be instantiated and called as such:
* RandomizedSet* obj = new RandomizedSet();
* bool param_1 = obj->insert(val);
* bool param_2 = obj->remove(val);
* int param_3 = obj->getRandom();
*/
// @lc code=end
| 29.140625 | 91 | 0.635389 | [
"object",
"vector"
] |
14b1f54c4e9a98cf5ea9da3899a49e7a9ee47fe9 | 6,008 | cpp | C++ | Source/Urho3D/Core/Timer.cpp | TrevorCash/Urho3D_old | d24b1467ab2932e9f2bf7881cf116f841a20a6a7 | [
"MIT"
] | 3 | 2018-06-26T05:53:51.000Z | 2018-10-24T20:52:38.000Z | Source/Urho3D/Core/Timer.cpp | TrevorCash/Urho3D_old | d24b1467ab2932e9f2bf7881cf116f841a20a6a7 | [
"MIT"
] | 1 | 2018-02-17T17:32:37.000Z | 2018-03-03T03:51:11.000Z | Source/Urho3D/Core/Timer.cpp | TrevorCash/Urho3D_old | d24b1467ab2932e9f2bf7881cf116f841a20a6a7 | [
"MIT"
] | 2 | 2018-08-04T21:12:11.000Z | 2019-02-09T05:04:29.000Z | //
// Copyright (c) 2008-2018 the Urho3D project.
//
// 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 "../Precompiled.h"
#include "../Core/CoreEvents.h"
#include "../Core/Profiler.h"
#include <ctime>
#ifdef _WIN32
#include <windows.h>
#include <mmsystem.h>
#elif __EMSCRIPTEN__
#include <emscripten/emscripten.h>
#else
#include <sys/time.h>
#include <unistd.h>
#endif
#include "../DebugNew.h"
namespace Urho3D
{
bool HiresTimer::supported(false);
long long HiresTimer::frequency(1000);
Time::Time(Context* context) :
Object(context),
frameNumber_(0),
timeStep_(0.0f),
timerPeriod_(0)
{
#ifdef _WIN32
LARGE_INTEGER frequency;
if (QueryPerformanceFrequency(&frequency))
{
HiresTimer::frequency = frequency.QuadPart;
HiresTimer::supported = true;
}
#else
HiresTimer::frequency = 1000000;
HiresTimer::supported = true;
#endif
}
Time::~Time()
{
SetTimerPeriod(0);
}
static unsigned Tick()
{
#ifdef _WIN32
return (unsigned)GetTickCount();
#elif __EMSCRIPTEN__
return (unsigned)emscripten_get_now();
#else
struct timeval time{};
gettimeofday(&time, nullptr);
return (unsigned)(time.tv_sec * 1000 + time.tv_usec / 1000);
#endif
}
static long long HiresTick()
{
#ifdef _WIN32
if (HiresTimer::IsSupported())
{
LARGE_INTEGER counter;
QueryPerformanceCounter(&counter);
return counter.QuadPart;
}
else
return GetTickCount();
#elif __EMSCRIPTEN__
return (unsigned)(emscripten_get_now()*1000.0);
#else
struct timeval time{};
gettimeofday(&time, nullptr);
return time.tv_sec * 1000000LL + time.tv_usec;
#endif
}
void Time::SetTimerPeriod(unsigned mSec)
{
#ifdef _WIN32
if (timerPeriod_ > 0)
timeEndPeriod(timerPeriod_);
timerPeriod_ = mSec;
if (timerPeriod_ > 0)
timeBeginPeriod(timerPeriod_);
#endif
}
float Time::GetElapsedTime()
{
return elapsedTime_.GetMSec(false) / 1000.0f;
}
unsigned Time::GetSystemTime()
{
return Tick();
}
unsigned Time::GetTimeSinceEpoch()
{
return (unsigned)time(nullptr);
}
String Time::GetTimeStamp()
{
char dateTime[20];
time_t sysTime;
time(&sysTime);
tm* timeInfo = localtime(&sysTime);
strftime(dateTime, sizeof(dateTime), "%Y-%m-%d %H:%M:%S", timeInfo);
return dateTime;
}
void Time::Sleep(unsigned mSec)
{
#ifdef _WIN32
::Sleep(mSec);
#else
timespec time{static_cast<time_t>(mSec / 1000), static_cast<long>((mSec % 1000) * 1000000)};
nanosleep(&time, nullptr);
#endif
}
Timer::Timer()
{
Reset();
}
Timer::Timer(unsigned timeoutDurationMs)
{
Reset();
SetTimeoutDuration(timeoutDurationMs);
}
unsigned Timer::GetMSec(bool reset)
{
unsigned currentTime = Tick();
unsigned elapsedTime = currentTime - startTime_;
if (reset) {
Reset();
}
return elapsedTime;
}
unsigned Timer::GetStartTime()
{
return startTime_;
}
void Timer::SetTimeoutDuration(unsigned timeoutDurationMs, bool reset)
{
timeoutDuration_ = timeoutDurationMs;
if (reset)
Reset();
}
unsigned Timer::GetTimeoutDuration()
{
return timeoutDuration_;
}
bool Timer::IsTimedOut()
{
unsigned currentTime = Tick();
if (currentTime - startTime_ >= timeoutDuration_ && (timeoutDuration_ != 0))
return true;
return false;
}
void Timer::Reset()
{
startTime_ = Tick();
}
HiresTimer::HiresTimer()
{
Reset();
}
HiresTimer::HiresTimer(long long timeoutDurationUs)
{
Reset();
SetTimeoutDuration(timeoutDurationUs);
}
long long HiresTimer::GetUSec(bool reset)
{
long long currentTime = HiresTick();
long long elapsedTicks = currentTime - startTime_;
// Correct for possible weirdness with changing internal frequency
if (elapsedTicks < 0)
elapsedTicks = 0;
if (reset)
Reset();
return TicksToUSec(elapsedTicks);
}
long long HiresTimer::GetStartTime()
{
return startTime_;
}
void HiresTimer::SetTimeoutDuration(long long timeoutDurationUs, bool reset)
{
timeoutDurationTicks_ = USecToTicks(timeoutDurationUs);
if (reset)
Reset();
}
long long HiresTimer::GetTimeoutDuration()
{
return TicksToUSec(timeoutDurationTicks_);
}
bool HiresTimer::IsTimedOut()
{
long long currentTick = HiresTick();
if (currentTick - startTime_ >= timeoutDurationTicks_ && (timeoutDurationTicks_ != 0))
return true;
return false;
}
void HiresTimer::Reset()
{
startTime_ = HiresTick();
}
long long HiresTimer::TicksToUSec( long long ticks)
{
return (ticks * 1000000LL) / frequency;
}
long long HiresTimer::USecToTicks(long long microseconds)
{
return (microseconds * frequency) / 1000000LL + 1;
}
}
| 21.53405 | 97 | 0.661784 | [
"object"
] |
14b25d2a06c37ace7abcf1a50258e0dc0587ef01 | 1,862 | cpp | C++ | aho-koras/main.cpp | unegare/algo | 9746a41fe0080443bfa20f6094b68d3d3e720731 | [
"MIT"
] | null | null | null | aho-koras/main.cpp | unegare/algo | 9746a41fe0080443bfa20f6094b68d3d3e720731 | [
"MIT"
] | null | null | null | aho-koras/main.cpp | unegare/algo | 9746a41fe0080443bfa20f6094b68d3d3e720731 | [
"MIT"
] | null | null | null | #include <algorithm>
#include <iostream>
#include <sstream>
#include <iomanip>
#include <vector>
#include "Bohr.hpp"
int main() {
using MyBohr = Bohr<uint32_t>;
using symbol_t = MyBohr::symbol_t;
using pattern_t = MyBohr::pattern_t;
MyBohr b;
std::vector<pattern_t> patterns{{1,2,3,0}, {1,2,0}, {2,0}, {3,1}, {2,3,4}};
std::vector<symbol_t> text{1,2,0,4,1,2,3,0,1,2,3,0,};
std::for_each(patterns.cbegin(), patterns.cend(), [&b](const pattern_t &p) {
b.add_pattern(p);
std::cout << "added_pattern:\t";
std::copy(p.begin(), p.end(), std::ostream_iterator<symbol_t>(std::cout, " "));
std::cout << std::endl;
});
std::cout << "--------------------------------\n";
std::vector<pattern_t> false_patterns_to_check{{4,5}, {1,0}, {1,2,3}, {3,4}, {2,3,1}};
std::cout << "false patterns:\n";
std::for_each(false_patterns_to_check.begin(), false_patterns_to_check.end(), [&b](const pattern_t &p) {
std::ostringstream ss;
std::copy(p.begin(), p.end(), std::ostream_iterator<symbol_t>(ss, " "));
std::cout << std::setw(15) << std::left << ss.str() << ":\t" << std::boolalpha << b.contains(p) << std::endl;
});
std::cout << "\ntrue patterns:\n";
std::for_each(patterns.begin(), patterns.end(), [&b](const pattern_t &p) {
std::ostringstream ss;
std::copy(p.begin(), p.end(), std::ostream_iterator<symbol_t>(ss, " "));
std::cout << std::setw(15) << std::left << ss.str() << ":\t" << std::boolalpha << b.contains(p) << std::endl;
});
auto res = b.find(text);
std::cout << "--------------------------------\n";
std::cout << "text: ";
std::copy(text.begin(), text.end(), std::ostream_iterator<symbol_t>(std::cout, " "));
std::cout << std::endl;
for (const auto &el : res) {
std::cout << "{ pattern_number: " << el.first << ", i: " << el.second << " }" << std::endl;
}
return 0;
}
| 35.132075 | 113 | 0.567669 | [
"vector"
] |
14b63dd093410a63477050d6ee5cfda8d747d241 | 8,375 | cpp | C++ | src/modules/block/block_generator.cpp | cmyers-spirent/openperf | 3d48c622223ae37086af6f3fcb8539db71b05c86 | [
"Apache-2.0"
] | null | null | null | src/modules/block/block_generator.cpp | cmyers-spirent/openperf | 3d48c622223ae37086af6f3fcb8539db71b05c86 | [
"Apache-2.0"
] | null | null | null | src/modules/block/block_generator.cpp | cmyers-spirent/openperf | 3d48c622223ae37086af6f3fcb8539db71b05c86 | [
"Apache-2.0"
] | null | null | null | #include <cstring>
#include <stdexcept>
#include "block_generator.hpp"
#include "device_stack.hpp"
#include "file_stack.hpp"
namespace openperf::block::generator {
using namespace std::chrono_literals;
static uint16_t serial_counter = 0;
auto to_statistics_t(const task_stat_t& task_stat)
{
return model::block_generator_result::statistics_t{
.ops_target = task_stat.ops_target,
.ops_actual = task_stat.ops_actual,
.bytes_target = task_stat.bytes_target,
.bytes_actual = task_stat.bytes_actual,
.io_errors = task_stat.errors,
.latency = task_stat.latency,
.latency_min = task_stat.latency_min,
.latency_max = task_stat.latency_max};
};
std::optional<double> get_field(const block_generator::block_stat& stat,
std::string_view name)
{
auto& read = stat.read;
if (name == "read.ops_target") return read.ops_target;
if (name == "read.ops_actual") return read.ops_actual;
if (name == "read.bytes_target") return read.bytes_target;
if (name == "read.bytes_actual") return read.bytes_actual;
if (name == "read.io_errors") return read.errors;
if (name == "read.latency_total") return read.latency.count();
if (name == "read.latency_min")
return read.latency_min.value_or(0ns).count();
if (name == "read.latency_max")
return read.latency_max.value_or(0ns).count();
auto& write = stat.write;
if (name == "write.ops_target") return write.ops_target;
if (name == "write.ops_actual") return write.ops_actual;
if (name == "write.bytes_target") return write.bytes_target;
if (name == "write.bytes_actual") return write.bytes_actual;
if (name == "write.io_errors") return write.errors;
if (name == "write.latency_total") return write.latency.count();
if (name == "write.latency_min")
return write.latency_min.value_or(0ns).count();
if (name == "write.latency_max")
return write.latency_max.value_or(0ns).count();
if (name == "timestamp")
return std::max(write.updated, read.updated).time_since_epoch().count();
return std::nullopt;
}
block_generator::block_generator(
const model::block_generator& generator_model,
const std::vector<virtual_device_stack*>& vdev_stack_list)
: model::block_generator(generator_model)
, m_serial_number(++serial_counter)
, m_vdev_stack_list(vdev_stack_list)
, m_stat_ptr(&m_stat)
, m_dynamic(get_field)
, m_controller(NAME_PREFIX + std::to_string(m_serial_number) + "_ctl")
{
m_controller.start<task_stat_t>([this](const task_stat_t& stat) {
auto elapsed_time = stat.updated - m_start_time;
auto stat_copy = m_stat;
m_stat_ptr = &stat_copy;
using double_time = std::chrono::duration<double>;
switch (stat.operation) {
case task_operation::READ:
m_stat.read += stat;
m_stat.read.ops_target = static_cast<uint64_t>(
(std::chrono::duration_cast<double_time>(elapsed_time)
* std::min(m_config.read_size, 1U) * m_config.reads_per_sec)
.count());
m_stat.read.bytes_target =
m_stat.read.ops_target * m_config.read_size;
break;
case task_operation::WRITE:
m_stat.write += stat;
m_stat.write.ops_target = static_cast<uint64_t>(
(std::chrono::duration_cast<double_time>(elapsed_time)
* std::min(m_config.write_size, 1U) * m_config.writes_per_sec)
.count());
m_stat.write.bytes_target =
m_stat.write.ops_target * m_config.write_size;
break;
}
m_dynamic.add(m_stat);
m_stat_ptr = &m_stat;
});
update_resource(m_resource_id);
block_generator::config(m_config);
}
block_generator::~block_generator()
{
stop();
m_controller.clear();
m_vdev->close();
}
block_generator::block_result_ptr block_generator::start()
{
if (m_running) return statistics();
reset();
m_controller.resume();
m_running = true;
return statistics();
}
block_generator::block_result_ptr
block_generator::start(const dynamic::configuration& config)
{
if (m_running) return statistics();
m_dynamic.configure(config);
return start();
}
void block_generator::stop()
{
if (!m_running) return;
m_controller.pause();
m_running = false;
}
void block_generator::config(const model::block_generator_config& value)
{
m_controller.pause();
m_controller.clear();
reset();
if (value.reads_per_sec && value.read_size) {
auto task = std::make_unique<block_task>(
make_task_config(value, task_operation::READ));
m_controller.add(
task, NAME_PREFIX + std::to_string(m_serial_number) + "_read");
}
if (value.writes_per_sec && value.write_size) {
auto task = std::make_unique<block_task>(
make_task_config(value, task_operation::WRITE));
m_controller.add(
task, NAME_PREFIX + std::to_string(m_serial_number) + "_write");
}
if (m_running) m_controller.resume();
}
void block_generator::resource_id(std::string_view value)
{
auto dev = m_vdev;
update_resource(std::string(value));
if (dev) m_vdev->close();
config(m_config);
m_resource_id = value;
}
void block_generator::update_resource(const std::string& resource_id)
{
std::shared_ptr<virtual_device> vdev_ptr;
for (auto vdev_stack : m_vdev_stack_list) {
if (auto vdev = vdev_stack->vdev(resource_id)) {
vdev_ptr = vdev;
break;
}
}
if (!vdev_ptr)
throw std::runtime_error("Unknown or unusable resource: "
+ resource_id);
if (auto result = vdev_ptr->open(); !result)
throw std::runtime_error("Cannot open resource: "
+ std::string(std::strerror(result.error())));
m_vdev = vdev_ptr;
}
void block_generator::running(bool is_running)
{
if (is_running)
start();
else
stop();
}
block_generator::block_result_ptr block_generator::statistics() const
{
auto stat = *m_stat_ptr;
auto result = std::make_shared<model::block_generator_result>();
result->id(m_statistics_id);
result->generator_id(m_id);
result->active(m_running);
result->read_stats(to_statistics_t(stat.read));
result->write_stats(to_statistics_t(stat.write));
result->timestamp(std::max(stat.write.updated, stat.read.updated));
result->start_timestamp(m_start_time);
result->dynamic_results(m_dynamic.result());
return result;
}
void block_generator::reset()
{
m_controller.pause();
m_controller.reset();
m_dynamic.reset();
m_start_time = chronometer::now();
m_stat = {};
m_statistics_id = core::to_string(core::uuid::random());
if (m_running) m_controller.resume();
}
task_config_t
block_generator::make_task_config(const model::block_generator_config& config,
task_operation op)
{
auto block_size =
(op == task_operation::READ) ? config.read_size : config.write_size;
if (static_cast<uint64_t>(block_size) + m_vdev->header_size()
> m_vdev->size())
throw std::runtime_error(
"Cannot use resource: resource size is too small");
auto fd = m_vdev->fd();
assert(fd);
task_config_t t_config{
.fd = (op == task_operation::READ) ? fd.value().read : fd.value().write,
.f_size = m_vdev->size(),
.header_size = m_vdev->header_size(),
.queue_depth = config.queue_depth,
.operation = op,
.ops_per_sec = (op == task_operation::READ) ? config.reads_per_sec
: config.writes_per_sec,
.block_size = block_size,
.pattern = config.pattern,
};
if (config.ratio) {
t_config.synchronizer = &m_synchronizer;
m_synchronizer.ratio_reads.store(config.ratio.value().reads,
std::memory_order_relaxed);
m_synchronizer.ratio_writes.store(config.ratio.value().writes,
std::memory_order_relaxed);
}
return t_config;
}
} // namespace openperf::block::generator
| 30.677656 | 80 | 0.637731 | [
"vector",
"model"
] |
14b7810514c7e734d3bd00adb0a16c382faf311e | 15,547 | cpp | C++ | AvxBlas/Transform/transform_transpose_s.cpp | tk-yoshimura/AvxBlas | 37ae77f05e35aa3e97109785276afba3835585ec | [
"MIT"
] | null | null | null | AvxBlas/Transform/transform_transpose_s.cpp | tk-yoshimura/AvxBlas | 37ae77f05e35aa3e97109785276afba3835585ec | [
"MIT"
] | null | null | null | AvxBlas/Transform/transform_transpose_s.cpp | tk-yoshimura/AvxBlas | 37ae77f05e35aa3e97109785276afba3835585ec | [
"MIT"
] | null | null | null | #include "../avxblas.h"
#include "../constants.h"
#include "../utils.h"
#include "../Inline/inline_loadstore_xn_s.hpp"
using namespace System;
#pragma unmanaged
int transpose_stride1_s(
const uint n, const uint r, const uint s, const uint stride,
infloats x_ptr, outfloats y_ptr) {
#ifdef _DEBUG
if (stride != 1) {
return FAILURE_BADPARAM;
}
#endif // _DEBUG
for (uint th = 0; th < n; th++) {
for (uint k = 0; k < r; k++) {
uint offset = k;
for (uint j = 0; j < s; j++) {
y_ptr[offset] = *x_ptr;
x_ptr++;
offset += r;
}
}
y_ptr += s * r;
}
return SUCCESS;
}
int transpose_stride2_s(
const uint n, const uint r, const uint s, const uint stride,
infloats x_ptr, outfloats y_ptr) {
#ifdef _DEBUG
if (stride != 2) {
return FAILURE_BADPARAM;
}
#endif // _DEBUG
for (uint th = 0; th < n; th++) {
for (uint k = 0; k < r; k++) {
uint offset = k * 2;
for (uint j = 0; j < s; j++) {
y_ptr[offset] = x_ptr[0];
y_ptr[offset + 1] = x_ptr[1];
x_ptr += 2;
offset += r * 2;
}
}
y_ptr += s * r * 2;
}
return SUCCESS;
}
int transpose_stride3_s(
const uint n, const uint r, const uint s, const uint stride,
infloats x_ptr, outfloats y_ptr) {
#ifdef _DEBUG
if (stride != 3) {
return FAILURE_BADPARAM;
}
#endif // _DEBUG
const __m128i mask = _mm_setmask_ps(3);
__m128 x;
for (uint th = 0; th < n; th++) {
for (uint k = 0; k < r; k++) {
uint offset = k * 3;
for (uint j = 0; j < s; j++) {
x = _mm_loadu_ps(x_ptr);
_mm_maskstore_ps(y_ptr + offset, mask, x);
x_ptr += 3;
offset += r * 3;
}
}
y_ptr += s * r * 3;
}
return SUCCESS;
}
int transpose_stride4_s(
const uint n, const uint r, const uint s, const uint stride,
infloats x_ptr, outfloats y_ptr) {
#ifdef _DEBUG
if ((stride != 4) || ((size_t)x_ptr % AVX1_ALIGNMENT) != 0 || ((size_t)y_ptr % AVX1_ALIGNMENT) != 0) {
return FAILURE_BADPARAM;
}
#endif // _DEBUG
__m128 x;
for (uint th = 0; th < n; th++) {
for (uint k = 0; k < r; k++) {
uint offset = k * 4;
for (uint j = 0; j < s; j++) {
x = _mm_load_ps(x_ptr);
_mm_stream_ps(y_ptr + offset, x);
x_ptr += 4;
offset += r * 4;
}
}
y_ptr += s * r * 4;
}
return SUCCESS;
}
int transpose_stride5to7_s(
const uint n, const uint r, const uint s, const uint stride,
infloats x_ptr, outfloats y_ptr) {
#ifdef _DEBUG
if (stride <= AVX2_FLOAT_STRIDE / 2 || stride >= AVX2_FLOAT_STRIDE) {
return FAILURE_BADPARAM;
}
#endif // _DEBUG
const __m256i mask = _mm256_setmask_ps(stride);
__m256 x;
for (uint th = 0; th < n; th++) {
for (uint k = 0; k < r; k++) {
uint offset = k * stride;
for (uint j = 0; j < s; j++) {
x = _mm256_loadu_ps(x_ptr);
_mm256_maskstore_ps(y_ptr + offset, mask, x);
x_ptr += stride;
offset += r * stride;
}
}
y_ptr += s * r * stride;
}
return SUCCESS;
}
int transpose_stride8_s(
const uint n, const uint r, const uint s, const uint stride,
infloats x_ptr, outfloats y_ptr) {
#ifdef _DEBUG
if ((stride != AVX2_FLOAT_STRIDE) || ((size_t)x_ptr % AVX2_ALIGNMENT) != 0 || ((size_t)y_ptr % AVX2_ALIGNMENT) != 0) {
return FAILURE_BADPARAM;
}
#endif // _DEBUG
__m256 x;
for (uint th = 0; th < n; th++) {
for (uint k = 0; k < r; k++) {
uint offset = k * AVX2_FLOAT_STRIDE;
for (uint j = 0; j < s; j++) {
x = _mm256_load_ps(x_ptr);
_mm256_stream_ps(y_ptr + offset, x);
x_ptr += AVX2_FLOAT_STRIDE;
offset += r * AVX2_FLOAT_STRIDE;
}
}
y_ptr += s * r * AVX2_FLOAT_STRIDE;
}
return SUCCESS;
}
int transpose_stride9to15_s(
const uint n, const uint r, const uint s, const uint stride,
infloats x_ptr, outfloats y_ptr) {
#ifdef _DEBUG
if (stride <= AVX2_FLOAT_STRIDE || stride >= AVX2_FLOAT_STRIDE * 2) {
return FAILURE_BADPARAM;
}
#endif // _DEBUG
const __m256i mask = _mm256_setmask_ps(stride & AVX2_FLOAT_REMAIN_MASK);
__m256 x0, x1;
for (uint th = 0; th < n; th++) {
for (uint k = 0; k < r; k++) {
uint offset = k * stride;
for (uint j = 0; j < s; j++) {
_mm256_loadu_x2_ps(x_ptr, x0, x1);
_mm256_maskstore_x2_ps(y_ptr + offset, x0, x1, mask);
x_ptr += stride;
offset += r * stride;
}
}
y_ptr += s * r * stride;
}
return SUCCESS;
}
int transpose_stride16_s(
const uint n, const uint r, const uint s, const uint stride,
infloats x_ptr, outfloats y_ptr) {
#ifdef _DEBUG
if ((stride != AVX2_FLOAT_STRIDE * 2) || ((size_t)x_ptr % AVX2_ALIGNMENT) != 0 || ((size_t)y_ptr % AVX2_ALIGNMENT) != 0) {
return FAILURE_BADPARAM;
}
#endif // _DEBUG
__m256 x0, x1;
for (uint th = 0; th < n; th++) {
for (uint k = 0; k < r; k++) {
uint offset = k * AVX2_FLOAT_STRIDE * 2;
for (uint j = 0; j < s; j++) {
_mm256_load_x2_ps(x_ptr, x0, x1);
_mm256_stream_x2_ps(y_ptr + offset, x0, x1);
x_ptr += AVX2_FLOAT_STRIDE * 2;
offset += r * AVX2_FLOAT_STRIDE * 2;
}
}
y_ptr += s * r * AVX2_FLOAT_STRIDE * 2;
}
return SUCCESS;
}
int transpose_stride17to23_s(
const uint n, const uint r, const uint s, const uint stride,
infloats x_ptr, outfloats y_ptr) {
#ifdef _DEBUG
if (stride <= AVX2_FLOAT_STRIDE * 2 || stride >= AVX2_FLOAT_STRIDE * 3) {
return FAILURE_BADPARAM;
}
#endif // _DEBUG
const __m256i mask = _mm256_setmask_ps(stride & AVX2_FLOAT_REMAIN_MASK);
__m256 x0, x1, x2;
for (uint th = 0; th < n; th++) {
for (uint k = 0; k < r; k++) {
uint offset = k * stride;
for (uint j = 0; j < s; j++) {
_mm256_loadu_x3_ps(x_ptr, x0, x1, x2);
_mm256_maskstore_x3_ps(y_ptr + offset, x0, x1, x2, mask);
x_ptr += stride;
offset += r * stride;
}
}
y_ptr += s * r * stride;
}
return SUCCESS;
}
int transpose_stride24_s(
const uint n, const uint r, const uint s, const uint stride,
infloats x_ptr, outfloats y_ptr) {
#ifdef _DEBUG
if ((stride != AVX2_FLOAT_STRIDE * 3) || ((size_t)x_ptr % AVX2_ALIGNMENT) != 0 || ((size_t)y_ptr % AVX2_ALIGNMENT) != 0) {
return FAILURE_BADPARAM;
}
#endif // _DEBUG
__m256 x0, x1, x2;
for (uint th = 0; th < n; th++) {
for (uint k = 0; k < r; k++) {
uint offset = k * AVX2_FLOAT_STRIDE * 3;
for (uint j = 0; j < s; j++) {
_mm256_load_x3_ps(x_ptr, x0, x1, x2);
_mm256_stream_x3_ps(y_ptr + offset, x0, x1, x2);
x_ptr += AVX2_FLOAT_STRIDE * 3;
offset += r * AVX2_FLOAT_STRIDE * 3;
}
}
y_ptr += s * r * AVX2_FLOAT_STRIDE * 3;
}
return SUCCESS;
}
int transpose_stride25to31_s(
const uint n, const uint r, const uint s, const uint stride,
infloats x_ptr, outfloats y_ptr) {
#ifdef _DEBUG
if (stride <= AVX2_FLOAT_STRIDE * 3 || stride >= AVX2_FLOAT_STRIDE * 4) {
return FAILURE_BADPARAM;
}
#endif // _DEBUG
const __m256i mask = _mm256_setmask_ps(stride & AVX2_FLOAT_REMAIN_MASK);
__m256 x0, x1, x2, x3;
for (uint th = 0; th < n; th++) {
for (uint k = 0; k < r; k++) {
uint offset = k * stride;
for (uint j = 0; j < s; j++) {
_mm256_loadu_x4_ps(x_ptr, x0, x1, x2, x3);
_mm256_maskstore_x4_ps(y_ptr + offset, x0, x1, x2, x3, mask);
x_ptr += stride;
offset += r * stride;
}
}
y_ptr += s * r * stride;
}
return SUCCESS;
}
int transpose_stride32_s(
const uint n, const uint r, const uint s, const uint stride,
infloats x_ptr, outfloats y_ptr) {
#ifdef _DEBUG
if ((stride != AVX2_FLOAT_STRIDE * 4) || ((size_t)x_ptr % AVX2_ALIGNMENT) != 0 || ((size_t)y_ptr % AVX2_ALIGNMENT) != 0) {
return FAILURE_BADPARAM;
}
#endif // _DEBUG
__m256 x0, x1, x2, x3;
for (uint th = 0; th < n; th++) {
for (uint k = 0; k < r; k++) {
uint offset = k * AVX2_FLOAT_STRIDE * 4;
for (uint j = 0; j < s; j++) {
_mm256_load_x4_ps(x_ptr, x0, x1, x2, x3);
_mm256_stream_x4_ps(y_ptr + offset, x0, x1, x2, x3);
x_ptr += AVX2_FLOAT_STRIDE * 4;
offset += r * AVX2_FLOAT_STRIDE * 4;
}
}
y_ptr += s * r * AVX2_FLOAT_STRIDE * 4;
}
return SUCCESS;
}
int transpose_strideleq8_s(
const uint n, const uint r, const uint s, const uint stride,
infloats x_ptr, outfloats y_ptr) {
if (stride == 1) {
return transpose_stride1_s(n, r, s, stride, x_ptr, y_ptr);
}
if (stride == 2) {
return transpose_stride2_s(n, r, s, stride, x_ptr, y_ptr);
}
if (stride == 3) {
return transpose_stride3_s(n, r, s, stride, x_ptr, y_ptr);
}
if (stride == 4) {
return transpose_stride4_s(n, r, s, stride, x_ptr, y_ptr);
}
if (stride < 8) {
return transpose_stride5to7_s(n, r, s, stride, x_ptr, y_ptr);
}
if (stride == 8) {
return transpose_stride8_s(n, r, s, stride, x_ptr, y_ptr);
}
return FAILURE_BADPARAM;
}
int transpose_aligned_s(
const uint n, const uint r, const uint s, const uint stride,
infloats x_ptr, outfloats y_ptr) {
#ifdef _DEBUG
if (((stride & AVX2_FLOAT_REMAIN_MASK) != 0) || ((size_t)x_ptr % AVX2_ALIGNMENT) != 0 || ((size_t)y_ptr % AVX2_ALIGNMENT) != 0) {
return FAILURE_BADPARAM;
}
#endif // _DEBUG
if (stride == AVX2_FLOAT_STRIDE) {
return transpose_stride8_s(n, r, s, stride, x_ptr, y_ptr);
}
if (stride == AVX2_FLOAT_STRIDE * 2) {
return transpose_stride16_s(n, r, s, stride, x_ptr, y_ptr);
}
if (stride == AVX2_FLOAT_STRIDE * 3) {
return transpose_stride24_s(n, r, s, stride, x_ptr, y_ptr);
}
if (stride == AVX2_FLOAT_STRIDE * 4) {
return transpose_stride32_s(n, r, s, stride, x_ptr, y_ptr);
}
__m256 x0, x1, x2, x3;
for (uint th = 0; th < n; th++) {
for (uint k = 0; k < r; k++) {
uint offset = k * stride;
for (uint j = 0; j < s; j++) {
uint sr = stride, index = 0;
while (sr >= AVX2_FLOAT_STRIDE * 4) {
_mm256_load_x4_ps(x_ptr, x0, x1, x2, x3);
_mm256_stream_x4_ps(y_ptr + offset + index, x0, x1, x2, x3);
x_ptr += AVX2_FLOAT_STRIDE * 4;
index += AVX2_FLOAT_STRIDE * 4;
sr -= AVX2_FLOAT_STRIDE * 4;
}
if (sr >= AVX2_FLOAT_STRIDE * 2) {
_mm256_load_x2_ps(x_ptr, x0, x1);
_mm256_stream_x2_ps(y_ptr + offset + index, x0, x1);
x_ptr += AVX2_FLOAT_STRIDE * 2;
index += AVX2_FLOAT_STRIDE * 2;
sr -= AVX2_FLOAT_STRIDE * 2;
}
if (sr >= AVX2_FLOAT_STRIDE) {
_mm256_load_x1_ps(x_ptr, x0);
_mm256_stream_x1_ps(y_ptr + offset + index, x0);
}
x_ptr += sr;
offset += r * stride;
}
}
y_ptr += s * r * stride;
}
return SUCCESS;
}
int transpose_unaligned_s(
const uint n, const uint r, const uint s, const uint stride,
infloats x_ptr, outfloats y_ptr) {
#ifdef _DEBUG
if ((stride & AVX2_FLOAT_REMAIN_MASK) == 0) {
return FAILURE_BADPARAM;
}
#endif // _DEBUG
if (stride <= AVX2_FLOAT_STRIDE) {
return transpose_strideleq8_s(n, r, s, stride, x_ptr, y_ptr);
}
if (stride <= AVX2_FLOAT_STRIDE * 2) {
return transpose_stride9to15_s(n, r, s, stride, x_ptr, y_ptr);
}
if (stride <= AVX2_FLOAT_STRIDE * 3) {
return transpose_stride17to23_s(n, r, s, stride, x_ptr, y_ptr);
}
if (stride <= AVX2_FLOAT_STRIDE * 4) {
return transpose_stride25to31_s(n, r, s, stride, x_ptr, y_ptr);
}
const __m256i mask = _mm256_setmask_ps(stride & AVX2_FLOAT_REMAIN_MASK);
__m256 x0, x1, x2, x3;
for (uint th = 0; th < n; th++) {
for (uint k = 0; k < r; k++) {
uint offset = k * stride;
for (uint j = 0; j < s; j++) {
uint sr = stride, index = 0;
while (sr >= AVX2_FLOAT_STRIDE * 4) {
_mm256_loadu_x4_ps(x_ptr, x0, x1, x2, x3);
_mm256_storeu_x4_ps(y_ptr + offset + index, x0, x1, x2, x3);
x_ptr += AVX2_FLOAT_STRIDE * 4;
index += AVX2_FLOAT_STRIDE * 4;
sr -= AVX2_FLOAT_STRIDE * 4;
}
if (sr >= AVX2_FLOAT_STRIDE * 2) {
__m256 x0, x1;
_mm256_loadu_x2_ps(x_ptr, x0, x1);
_mm256_storeu_x2_ps(y_ptr + offset + index, x0, x1);
x_ptr += AVX2_FLOAT_STRIDE * 2;
index += AVX2_FLOAT_STRIDE * 2;
sr -= AVX2_FLOAT_STRIDE * 2;
}
if (sr >= AVX2_FLOAT_STRIDE) {
__m256 x0;
_mm256_loadu_x1_ps(x_ptr, x0);
_mm256_storeu_x1_ps(y_ptr + offset + index, x0);
x_ptr += AVX2_FLOAT_STRIDE;
index += AVX2_FLOAT_STRIDE;
sr -= AVX2_FLOAT_STRIDE;
}
if (sr > 0) {
__m256 x0 = _mm256_loadu_ps(x_ptr);
_mm256_maskstore_ps(y_ptr + offset + index, mask, x0);
}
x_ptr += sr;
offset += r * stride;
}
}
y_ptr += s * r * stride;
}
return SUCCESS;
}
#pragma managed
void AvxBlas::Transform::Transpose(UInt32 n, UInt32 r, UInt32 s, UInt32 stride, Array<float>^ x, Array<float>^ y) {
if (n <= 0 || r <= 0 || s <= 0 || stride <= 0) {
return;
}
Util::CheckProdOverflow(n, r, s, stride);
Util::CheckLength(n * r * s * stride, x, y);
Util::CheckDuplicateArray(x, y);
float* x_ptr = (float*)(x->Ptr.ToPointer());
float* y_ptr = (float*)(y->Ptr.ToPointer());
int ret = UNEXECUTED;
if ((stride & AVX2_FLOAT_REMAIN_MASK) == 0u) {
#ifdef _DEBUG
Console::WriteLine("type aligned");
#endif // _DEBUG
ret = transpose_aligned_s(n, r, s, stride, x_ptr, y_ptr);
}
else {
#ifdef _DEBUG
Console::WriteLine("type unaligned");
#endif // _DEBUG
ret = transpose_unaligned_s(n, r, s, stride, x_ptr, y_ptr);
}
Util::AssertReturnCode(ret);
} | 25.740066 | 133 | 0.513475 | [
"transform"
] |
14b8b4b04758d3e4ad110263f0ff43627f28db58 | 640 | hpp | C++ | lib/GAME_H/gamemap/obstacle.hpp | leogenot/IMACRUN | 9767a6f23d03d8ef61d3aa2bd7c5a8873f3d21b4 | [
"MIT"
] | null | null | null | lib/GAME_H/gamemap/obstacle.hpp | leogenot/IMACRUN | 9767a6f23d03d8ef61d3aa2bd7c5a8873f3d21b4 | [
"MIT"
] | null | null | null | lib/GAME_H/gamemap/obstacle.hpp | leogenot/IMACRUN | 9767a6f23d03d8ef61d3aa2bd7c5a8873f3d21b4 | [
"MIT"
] | 1 | 2021-11-10T13:52:22.000Z | 2021-11-10T13:52:22.000Z | #ifndef OBSTACLE_H
#define OBSTACLE_H
#include "../utilities/shader_m.hpp"
#include "../lighting/light.hpp"
#include "../lighting/sceneLight.hpp"
#include <vector>
class Obstacle
{
private:
Shader m_shader;
unsigned int m_texture;
unsigned int m_VAO;
glm::vec3 m_pos;
public:
Obstacle(glm::vec3 pos, unsigned int texture);
~Obstacle() { glDeleteVertexArrays(1, &m_VAO); };
void draw(glm::mat4 view, glm::mat4 projection, glm::mat4 model, glm::vec3 camPos, SceneLight sceneLight, std::vector<Light*> lights, glm::vec3 playerPos, int renderRadius) const;
glm::vec3 getPos() const {return m_pos;};
};
#endif | 27.826087 | 183 | 0.70625 | [
"vector",
"model"
] |
14beca86272d996219044724a0b99fc93f1565bf | 1,880 | cpp | C++ | src/parser.cpp | Siprj/job-interview-assignment-phonexia | d0761bc480e56499831b379bfdef2a55b6e0ea2e | [
"MIT"
] | null | null | null | src/parser.cpp | Siprj/job-interview-assignment-phonexia | d0761bc480e56499831b379bfdef2a55b6e0ea2e | [
"MIT"
] | null | null | null | src/parser.cpp | Siprj/job-interview-assignment-phonexia | d0761bc480e56499831b379bfdef2a55b6e0ea2e | [
"MIT"
] | null | null | null | #include "parser.h"
#include <iostream>
#include "constants.h"
#include "csv.h"
using namespace std;
using namespace io;
vector<Entry> retrieveData(const char* filePath)
{
// Instantiate CSV reader with three active columns
CSVReader
< 3
, trim_chars<' ', '\t'>
, no_quote_escape<';'>
> inputData(filePath);
try {
inputData.read_header
( ignore_extra_column
, "number"
, "duration"
, "type"
);
}
catch(const exception& e)
{
// Here should be better error handling in case of bigger app.
cerr << e.what();
exit(EXIT_FAILURE);
}
vector<Entry> data;
string number;
int duration;
string stringifiedType;
while(inputData.read_row(number, duration, stringifiedType))
{
Entry entry;
entry.number = number;
entry.duration = duration;
if (stringifiedType.compare(INTERNAL_CALL_STR) == 0)
{
entry.channelType = Call;
entry.destinationType = Internal;
}
else if (stringifiedType.compare(EXTERNAL_CALL_STR) == 0)
{
entry.channelType = Call;
entry.destinationType = External;
}
else if (stringifiedType.compare(INTERNAL_SMS_STR) == 0)
{
entry.channelType = SMS;
entry.destinationType = Internal;
}
else if (stringifiedType.compare(EXTERNAL_SMS_STR) == 0)
{
entry.channelType = SMS;
entry.destinationType = External;
}
else
{
// Here should be better error handling in case of bigger app.
cerr << "Unrecognized entry type: " << stringifiedType << endl;
exit(EXIT_FAILURE);
}
data.push_back(entry);
}
return data;
}
| 23.797468 | 75 | 0.555319 | [
"vector"
] |
14c0e16e62de11cab98b1f41c514f0fb087a8657 | 10,162 | cpp | C++ | DroneUtil.cpp | cps-sei/cps-synth-resolultion | 3834bcd566d5fc4ce3f2c107d5ee3b7d06caf31f | [
"MIT"
] | 1 | 2020-10-01T13:56:35.000Z | 2020-10-01T13:56:35.000Z | DroneUtil.cpp | cps-sei/cps-synth-resolultion | 3834bcd566d5fc4ce3f2c107d5ee3b7d06caf31f | [
"MIT"
] | null | null | null | DroneUtil.cpp | cps-sei/cps-synth-resolultion | 3834bcd566d5fc4ce3f2c107d5ee3b7d06caf31f | [
"MIT"
] | 1 | 2021-06-03T00:09:30.000Z | 2021-06-03T00:09:30.000Z | /*
* Synthesis-based resolution of features/enforcers interactions in CPS
* Copyright 2020 Carnegie Mellon University.
* NO WARRANTY. THIS CARNEGIE MELLON UNIVERSITY AND SOFTWARE ENGINEERING
* INSTITUTE MATERIAL IS FURNISHED ON AN "AS-IS" BASIS. CARNEGIE MELLON
* UNIVERSITY MAKES NO WARRANTIES OF ANY KIND, EITHER EXPRESSED OR IMPLIED,
* AS TO ANY MATTER INCLUDING, BUT NOT LIMITED TO, WARRANTY OF FITNESS FOR
* PURPOSE OR MERCHANTABILITY, EXCLUSIVITY, OR RESULTS OBTAINED FROM USE OF
* THE MATERIAL. CARNEGIE MELLON UNIVERSITY DOES NOT MAKE ANY WARRANTY OF ANY
* KIND WITH RESPECT TO FREEDOM FROM PATENT, TRADEMARK, OR COPYRIGHT
* INFRINGEMENT.
* Released under a BSD (SEI)-style license, please see license.txt or contact
* permission@sei.cmu.edu for full terms.
* [DISTRIBUTION STATEMENT A] This material has been approved for public
* release and unlimited distribution. Please see Copyright notice for
* non-US Government use and distribution.
* This Software includes and/or makes use of the following Third-Party Software
* subject to its own license:
* 1. JsonCpp
* (https://github.com/open-source-parsers/jsoncpp/blob/master/LICENSE)
* Copyright 2010 Baptiste Lepilleur and The JsonCpp Authors.
* DM20-0762
*/
#include "DroneUtil.h"
#include <math.h>
#include <iostream>
#include <fstream>
#include <sstream>
#include <stdlib.h>
#include <stdio.h>
using namespace dronecode_sdk;
namespace droneutil {
float MAX_DRONE_SPEED = 2.00; // m/s
float ENEMY_CHASE_DISTANCE = 4.00; // m
float ENEMY_DRONE_SPEED = 1.6; // m/s
float TICK_DURATION = 0.06; // sec
float TICKS_TO_CORRECT = 5; // Used as the length of the prediction window in estimating signal -- Could be used to make properties violated for N ticks as well
// NOTE: turning off z-velocity stuff might be a bit broken right now -- not supported with all new enforcers
bool USE_Z_VELOCITY = true; // Should we use z velocity? (changes follower and ego z velocity)
bool FOLLOWER_Z_VELOCITY = USE_Z_VELOCITY;
bool EGO_Z_VELOCITY = USE_Z_VELOCITY;
float CATCH_DISTANCE = 0.1; // When is the drone considered to be 'caught'
float RECON_HEIGHT = 1.2; // Desired altitude of recon mission -- used by reconmission.h
float BOUNDARY_WEIGHT = 2;
float RUNAWAY_WEIGHT = 3;
float FLIGHT_WEIGHT = 10;
float RECON_WEIGHT = 1; // Unused
float MISSILE_WEIGHT = 3;
bool NONLINEAR_PENALTY = true; // Used in SigFun.cpp
bool SYNTHESIZE_ACTIONS = true; // Only relevant to RobustnessCoordinator, overwritten by SynthRobustnessCoordinator (to true)
bool CHOOSE_LEAST_DIFFERENT_ACTION = true; // Only relevant to (Synth|)RobustnessCoordinator
unsigned int RANDOM_SEARCH_GRANULARITY = 10; // Only relevant to RobustnessCoordinator w/ synthesis -- determines how rigorously to search the action range (higher=more)
bool SUGGEST_ACTION_RANGE = true; // Used by each enforcer -- if false, each only proposes a single action
unsigned int WAYPOINT_SEED = 0; // Used by reconmission to randomly generate waypoints
float BOUNDARY_X_MIN = -10;
float BOUNDARY_X_MAX = 10;
float BOUNDARY_Y_MIN = -10;
float BOUNDARY_Y_MAX = 10;
float BOUNDARY_Z_MIN = 0;
float BOUNDARY_Z_MAX = 6;
float BOUNDARY_SAFE_TTI_THRESHOLD = 1.5; // Safe TTI threshold used by BoundaryEnforcer
void scaleVector(Offboard::VelocityNEDYaw& vec, float new_magnitude) {
float cur_magnitude = getMagnitude(vec);
float scaling_factor = new_magnitude/cur_magnitude;
vec.north_m_s *= scaling_factor;
vec.east_m_s *= scaling_factor;
vec.down_m_s *= scaling_factor;
}
void scaleToUnitVector(Offboard::VelocityNEDYaw& vec) {
scaleVector(vec, 1);
}
void scaleToMaxVelocity(dronecode_sdk::Offboard::VelocityNEDYaw& vec) {
scaleVector(vec, droneutil::MAX_DRONE_SPEED);
}
float getMagnitude(const Offboard::VelocityNEDYaw& vec) {
return sqrt(vec.north_m_s*vec.north_m_s + vec.east_m_s*vec.east_m_s + vec.down_m_s*vec.down_m_s);
}
// Compute the velocity vector from "current" to "target"
Offboard::VelocityNEDYaw computeNEDtoTarget(float curr_north_m, float curr_east_m, float curr_down_m,
float target_north_m, float target_east_m, float target_down_m,
float speed, float yaw){
float delta_north = target_north_m - curr_north_m;
float delta_east = target_east_m - curr_east_m;
float delta_down = EGO_Z_VELOCITY ? target_down_m - curr_down_m : 0;
float delta = sqrt(pow(delta_north, 2) + pow(delta_east, 2) + pow(delta_down, 2));
Offboard::VelocityNEDYaw velNED;
velNED.north_m_s = (delta_north / delta) * speed;
velNED.east_m_s = (delta_east / delta) * speed;
velNED.down_m_s = (delta_down / delta) * speed;
velNED.yaw_deg = yaw;
return velNED;
}
/* grosssssssss */
void setVar(std::string name, float value) {
if(name == "MAX_DRONE_SPEED") {
MAX_DRONE_SPEED = value;
} else if(name == "ENEMY_CHASE_DISTANCE") {
ENEMY_CHASE_DISTANCE = value;
} else if(name == "ENEMY_DRONE_SPEED") {
ENEMY_DRONE_SPEED = value;
} else if(name == "TICK_DURATION") {
TICK_DURATION = value;
} else if(name == "TICKS_TO_CORRECT") {
TICKS_TO_CORRECT = value;
} else if(name == "USE_Z_VELOCITY") {
USE_Z_VELOCITY = value != 0;
FOLLOWER_Z_VELOCITY = USE_Z_VELOCITY;
EGO_Z_VELOCITY = USE_Z_VELOCITY;
} else if(name == "CATCH_DISTANCE") {
CATCH_DISTANCE = value;
} else if(name == "BOUNDARY_WEIGHT") {
BOUNDARY_WEIGHT = value;
} else if(name == "RUNAWAY_WEIGHT") {
RUNAWAY_WEIGHT = value;
} else if(name == "FLIGHT_WEIGHT") {
FLIGHT_WEIGHT = value;
} else if(name == "MISSILE_WEIGHT") {
MISSILE_WEIGHT = value;
} else if(name == "RECON_WEIGHT") {
RECON_WEIGHT = value;
} else if(name == "RECON_HEIGHT") {
RECON_HEIGHT = value;
} else if(name == "NONLINEAR_PENALTY") {
NONLINEAR_PENALTY = value != 0;
} else if(name == "SYNTHESIZE_ACTIONS") {
SYNTHESIZE_ACTIONS = value != 0;
} else if(name == "CHOOSE_LEAST_DIFFERENT_ACTION") {
CHOOSE_LEAST_DIFFERENT_ACTION = value != 0;
} else if(name == "SUGGEST_ACTION_RANGE") {
SUGGEST_ACTION_RANGE = value != 0;
} else if(name == "WAYPOINT_SEED") {
WAYPOINT_SEED = (unsigned int)value;
} else if(name == "BOUNDARY_X_MIN") {
BOUNDARY_X_MIN = value;
} else if(name == "BOUNDARY_X_MAX") {
BOUNDARY_X_MAX = value;
} else if(name == "BOUNDARY_Y_MIN") {
BOUNDARY_Y_MIN = value;
} else if(name == "BOUNDARY_Y_MAX") {
BOUNDARY_Y_MAX = value;
} else if(name == "BOUNDARY_Z_MIN") {
BOUNDARY_Z_MIN = value;
} else if(name == "BOUNDARY_SAFE_TTI_THRESHOLD") {
BOUNDARY_SAFE_TTI_THRESHOLD = value;
} else if(name == "BOUNDARY_SIZE") {
BOUNDARY_X_MIN = -value;
BOUNDARY_X_MAX = value;
BOUNDARY_Y_MIN = -value;
BOUNDARY_Y_MAX = value;
BOUNDARY_Z_MIN = -value; // We don't really want this anywho
BOUNDARY_Z_MAX = value;
} else if(name == "RANDOM_SEARCH_GRANULARITY") {
RANDOM_SEARCH_GRANULARITY = value;
} else {
fprintf(stderr, "Unknown variable name: %s, %f\n", name.c_str(), value);
}
}
void parseConfig(std::string fname){
std::ifstream infile(fname);
std::string line;
while (std::getline(infile, line)) {
std::istringstream iss(line);
std::string name;
float val;
if (!(iss >> name >> val)) { break; } // error
setVar(name, val);
std::cout << name << ":" << val << std::endl;
}
}
double getAngle(double deltaX, double deltaY){
double deg = atan(deltaY / deltaX) * 180.0 / M_PI;
// for clock-wise 0-north angles
if (deltaX < 0) {
deg += 180;
} else if (deltaY < 0) {
deg += 360;
}
return deg;
}
dronecode_sdk::Telemetry::PositionNED pos2ned(const dronecode_sdk::Telemetry::Position& pos, const dronecode_sdk::Telemetry::Position& origin) {
dronecode_sdk::Telemetry::PositionNED ned;
// based on formulas from https://www.movable-type.co.uk/scripts/latlong.html
const double R = 6371e3; // metres
const double DEG_TO_RAD = M_PI / 180.0;
double phi1 = origin.latitude_deg * DEG_TO_RAD;
double phi2 = pos.latitude_deg * DEG_TO_RAD;
double deltaLambda = (pos.longitude_deg - origin.longitude_deg) * DEG_TO_RAD;
double x = deltaLambda * cos((phi1 + phi2)/2);
double y = (phi2-phi1);
ned.north_m = y * R;
ned.east_m = x * R;
/* NOTE/IMPORTANT: This is inaccurate a lot of the time bc origin altitudes vary depending on some timing stuff?
* Need to fix z velocity outside */
// negative bc down position is opposite up position (altitude)
ned.down_m = -(pos.absolute_altitude_m - origin.absolute_altitude_m);
ned.down_m = -(pos.absolute_altitude_m - origin.absolute_altitude_m);
return ned;
}
bool cmp(const dronecode_sdk::Offboard::VelocityNEDYaw& v1, const dronecode_sdk::Offboard::VelocityNEDYaw& v2, float epsilon){
// Ensure magnitudes are equivalent before comparing -- NOTE: scale the vectors if they're not
assert(getMagnitude(v1) == getMagnitude(v2));
bool is_eq =
(fabsf(v1.north_m_s - v2.north_m_s) < epsilon) &&
(fabsf(v1.east_m_s - v2.east_m_s ) < epsilon) &&
(fabsf(v1.down_m_s - v2.down_m_s ) < epsilon);
return is_eq;
}
/*
* Quantify the similarity between two vectors
* Using cosine similarity measure
* Note: Doesn't take into account vector magnitude
* https://en.wikipedia.org/wiki/Cosine_similarity
*/
double cosineSimilarity(const Offboard::VelocityNEDYaw& v1, const Offboard::VelocityNEDYaw& v2) {
double mag_product = getMagnitude(v1) * getMagnitude(v2);
double dot_product = v1.north_m_s * v2.north_m_s +
v1.east_m_s * v2.east_m_s +
v1.down_m_s * v2.down_m_s;
return dot_product/mag_product;
}
}
| 37.498155 | 172 | 0.67595 | [
"vector"
] |
14d44ff02ac73a7d7b0a933264fc3a4f1148ba2e | 9,833 | cxx | C++ | GUISupport/Qt/vtkQtItemView.cxx | garyc618/GitTagBug | 0b1cdbf5a6f6b9b23fa03ff1d9f4a84953831864 | [
"BSD-3-Clause"
] | 1 | 2019-05-31T06:45:40.000Z | 2019-05-31T06:45:40.000Z | GUISupport/Qt/vtkQtItemView.cxx | garyc618/GitTagBug | 0b1cdbf5a6f6b9b23fa03ff1d9f4a84953831864 | [
"BSD-3-Clause"
] | null | null | null | GUISupport/Qt/vtkQtItemView.cxx | garyc618/GitTagBug | 0b1cdbf5a6f6b9b23fa03ff1d9f4a84953831864 | [
"BSD-3-Clause"
] | null | null | null | /*=========================================================================
Program: Visualization Toolkit
Module: vtkQtItemView.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.
=========================================================================*/
/*-------------------------------------------------------------------------
Copyright 2008 Sandia Corporation.
Under the terms of Contract DE-AC04-94AL85000 with Sandia Corporation,
the U.S. Government retains certain rights in this software.
-------------------------------------------------------------------------*/
#include "vtkQtItemView.h"
#include <QObject>
#include <QAbstractItemView>
#include <QAbstractItemModel>
#include <QItemSelectionModel>
#include "vtkAlgorithm.h"
#include "vtkAlgorithmOutput.h"
#include "vtkCommand.h"
#include "vtkConvertSelection.h"
#include "vtkDataRepresentation.h"
#include "vtkDataSet.h"
#include "vtkFieldData.h"
#include "vtkGraph.h"
#include "vtkIdTypeArray.h"
#include "vtkInformation.h"
#include "vtkObjectFactory.h"
#include "vtkPointData.h"
#include "vtkSelection.h"
#include "vtkSelectionLink.h"
#include "vtkSelectionNode.h"
#include "vtkSmartPointer.h"
#include "vtkVariant.h"
vtkCxxRevisionMacro(vtkQtItemView, "1.7");
vtkStandardNewMacro(vtkQtItemView);
// Signal helper class
void vtkQtSignalHandler::slotSelectionChanged(const QItemSelection& s1, const QItemSelection& s2)
{
this->Target->QtSelectionChanged(s1, s2);
}
//----------------------------------------------------------------------------
vtkQtItemView::vtkQtItemView()
{
// Set my view and model adapter to NULL
this->ItemViewPtr = 0;
this->ModelAdapterPtr = 0;
this->SelectionModel = 0;
// Initialize selecting to false
this->Selecting = false;
this->IOwnSelectionModel = false;
// Funny little hook to get around multiple inheritance
this->SignalHandler.setTarget(this);
}
//----------------------------------------------------------------------------
vtkQtItemView::~vtkQtItemView()
{
//if(this->IOwnSelectionModel && this->SelectionModel)
// {
// delete this->SelectionModel;
// this->SelectionModel = 0;
// }
}
// Description:
// Just a convenience function for making sure
// that the view and model pointers are valid
int vtkQtItemView::CheckViewAndModelError()
{
// Sub-classes might use their own views, so don't insist that a view has been set
//if (this->ItemViewPtr == 0)
// {
// vtkErrorMacro("Trying to use vtkQtItemView with in invalid View");
// return 1;
// }
if (this->ModelAdapterPtr == 0)
{
vtkErrorMacro("Trying to use vtkQtItemView with in invalid ModelAdapter");
return 1;
}
return 0;
}
//----------------------------------------------------------------------------
void vtkQtItemView::SetItemView(QAbstractItemView *qiv)
{
// Set up my internals to point to the new view
this->ItemViewPtr = qiv;
}
//----------------------------------------------------------------------------
QAbstractItemView* vtkQtItemView::GetItemView()
{
return this->ItemViewPtr;
}
//----------------------------------------------------------------------------
void vtkQtItemView::SetItemModelAdapter(vtkQtAbstractModelAdapter* qma)
{
// Set up my internals to point to the new view
this->ModelAdapterPtr = qma;
if(this->SelectionModel)
{
delete this->SelectionModel;
this->SelectionModel = 0;
this->IOwnSelectionModel = false;
}
}
//----------------------------------------------------------------------------
vtkQtAbstractModelAdapter* vtkQtItemView::GetItemModelAdapter()
{
return this->ModelAdapterPtr;
}
//----------------------------------------------------------------------------
QItemSelectionModel* vtkQtItemView::GetSelectionModel()
{
// If a view has been set, use its selection model
if(this->ItemViewPtr)
{
return this->ItemViewPtr->selectionModel();
}
// Otherwise, create one of our own (if we haven't already done so)
// using the item model.
if(!this->SelectionModel)
{
this->SelectionModel = new QItemSelectionModel(this->ModelAdapterPtr);
this->IOwnSelectionModel = true;
}
return this->SelectionModel;
}
//----------------------------------------------------------------------------
void vtkQtItemView::AddInputConnection( int vtkNotUsed(port), int vtkNotUsed(index),
vtkAlgorithmOutput* conn, vtkAlgorithmOutput* vtkNotUsed(selectionConn))
{
// Make sure I have a view and a model
if (CheckViewAndModelError()) return;
// Hand VTK data off to the adapter
conn->GetProducer()->Update();
vtkDataObject *d = conn->GetProducer()->GetOutputDataObject(0);
this->ModelAdapterPtr->SetVTKDataObject(d);
// Sub-classes might use their own views, so don't assume the view has been set
if(this->ItemViewPtr)
{
this->ItemViewPtr->setModel(this->ModelAdapterPtr);
this->ItemViewPtr->update();
// Setup selction links
this->ItemViewPtr->setSelectionMode(QAbstractItemView::ExtendedSelection);
}
QObject::connect(this->GetSelectionModel(), SIGNAL(selectionChanged(const QItemSelection&,const QItemSelection&)),
&this->SignalHandler, SLOT(slotSelectionChanged(const QItemSelection&,const QItemSelection&)));
}
//----------------------------------------------------------------------------
void vtkQtItemView::RemoveInputConnection(int vtkNotUsed(port), int vtkNotUsed(index),
vtkAlgorithmOutput* conn, vtkAlgorithmOutput* vtkNotUsed(selectionConn))
{
// Make sure I have a view and a model
if (CheckViewAndModelError()) return;
// Remove VTK data from the adapter
conn->GetProducer()->Update();
vtkDataObject *d = conn->GetProducer()->GetOutputDataObject(0);
if (this->ModelAdapterPtr->GetVTKDataObject() == d)
{
this->ModelAdapterPtr->SetVTKDataObject(0);
// Sub-classes might use their own views, so don't assume the view has been set
if(this->ItemViewPtr)
{
this->ItemViewPtr->update();
}
}
}
//----------------------------------------------------------------------------
void vtkQtItemView::QtSelectionChanged(const QItemSelection&, const QItemSelection&)
{
// Make sure I have a view and a model
if (CheckViewAndModelError()) return;
this->Selecting = true;
// Create index selection
vtkSmartPointer<vtkSelection> selection =
vtkSmartPointer<vtkSelection>::New();
vtkSmartPointer<vtkSelectionNode> node =
vtkSmartPointer<vtkSelectionNode>::New();
node->SetContentType(vtkSelectionNode::INDICES);
node->SetFieldType(vtkSelectionNode::VERTEX);
vtkSmartPointer<vtkIdTypeArray> idarr =
vtkSmartPointer<vtkIdTypeArray>::New();
node->SetSelectionList(idarr);
selection->AddNode(node);
const QModelIndexList list = this->GetSelectionModel()->selectedRows();
// For index selection do this odd little dance with two maps :)
for (int i = 0; i < list.size(); i++)
{
vtkIdType pid = this->ModelAdapterPtr->QModelIndexToPedigree(list.at(i));
idarr->InsertNextValue(this->ModelAdapterPtr->PedigreeToId(pid));
}
// Convert to the correct type of selection
vtkDataObject* data = this->ModelAdapterPtr->GetVTKDataObject();
vtkSmartPointer<vtkSelection> converted;
converted.TakeReference(vtkConvertSelection::ToSelectionType(
selection, data, this->SelectionType, this->SelectionArrayNames));
// Call select on the representation
this->GetRepresentation()->Select(this, converted);
// Invoke selection changed event
this->Selecting = false;
}
//----------------------------------------------------------------------------
void vtkQtItemView::ProcessEvents(
vtkObject* caller,
unsigned long eventId,
void* callData)
{
Superclass::ProcessEvents(caller, eventId, callData);
}
//----------------------------------------------------------------------------
void vtkQtItemView::Update()
{
// Make sure I have a view and a model
if (CheckViewAndModelError()) return;
vtkDataRepresentation* rep = this->GetRepresentation();
if (!rep)
{
return;
}
// Make the data current
vtkAlgorithm* alg = rep->GetInputConnection()->GetProducer();
alg->Update();
vtkDataObject *d = alg->GetOutputDataObject(0);
this->ModelAdapterPtr->SetVTKDataObject(d);
// Make the selection current
if (this->Selecting)
{
// If we initiated the selection, do nothing.
return;
}
vtkSelection* s = rep->GetSelectionLink()->GetSelection();
vtkSmartPointer<vtkSelection> selection;
selection.TakeReference(vtkConvertSelection::ToIndexSelection(s, d));
QItemSelection list;
vtkSelectionNode* node = selection->GetNode(0);
if (node)
{
vtkIdTypeArray* arr = vtkIdTypeArray::SafeDownCast(node->GetSelectionList());
if (arr)
{
for (vtkIdType i = 0; i < arr->GetNumberOfTuples(); i++)
{
vtkIdType id = arr->GetValue(i);
QModelIndex index =
this->ModelAdapterPtr->PedigreeToQModelIndex(
this->ModelAdapterPtr->IdToPedigree(id));
list.select(index, index);
}
}
}
this->GetSelectionModel()->select(list,
QItemSelectionModel::ClearAndSelect | QItemSelectionModel::Rows);
// Sub-classes might use their own views, so don't assume the view has been set
if(this->ItemViewPtr)
{
this->ItemViewPtr->update();
}
}
//----------------------------------------------------------------------------
void vtkQtItemView::PrintSelf(ostream& os, vtkIndent indent)
{
this->Superclass::PrintSelf(os,indent);
}
| 31.215873 | 116 | 0.620462 | [
"model"
] |
14d57fe6a449f43d8482dace6b72d4885cd7dc8b | 2,123 | cpp | C++ | 2019/day4/cpp/src/test.cpp | ivobatkovic/advent-of-code | e43489bcd2307f0f3ac8b0ec4e850f0a201f9944 | [
"MIT"
] | 3 | 2019-12-14T16:24:50.000Z | 2020-12-06T16:40:13.000Z | 2019/day4/cpp/src/test.cpp | ivobatkovic/advent-of-code | e43489bcd2307f0f3ac8b0ec4e850f0a201f9944 | [
"MIT"
] | 4 | 2019-12-03T14:18:13.000Z | 2020-12-03T08:29:32.000Z | 2019/day4/cpp/src/test.cpp | ivobatkovic/advent-of-code | e43489bcd2307f0f3ac8b0ec4e850f0a201f9944 | [
"MIT"
] | 2 | 2019-12-06T07:25:57.000Z | 2020-12-08T12:42:37.000Z | #include <gtest/gtest.h>
#include <iostream>
#include <tuple>
#include "2019/day4/cpp/include/digits.hpp"
using std::string;
using std::vector;
typedef std::tuple<string, bool> testInput;
class DigitsPartOne : public ::testing::TestWithParam<testInput> {};
class DigitsPartTwo : public ::testing::TestWithParam<testInput> {};
TEST_P(DigitsPartOne, partOne) {
// Get parameters
auto param = GetParam();
// Check if input is monotonic
string input = std::get<0>(param);
string monotonic_digit = Digits::make_monotonic(input);
bool monotonic = (monotonic_digit == input) ? true : false;
// Check if input satisfies montonicity and double digits
bool is_double_digit = Digits::double_digit(monotonic_digit);
bool double_digits = (monotonic & is_double_digit) ? true : false;
// Compare output with desired output
EXPECT_EQ(std::get<1>(param), double_digits);
}
TEST_P(DigitsPartTwo, partTwo) {
// Get parameters
auto param = GetParam();
// Check if input is monotonic
string input = std::get<0>(param);
string monotonic_digit = Digits::make_monotonic(input);
bool monotonic = (monotonic_digit == input) ? true : false;
// Check if input satisfies montonicity and double digits
bool is_double_digit = Digits::double_digit_no_adjacent(monotonic_digit);
bool double_digits = (monotonic & is_double_digit) ? true : false;
// Compare output with desired output
EXPECT_EQ(std::get<1>(param), double_digits);
}
INSTANTIATE_TEST_SUITE_P(partOne, DigitsPartOne,
::testing::Values(std::make_tuple("111111", true),
std::make_tuple("223450", false),
std::make_tuple("123789", false)));
INSTANTIATE_TEST_SUITE_P(partTwo, DigitsPartTwo,
::testing::Values(std::make_tuple("112233", true),
std::make_tuple("123444", false),
std::make_tuple("111122", true)));
int main(int argc, char **argv) {
testing::InitGoogleTest(&argc, argv);
return RUN_ALL_TESTS();
}
| 33.171875 | 78 | 0.654734 | [
"vector"
] |
14d70bb116fe4d98de02627148ec10a41fa7dd50 | 2,001 | hpp | C++ | openscenario/openscenario_interpreter/include/openscenario_interpreter/syntax/parameter_declarations.hpp | autocore-ai/scenario_simulator_v2 | bb9569043e20649f0e4390e9225b6bb7b4de10b6 | [
"Apache-2.0"
] | null | null | null | openscenario/openscenario_interpreter/include/openscenario_interpreter/syntax/parameter_declarations.hpp | autocore-ai/scenario_simulator_v2 | bb9569043e20649f0e4390e9225b6bb7b4de10b6 | [
"Apache-2.0"
] | null | null | null | openscenario/openscenario_interpreter/include/openscenario_interpreter/syntax/parameter_declarations.hpp | autocore-ai/scenario_simulator_v2 | bb9569043e20649f0e4390e9225b6bb7b4de10b6 | [
"Apache-2.0"
] | null | null | null | // Copyright 2015-2020 Tier IV, Inc. 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.
#ifndef OPENSCENARIO_INTERPRETER__SYNTAX__PARAMETER_DECLARATIONS_HPP_
#define OPENSCENARIO_INTERPRETER__SYNTAX__PARAMETER_DECLARATIONS_HPP_
#include <openscenario_interpreter/reader/element.hpp>
#include <openscenario_interpreter/scope.hpp>
#include <openscenario_interpreter/syntax/parameter_declaration.hpp>
#include <vector>
namespace openscenario_interpreter
{
inline namespace syntax
{
/* ---- ParameterDeclarations --------------------------------------------------
*
* <xsd:complexType name="ParameterDeclarations">
* <xsd:sequence>
* <xsd:element name="ParameterDeclaration" minOccurs="0" maxOccurs="unbounded" type="ParameterDeclaration"/>
* </xsd:sequence>
* </xsd:complexType>
*
* -------------------------------------------------------------------------- */
struct ParameterDeclarations : public std::vector<ParameterDeclaration>
{
ParameterDeclarations() = default;
template <typename Node, typename Scope>
explicit ParameterDeclarations(const Node & node, Scope & outer_scope)
{
callWithElements(node, "ParameterDeclaration", 0, unbounded, [&](auto && each) {
return emplace_back(each, outer_scope);
});
}
};
std::ostream & operator<<(std::ostream &, const ParameterDeclarations &);
} // namespace syntax
} // namespace openscenario_interpreter
#endif // OPENSCENARIO_INTERPRETER__SYNTAX__PARAMETER_DECLARATIONS_HPP_
| 37.055556 | 114 | 0.714143 | [
"vector"
] |
14dabc7527c84766e1739393e832240f55fc34ca | 413 | cpp | C++ | leetcode/198.cpp | 01nomagic/Algorithms | b184aa12141f5127baa55502d3ea47ccd1f97ba8 | [
"MIT"
] | 2 | 2021-03-27T03:23:20.000Z | 2021-08-11T12:54:17.000Z | leetcode/198.cpp | 01nomagic/Algorithms | b184aa12141f5127baa55502d3ea47ccd1f97ba8 | [
"MIT"
] | null | null | null | leetcode/198.cpp | 01nomagic/Algorithms | b184aa12141f5127baa55502d3ea47ccd1f97ba8 | [
"MIT"
] | null | null | null | #include "./leetcode.hpp"
class Solution {
public:
int rob(vector<int> &nums) {
vector<int> dp;
for (int i = 0; i < nums.size(); i += 1) {
if (i == 0) {
dp.push_back(nums[i]);
} else if (i == 1) {
dp.push_back(max(dp[0], nums[i]));
} else {
dp.push_back(max(dp[i - 2] + nums[i], dp[i - 1]));
}
}
return dp.back();
}
}; | 22.944444 | 60 | 0.433414 | [
"vector"
] |
14dc47fbf2f9962dfbb5dd57baf70a2e1931f7c6 | 5,341 | inl | C++ | Gems/EMotionFX/Code/MCore/Source/Algorithms.inl | aaarsene/o3de | 37e3b0226958974defd14dd6d808e8557dcd7345 | [
"Apache-2.0",
"MIT"
] | 1 | 2021-09-13T00:01:12.000Z | 2021-09-13T00:01:12.000Z | Gems/EMotionFX/Code/MCore/Source/Algorithms.inl | aaarsene/o3de | 37e3b0226958974defd14dd6d808e8557dcd7345 | [
"Apache-2.0",
"MIT"
] | null | null | null | Gems/EMotionFX/Code/MCore/Source/Algorithms.inl | aaarsene/o3de | 37e3b0226958974defd14dd6d808e8557dcd7345 | [
"Apache-2.0",
"MIT"
] | 1 | 2021-07-20T11:07:25.000Z | 2021-07-20T11:07:25.000Z | /*
* Copyright (c) Contributors to the Open 3D Engine Project. For complete copyright and license terms please see the LICENSE at the root of this distribution.
*
* SPDX-License-Identifier: Apache-2.0 OR MIT
*
*/
// calculate the cube root
MCORE_INLINE float CubeRoot(float x)
{
if (x > 0.0f)
{
return Math::Pow(x, 0.333333f);
}
else if (x < 0.0f)
{
return -Math::Pow(-x, 0.333333f);
}
return 0.0f;
}
// calculate the cosine interpolation weight value
MCORE_INLINE float CalcCosineInterpolationWeight(float linearValue)
{
return (1.0f - Math::Cos(linearValue * Math::pi)) * 0.5f;
}
// linear interpolate
template <class T>
MCORE_INLINE T LinearInterpolate(const T& source, const T& target, float timeValue)
{
return static_cast<T>(source * (1.0f - timeValue) + (timeValue * target));
}
// cosine interpolate
template <class T>
MCORE_INLINE T CosineInterpolate(const T& source, const T& target, float timeValue)
{
const float weight = CalcCosineInterpolationWeight(timeValue);
return source * (1.0f - weight) + (weight * target);
}
// barycentric interpolation
template <class T>
MCORE_INLINE T BarycentricInterpolate(float u, float v, const T& pointA, const T& pointB, const T& pointC)
{
return (1.0f - u - v) * pointA + u * pointB + v * pointC;
}
// swap two values
template <class T>
MCORE_INLINE void Swap(T& a, T& b)
{
// don't do anything when both items are the same
if (&a == &b)
{
return;
}
const T temp(std::move(a));
a = std::move(b);
b = std::move(temp);
/* T tempObj = a;
a = b;
b = tempObj;*/
}
// get the minimum of two values
template <class T>
MCORE_INLINE T Min(T a, T b)
{
return (a < b) ? a : b;
}
// get the maximum of two values
template <class T>
MCORE_INLINE T Max(T a, T b)
{
return (a > b) ? a : b;
}
// get the minimum of 3 values
template <class T>
MCORE_INLINE T Min3(T a, T b, T c)
{
return Min(Min(a, b), c);
}
// get the maximum of three values
template <class T>
MCORE_INLINE T Max3(T a, T b, T c)
{
return Max(Max(a, b), c);
}
// return -1 in case of a negative value, 0 when zero, or +1 when positive
template <class T>
MCORE_INLINE T Sgn(T A)
{
return (A > (T)0) ? (T)1 : ((A < (T)0) ? (T)-1 : (T)0);
}
// the square of the value
template <class T>
MCORE_INLINE T Square(T x)
{
return x * x;
}
// the square of the value, same like Square, but with another name
template <class T>
MCORE_INLINE T Sqr(T x)
{
return x * x;
}
// check if a value is negative or not
// TODO: use intel optimization here by checking the bits? (when compiling for PC)
template <class T>
MCORE_INLINE bool IsNegative(T x)
{
return (x < 0);
}
// check if a value is positive or not
// TODO: use intel optimization here by checking the bits? (when compiling for PC)
template <class T>
MCORE_INLINE bool IsPositive(T x)
{
return (x >= 0);
}
// clamp/clip a value to a given range
template <class T>
MCORE_INLINE T Clamp(T x, T min, T max)
{
if (x < min)
{
x = min;
}
if (x > max)
{
x = max;
}
return x;
}
// check if value x is within a given range
template <class T>
MCORE_INLINE bool InRange(T x, T low, T high)
{
return ((x >= low) && (x <= high));
}
// sample an ease-in/out curve
MCORE_INLINE float SampleEaseInOutCurve(float t, float k1, float k2)
{
const float f = k1 * 2.0f / MCore::Math::pi + k2 - k1 + (1.0f - k2) * 2.0f / MCore::Math::pi;
if (t < k1) // ease in section
{
return (k1 * (2.0f / MCore::Math::pi) * (MCore::Math::Sin((t / k1) * MCore::Math::halfPi - MCore::Math::halfPi) + 1.0f)) / f;
}
else
if (t < k2) // mid section
{
return (k1 / MCore::Math::halfPi + t - k1) / f;
}
else // ease out section
{
return ((k1 / MCore::Math::halfPi) + k2 - k1 + ((1.0f - k2) * (2.0f / MCore::Math::pi) * MCore::Math::Sin(((t - k2) / (1.0f - k2)) * MCore::Math::halfPi))) / f;
}
}
// ease-in/out interpolation
template <class T>
MCORE_INLINE T EaseInOutInterpolate(const T& source, const T& target, float timeValue, float k1, float k2)
{
const float t = SampleEaseInOutCurve(timeValue, k1, k2);
return source + t * (target - source);
}
// sample an ease-in-out curve with smoothness control
// basically this is a much simplified TCB spline
MCORE_INLINE float SampleEaseInOutCurveWithSmoothness(float t, float easeInSmoothness, float easeOutSmoothness)
{
const float continuity = -1.0f + easeInSmoothness;
const float tangentA = -(1.0f + continuity) * 0.5f + (1.0f - continuity) * 0.5f;
const float continuity2 = -1.0f + easeOutSmoothness;
const float tangentB = -(1.0f + continuity2) * 0.5f + (1.0f - continuity2) * 0.5f;
const float t2 = t * t;
const float t3 = t2 * t;
return (-2 * t3 + 3 * t2) +
(t3 + -2 * t2 + t) * tangentA +
(t3 + -t2) * tangentB;
}
// interpolate with ease-in out with smoothness
template <class T>
MCORE_INLINE T EaseInOutWithSmoothnessInterpolate(const T& source, const T& target, float timeValue, float easeInSmoothness, float easeOutSmoothness)
{
const float t = MCore::SampleEaseInOutCurveWithSmoothness(timeValue, easeInSmoothness, easeOutSmoothness);
return source + t * (target - source);
}
| 23.221739 | 168 | 0.630032 | [
"3d"
] |
14df71fa33f317cb4b39102dffe20e8faa8869d1 | 417 | cpp | C++ | LeetCode/349_Intersection_of_Two_Arrays/main.cpp | sungmen/Acmicpc_Solve | 0298a6aec84993a4d8767bd2c00490b7201e06a4 | [
"MIT"
] | null | null | null | LeetCode/349_Intersection_of_Two_Arrays/main.cpp | sungmen/Acmicpc_Solve | 0298a6aec84993a4d8767bd2c00490b7201e06a4 | [
"MIT"
] | null | null | null | LeetCode/349_Intersection_of_Two_Arrays/main.cpp | sungmen/Acmicpc_Solve | 0298a6aec84993a4d8767bd2c00490b7201e06a4 | [
"MIT"
] | null | null | null | class Solution {
public:
vector<int> intersection(vector<int>& nums1, vector<int>& nums2) {
map<int, int> m;
for (auto i : nums1) {
m[i] = 1;
}
vector<int> ans;
set<int> s;
for (auto i : nums2) {
s.insert(i);
}
for (auto i : s) {
if (m.find(i) != m.end()) ans.push_back(i);
}
return ans;
}
};
| 21.947368 | 70 | 0.42446 | [
"vector"
] |
14e1bf33c8987e5b38a51ae994bbb5d18c0818c8 | 1,159 | hh | C++ | y3_cluster_cpp/utils/mz_power_law.hh | marcpaterno/gpuintegration | 79144c35f05ad99879d06b571291ac1700dd9026 | [
"BSD-3-Clause"
] | 2 | 2020-04-16T13:34:28.000Z | 2020-05-09T17:11:25.000Z | y3_cluster_cpp/utils/mz_power_law.hh | marcpaterno/gpuintegration | 79144c35f05ad99879d06b571291ac1700dd9026 | [
"BSD-3-Clause"
] | null | null | null | y3_cluster_cpp/utils/mz_power_law.hh | marcpaterno/gpuintegration | 79144c35f05ad99879d06b571291ac1700dd9026 | [
"BSD-3-Clause"
] | 1 | 2019-07-19T19:18:07.000Z | 2019-07-19T19:18:07.000Z | #ifndef Y3_CLUSTER_MZ_POWER_LAW_HH
#define Y3_CLUSTER_MZ_POWER_LAW_HH
#include <cmath>
namespace y3_cluster {
// mz_power_law represents a commonly-used power law relationship, with the
// form
// A * m**B * (1+z)**C
// with A, B and C being constants set in the construction of the power law
// object.
class mz_power_law {
public:
mz_power_law(double A, double B, double C) noexcept;
// The function call operator evaluates the power law at the given
// values of lnM and z. Note that the first parameter is not mass,
// but ln(mass).
double operator()(double lnM, double z) const noexcept;
private:
double const log_A_;
double const B_;
double const C_;
};
} // namespace y3_cluster
inline y3_cluster::mz_power_law::mz_power_law(double A,
double B,
double C) noexcept
: log_A_(std::log(A)), B_(B), C_(C)
{}
inline double
y3_cluster::mz_power_law::operator()(double lnM, double z) const noexcept
{
double const log_res = B_ * lnM + C_ * std::log1p(z) + log_A_;
return std::exp(log_res);
}
#endif
| 27.595238 | 77 | 0.638481 | [
"object"
] |
14e5649318571d2601bb2a99442cb31522106a78 | 21,442 | cpp | C++ | src/modules/osg/generated_code/BufferData.pypp.cpp | cmbruns/osgpyplusplus | f8bfca2cf841e15f6ddb41c958f3ad0d0b9e4b75 | [
"BSD-3-Clause"
] | 3 | 2017-04-20T09:11:47.000Z | 2021-04-29T19:24:03.000Z | src/modules/osg/generated_code/BufferData.pypp.cpp | cmbruns/osgpyplusplus | f8bfca2cf841e15f6ddb41c958f3ad0d0b9e4b75 | [
"BSD-3-Clause"
] | null | null | null | src/modules/osg/generated_code/BufferData.pypp.cpp | cmbruns/osgpyplusplus | f8bfca2cf841e15f6ddb41c958f3ad0d0b9e4b75 | [
"BSD-3-Clause"
] | null | null | null | // This file has been generated by Py++.
#include "boost/python.hpp"
#include "wrap_osg.h"
#include "wrap_referenced.h"
#include "BufferData.pypp.hpp"
namespace bp = boost::python;
struct BufferData_wrapper : osg::BufferData, bp::wrapper< osg::BufferData > {
struct ModifiedCallback_wrapper : osg::BufferData::ModifiedCallback, bp::wrapper< osg::BufferData::ModifiedCallback > {
virtual char const * className( ) const {
if( bp::override func_className = this->get_override( "className" ) )
return func_className( );
else{
return this->osg::BufferData::ModifiedCallback::className( );
}
}
char const * default_className( ) const {
return osg::BufferData::ModifiedCallback::className( );
}
virtual ::osg::Object * clone( ::osg::CopyOp const & copyop ) const {
if( bp::override func_clone = this->get_override( "clone" ) )
return func_clone( boost::ref(copyop) );
else{
return this->osg::BufferData::ModifiedCallback::clone( boost::ref(copyop) );
}
}
::osg::Object * default_clone( ::osg::CopyOp const & copyop ) const {
return osg::BufferData::ModifiedCallback::clone( boost::ref(copyop) );
}
virtual ::osg::Object * cloneType( ) const {
if( bp::override func_cloneType = this->get_override( "cloneType" ) )
return func_cloneType( );
else{
return this->osg::BufferData::ModifiedCallback::cloneType( );
}
}
::osg::Object * default_cloneType( ) const {
return osg::BufferData::ModifiedCallback::cloneType( );
}
virtual bool isSameKindAs( ::osg::Object const * obj ) const {
if( bp::override func_isSameKindAs = this->get_override( "isSameKindAs" ) )
return func_isSameKindAs( boost::python::ptr(obj) );
else{
return this->osg::BufferData::ModifiedCallback::isSameKindAs( boost::python::ptr(obj) );
}
}
bool default_isSameKindAs( ::osg::Object const * obj ) const {
return osg::BufferData::ModifiedCallback::isSameKindAs( boost::python::ptr(obj) );
}
virtual char const * libraryName( ) const {
if( bp::override func_libraryName = this->get_override( "libraryName" ) )
return func_libraryName( );
else{
return this->osg::BufferData::ModifiedCallback::libraryName( );
}
}
char const * default_libraryName( ) const {
return osg::BufferData::ModifiedCallback::libraryName( );
}
virtual void modified( ::osg::BufferData * arg0 ) const {
if( bp::override func_modified = this->get_override( "modified" ) )
func_modified( boost::python::ptr(arg0) );
else{
this->osg::BufferData::ModifiedCallback::modified( boost::python::ptr(arg0) );
}
}
void default_modified( ::osg::BufferData * arg0 ) const {
osg::BufferData::ModifiedCallback::modified( boost::python::ptr(arg0) );
}
};
virtual ::osg::Array * asArray( ) {
if( bp::override func_asArray = this->get_override( "asArray" ) )
return func_asArray( );
else{
return this->osg::BufferData::asArray( );
}
}
::osg::Array * default_asArray( ) {
return osg::BufferData::asArray( );
}
virtual ::osg::Array const * asArray( ) const {
if( bp::override func_asArray = this->get_override( "asArray" ) )
return func_asArray( );
else{
return this->osg::BufferData::asArray( );
}
}
::osg::Array const * default_asArray( ) const {
return osg::BufferData::asArray( );
}
virtual char const * className( ) const {
if( bp::override func_className = this->get_override( "className" ) )
return func_className( );
else{
return this->osg::BufferData::className( );
}
}
char const * default_className( ) const {
return osg::BufferData::className( );
}
virtual ::GLvoid const * getDataPointer( ) const {
bp::override func_getDataPointer = this->get_override( "getDataPointer" );
return func_getDataPointer( );
}
virtual unsigned int getTotalDataSize( ) const {
bp::override func_getTotalDataSize = this->get_override( "getTotalDataSize" );
return func_getTotalDataSize( );
}
virtual bool isSameKindAs( ::osg::Object const * obj ) const {
if( bp::override func_isSameKindAs = this->get_override( "isSameKindAs" ) )
return func_isSameKindAs( boost::python::ptr(obj) );
else{
return this->osg::BufferData::isSameKindAs( boost::python::ptr(obj) );
}
}
bool default_isSameKindAs( ::osg::Object const * obj ) const {
return osg::BufferData::isSameKindAs( boost::python::ptr(obj) );
}
virtual char const * libraryName( ) const {
if( bp::override func_libraryName = this->get_override( "libraryName" ) )
return func_libraryName( );
else{
return this->osg::BufferData::libraryName( );
}
}
char const * default_libraryName( ) const {
return osg::BufferData::libraryName( );
}
virtual void resizeGLObjectBuffers( unsigned int maxSize ) {
if( bp::override func_resizeGLObjectBuffers = this->get_override( "resizeGLObjectBuffers" ) )
func_resizeGLObjectBuffers( maxSize );
else{
this->osg::BufferData::resizeGLObjectBuffers( maxSize );
}
}
void default_resizeGLObjectBuffers( unsigned int maxSize ) {
osg::BufferData::resizeGLObjectBuffers( maxSize );
}
virtual ::osg::Object * clone( ::osg::CopyOp const & arg0 ) const {
bp::override func_clone = this->get_override( "clone" );
return func_clone( boost::ref(arg0) );
}
virtual ::osg::Object * cloneType( ) const {
bp::override func_cloneType = this->get_override( "cloneType" );
return func_cloneType( );
}
};
void register_BufferData_class(){
{ //::osg::BufferData
typedef bp::class_< BufferData_wrapper, bp::bases< osg::Object >, osg::ref_ptr< ::osg::BufferData >, boost::noncopyable > BufferData_exposer_t;
BufferData_exposer_t BufferData_exposer = BufferData_exposer_t( "BufferData", bp::no_init );
bp::scope BufferData_scope( BufferData_exposer );
bp::class_< BufferData_wrapper::ModifiedCallback_wrapper, bp::bases< osg::Object >, osg::ref_ptr< BufferData_wrapper::ModifiedCallback_wrapper >, boost::noncopyable >( "ModifiedCallback" )
.def(
"className"
, (char const * ( ::osg::BufferData::ModifiedCallback::* )( ) const)(&::osg::BufferData::ModifiedCallback::className)
, (char const * ( BufferData_wrapper::ModifiedCallback_wrapper::* )( ) const)(&BufferData_wrapper::ModifiedCallback_wrapper::default_className) )
.def(
"clone"
, (::osg::Object * ( ::osg::BufferData::ModifiedCallback::* )( ::osg::CopyOp const & ) const)(&::osg::BufferData::ModifiedCallback::clone)
, (::osg::Object * ( BufferData_wrapper::ModifiedCallback_wrapper::* )( ::osg::CopyOp const & ) const)(&BufferData_wrapper::ModifiedCallback_wrapper::default_clone)
, ( bp::arg("copyop") )
, bp::return_value_policy< bp::reference_existing_object >() )
.def(
"cloneType"
, (::osg::Object * ( ::osg::BufferData::ModifiedCallback::* )( ) const)(&::osg::BufferData::ModifiedCallback::cloneType)
, (::osg::Object * ( BufferData_wrapper::ModifiedCallback_wrapper::* )( ) const)(&BufferData_wrapper::ModifiedCallback_wrapper::default_cloneType)
, bp::return_value_policy< bp::reference_existing_object >() )
.def(
"isSameKindAs"
, (bool ( ::osg::BufferData::ModifiedCallback::* )( ::osg::Object const * ) const)(&::osg::BufferData::ModifiedCallback::isSameKindAs)
, (bool ( BufferData_wrapper::ModifiedCallback_wrapper::* )( ::osg::Object const * ) const)(&BufferData_wrapper::ModifiedCallback_wrapper::default_isSameKindAs)
, ( bp::arg("obj") ) )
.def(
"libraryName"
, (char const * ( ::osg::BufferData::ModifiedCallback::* )( ) const)(&::osg::BufferData::ModifiedCallback::libraryName)
, (char const * ( BufferData_wrapper::ModifiedCallback_wrapper::* )( ) const)(&BufferData_wrapper::ModifiedCallback_wrapper::default_libraryName) )
.def(
"modified"
, (void ( ::osg::BufferData::ModifiedCallback::* )( ::osg::BufferData * ) const)(&::osg::BufferData::ModifiedCallback::modified)
, (void ( BufferData_wrapper::ModifiedCallback_wrapper::* )( ::osg::BufferData * ) const)(&BufferData_wrapper::ModifiedCallback_wrapper::default_modified)
, ( bp::arg("arg0") ) );
{ //::osg::BufferData::addClient
typedef void ( ::osg::BufferData::*addClient_function_type )( ::osg::Object * ) ;
BufferData_exposer.def(
"addClient"
, addClient_function_type( &::osg::BufferData::addClient )
, ( bp::arg("arg0") ) );
}
{ //::osg::BufferData::asArray
typedef ::osg::Array * ( ::osg::BufferData::*asArray_function_type )( ) ;
typedef ::osg::Array * ( BufferData_wrapper::*default_asArray_function_type )( ) ;
BufferData_exposer.def(
"asArray"
, asArray_function_type(&::osg::BufferData::asArray)
, default_asArray_function_type(&BufferData_wrapper::default_asArray)
, bp::return_internal_reference< >() );
}
{ //::osg::BufferData::asArray
typedef ::osg::Array const * ( ::osg::BufferData::*asArray_function_type )( ) const;
typedef ::osg::Array const * ( BufferData_wrapper::*default_asArray_function_type )( ) const;
BufferData_exposer.def(
"asArray"
, asArray_function_type(&::osg::BufferData::asArray)
, default_asArray_function_type(&BufferData_wrapper::default_asArray)
, bp::return_internal_reference< >() );
}
{ //::osg::BufferData::className
typedef char const * ( ::osg::BufferData::*className_function_type )( ) const;
typedef char const * ( BufferData_wrapper::*default_className_function_type )( ) const;
BufferData_exposer.def(
"className"
, className_function_type(&::osg::BufferData::className)
, default_className_function_type(&BufferData_wrapper::default_className) );
}
{ //::osg::BufferData::dirty
typedef void ( ::osg::BufferData::*dirty_function_type )( ) ;
BufferData_exposer.def(
"dirty"
, dirty_function_type( &::osg::BufferData::dirty )
, " Dirty the primitive, which increments the modified count, to force buffer objects to update.\n If a ModifiedCallback is attached to this BufferData then the callback is called prior to the bufferObjects dirty is called." );
}
{ //::osg::BufferData::getBufferIndex
typedef unsigned int ( ::osg::BufferData::*getBufferIndex_function_type )( ) const;
BufferData_exposer.def(
"getBufferIndex"
, getBufferIndex_function_type( &::osg::BufferData::getBufferIndex ) );
}
{ //::osg::BufferData::getBufferObject
typedef ::osg::BufferObject * ( ::osg::BufferData::*getBufferObject_function_type )( ) ;
BufferData_exposer.def(
"getBufferObject"
, getBufferObject_function_type( &::osg::BufferData::getBufferObject )
, bp::return_internal_reference< >() );
}
{ //::osg::BufferData::getBufferObject
typedef ::osg::BufferObject const * ( ::osg::BufferData::*getBufferObject_function_type )( ) const;
BufferData_exposer.def(
"getBufferObject"
, getBufferObject_function_type( &::osg::BufferData::getBufferObject )
, bp::return_internal_reference< >() );
}
{ //::osg::BufferData::getDataPointer
typedef ::GLvoid const * ( ::osg::BufferData::*getDataPointer_function_type )( ) const;
BufferData_exposer.def(
"getDataPointer"
, bp::pure_virtual( getDataPointer_function_type(&::osg::BufferData::getDataPointer) )
, bp::return_value_policy< bp::return_opaque_pointer >() );
}
{ //::osg::BufferData::getGLBufferObject
typedef ::osg::GLBufferObject * ( ::osg::BufferData::*getGLBufferObject_function_type )( unsigned int ) const;
BufferData_exposer.def(
"getGLBufferObject"
, getGLBufferObject_function_type( &::osg::BufferData::getGLBufferObject )
, ( bp::arg("contextID") )
, bp::return_internal_reference< >() );
}
{ //::osg::BufferData::getModifiedCallback
typedef ::osg::BufferData::ModifiedCallback * ( ::osg::BufferData::*getModifiedCallback_function_type )( ) ;
BufferData_exposer.def(
"getModifiedCallback"
, getModifiedCallback_function_type( &::osg::BufferData::getModifiedCallback )
, bp::return_internal_reference< >() );
}
{ //::osg::BufferData::getModifiedCallback
typedef ::osg::BufferData::ModifiedCallback const * ( ::osg::BufferData::*getModifiedCallback_function_type )( ) const;
BufferData_exposer.def(
"getModifiedCallback"
, getModifiedCallback_function_type( &::osg::BufferData::getModifiedCallback )
, bp::return_internal_reference< >() );
}
{ //::osg::BufferData::getModifiedCount
typedef unsigned int ( ::osg::BufferData::*getModifiedCount_function_type )( ) const;
BufferData_exposer.def(
"getModifiedCount"
, getModifiedCount_function_type( &::osg::BufferData::getModifiedCount )
, " Get modified count value." );
}
{ //::osg::BufferData::getNumClients
typedef unsigned int ( ::osg::BufferData::*getNumClients_function_type )( ) const;
BufferData_exposer.def(
"getNumClients"
, getNumClients_function_type( &::osg::BufferData::getNumClients ) );
}
{ //::osg::BufferData::getOrCreateGLBufferObject
typedef ::osg::GLBufferObject * ( ::osg::BufferData::*getOrCreateGLBufferObject_function_type )( unsigned int ) const;
BufferData_exposer.def(
"getOrCreateGLBufferObject"
, getOrCreateGLBufferObject_function_type( &::osg::BufferData::getOrCreateGLBufferObject )
, ( bp::arg("contextID") )
, bp::return_internal_reference< >() );
}
{ //::osg::BufferData::getTotalDataSize
typedef unsigned int ( ::osg::BufferData::*getTotalDataSize_function_type )( ) const;
BufferData_exposer.def(
"getTotalDataSize"
, bp::pure_virtual( getTotalDataSize_function_type(&::osg::BufferData::getTotalDataSize) ) );
}
{ //::osg::BufferData::isSameKindAs
typedef bool ( ::osg::BufferData::*isSameKindAs_function_type )( ::osg::Object const * ) const;
typedef bool ( BufferData_wrapper::*default_isSameKindAs_function_type )( ::osg::Object const * ) const;
BufferData_exposer.def(
"isSameKindAs"
, isSameKindAs_function_type(&::osg::BufferData::isSameKindAs)
, default_isSameKindAs_function_type(&BufferData_wrapper::default_isSameKindAs)
, ( bp::arg("obj") ) );
}
{ //::osg::BufferData::libraryName
typedef char const * ( ::osg::BufferData::*libraryName_function_type )( ) const;
typedef char const * ( BufferData_wrapper::*default_libraryName_function_type )( ) const;
BufferData_exposer.def(
"libraryName"
, libraryName_function_type(&::osg::BufferData::libraryName)
, default_libraryName_function_type(&BufferData_wrapper::default_libraryName) );
}
{ //::osg::BufferData::removeClient
typedef void ( ::osg::BufferData::*removeClient_function_type )( ::osg::Object * ) ;
BufferData_exposer.def(
"removeClient"
, removeClient_function_type( &::osg::BufferData::removeClient )
, ( bp::arg("arg0") ) );
}
{ //::osg::BufferData::resizeGLObjectBuffers
typedef void ( ::osg::BufferData::*resizeGLObjectBuffers_function_type )( unsigned int ) ;
typedef void ( BufferData_wrapper::*default_resizeGLObjectBuffers_function_type )( unsigned int ) ;
BufferData_exposer.def(
"resizeGLObjectBuffers"
, resizeGLObjectBuffers_function_type(&::osg::BufferData::resizeGLObjectBuffers)
, default_resizeGLObjectBuffers_function_type(&BufferData_wrapper::default_resizeGLObjectBuffers)
, ( bp::arg("maxSize") ) );
}
{ //::osg::BufferData::setBufferIndex
typedef void ( ::osg::BufferData::*setBufferIndex_function_type )( unsigned int ) ;
BufferData_exposer.def(
"setBufferIndex"
, setBufferIndex_function_type( &::osg::BufferData::setBufferIndex )
, ( bp::arg("index") ) );
}
{ //::osg::BufferData::setBufferObject
typedef void ( ::osg::BufferData::*setBufferObject_function_type )( ::osg::BufferObject * ) ;
BufferData_exposer.def(
"setBufferObject"
, setBufferObject_function_type( &::osg::BufferData::setBufferObject )
, ( bp::arg("bufferObject") ) );
}
{ //::osg::BufferData::setModifiedCallback
typedef void ( ::osg::BufferData::*setModifiedCallback_function_type )( ::osg::BufferData::ModifiedCallback * ) ;
BufferData_exposer.def(
"setModifiedCallback"
, setModifiedCallback_function_type( &::osg::BufferData::setModifiedCallback )
, ( bp::arg("md") ) );
}
{ //::osg::BufferData::setModifiedCount
typedef void ( ::osg::BufferData::*setModifiedCount_function_type )( unsigned int ) ;
BufferData_exposer.def(
"setModifiedCount"
, setModifiedCount_function_type( &::osg::BufferData::setModifiedCount )
, ( bp::arg("value") )
, " Set the modified count value." );
}
{ //::osg::Object::clone
typedef ::osg::Object * ( ::osg::Object::*clone_function_type )( ::osg::CopyOp const & ) const;
BufferData_exposer.def(
"clone"
, bp::pure_virtual( clone_function_type(&::osg::Object::clone) )
, ( bp::arg("arg0") )
, bp::return_value_policy< bp::reference_existing_object >()
, "\n Clone an object, with Object* return type.\n Must be defined by derived classes.\n" );
}
{ //::osg::Object::cloneType
typedef ::osg::Object * ( ::osg::Object::*cloneType_function_type )( ) const;
BufferData_exposer.def(
"cloneType"
, bp::pure_virtual( cloneType_function_type(&::osg::Object::cloneType) )
, bp::return_value_policy< bp::reference_existing_object >()
, "\n Clone the type of an object, with Object* return type.\n Must be defined by derived classes.\n" );
}
}
}
| 43.404858 | 243 | 0.560629 | [
"object"
] |
14ed0c66bdae575c04e1416f2dedce09a5fda144 | 3,743 | cpp | C++ | api/c++/test/metadata_tests.cpp | AudiovisualMetadataPlatform/mico | 7a4faf553859119faf1abfa15d41a7c88835136f | [
"Apache-2.0"
] | null | null | null | api/c++/test/metadata_tests.cpp | AudiovisualMetadataPlatform/mico | 7a4faf553859119faf1abfa15d41a7c88835136f | [
"Apache-2.0"
] | null | null | null | api/c++/test/metadata_tests.cpp | AudiovisualMetadataPlatform/mico | 7a4faf553859119faf1abfa15d41a7c88835136f | [
"Apache-2.0"
] | null | null | null | /**
* 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 "gtest.h"
#include <iostream>
#include <sstream>
#include <fstream>
#include <boost/uuid/uuid.hpp>
#include <boost/uuid/uuid_generators.hpp>
#include <boost/uuid/uuid_io.hpp>
#include "http_client.hpp"
#include "Metadata.hpp"
#include "rdf_model.hpp"
#include "rdf_query.hpp"
using namespace boost::uuids;
using namespace mico::persistence;
using namespace mico::http;
using namespace mico::rdf::query;
using namespace mico::rdf::model;
extern std::string mico_host;
extern std::string mico_user;
extern std::string mico_pass;
class MetadataTest : public ::testing::Test {
protected:
std::string base_url = "http://" + mico_host +":8080/marmotta";
uuid base_ctx;
random_generator gen;
HTTPClient client;
virtual void SetUp() {
base_ctx = gen();
// pre-load data using http client and import endpoint
std::ifstream t("../../java/persistence/src/test/resources/demo-data.foaf");
std::stringstream buffer;
buffer << t.rdbuf();
Request req(POST,base_url+"/import/upload?context="+base_url+"/"+boost::uuids::to_string(base_ctx));
req.setBody(buffer.str(),"application/rdf+xml");
Response* resp = client.execute(req);
delete resp;
}
virtual void TearDown() {
// delete pre-loaded data
Request req(DELETE,base_url+"/context?graph="+base_url+"/"+boost::uuids::to_string(base_ctx));
Response* resp = client.execute(req);
delete resp;
}
};
TEST_F(MetadataTest,Select) {
Metadata m(base_url, boost::uuids::to_string(base_ctx));
const TupleResult *r = m.query("SELECT ?s ?p ?o WHERE {?s ?p ?o} LIMIT 10");
ASSERT_TRUE(r->size() > 0);
}
TEST_F(MetadataTest,Ask) {
Metadata m(base_url, boost::uuids::to_string(base_ctx));
ASSERT_TRUE(m.ask("ASK { <http://localhost:8080/LMF/resource/hans_meier> <http://xmlns.com/foaf/0.1/interest> <http://rdf.freebase.com/ns/en.software_engineering> }"));
ASSERT_FALSE(m.ask("ASK { <http://localhost:8080/LMF/resource/hans_meier> <http://xmlns.com/foaf/0.1/interest> <http://rdf.freebase.com/ns/en.design> }"));
}
TEST_F(MetadataTest,Update) {
Metadata m(base_url, boost::uuids::to_string(base_ctx));
EXPECT_FALSE(m.ask("ASK { <http://example.org/resource/R1> <http://example.org/property/P1> \"Value 1\" }"));
m.update("INSERT DATA { <http://example.org/resource/R1> <http://example.org/property/P1> \"Value 1\" } ");
ASSERT_TRUE(m.ask("ASK { <http://example.org/resource/R1> <http://example.org/property/P1> \"Value 1\" }"));
}
TEST_F(MetadataTest,Load) {
Metadata m(base_url, boost::uuids::to_string(base_ctx));
std::ifstream is("../../java/persistence/src/test/resources/version-base.rdf");
EXPECT_FALSE(m.ask("ASK { <http://marmotta.apache.org/testing/ns1/R1> <http://marmotta.apache.org/testing/ns1/P1> \"property 1 value 1\" }"));
m.load(is, "application/rdf+xml");
EXPECT_TRUE(m.ask("ASK { <http://marmotta.apache.org/testing/ns1/R1> <http://marmotta.apache.org/testing/ns1/P1> \"property 1 value 1\" }"));
}
TEST_F(MetadataTest,Dump) {
Metadata m(base_url, boost::uuids::to_string(base_ctx));
std::stringstream buffer;
m.dump(buffer, "text/turtle");
ASSERT_TRUE(buffer.str() != "");
}
| 31.191667 | 170 | 0.697034 | [
"model"
] |
14ed83a39acc083508e5e09430b03a91da7fc6e9 | 1,512 | hpp | C++ | src/stan/lang/generator/generate_member_var_decls.hpp | ludkinm/stan | c318114f875266f22c98cf0bebfff928653727cb | [
"CC-BY-3.0",
"BSD-3-Clause"
] | null | null | null | src/stan/lang/generator/generate_member_var_decls.hpp | ludkinm/stan | c318114f875266f22c98cf0bebfff928653727cb | [
"CC-BY-3.0",
"BSD-3-Clause"
] | null | null | null | src/stan/lang/generator/generate_member_var_decls.hpp | ludkinm/stan | c318114f875266f22c98cf0bebfff928653727cb | [
"CC-BY-3.0",
"BSD-3-Clause"
] | null | null | null | #ifndef STAN_LANG_GENERATOR_GENERATE_MEMBER_VAR_DECLS_HPP
#define STAN_LANG_GENERATOR_GENERATE_MEMBER_VAR_DECLS_HPP
#include <stan/lang/ast.hpp>
#include <stan/lang/generator/constants.hpp>
#include <stan/lang/generator/generate_indent.hpp>
#include <stan/lang/generator/get_typedef_var_type.hpp>
#include <ostream>
#include <vector>
#include <string>
namespace stan {
namespace lang {
/**
* Generate model class member variable declarations for
* variables declared in data and transformed data blocks
* at the specified indentation level to the specified stream.
*
* NOTE: variable decls typedefs defined in stan::math.
*
* @param[in] vs variable declarations
* @param[in] indent indentation level
* @param[in] o stream for writing
*/
void generate_member_var_decls(const std::vector<block_var_decl>& vs,
int indent, std::ostream& o) {
for (size_t i = 0; i < vs.size(); ++i) {
generate_indent(indent, o);
std::string var_name(vs[i].name());
block_var_type btype = vs[i].type().innermost_type();
std::string typedef_var_type = get_typedef_var_type(btype.bare_type());
int ar_dims = vs[i].type().array_dims();
for (int i = 0; i < indent; ++i)
o << INDENT;
for (int i = 0; i < ar_dims; ++i)
o << "std::vector<";
o << typedef_var_type;
if (ar_dims > 0)
o << ">";
for (int i = 1; i < ar_dims; ++i)
o << " >";
o << " " << var_name << ";" << EOL;
}
}
} // namespace lang
} // namespace stan
#endif
| 30.24 | 75 | 0.660714 | [
"vector",
"model"
] |
14ee15f7716195df14d9fa4dfb7b7476e30c64d9 | 797 | cpp | C++ | FootSoldier.cpp | mulugetaf/wargame-a | 8851bd01942d300ae1a59ecf99d8104590191c78 | [
"MIT"
] | null | null | null | FootSoldier.cpp | mulugetaf/wargame-a | 8851bd01942d300ae1a59ecf99d8104590191c78 | [
"MIT"
] | null | null | null | FootSoldier.cpp | mulugetaf/wargame-a | 8851bd01942d300ae1a59ecf99d8104590191c78 | [
"MIT"
] | null | null | null |
#include <string>
#include <vector>
#include <stdexcept>
#include <iostream>
#include "FootSoldier.hpp"
void WarGame::FootSoldier::Full_attack(WarGame::Soldier &other, std::vector<std::vector<WarGame::Soldier *>> board, std::pair<int, int> p)
{
Basic_attack(other, board, p);
}
void WarGame::FootSoldier::Basic_attack(WarGame::Soldier &other, std::vector<std::vector<WarGame::Soldier *>> board, std::pair<int, int> p)
{
int i = (int)p.first;
int j = (int)p.second;
// cout << "attacker demage : " << other.player_damge << " attacked : " << i << "," << j << endl;
if (board[i][j]->player_health <= 10)
{
board[i][j]->player_health = 0;
}
else
{
board[i][j]->player_health =
board[i][j]->player_health - other.player_damge;
}
}
| 29.518519 | 139 | 0.614806 | [
"vector"
] |
14ef6d9be58854b3edb93e276f06acfcb95e7cb2 | 1,672 | cpp | C++ | libiop/tests/algebra/test_algebra_utils.cpp | alexander-zw/libiop | a2ed2ec2f3e85f29b6035951553b02cb737c817a | [
"MIT"
] | null | null | null | libiop/tests/algebra/test_algebra_utils.cpp | alexander-zw/libiop | a2ed2ec2f3e85f29b6035951553b02cb737c817a | [
"MIT"
] | null | null | null | libiop/tests/algebra/test_algebra_utils.cpp | alexander-zw/libiop | a2ed2ec2f3e85f29b6035951553b02cb737c817a | [
"MIT"
] | null | null | null | #include <cstdint>
#include <gtest/gtest.h>
#include <vector>
#include <libff/algebra/curves/alt_bn128/alt_bn128_pp.hpp>
#include <libff/algebra/fields/binary/gf64.hpp>
#include <libff/common/utils.hpp>
#include "libiop/algebra/utils.hpp"
namespace libiop {
TEST(BatchInverseTest, SimpleTest) {
typedef libff::gf64 FieldT;
const std::size_t sz = 100;
const std::vector<FieldT> vec = random_vector<FieldT>(sz);
const std::vector<FieldT> vec_inv = batch_inverse<FieldT>(vec);
for (std::size_t i = 0; i < sz; ++i)
{
EXPECT_EQ(vec[i] * vec_inv[i], FieldT(1));
}
std::vector<FieldT> vec_inv2 = vec;
mut_batch_inverse(vec_inv2);
for (std::size_t i = 0; i < sz; ++i)
{
EXPECT_EQ(vec[i] * vec_inv2[i], FieldT(1));
}
}
TEST(MultiplicativeBatchInverseTest, SimpleTest) {
libff::alt_bn128_pp::init_public_params();
typedef libff::alt_bn128_Fr FieldT;
const std::size_t sz = 100;
std::vector<FieldT> vec = random_vector<FieldT>(sz);
std::vector<FieldT> vec_inv = batch_inverse<FieldT>(vec);
for (std::size_t i = 0; i < sz; ++i)
{
EXPECT_TRUE(vec[i] * vec_inv[i] == FieldT(1));
}
std::vector<FieldT> vec_inv2 = vec;
mut_batch_inverse(vec_inv2);
for (std::size_t i = 0; i < sz; ++i)
{
EXPECT_TRUE(vec[i] * vec_inv2[i] == FieldT(1));
}
vec[0] = FieldT::zero();
const bool input_can_contain_zeroes = true;
vec_inv = batch_inverse<FieldT>(vec, input_can_contain_zeroes);
ASSERT_TRUE(vec_inv[0] == FieldT::zero());
for (std::size_t i = 1; i < sz; ++i)
{
EXPECT_TRUE(vec[i] * vec_inv[i] == FieldT(1));
}
}
}
| 25.333333 | 67 | 0.627392 | [
"vector"
] |
14f0375ab5845eb8d2c2f1f96ae5ca1efef0d8b4 | 4,778 | cpp | C++ | r/src/dataset.cpp | LuoZijun/arrow | 8219a8b878d9344fe73e07def34a18a71a8f85a8 | [
"CC-BY-3.0",
"Apache-2.0",
"CC0-1.0"
] | null | null | null | r/src/dataset.cpp | LuoZijun/arrow | 8219a8b878d9344fe73e07def34a18a71a8f85a8 | [
"CC-BY-3.0",
"Apache-2.0",
"CC0-1.0"
] | null | null | null | r/src/dataset.cpp | LuoZijun/arrow | 8219a8b878d9344fe73e07def34a18a71a8f85a8 | [
"CC-BY-3.0",
"Apache-2.0",
"CC0-1.0"
] | 1 | 2020-02-27T02:00:20.000Z | 2020-02-27T02:00:20.000Z | // Licensed to the Apache Software Foundation (ASF) under one
// or more contributor license agreements. See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership. The ASF licenses this file
// to you under the Apache License, Version 2.0 (the
// "License"); you may not use this file except in compliance
// with the License. You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing,
// software distributed under the License is distributed on an
// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied. See the License for the
// specific language governing permissions and limitations
// under the License.
#include "./arrow_types.h"
#if defined(ARROW_R_WITH_ARROW)
// [[arrow::export]]
std::shared_ptr<arrow::dataset::DataSourceDiscovery> dataset___FSDSDiscovery__Make(
const std::shared_ptr<arrow::fs::FileSystem>& fs,
const std::shared_ptr<arrow::fs::Selector>& selector) {
std::shared_ptr<arrow::dataset::DataSourceDiscovery> discovery;
// TODO(npr): add format as an argument, don't hard-code Parquet
auto format = std::make_shared<arrow::dataset::ParquetFileFormat>();
STOP_IF_NOT_OK(arrow::dataset::FileSystemDataSourceDiscovery::Make(fs.get(), *selector,
format, &discovery));
return discovery;
}
// [[arrow::export]]
std::shared_ptr<arrow::dataset::DataSource> dataset___DSDiscovery__Finish(
const std::shared_ptr<arrow::dataset::DataSourceDiscovery>& discovery) {
std::shared_ptr<arrow::dataset::DataSource> out;
STOP_IF_NOT_OK(discovery->Finish(&out));
return out;
}
// [[arrow::export]]
std::shared_ptr<arrow::Schema> dataset___DSDiscovery__Inspect(
const std::shared_ptr<arrow::dataset::DataSourceDiscovery>& discovery) {
std::shared_ptr<arrow::Schema> out;
STOP_IF_NOT_OK(discovery->Inspect(&out));
return out;
}
// [[arrow::export]]
void dataset___DSDiscovery__SetPartitionScheme(
const std::shared_ptr<arrow::dataset::DataSourceDiscovery>& discovery,
const std::shared_ptr<arrow::dataset::PartitionScheme>& part) {
STOP_IF_NOT_OK(discovery->SetPartitionScheme(part));
}
// [[arrow::export]]
std::shared_ptr<arrow::dataset::SchemaPartitionScheme> dataset___SchemaPartitionScheme(
const std::shared_ptr<arrow::Schema>& schm) {
return std::make_shared<arrow::dataset::SchemaPartitionScheme>(schm);
}
// [[arrow::export]]
std::shared_ptr<arrow::dataset::HivePartitionScheme> dataset___HivePartitionScheme(
const std::shared_ptr<arrow::Schema>& schm) {
return std::make_shared<arrow::dataset::HivePartitionScheme>(schm);
}
// [[arrow::export]]
std::shared_ptr<arrow::dataset::Dataset> dataset___Dataset__create(
const std::vector<std::shared_ptr<arrow::dataset::DataSource>>& sources,
const std::shared_ptr<arrow::Schema>& schm) {
return std::make_shared<arrow::dataset::Dataset>(sources, schm);
}
// [[arrow::export]]
std::shared_ptr<arrow::Schema> dataset___Dataset__schema(
const std::unique_ptr<arrow::dataset::Dataset>& ds) {
return ds->schema();
}
// [[arrow::export]]
std::unique_ptr<arrow::dataset::ScannerBuilder> dataset___Dataset__NewScan(
const std::shared_ptr<arrow::dataset::Dataset>& ds) {
std::unique_ptr<arrow::dataset::ScannerBuilder> out;
STOP_IF_NOT_OK(ds->NewScan(&out));
return out;
}
// [[arrow::export]]
void dataset___ScannerBuilder__Project(
const std::unique_ptr<arrow::dataset::ScannerBuilder>& sb,
const std::vector<std::string>& cols) {
STOP_IF_NOT_OK(sb->Project(cols));
}
// [[arrow::export]]
void dataset___ScannerBuilder__Filter(
const std::unique_ptr<arrow::dataset::ScannerBuilder>& sb,
const std::shared_ptr<arrow::dataset::Expression>& expr) {
STOP_IF_NOT_OK(sb->Filter(expr));
}
// [[arrow::export]]
void dataset___ScannerBuilder__UseThreads(
const std::unique_ptr<arrow::dataset::ScannerBuilder>& sb, bool threads) {
STOP_IF_NOT_OK(sb->UseThreads(threads));
}
// [[arrow::export]]
std::shared_ptr<arrow::Schema> dataset___ScannerBuilder__schema(
const std::unique_ptr<arrow::dataset::ScannerBuilder>& sb) {
return sb->schema();
}
// [[arrow::export]]
std::unique_ptr<arrow::dataset::Scanner> dataset___ScannerBuilder__Finish(
const std::unique_ptr<arrow::dataset::ScannerBuilder>& sb) {
std::unique_ptr<arrow::dataset::Scanner> out;
STOP_IF_NOT_OK(sb->Finish(&out));
return out;
}
// [[arrow::export]]
std::shared_ptr<arrow::Table> dataset___Scanner__ToTable(
const std::unique_ptr<arrow::dataset::Scanner>& scn) {
std::shared_ptr<arrow::Table> out;
STOP_IF_NOT_OK(scn->ToTable(&out));
return out;
}
#endif
| 35.656716 | 90 | 0.728338 | [
"vector"
] |
14fca847d0b237b448a531e95eb4b5781a63d5b6 | 28,799 | cpp | C++ | module/mpc-be/SRC/src/ExtLib/MediaInfo/MediaInfo/Multiple/File_Ibi.cpp | 1aq/PBox | 67ced599ee36ceaff097c6584f8100cf96006dfe | [
"MIT"
] | null | null | null | module/mpc-be/SRC/src/ExtLib/MediaInfo/MediaInfo/Multiple/File_Ibi.cpp | 1aq/PBox | 67ced599ee36ceaff097c6584f8100cf96006dfe | [
"MIT"
] | null | null | null | module/mpc-be/SRC/src/ExtLib/MediaInfo/MediaInfo/Multiple/File_Ibi.cpp | 1aq/PBox | 67ced599ee36ceaff097c6584f8100cf96006dfe | [
"MIT"
] | null | null | null | /* Copyright (c) MediaArea.net SARL. All Rights Reserved.
*
* Use of this source code is governed by a BSD-style license that can
* be found in the License.html file in the root of the source tree.
*/
//---------------------------------------------------------------------------
// Pre-compilation
#include "MediaInfo/PreComp.h"
#ifdef __BORLANDC__
#pragma hdrstop
#endif
//---------------------------------------------------------------------------
//---------------------------------------------------------------------------
#include "MediaInfo/Setup.h"
//---------------------------------------------------------------------------
//---------------------------------------------------------------------------
#if MEDIAINFO_IBI
//---------------------------------------------------------------------------
//---------------------------------------------------------------------------
#include "MediaInfo/Multiple/File_Ibi.h"
#include "MediaInfo/MediaInfo_Config_MediaInfo.h"
#include <zlib.h>
//---------------------------------------------------------------------------
namespace MediaInfoLib
{
//***************************************************************************
// Constructor/Destructor
//***************************************************************************
//---------------------------------------------------------------------------
File_Ibi::File_Ibi()
:File__Analyze()
{
//Configuration
#if MEDIAINFO_DEMUX
Demux_Level=2; //Container
#endif //MEDIAINFO_DEMUX
DataMustAlwaysBeComplete=false;
#if MEDIAINFO_IBIUSAGE
//In
Ibi=NULL;
//Temp
Ibi_MustDelete=false;
#endif //MEDIAINFO_IBIUSAGE
}
//---------------------------------------------------------------------------
File_Ibi::~File_Ibi()
{
#if MEDIAINFO_IBIUSAGE
if (Ibi_MustDelete)
delete Ibi; //Ibi=NULL;
#endif //MEDIAINFO_IBIUSAGE
}
//***************************************************************************
// Get information
//***************************************************************************
//---------------------------------------------------------------------------
#if MEDIAINFO_IBIUSAGE
const Ztring &File_Ibi::Get (stream_t /*StreamKind*/, size_t /*StreamNumber*/, const Ztring &Parameter, info_t /*KindOfInfo*/, info_t /*KindOfSearch*/)
{
ibi::streams::iterator IbiStream_Temp=Ibi->Streams.begin(); //TODO: management of multiple streams
if (IbiStream_Temp!=Ibi->Streams.end() && !IbiStream_Temp->second->Infos.empty())
{
int64u FrameNumber=Parameter.To_int64u();
for (size_t Pos=0; Pos<IbiStream_Temp->second->Infos.size()-1; Pos++)
if (IbiStream_Temp->second->Infos[Pos].FrameNumber==FrameNumber || IbiStream_Temp->second->Infos[Pos+1].FrameNumber>FrameNumber)
{
Get_Temp=__T("StreamOffset=")+Ztring::ToZtring(IbiStream_Temp->second->Infos[Pos].StreamOffset)
+ __T(" / FrameNumber=")+Ztring::ToZtring(IbiStream_Temp->second->Infos[Pos].FrameNumber)
+ __T(" / Dts=")+Ztring::ToZtring(IbiStream_Temp->second->Infos[Pos].Dts);
return Get_Temp;
}
}
//Can not be found
Get_Temp.clear();
return Get_Temp;
}
#endif //MEDIAINFO_IBIUSAGE
//***************************************************************************
// Streams management
//***************************************************************************
//---------------------------------------------------------------------------
void File_Ibi::Streams_Accept()
{
Fill(Stream_General, 0, General_Format, "Ibi");
#if MEDIAINFO_IBIUSAGE
if (Ibi==NULL)
{
Ibi=new ibi();
Ibi_MustDelete=true;
}
#endif //MEDIAINFO_IBIUSAGE
}
//---------------------------------------------------------------------------
#if MEDIAINFO_IBIUSAGE
void File_Ibi::Streams_Finish()
{
Config->File_KeepInfo_Set(true); //In order to let Get() available
if (Count_Get(Stream_Video)==0) //If not yet done by Inform part
for (ibi::streams::iterator IbiStream_Temp=Ibi->Streams.begin(); IbiStream_Temp!=Ibi->Streams.end(); ++IbiStream_Temp)
{
Stream_Prepare(Stream_Video);
Fill(Stream_Video, StreamPos_Last, General_ID, IbiStream_Temp->first);
}
}
#endif //MEDIAINFO_IBIUSAGE
//***************************************************************************
// Buffer
//***************************************************************************
//---------------------------------------------------------------------------
void File_Ibi::Header_Parse()
{
//Test of zero padding
int8u Null;
Peek_B1(Null);
if (Null==0x00)
{
if (Buffer_Offset_Temp==0)
Buffer_Offset_Temp=Buffer_Offset+1;
while (Buffer_Offset_Temp<Buffer_Size)
{
if (Buffer[Buffer_Offset_Temp])
break;
Buffer_Offset_Temp++;
}
if (Buffer_Offset_Temp>=Buffer_Size)
{
Element_WaitForMoreData();
return;
}
Header_Fill_Code((int32u)-1); //Should be (int64u)-1 but Borland C++ does not like this
Header_Fill_Size(Buffer_Offset_Temp-Buffer_Offset);
Buffer_Offset_Temp=0;
return;
}
//Parsing
int64u Name, Size;
Get_EB (Name, "Name");
Get_EB (Size, "Size");
//Filling
Header_Fill_Code(Name, Ztring().From_Number(Name, 16));
Header_Fill_Size(Element_Offset+Size);
}
//---------------------------------------------------------------------------
namespace Elements
{
//Common
const int64u Zero=(int32u)-1; //Should be (int64u)-1 but Borland C++ does not like this
const int64u CRC32=0x3F;
const int64u Void=0x6C;
//EBML
const int64u Ebml=0xA45DFA3;
const int64u Ebml_Version=0x286;
const int64u Ebml_ReadVersion=0x2F7;
const int64u Ebml_MaxIDLength=0x2F2;
const int64u Ebml_MaxSizeLength=0x2F3;
const int64u Ebml_DocType=0x282;
const int64u Ebml_DocTypeVersion=0x287;
const int64u Ebml_DocTypeReadVersion=0x285;
//Segment
const int64u Stream=1;
const int64u Stream_Header=1;
const int64u Stream_ByteOffset=2;
const int64u Stream_FrameNumber=3;
const int64u Stream_Dts=4;
const int64u CompressedIndex=2;
const int64u WritingApplication=3;
const int64u WritingApplication_Name=1;
const int64u WritingApplication_Version=2;
const int64u InformData=4;
const int64u SourceInfo=5;
const int64u SourceInfo_IndexCreationDate=1;
const int64u SourceInfo_SourceModificationDate=2;
const int64u SourceInfo_SourceSize=3;
}
//---------------------------------------------------------------------------
void File_Ibi::Data_Parse()
{
#define LIS2(_ATOM, _NAME) \
case Elements::_ATOM : \
if (Level==Element_Level) \
{ \
Element_Name(_NAME); \
_ATOM(); \
Element_ThisIsAList(); \
} \
#define ATO2(_ATOM, _NAME) \
case Elements::_ATOM : \
if (Level==Element_Level) \
{ \
if (Element_IsComplete_Get()) \
{ \
Element_Name(_NAME); \
_ATOM(); \
} \
else \
{ \
Element_WaitForMoreData(); \
return; \
} \
} \
break; \
#define ATOM_END_MK \
ATOM(Zero) \
ATOM(CRC32) \
ATOM(Void) \
ATOM_END
//Parsing
DATA_BEGIN
LIST(Ebml)
ATOM_BEGIN
ATOM(Ebml_Version)
ATOM(Ebml_ReadVersion)
ATOM(Ebml_MaxIDLength)
ATOM(Ebml_MaxSizeLength)
ATOM(Ebml_DocType)
ATOM(Ebml_DocTypeVersion)
ATOM(Ebml_DocTypeReadVersion)
ATOM_END_MK
LIST(Stream)
ATOM_BEGIN
ATOM(Stream_Header)
ATOM(Stream_ByteOffset)
ATOM(Stream_FrameNumber)
ATOM(Stream_Dts)
ATOM_END_MK
ATOM(CompressedIndex)
LIST(WritingApplication)
ATOM_BEGIN
ATOM(WritingApplication_Name)
ATOM(WritingApplication_Version)
ATOM_END_MK
LIST(SourceInfo)
ATOM_BEGIN
ATOM(SourceInfo_IndexCreationDate)
ATOM(SourceInfo_SourceModificationDate)
ATOM(SourceInfo_SourceSize)
ATOM_END_MK
ATOM(InformData)
DATA_END_DEFAULT
}
//***************************************************************************
// Elements
//***************************************************************************
//---------------------------------------------------------------------------
void File_Ibi::Zero()
{
Element_Name("ZeroPadding");
}
//---------------------------------------------------------------------------
void File_Ibi::CRC32()
{
Element_Name("CRC32");
//Parsing
UInteger_Info();
}
//---------------------------------------------------------------------------
void File_Ibi::Void()
{
Element_Name("Void");
//Parsing
UInteger_Info();
}
//---------------------------------------------------------------------------
void File_Ibi::Ebml()
{
Element_Name("Ebml");
}
//---------------------------------------------------------------------------
void File_Ibi::Ebml_Version()
{
Element_Name("Version");
//Parsing
UInteger_Info();
}
//---------------------------------------------------------------------------
void File_Ibi::Ebml_ReadVersion()
{
Element_Name("ReadVersion");
//Parsing
UInteger_Info();
}
//---------------------------------------------------------------------------
void File_Ibi::Ebml_MaxIDLength()
{
Element_Name("MaxIDLength");
//Parsing
UInteger_Info();
}
//---------------------------------------------------------------------------
void File_Ibi::Ebml_MaxSizeLength()
{
Element_Name("MaxSizeLength");
//Parsing
UInteger_Info();
}
//---------------------------------------------------------------------------
void File_Ibi::Ebml_DocType()
{
Element_Name("DocType");
//Parsing
Ztring Data;
Get_UTF8(Element_Size, Data, "Data"); Element_Info1(Data);
//Filling
FILLING_BEGIN();
if (Data==__T("MediaInfo Index"))
Accept("Ibi");
else
{
Reject("Ibi");
return;
}
FILLING_END();
}
//---------------------------------------------------------------------------
void File_Ibi::Ebml_DocTypeVersion()
{
Element_Name("DocTypeVersion");
//Parsing
UInteger_Info();
}
//---------------------------------------------------------------------------
void File_Ibi::Ebml_DocTypeReadVersion()
{
Element_Name("DocTypeReadVersion");
//Parsing
UInteger_Info();
}
//---------------------------------------------------------------------------
void File_Ibi::Stream()
{
Element_Name("Stream");
ID_Current=(int64u)-1;
}
void File_Ibi::Stream_Header()
{
Element_Name("Stream Header");
Get_EB (ID_Current, "ID");
FILLING_BEGIN();
#if MEDIAINFO_IBIUSAGE
if (Ibi)
{
//Filling information for ID after data
ibi::streams::iterator IbiStream_Temp=Ibi->Streams.find((int64u)-1);
if (IbiStream_Temp!=Ibi->Streams.end())
{
Ibi->Streams[ID_Current]=IbiStream_Temp->second;
Ibi->Streams.erase(IbiStream_Temp);
}
}
#else //MEDIAINFO_IBIUSAGE
Stream_Prepare(Stream_Video);
Fill(Stream_Video, StreamPos_Last, General_ID, ID_Current);
#endif //MEDIAINFO_IBIUSAGE
FILLING_END();
}
void File_Ibi::Stream_ByteOffset()
{
Element_Name("Byte Offset");
//Parsing
#if MEDIAINFO_IBIUSAGE
size_t Pos=0;
#endif //MEDIAINFO_IBIUSAGE
int64u Offset=0;
while (Element_Offset<Element_Size)
{
int64u Item;
Get_EB (Item, "Item");
Offset+=Item;
#if MEDIAINFO_IBIUSAGE
Param_Info1(Pos);
#endif //MEDIAINFO_IBIUSAGE
Param_Info1(Get_Hex_ID(Offset));
#if MEDIAINFO_IBIUSAGE
FILLING_BEGIN();
if (Ibi)
{
//Filling information for ID after data
if (Ibi->Streams[ID_Current]==NULL)
Ibi->Streams[ID_Current]=new ibi::stream();
if (Pos>=Ibi->Streams[ID_Current]->Infos.size())
{
Ibi->Streams[ID_Current]->Infos.push_back(ibi::stream::info());
Ibi->Streams[ID_Current]->Infos[Pos].IsContinuous=true; //default
}
Ibi->Streams[ID_Current]->Infos[Pos].StreamOffset=Offset;
Pos++;
}
FILLING_END();
#endif //MEDIAINFO_IBIUSAGE
}
}
void File_Ibi::Stream_FrameNumber()
{
Element_Name("Frame Number");
//Parsing
#if MEDIAINFO_IBIUSAGE
size_t Pos=0;
#endif //MEDIAINFO_IBIUSAGE
int64u Offset=0;
while (Element_Offset<Element_Size)
{
int64u Item;
Get_EB (Item, "Item");
Offset+=Item;
#if MEDIAINFO_IBIUSAGE
Param_Info1(Pos);
#endif //MEDIAINFO_IBIUSAGE
Param_Info1(Get_Hex_ID(Offset));
#if MEDIAINFO_IBIUSAGE
FILLING_BEGIN();
if (Ibi)
{
//Filling information for ID after data
if (Ibi->Streams[ID_Current]==NULL)
Ibi->Streams[ID_Current]=new ibi::stream();
if (Pos>=Ibi->Streams[ID_Current]->Infos.size())
{
Ibi->Streams[ID_Current]->Infos.push_back(ibi::stream::info());
Ibi->Streams[ID_Current]->Infos[Pos].IsContinuous=true; //default
}
Ibi->Streams[ID_Current]->Infos[Pos].FrameNumber=Offset;
Pos++;
}
FILLING_END();
#endif //MEDIAINFO_IBIUSAGE
}
}
void File_Ibi::Stream_Dts()
{
Element_Name("DTS");
//Parsing
int64u Item;
Get_EB (Item, "DtsFrequencyNumerator");
#if MEDIAINFO_IBIUSAGE
FILLING_BEGIN();
if (Ibi)
Ibi->Streams[ID_Current]->DtsFrequencyNumerator=Item;
FILLING_END();
#endif //MEDIAINFO_IBIUSAGE
Get_EB (Item, "DtsFrequencyDenominator");
#if MEDIAINFO_IBIUSAGE
FILLING_BEGIN();
if (Ibi)
{
Ibi->Streams[ID_Current]->DtsFrequencyDenominator=Item;
//Handling of previous inverted Numerator/Denominator
if (Ibi->Streams[ID_Current]->DtsFrequencyNumerator<Ibi->Streams[ID_Current]->DtsFrequencyDenominator)
std::swap(Ibi->Streams[ID_Current]->DtsFrequencyNumerator, Ibi->Streams[ID_Current]->DtsFrequencyDenominator);
}
FILLING_END();
#endif //MEDIAINFO_IBIUSAGE
#if MEDIAINFO_IBIUSAGE
size_t Pos=0;
#endif //MEDIAINFO_IBIUSAGE
int64u Offset=0;
while (Element_Offset<Element_Size)
{
int64u Item;
Get_EB (Item, "Item");
Offset+=Item;
#if MEDIAINFO_IBIUSAGE
Param_Info1(Pos);
#endif //MEDIAINFO_IBIUSAGE
Param_Info1(Get_Hex_ID(Offset));
#if MEDIAINFO_IBIUSAGE
FILLING_BEGIN();
if (Ibi)
{
//Filling information for ID after data
if (Ibi->Streams[ID_Current]==NULL)
Ibi->Streams[ID_Current]=new ibi::stream();
if (Pos>=Ibi->Streams[ID_Current]->Infos.size())
{
Ibi->Streams[ID_Current]->Infos.push_back(ibi::stream::info());
Ibi->Streams[ID_Current]->Infos[Pos].IsContinuous=true; //default
}
Ibi->Streams[ID_Current]->Infos[Pos].Dts=Offset;
Pos++;
}
FILLING_END();
#endif //MEDIAINFO_IBIUSAGE
}
}
void File_Ibi::CompressedIndex()
{
if (!Status[IsAccepted])
{
Reject("Ibi");
return;
}
Element_Name("Compressed Index");
int64u UncompressedSize;
Get_EB (UncompressedSize, "Uncompressed size");
//Sizes
unsigned long Source_Size=(unsigned long)(Element_Size-Element_Offset);
unsigned long Dest_Size=(unsigned long)UncompressedSize;
if (Dest_Size>=64*1024*1024)
{
Reject("Ibi");
return;
}
//Uncompressing
int8u* Dest;
{
Dest=new int8u[Dest_Size];
}
if (uncompress((Bytef*)Dest, &Dest_Size, (const Bytef*)Buffer+Buffer_Offset+(size_t)Element_Offset, Source_Size)<0)
{
Skip_XX(Element_Size-Element_Offset, "Problem during the decompression");
delete[] Dest; //Dest=NULL;
return;
}
//Exiting this element
Skip_XX(Element_Size-Element_Offset, "Will be parsed");
//Configuring buffer
const int8u* Buffer_Sav=Buffer;
size_t Buffer_Size_Sav=Buffer_Size;
int8u* Buffer_Temp_Sav=Buffer_Temp;
size_t Buffer_Temp_Size_Sav=Buffer_Temp_Size;
size_t Buffer_Offset_Sav=Buffer_Offset;
size_t Buffer_Offset_Temp_Sav=Buffer_Offset_Temp;
Buffer=NULL;
Buffer_Size=0;
Buffer_Temp=NULL;
Buffer_Temp_Size=0;
Buffer_Offset=0;
Buffer_Offset_Temp=0;
//Configuring level
std::vector<int64u> Element_Sizes_Sav;
size_t Element_Level_Sav=Element_Level;
while(Element_Level)
{
Element_Sizes_Sav.push_back(Element_TotalSize_Get());
Element_End0();
}
//Configuring file size
int64u File_Size_Sav=File_Size;
if (File_Size<File_Offset+Buffer_Offset+Element_Offset+Dest_Size)
File_Size=File_Offset+Buffer_Offset+Element_Offset+Dest_Size;
Element_Level++;
Header_Fill_Size(File_Size);
Element_Level--;
//Parsing
Buffer=Dest;
Buffer_Size=Dest_Size;
while (Open_Buffer_Continue_Loop());
delete[] Dest; //Dest=NULL;
//Resetting file size
File_Size=File_Size_Sav;
while(Element_Level)
Element_End0();
Element_Level++;
Header_Fill_Size(File_Size);
Element_Level--;
//Configuring level
while(Element_Level<Element_Level_Sav)
{
Element_Begin0();
Element_Begin0();
Header_Fill_Size(Element_Sizes_Sav[0]);
Element_End0();
}
//Resetting buffer
Buffer=Buffer_Sav;
Buffer_Size=Buffer_Size_Sav;
Buffer_Temp=Buffer_Temp_Sav;
Buffer_Temp_Size=Buffer_Temp_Size_Sav;
Buffer_Offset=Buffer_Offset_Sav;
Buffer_Offset_Temp=Buffer_Offset_Temp_Sav;
}
//---------------------------------------------------------------------------
void File_Ibi::WritingApplication()
{
Element_Name("WritingApplication");
}
//---------------------------------------------------------------------------
void File_Ibi::WritingApplication_Name()
{
Element_Name("Name");
//Parsing
Skip_UTF8(Element_Size, "Data");
}
//---------------------------------------------------------------------------
void File_Ibi::WritingApplication_Version()
{
Element_Name("Version");
//Parsing
Skip_UTF8(Element_Size, "Data");
}
//---------------------------------------------------------------------------
void File_Ibi::SourceInfo()
{
Element_Name("Source Information");
}
//---------------------------------------------------------------------------
void File_Ibi::SourceInfo_IndexCreationDate()
{
Element_Name("Index Creation Date");
//Parsing
Skip_B8( "Data");
}
//---------------------------------------------------------------------------
void File_Ibi::SourceInfo_SourceModificationDate()
{
Element_Name("Source Modification Date");
//Parsing
Skip_B8( "Data");
}
//---------------------------------------------------------------------------
void File_Ibi::SourceInfo_SourceSize()
{
Element_Name("Source Size");
//Parsing
Skip_B8( "Data");
}
//---------------------------------------------------------------------------
void File_Ibi::InformData()
{
Element_Name("InformData");
//Parsing
Ztring InformData_FromFile;
Get_UTF8 (Element_Size, InformData_FromFile, "Data");
//Filling
#if MEDIAINFO_IBIUSAGE
if (Config->Ibi_UseIbiInfoIfAvailable_Get())
{
ZtringListList Fields(InformData_FromFile);
for (size_t Pos=0; Pos<Fields.size(); Pos++)
{
if (Pos==0 || Fields[Pos].size()<2)
{
if (Pos)
Pos++;
if (Pos>Fields.size() || Fields[Pos].size()<1)
break; //End or problem
if (Fields[Pos][0]==__T("General"))
; //Nothing to do
else if (Fields[Pos][0]==__T("Video"))
Stream_Prepare(Stream_Video);
else if (Fields[Pos][0]==__T("Audio"))
Stream_Prepare(Stream_Audio);
else if (Fields[Pos][0]==__T("Text"))
Stream_Prepare(Stream_Text);
else if (Fields[Pos][0]==__T("Other"))
Stream_Prepare(Stream_Other);
else if (Fields[Pos][0]==__T("Image"))
Stream_Prepare(Stream_Image);
else if (Fields[Pos][0]==__T("Menu"))
Stream_Prepare(Stream_Menu);
else
break; //Problem
Pos++;
}
Fill(StreamKind_Last, StreamPos_Last, Fields[Pos][0].To_UTF8().c_str(), Fields[Pos][1], true);
Fill_SetOptions(StreamKind_Last, StreamPos_Last, Fields[Pos][0].To_UTF8().c_str(), Fields[Pos][Info_Options].To_UTF8().c_str());
}
}
#endif //MEDIAINFO_IBIUSAGE
}
//***************************************************************************
// Data
//***************************************************************************
//---------------------------------------------------------------------------
void File_Ibi::UInteger_Info()
{
switch (Element_Size)
{
case 1 :
{
Info_B1(Data, "Data"); Element_Info1(Data);
return;
}
case 2 :
{
Info_B2(Data, "Data"); Element_Info1(Data);
return;
}
case 3 :
{
Info_B3(Data, "Data"); Element_Info1(Data);
return;
}
case 4 :
{
Info_B4(Data, "Data"); Element_Info1(Data);
return;
}
case 5 :
{
Info_B5(Data, "Data"); Element_Info1(Data);
return;
}
case 6 :
{
Info_B6(Data, "Data"); Element_Info1(Data);
return;
}
case 7 :
{
Info_B7(Data, "Data"); Element_Info1(Data);
return;
}
case 8 :
{
Info_B8(Data, "Data"); Element_Info1(Data);
return;
}
case 16:
{
Info_B16(Data, "Data"); Element_Info1(Data);
return;
}
default : Skip_XX(Element_Size, "Data");
}
}
//---------------------------------------------------------------------------
int64u File_Ibi::UInteger_Get()
{
switch (Element_Size)
{
case 1 :
{
int8u Data;
Get_B1 (Data, "Data"); Element_Info1(Data);
return Data;
}
case 2 :
{
int16u Data;
Get_B2 (Data, "Data"); Element_Info1(Data);
return Data;
}
case 3 :
{
int32u Data;
Get_B3 (Data, "Data"); Element_Info1(Data);
return Data;
}
case 4 :
{
int32u Data;
Get_B4 (Data, "Data"); Element_Info1(Data);
return Data;
}
case 5 :
{
int64u Data;
Get_B5 (Data, "Data"); Element_Info1(Data);
return Data;
}
case 6 :
{
int64u Data;
Get_B6 (Data, "Data"); Element_Info1(Data);
return Data;
}
case 7 :
{
int64u Data;
Get_B7 (Data, "Data"); Element_Info1(Data);
return Data;
}
case 8 :
{
int64u Data;
Get_B8 (Data, "Data"); Element_Info1(Data);
return Data;
}
default : Skip_XX(Element_Size, "Data");
return 0;
}
}
//---------------------------------------------------------------------------
int128u File_Ibi::UInteger16_Get()
{
switch (Element_Size)
{
case 1 :
{
int8u Data;
Get_B1 (Data, "Data"); Element_Info1(Data);
return Data;
}
case 2 :
{
int16u Data;
Get_B2 (Data, "Data"); Element_Info1(Data);
return Data;
}
case 3 :
{
int32u Data;
Get_B3 (Data, "Data"); Element_Info1(Data);
return Data;
}
case 4 :
{
int32u Data;
Get_B4 (Data, "Data"); Element_Info1(Data);
return Data;
}
case 5 :
{
int64u Data;
Get_B5 (Data, "Data"); Element_Info1(Data);
return Data;
}
case 6 :
{
int64u Data;
Get_B6 (Data, "Data"); Element_Info1(Data);
return Data;
}
case 7 :
{
int64u Data;
Get_B7 (Data, "Data"); Element_Info1(Data);
return Data;
}
case 8 :
{
int64u Data;
Get_B8 (Data, "Data"); Element_Info1(Data);
return Data;
}
case 16:
{
int128u Data;
Get_B16(Data, "Data"); Element_Info1(Data);
return Data;
}
default : Skip_XX(Element_Size, "Data");
return 0;
}
}
} //NameSpace
#endif //MEDIAINFO_IBI
| 30.507415 | 151 | 0.437793 | [
"vector"
] |
14fecbf32057e8201f2ccb9bd24a4cbed90acb92 | 902 | cpp | C++ | C++/problem0945_test02.cpp | 1050669722/LeetCode-Answers | c8f4d1ccaac09cda63b60d75144335347b06dc81 | [
"MIT"
] | null | null | null | C++/problem0945_test02.cpp | 1050669722/LeetCode-Answers | c8f4d1ccaac09cda63b60d75144335347b06dc81 | [
"MIT"
] | null | null | null | C++/problem0945_test02.cpp | 1050669722/LeetCode-Answers | c8f4d1ccaac09cda63b60d75144335347b06dc81 | [
"MIT"
] | null | null | null | #include <iostream>
#include <iomanip>
#include <vector>
#include <map>
#include <set>
#include <algorithm>
#include <cmath>
#include <ctime>
#include <cstdlib>
#include <windows.h>
#include <string>
#include <numeric>
using namespace std;
class Solution {
public:
int minIncrementForUnique(vector<int>& A)
{
if (A.empty())
{
return 0;
}
int sum = accumulate(A.begin(), A.end(), 0);
sort(A.begin(), A.end(), less<int>());
vector<int>::iterator it;
for (it = A.begin()+1; it != A.end(); ++it)
{
if (*it <= *(it-1))
{
*it = *(it-1) + 1;
}
}
return accumulate(A.begin(), A.end(), 0) - sum;
}
};
int main()
{
vector<int> A {3,2,1,2,1,7};
Solution solu;
int ans = solu.minIncrementForUnique(A);
cout << ans << endl;
return 0;
} | 19.608696 | 55 | 0.507761 | [
"vector"
] |
0901e643afaa60370fab38f6f21b677393aab678 | 8,569 | cpp | C++ | searchlib/src/vespa/searchlib/tensor/streamed_value_store.cpp | Anlon-Burke/vespa | 5ecd989b36cc61716bf68f032a3482bf01fab726 | [
"Apache-2.0"
] | 4,054 | 2017-08-11T07:58:38.000Z | 2022-03-31T22:32:15.000Z | searchlib/src/vespa/searchlib/tensor/streamed_value_store.cpp | Anlon-Burke/vespa | 5ecd989b36cc61716bf68f032a3482bf01fab726 | [
"Apache-2.0"
] | 4,854 | 2017-08-10T20:19:25.000Z | 2022-03-31T19:04:23.000Z | searchlib/src/vespa/searchlib/tensor/streamed_value_store.cpp | Anlon-Burke/vespa | 5ecd989b36cc61716bf68f032a3482bf01fab726 | [
"Apache-2.0"
] | 541 | 2017-08-10T18:51:18.000Z | 2022-03-11T03:18:56.000Z | // Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
#include "streamed_value_store.h"
#include <vespa/eval/eval/value.h>
#include <vespa/eval/eval/value_codec.h>
#include <vespa/eval/eval/fast_value.hpp>
#include <vespa/eval/streamed/streamed_value_builder_factory.h>
#include <vespa/eval/streamed/streamed_value_view.h>
#include <vespa/vespalib/datastore/buffer_type.hpp>
#include <vespa/vespalib/datastore/datastore.hpp>
#include <vespa/vespalib/objects/nbostream.h>
#include <vespa/vespalib/util/size_literals.h>
#include <vespa/vespalib/util/typify.h>
#include <vespa/vespalib/util/stringfmt.h>
#include <vespa/log/log.h>
LOG_SETUP(".searchlib.tensor.streamed_value_store");
using vespalib::datastore::Handle;
using vespalib::datastore::EntryRef;
using namespace vespalib::eval;
using vespalib::ConstArrayRef;
using vespalib::MemoryUsage;
using vespalib::string_id;
namespace search::tensor {
//-----------------------------------------------------------------------------
namespace {
template <typename CT, typename F>
void each_subspace(const Value &value, size_t num_mapped, size_t dense_size, F f) {
size_t subspace;
std::vector<string_id> addr(num_mapped);
std::vector<string_id*> refs;
refs.reserve(addr.size());
for (string_id &label: addr) {
refs.push_back(&label);
}
auto cells = value.cells().typify<CT>();
auto view = value.index().create_view({});
view->lookup({});
while (view->next_result(refs, subspace)) {
size_t offset = subspace * dense_size;
f(ConstArrayRef<string_id>(addr), ConstArrayRef<CT>(cells.begin() + offset, dense_size));
}
}
using TensorEntry = StreamedValueStore::TensorEntry;
struct CreateTensorEntry {
template <typename CT>
static TensorEntry::SP invoke(const Value &value, size_t num_mapped, size_t dense_size) {
using EntryImpl = StreamedValueStore::TensorEntryImpl<CT>;
return std::make_shared<EntryImpl>(value, num_mapped, dense_size);
}
};
struct MyFastValueView final : Value {
const ValueType &my_type;
FastValueIndex my_index;
TypedCells my_cells;
MyFastValueView(const ValueType &type_ref, const std::vector<string_id> &handle_view, TypedCells cells, size_t num_mapped, size_t num_spaces)
: my_type(type_ref),
my_index(num_mapped, handle_view, num_spaces),
my_cells(cells)
{
const std::vector<string_id> &labels = handle_view;
for (size_t i = 0; i < num_spaces; ++i) {
ConstArrayRef<string_id> addr(&labels[i * num_mapped], num_mapped);
my_index.map.add_mapping(FastAddrMap::hash_labels(addr));
}
assert(my_index.map.size() == num_spaces);
}
const ValueType &type() const override { return my_type; }
const Value::Index &index() const override { return my_index; }
TypedCells cells() const override { return my_cells; }
MemoryUsage get_memory_usage() const override {
MemoryUsage usage = self_memory_usage<MyFastValueView>();
usage.merge(my_index.map.estimate_extra_memory_usage());
return usage;
}
};
} // <unnamed>
//-----------------------------------------------------------------------------
StreamedValueStore::TensorEntry::~TensorEntry() = default;
StreamedValueStore::TensorEntry::SP
StreamedValueStore::TensorEntry::create_shared_entry(const Value &value)
{
size_t num_mapped = value.type().count_mapped_dimensions();
size_t dense_size = value.type().dense_subspace_size();
return vespalib::typify_invoke<1,TypifyCellType,CreateTensorEntry>(value.type().cell_type(), value, num_mapped, dense_size);
}
template <typename CT>
StreamedValueStore::TensorEntryImpl<CT>::TensorEntryImpl(const Value &value, size_t num_mapped, size_t dense_size)
: handles(),
cells()
{
handles.reserve(num_mapped * value.index().size());
cells.reserve(dense_size * value.index().size());
auto store_subspace = [&](auto addr, auto data) {
for (string_id label: addr) {
handles.push_back(label);
}
for (CT entry: data) {
cells.push_back(entry);
}
};
each_subspace<CT>(value, num_mapped, dense_size, store_subspace);
}
template <typename CT>
Value::UP
StreamedValueStore::TensorEntryImpl<CT>::create_fast_value_view(const ValueType &type_ref) const
{
size_t num_mapped = type_ref.count_mapped_dimensions();
size_t dense_size = type_ref.dense_subspace_size();
size_t num_spaces = cells.size() / dense_size;
assert(dense_size * num_spaces == cells.size());
assert(num_mapped * num_spaces == handles.view().size());
return std::make_unique<MyFastValueView>(type_ref, handles.view(), TypedCells(cells), num_mapped, num_spaces);
}
template <typename CT>
void
StreamedValueStore::TensorEntryImpl<CT>::encode_value(const ValueType &type, vespalib::nbostream &target) const
{
size_t num_mapped = type.count_mapped_dimensions();
size_t dense_size = type.dense_subspace_size();
size_t num_spaces = cells.size() / dense_size;
assert(dense_size * num_spaces == cells.size());
assert(num_mapped * num_spaces == handles.view().size());
StreamedValueView my_value(type, num_mapped, TypedCells(cells), num_spaces, handles.view());
::vespalib::eval::encode_value(my_value, target);
}
template <typename CT>
MemoryUsage
StreamedValueStore::TensorEntryImpl<CT>::get_memory_usage() const
{
MemoryUsage usage = self_memory_usage<TensorEntryImpl<CT>>();
usage.merge(vector_extra_memory_usage(handles.view()));
usage.merge(vector_extra_memory_usage(cells));
return usage;
}
template <typename CT>
StreamedValueStore::TensorEntryImpl<CT>::~TensorEntryImpl() = default;
//-----------------------------------------------------------------------------
constexpr size_t MIN_BUFFER_ARRAYS = 8_Ki;
StreamedValueStore::TensorBufferType::TensorBufferType() noexcept
: ParentType(1, MIN_BUFFER_ARRAYS, TensorStoreType::RefType::offsetSize())
{
}
void
StreamedValueStore::TensorBufferType::cleanHold(void* buffer, size_t offset, ElemCount num_elems, CleanContext clean_ctx)
{
TensorEntry::SP* elem = static_cast<TensorEntry::SP*>(buffer) + offset;
for (size_t i = 0; i < num_elems; ++i) {
clean_ctx.extraBytesCleaned((*elem)->get_memory_usage().allocatedBytes());
*elem = _emptyEntry;
++elem;
}
}
StreamedValueStore::StreamedValueStore(const ValueType &tensor_type)
: TensorStore(_concrete_store),
_concrete_store(std::make_unique<TensorBufferType>()),
_tensor_type(tensor_type)
{
_concrete_store.enableFreeLists();
}
StreamedValueStore::~StreamedValueStore() = default;
EntryRef
StreamedValueStore::add_entry(TensorEntry::SP tensor)
{
auto ref = _concrete_store.addEntry(tensor);
auto& state = _concrete_store.getBufferState(RefType(ref).bufferId());
state.incExtraUsedBytes(tensor->get_memory_usage().allocatedBytes());
return ref;
}
const StreamedValueStore::TensorEntry *
StreamedValueStore::get_tensor_entry(EntryRef ref) const
{
if (!ref.valid()) {
return nullptr;
}
const auto& entry = _concrete_store.getEntry(ref);
assert(entry);
return entry.get();
}
void
StreamedValueStore::holdTensor(EntryRef ref)
{
if (!ref.valid()) {
return;
}
const auto& tensor = _concrete_store.getEntry(ref);
assert(tensor);
_concrete_store.holdElem(ref, 1, tensor->get_memory_usage().allocatedBytes());
}
TensorStore::EntryRef
StreamedValueStore::move(EntryRef ref)
{
if (!ref.valid()) {
return EntryRef();
}
const auto& old_tensor = _concrete_store.getEntry(ref);
assert(old_tensor);
auto new_ref = add_entry(old_tensor);
_concrete_store.holdElem(ref, 1, old_tensor->get_memory_usage().allocatedBytes());
return new_ref;
}
bool
StreamedValueStore::encode_tensor(EntryRef ref, vespalib::nbostream &target) const
{
if (const auto * entry = get_tensor_entry(ref)) {
entry->encode_value(_tensor_type, target);
return true;
} else {
return false;
}
}
TensorStore::EntryRef
StreamedValueStore::store_tensor(const Value &tensor)
{
assert(tensor.type() == _tensor_type);
return add_entry(TensorEntry::create_shared_entry(tensor));
}
TensorStore::EntryRef
StreamedValueStore::store_encoded_tensor(vespalib::nbostream &encoded)
{
const auto &factory = StreamedValueBuilderFactory::get();
auto val = vespalib::eval::decode_value(encoded, factory);
return store_tensor(*val);
}
}
| 33.342412 | 145 | 0.699031 | [
"vector"
] |
0904bccb44c4ce445b49a714235ab45f1c9172e8 | 4,781 | cpp | C++ | src/nuclear/tests/dsl/TransientMultiTrigger.cpp | Bidski/NUClearNet.js | cbca598a4a930de48e05653a58f69fe1652c8793 | [
"MIT"
] | null | null | null | src/nuclear/tests/dsl/TransientMultiTrigger.cpp | Bidski/NUClearNet.js | cbca598a4a930de48e05653a58f69fe1652c8793 | [
"MIT"
] | null | null | null | src/nuclear/tests/dsl/TransientMultiTrigger.cpp | Bidski/NUClearNet.js | cbca598a4a930de48e05653a58f69fe1652c8793 | [
"MIT"
] | null | null | null | /*
* Copyright (C) 2013 Trent Houliston <trent@houliston.me>, Jake Woods <jake.f.woods@gmail.com>
* 2014-2017 Trent Houliston <trent@houliston.me>
*
* 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 <catch.hpp>
#include "nuclear"
namespace {
int value = 0;
std::vector<std::pair<int, int>> value_pairs;
struct DataType {
int value;
bool good;
operator bool() const {
return good;
}
};
} // namespace
namespace NUClear {
namespace dsl {
namespace trait {
template <>
struct is_transient<DataType> : public std::true_type {};
} // namespace trait
} // namespace dsl
} // namespace NUClear
namespace {
struct SimpleMessage {
SimpleMessage(int value) : value(value){};
int value;
};
struct TransientTypeGetter : public NUClear::dsl::operation::TypeBind<int> {
template <typename DSL>
static inline DataType get(NUClear::threading::Reaction& /*unused*/) {
// We say for this test that our data is valid if it is odd
return DataType{value, value % 2 == 1};
}
};
class TestReactor : public NUClear::Reactor {
public:
TestReactor(std::unique_ptr<NUClear::Environment> environment) : Reactor(std::move(environment)) {
on<TransientTypeGetter, Trigger<SimpleMessage>>().then([this](const DataType& d, const SimpleMessage& m) {
value_pairs.push_back(std::make_pair(m.value, d.value));
});
on<Startup>().then([this] {
// Our data starts off as invalid
value = 0;
// This should not start a run as our data is invalid
emit(std::make_unique<SimpleMessage>(10));
// Change our value to 1, our transient data is now valid
value = 1;
// This should execute our function resulting in the pair 10,1
emit(std::make_unique<int>(0));
// This should make our transient data invalid again
value = 2;
// This should execute our function resulting in the pair 20,1
emit(std::make_unique<SimpleMessage>(20));
// This should update to a new good value
value = 5;
// This should execute our function resulting in the pair 30,5
emit(std::make_unique<SimpleMessage>(30));
// This should execute our function resulting in the pair 30,5
emit(std::make_unique<int>(0));
// Value is now bad again
value = 10;
// This should execute our function resulting in the pair 30,5
emit(std::make_unique<int>(0));
// TODO(trent): technically the thing that triggered this resulted in invalid data but used old data, do we
// want to stop this?
// TODO(trent): This would result in two states, invalid data, and non existant data
// We are finished the test
powerplant.shutdown();
});
}
};
} // namespace
TEST_CASE("Testing whether getters that return transient data can cache between calls", "[api][transient]") {
NUClear::PowerPlant::Configuration config;
config.thread_count = 1;
NUClear::PowerPlant plant(config);
plant.install<TestReactor>();
plant.start();
// Now we validate the list (which may be in a different order due to NUClear scheduling)
std::sort(std::begin(value_pairs), std::end(value_pairs));
// Check that it was all as expected
REQUIRE(value_pairs.size() == 5);
REQUIRE(value_pairs[0] == std::make_pair(10, 1));
REQUIRE(value_pairs[1] == std::make_pair(20, 1));
REQUIRE(value_pairs[2] == std::make_pair(30, 5));
REQUIRE(value_pairs[3] == std::make_pair(30, 5));
REQUIRE(value_pairs[4] == std::make_pair(30, 5));
}
| 35.414815 | 120 | 0.654884 | [
"vector"
] |
0907ffe8e99626fe4b6315a0b5a83d3847964ec1 | 4,506 | cc | C++ | src/source-position.cc | isabella232/v8 | 30ef8e33f3a199a27ca8512bcee314c9522d03f6 | [
"BSD-3-Clause"
] | 22 | 2016-07-28T03:25:31.000Z | 2022-02-19T02:51:14.000Z | src/source-position.cc | nodejs/v8 | 30ef8e33f3a199a27ca8512bcee314c9522d03f6 | [
"BSD-3-Clause"
] | 10 | 2016-09-30T14:57:49.000Z | 2017-06-30T12:56:01.000Z | src/source-position.cc | isabella232/v8 | 30ef8e33f3a199a27ca8512bcee314c9522d03f6 | [
"BSD-3-Clause"
] | 23 | 2016-08-03T17:43:32.000Z | 2021-03-04T17:09:00.000Z | // Copyright 2016 the V8 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.
#include "src/source-position.h"
#include "src/compilation-info.h"
#include "src/objects-inl.h"
namespace v8 {
namespace internal {
std::ostream& operator<<(std::ostream& out, const SourcePositionInfo& pos) {
Handle<SharedFunctionInfo> function;
if (pos.function.ToHandle(&function)) {
Handle<Script> script(Script::cast(function->script()));
out << "<";
if (script->name()->IsString()) {
out << String::cast(script->name())->ToCString(DISALLOW_NULLS).get();
} else {
out << "unknown";
}
out << ":" << pos.line + 1 << ":" << pos.column + 1 << ">";
} else {
out << "<unknown:" << pos.position.ScriptOffset() << ">";
}
return out;
}
std::ostream& operator<<(std::ostream& out,
const std::vector<SourcePositionInfo>& stack) {
out << stack.back();
for (int i = static_cast<int>(stack.size()) - 2; i >= 0; --i) {
out << " inlined at ";
out << stack[i];
}
return out;
}
std::ostream& operator<<(std::ostream& out, const SourcePosition& pos) {
if (pos.isInlined()) {
out << "<inlined(" << pos.InliningId() << "):";
} else {
out << "<not inlined:";
}
out << pos.ScriptOffset() << ">";
return out;
}
SourcePositionInfo SourcePosition::Info(
Handle<SharedFunctionInfo> function) const {
Handle<Script> script(Script::cast(function->script()));
SourcePositionInfo result(*this);
Script::PositionInfo pos;
if (Script::GetPositionInfo(script, ScriptOffset(), &pos,
Script::WITH_OFFSET)) {
result.line = pos.line;
result.column = pos.column;
}
result.function = function;
return result;
}
std::vector<SourcePositionInfo> SourcePosition::InliningStack(
CompilationInfo* cinfo) const {
if (!isInlined()) {
return std::vector<SourcePositionInfo>{Info(cinfo->shared_info())};
} else {
InliningPosition inl = cinfo->inlined_functions()[InliningId()].position;
std::vector<SourcePositionInfo> stack = inl.position.InliningStack(cinfo);
stack.push_back(Info(cinfo->inlined_functions()[InliningId()].shared_info));
return stack;
}
}
std::vector<SourcePositionInfo> SourcePosition::InliningStack(
Handle<Code> code) const {
Handle<DeoptimizationInputData> deopt_data(
DeoptimizationInputData::cast(code->deoptimization_data()));
if (!isInlined()) {
Handle<SharedFunctionInfo> function(
SharedFunctionInfo::cast(deopt_data->SharedFunctionInfo()));
return std::vector<SourcePositionInfo>{Info(function)};
} else {
InliningPosition inl = deopt_data->InliningPositions()->get(InliningId());
std::vector<SourcePositionInfo> stack = inl.position.InliningStack(code);
if (inl.inlined_function_id == -1) {
stack.push_back(SourcePositionInfo(*this));
} else {
Handle<SharedFunctionInfo> function(SharedFunctionInfo::cast(
deopt_data->LiteralArray()->get(inl.inlined_function_id)));
stack.push_back(Info(function));
}
return stack;
}
}
void SourcePosition::Print(std::ostream& out,
SharedFunctionInfo* function) const {
Script* script = Script::cast(function->script());
Object* source_name = script->name();
Script::PositionInfo pos;
script->GetPositionInfo(ScriptOffset(), &pos, Script::WITH_OFFSET);
out << "<";
if (source_name->IsString()) {
out << String::cast(source_name)
->ToCString(DISALLOW_NULLS, ROBUST_STRING_TRAVERSAL)
.get();
} else {
out << "unknown";
}
out << ":" << pos.line + 1 << ":" << pos.column + 1 << ">";
}
void SourcePosition::Print(std::ostream& out, Code* code) const {
DeoptimizationInputData* deopt_data =
DeoptimizationInputData::cast(code->deoptimization_data());
if (!isInlined()) {
SharedFunctionInfo* function(
SharedFunctionInfo::cast(deopt_data->SharedFunctionInfo()));
Print(out, function);
} else {
InliningPosition inl = deopt_data->InliningPositions()->get(InliningId());
if (inl.inlined_function_id == -1) {
out << *this;
} else {
SharedFunctionInfo* function = SharedFunctionInfo::cast(
deopt_data->LiteralArray()->get(inl.inlined_function_id));
Print(out, function);
}
out << " inlined at ";
inl.position.Print(out, code);
}
}
} // namespace internal
} // namespace v8
| 32.652174 | 80 | 0.648691 | [
"object",
"vector"
] |
090b55846e4210e8cf2c04d55e0c5a319ca13080 | 13,762 | cpp | C++ | lib/seldon/lib/Compil/Seldon/TinyVector.cpp | HongyuHe/lsolver | c791bf192308ba6b564cb60cb3991d2e72093cd7 | [
"Apache-2.0"
] | 7 | 2021-01-31T23:20:07.000Z | 2021-09-09T20:54:15.000Z | lib/seldon/lib/Compil/Seldon/TinyVector.cpp | HongyuHe/lsolver | c791bf192308ba6b564cb60cb3991d2e72093cd7 | [
"Apache-2.0"
] | 1 | 2021-06-07T07:52:38.000Z | 2021-08-13T20:40:55.000Z | lib/seldon/lib/Compil/Seldon/TinyVector.cpp | HongyuHe/lsolver | c791bf192308ba6b564cb60cb3991d2e72093cd7 | [
"Apache-2.0"
] | null | null | null | #include "SeldonFlag.hxx"
#include "SeldonHeader.hxx"
#include "SeldonInline.hxx"
#ifndef SELDON_WITH_COMPILED_LIBRARY
#include "vector/Vector.cxx"
#include "vector/TinyVector.cxx"
#include "matrix/TinyMatrix.cxx"
#endif
namespace Seldon
{
/* TinyVector */
SELDON_EXTERN template ostream& operator <<(ostream&, const Vector<TinyVector<Real_wp, 1> >&);
SELDON_EXTERN template ostream& operator <<(ostream&, const Vector<TinyVector<Real_wp, 2> >&);
SELDON_EXTERN template ostream& operator <<(ostream&, const Vector<TinyVector<Real_wp, 3> >&);
SELDON_EXTERN template ostream& operator <<(ostream&, const Vector<TinyVector<Complex_wp, 1> >&);
SELDON_EXTERN template ostream& operator <<(ostream&, const Vector<TinyVector<Complex_wp, 2> >&);
SELDON_EXTERN template ostream& operator <<(ostream&, const Vector<TinyVector<Complex_wp, 3> >&);
SELDON_EXTERN template class Vector_Base<TinyVector<Real_wp, 1> >;
SELDON_EXTERN template class Vector_Base<TinyVector<Real_wp, 2> >;
SELDON_EXTERN template class Vector_Base<TinyVector<Real_wp, 3> >;
SELDON_EXTERN template class Vector_Base<TinyVector<Real_wp, 4> >;
SELDON_EXTERN template class Vector_Base<TinyVector<Real_wp, 5> >;
SELDON_EXTERN template class Vector_Base<TinyVector<Real_wp, 6> >;
SELDON_EXTERN template class Vector_Base<TinyVector<Real_wp, 7> >;
SELDON_EXTERN template class Vector_Base<TinyVector<Complex_wp, 1> >;
SELDON_EXTERN template class Vector_Base<TinyVector<Complex_wp, 2> >;
SELDON_EXTERN template class Vector_Base<TinyVector<Complex_wp, 3> >;
SELDON_EXTERN template class Vector_Base<TinyVector<Complex_wp, 4> >;
SELDON_EXTERN template class Vector_Base<TinyVector<Complex_wp, 5> >;
SELDON_EXTERN template class Vector_Base<TinyVector<Complex_wp, 6> >;
SELDON_EXTERN template class Vector_Base<TinyVector<Complex_wp, 7> >;
SELDON_EXTERN template Real_wp Norm2_Column(const Matrix<Real_wp>&, int, int);
/* TinyMatrix */
SELDON_EXTERN template void GetCholesky(TinyMatrix<Real_wp, Symmetric, 1, 1>&);
SELDON_EXTERN template void SolveCholesky(const class_SeldonTrans&, const TinyMatrix<Real_wp, Symmetric, 1, 1>&, TinyVector<Real_wp, 1>&);
SELDON_EXTERN template void SolveCholesky(const class_SeldonNoTrans&, const TinyMatrix<Real_wp, Symmetric, 1, 1>&, TinyVector<Real_wp, 1>&);
// 2x2 matrices
SELDON_EXTERN template Real_wp Norm2_Column(const TinyMatrix<Real_wp, General, 2, 2>&, int, int);
SELDON_EXTERN template void GetInverse(TinyMatrix<Real_wp, General, 2, 2>&);
SELDON_EXTERN template void GetInverse(const TinyMatrix<Real_wp, General, 2, 2>&, TinyMatrix<Real_wp, General, 2, 2>&);
SELDON_EXTERN template void GetInverse(TinyMatrix<Complex_wp, General, 2, 2>&);
SELDON_EXTERN template void GetInverse(const TinyMatrix<Complex_wp, General, 2, 2>&, TinyMatrix<Complex_wp, General, 2, 2>&);
SELDON_EXTERN template void GetInverse(TinyMatrix<Real_wp, Symmetric, 2, 2>&);
SELDON_EXTERN template void GetInverse(const TinyMatrix<Real_wp, Symmetric, 2, 2>&, TinyMatrix<Real_wp, Symmetric, 2, 2>&);
SELDON_EXTERN template void GetInverse(TinyMatrix<Complex_wp, Symmetric, 2, 2>&);
SELDON_EXTERN template void GetInverse(const TinyMatrix<Complex_wp, Symmetric, 2, 2>&, TinyMatrix<Complex_wp, Symmetric, 2, 2>&);
SELDON_EXTERN template void GetEigenvalues(TinyMatrix<Real_wp, General, 2, 2>&, TinyVector<Real_wp, 2>&, TinyVector<Real_wp, 2>&);
SELDON_EXTERN template void GetEigenvalues(TinyMatrix<Complex_wp, General, 2, 2>&, TinyVector<Complex_wp, 2>&);
SELDON_EXTERN template void GetEigenvalues(TinyMatrix<Real_wp, Symmetric, 2, 2>&, TinyVector<Real_wp, 2>&);
SELDON_EXTERN template void GetEigenvalues(TinyMatrix<Complex_wp, Symmetric, 2, 2>&, TinyVector<Complex_wp, 2>&);
SELDON_EXTERN template void GetEigenvaluesEigenvectors(TinyMatrix<Real_wp, Symmetric, 2, 2>&, TinyVector<Real_wp, 2>&, TinyMatrix<Real_wp, General, 2, 2>&);
SELDON_EXTERN template void GetSquareRoot(TinyMatrix<Real_wp, Symmetric, 2, 2>&);
SELDON_EXTERN template void GetEigenvaluesEigenvectors(TinyMatrix<Complex_wp, Symmetric, 2, 2>&, TinyVector<Complex_wp, 2>&, TinyMatrix<Complex_wp, General, 2, 2>&);
SELDON_EXTERN template void GetSquareRoot(TinyMatrix<Complex_wp, Symmetric, 2, 2>&);
SELDON_EXTERN template void GetCholesky(TinyMatrix<Real_wp, Symmetric, 2, 2>&);
SELDON_EXTERN template void SolveCholesky(const class_SeldonTrans&, const TinyMatrix<Real_wp, Symmetric, 2, 2>&, TinyVector<Real_wp, 2>&);
SELDON_EXTERN template void SolveCholesky(const class_SeldonNoTrans&, const TinyMatrix<Real_wp, Symmetric, 2, 2>&, TinyVector<Real_wp, 2>&);
SELDON_EXTERN template void MltCholesky(const class_SeldonTrans&, const TinyMatrix<Real_wp, Symmetric, 2, 2>&, TinyVector<Real_wp, 2>&);
SELDON_EXTERN template void MltCholesky(const class_SeldonNoTrans&, const TinyMatrix<Real_wp, Symmetric, 2, 2>&, TinyVector<Real_wp, 2>&);
SELDON_EXTERN template int IntersectionEdges(const TinyVector<Real_wp, 2>& pointA, const TinyVector<Real_wp, 2>& pointB,
const TinyVector<Real_wp, 2>& pt1, const TinyVector<Real_wp, 2>& pt2,
TinyVector<Real_wp, 2>& res, const Real_wp& threshold);
SELDON_EXTERN template int IntersectionDroites(const TinyVector<Real_wp, 2>& pointA, const TinyVector<Real_wp, 2>& pointB,
const TinyVector<Real_wp, 2>& pt1, const TinyVector<Real_wp, 2>& pt2,
TinyVector<Real_wp, 2>& res, const Real_wp& threshold);
// 3x3 matrices
SELDON_EXTERN template Real_wp Norm2_Column(const TinyMatrix<Real_wp, General, 3, 3>&, int, int);
SELDON_EXTERN template Real_wp Det(const TinyMatrix<Real_wp, General, 3, 3>&);
SELDON_EXTERN template Real_wp Det(const TinyMatrix<Real_wp, Symmetric, 3, 3>&);
SELDON_EXTERN template void GetInverse(TinyMatrix<Real_wp, General, 3, 3>&);
SELDON_EXTERN template void GetInverse(const TinyMatrix<Real_wp, General, 3, 3>&, TinyMatrix<Real_wp, General, 3, 3>&);
SELDON_EXTERN template void GetInverse(TinyMatrix<Complex_wp, General, 3, 3>&);
SELDON_EXTERN template void GetInverse(const TinyMatrix<Complex_wp, General, 3, 3>&, TinyMatrix<Complex_wp, General, 3, 3>&);
SELDON_EXTERN template void GetInverse(TinyMatrix<Real_wp, Symmetric, 3, 3>&);
SELDON_EXTERN template void GetInverse(const TinyMatrix<Real_wp, Symmetric, 3, 3>&, TinyMatrix<Real_wp, Symmetric, 3, 3>&);
SELDON_EXTERN template void GetInverse(TinyMatrix<Complex_wp, Symmetric, 3, 3>&);
SELDON_EXTERN template void GetInverse(const TinyMatrix<Complex_wp, Symmetric, 3, 3>&, TinyMatrix<Complex_wp, Symmetric, 3, 3>&);
SELDON_EXTERN template void GetNormalProjector(const TinyVector<Real_wp, 3>&, TinyMatrix<Real_wp, General, 3, 3>&);
SELDON_EXTERN template void GetNormalProjector(const TinyVector<Real_wp, 3>&, TinyMatrix<Real_wp, Symmetric, 3, 3>&);
SELDON_EXTERN template void GetNormalProjector(const TinyVector<Real_wp, 3>&, TinyMatrix<Complex_wp, General, 3, 3>&);
SELDON_EXTERN template void GetNormalProjector(const TinyVector<Real_wp, 3>&, TinyMatrix<Complex_wp, Symmetric, 3, 3>&);
SELDON_EXTERN template void GetNormalProjector(const TinyVector<Complex_wp, 3>&, TinyMatrix<Complex_wp, General, 3, 3>&);
SELDON_EXTERN template void GetNormalProjector(const TinyVector<Complex_wp, 3>&, TinyMatrix<Complex_wp, Symmetric, 3, 3>&);
SELDON_EXTERN template void GetTangentialProjector(const TinyVector<Real_wp, 3>&, TinyMatrix<Real_wp, Symmetric, 3, 3>&);
SELDON_EXTERN template void GetTangentialProjector(const TinyVector<Real_wp, 3>&, TinyMatrix<Complex_wp, Symmetric, 3, 3>&);
SELDON_EXTERN template void GetVectorPlane(const TinyVector<Real_wp, 3>&, TinyVector<Real_wp, 3>&, TinyVector<Real_wp, 3>&);
SELDON_EXTERN template void GetEigenvalues(TinyMatrix<Real_wp, Symmetric, 3, 3>&, TinyVector<Real_wp, 3>&);
SELDON_EXTERN template void GetEigenvalues(TinyMatrix<Complex_wp, Symmetric, 3, 3>&, TinyVector<Complex_wp, 3>&);
SELDON_EXTERN template void GetEigenvaluesEigenvectors(TinyMatrix<Real_wp, Symmetric, 3, 3>&, TinyVector<Real_wp, 3>&, TinyMatrix<Real_wp, General, 3, 3>&);
SELDON_EXTERN template void GetSquareRoot(TinyMatrix<Real_wp, Symmetric, 3, 3>&);
SELDON_EXTERN template void GetEigenvaluesEigenvectors(TinyMatrix<Complex_wp, Symmetric, 3, 3>&, TinyVector<Complex_wp, 3>&, TinyMatrix<Complex_wp, General, 3, 3>&);
SELDON_EXTERN template void GetSquareRoot(TinyMatrix<Complex_wp, Symmetric, 3, 3>&);
SELDON_EXTERN template void GetCholesky(TinyMatrix<Real_wp, Symmetric, 3, 3>&);
SELDON_EXTERN template void SolveCholesky(const class_SeldonTrans&, const TinyMatrix<Real_wp, Symmetric, 3, 3>&, TinyVector<Real_wp, 3>&);
SELDON_EXTERN template void SolveCholesky(const class_SeldonNoTrans&, const TinyMatrix<Real_wp, Symmetric, 3, 3>&, TinyVector<Real_wp, 3>&);
SELDON_EXTERN template void MltCholesky(const class_SeldonTrans&, const TinyMatrix<Real_wp, Symmetric, 3, 3>&, TinyVector<Real_wp, 3>&);
SELDON_EXTERN template void MltCholesky(const class_SeldonNoTrans&, const TinyMatrix<Real_wp, Symmetric, 3, 3>&, TinyVector<Real_wp, 3>&);
// 4x4 matrices
SELDON_EXTERN template void GetInverse(TinyMatrix<Real_wp, General, 4, 4>&);
SELDON_EXTERN template void GetInverse(const TinyMatrix<Real_wp, General, 4, 4>&, TinyMatrix<Real_wp, General, 4, 4>&);
SELDON_EXTERN template void GetInverse(TinyMatrix<Complex_wp, General, 4, 4>&);
SELDON_EXTERN template void GetInverse(const TinyMatrix<Complex_wp, General, 4, 4>&, TinyMatrix<Complex_wp, General, 4, 4>&);
SELDON_EXTERN template void GetInverse(TinyMatrix<Real_wp, Symmetric, 4, 4>&);
SELDON_EXTERN template void GetInverse(const TinyMatrix<Real_wp, Symmetric, 4, 4>&, TinyMatrix<Real_wp, Symmetric, 4, 4>&);
SELDON_EXTERN template void GetInverse(TinyMatrix<Complex_wp, Symmetric, 4, 4>&);
SELDON_EXTERN template void GetInverse(const TinyMatrix<Complex_wp, Symmetric, 4, 4>&, TinyMatrix<Complex_wp, Symmetric, 4, 4>&);
// 5x5 matrices
SELDON_EXTERN template void GetInverse(TinyMatrix<Real_wp, General, 5, 5>&);
SELDON_EXTERN template void GetInverse(const TinyMatrix<Real_wp, General, 5, 5>&, TinyMatrix<Real_wp, General, 5, 5>&);
SELDON_EXTERN template void GetInverse(TinyMatrix<Complex_wp, General, 5, 5>&);
SELDON_EXTERN template void GetInverse(const TinyMatrix<Complex_wp, General, 5, 5>&, TinyMatrix<Complex_wp, General, 5, 5>&);
SELDON_EXTERN template void GetInverse(TinyMatrix<Real_wp, Symmetric, 5, 5>&);
SELDON_EXTERN template void GetInverse(const TinyMatrix<Real_wp, Symmetric, 5, 5>&, TinyMatrix<Real_wp, Symmetric, 5, 5>&);
SELDON_EXTERN template void GetInverse(TinyMatrix<Complex_wp, Symmetric, 5, 5>&);
SELDON_EXTERN template void GetInverse(const TinyMatrix<Complex_wp, Symmetric, 5, 5>&, TinyMatrix<Complex_wp, Symmetric, 5, 5>&);
SELDON_EXTERN template void GetEigenvaluesEigenvectors(TinyMatrix<Real_wp, Symmetric, 5, 5>&, TinyVector<Real_wp, 5>&, TinyMatrix<Real_wp, General, 5, 5>&);
SELDON_EXTERN template void GetSquareRoot(TinyMatrix<Real_wp, Symmetric, 5, 5>&);
SELDON_EXTERN template void GetEigenvaluesEigenvectors(TinyMatrix<Complex_wp, Symmetric, 5, 5>&, TinyVector<Complex_wp, 5>&, TinyMatrix<Complex_wp, General, 5, 5>&);
SELDON_EXTERN template void GetSquareRoot(TinyMatrix<Complex_wp, Symmetric, 5, 5>&);
// 6x6 matrices
SELDON_EXTERN template void GetInverse(TinyMatrix<Real_wp, General, 6, 6>&);
SELDON_EXTERN template void GetInverse(const TinyMatrix<Real_wp, General, 6, 6>&, TinyMatrix<Real_wp, General, 6, 6>&);
SELDON_EXTERN template void GetInverse(TinyMatrix<Complex_wp, General, 6, 6>&);
SELDON_EXTERN template void GetInverse(const TinyMatrix<Complex_wp, General, 6, 6>&, TinyMatrix<Complex_wp, General, 6, 6>&);
SELDON_EXTERN template void GetInverse(TinyMatrix<Real_wp, Symmetric, 6, 6>&);
SELDON_EXTERN template void GetInverse(const TinyMatrix<Real_wp, Symmetric, 6, 6>&, TinyMatrix<Real_wp, Symmetric, 6, 6>&);
SELDON_EXTERN template void GetInverse(TinyMatrix<Complex_wp, Symmetric, 6, 6>&);
SELDON_EXTERN template void GetInverse(const TinyMatrix<Complex_wp, Symmetric, 6, 6>&, TinyMatrix<Complex_wp, Symmetric, 6, 6>&);
// 7x7 matrices
SELDON_EXTERN template void GetInverse(TinyMatrix<Real_wp, General, 7, 7>&);
SELDON_EXTERN template void GetInverse(const TinyMatrix<Real_wp, General, 7, 7>&, TinyMatrix<Real_wp, General, 7, 7>&);
SELDON_EXTERN template void GetInverse(TinyMatrix<Complex_wp, General, 7, 7>&);
SELDON_EXTERN template void GetInverse(const TinyMatrix<Complex_wp, General, 7, 7>&, TinyMatrix<Complex_wp, General, 7, 7>&);
// Norm2_Column
SELDON_EXTERN template Real_wp Norm2_Column(const TinyMatrix<Real_wp, General, 5, 4>&, int, int);
SELDON_EXTERN template Real_wp Norm2_Column(const TinyMatrix<Real_wp, General, 7, 7>&, int, int);
SELDON_EXTERN template Real_wp Norm2_Column(const TinyMatrix<Complex_wp, General, 5, 4>&, int, int);
SELDON_EXTERN template Real_wp Norm2_Column(const TinyMatrix<Complex_wp, General, 7, 7>&, int, int);
SELDON_EXTERN template Real_wp Norm2_Column(const TinyMatrix<Real_wp, Symmetric, 2, 2>&, int, int);
SELDON_EXTERN template Real_wp Norm2_Column(const TinyMatrix<Real_wp, Symmetric, 3, 3>&, int, int);
SELDON_EXTERN template Real_wp Norm2_Column(const TinyMatrix<Real_wp, Symmetric, 5, 5>&, int, int);
SELDON_EXTERN template Real_wp Norm2_Column(const TinyMatrix<Complex_wp, Symmetric, 2, 2>&, int, int);
SELDON_EXTERN template Real_wp Norm2_Column(const TinyMatrix<Complex_wp, Symmetric, 3, 3>&, int, int);
SELDON_EXTERN template Real_wp Norm2_Column(const TinyMatrix<Complex_wp, Symmetric, 5, 5>&, int, int);
}
| 69.505051 | 167 | 0.760427 | [
"vector"
] |
090f732cbcea2a351f21b9a476e739e404947fc9 | 12,018 | cpp | C++ | Plugins/ChaosClothEditor/Source/Chaos/Private/ChaosClothEditor/ChaosSimulationEditorExtender.cpp | monguri/UEChaosSandbox | f586bdfc3c15bb56bdcba69550cd0ecaae6c1e7d | [
"MIT"
] | null | null | null | Plugins/ChaosClothEditor/Source/Chaos/Private/ChaosClothEditor/ChaosSimulationEditorExtender.cpp | monguri/UEChaosSandbox | f586bdfc3c15bb56bdcba69550cd0ecaae6c1e7d | [
"MIT"
] | null | null | null | Plugins/ChaosClothEditor/Source/Chaos/Private/ChaosClothEditor/ChaosSimulationEditorExtender.cpp | monguri/UEChaosSandbox | f586bdfc3c15bb56bdcba69550cd0ecaae6c1e7d | [
"MIT"
] | null | null | null | // Copyright Epic Games, Inc. All Rights Reserved.
#if WITH_CHAOS
#include "ChaosClothEditor/ChaosSimulationEditorExtender.h"
#include "ChaosClothEditorPrivate.h"
#include "ChaosCloth/ChaosClothingSimulationFactory.h"
#include "ChaosCloth/ChaosClothingSimulation.h"
#include "Framework/Commands/UIAction.h"
#include "Framework/MultiBox/MultiBoxBuilder.h"
#include "Animation/DebugSkelMeshComponent.h"
#include "Rendering/SkeletalMeshRenderData.h"
#include "IPersonaPreviewScene.h"
#define LOCTEXT_NAMESPACE "ChaosSimulationEditorExtender"
namespace Chaos
{
struct FVisualizationOption
{
// Actual option entries
static const FVisualizationOption OptionData[];
static const uint32 Count;
// Chaos debug draw function
typedef void (Chaos::FClothingSimulation::*FDebugDrawFunction)(FPrimitiveDrawInterface*) const;
typedef void (Chaos::FClothingSimulation::*FDebugDrawTextsFunction)(FCanvas*, const FSceneView*) const;
FDebugDrawFunction DebugDrawFunction;
FDebugDrawTextsFunction DebugDrawTextsFunction;
FText DisplayName; // Text for menu entries.
FText ToolTip; // Text for menu tooltips.
bool bDisablesSimulation; // Whether or not this option requires the simulation to be disabled.
bool bHidesClothSections; // Hides the cloth section to avoid zfighting with the debug geometry.
FVisualizationOption(FDebugDrawFunction InDebugDrawFunction, const FText& InDisplayName, const FText& InToolTip, bool bInDisablesSimulation = false, bool bInHidesClothSections = false)
: DebugDrawFunction(InDebugDrawFunction)
, DisplayName(InDisplayName)
, ToolTip(InToolTip)
, bDisablesSimulation(bInDisablesSimulation)
, bHidesClothSections(bInHidesClothSections)
{}
FVisualizationOption(FDebugDrawTextsFunction InDebugDrawTextsFunction, const FText& InDisplayName, const FText& InToolTip, bool bInDisablesSimulation = false, bool bInHidesClothSections = false)
: DebugDrawTextsFunction(InDebugDrawTextsFunction)
, DisplayName(InDisplayName)
, ToolTip(InToolTip)
, bDisablesSimulation(bInDisablesSimulation)
, bHidesClothSections(bInHidesClothSections)
{}
};
}
using namespace Chaos;
const FVisualizationOption FVisualizationOption::OptionData[] =
{
FVisualizationOption(&Chaos::FClothingSimulation::DebugDrawPhysMeshShaded , LOCTEXT("ChaosVisName_PhysMesh" , "Physical Mesh (Flat Shaded)"), LOCTEXT("ChaosVisName_PhysMeshShaded_ToolTip" , "Draws the current physical result as a doubled sided flat shaded mesh"), /*bDisablesSimulation =*/false, /*bHidesClothSections=*/true),
FVisualizationOption(&Chaos::FClothingSimulation::DebugDrawPhysMeshWired , LOCTEXT("ChaosVisName_PhysMeshWire" , "Physical Mesh (Wireframe)" ), LOCTEXT("ChaosVisName_PhysMeshWired_ToolTip" , "Draws the current physical mesh result in wireframe")),
FVisualizationOption(&Chaos::FClothingSimulation::DebugDrawAnimMeshWired , LOCTEXT("ChaosVisName_AnimMeshWire" , "Animated Mesh (Wireframe)" ), LOCTEXT("ChaosVisName_AnimMeshWired_ToolTip" , "Draws the current animated mesh input in wireframe")),
FVisualizationOption(&Chaos::FClothingSimulation::DebugDrawParticleIndices , LOCTEXT("ChaosVisName_ParticleIndices" , "Particle Indices" ), LOCTEXT("ChaosVisName_ParticleIndices_ToolTip" , "Draws the particle indices as instantiated by the solver")),
FVisualizationOption(&Chaos::FClothingSimulation::DebugDrawElementIndices , LOCTEXT("ChaosVisName_ElementIndices" , "Element Indices" ), LOCTEXT("ChaosVisName_ElementIndices_ToolTip" , "Draws the element's (triangle or other) indices as instantiated by the solver")),
FVisualizationOption(&Chaos::FClothingSimulation::DebugDrawPointNormals , LOCTEXT("ChaosVisName_PointNormals" , "Point Normals" ), LOCTEXT("ChaosVisName_PointNormals_ToolTip" , "Draws the current point normals for the simulation mesh")),
FVisualizationOption(&Chaos::FClothingSimulation::DebugDrawInversedPointNormals, LOCTEXT("ChaosVisName_InversedPointNormals", "Inversed Point Normals" ), LOCTEXT("ChaosVisName_InversedPointNormals_ToolTip", "Draws the inversed point normals for the simulation mesh")),
FVisualizationOption(&Chaos::FClothingSimulation::DebugDrawCollision , LOCTEXT("ChaosVisName_Collision" , "Collisions" ), LOCTEXT("ChaosVisName_Collision_ToolTip" , "Draws the collision bodies the simulation is currently using")),
FVisualizationOption(&Chaos::FClothingSimulation::DebugDrawBackstops , LOCTEXT("ChaosVisName_Backstop" , "Backstops" ), LOCTEXT("ChaosVisName_Backstop_ToolTip" , "Draws the backstop radius and position for each simulation particle")),
FVisualizationOption(&Chaos::FClothingSimulation::DebugDrawBackstopDistances , LOCTEXT("ChaosVisName_BackstopDistance" , "Backstop Distances" ), LOCTEXT("ChaosVisName_BackstopDistance_ToolTip" , "Draws the backstop distance offset for each simulation particle"), /*bDisablesSimulation =*/true),
FVisualizationOption(&Chaos::FClothingSimulation::DebugDrawMaxDistances , LOCTEXT("ChaosVisName_MaxDistance" , "Max Distances" ), LOCTEXT("ChaosVisName_MaxDistance_ToolTip" , "Draws the current max distances for the sim particles as a line along its normal"), /*bDisablesSimulation =*/true),
FVisualizationOption(&Chaos::FClothingSimulation::DebugDrawMaxDistanceValues , LOCTEXT("ChaosVisName_MaxDistanceValue" , "Max Distances As Numbers" ), LOCTEXT("ChaosVisName_MaxDistanceValue_ToolTip" , "Draws the current max distances as numbers")),
FVisualizationOption(&Chaos::FClothingSimulation::DebugDrawAnimDrive , LOCTEXT("ChaosVisName_AnimDrive" , "Anim Drive" ), LOCTEXT("ChaosVisName_AnimDrive_Tooltip" , "Draws the current skinned reference mesh for the simulation which anim drive will attempt to reach if enabled")),
FVisualizationOption(&Chaos::FClothingSimulation::DebugDrawBendingConstraint , LOCTEXT("ChaosVisName_BendingConstraint" , "Bending Constraint" ), LOCTEXT("ChaosVisName_BendingConstraint_Tooltip" , "Draws the bending spring constraints")),
FVisualizationOption(&Chaos::FClothingSimulation::DebugDrawLongRangeConstraint , LOCTEXT("ChaosVisName_LongRangeConstraint" , "Long Range Constraint" ), LOCTEXT("ChaosVisName_LongRangeConstraint_Tooltip" , "Draws the long range attachment constraint distances")),
FVisualizationOption(&Chaos::FClothingSimulation::DebugDrawWindForces , LOCTEXT("ChaosVisName_WindForces" , "Wind Aerodynamic Forces" ), LOCTEXT("ChaosVisName_Wind_Tooltip" , "Draws the Wind drag and lift forces")),
FVisualizationOption(&Chaos::FClothingSimulation::DebugDrawLocalSpace , LOCTEXT("ChaosVisName_LocalSpace" , "Local Space Reference Bone" ), LOCTEXT("ChaosVisName_LocalSpace_Tooltip" , "Draws the local space reference bone")),
FVisualizationOption(&Chaos::FClothingSimulation::DebugDrawSelfCollision , LOCTEXT("ChaosVisName_SelfCollision" , "Self Collision" ), LOCTEXT("ChaosVisName_SelfCollision_Tooltip" , "Draws the self collision thickness/debugging information")),
};
const uint32 FVisualizationOption::Count = sizeof(OptionData) / sizeof(FVisualizationOption);
FSimulationEditorExtender::FSimulationEditorExtender()
: Flags(false, FVisualizationOption::Count)
{
}
UClass* FSimulationEditorExtender::GetSupportedSimulationFactoryClass()
{
return UChaosClothingSimulationFactory::StaticClass();
}
void FSimulationEditorExtender::ExtendViewportShowMenu(FMenuBuilder& MenuBuilder, TSharedRef<IPersonaPreviewScene> PreviewScene)
{
MenuBuilder.BeginSection(TEXT("ChaosSimulation_Visualizations"), LOCTEXT("VisualizationSection", "Visualizations"));
{
for (uint32 OptionIndex = 0; OptionIndex < FVisualizationOption::Count; ++OptionIndex)
{
// Handler for visualization entry being clicked
const FExecuteAction ExecuteAction = FExecuteAction::CreateLambda([this, OptionIndex, PreviewScene]()
{
Flags[OptionIndex] = !Flags[OptionIndex];
// If we need to toggle the disabled or visibility states, handle it
if (UDebugSkelMeshComponent* const MeshComponent = PreviewScene->GetPreviewMeshComponent())
{
// Disable simulation
const bool bShouldDisableSimulation = ShouldDisableSimulation();
if (bShouldDisableSimulation && MeshComponent->bDisableClothSimulation != bShouldDisableSimulation)
{
MeshComponent->bDisableClothSimulation = !MeshComponent->bDisableClothSimulation;
}
// Hide cloth section
if (FVisualizationOption::OptionData[OptionIndex].bHidesClothSections)
{
const bool bIsClothSectionsVisible = !Flags[OptionIndex];
ShowClothSections(MeshComponent, bIsClothSectionsVisible);
}
}
});
// Checkstate function for visualization entries
const FIsActionChecked IsActionChecked = FIsActionChecked::CreateLambda([this, OptionIndex]()
{
return Flags[OptionIndex];
});
const FUIAction Action(ExecuteAction, FCanExecuteAction(), IsActionChecked);
MenuBuilder.AddMenuEntry(FVisualizationOption::OptionData[OptionIndex].DisplayName, FVisualizationOption::OptionData[OptionIndex].ToolTip, FSlateIcon(), Action, NAME_None, EUserInterfaceActionType::ToggleButton);
}
}
MenuBuilder.EndSection();
}
void FSimulationEditorExtender::DebugDrawSimulation(const IClothingSimulation* Simulation, USkeletalMeshComponent* /*OwnerComponent*/, FPrimitiveDrawInterface* PDI)
{
if (!ensure(Simulation)) { return; }
const FClothingSimulation* const ChaosSimulation = static_cast<const FClothingSimulation*>(Simulation);
for (int32 OptionIndex = 0; OptionIndex < FVisualizationOption::Count; ++OptionIndex)
{
if (Flags[OptionIndex] && FVisualizationOption::OptionData[OptionIndex].DebugDrawFunction)
{
(ChaosSimulation->*(FVisualizationOption::OptionData[OptionIndex].DebugDrawFunction))(PDI);
}
}
}
void FSimulationEditorExtender::DebugDrawSimulationTexts(const IClothingSimulation* Simulation, USkeletalMeshComponent* /*OwnerComponent*/, FCanvas* Canvas, const FSceneView* SceneView)
{
if (!ensure(Simulation)) { return; }
const FClothingSimulation* const ChaosSimulation = static_cast<const FClothingSimulation*>(Simulation);
for (int32 OptionIndex = 0; OptionIndex < FVisualizationOption::Count; ++OptionIndex)
{
if (Flags[OptionIndex] && FVisualizationOption::OptionData[OptionIndex].DebugDrawTextsFunction)
{
(ChaosSimulation->*(FVisualizationOption::OptionData[OptionIndex].DebugDrawTextsFunction))(Canvas, SceneView);
}
}
}
bool FSimulationEditorExtender::ShouldDisableSimulation() const
{
for (uint32 OptionIndex = 0; OptionIndex < FVisualizationOption::Count; ++OptionIndex)
{
if (Flags[OptionIndex])
{
const FVisualizationOption& Data = FVisualizationOption::OptionData[OptionIndex];
if (Data.bDisablesSimulation)
{
return true;
}
}
}
return false;
}
void FSimulationEditorExtender::ShowClothSections(USkeletalMeshComponent* MeshComponent, bool bIsClothSectionsVisible) const
{
if (FSkeletalMeshRenderData* const SkeletalMeshRenderData = MeshComponent->GetSkeletalMeshRenderData())
{
for (int32 LODIndex = 0; LODIndex < SkeletalMeshRenderData->LODRenderData.Num(); ++LODIndex)
{
FSkeletalMeshLODRenderData& SkeletalMeshLODRenderData = SkeletalMeshRenderData->LODRenderData[LODIndex];
for (int32 SectionIndex = 0; SectionIndex < SkeletalMeshLODRenderData.RenderSections.Num(); ++SectionIndex)
{
FSkelMeshRenderSection& SkelMeshRenderSection = SkeletalMeshLODRenderData.RenderSections[SectionIndex];
if (SkelMeshRenderSection.HasClothingData())
{
MeshComponent->ShowMaterialSection(SkelMeshRenderSection.MaterialIndex, SectionIndex, bIsClothSectionsVisible, LODIndex);
}
}
}
}
}
#undef LOCTEXT_NAMESPACE
#endif // #if WITH_CHAOS | 59.791045 | 348 | 0.770012 | [
"mesh",
"geometry"
] |
09165c075ecefea9dd52f57f2a66856dc9798cdf | 23,344 | cpp | C++ | libraries/chain/contract_nht_handle.cpp | prefix309/cocos-mainnet | 17608a80ff9bf1b4ed4d70c88b450d2410891b0d | [
"MIT"
] | 1 | 2020-08-16T06:00:27.000Z | 2020-08-16T06:00:27.000Z | libraries/chain/contract_nht_handle.cpp | prefix309/cocos-mainnet | 17608a80ff9bf1b4ed4d70c88b450d2410891b0d | [
"MIT"
] | null | null | null | libraries/chain/contract_nht_handle.cpp | prefix309/cocos-mainnet | 17608a80ff9bf1b4ed4d70c88b450d2410891b0d | [
"MIT"
] | null | null | null | #include <graphene/chain/contract_object.hpp>
#include <graphene/chain/nh_asset_object.hpp>
#include <graphene/chain/nh_asset_creator_object.hpp>
#include <graphene/chain/world_view_object.hpp>
#include <graphene/chain/contract_function_register_scheduler.hpp>
#include <boost/algorithm/string/split.hpp>
#include <boost/algorithm/string/classification.hpp>
namespace graphene
{
namespace chain
{
const nh_asset_object ®ister_scheduler::get_nh_asset(string hash_or_id)
{
try
{
if (auto id = db.maybe_id<nh_asset_id_type>(hash_or_id))
{
const auto &nh_assets = db.get_index_type<nh_asset_index>().indices().get<by_id>();
auto itr = nh_assets.find(*id);
FC_ASSERT(itr != nh_assets.end(), "not find non homogeneity token: ${token}", ("token", hash_or_id));
return *itr;
}
else
{
const auto &nh_assets = db.get_index_type<nh_asset_index>().indices().get<by_nh_asset_hash_id>();
auto itr = nh_assets.find(nh_hash_type(hash_or_id));
FC_ASSERT(itr != nh_assets.end(), "not find non homogeneity token: ${token}", ("token", hash_or_id));
return *itr;
}
}
catch (fc::exception e)
{
LUA_C_ERR_THROW(this->context.mState, e.to_string());
}
}
string register_scheduler::create_nft_asset(account_id_type owner_id, account_id_type dealer_id, string world_view, string base_describe, bool enable_logger)
{
try
{
const auto &nh_asset_creator_idx_by_nh_asset_creator = db.get_index_type<nh_asset_creator_index>().indices().get<by_nh_asset_creator>();
const auto &nh_asset_creator_idx = nh_asset_creator_idx_by_nh_asset_creator.find(contract.owner);
FC_ASSERT(nh_asset_creator_idx != nh_asset_creator_idx_by_nh_asset_creator.end(), "contract owner isn't a NFT asset creator, so you can't create a NFT asset.");
FC_ASSERT(find(nh_asset_creator_idx->world_view.begin(), nh_asset_creator_idx->world_view.end(), world_view) != nh_asset_creator_idx->world_view.end(),
"contract owner don't have this world view.");
// Verify that if the world view exists
const auto &version_idx_by_symbol = db.get_index_type<world_view_index>().indices().get<by_world_view>();
const auto &ver_idx = version_idx_by_symbol.find(world_view);
FC_ASSERT(ver_idx != version_idx_by_symbol.end(), "The world view does not exist.");
const nh_asset_object &nh_asset_obj = db.create<nh_asset_object>([&](nh_asset_object &nh_asset) {
nh_asset.nh_asset_owner = owner_id;
nh_asset.nh_asset_creator = contract.owner;
nh_asset.nh_asset_active = owner_id;
nh_asset.dealership = dealer_id;
nh_asset.world_view = world_view;
nh_asset.base_describe = base_describe;
nh_asset.create_time = db.head_block_time();
nh_asset.get_hash();
});
if (enable_logger)
{
graphene::chain::nht_affected contract_transaction;
contract_transaction.affected_account = owner_id;
contract_transaction.affected_item = nh_asset_obj.id;
contract_transaction.action = nht_affected_type::create_for;
result.contract_affecteds.push_back(std::move(contract_transaction));
contract_transaction.affected_account = contract.owner;
contract_transaction.action = nht_affected_type::create_by;
result.contract_affecteds.push_back(std::move(contract_transaction));
}
return string(nh_asset_obj.id);
}
catch (fc::exception e)
{
LUA_C_ERR_THROW(this->context.mState, e.to_string());
}
}
string register_scheduler::create_nh_asset(string owner_id_or_name, string symbol, string world_view, string base_describe, bool enable_logger)
{
auto owner_id = get_account(owner_id_or_name).get_id();
return create_nft_asset(owner_id, owner_id, world_view, base_describe, enable_logger);
}
void register_scheduler::nht_describe_change(string nht_hash_or_id, string key, string value, bool enable_logger)
{
try
{
auto &ob = get_nh_asset(nht_hash_or_id);
FC_ASSERT(caller == ob.nh_asset_owner || caller == ob.nh_asset_active, "No permission to modify the corresponding description");
if (ob.nh_asset_owner != ob.nh_asset_active)
{
if (caller == ob.nh_asset_active)
{
auto limit_itr = find(ob.limit_list.begin(), ob.limit_list.end(), contract.id);
if (ob.limit_type == nh_asset_lease_limit_type::white_list)
FC_ASSERT(limit_itr != ob.limit_list.end(), "The designated contracts not found on the whitelist,contract:${contract}", ("contract", contract.id));
else
FC_ASSERT(limit_itr == ob.limit_list.end(), "The designated contract was found on the blacklist,contract:${contract}", ("contract", contract.id));
}
else
FC_THROW("The designated contract was found on the blacklist,nht_token:${nht_token}", ("nht_token", ob.id));
}
if (key.empty())
return;
auto contract_nht_describe_itr = ob.describe_with_contract.find(contract.id);
if (contract_nht_describe_itr == ob.describe_with_contract.end())
{
if (value.empty())
return;
map<string, string> temp_describe;
temp_describe[key] = value;
db.modify(ob, [&](nh_asset_object &gob) {
gob.describe_with_contract[contract.id] = temp_describe;
});
}
else
{
optional<map<string, string>> contract_nht_describe = contract_nht_describe_itr->second;
auto find_itr = contract_nht_describe->find(key);
if (find_itr != (*contract_nht_describe).end())
{
if (value.empty())
contract_nht_describe->erase(find_itr);
else
find_itr->second = value;
}
else
{
if (value.empty())
return;
(*contract_nht_describe).insert(map<string, string>::value_type(key, value));
}
db.modify(ob, [&](nh_asset_object &gob) {
if (contract_nht_describe->size() == 0)
gob.describe_with_contract.erase(gob.describe_with_contract.find(contract.id));
else
gob.describe_with_contract[contract.id] = *contract_nht_describe;
});
}
if (enable_logger)
{
graphene::chain::nht_affected contract_transaction;
contract_transaction.affected_account = caller;
contract_transaction.affected_item = ob.id;
contract_transaction.action = nht_affected_type::modified;
contract_transaction.modified = std::pair<string, string>(key, value);
result.contract_affecteds.push_back(std::move(contract_transaction));
}
}
catch (fc::exception e)
{
LUA_C_ERR_THROW(this->context.mState, e.to_string());
}
}
void register_scheduler::transfer_nht(account_id_type from, account_id_type account_to, const nh_asset_object &token, bool enable_logger)
{
try
{
// Verify asset transfer
nft::assert_asset_transfer(from, account_to, token);
// Verify asset unlocked
nft::assert_asset_unlocked(from(db), token);
db.modify(token, [&](nh_asset_object &g) {
g.nh_asset_owner = account_to;
g.nh_asset_active = account_to;
g.dealership = account_to;
});
if (enable_logger)
{
graphene::chain::nht_affected contract_transaction;
contract_transaction.affected_account = from;
contract_transaction.affected_item = token.id;
contract_transaction.action = nht_affected_type::transfer_from;
result.contract_affecteds.push_back(std::move(contract_transaction));
contract_transaction.affected_account = account_to;
contract_transaction.affected_item = token.id;
contract_transaction.action = nht_affected_type::transfer_to;
result.contract_affecteds.push_back(std::move(contract_transaction));
}
}
catch (fc::exception e)
{
LUA_C_ERR_THROW(this->context.mState, e.to_string());
}
}
// transfer of non homogeneous asset's use rights
void register_scheduler::transfer_nht_active(account_id_type from, account_id_type account_to, const nh_asset_object &token, bool enable_logger)
{
try
{
if (token.dealership != from) // if the trader is not the authority account, carry out the following checks
{
FC_ASSERT(token.nh_asset_active == from, "You're not the nh asset's active, so you can't transfer it'suse rights, nh asset:${token}.", ("token", token));
}
FC_ASSERT(account_to != token.nh_asset_active, "You can't transfer it to yourslef, nh asset:${token}.", ("token", token));
db.modify(token, [&](nh_asset_object &g) {from= g.nh_asset_active;g.nh_asset_active = account_to; });
if (enable_logger)
{
graphene::chain::nht_affected contract_transaction;
contract_transaction.affected_account = from;
contract_transaction.affected_item = token.id;
contract_transaction.action = nht_affected_type::transfer_active_from;
result.contract_affecteds.push_back(std::move(contract_transaction));
contract_transaction.affected_account = account_to;
contract_transaction.affected_item = token.id;
contract_transaction.action = nht_affected_type::transfer_active_to;
result.contract_affecteds.push_back(std::move(contract_transaction));
}
}
catch (fc::exception e)
{
LUA_C_ERR_THROW(this->context.mState, e.to_string());
}
}
void register_scheduler::transfer_nft_ownership(account_id_type from, account_id_type account_to, const nh_asset_object &token, bool enable_logger)
{
try
{
// Verify that the trader is the owner of nh asset
FC_ASSERT(token.nh_asset_owner == from, "You're not the NFT asset's owner, so you can't transfer its ownership, NFT asset:${token}.", ("token", token));
FC_ASSERT(account_to != token.nh_asset_owner, "You can't transfer it to yourslef, nh asset:${token}.", ("token", token));
// Verify asset unlocked
nft::assert_asset_unlocked(from(db), token);
db.modify(token, [&](nh_asset_object &g) { g.nh_asset_owner = account_to; });
if (enable_logger)
{
graphene::chain::nht_affected contract_transaction;
contract_transaction.affected_account = from;
contract_transaction.affected_item = token.id;
contract_transaction.action = nht_affected_type::transfer_owner_from;
result.contract_affecteds.push_back(std::move(contract_transaction));
contract_transaction.affected_account = account_to;
contract_transaction.affected_item = token.id;
contract_transaction.action = nht_affected_type::transfer_owner_to;
result.contract_affecteds.push_back(std::move(contract_transaction));
}
}
catch (fc::exception e)
{
LUA_C_ERR_THROW(this->context.mState, e.to_string());
}
}
/*
// transfer of non homogeneous asset's ownership
void register_scheduler::transfer_nht_ownership(account_id_type from, account_id_type account_to, const nh_asset_object &token, bool enable_logger)
{
try
{
if (token.dealership != from) // if the trader is not the authority account, carry out the following checks
{
// Verify that the trader is the owner of nh asset
FC_ASSERT(token.nh_asset_owner == from, "You're not the nh asset's owner, so you can't transfer it's ownership, nh asset:${token}.", ("token", token));
// If the trader owns the active of the nh asset , or the ownership of the nh asset is transferred to the owner of the nh asset, the transfer of the ownership can be used.
FC_ASSERT(token.nh_asset_active == from || token.nh_asset_active == account_to, "You're not the nh asset's active, or transfer to the active, nh asset:${token}.", ("token", token));
}
FC_ASSERT(account_to != token.nh_asset_owner, "You can't transfer it to yourslef, nh asset:${token}.", ("token", token));
db.modify(token, [&](nh_asset_object &g) { g.nh_asset_owner = account_to; });
if (enable_logger)
{
graphene::chain::nht_affected contract_transaction;
contract_transaction.affected_account = from;
contract_transaction.affected_item = token.id;
contract_transaction.action = nht_affected_type::transfer_owner_from;
result.contract_affecteds.push_back(std::move(contract_transaction));
contract_transaction.affected_account = account_to;
contract_transaction.affected_item = token.id;
contract_transaction.action = nht_affected_type::transfer_owner_to;
result.contract_affecteds.push_back(std::move(contract_transaction));
}
}
catch (fc::exception e)
{
LUA_C_ERR_THROW(this->context.mState, e.to_string());
}
}
*/
// transfer of non homogeneous asset's authority
void register_scheduler::transfer_nht_dealership(account_id_type from, account_id_type account_to, const nh_asset_object &token, bool enable_logger)
{
try
{
// Verify that the trader is the authority account of nh asset
FC_ASSERT(token.dealership == from, "You're not the nh asset's authority account, so you can't transfer it's authority, nh asset:${token}.", ("token", token));
FC_ASSERT(account_to != from, "You can't transfer it to yourslef, nh asset:${token}.", ("token", token));
db.modify(token, [&](nh_asset_object &g) { g.dealership = account_to; });
if (enable_logger)
{
graphene::chain::nht_affected contract_transaction;
contract_transaction.affected_account = from;
contract_transaction.affected_item = token.id;
contract_transaction.action = nht_affected_type::transfer_authority_from;
result.contract_affecteds.push_back(std::move(contract_transaction));
contract_transaction.affected_account = account_to;
contract_transaction.affected_item = token.id;
contract_transaction.action = nht_affected_type::transfer_authority_to;
result.contract_affecteds.push_back(std::move(contract_transaction));
}
}
catch (fc::exception e)
{
LUA_C_ERR_THROW(this->context.mState, e.to_string());
}
}
// set non homogeneous asset's limit list
void register_scheduler::set_nht_limit_list(account_id_type nht_owner, const nh_asset_object &token, const string &contract_name_or_ids, bool limit_type, bool enable_logger)
{
try
{
// Verify that the trader is the owner of nh asset and the nht must not be leasing.
FC_ASSERT(token.nh_asset_owner == nht_owner && token.nh_asset_owner == token.nh_asset_active, "You must be the nh asset's owner, and the nht must not be leasing, nh asset:${token}.", ("token", token));
auto temp_object = token;
limit_type ? temp_object.limit_type = nh_asset_lease_limit_type::white_list : temp_object.limit_type = nh_asset_lease_limit_type::black_list;
if (temp_object.limit_type != token.limit_type)
temp_object.limit_list.clear();
contract_id_type contract_id;
flat_set<string> contracts;
boost::split(contracts, contract_name_or_ids, boost::is_any_of(" ,"), boost::token_compress_on);
for (auto contract_itr = contracts.begin(); contract_itr != contracts.end(); contract_itr++)
{
if (contract_itr->empty())
continue;
if (auto id = db.maybe_id<contract_id_type>(*contract_itr))
{
const auto &contracts = db.get_index_type<contract_index>().indices().get<by_id>();
auto itr = contracts.find(*id);
FC_ASSERT(itr != contracts.end(), "not find contract: ${contract}", ("contract", *contract_itr));
contract_id = itr->id;
}
else
{
const auto &contracts = db.get_index_type<contract_index>().indices().get<by_name>();
auto itr = contracts.find(*contract_itr);
FC_ASSERT(itr != contracts.end(), "not find contract: ${contract}", ("contract", *contract_itr));
contract_id = itr->id;
}
if (temp_object.limit_list.end() == find(temp_object.limit_list.begin(), temp_object.limit_list.end(), contract_id))
{
temp_object.limit_list.push_back(std::move(contract_id));
}
}
db.modify(token, [&](nh_asset_object &g) { g = temp_object; });
if (enable_logger)
{
graphene::chain::nht_affected contract_transaction;
contract_transaction.affected_account = nht_owner;
contract_transaction.affected_item = token.id;
contract_transaction.action = nht_affected_type::set_limit_list;
result.contract_affecteds.push_back(std::move(contract_transaction));
}
}
catch (fc::exception e)
{
LUA_C_ERR_THROW(this->context.mState, e.to_string());
}
}
void register_scheduler::relate_nh_asset(account_id_type nht_creator, const nh_asset_object &parent_nh_asset, const nh_asset_object &child_nh_asset, bool relate, bool enable_logger)
{
try
{
if (!(trx_state->skip & (database::validation_steps::skip_transaction_signatures |database::validation_steps::skip_authority_check)))
FC_ASSERT(sigkeys.find(contract.contract_authority)!=sigkeys.end(),"${contract_authority},${sigkeys}",("contract_authority",contract.contract_authority)("sigkeys",sigkeys));
FC_ASSERT(parent_nh_asset.nh_asset_owner==nht_creator,"You're not the parent nh asset's creator, so you can't relate it.${id}",("id",parent_nh_asset.id));
FC_ASSERT(child_nh_asset.nh_asset_owner==nht_creator,"You're not the child nh asset's creator, so you can't relate it.${id}",("id",child_nh_asset.id));
// Verify that the trader is the creator of nh asset
const auto& contract_id = this->contract.id;
const auto &iter = parent_nh_asset.child.find(contract_id);
if ( relate )
{
if (iter != parent_nh_asset.child.end())
{
FC_ASSERT(find(iter->second.begin(), iter->second.end(), child_nh_asset.id) == iter->second.end(), "The parent item and child item had be related.");
db.modify(parent_nh_asset, [&](nh_asset_object &g) {g.child[contract_id].emplace_back(child_nh_asset.id);});
db.modify(child_nh_asset, [&](nh_asset_object &g) {g.parent[contract_id].emplace_back(parent_nh_asset.id);});
}
else
{
db.modify(parent_nh_asset, [&](nh_asset_object &g) {g.child.emplace(contract_id, vector<nh_asset_id_type>(1, child_nh_asset.id));});
db.modify(child_nh_asset, [&](nh_asset_object &g) {g.parent.emplace(contract_id, vector<nh_asset_id_type>(1, parent_nh_asset.id));});
}
}
else
{
FC_ASSERT( iter != parent_nh_asset.child.end(), "The parent nh asset's parent dosen't contain this contract.");
FC_ASSERT(find(iter->second.begin(), iter->second.end(), child_nh_asset.id) != iter->second.end(),
"The parent nh asset and child nh asset did not relate.");
db.modify(parent_nh_asset, [&](nh_asset_object &g) {
g.child[contract_id].erase(find(g.child[contract_id].begin(), g.child[contract_id].end(), child_nh_asset.id));
});
db.modify(child_nh_asset, [&](nh_asset_object &g) {
g.parent[contract_id].erase(find(g.parent[contract_id].begin(), g.parent[contract_id].end(), parent_nh_asset.id));
});
}
if (enable_logger)
{
graphene::chain::nht_affected contract_transaction;
contract_transaction.affected_account = nht_creator;
contract_transaction.affected_item = parent_nh_asset.id;
contract_transaction.action = nht_affected_type::relate_nh_asset;
result.contract_affecteds.emplace_back(contract_transaction);
contract_transaction.affected_item = child_nh_asset.id;
result.contract_affecteds.emplace_back(std::move(contract_transaction));
}
}
catch (fc::exception e)
{
LUA_C_ERR_THROW(this->context.mState, e.to_string());
}
}
void register_scheduler::adjust_lock_nft_asset(const nh_asset_object &token, bool lock_or_unlock)
{
try
{
auto contract_owner = contract.owner(db);
auto contract_id = contract.get_id();
auto nft_asset_id = token.get_id();
// Verify if the contract owner owns the NFT asset
FC_ASSERT( token.nh_asset_owner == contract_owner.get_id(), "The contract owner doesn't own the NFT token, token:${token}", ("token", token));
vector<nh_asset_id_type> nft_locked = contract_owner.asset_locked.nft_locked;
vector<nh_asset_id_type>::iterator find_pos = std::find(nft_locked.begin(), nft_locked.end(), nft_asset_id);
bool is_already_locked = (find_pos != nft_locked.end());
vector<nh_asset_id_type> contract_nft_lock_details = contract_owner.asset_locked.contract_nft_lock_details[contract_id];
if (lock_or_unlock)
{
// to lock
FC_ASSERT( !is_already_locked, "The NFT token has already been locked somewhere, token:${token}", ("token", token));
nft_locked.push_back(nft_asset_id);
contract_nft_lock_details.push_back(nft_asset_id);
}
else
{
// to unlock
FC_ASSERT( is_already_locked, "The NFT token has not be locked anywhere, token:${token}", ("token", token));
vector<nh_asset_id_type>::iterator contract_find_pos = std::find(contract_nft_lock_details.begin(), contract_nft_lock_details.end(), nft_asset_id);
FC_ASSERT( contract_find_pos != contract_nft_lock_details.end(), "The NFT token has already been locked by some other contract, token:${token}", ("token", token));
nft_locked.erase(find_pos);
contract_nft_lock_details.erase(contract_find_pos);
}
// update locked asset
contract_owner.asset_locked.nft_locked = nft_locked;
contract_owner.asset_locked.contract_nft_lock_details[contract_id] = contract_nft_lock_details;
db.modify(contract.owner(db), [&](account_object &ac) {
ac.asset_locked = contract_owner.asset_locked;
});
}
catch (fc::exception e)
{
LUA_C_ERR_THROW(this->context.mState, e.to_string());
}
}
} // namespace chain
} // namespace graphene
| 48.231405 | 209 | 0.656314 | [
"vector"
] |
0917e3ded7cbefd159987e61deb87a5f2b4b402c | 36,088 | cpp | C++ | src/plugins/lmp/playlistwidget.cpp | ForNeVeR/leechcraft | 384d041d23b1cdb7cc3c758612ac8d68d3d3d88c | [
"BSL-1.0"
] | 1 | 2017-01-12T07:05:45.000Z | 2017-01-12T07:05:45.000Z | src/plugins/lmp/playlistwidget.cpp | ForNeVeR/leechcraft | 384d041d23b1cdb7cc3c758612ac8d68d3d3d88c | [
"BSL-1.0"
] | null | null | null | src/plugins/lmp/playlistwidget.cpp | ForNeVeR/leechcraft | 384d041d23b1cdb7cc3c758612ac8d68d3d3d88c | [
"BSL-1.0"
] | null | null | null | /**********************************************************************
* LeechCraft - modular cross-platform feature rich internet client.
* Copyright (C) 2006-2014 Georg Rudoy
*
* Boost Software License - Version 1.0 - August 17th, 2003
*
* Permission is hereby granted, free of charge, to any person or organization
* obtaining a copy of the software and accompanying documentation covered by
* this license (the "Software") to use, reproduce, display, distribute,
* execute, and transmit the Software, and to prepare derivative works of the
* Software, and to permit third-parties to whom the Software is furnished to
* do so, all subject to the following:
*
* The copyright notices in the Software and this entire statement, including
* the above license grant, this restriction and the following disclaimer,
* must be included in all copies of the Software, in whole or in part, and
* all derivative works of the Software, unless such copies or derivative
* works are solely in the form of machine-executable object code generated by
* a source language processor.
*
* 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, TITLE AND NON-INFRINGEMENT. IN NO EVENT
* SHALL THE COPYRIGHT HOLDERS OR ANYONE DISTRIBUTING THE SOFTWARE BE LIABLE
* FOR ANY DAMAGES OR OTHER LIABILITY, WHETHER IN CONTRACT, TORT OR OTHERWISE,
* ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
* DEALINGS IN THE SOFTWARE.
**********************************************************************/
#include "playlistwidget.h"
#include <algorithm>
#include <QToolBar>
#include <QInputDialog>
#include <QFileDialog>
#include <QActionGroup>
#include <QToolButton>
#include <QMenu>
#include <QUndoStack>
#include <QMessageBox>
#include <QClipboard>
#include <QApplication>
#include <QKeyEvent>
#include <QSortFilterProxyModel>
#include <QTimer>
#include <QPainter>
#include <QScrollBar>
#include <util/util.h>
#include <util/xpc/util.h>
#include <util/xpc/defaulthookproxy.h>
#include <util/gui/clearlineeditaddon.h>
#include <util/sll/functional.h>
#include <util/sll/slotclosure.h>
#include <util/sll/delayedexecutor.h>
#include <util/sll/prelude.h>
#include <interfaces/core/iiconthememanager.h>
#include <interfaces/core/ientitymanager.h>
#include <interfaces/core/ipluginsmanager.h>
#include <interfaces/an/ianrulesstorage.h>
#include "player.h"
#include "playlistdelegate.h"
#include "xmlsettingsmanager.h"
#include "core.h"
#include "playlistmanager.h"
#include "staticplaylistmanager.h"
#include "audiopropswidget.h"
#include "playlistundocommand.h"
#include "sortingcriteriadialog.h"
#include "util.h"
#include "palettefixerfilter.h"
#include "engine/sourceobject.h"
#include "hookinterconnector.h"
#include "playlistwidgetviewexpander.h"
Q_DECLARE_METATYPE (QList<LeechCraft::Entity>)
namespace LeechCraft
{
namespace LMP
{
namespace
{
class PlaylistTreeEventFilter : public QObject
{
Player * const Player_;
const QTreeView * const View_;
const QSortFilterProxyModel * const PlaylistFilter_;
bool HadPress_ = false;
public:
PlaylistTreeEventFilter (Player* player,
QTreeView *view,
QSortFilterProxyModel *filter,
QObject *parent = nullptr)
: QObject { parent }
, Player_ { player }
, View_ { view }
, PlaylistFilter_ { filter }
{
}
bool eventFilter (QObject*, QEvent *e)
{
const auto type = e->type ();
if (type != QEvent::KeyRelease &&
type != QEvent::KeyPress)
return false;
auto keyEvent = static_cast<QKeyEvent*> (e);
const auto key = keyEvent->key ();
const bool isSuitable = key == Qt::Key_Enter ||
key == Qt::Key_Return ||
(key == Qt::Key_Space && keyEvent->modifiers () == Qt::NoModifier);
if (!isSuitable)
return false;
if (keyEvent->isAutoRepeat () ||
keyEvent->count () > 1)
return false;
if (type == QEvent::KeyPress)
{
HadPress_ = true;
return false;
}
if (!HadPress_)
return false;
HadPress_ = false;
Player_->play (PlaylistFilter_->mapToSource (View_->currentIndex ()));
return true;
}
};
class TreeFilterModel : public QSortFilterProxyModel
{
public:
TreeFilterModel (QObject *parent = 0)
: QSortFilterProxyModel (parent)
{
setDynamicSortFilter (true);
}
protected:
bool filterAcceptsRow (int row, const QModelIndex& parent) const
{
const auto& str = filterRegExp ().pattern ();
if (str.isEmpty ())
return true;
auto check = [&str] (const QString& string)
{
return string.contains (str, Qt::CaseInsensitive);
};
const auto& idx = sourceModel ()->index (row, 0, parent);
const auto& info = idx.data (Player::Role::Info).value<MediaInfo> ();
bool isInt = false;
if (check (info.Artist_) ||
check (info.Album_) ||
(info.Year_ == str.toInt (&isInt) && isInt))
return true;
if (check (info.Title_) || check (info.LocalPath_))
return true;
for (int i = 0, rc = sourceModel ()->rowCount (idx); i < rc; ++i)
if (filterAcceptsRow (i, idx))
return true;
return false;
}
};
}
PlaylistWidget::PlaylistWidget (QWidget *parent)
: QWidget (parent)
, PlaylistToolbar_ (new QToolBar ())
, PlaylistFilter_ (new TreeFilterModel (this))
, UndoStack_ (new QUndoStack (this))
{
qRegisterMetaType<QItemSelection> ("QItemSelection");
Ui_.setupUi (this);
Ui_.BufferProgress_->hide ();
connect (Ui_.SearchPlaylist_,
SIGNAL (textChanged (QString)),
PlaylistFilter_,
SLOT (setFilterFixedString (QString)));
new PlaylistWidgetViewExpander { PlaylistFilter_, [this] { expandAll (); }, this };
connect (PlaylistFilter_,
SIGNAL (modelReset ()),
this,
SLOT (expandAll ()),
Qt::QueuedConnection);
connect (PlaylistFilter_,
SIGNAL (modelReset ()),
this,
SLOT (checkSelections ()),
Qt::QueuedConnection);
connect (PlaylistFilter_,
SIGNAL (modelAboutToBeReset ()),
this,
SLOT (savePlayScrollPosition ()));
Core::Instance ().GetHookInterconnector ()->RegisterHookable (this);
}
void PlaylistWidget::SetPlayer (Player *player, const ICoreProxy_ptr& proxy)
{
new Util::ClearLineEditAddon (proxy, Ui_.SearchPlaylist_);
Ui_.Playlist_->setItemDelegate (new PlaylistDelegate (Ui_.Playlist_, Ui_.Playlist_, proxy));
Proxy_ = proxy;
Player_ = player;
connect (Player_,
SIGNAL (bufferStatusChanged (int)),
this,
SLOT (handleBufferStatus (int)));
connect (Player_,
SIGNAL (songChanged (MediaInfo)),
this,
SLOT (handleSongChanged (MediaInfo)));
const auto model = Player_->GetPlaylistModel ();
PlaylistFilter_->setSourceModel (model);
Ui_.Playlist_->setModel (PlaylistFilter_);
Ui_.Playlist_->expandAll ();
connect (Ui_.Playlist_,
SIGNAL (doubleClicked (QModelIndex)),
this,
SLOT (play (QModelIndex)));
connect (Player_,
SIGNAL (insertedAlbum (QModelIndex)),
this,
SLOT (expand (QModelIndex)));
Ui_.PlaylistLayout_->addWidget (PlaylistToolbar_);
InitCommonActions ();
InitViewActions ();
InitToolbarActions ();
connect (model,
SIGNAL (rowsInserted (QModelIndex, int, int)),
this,
SLOT (updateStatsLabel ()),
Qt::QueuedConnection);
connect (model,
SIGNAL (rowsRemoved (QModelIndex, int, int)),
this,
SLOT (updateStatsLabel ()),
Qt::QueuedConnection);
connect (model,
SIGNAL (modelReset ()),
this,
SLOT (updateStatsLabel ()),
Qt::QueuedConnection);
connect (Ui_.Playlist_->selectionModel (),
SIGNAL (selectionChanged (QItemSelection, QItemSelection)),
this,
SLOT (updateStatsLabel ()),
Qt::QueuedConnection);
updateStatsLabel ();
connect (Ui_.Playlist_->selectionModel (),
SIGNAL (currentChanged (QModelIndex, QModelIndex)),
this,
SLOT (updateDownloadAction ()));
connect (Ui_.Playlist_->selectionModel (),
SIGNAL (selectionChanged (QItemSelection, QItemSelection)),
this,
SLOT (updateDownloadAction ()));
Ui_.Playlist_->installEventFilter (new PlaylistTreeEventFilter (Player_,
Ui_.Playlist_,
PlaylistFilter_));
new PaletteFixerFilter (Ui_.Playlist_);
connect (player,
SIGNAL (shouldClearFiltering ()),
Ui_.SearchPlaylist_,
SLOT (clear ()));
}
void PlaylistWidget::InitCommonActions ()
{
ActionDownloadTrack_ = new QAction (tr ("Download..."), this);
ActionDownloadTrack_->setProperty ("ActionIcon", "download");
connect (ActionDownloadTrack_,
SIGNAL (triggered ()),
this,
SLOT (handleDownload ()));
}
void PlaylistWidget::InitToolbarActions ()
{
QAction *clearPlaylist = new QAction (tr ("Clear..."), this);
clearPlaylist->setProperty ("ActionIcon", "edit-clear-list");
connect (clearPlaylist,
SIGNAL (triggered ()),
Player_,
SLOT (clear ()));
PlaylistToolbar_->addAction (clearPlaylist);
QAction *savePlaylist = new QAction (tr ("Save playlist..."), this);
savePlaylist->setProperty ("ActionIcon", "document-save");
connect (savePlaylist,
SIGNAL (triggered ()),
this,
SLOT (handleSavePlaylist ()));
PlaylistToolbar_->addAction (savePlaylist);
QAction *loadFiles = new QAction (tr ("Load from disk..."), this);
loadFiles->setProperty ("ActionIcon", "document-open");
connect (loadFiles,
SIGNAL (triggered ()),
this,
SLOT (loadFromDisk ()));
PlaylistToolbar_->addAction (loadFiles);
QAction *addURL = new QAction (tr ("Add URL..."), this);
addURL->setProperty ("ActionIcon", "folder-remote");
connect (addURL,
SIGNAL (triggered ()),
this,
SLOT (addURL ()));
PlaylistToolbar_->addAction (addURL);
PlaylistToolbar_->addSeparator ();
PlaylistToolbar_->addAction (ActionDownloadTrack_);
PlaylistToolbar_->addSeparator ();
ActionMoveTop_ = new QAction (tr ("Move tracks to top"), Ui_.Playlist_);
ActionMoveTop_->setProperty ("ActionIcon", "go-top");
connect (ActionMoveTop_,
SIGNAL (triggered ()),
this,
SLOT (handleMoveTop ()));
ActionMoveUp_ = new QAction (tr ("Move tracks up"), Ui_.Playlist_);
ActionMoveUp_->setProperty ("ActionIcon", "go-up");
ActionMoveUp_->setShortcut (QString ("Ctrl+Up"));
connect (ActionMoveUp_,
SIGNAL (triggered ()),
this,
SLOT (handleMoveUp ()));
ActionMoveDown_ = new QAction (tr ("Move tracks down"), Ui_.Playlist_);
ActionMoveDown_->setProperty ("ActionIcon", "go-down");
ActionMoveDown_->setShortcut (QString ("Ctrl+Down"));
connect (ActionMoveDown_,
SIGNAL (triggered ()),
this,
SLOT (handleMoveDown ()));
ActionMoveBottom_ = new QAction (tr ("Move tracks to bottom"), Ui_.Playlist_);
ActionMoveBottom_->setProperty ("ActionIcon", "go-bottom");
connect (ActionMoveBottom_,
SIGNAL (triggered ()),
this,
SLOT (handleMoveBottom ()));
auto moveUpButton = new QToolButton;
moveUpButton->setDefaultAction (ActionMoveUp_);
moveUpButton->setMenu (new QMenu);
moveUpButton->menu ()->addAction (ActionMoveTop_);
auto moveDownButton = new QToolButton;
moveDownButton->setDefaultAction (ActionMoveDown_);
moveDownButton->setMenu (new QMenu);
moveDownButton->menu ()->addAction (ActionMoveBottom_);
SetPlayModeButton ();
SetSortOrderButton ();
auto shuffleAction = new QAction (tr ("Shuffle tracks"), Ui_.Playlist_);
shuffleAction->setProperty ("ActionIcon", "media-playlist-shuffle");
connect (shuffleAction,
SIGNAL (triggered ()),
Player_,
SLOT (shufflePlaylist ()));
PlaylistToolbar_->addAction (shuffleAction);
MoveUpButtonAction_ = PlaylistToolbar_->addWidget (moveUpButton);
MoveDownButtonAction_ = PlaylistToolbar_->addWidget (moveDownButton);
EnableMoveButtons (false);
PlaylistToolbar_->addSeparator ();
auto undo = UndoStack_->createUndoAction (this);
undo->setProperty ("ActionIcon", "edit-undo");
undo->setShortcut (QKeySequence ("Ctrl+Z"));
PlaylistToolbar_->addAction (undo);
auto redo = UndoStack_->createRedoAction (this);
redo->setProperty ("ActionIcon", "edit-redo");
PlaylistToolbar_->addAction (redo);
PlaylistToolbar_->addSeparator ();
PlaylistToolbar_->addAction (ActionToggleSearch_);
}
void PlaylistWidget::SetPlayModeButton ()
{
auto playButton = new QToolButton;
playButton->setIcon (Proxy_->GetIconThemeManager ()->GetIcon ("view-media-playlist"));
playButton->setPopupMode (QToolButton::InstantPopup);
QMenu *playMode = new QMenu (tr ("Play mode"));
playButton->setMenu (playMode);
const std::vector<std::pair<Player::PlayMode, QString>> modes =
{
{ Player::PlayMode::Sequential, tr ("Sequential") },
{ Player::PlayMode::Shuffle, tr ("Shuffle") },
{ Player::PlayMode::ShuffleAlbums, tr ("Shuffle albums") },
{ Player::PlayMode::ShuffleArtists, tr ("Shuffle artists") },
{ Player::PlayMode::RepeatTrack, tr ("Repeat track") },
{ Player::PlayMode::RepeatAlbum, tr ("Repeat album") },
{ Player::PlayMode::RepeatWhole, tr ("Repeat whole") }
};
PlayModesGroup_ = new QActionGroup (this);
bool hadChecked = false;
for (const auto& pair : modes)
{
QAction *action = new QAction (pair.second, this);
action->setProperty ("PlayMode", static_cast<int> (pair.first));
action->setCheckable (true);
action->setChecked (hadChecked ? false : hadChecked = true);
action->setActionGroup (PlayModesGroup_);
playMode->addAction (action);
connect (action,
SIGNAL (triggered ()),
this,
SLOT (handleChangePlayMode ()));
}
connect (Player_,
SIGNAL (playModeChanged (Player::PlayMode)),
this,
SLOT (handlePlayModeChanged (Player::PlayMode)));
const int resumeMode = XmlSettingsManager::Instance ()
.Property ("PlayMode", static_cast<int> (Player::PlayMode::Sequential)).toInt ();
Player_->SetPlayMode (static_cast<Player::PlayMode> (resumeMode));
PlaylistToolbar_->addWidget (playButton);
}
void PlaylistWidget::SetSortOrderButton ()
{
auto sortButton = new QToolButton;
sortButton->setIcon (Proxy_->GetIconThemeManager ()->GetIcon ("view-sort-ascending"));
sortButton->setPopupMode (QToolButton::InstantPopup);
auto menu = new QMenu (tr ("Sorting"));
sortButton->setMenu (menu);
auto getInts = [] (const QList<SortingCriteria>& crit) -> QVariantList
{
QVariantList result;
std::transform (crit.begin (), crit.end (), std::back_inserter (result),
[] (decltype (crit.front ()) item) { return static_cast<int> (item); });
return result;
};
const auto stdSorts =
{
QPair<QString, QList<SortingCriteria>>
{
tr ("Artist / Year / Album / Track number"),
{
SortingCriteria::Artist,
SortingCriteria::Year,
SortingCriteria::Album,
SortingCriteria::TrackNumber
}
},
{
tr ("Artist / Track title"),
{
SortingCriteria::Artist,
SortingCriteria::TrackTitle
}
},
{
tr ("File path"),
{
SortingCriteria::DirectoryPath,
SortingCriteria::FileName
}
},
{
tr ("No sort"),
{}
}
};
const auto& currentCriteria = Player_->GetSortingCriteria ();
auto sortGroup = new QActionGroup (this);
bool wasChecked = false;
for (const auto& pair : stdSorts)
{
auto act = menu->addAction (pair.first);
act->setProperty ("SortInts", getInts (pair.second));
act->setCheckable (true);
sortGroup->addAction (act);
if (pair.second == currentCriteria)
{
act->setChecked (true);
wasChecked = true;
}
else
act->setChecked (false);
connect (act,
SIGNAL (triggered ()),
this,
SLOT (handleStdSort ()));
}
menu->addSeparator ();
auto customAct = menu->addAction (tr ("Custom..."));
customAct->setCheckable (true);
if (!wasChecked)
customAct->setChecked (true);
sortGroup->addAction (customAct);
connect (customAct,
SIGNAL (triggered ()),
this,
SLOT (handleCustomSort ()));
PlaylistToolbar_->addWidget (sortButton);
}
void PlaylistWidget::InitViewActions ()
{
ActionRemoveSelected_ = new QAction (tr ("Delete from playlist"), Ui_.Playlist_);
ActionRemoveSelected_->setProperty ("ActionIcon", "list-remove");
ActionRemoveSelected_->setShortcut (Qt::Key_Delete);
ActionRemoveSelected_->setShortcutContext (Qt::WidgetShortcut);
connect (ActionRemoveSelected_,
SIGNAL (triggered ()),
this,
SLOT (removeSelectedSongs ()));
Ui_.Playlist_->addAction (ActionRemoveSelected_);
ActionStopAfterSelected_ = new QAction (tr ("Stop after this track"), Ui_.Playlist_);
ActionStopAfterSelected_->setProperty ("ActionIcon", "media-playback-stop");
connect (ActionStopAfterSelected_,
SIGNAL (triggered ()),
this,
SLOT (setStopAfterSelected ()));
ActionAddToOneShot_ = new QAction (tr ("Add to instant queue"), Ui_.Playlist_);
ActionAddToOneShot_->setProperty ("ActionIcon", "list-add");
connect (ActionAddToOneShot_,
SIGNAL (triggered ()),
this,
SLOT (addToOneShot ()));
ActionRemoveFromOneShot_ = new QAction (tr ("Remove from instant queue"), Ui_.Playlist_);
ActionRemoveFromOneShot_->setProperty ("ActionIcon", "list-remove");
connect (ActionRemoveFromOneShot_,
SIGNAL (triggered ()),
this,
SLOT (removeFromOneShot ()));
ActionMoveOneShotUp_ = new QAction (tr ("Move up in instant queue"), Ui_.Playlist_);
ActionMoveOneShotUp_->setProperty ("ActionIcon", "go-up");
connect (ActionMoveOneShotUp_,
SIGNAL (triggered ()),
this,
SLOT (moveOneShotUp ()));
ActionMoveOneShotDown_ = new QAction (tr ("Move down in instant queue"), Ui_.Playlist_);
ActionMoveOneShotDown_->setProperty ("ActionIcon", "go-down");
connect (ActionMoveOneShotDown_,
SIGNAL (triggered ()),
this,
SLOT (moveOneShotDown ()));
ActionShowTrackProps_ = new QAction (tr ("Show track properties"), Ui_.Playlist_);
ActionShowTrackProps_->setProperty ("ActionIcon", "document-properties");
connect (ActionShowTrackProps_,
SIGNAL (triggered ()),
this,
SLOT (showTrackProps ()));
ActionShowAlbumArt_ = new QAction (tr ("Show album art"), Ui_.Playlist_);
ActionShowAlbumArt_->setProperty ("ActionIcon", "media-optical");
connect (ActionShowAlbumArt_,
SIGNAL (triggered ()),
this,
SLOT (showAlbumArt ()));
TrackActions_ = new QMenu (tr ("Track actions"));
TrackActions_->addAction (tr ("Perform action after this track starts..."),
this, SLOT (initPerformAfterTrackStart ()));
TrackActions_->addAction (tr ("Perform action after this track stops..."),
this, SLOT (initPerformAfterTrackStop ()));
ExistingTrackActions_ = TrackActions_->addMenu (tr ("Existing"));
connect (ExistingTrackActions_,
SIGNAL (triggered (QAction*)),
this,
SLOT (handleExistingTrackAction (QAction*)));
ActionToggleSearch_ = new QAction (tr ("Toggle search field"), Ui_.Playlist_);
ActionToggleSearch_->setShortcut (QKeySequence::Find);
ActionToggleSearch_->setCheckable (true);
ActionToggleSearch_->setProperty ("ActionIcon", "edit-find");
connect (ActionToggleSearch_,
SIGNAL (toggled (bool)),
Ui_.SearchPlaylist_,
SLOT (setVisible (bool)));
connect (ActionToggleSearch_,
SIGNAL (toggled (bool)),
Ui_.SearchPlaylist_,
SLOT (setFocus ()));
connect (ActionToggleSearch_,
SIGNAL (toggled (bool)),
Ui_.SearchPlaylist_,
SLOT (clear ()));
Ui_.SearchPlaylist_->setVisible (false);
}
void PlaylistWidget::EnableMoveButtons (bool enabled)
{
MoveUpButtonAction_->setEnabled (enabled);
MoveDownButtonAction_->setEnabled (enabled);
}
QList<AudioSource> PlaylistWidget::GetSelected () const
{
auto selected = Ui_.Playlist_->selectionModel ()->selectedRows ();
if (selected.isEmpty ())
selected << Ui_.Playlist_->currentIndex ();
QList<AudioSource> sources;
for (const auto& index : selected)
sources += Player_->GetIndexSources (PlaylistFilter_->mapToSource (index));
return sources;
}
void PlaylistWidget::SelectSources (const QList<AudioSource>& sources)
{
auto tryIdx = [&sources, this] (const QModelIndex& idx)
{
if (sources.contains (Player_->GetIndexSources (idx).value (0)))
Ui_.Playlist_->selectionModel ()->select (PlaylistFilter_->mapFromSource (idx),
QItemSelectionModel::Select | QItemSelectionModel::Rows);
};
auto plModel = Player_->GetPlaylistModel ();
for (int i = 0; i < plModel->rowCount (); ++i)
{
const auto& albumIdx = plModel->index (i, 0);
const int tracks = plModel->rowCount (albumIdx);
if (!tracks)
tryIdx (albumIdx);
else
for (int j = 0; j < tracks; ++j)
tryIdx (plModel->index (j, 0, albumIdx));
}
}
void PlaylistWidget::focusIndex (const QModelIndex& index)
{
if (!XmlSettingsManager::Instance ().property ("AutocenterCurrentTrack").toBool ())
return;
Ui_.Playlist_->scrollTo (PlaylistFilter_->mapFromSource (index),
QAbstractItemView::PositionAtCenter);
}
namespace
{
QIcon SymbolToIcon (const QPair<QString, QColor>& symb, const QFontMetrics& fm)
{
const auto& rect = fm.boundingRect (symb.first);
QPixmap px { rect.size () };
px.fill (Qt::transparent);
{
QPainter painter { &px };
if (symb.second.isValid ())
painter.setPen (symb.second);
painter.drawText (QRect { { 0, 0 }, rect.size () },
Qt::AlignCenter | Qt::AlignHCenter,
symb.first);
}
QIcon icon;
icon.addPixmap (px);
return icon;
}
}
void PlaylistWidget::on_Playlist__customContextMenuRequested (const QPoint& pos)
{
const auto& idx = Ui_.Playlist_->indexAt (pos);
if (!idx.isValid ())
return;
auto menu = new QMenu (Ui_.Playlist_);
menu->addAction (ActionRemoveSelected_);
if (idx.data (Player::Role::IsAlbum).toBool ())
menu->addAction (ActionShowAlbumArt_);
else
menu->addAction (ActionShowTrackProps_);
menu->addSeparator ();
menu->addAction (ActionStopAfterSelected_);
const auto& oneShotPosVar = idx.data (Player::Role::OneShotPos);
if (!oneShotPosVar.isValid ())
menu->addAction (ActionAddToOneShot_);
else
{
menu->addAction (ActionRemoveFromOneShot_);
if (oneShotPosVar.toInt () > 0)
menu->addAction (ActionMoveOneShotUp_);
if (oneShotPosVar.toInt () < Player_->GetOneShotQueueSize () - 1)
menu->addAction (ActionMoveOneShotDown_);
}
menu->addMenu (TrackActions_);
const auto& existingRules = idx.data (Player::Role::MatchingRules).value<QList<Entity>> ();
ExistingTrackActions_->menuAction ()->setVisible (!existingRules.isEmpty ());
ExistingTrackActions_->clear ();
for (const auto& rule : existingRules)
{
const auto action = ExistingTrackActions_->addAction (rule.Entity_.toString ());
action->setProperty ("LMP/SourceRule", QVariant::fromValue (rule));
const auto& symbol = GetRuleSymbol (rule);
action->setIcon (SymbolToIcon (symbol, menu->fontMetrics ()));
}
menu->addSeparator ();
if (updateDownloadAction ())
{
menu->addAction (ActionDownloadTrack_);
menu->addSeparator ();
}
menu->addAction (ActionToggleSearch_);
auto mediaInfo = idx.data (Player::Role::Info).value<MediaInfo> ();
if (idx.model ()->rowCount (idx))
mediaInfo = idx.model ()->index (0, 0, idx).data (Player::Role::Info).value<MediaInfo> ();
emit hookPlaylistContextMenuRequested (std::make_shared<Util::DefaultHookProxy> (),
menu,
mediaInfo);
menu->setAttribute (Qt::WA_DeleteOnClose);
menu->exec (Ui_.Playlist_->viewport ()->mapToGlobal (pos));
}
void PlaylistWidget::handleChangePlayMode ()
{
auto mode = sender ()->property ("PlayMode").toInt ();
Player_->SetPlayMode (static_cast<Player::PlayMode> (mode));
XmlSettingsManager::Instance ().setProperty ("PlayMode", mode);
}
void PlaylistWidget::handlePlayModeChanged (Player::PlayMode mode)
{
Q_FOREACH (QAction *action, PlayModesGroup_->actions ())
if (action->property ("PlayMode").toInt () == static_cast<int> (mode))
{
action->setChecked (true);
return;
}
}
void PlaylistWidget::play (const QModelIndex& index)
{
Player_->play (PlaylistFilter_->mapToSource (index));
}
void PlaylistWidget::expand (const QModelIndex& index)
{
Ui_.Playlist_->expand (PlaylistFilter_->mapFromSource (index));
}
void PlaylistWidget::expandAll ()
{
Ui_.Playlist_->expandAll ();
checkSelections ();
}
void PlaylistWidget::checkSelections ()
{
if (NextResetSelect_.isEmpty () || !PlaylistFilter_->rowCount ())
return;
SelectSources (NextResetSelect_);
NextResetSelect_.clear ();
}
void PlaylistWidget::handleBufferStatus (int status)
{
Ui_.BufferProgress_->setValue (status);
Ui_.BufferProgress_->setVisible (status > 0 && status < 100);
}
void PlaylistWidget::handleSongChanged (const MediaInfo& info)
{
if (!info.LocalPath_.isEmpty ())
handleBufferStatus (100);
}
void PlaylistWidget::handleStdSort ()
{
const auto& intVars = sender ()->property ("SortInts").toList ();
const auto& criteria = Util::Map (intVars,
[] (const QVariant& var) { return static_cast<SortingCriteria> (var.toInt ()); });
Player_->SetSortingCriteria (criteria);
EnableMoveButtons (criteria.isEmpty ());
}
void PlaylistWidget::handleCustomSort ()
{
const auto& var = XmlSettingsManager::Instance ().property ("LastCustomSortCriteria");
auto lastCustom = LoadCriteria (var);
const auto& current = Player_->GetSortingCriteria ();
if (lastCustom.isEmpty ())
lastCustom = current;
SortingCriteriaDialog dia (this);
dia.SetCriteria (lastCustom);
if (dia.exec () != QDialog::Accepted)
return;
const auto& newCriteria = dia.GetCriteria ();
if (!newCriteria.isEmpty ())
{
const auto& var = SaveCriteria (newCriteria);
XmlSettingsManager::Instance ().setProperty ("LastCustomSortCriteria", var);
}
if (newCriteria != current)
Player_->SetSortingCriteria (newCriteria);
}
void PlaylistWidget::savePlayScrollPosition ()
{
const auto bar = Ui_.Playlist_->verticalScrollBar ();
if (!bar)
return;
const auto val = bar->value ();
new Util::SlotClosure<Util::DeleteLaterPolicy>
{
[bar, val]
{
Util::ExecuteLater ([=] { bar->setValue (std::min (val, bar->maximum ())); });
},
PlaylistFilter_,
SIGNAL (modelReset ()),
this
};
}
void PlaylistWidget::removeSelectedSongs ()
{
const auto& removedSources = GetSelected ();
const auto& title = tr ("Remove %n song(s)", 0, removedSources.size ());
auto cmd = new PlaylistUndoCommand (title, removedSources, Player_);
UndoStack_->push (cmd);
}
void PlaylistWidget::setStopAfterSelected ()
{
const auto& index = PlaylistFilter_->mapToSource (Ui_.Playlist_->currentIndex ());
if (!index.isValid ())
return;
Player_->SetStopAfter (index);
}
void PlaylistWidget::addToOneShot ()
{
auto selected = Ui_.Playlist_->selectionModel ()->selectedRows (0);
if (selected.isEmpty ())
selected << Ui_.Playlist_->currentIndex ();
const auto& mapped = Util::Map (selected,
[this] (const QModelIndex& index) { return PlaylistFilter_->mapToSource (index); });
if (mapped.isEmpty ())
return;
for (const auto& index : mapped)
Player_->AddToOneShotQueue (index);
}
void PlaylistWidget::removeFromOneShot ()
{
auto selection = Ui_.Playlist_->selectionModel ()->selectedRows ();
const auto& current = Ui_.Playlist_->currentIndex ();
if (!selection.contains (current) && current.isValid ())
selection << current;
for (const auto& index : selection)
Player_->RemoveFromOneShotQueue (PlaylistFilter_->mapToSource (index));
}
void PlaylistWidget::moveOneShotUp ()
{
const auto& index = PlaylistFilter_->mapToSource (Ui_.Playlist_->currentIndex ());
if (!index.isValid ())
return;
Player_->OneShotMoveUp (index);
}
void PlaylistWidget::moveOneShotDown ()
{
const auto& index = PlaylistFilter_->mapToSource (Ui_.Playlist_->currentIndex ());
if (!index.isValid ())
return;
Player_->OneShotMoveDown (index);
}
void PlaylistWidget::showTrackProps ()
{
const auto& index = Ui_.Playlist_->currentIndex ();
const auto& info = index.data (Player::Role::Info).value<MediaInfo> ();
if (info.LocalPath_.isEmpty ())
return;
AudioPropsWidget::MakeDialog ()->SetProps (info);
}
void PlaylistWidget::showAlbumArt ()
{
const auto& index = Ui_.Playlist_->currentIndex ();
const auto& info = index.data (Player::Role::Info).value<MediaInfo> ();
ShowAlbumArt (info.LocalPath_, QCursor::pos ());
}
namespace
{
void EmitStateRule (const QModelIndex& index, const QString& state,
const QString& nameTempl, const ICoreProxy_ptr& proxy)
{
const auto& info = index.data (Player::Role::Info).value<MediaInfo> ();
auto url = info.Additional_.value ("URL").toUrl ();
if (url.isEmpty ())
url = QUrl::fromLocalFile (info.LocalPath_);
const auto& e = Util::MakeANRule (nameTempl
.arg (info.Title_)
.arg (info.Artist_),
"org.LeechCraft.LMP",
AN::CatMediaPlayer,
{ AN::TypeMediaPlaybackStatus },
AN::NotifySingleShot,
true,
{
{
AN::Field::MediaPlaybackStatus,
ANStringFieldValue { state }
},
{
AN::Field::MediaArtist,
ANStringFieldValue { info.Artist_ }
},
{
AN::Field::MediaAlbum,
ANStringFieldValue { info.Album_ }
},
{
AN::Field::MediaTitle,
ANStringFieldValue { info.Title_ }
},
{
AN::Field::MediaLength,
ANIntFieldValue { info.Length_, ANIntFieldValue::OEqual }
},
{
AN::Field::MediaPlayerURL,
ANStringFieldValue { url.toEncoded () }
}
});
proxy->GetEntityManager ()->HandleEntity (e);
}
}
void PlaylistWidget::initPerformAfterTrackStart ()
{
EmitStateRule (Ui_.Playlist_->currentIndex (),
"Playing",
tr ("Perform when %1 by %2 starts playing"),
Proxy_);
}
void PlaylistWidget::initPerformAfterTrackStop ()
{
EmitStateRule (Ui_.Playlist_->currentIndex (),
"Stopped",
tr ("Perform when %1 by %2 stops playing"),
Proxy_);
}
void PlaylistWidget::handleExistingTrackAction (QAction *action)
{
const auto& rule = action->property ("LMP/SourceRule").value<Entity> ();
const auto& pluginId = rule.Additional_ ["org.LC.AdvNotifications.SenderID"].toByteArray ();
const auto pluginMgr = Proxy_->GetPluginsManager ();
const auto pluginObj = pluginMgr->GetPluginByID (pluginId);
if (!pluginObj)
{
qWarning () << Q_FUNC_INFO
<< "plugin"
<< pluginId
<< "not found";
return;
}
const auto irs = qobject_cast<IANRulesStorage*> (pluginObj);
irs->RequestRuleConfiguration (rule);
}
void PlaylistWidget::handleMoveUp ()
{
const auto& sources = GetSelected ();
if (sources.isEmpty ())
return;
auto allSrcs = Player_->GetQueue ();
for (int i = 1, size = allSrcs.size (); i < size; ++i)
if (sources.contains (allSrcs.at (i)))
std::swap (allSrcs [i], allSrcs [i - 1]);
Player_->Enqueue (allSrcs, Player::EnqueueReplace);
NextResetSelect_ = sources;
}
void PlaylistWidget::handleMoveTop ()
{
const auto& sources = GetSelected ();
auto allSrcs = Player_->GetQueue ();
Q_FOREACH (const auto& source, sources)
allSrcs.removeAll (source);
Player_->Enqueue (sources + allSrcs, Player::EnqueueReplace);
NextResetSelect_ = sources;
}
void PlaylistWidget::handleMoveDown ()
{
const auto& sources = GetSelected ();
if (sources.isEmpty ())
return;
auto allSrcs = Player_->GetQueue ();
for (int i = allSrcs.size () - 2; i >= 0; --i)
if (sources.contains (allSrcs.at (i)))
std::swap (allSrcs [i], allSrcs [i + 1]);
Player_->Enqueue (allSrcs, Player::EnqueueReplace);
NextResetSelect_ = sources;
}
void PlaylistWidget::handleMoveBottom ()
{
const auto& sources = GetSelected ();
auto allSrcs = Player_->GetQueue ();
Q_FOREACH (const auto& source, sources)
allSrcs.removeAll (source);
Player_->Enqueue (allSrcs + sources, Player::EnqueueReplace);
NextResetSelect_ = sources;
}
void PlaylistWidget::handleSavePlaylist ()
{
const auto& name = QInputDialog::getText (this,
tr ("Save playlist"),
tr ("Enter name for the playlist:"));
if (name.isEmpty ())
return;
auto mgr = Core::Instance ().GetPlaylistManager ()->GetStaticManager ();
if (mgr->EnumerateCustomPlaylists ().contains (name) &&
QMessageBox::question (this,
"LeechCraft",
tr ("Playlist %1 already exists. Do you want to overwrite it?")
.arg ("<em>" + name + "</em>"),
QMessageBox::Yes | QMessageBox::No) != QMessageBox::Yes)
return;
mgr->SaveCustomPlaylist (name, Player_->GetAsNativePlaylist ());
}
void PlaylistWidget::loadFromDisk ()
{
auto prevPath = XmlSettingsManager::Instance ()
.Property ("PrevAddToPlaylistPath", QDir::homePath ()).toString ();
auto files = QFileDialog::getOpenFileNames (this,
tr ("Load files"),
prevPath,
QString { "%1 (*.ogg *.flac *.mp3 *.wav);;%2 (*.pls *.m3u *.m3u8 *.xspf);;%3 (*.*)" }
.arg (tr ("Music files"))
.arg (tr ("Playlists"))
.arg (tr ("All files")));
if (files.isEmpty ())
return;
#if QT_VERSION < 0x050000
if (files.size () > 1)
for (auto& file : files)
file = QString::fromUtf8 (QByteArray::fromPercentEncoding (file.toUtf8 ()));
#endif
prevPath = QFileInfo (files.at (0)).absoluteDir ().absolutePath ();
XmlSettingsManager::Instance ().setProperty ("PrevAddToPlaylistPath", prevPath);
Player_->Enqueue (files);
}
void PlaylistWidget::addURL ()
{
auto cb = qApp->clipboard ();
QString textCb = cb->text (QClipboard::Selection);
if (textCb.isEmpty () || !QUrl (textCb).isValid ())
textCb = cb->text (QClipboard::Selection);
if (!QUrl (textCb).isValid ())
textCb.clear ();
const auto& url = QInputDialog::getText (this,
"LeechCraft",
tr ("Enter URL to add to the play queue:"),
QLineEdit::Normal,
textCb);
if (url.isEmpty ())
return;
QUrl urlObj (url);
if (!urlObj.isValid ())
{
QMessageBox::warning (this,
"LeechCraft",
tr ("Invalid URL."));
return;
}
Player_->Enqueue ({ urlObj });
}
namespace
{
QList<AudioSource> GetSelectedOrCurrent (const QList<AudioSource>& selected, Player *player)
{
if (!selected.isEmpty ())
return selected;
return { player->GetSourceObject ()->GetCurrentSource () };
}
}
bool PlaylistWidget::updateDownloadAction ()
{
const auto& selected = GetSelectedOrCurrent (GetSelected (), Player_);
const bool hasRemote = std::any_of (selected.begin (), selected.end (),
[] (const AudioSource& src) { return src.IsRemote (); });
ActionDownloadTrack_->setEnabled (hasRemote);
return hasRemote;
}
void PlaylistWidget::handleDownload ()
{
const auto& remotes = Util::Filter (GetSelectedOrCurrent (GetSelected (), Player_), &AudioSource::IsRemote);
if (remotes.isEmpty ())
return;
GrabTracks (Util::Map (remotes, Util::BindMemFn (&Player::GetMediaInfo, Player_)), this);
}
void PlaylistWidget::updateStatsLabel ()
{
const int tracksCount = Player_->GetQueue ().size ();
auto model = Player_->GetPlaylistModel ();
int length = 0;
for (int i = 0, rc = model->rowCount (); i < rc; ++i)
{
const auto& idx = model->index (i, 0);
length += model->rowCount (idx) ?
idx.data (Player::Role::AlbumLength).toInt () :
idx.data (Player::Role::Info).value<MediaInfo> ().Length_;
}
QModelIndexList selectedTracks;
for (const auto& idx : Ui_.Playlist_->selectionModel ()->selectedRows ())
if (!model->rowCount (idx))
selectedTracks << idx;
int selectedLength = 0;
if (selectedTracks.size () > 1)
for (const auto& idx : selectedTracks)
selectedLength += idx.data (Player::Role::Info).value<MediaInfo> ().Length_;
QString text;
if (selectedLength > 0)
text = tr ("%n track(s), total duration: %1; selected duration: %2", 0, tracksCount)
.arg (Util::MakeTimeFromLong (length))
.arg (Util::MakeTimeFromLong (selectedLength));
else
text = tr ("%n track(s), total duration: %1", 0, tracksCount)
.arg (Util::MakeTimeFromLong (length));
Ui_.StatsLabel_->setText (text);
}
}
}
| 28.893515 | 110 | 0.678951 | [
"object",
"vector",
"model",
"transform"
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.