text
stringlengths 54
60.6k
|
---|
<commit_before>// Copyright 2009 Anders Bakken
//
// 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 "textlayout_p.h"
#include "textedit_p.h"
#include "textdocument.h"
#include "textedit.h"
void TextLayout::dirty(int width)
{
viewport = width;
layoutDirty = true;
if (textEdit)
textEdit->viewport()->update();
}
int TextLayout::viewportWidth() const
{
if (!lineBreaking)
return INT_MAX;
return textEdit ? textEdit->viewport()->width() : viewport;
}
int TextLayout::doLayout(int index, QList<TextSection*> *sections) // index is in document coordinates
{
QTextLayout *textLayout = 0;
if (!unusedTextLayouts.isEmpty()) {
textLayout = unusedTextLayouts.takeLast();
textLayout->clearAdditionalFormats();
} else {
textLayout = new QTextLayout;
textLayout->setFont(font);
QTextOption option;
option.setWrapMode(QTextOption::WrapAtWordBoundaryOrAnywhere);
textLayout->setTextOption(option);
}
textLayouts.append(textLayout);
if (index != 0 && bufferReadCharacter(index - 1) != '\n') {
qWarning() << index << viewportPosition << document->read(index - 1, 20)
<< bufferReadCharacter(index - 1);
}
Q_ASSERT(index == 0 || bufferReadCharacter(index - 1) == '\n');
const int max = bufferPosition + buffer.size();
const int lineStart = index;
while (index < max && bufferReadCharacter(index) != '\n')
++index;
const QString string = buffer.mid(lineStart - bufferPosition, index - lineStart);
Q_ASSERT(string.size() == index - lineStart);
Q_ASSERT(!string.contains('\n'));
if (index < max)
++index; // for the newline
textLayout->setText(string);
QMultiMap<int, QTextLayout::FormatRange> formatMap;
if (sections) {
do {
Q_ASSERT(!sections->isEmpty());
TextSection *l = sections->first();
Q_ASSERT(::matchSection(l, textEdit));
Q_ASSERT(l->position() + l->size() >= lineStart);
if (l->position() >= index) {
break;
}
// section is in this QTextLayout
QTextLayout::FormatRange range;
range.start = qMax(0, l->position() - lineStart); // offset in QTextLayout
range.length = qMin(l->position() + l->size(), index) - lineStart - range.start;
range.format = l->format();
formatMap.insertMulti(l->priority(), range);
if (l->position() + l->size() >= index) { // > ### ???
// means section didn't end here. It continues in the next QTextLayout
break;
}
sections->removeFirst();
} while (!sections->isEmpty());
}
QList<QTextLayout::FormatRange> formats = formatMap.values();
int leftMargin = LeftMargin;
int rightMargin = 0;
int topMargin = 0;
int bottomMargin = 0;
if (syntaxHighlighter) {
syntaxHighlighter->d->currentBlockPosition = lineStart;
syntaxHighlighter->d->formatRanges.clear();
syntaxHighlighter->d->currentBlock = string;
syntaxHighlighter->highlightBlock(string);
syntaxHighlighter->d->currentBlock.clear();
if (syntaxHighlighter->d->blockFormat.isValid()) {
blockFormats[textLayout] = syntaxHighlighter->d->blockFormat;
if (syntaxHighlighter->d->blockFormat.hasProperty(QTextFormat::BlockLeftMargin))
leftMargin = syntaxHighlighter->d->blockFormat.leftMargin();
if (syntaxHighlighter->d->blockFormat.hasProperty(QTextFormat::BlockRightMargin))
rightMargin = syntaxHighlighter->d->blockFormat.rightMargin();
if (syntaxHighlighter->d->blockFormat.hasProperty(QTextFormat::BlockTopMargin))
topMargin = syntaxHighlighter->d->blockFormat.topMargin();
if (syntaxHighlighter->d->blockFormat.hasProperty(QTextFormat::BlockBottomMargin))
bottomMargin = syntaxHighlighter->d->blockFormat.bottomMargin();
}
syntaxHighlighter->d->previousBlockState = syntaxHighlighter->d->currentBlockState;
if (!syntaxHighlighter->d->formatRanges.isEmpty())
formats += syntaxHighlighter->d->formatRanges;
}
textLayout->setAdditionalFormats(formats);
textLayout->beginLayout();
const int lineWidth = viewportWidth() - (leftMargin + rightMargin);
int localWidest = -1;
forever {
QTextLine line = textLayout->createLine();
if (!line.isValid()) {
break;
}
line.setLineWidth(lineWidth);
if (!lineBreaking)
localWidest = qMax<int>(localWidest, line.naturalTextWidth() + (LeftMargin * 2));
// ### support blockformat margins etc
int y = topMargin + lastBottomMargin;
if (!lines.isEmpty()) {
y += int(lines.last().second.rect().bottom());
// QTextLine doesn't seem to get its rect() update until a
// new line has been created (or presumably in endLayout)
}
line.setPosition(QPoint(leftMargin, y));
lines.append(qMakePair(lineStart + line.textStart(), line));
}
widest = qMax(widest, localWidest);
lastBottomMargin = bottomMargin;
textLayout->endLayout();
#ifndef QT_NO_DEBUG
for (int i=1; i<lines.size(); ++i) {
Q_ASSERT(lines.at(i).first - (lines.at(i - 1).first + lines.at(i - 1).second.textLength()) <= 1);
}
#endif
QRect r = textLayout->boundingRect().toRect();
// this will actually take the entire width set in setLineWidth
// and not what it actually uses.
r.setWidth(localWidest);
contentRect |= r;
Q_ASSERT(!lineBreaking || contentRect.right() <= viewportWidth() + LeftMargin);
if (syntaxHighlighter) {
syntaxHighlighter->d->formatRanges.clear();
syntaxHighlighter->d->blockFormat = QTextBlockFormat();
syntaxHighlighter->d->currentBlockPosition = -1;
}
return index;
}
int TextLayout::textPositionAt(const QPoint &p) const
{
QPoint pos = p;
if (pos.x() >= 0 && pos.x() < LeftMargin)
pos.rx() = LeftMargin; // clicking in the margin area should count as the first characters
int textLayoutOffset = viewportPosition;
foreach(const QTextLayout *l, textLayouts) {
if (l->boundingRect().toRect().contains(pos)) {
const int lineCount = l->lineCount();
for (int i=0; i<lineCount; ++i) {
const QTextLine line = l->lineAt(i);
if (line.y() <= pos.y() && pos.y() <= line.height() + line.y()) { // ### < ???
return textLayoutOffset + line.xToCursor(qMax<int>(LeftMargin, pos.x()));
}
}
}
textLayoutOffset += l->text().size() + 1; // + 1 for newlines which aren't in the QTextLayout
}
return -1;
}
QList<TextSection*> TextLayout::relayoutCommon()
{
// widest = -1; // ### should this be relative to current content or remember? What if you remove the line that was the widest?
Q_ASSERT(layoutDirty);
layoutDirty = false;
Q_ASSERT(document);
lines.clear();
unusedTextLayouts = textLayouts;
textLayouts.clear();
contentRect = QRect();
visibleLines = lastVisibleCharacter = -1;
if (syntaxHighlighter) {
syntaxHighlighter->d->previousBlockState = syntaxHighlighter->d->currentBlockState = -1;
}
if (viewportPosition < bufferPosition
|| (bufferPosition + buffer.size() < document->documentSize()
&& buffer.size() - bufferOffset() < MinimumBufferSize)) {
bufferPosition = qMax(0, viewportPosition - MinimumBufferSize);
buffer = document->read(bufferPosition, int(MinimumBufferSize * 2.5));
sections = document->d->getSections(bufferPosition, buffer.size(), TextSection::IncludePartial, textEdit);
} else if (sectionsDirty) {
sections = document->d->getSections(bufferPosition, buffer.size(), TextSection::IncludePartial, textEdit);
}
sectionsDirty = false;
QList<TextSection*> l = sections;
while (!l.isEmpty() && l.first()->position() + l.first()->size() < viewportPosition)
l.takeFirst(); // could cache these as well
return l;
}
void TextLayout::relayoutByGeometry(int height)
{
if (!layoutDirty)
return;
QList<TextSection*> l = relayoutCommon();
const int max = viewportPosition + buffer.size() - bufferOffset(); // in document coordinates
Q_ASSERT(viewportPosition == 0 || bufferReadCharacter(viewportPosition - 1) == '\n');
static const int extraLines = qMax(2, qgetenv("LAZYTEXTEDIT_EXTRA_LINES").toInt());
int index = viewportPosition;
while (index < max) {
index = doLayout(index, l.isEmpty() ? 0 : &l);
Q_ASSERT(index == max || document->readCharacter(index - 1) == '\n');
Q_ASSERT(!textLayouts.isEmpty());
const int y = int(textLayouts.last()->boundingRect().bottom());
if (y >= height) {
if (visibleLines == -1) {
visibleLines = lines.size();
lastVisibleCharacter = index;
} else if (lines.size() >= visibleLines + extraLines) {
break;
}
}
}
if (visibleLines == -1) {
visibleLines = lines.size();
lastVisibleCharacter = index;
}
layoutEnd = qMin(index, max);
qDeleteAll(unusedTextLayouts);
unusedTextLayouts.clear();
Q_ASSERT(viewportPosition < layoutEnd ||
(viewportPosition == layoutEnd && viewportPosition == document->documentSize()));
// qDebug() << "layoutEnd" << layoutEnd << "viewportPosition" << viewportPosition;
}
void TextLayout::relayoutByPosition(int size)
{
if (!layoutDirty)
return;
QList<TextSection*> l = relayoutCommon();
const int max = viewportPosition + qMin(size, buffer.size() - bufferOffset());
Q_ASSERT(viewportPosition == 0 || bufferReadCharacter(viewportPosition - 1) == '\n');
int index = viewportPosition;
while (index < max) {
index = doLayout(index, l.isEmpty() ? 0 : &l);
}
layoutEnd = index;
qDeleteAll(unusedTextLayouts);
unusedTextLayouts.clear();
Q_ASSERT(viewportPosition < layoutEnd ||
(viewportPosition == layoutEnd && viewportPosition == document->documentSize()));
}
QTextLayout *TextLayout::layoutForPosition(int pos, int *offset, int *index) const
{
if (offset)
*offset = -1;
if (index)
*index = -1;
if (textLayouts.isEmpty() || pos < viewportPosition || pos > layoutEnd) {
return 0;
}
int textLayoutOffset = viewportPosition;
int i = 0;
foreach(QTextLayout *l, textLayouts) {
if (pos >= textLayoutOffset && pos <= l->text().size() + textLayoutOffset) {
if (offset)
*offset = pos - textLayoutOffset;
if (index)
*index = i;
return l;
}
++i;
textLayoutOffset += l->text().size() + 1;
}
return 0;
}
QTextLine TextLayout::lineForPosition(int pos, int *offsetInLine, int *lineIndex) const
{
if (offsetInLine)
*offsetInLine = -1;
if (lineIndex)
*lineIndex = -1;
if (pos < viewportPosition || pos >= layoutEnd || textLayouts.isEmpty() || lines.isEmpty()) {
return QTextLine();
}
for (int i=0; i<lines.size(); ++i) {
const QPair<int, QTextLine> &line = lines.at(i);
const int lineEnd = line.first + line.second.textLength() + 1; // 1 is for newline characteru
if (pos < lineEnd) {
if (offsetInLine) {
*offsetInLine = pos - line.first;
Q_ASSERT(*offsetInLine >= 0);
Q_ASSERT(*offsetInLine < lineEnd + pos);
}
if (lineIndex) {
*lineIndex = i;
}
return line.second;
}
}
qWarning() << "Couldn't find a line for" << pos << "viewportPosition" << viewportPosition
<< "layoutEnd" << layoutEnd;
Q_ASSERT(0);
return QTextLine();
}
// pos is not necessarily on a newline. Finds closest newline in the
// right direction and sets viewportPosition to that. Updates
// scrollbars if this is a TextEditPrivate
void TextLayout::updatePosition(int pos, Direction direction)
{
pos = qMin(pos, maxViewportPosition);
if (document->documentSize() == 0) {
viewportPosition = 0;
} else {
Q_ASSERT(document->documentSize() > 0);
int index = document->find('\n', qMax(0, pos + (direction == Backward ? -1 : 0)),
TextDocument::FindMode(direction)).position();
if (index == -1) {
if (direction == Backward) {
index = 0;
} else {
index = document->find('\n', document->documentSize() - 1, TextDocument::FindBackward).position() + 1;
// position after last newline in document
}
} else {
++index;
}
Q_ASSERT(index != -1);
viewportPosition = index;
if (viewportPosition != 0 && document->read(viewportPosition - 1, 1) != QString("\n"))
qWarning() << "viewportPosition" << viewportPosition << document->read(viewportPosition - 1, 10) << this;
Q_ASSERT(viewportPosition == 0 || document->read(viewportPosition - 1, 1) == QString("\n"));
}
if (viewportPosition > maxViewportPosition && direction == Forward) {
updatePosition(viewportPosition, Backward);
return;
}
dirty(viewportWidth());
if (textEdit) {
TextEditPrivate *p = static_cast<TextEditPrivate*>(this);
p->pendingScrollBarUpdate = true;
p->updateCursorPosition(p->lastHoverPos);
if (!textEdit->verticalScrollBar()->isSliderDown()) {
p->updateScrollBar();
} // sliderReleased is connected to updateScrollBar()
}
}
#ifndef QT_NO_DEBUG_STREAM
QDebug &operator<<(QDebug &str, const QTextLine &line)
{
if (!line.isValid()) {
str << "QTextLine() (invalid)";
return str;
}
str.space() << "lineNumber" << line.lineNumber()
<< "textStart" << line.textStart()
<< "textLength" << line.textLength()
<< "position" << line.position();
return str;
}
#endif
<commit_msg>fix an off by one bug<commit_after>// Copyright 2009 Anders Bakken
//
// 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 "textlayout_p.h"
#include "textedit_p.h"
#include "textdocument.h"
#include "textedit.h"
void TextLayout::dirty(int width)
{
viewport = width;
layoutDirty = true;
if (textEdit)
textEdit->viewport()->update();
}
int TextLayout::viewportWidth() const
{
if (!lineBreaking)
return INT_MAX;
return textEdit ? textEdit->viewport()->width() : viewport;
}
int TextLayout::doLayout(int index, QList<TextSection*> *sections) // index is in document coordinates
{
QTextLayout *textLayout = 0;
if (!unusedTextLayouts.isEmpty()) {
textLayout = unusedTextLayouts.takeLast();
textLayout->clearAdditionalFormats();
} else {
textLayout = new QTextLayout;
textLayout->setFont(font);
QTextOption option;
option.setWrapMode(QTextOption::WrapAtWordBoundaryOrAnywhere);
textLayout->setTextOption(option);
}
textLayouts.append(textLayout);
if (index != 0 && bufferReadCharacter(index - 1) != '\n') {
qWarning() << index << viewportPosition << document->read(index - 1, 20)
<< bufferReadCharacter(index - 1);
}
Q_ASSERT(index == 0 || bufferReadCharacter(index - 1) == '\n');
const int max = bufferPosition + buffer.size();
const int lineStart = index;
while (index < max && bufferReadCharacter(index) != '\n')
++index;
const QString string = buffer.mid(lineStart - bufferPosition, index - lineStart);
Q_ASSERT(string.size() == index - lineStart);
Q_ASSERT(!string.contains('\n'));
if (index < max)
++index; // for the newline
textLayout->setText(string);
QMultiMap<int, QTextLayout::FormatRange> formatMap;
if (sections) {
do {
Q_ASSERT(!sections->isEmpty());
TextSection *l = sections->first();
Q_ASSERT(::matchSection(l, textEdit));
Q_ASSERT(l->position() + l->size() >= lineStart);
if (l->position() >= index) {
break;
}
// section is in this QTextLayout
QTextLayout::FormatRange range;
range.start = qMax(0, l->position() - lineStart); // offset in QTextLayout
range.length = qMin(l->position() + l->size(), index) - lineStart - range.start;
range.format = l->format();
formatMap.insertMulti(l->priority(), range);
if (l->position() + l->size() >= index) { // > ### ???
// means section didn't end here. It continues in the next QTextLayout
break;
}
sections->removeFirst();
} while (!sections->isEmpty());
}
QList<QTextLayout::FormatRange> formats = formatMap.values();
int leftMargin = LeftMargin;
int rightMargin = 0;
int topMargin = 0;
int bottomMargin = 0;
if (syntaxHighlighter) {
syntaxHighlighter->d->currentBlockPosition = lineStart;
syntaxHighlighter->d->formatRanges.clear();
syntaxHighlighter->d->currentBlock = string;
syntaxHighlighter->highlightBlock(string);
syntaxHighlighter->d->currentBlock.clear();
if (syntaxHighlighter->d->blockFormat.isValid()) {
blockFormats[textLayout] = syntaxHighlighter->d->blockFormat;
if (syntaxHighlighter->d->blockFormat.hasProperty(QTextFormat::BlockLeftMargin))
leftMargin = syntaxHighlighter->d->blockFormat.leftMargin();
if (syntaxHighlighter->d->blockFormat.hasProperty(QTextFormat::BlockRightMargin))
rightMargin = syntaxHighlighter->d->blockFormat.rightMargin();
if (syntaxHighlighter->d->blockFormat.hasProperty(QTextFormat::BlockTopMargin))
topMargin = syntaxHighlighter->d->blockFormat.topMargin();
if (syntaxHighlighter->d->blockFormat.hasProperty(QTextFormat::BlockBottomMargin))
bottomMargin = syntaxHighlighter->d->blockFormat.bottomMargin();
}
syntaxHighlighter->d->previousBlockState = syntaxHighlighter->d->currentBlockState;
if (!syntaxHighlighter->d->formatRanges.isEmpty())
formats += syntaxHighlighter->d->formatRanges;
}
textLayout->setAdditionalFormats(formats);
textLayout->beginLayout();
const int lineWidth = viewportWidth() - (leftMargin + rightMargin);
int localWidest = -1;
forever {
QTextLine line = textLayout->createLine();
if (!line.isValid()) {
break;
}
line.setLineWidth(lineWidth);
if (!lineBreaking)
localWidest = qMax<int>(localWidest, line.naturalTextWidth() + (LeftMargin * 2));
// ### support blockformat margins etc
int y = topMargin + lastBottomMargin;
if (!lines.isEmpty()) {
y += int(lines.last().second.rect().bottom());
// QTextLine doesn't seem to get its rect() update until a
// new line has been created (or presumably in endLayout)
}
line.setPosition(QPoint(leftMargin, y));
lines.append(qMakePair(lineStart + line.textStart(), line));
}
widest = qMax(widest, localWidest);
lastBottomMargin = bottomMargin;
textLayout->endLayout();
#ifndef QT_NO_DEBUG
for (int i=1; i<lines.size(); ++i) {
Q_ASSERT(lines.at(i).first - (lines.at(i - 1).first + lines.at(i - 1).second.textLength()) <= 1);
}
#endif
QRect r = textLayout->boundingRect().toRect();
// this will actually take the entire width set in setLineWidth
// and not what it actually uses.
r.setWidth(localWidest);
contentRect |= r;
Q_ASSERT(!lineBreaking || contentRect.right() <= viewportWidth() + LeftMargin);
if (syntaxHighlighter) {
syntaxHighlighter->d->formatRanges.clear();
syntaxHighlighter->d->blockFormat = QTextBlockFormat();
syntaxHighlighter->d->currentBlockPosition = -1;
}
return index;
}
int TextLayout::textPositionAt(const QPoint &p) const
{
QPoint pos = p;
if (pos.x() >= 0 && pos.x() < LeftMargin)
pos.rx() = LeftMargin; // clicking in the margin area should count as the first characters
int textLayoutOffset = viewportPosition;
foreach(const QTextLayout *l, textLayouts) {
if (l->boundingRect().toRect().contains(pos)) {
const int lineCount = l->lineCount();
for (int i=0; i<lineCount; ++i) {
const QTextLine line = l->lineAt(i);
if (line.y() <= pos.y() && pos.y() <= line.height() + line.y()) { // ### < ???
return textLayoutOffset + line.xToCursor(qMax<int>(LeftMargin, pos.x()));
}
}
}
textLayoutOffset += l->text().size() + 1; // + 1 for newlines which aren't in the QTextLayout
}
return -1;
}
QList<TextSection*> TextLayout::relayoutCommon()
{
// widest = -1; // ### should this be relative to current content or remember? What if you remove the line that was the widest?
Q_ASSERT(layoutDirty);
layoutDirty = false;
Q_ASSERT(document);
lines.clear();
unusedTextLayouts = textLayouts;
textLayouts.clear();
contentRect = QRect();
visibleLines = lastVisibleCharacter = -1;
if (syntaxHighlighter) {
syntaxHighlighter->d->previousBlockState = syntaxHighlighter->d->currentBlockState = -1;
}
if (viewportPosition < bufferPosition
|| (bufferPosition + buffer.size() < document->documentSize()
&& buffer.size() - bufferOffset() < MinimumBufferSize)) {
bufferPosition = qMax(0, viewportPosition - MinimumBufferSize);
buffer = document->read(bufferPosition, int(MinimumBufferSize * 2.5));
sections = document->d->getSections(bufferPosition, buffer.size(), TextSection::IncludePartial, textEdit);
} else if (sectionsDirty) {
sections = document->d->getSections(bufferPosition, buffer.size(), TextSection::IncludePartial, textEdit);
}
sectionsDirty = false;
QList<TextSection*> l = sections;
while (!l.isEmpty() && l.first()->position() + l.first()->size() < viewportPosition)
l.takeFirst(); // could cache these as well
return l;
}
void TextLayout::relayoutByGeometry(int height)
{
if (!layoutDirty)
return;
QList<TextSection*> l = relayoutCommon();
const int max = viewportPosition + buffer.size() - bufferOffset(); // in document coordinates
Q_ASSERT(viewportPosition == 0 || bufferReadCharacter(viewportPosition - 1) == '\n');
static const int extraLines = qMax(2, qgetenv("LAZYTEXTEDIT_EXTRA_LINES").toInt());
int index = viewportPosition;
while (index < max) {
index = doLayout(index, l.isEmpty() ? 0 : &l);
Q_ASSERT(index == max || document->readCharacter(index - 1) == '\n');
Q_ASSERT(!textLayouts.isEmpty());
const int y = int(textLayouts.last()->boundingRect().bottom());
if (y >= height) {
if (visibleLines == -1) {
visibleLines = lines.size();
lastVisibleCharacter = index;
} else if (lines.size() >= visibleLines + extraLines) {
break;
}
}
}
if (visibleLines == -1) {
visibleLines = lines.size();
lastVisibleCharacter = index;
}
layoutEnd = qMin(index, max);
qDeleteAll(unusedTextLayouts);
unusedTextLayouts.clear();
Q_ASSERT(viewportPosition < layoutEnd ||
(viewportPosition == layoutEnd && viewportPosition == document->documentSize()));
// qDebug() << "layoutEnd" << layoutEnd << "viewportPosition" << viewportPosition;
}
void TextLayout::relayoutByPosition(int size)
{
if (!layoutDirty)
return;
QList<TextSection*> l = relayoutCommon();
const int max = viewportPosition + qMin(size, buffer.size() - bufferOffset());
Q_ASSERT(viewportPosition == 0 || bufferReadCharacter(viewportPosition - 1) == '\n');
int index = viewportPosition;
while (index < max) {
index = doLayout(index, l.isEmpty() ? 0 : &l);
}
layoutEnd = index;
qDeleteAll(unusedTextLayouts);
unusedTextLayouts.clear();
Q_ASSERT(viewportPosition < layoutEnd ||
(viewportPosition == layoutEnd && viewportPosition == document->documentSize()));
}
QTextLayout *TextLayout::layoutForPosition(int pos, int *offset, int *index) const
{
if (offset)
*offset = -1;
if (index)
*index = -1;
if (textLayouts.isEmpty() || pos < viewportPosition || pos > layoutEnd) {
return 0;
}
int textLayoutOffset = viewportPosition;
int i = 0;
foreach(QTextLayout *l, textLayouts) {
if (pos >= textLayoutOffset && pos <= l->text().size() + textLayoutOffset) {
if (offset)
*offset = pos - textLayoutOffset;
if (index)
*index = i;
return l;
}
++i;
textLayoutOffset += l->text().size() + 1;
}
return 0;
}
QTextLine TextLayout::lineForPosition(int pos, int *offsetInLine, int *lineIndex) const
{
if (offsetInLine)
*offsetInLine = -1;
if (lineIndex)
*lineIndex = -1;
if (pos < viewportPosition || pos >= layoutEnd || textLayouts.isEmpty() || lines.isEmpty()) {
return QTextLine();
}
int layoutIndex = 0;
QTextLayout *layout = textLayouts.value(layoutIndex);
Q_ASSERT(layout);
for (int i=0; i<lines.size(); ++i) {
const QPair<int, QTextLine> &line = lines.at(i);
int lineEnd = line.first + line.second.textLength();
if (line.second.lineNumber() + 1 == layout->lineCount()) {
++lineEnd;
// 1 is for newline characters
layout = textLayouts.value(++layoutIndex);
Q_ASSERT(layout);
}
if (pos < lineEnd) {
if (offsetInLine) {
*offsetInLine = pos - line.first;
Q_ASSERT(*offsetInLine >= 0);
Q_ASSERT(*offsetInLine < lineEnd + pos);
}
if (lineIndex) {
*lineIndex = i;
}
return line.second;
}
}
qWarning() << "Couldn't find a line for" << pos << "viewportPosition" << viewportPosition
<< "layoutEnd" << layoutEnd;
Q_ASSERT(0);
return QTextLine();
}
// pos is not necessarily on a newline. Finds closest newline in the
// right direction and sets viewportPosition to that. Updates
// scrollbars if this is a TextEditPrivate
void TextLayout::updatePosition(int pos, Direction direction)
{
pos = qMin(pos, maxViewportPosition);
if (document->documentSize() == 0) {
viewportPosition = 0;
} else {
Q_ASSERT(document->documentSize() > 0);
int index = document->find('\n', qMax(0, pos + (direction == Backward ? -1 : 0)),
TextDocument::FindMode(direction)).position();
if (index == -1) {
if (direction == Backward) {
index = 0;
} else {
index = document->find('\n', document->documentSize() - 1, TextDocument::FindBackward).position() + 1;
// position after last newline in document
}
} else {
++index;
}
Q_ASSERT(index != -1);
viewportPosition = index;
if (viewportPosition != 0 && document->read(viewportPosition - 1, 1) != QString("\n"))
qWarning() << "viewportPosition" << viewportPosition << document->read(viewportPosition - 1, 10) << this;
Q_ASSERT(viewportPosition == 0 || document->read(viewportPosition - 1, 1) == QString("\n"));
}
if (viewportPosition > maxViewportPosition && direction == Forward) {
updatePosition(viewportPosition, Backward);
return;
}
dirty(viewportWidth());
if (textEdit) {
TextEditPrivate *p = static_cast<TextEditPrivate*>(this);
p->pendingScrollBarUpdate = true;
p->updateCursorPosition(p->lastHoverPos);
if (!textEdit->verticalScrollBar()->isSliderDown()) {
p->updateScrollBar();
} // sliderReleased is connected to updateScrollBar()
}
}
#ifndef QT_NO_DEBUG_STREAM
QDebug &operator<<(QDebug &str, const QTextLine &line)
{
if (!line.isValid()) {
str << "QTextLine() (invalid)";
return str;
}
str.space() << "lineNumber" << line.lineNumber()
<< "textStart" << line.textStart()
<< "textLength" << line.textLength()
<< "position" << line.position();
return str;
}
#endif
<|endoftext|> |
<commit_before><commit_msg>use chart2 API for attached axis export<commit_after><|endoftext|> |
<commit_before>#include <iostream>
#include <cstdlib>
#include <iomanip>
using namespace std;
long int **create_array(long int w, long int k)
{
long int **array2 = new long int *[w];
for (long int i = 0; i < w; i++)
array2[i] = new long int[k];
return(array2);
}
void fill_array(long int w, long int k, long int x, long int **array2)
{
for(long int i = 0; i < w; i++)
for(long int j = 0; j < k; j++)
array2[i][j] = rand() % x;
}
void show_array(long int w, long int k, long int x, long int **array2)
{
for(long int i = 0; i < w; i++)
{
cout << endl;
for(long int j = 0; j < k; j++)
{
cout.width(5);
cout << array2[i][j];
}
}
cout << endl;
}
void delete_array(long int **array2, long int w)
{
for (long int i = 0; i < w; i++)
delete [] array2[i];
delete [] array2;
array2 = NULL;
}
void menu()
{
char option;
long int **array2;
bool array_exist=false;
bool fill_exist=false;
bool x_exist=false;
long int w,k,x;
while(1) {
cout << endl << "- - - - - - - - - - - - - - - - - - - - - -" << endl;
cout << "1. Ustal rozmiar tablicy" << endl;
cout << "2. Ustal maksymalna wartosc x" << endl;
cout << "3. Wypelnij tablice wartosciami od 0 do x" << endl;
cout << "4. Wyswietl tablice" << endl;
cout << "5. Usun tablice" << endl;
cout << "0. Koniec (usuwa dynamiczna tablice)" << endl;
cout << "- - - - - - - - - - - - - - - - - - - - - -" << endl << endl;
cout << "Wybor (0-5): ";
cin >> option;
cout << endl << endl;
switch(option)
{
case '1':
cout << "Podaj liczbe wierszy: ";
cin >> w;
cout << "Podaj liczbe kolumn: ";
cin >> k;
if(w>0 && k>0){
array2=create_array(w,k);
array_exist=true;
} else {
cerr << "Podano nieprawidlowe wymiary tablicy" << endl;
}
break;
case '2':
cout << "Podaj wartosc x: ";
cin >> x;
if (x<=0) cerr << "Podano nieprawdilowa wartosc x, podaj wartosc >0" << endl;
else x_exist=true;
break;
case '3':
if (x_exist && array_exist) fill_array(w,k,x,array2);
else {
cerr << "Nie podano rozmiaru tablicy badz wartosci x" << endl;
menu();
}
fill_exist=true;
break;
case '4':
if (fill_exist) show_array(w,k,x,array2);
else {
cerr << "Nie wypelniono tablicy" << endl;
menu();
}
break;
case '5':
if (array_exist) delete_array(array2,w);
else {
cerr << "Tablica nie istnieje" << endl;
menu();
}
array_exist=false;
fill_exist=false;
break;
case '0':
if (array_exist) delete_array(array2,w);
exit(0);
break;
default:
cerr << "Brak takiej opcji w menu" << endl;
menu();
break;
}
}
}
int main()
{
menu();
return 0;
}
<commit_msg>Final version of first task<commit_after>#include <iostream>
#include <cstdlib>
#include <iomanip>
using namespace std;
long int **create_array(long int w, long int k)
{
long int **array2 = new long int *[w];
for (long int i = 0; i < w; i++)
array2[i] = new long int[k];
return(array2);
}
void fill_array(long int w, long int k, long int x, long int **array2)
{
for(long int i = 0; i < w; i++)
for(long int j = 0; j < k; j++)
array2[i][j] = rand() % x;
}
void show_array(long int w, long int k, long int x, long int **array2)
{
for(long int i = 0; i < w; i++)
{
cout << endl;
for(long int j = 0; j < k; j++)
{
cout.width(5);
cout << array2[i][j];
}
}
cout << endl;
}
void delete_array(long int **array2, long int w)
{
for (long int i = 0; i < w; i++)
delete [] array2[i];
delete [] array2;
array2 = NULL;
}
void menu()
{
char option;
long int **array2;
bool array_exist=false;
bool fill_exist=false;
bool x_exist=false;
long int w,k,x;
while(1) {
cout << endl << "- - - - - - - - - - - - - - - - - - - - - -" << endl;
cout << "1. Ustal rozmiar tablicy" << endl;
cout << "2. Ustal maksymalna wartosc x" << endl;
cout << "3. Wypelnij tablice wartosciami od 0 do x" << endl;
cout << "4. Wyswietl tablice" << endl;
cout << "5. Usun tablice" << endl;
cout << "0. Koniec (usuwa dynamiczna tablice)" << endl;
cout << "- - - - - - - - - - - - - - - - - - - - - -" << endl << endl;
cout << "Wybor (0-5): ";
cin >> option;
cout << endl << endl;
switch(option)
{
case '1':
cout << "Podaj liczbe wierszy: ";
cin >> w;
cout << "Podaj liczbe kolumn: ";
cin >> k;
if(w>0 && k>0){
array2=create_array(w,k);
array_exist=true;
} else {
cerr << "Podano nieprawidlowe wymiary tablicy" << endl;
}
break;
case '2':
cout << "Podaj wartosc x: ";
cin >> x;
if (x<=0) cerr << "Podano nieprawdilowa wartosc x, podaj wartosc >0" << endl;
else x_exist=true;
break;
case '3':
if (x_exist && array_exist) fill_array(w,k,x,array2);
else {
cerr << "Nie podano rozmiaru tablicy badz wartosci x" << endl;
menu();
}
fill_exist=true;
break;
case '4':
if (fill_exist) show_array(w,k,x,array2);
else {
cerr << "Nie wypelniono tablicy" << endl;
menu();
}
break;
case '5':
if (array_exist) delete_array(array2,w);
else {
cerr << "Tablica nie istnieje" << endl;
menu();
}
array_exist=false;
fill_exist=false;
break;
case '0':
if (array_exist) delete_array(array2,w);
exit(0);
break;
default:
cerr << "Brak takiej opcji w menu" << endl;
menu();
break;
}
}
}
int main()
{
menu();
return 0;
}
<|endoftext|> |
<commit_before>#include "constants.hpp"
#include <iostream>
int main(int argc, const char* argv[]) {
std::cout << "get_user_configuration_directory: " << constants::get_user_configuration_directory() << std::endl;
std::cout << "get_user_data_directory: " << constants::get_user_data_directory() << std::endl;
std::cout << "get_user_log_directory: " << constants::get_user_log_directory() << std::endl;
std::cout << std::endl;
return 0;
}
<commit_msg>update dump_constants<commit_after>#include "constants.hpp"
#include <iostream>
int main(int argc, const char* argv[]) {
std::cout << "get_user_configuration_directory: " << constants::get_user_configuration_directory() << std::endl;
std::cout << "get_user_data_directory: " << constants::get_user_data_directory() << std::endl;
std::cout << "get_user_log_directory: " << constants::get_user_log_directory() << std::endl;
std::cout << "get_core_configuration_file_path: " << constants::get_core_configuration_file_path() << std::endl;
std::cout << std::endl;
return 0;
}
<|endoftext|> |
<commit_before>// __BEGIN_LICENSE__
// Copyright (c) 2006-2012, United States Government as represented by the
// Administrator of the National Aeronautics and Space Administration. All
// rights reserved.
//
// The NASA Vision Workbench is 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.
// __END_LICENSE__
// For every point in a given csv file draw a ray to the planet
// center, intersect the given dem (via interpolation), and compute
// the resulting distance from the starting point to the intersection
// point. Return the list of errors, and display statistics for them.
// The csv file is in the lat,lon,height format, with spaces or commas
// as separators. The first line may be a header file.
#ifdef _MSC_VER
#pragma warning(disable:4244)
#pragma warning(disable:4267)
#pragma warning(disable:4996)
#endif
#include <cstdlib>
#include <iostream>
#include <cmath>
#include <string>
#include <boost/tokenizer.hpp>
#include <boost/lexical_cast.hpp>
#include <boost/numeric/conversion/cast.hpp>
#include <boost/program_options.hpp>
#include <boost/filesystem/path.hpp>
#include <boost/foreach.hpp>
namespace fs = boost::filesystem;
namespace po = boost::program_options;
#include <vw/Core/Functors.h>
#include <vw/Image/Algorithms.h>
#include <vw/Image/ImageMath.h>
#include <vw/Image/ImageViewRef.h>
#include <vw/Image/PerPixelViews.h>
#include <vw/Image/PixelMask.h>
#include <vw/Image/MaskViews.h>
#include <vw/Image/PixelTypes.h>
#include <vw/Image/Statistics.h>
#include <vw/FileIO/DiskImageView.h>
#include <vw/Cartography/GeoReference.h>
#include <vw/tools/Common.h>
#include <vw/FileIO/DiskImageResourceGDAL.h>
#include <vw/Image/Interpolation.h>
#include <asp/Core/Macros.h>
#include <asp/Core/Common.h>
using namespace vw;
using namespace vw::cartography;
using namespace std;
// TODO: Several of these functions are already present in pc_align
struct Options: asp::BaseOptions {
// Input
string csv, dem;
// Output
string output_prefix;
};
void handle_arguments( int argc, char *argv[], Options& opt ) {
po::options_description general_options("");
general_options.add_options()
("output-prefix,o", po::value(&opt.output_prefix), "Specify the output prefix.");
general_options.add( asp::BaseOptionsDescription(opt) );
po::options_description positional("");
positional.add_options()
("csv", po::value(&opt.csv), "The csv file to find the distances from.")
("dem", po::value(&opt.dem), "The dem to the find distances to.");
po::positional_options_description positional_desc;
positional_desc.add("csv", 1);
positional_desc.add("dem", 1);
string usage("<csv> <dem>");
bool allow_unregistered = false;
std::vector<std::string> unregistered;
po::variables_map vm =
asp::check_command_line( argc, argv, opt, general_options, general_options,
positional, positional_desc, usage,
allow_unregistered, unregistered );
if ( opt.dem.empty() || opt.csv.empty() )
vw_throw( ArgumentErr() << "Missing input files.\n"
<< usage << general_options );
// Set default output prefix if none was passed in
if ( opt.output_prefix.empty() ) {
opt.output_prefix = fs::basename(opt.csv) + "__" + fs::basename(opt.dem);
}
asp::create_out_dir(opt.output_prefix);
}
/// Helper function to check for parsing errors
void null_check(const char* token, string const& line){
if (token == NULL)
vw_throw( vw::IOErr() << "Failed to read line: " << line << "\n" );
}
/// Parse CSV file consisting of lat/lon/height triplets with an optional header.
void load_csv(string const& file_name,
cartography::Datum const& datum,
vector<Vector3> & lon_lat_height
){
// Set up string copy buffer
const int bufSize = 1024;
char temp[bufSize];
// Try to load the input file
ifstream file( file_name.c_str() );
if( !file ) {
vw_throw( vw::IOErr() << "Unable to open file \"" << file_name << "\"" );
}
// Loop through all the lines of the file
string line;
char sep[] = ", \t";
bool is_first_line = true;
while ( getline(file, line, '\n') ){
double lat, lon, height;
strncpy(temp, line.c_str(), bufSize);
const char* token = strtok(temp, sep);
null_check(token, line); // Throw if the token is null
int ret = sscanf(token, "%lg", &lat);
token = strtok(NULL, sep);
null_check(token, line);
ret += sscanf(token, "%lg", &lon);
token = strtok(NULL, sep);
null_check(token, line);
ret += sscanf(token, "%lg", &height);
// Be prepared for the fact that the first line may be the header.
if (ret != 3){
if (!is_first_line){
vw_throw( vw::IOErr() << "Failed to read line: " << line << "\n" );
}else{
is_first_line = false;
continue;
}
}
is_first_line = false;
lon_lat_height.push_back(Vector3(lon, lat, height));
}
}
/// Compute the mean of an std::vector of doubles out to a length
double calc_mean(vector<double> const& errs, int len){
if (len == 0)
return 0;
double mean = 0.0;
for (int i = 0; i < len; i++){
mean += errs[i];
}
return mean/len;
}
typedef InterpolationView< EdgeExtensionView< ImageViewRef< PixelMask<float> >,
ConstantEdgeExtension>,
BilinearInterpolation> InterpolationReadyDem;
/// Get ready to interpolate points on a DEM existing on disk.
InterpolationReadyDem load_interpolation_ready_dem(std::string const& dem_path,
cartography::GeoReference & georef) {
// Load the georeference from the DEM
bool is_good = cartography::read_georeference( georef, dem_path );
if (!is_good)
vw_throw(ArgumentErr() << "DEM: " << dem_path << " does not have a georeference.\n");
// Set up file handle to the DEM and read the nodata value
DiskImageView<float> dem(dem_path);
double nodata = numeric_limits<double>::quiet_NaN();
boost::shared_ptr<DiskImageResource> dem_rsrc( new DiskImageResourceGDAL(dem_path) );
if (dem_rsrc->has_nodata_read())
nodata = dem_rsrc->nodata_read();
// Set up interpolation + mask view of the DEM
ImageViewRef< PixelMask<float> > masked_dem = create_mask(dem, nodata);
return InterpolationReadyDem(interpolate(masked_dem));
}
/// Interpolates the DEM height at the input coordinate.
/// - Returns false if the coordinate falls outside the valid DEM area.
bool interp_dem_height(InterpolationReadyDem const & dem,
vw::cartography::GeoReference const & georef,
vw::Vector3 const & lonlat,
double & dem_height) {
// Convert the lon/lat location into a pixel in the DEM.
vw::Vector2 pix = georef.lonlat_to_pixel(subvector(lonlat, 0, 2));
double c = pix[0],
r = pix[1];
// Quit if the pixel falls outside the DEM.
if (c < 0 || c >= dem.cols()-1 || // TODO: This ought to be an image class function
r < 0 || r >= dem.rows()-1 )
return false;
// Interpolate the DEM height at the pixel location
vw::PixelMask<float> v = dem(c, r);
if (!is_valid(v))
return false;
dem_height = v.child();
return true;
}
/// As interp_dem_height but normalizes the longitude of input points.
bool interp_dem_height_safe(InterpolationReadyDem const & dem,
vw::cartography::GeoReference const & georef,
double const & mean_dem_lon,
vw::Vector3 const & lonlat,
double & dem_height) {
// Normalize the longitude to be within 360 degrees of the mean longitude
vw::Vector3 lonlat_adjusted(lonlat);
lonlat_adjusted[0] += 360.0*round((mean_dem_lon - lonlat[0])/360.0); // 360 deg adjustment
return interp_dem_height(dem, georef, lonlat_adjusted, dem_height)
}
/// Computes the centroid lonlat point of a DEM
Vector2 compute_dem_mean_lonlat(vw::cartography::GeoReference const & georef,
int num_rows, int num_cols) {
Vector2 mean_dem_lonlat =
(georef.pixel_to_lonlat(Vector2(0, 0))
+ georef.pixel_to_lonlat(Vector2(num_cols-1, 0))
+ georef.pixel_to_lonlat(Vector2(0, num_rows-1))
+ georef.pixel_to_lonlat(Vector2(num_cols-1, num_rows-1))
)/4.0;
return mean_dem_lonlat;
}
//----------------------------------------------------------------------------
int main( int argc, char *argv[] ){
Options opt;
try {
handle_arguments( argc, argv, opt );
// Load the DEM and prepare it for interpolation
cartography::GeoReference georef;
InterpolationReadyDem masked_dem_interp(load_interpolation_ready_dem(opt.dem, georef));
const int dem_num_rows = masked_dem_interp.rows();
const int dem_num_cols = masked_dem_interp.cols();
// Find the mean longitude for the DEM points. This will be used to adjust
// the longitude of csv file points if need be.
Vector2 mean_dem_lonlat = compute_dem_mean_lonlat(georef, dem_num_rows, dem_num_cols);
double mean_dem_lon = mean_dem_lonlat[0];
// Load the input CSV file into a vector of vectors
vector<Vector3> lon_lat_height;
load_csv(opt.csv, georef.datum(), lon_lat_height);
std::cout << "Loaded: " << lon_lat_height.size() << " points from " << opt.csv << "." << std::endl;
// Loop through all of the input points
double nan = numeric_limits<double>::quiet_NaN();
vector<double> valid_errors, all_dz(lon_lat_height.size(), nan),
all_v(lon_lat_height.size(), nan), all_err(lon_lat_height.size(), nan);
for (int i = 0; i < (int)lon_lat_height.size(); i++){
Vector3 llh = lon_lat_height[i];
double dem_height_here;
if (!interp_dem_height_safe(masked_dem_interp, georef, mean_dem_lon, llh, dem_height_here))
continue; // Skip if no DEM intersection
// Compute and record the distance the input point height.
double err = std::abs(llh[2] - dem_height_here);
valid_errors.push_back(err);
all_v[i] = v.child();
all_dz[i] = dz;
all_err[i] = err;
}
int len = valid_errors.size();
vw_out() << "Computed " << len << " valid vertical point to dem errors." << std::endl;
if (len == 0)
return 0;
// Sort the error vector to make computing percentiles easy
sort(valid_errors.begin(), valid_errors.end());
// Compute and display statistics
double p16 = valid_errors[std::min(len-1, (int)round(len*0.16))];
double p50 = valid_errors[std::min(len-1, (int)round(len*0.50))];
double p84 = valid_errors[std::min(len-1, (int)round(len*0.84))];
vw_out() << "Error percentiles: "
<< " 16%: " << p16 << ", 50%: " << p50 << ", 84%: " << p84 << endl;
double mean = calc_mean(valid_errors, len);
vw_out() << "Mean error: " << mean << std::endl;
// Save the errors
std::string output_file = opt.output_prefix + "-sample.csv";
std::cout << "Writing: " << output_file << std::endl;
ofstream outfile( output_file.c_str() );
outfile << "# lat,lon,z_mHAE,z_samp_mHAE,dz_m,abs_dz_m" << endl;
for (int i = 0; i < (int)lon_lat_height.size(); i++){
Vector3 llh = lon_lat_height[i];
outfile << std::setiosflags(ios::fixed) << std::setprecision(8) << llh[1] << ',' << llh[0] << ','
<< std::setiosflags(ios::fixed) << std::setprecision(3) << llh[2]
<< ',' << all_v[i] << ',' << all_dz[i] << ',' << all_err[i] << endl;
}
} ASP_STANDARD_CATCHES;
return 0;
}
<commit_msg>point_to_dem_dist: compute RMSE<commit_after>// __BEGIN_LICENSE__
// Copyright (c) 2006-2012, United States Government as represented by the
// Administrator of the National Aeronautics and Space Administration. All
// rights reserved.
//
// The NASA Vision Workbench is 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.
// __END_LICENSE__
// For every point in a given csv file draw a ray to the planet
// center, intersect the given dem (via interpolation), and compute
// the resulting distance from the starting point to the intersection
// point. Return the list of errors, and display statistics for them.
// The csv file is in the lat,lon,height format, with spaces or commas
// as separators. The first line may be a header file.
#ifdef _MSC_VER
#pragma warning(disable:4244)
#pragma warning(disable:4267)
#pragma warning(disable:4996)
#endif
#include <cstdlib>
#include <iostream>
#include <cmath>
#include <string>
#include <boost/tokenizer.hpp>
#include <boost/lexical_cast.hpp>
#include <boost/numeric/conversion/cast.hpp>
#include <boost/program_options.hpp>
#include <boost/filesystem/path.hpp>
#include <boost/foreach.hpp>
namespace fs = boost::filesystem;
namespace po = boost::program_options;
#include <vw/Core/Functors.h>
#include <vw/Image/Algorithms.h>
#include <vw/Image/ImageMath.h>
#include <vw/Image/ImageViewRef.h>
#include <vw/Image/PerPixelViews.h>
#include <vw/Image/PixelMask.h>
#include <vw/Image/MaskViews.h>
#include <vw/Image/PixelTypes.h>
#include <vw/Image/Statistics.h>
#include <vw/FileIO/DiskImageView.h>
#include <vw/Cartography/GeoReference.h>
#include <vw/tools/Common.h>
#include <vw/FileIO/DiskImageResourceGDAL.h>
#include <vw/Image/Interpolation.h>
#include <asp/Core/Macros.h>
#include <asp/Core/Common.h>
using namespace vw;
using namespace vw::cartography;
using namespace std;
// TODO: Several of these functions are already present in pc_align
struct Options: asp::BaseOptions {
// Input
string csv, dem;
// Output
string output_prefix;
};
void handle_arguments( int argc, char *argv[], Options& opt ) {
po::options_description general_options("");
general_options.add_options()
("output-prefix,o", po::value(&opt.output_prefix), "Specify the output prefix.");
general_options.add( asp::BaseOptionsDescription(opt) );
po::options_description positional("");
positional.add_options()
("csv", po::value(&opt.csv), "The csv file to find the distances from.")
("dem", po::value(&opt.dem), "The dem to the find distances to.");
po::positional_options_description positional_desc;
positional_desc.add("csv", 1);
positional_desc.add("dem", 1);
string usage("<csv> <dem>");
bool allow_unregistered = false;
std::vector<std::string> unregistered;
po::variables_map vm =
asp::check_command_line( argc, argv, opt, general_options, general_options,
positional, positional_desc, usage,
allow_unregistered, unregistered );
if ( opt.dem.empty() || opt.csv.empty() )
vw_throw( ArgumentErr() << "Missing input files.\n"
<< usage << general_options );
// Set default output prefix if none was passed in
if ( opt.output_prefix.empty() ) {
opt.output_prefix = fs::basename(opt.csv) + "__" + fs::basename(opt.dem);
}
asp::create_out_dir(opt.output_prefix);
}
/// Helper function to check for parsing errors
void null_check(const char* token, string const& line){
if (token == NULL)
vw_throw( vw::IOErr() << "Failed to read line: " << line << "\n" );
}
/// Parse CSV file consisting of lat/lon/height triplets with an optional header.
void load_csv(string const& file_name,
cartography::Datum const& datum,
vector<Vector3> & lon_lat_height
){
// Set up string copy buffer
const int bufSize = 1024;
char temp[bufSize];
// Try to load the input file
ifstream file( file_name.c_str() );
if( !file ) {
vw_throw( vw::IOErr() << "Unable to open file \"" << file_name << "\"" );
}
// Loop through all the lines of the file
string line;
char sep[] = ", \t";
bool is_first_line = true;
while ( getline(file, line, '\n') ){
double lat, lon, height;
strncpy(temp, line.c_str(), bufSize);
const char* token = strtok(temp, sep);
null_check(token, line); // Throw if the token is null
int ret = sscanf(token, "%lg", &lat);
token = strtok(NULL, sep);
null_check(token, line);
ret += sscanf(token, "%lg", &lon);
token = strtok(NULL, sep);
null_check(token, line);
ret += sscanf(token, "%lg", &height);
// Be prepared for the fact that the first line may be the header.
if (ret != 3){
if (!is_first_line){
vw_throw( vw::IOErr() << "Failed to read line: " << line << "\n" );
}else{
is_first_line = false;
continue;
}
}
is_first_line = false;
lon_lat_height.push_back(Vector3(lon, lat, height));
}
}
/// Compute the mean of an std::vector of doubles out to a length
double calc_mean(vector<double> const& errs, int len){
if (len == 0)
return 0;
double mean = 0.0;
for (int i = 0; i < len; i++){
mean += errs[i];
}
return mean/len;
}
typedef InterpolationView< EdgeExtensionView< ImageViewRef< PixelMask<float> >,
ConstantEdgeExtension>,
BilinearInterpolation> InterpolationReadyDem;
/// Get ready to interpolate points on a DEM existing on disk.
InterpolationReadyDem load_interpolation_ready_dem(std::string const& dem_path,
cartography::GeoReference & georef) {
// Load the georeference from the DEM
bool is_good = cartography::read_georeference( georef, dem_path );
if (!is_good)
vw_throw(ArgumentErr() << "DEM: " << dem_path << " does not have a georeference.\n");
// Set up file handle to the DEM and read the nodata value
DiskImageView<float> dem(dem_path);
double nodata = numeric_limits<double>::quiet_NaN();
boost::shared_ptr<DiskImageResource> dem_rsrc( new DiskImageResourceGDAL(dem_path) );
if (dem_rsrc->has_nodata_read())
nodata = dem_rsrc->nodata_read();
// Set up interpolation + mask view of the DEM
ImageViewRef< PixelMask<float> > masked_dem = create_mask(dem, nodata);
return InterpolationReadyDem(interpolate(masked_dem));
}
/// Interpolates the DEM height at the input coordinate.
/// - Returns false if the coordinate falls outside the valid DEM area.
bool interp_dem_height(InterpolationReadyDem const & dem,
vw::cartography::GeoReference const & georef,
vw::Vector3 const & lonlat,
double & dem_height) {
// Convert the lon/lat location into a pixel in the DEM.
vw::Vector2 pix = georef.lonlat_to_pixel(subvector(lonlat, 0, 2));
double c = pix[0],
r = pix[1];
// Quit if the pixel falls outside the DEM.
if (c < 0 || c >= dem.cols()-1 || // TODO: This ought to be an image class function
r < 0 || r >= dem.rows()-1 )
return false;
// Interpolate the DEM height at the pixel location
vw::PixelMask<float> v = dem(c, r);
if (!is_valid(v))
return false;
dem_height = v.child();
return true;
}
/// As interp_dem_height but normalizes the longitude of input points.
bool interp_dem_height_safe(InterpolationReadyDem const & dem,
vw::cartography::GeoReference const & georef,
double const & mean_dem_lon,
vw::Vector3 const & lonlat,
double & dem_height) {
// Normalize the longitude to be within 360 degrees of the mean longitude
vw::Vector3 lonlat_adjusted(lonlat);
lonlat_adjusted[0] += 360.0*round((mean_dem_lon - lonlat[0])/360.0); // 360 deg adjustment
return interp_dem_height(dem, georef, lonlat_adjusted, dem_height)
}
/// Computes the centroid lonlat point of a DEM
Vector2 compute_dem_mean_lonlat(vw::cartography::GeoReference const & georef,
int num_rows, int num_cols) {
Vector2 mean_dem_lonlat =
(georef.pixel_to_lonlat(Vector2(0, 0))
+ georef.pixel_to_lonlat(Vector2(num_cols-1, 0))
+ georef.pixel_to_lonlat(Vector2(0, num_rows-1))
+ georef.pixel_to_lonlat(Vector2(num_cols-1, num_rows-1))
)/4.0;
return mean_dem_lonlat;
}
//----------------------------------------------------------------------------
double calc_rmse(vector<double> const& errs, int len){
double sum = 0.0;
for (int i = 0; i < len; i++){
sum += errs[i]*errs[i];
}
if (len == 0) return 0;
return std::sqrt(sum/len);
}
int main( int argc, char *argv[] ){
Options opt;
try {
handle_arguments( argc, argv, opt );
// Load the DEM and prepare it for interpolation
cartography::GeoReference georef;
InterpolationReadyDem masked_dem_interp(load_interpolation_ready_dem(opt.dem, georef));
const int dem_num_rows = masked_dem_interp.rows();
const int dem_num_cols = masked_dem_interp.cols();
// Find the mean longitude for the DEM points. This will be used to adjust
// the longitude of csv file points if need be.
Vector2 mean_dem_lonlat = compute_dem_mean_lonlat(georef, dem_num_rows, dem_num_cols);
double mean_dem_lon = mean_dem_lonlat[0];
// Load the input CSV file into a vector of vectors
vector<Vector3> lon_lat_height;
load_csv(opt.csv, georef.datum(), lon_lat_height);
std::cout << "Loaded: " << lon_lat_height.size() << " points from " << opt.csv << "." << std::endl;
// Loop through all of the input points
double nan = numeric_limits<double>::quiet_NaN();
vector<double> valid_errors, all_dz(lon_lat_height.size(), nan),
all_v(lon_lat_height.size(), nan), all_err(lon_lat_height.size(), nan);
for (int i = 0; i < (int)lon_lat_height.size(); i++){
Vector3 llh = lon_lat_height[i];
double dem_height_here;
if (!interp_dem_height_safe(masked_dem_interp, georef, mean_dem_lon, llh, dem_height_here))
continue; // Skip if no DEM intersection
// Compute and record the distance the input point height.
double err = std::abs(llh[2] - dem_height_here);
valid_errors.push_back(err);
all_v[i] = v.child();
all_dz[i] = dz;
all_err[i] = err;
}
int len = valid_errors.size();
vw_out() << "Computed " << len << " valid vertical point to dem errors." << std::endl;
if (len == 0)
return 0;
// Sort the error vector to make computing percentiles easy
sort(valid_errors.begin(), valid_errors.end());
// Compute and display statistics
double p16 = valid_errors[std::min(len-1, (int)round(len*0.16))];
double p50 = valid_errors[std::min(len-1, (int)round(len*0.50))];
double p84 = valid_errors[std::min(len-1, (int)round(len*0.84))];
vw_out() << "Error percentiles: "
<< " 16%: " << p16 << ", 50%: " << p50 << ", 84%: " << p84 << endl;
double mean = calc_mean(valid_errors, len);
vw_out() << "Mean error: " << mean << std::endl;
double rmse = calc_rmse(valid_errors, len);
vw_out() << "RMSE: " << rmse << std::endl;
// Save the errors
std::string output_file = opt.output_prefix + "-sample.csv";
std::cout << "Writing: " << output_file << std::endl;
ofstream outfile( output_file.c_str() );
outfile << "# lat,lon,z_mHAE,z_samp_mHAE,dz_m,abs_dz_m" << endl;
for (int i = 0; i < (int)lon_lat_height.size(); i++){
Vector3 llh = lon_lat_height[i];
outfile << std::setiosflags(ios::fixed) << std::setprecision(8) << llh[1] << ',' << llh[0] << ','
<< std::setiosflags(ios::fixed) << std::setprecision(3) << llh[2]
<< ',' << all_v[i] << ',' << all_dz[i] << ',' << all_err[i] << endl;
}
} ASP_STANDARD_CATCHES;
return 0;
}
<|endoftext|> |
<commit_before>/* Copyright (c) 2014 Quanta Research Cambridge, Inc
*
* Permission is hereby granted, free of charge, to any person obtaining a
* copy of this software and associated documentation files (the "Software"),
* to deal in the Software without restriction, including without limitation
* the rights to use, copy, modify, merge, publish, distribute, sublicense,
* and/or sell copies of the Software, and to permit persons to whom the
* Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included
* in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
* OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
* THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
* DEALINGS IN THE SOFTWARE.
*/
#include "DmaConfigProxy.h"
#include "DmaIndicationWrapper.h"
#include "StdDmaIndication.h"
#include "GeneratedTypes.h"
#include "HdmiDisplayRequestProxy.h"
#include "HdmiDisplayIndicationWrapper.h"
#include "HdmiInternalIndicationWrapper.h"
#include "HdmiInternalRequestProxy.h"
#include "portal.h"
#include <stdio.h>
#include <sys/mman.h>
#include <ctype.h>
#include "i2chdmi.h"
#include "edid.h"
#define FRAME_COUNT 2
static HdmiInternalRequestProxy *hdmiInternal;
static HdmiDisplayRequestProxy *device;
static DmaConfigProxy *dma;
static PortalAlloc *portalAlloc[FRAME_COUNT];
static unsigned int ref_srcAlloc[FRAME_COUNT];
static int *dataptr[FRAME_COUNT];
static int frame_index;
static int nlines = 1080;
static int npixels = 1920;
static int fbsize = nlines*npixels*4;
void dump(const char *prefix, char *buf, size_t len)
{
fprintf(stderr, "%s: ", prefix);
for (int i = 0; i < 16; i++)
fprintf(stderr, "%02x", (unsigned char)buf[i]);
fprintf(stderr, "\n");
}
static void *thread_routine(void *data)
{
fprintf(stderr, "Calling portalExec\n");
portalExec(0);
fprintf(stderr, "portalExec returned ???\n");
return data;
}
static void fill_pixels(int offset)
{
static int once = 1;
int *ptr = dataptr[frame_index];
for (int line = 0; line < nlines-100; line++)
for (int pixel = 0; pixel < npixels; pixel++)
*ptr++ = ((((256 * line) / nlines)+offset) % 256) << 16
| ((((128 * pixel) / npixels)+offset) % 128);
if (once) {
dma->dCacheFlushInval(portalAlloc[frame_index], dataptr[frame_index]);
device->startFrameBuffer(ref_srcAlloc[frame_index], fbsize);
hdmiInternal->waitForVsync(0);
frame_index = 1 - frame_index;
}
//once = 0;
}
static int synccount = 0;
static long long totalcount;
static int number;
class HdmiIndication : public HdmiInternalIndicationWrapper {
public:
HdmiIndication(int id) : HdmiInternalIndicationWrapper(id) {}
virtual void vsync ( uint64_t v, uint32_t w ) {
static int base = 0;
totalcount += v;
number += w;
fill_pixels(base++);
if (synccount++ >= 30) {
synccount = 0;
fprintf(stderr, "[%s:%d] avg %lld; v=%d w=%d\n", __FUNCTION__, __LINE__, totalcount/number, (uint32_t) v, w);
}
}
};
class DisplayIndication : public HdmiDisplayIndicationWrapper {
public:
DisplayIndication(int id) : HdmiDisplayIndicationWrapper(id) {}
virtual void transferStarted ( uint32_t v ) {
fprintf(stderr, "[%s:%d] v=%d\n", __FUNCTION__, __LINE__, v);
}
virtual void transferFinished ( uint32_t v ) {
fprintf(stderr, "[%s:%d] v=%d\n", __FUNCTION__, __LINE__, v);
}
virtual void transferStats ( uint32_t count, uint32_t cycles, uint64_t sumcycles ) {
fprintf(stderr, "[%s:%d] count=%d cycles=%d sumcycles=%lld avgcycles=%f\n", __FUNCTION__, __LINE__, count, cycles, sumcycles, (double)sumcycles / count);
}
};
int main(int argc, const char **argv)
{
PortalPoller *poller = 0;
DmaIndicationWrapper *dmaIndication;
poller = new PortalPoller();
device = new HdmiDisplayRequestProxy(IfcNames_HdmiDisplayRequest, poller);
dma = new DmaConfigProxy(IfcNames_DmaConfig);
dmaIndication = new DmaIndication(dma, IfcNames_DmaIndication);
HdmiInternalIndicationWrapper *hdmiIndication = new HdmiIndication(IfcNames_HdmiInternalIndication);
HdmiDisplayIndicationWrapper *displayIndication = new DisplayIndication(IfcNames_HdmiDisplayIndication);
hdmiInternal = new HdmiInternalRequestProxy(IfcNames_HdmiInternalRequest);
// read out monitor EDID from ADV7511
struct edid edid;
init_i2c_hdmi();
int i2cfd = open("/dev/i2c-0", O_RDWR);
fprintf(stderr, "Monitor EDID:\n");
for (int i = 0; i < 256; i++) {
edid.raw[i] = i2c_read_reg(i2cfd, 0x3f, i);
fprintf(stderr, " %02x", edid.raw[i]);
if ((i % 16) == 15) {
fprintf(stderr, " ");
for (int j = i-15; j <= i; j++) {
unsigned char c = edid.raw[j];
fprintf(stderr, "%c", (isprint(c) && isascii(c)) ? c : '.');
}
fprintf(stderr, "\n");
}
}
close(i2cfd);
parseEdid(edid);
device->stopFrameBuffer();
pthread_t thread;
pthread_attr_t attr;
pthread_attr_init(&attr);
pthread_create(&thread, &attr, thread_routine, 0);
int status;
status = poller->setClockFrequency(0, 100000000, 0);
for (int i = 0; i < 4; i++) {
int pixclk = (long)edid.timing[i].pixclk * 10000;
if ((pixclk > 0) && (pixclk < 170000000)) {
nlines = edid.timing[i].nlines;
npixels = edid.timing[i].npixels;
int lmin = edid.timing[i].blines;
int pmin = edid.timing[i].bpixels;
int vsyncwidth = edid.timing[i].vsyncwidth;
int hsyncwidth = edid.timing[i].hsyncwidth;
fprintf(stderr, "lines %d, pixels %d, lmin %d, pmin %d, vwidth %d, hwidth %d\n", nlines, npixels, lmin, pmin, vsyncwidth, hsyncwidth);
fprintf(stderr, "Using pixclk %d calc_pixclk %d npixels %d nlines %d\n",
pixclk,
60l * (long)(pmin + npixels) * (long)(lmin + nlines),
npixels, nlines);
status = poller->setClockFrequency(1, pixclk, 0);
hdmiInternal->setNumberOfLines(lmin + nlines);
hdmiInternal->setNumberOfPixels(pmin + npixels);
hdmiInternal->setDeLineCountMinMax (lmin - vsyncwidth, lmin + nlines - vsyncwidth, (lmin + lmin + nlines) / 2 - vsyncwidth);
hdmiInternal->setDePixelCountMinMax (pmin, pmin + npixels, pmin + npixels / 2);
break;
}
}
fbsize = nlines*npixels*4;
for (int i = 0; i < FRAME_COUNT; i++) {
int err = dma->alloc(fbsize, &portalAlloc[i]);
dataptr[i] = (int*)mmap(0, fbsize, PROT_READ|PROT_WRITE, MAP_SHARED, portalAlloc[i]->header.fd, 0);
fprintf(stderr, "calling dma->reference\n");
ref_srcAlloc[i] = dma->reference(portalAlloc[i]);
}
fprintf(stderr, "first mem_stats=%10u\n", dma->show_mem_stats(ChannelType_Read));
sleep(3);
fprintf(stderr, "Starting frame buffer ref=%d...", ref_srcAlloc[0]);
fill_pixels(0);
fprintf(stderr, "done\n");
while (1) {
fprintf(stderr, "mem_stats=%10u\n", dma->show_mem_stats(ChannelType_Read));
sleep(1);
}
}
<commit_msg>simplify hdmi test<commit_after>/* Copyright (c) 2014 Quanta Research Cambridge, Inc
*
* Permission is hereby granted, free of charge, to any person obtaining a
* copy of this software and associated documentation files (the "Software"),
* to deal in the Software without restriction, including without limitation
* the rights to use, copy, modify, merge, publish, distribute, sublicense,
* and/or sell copies of the Software, and to permit persons to whom the
* Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included
* in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
* OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
* THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
* DEALINGS IN THE SOFTWARE.
*/
#include "DmaConfigProxy.h"
#include "DmaIndicationWrapper.h"
#include "StdDmaIndication.h"
#include "GeneratedTypes.h"
#include "HdmiDisplayRequestProxy.h"
#include "HdmiDisplayIndicationWrapper.h"
#include "HdmiInternalIndicationWrapper.h"
#include "HdmiInternalRequestProxy.h"
#include "portal.h"
#include <stdio.h>
#include <sys/mman.h>
#include <ctype.h>
#include "i2chdmi.h"
#include "edid.h"
#define FRAME_COUNT 2
static HdmiInternalRequestProxy *hdmiInternal;
static HdmiDisplayRequestProxy *device;
static DmaConfigProxy *dma;
static PortalAlloc *portalAlloc[FRAME_COUNT];
static unsigned int ref_srcAlloc[FRAME_COUNT];
static int *dataptr[FRAME_COUNT];
static int frame_index;
static int nlines = 1080;
static int npixels = 1920;
static int fbsize = nlines*npixels*4;
void dump(const char *prefix, char *buf, size_t len)
{
fprintf(stderr, "%s: ", prefix);
for (int i = 0; i < 16; i++)
fprintf(stderr, "%02x", (unsigned char)buf[i]);
fprintf(stderr, "\n");
}
static void *thread_routine(void *data)
{
fprintf(stderr, "Calling portalExec\n");
portalExec(0);
fprintf(stderr, "portalExec returned ???\n");
return data;
}
static void fill_pixels(int offset)
{
int begin = 0;
if (offset) {
begin = 200;
}
int *ptr = dataptr[frame_index];
for (int line = begin; line < nlines-20; line++)
for (int pixel = 0; pixel < npixels; pixel++)
ptr[line * npixels + pixel] = ((((256 * line) / nlines)+offset) % 256) << 16
| ((((128 * pixel) / npixels)+offset) % 128);
dma->dCacheFlushInval(portalAlloc[frame_index], dataptr[frame_index]);
device->startFrameBuffer(ref_srcAlloc[frame_index], fbsize);
hdmiInternal->waitForVsync(0);
frame_index = 1 - frame_index;
}
static int synccount = 0;
static long long totalcount;
static int number;
class HdmiIndication : public HdmiInternalIndicationWrapper {
public:
HdmiIndication(int id) : HdmiInternalIndicationWrapper(id) {}
virtual void vsync ( uint64_t v, uint32_t w ) {
static int base = 0;
totalcount += v;
number += w;
fill_pixels(base++);
if (synccount++ >= 30) {
synccount = 0;
fprintf(stderr, "[%s:%d] avg %lld; v=%d w=%d\n", __FUNCTION__, __LINE__, totalcount/number, (uint32_t) v, w);
}
}
};
class DisplayIndication : public HdmiDisplayIndicationWrapper {
public:
DisplayIndication(int id) : HdmiDisplayIndicationWrapper(id) {}
virtual void transferStarted ( uint32_t v ) {
fprintf(stderr, "[%s:%d] v=%d\n", __FUNCTION__, __LINE__, v);
}
virtual void transferFinished ( uint32_t v ) {
fprintf(stderr, "[%s:%d] v=%d\n", __FUNCTION__, __LINE__, v);
}
virtual void transferStats ( uint32_t count, uint32_t cycles, uint64_t sumcycles ) {
fprintf(stderr, "[%s:%d] count=%d cycles=%d sumcycles=%lld avgcycles=%f\n", __FUNCTION__, __LINE__, count, cycles, sumcycles, (double)sumcycles / count);
}
};
int main(int argc, const char **argv)
{
PortalPoller *poller = 0;
DmaIndicationWrapper *dmaIndication;
poller = new PortalPoller();
device = new HdmiDisplayRequestProxy(IfcNames_HdmiDisplayRequest, poller);
dma = new DmaConfigProxy(IfcNames_DmaConfig);
dmaIndication = new DmaIndication(dma, IfcNames_DmaIndication);
HdmiInternalIndicationWrapper *hdmiIndication = new HdmiIndication(IfcNames_HdmiInternalIndication);
HdmiDisplayIndicationWrapper *displayIndication = new DisplayIndication(IfcNames_HdmiDisplayIndication);
hdmiInternal = new HdmiInternalRequestProxy(IfcNames_HdmiInternalRequest);
// read out monitor EDID from ADV7511
struct edid edid;
init_i2c_hdmi();
int i2cfd = open("/dev/i2c-0", O_RDWR);
fprintf(stderr, "Monitor EDID:\n");
for (int i = 0; i < 256; i++) {
edid.raw[i] = i2c_read_reg(i2cfd, 0x3f, i);
fprintf(stderr, " %02x", edid.raw[i]);
if ((i % 16) == 15) {
fprintf(stderr, " ");
for (int j = i-15; j <= i; j++) {
unsigned char c = edid.raw[j];
fprintf(stderr, "%c", (isprint(c) && isascii(c)) ? c : '.');
}
fprintf(stderr, "\n");
}
}
close(i2cfd);
parseEdid(edid);
device->stopFrameBuffer();
pthread_t thread;
pthread_attr_t attr;
pthread_attr_init(&attr);
pthread_create(&thread, &attr, thread_routine, 0);
int status;
status = poller->setClockFrequency(0, 100000000, 0);
for (int i = 0; i < 4; i++) {
int pixclk = (long)edid.timing[i].pixclk * 10000;
if ((pixclk > 0) && (pixclk < 170000000)) {
nlines = edid.timing[i].nlines;
npixels = edid.timing[i].npixels;
int lmin = edid.timing[i].blines;
int pmin = edid.timing[i].bpixels;
int vsyncwidth = edid.timing[i].vsyncwidth;
int hsyncwidth = edid.timing[i].hsyncwidth;
fprintf(stderr, "lines %d, pixels %d, lmin %d, pmin %d, vwidth %d, hwidth %d\n", nlines, npixels, lmin, pmin, vsyncwidth, hsyncwidth);
fprintf(stderr, "Using pixclk %d calc_pixclk %d npixels %d nlines %d\n",
pixclk,
60l * (long)(pmin + npixels) * (long)(lmin + nlines),
npixels, nlines);
status = poller->setClockFrequency(1, pixclk, 0);
hdmiInternal->setNumberOfLines(lmin + nlines);
hdmiInternal->setNumberOfPixels(pmin + npixels);
hdmiInternal->setDeLineCountMinMax (lmin - vsyncwidth, lmin + nlines - vsyncwidth, (lmin + lmin + nlines) / 2 - vsyncwidth);
hdmiInternal->setDePixelCountMinMax (pmin, pmin + npixels, pmin + npixels / 2);
break;
}
}
fbsize = nlines*npixels*4;
for (int i = 0; i < FRAME_COUNT; i++) {
int err = dma->alloc(fbsize, &portalAlloc[i]);
dataptr[i] = (int*)mmap(0, fbsize, PROT_READ|PROT_WRITE, MAP_SHARED, portalAlloc[i]->header.fd, 0);
memset(dataptr[i], i ? 0xff : 0, fbsize);
fprintf(stderr, "calling dma->reference\n");
ref_srcAlloc[i] = dma->reference(portalAlloc[i]);
}
fprintf(stderr, "first mem_stats=%10u\n", dma->show_mem_stats(ChannelType_Read));
sleep(3);
fprintf(stderr, "Starting frame buffer ref=%d...", ref_srcAlloc[0]);
fill_pixels(0);
fprintf(stderr, "done\n");
while (1) {
fprintf(stderr, "mem_stats=%10u\n", dma->show_mem_stats(ChannelType_Read));
sleep(1);
}
}
<|endoftext|> |
<commit_before>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: typemap.cxx,v $
*
* $Revision: 1.12 $
*
* last change: $Author: obo $ $Date: 2006-09-16 18:17:35 $
*
* The Contents of this file are made available subject to
* the terms of GNU Lesser General Public License Version 2.1.
*
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2005 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
************************************************************************/
// MARKER(update_precomp.py): autogen include statement, do not remove
#include "precompiled_sd.hxx"
#define ITEMID_CASEMAP 0
#define ITEMID_DBTYPE 0
#define ITEMID_LINESPACE 0
#define ITEMID_INTERLINESPACE 0
#define ITEMID_BREAK 0
#define ITEMID_NUMTYPE 0
#define ITEMID_SHADOWLOCATION 0
#define ITEMID_BRUSH 0
#define ITEMID_PAGE 0
#define ITEMID_PAGEMODEL 0
#define ITEMID_ORPHANS 0
#define ITEMID_KERNING 0
#define ITEMID_POSTITDATE 0
#define ITEMID_SEARCH 0
#define ITEMID_TEXT 0
#define ITEMID_AUTHOR 0
#define ITEMID_DATE 0
#define ITEMID_SIZE 0
#define ITEMID_LANGUAGE 0
#define ITEMID_HYPHENZONE 0
#define ITEMID_FMTSPLIT 0
#define ITEMID_FMTKEEP 0
#define ITEMID_FMTBREAK 0
#define ITEMID_AUTOKERN 0
#define ITEMID_LINE 0
#define ITEMID_LONGLRSPACE 0
#define ITEMID_LONGULSPACE 0
#define ITEMID_ZOOM 0
#define ITEMID_HORJUSTIFY 0
#define ITEMID_VERJUSTIFY 0
#define ITEMID_ORIENTATION 0
#define ITEMID_WIDOWS 0
#define ITEMID_DOUBLE 0
#include "eetext.hxx"
#ifndef _EEITEM_HXX //autogen
#include <svx/eeitem.hxx>
#endif
#ifndef _SVX_LANGITEM_HXX //autogen
#include <svx/langitem.hxx>
#endif
#ifndef _SVX_FHGTITEM_HXX //autogen
#include <svx/fhgtitem.hxx>
#endif
#ifndef _SVX_COLRITEM_HXX //autogen
#include <svx/colritem.hxx>
#endif
#ifndef _SVX_ITEM_HXX //autogen
#include <svx/cntritem.hxx>
#endif
#ifndef _SVX_SHDDITEM_HXX //autogen
#include <svx/shdditem.hxx>
#endif
#ifndef _SVX_CRSDITEM_HXX //autogen
#include <svx/crsditem.hxx>
#endif
#ifndef _SVX_UDLNITEM_HXX //autogen
#include <svx/udlnitem.hxx>
#endif
#ifndef _SVX_WGHTITEM_HXX //autogen
#include <svx/wghtitem.hxx>
#endif
#ifndef _SVX_POSTITEM_HXX //autogen
#include <svx/postitem.hxx>
#endif
#ifndef _SVX_FONTITEM_HXX //autogen
#include <svx/fontitem.hxx>
#endif
#ifndef _SFXPOOLITEM_HXX //autogen
#include <svtools/poolitem.hxx>
#endif
#ifndef _SVX_TSPTITEM_HXX //autogen
#include <svx/tstpitem.hxx>
#endif
#ifndef _SVX_LRSPITEM_HXX //autogen
#include <svx/lrspitem.hxx>
#endif
#ifndef _SVX_PROTITEM_HXX //autogen
#include <svx/protitem.hxx>
#endif
#ifndef _SVX_CHRTITEM_HXX
#include <svx/chrtitem.hxx>
#endif
#include <svtools/globalnameitem.hxx>
#include <svx/hlnkitem.hxx>
#include <svx/postattr.hxx>
#include <svx/editdata.hxx>
#include <svx/srchdlg.hxx>
#include <svx/rulritem.hxx>
#include <svx/clipfmtitem.hxx>
#include <sfx2/srchitem.hxx>
#include <svx/sizeitem.hxx>
#include <svx/svxenum.hxx>
#include <svx/algitem.hxx>
#include <svx/zoomitem.hxx>
#include <svx/pageitem.hxx>
#include <svx/svdattr.hxx>
#include <svx/grafctrl.hxx>
#include "sdattr.hxx"
#ifndef _SVX_XFTSTIT_HXX //autogen
#include <svx/xftstit.hxx>
#endif
#ifndef _SVX_XLNWTIT_HXX //autogen
#include <svx/xlnwtit.hxx>
#endif
#ifndef _SVX_XLINEIT0_HXX //autogen
#include <svx/xlineit0.hxx>
#endif
#ifndef _SVX_XLNCLIT_HXX //autogen
#include <svx/xlnclit.hxx>
#endif
#ifndef _SVX_XLNDSIT_HXX //autogen
#include <svx/xlndsit.hxx>
#endif
#ifndef _SVX_XFLCLIT_HXX //autogen
#include <svx/xflclit.hxx>
#endif
#ifndef SVX_XFILLIT0_HXX //autogen
#include <svx/xfillit0.hxx>
#endif
#ifndef _SVX_XLNEDIT_HXX //autogen
#include <svx/xlnedit.hxx>
#endif
#ifndef _SVX_XLNSTIT_HXX //autogen
#include <svx/xlnstit.hxx>
#endif
#ifndef _SVX__XGRADIENT_HXX //autogen
#include <svx/xgrad.hxx>
#endif
#ifndef _SVX_XFLGRIT_HXX //autogen
#include <svx/xflgrit.hxx>
#endif
#ifndef _SVX_XFLHTIT_HXX //autogen
#include <svx/xflhtit.hxx>
#endif
#ifndef _SVX_XBTMPIT_HXX //autogen
#include <svx/xbtmpit.hxx>
#endif
#ifndef _SVX_TEXTIT0_HXX //autogen
#include <svx/xtextit0.hxx>
#endif
#ifndef _SVX_XFTADIT_HXX //autogen
#include <svx/xftadit.hxx>
#endif
#ifndef _SVX_XFTDIIT_HXX //autogen
#include <svx/xftdiit.hxx>
#endif
#ifndef _SVX_XFTMRIT_HXX //autogen
#include <svx/xftmrit.hxx>
#endif
#ifndef _SVX_XFTOUIT_HXX //autogen
#include <svx/xftouit.hxx>
#endif
#ifndef _SVX_XFTSHIT_HXX //autogen
#include <svx/xftshit.hxx>
#endif
#ifndef _SVX_XFTSHCLIT_HXX //autogen
#include <svx/xftshcit.hxx>
#endif
#ifndef _SVX_XFTSHXY_HXX //autogen
#include <svx/xftshxy.hxx>
#endif
#ifndef _SVX_XFTSFIT_HXX //autogen
#include <svx/xftsfit.hxx>
#endif
#ifndef _SVX_TEXTIT0_HXX //autogen
#include <svx/xtextit0.hxx>
#endif
#ifndef _AVMEDIA_MEDIAITEM_HXX
#include <avmedia/mediaitem.hxx>
#endif
#define ITEMID_DASH_LIST SID_DASH_LIST
#define ITEMID_LINEEND_LIST SID_LINEEND_LIST
#define ITEMID_COLOR_TABLE SID_COLOR_TABLE
#define ITEMID_GRADIENT_LIST SID_GRADIENT_LIST
#define ITEMID_HATCH_LIST SID_HATCH_LIST
#define ITEMID_BITMAP_LIST SID_BITMAP_LIST
#ifndef _SVX_DRAWITEM_HXX
#include <svx/drawitem.hxx>
#endif
// #UndoRedo#
#ifndef _SFXSLSTITM_HXX
#include <svtools/slstitm.hxx>
#endif
#include <svtools/lckbitem.hxx>
#define CharSetItem SfxUInt16Item
#define FontFamilyItem SfxUInt16Item
#define FontPitchItem SfxUInt16Item
#define FontAlignItem SfxUInt16Item
#define FontWeightItem SfxUInt16Item
#define FontUnderlineItem SfxUInt16Item
#define FontStrikeoutItem SfxUInt16Item
#define FontItalicItem SfxUInt16Item
#define SvxDbTypeItem SfxUInt16Item
#define SvxLineSpaceItem SfxUInt16Item
#define SvxInterLineSpaceItem SfxUInt16Item
#define SvxBreakItem SfxUInt16Item
#define BrushStyleItem SfxUInt16Item
#define SvxNumTypeItem SfxUInt16Item
#define SvxShadowLocationItem SfxUInt16Item
#define SvxDbTypeItem SfxUInt16Item
//#define SvxChooseControlEnumItem SfxUInt16Item
#define SvxDrawToolEnumItem SfxUInt16Item
#define SvxChooseControlItem SfxEnumItem
#define SvxDrawToolItem SfxUInt16Item
#define SvxCellHorJustifyEnumItem SfxUInt16Item
#define SvxCellVerJustifyEnumItem SfxUInt16Item
#define SvxCellOrientationEnumItem SfxUInt16Item
#define SvxLanguage SfxUInt16Item
//#define SfxLockBytesItem SfxPoolItem
#define OfaStringListItem SfxStringListItem
#define avmedia_MediaItem ::avmedia::MediaItem
#ifndef _SFX_TPLPITEM_HXX //autogen
#include <sfx2/tplpitem.hxx>
#endif
#ifndef _SFXPTITEM_HXX //autogen
#include <svtools/ptitem.hxx>
#endif
#ifndef _SFXRECTITEM_HXX //autogen
#include <svtools/rectitem.hxx>
#endif
#include <sfx2/frame.hxx>
#define SFX_TYPEMAP
#include "sdslots.hxx"
<commit_msg>INTEGRATION: CWS pchfix04 (1.12.66); FILE MERGED 2007/02/05 08:38:52 os 1.12.66.2: #i73604# usage of ITEMID_* removed 2007/01/19 10:49:54 hjs 1.12.66.1: #i73650# warning free with pch<commit_after>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: typemap.cxx,v $
*
* $Revision: 1.13 $
*
* last change: $Author: kz $ $Date: 2007-05-10 15:23:21 $
*
* The Contents of this file are made available subject to
* the terms of GNU Lesser General Public License Version 2.1.
*
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2005 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
************************************************************************/
// MARKER(update_precomp.py): autogen include statement, do not remove
#include "precompiled_sd.hxx"
#include "eetext.hxx"
#ifndef _EEITEM_HXX //autogen
#include <svx/eeitem.hxx>
#endif
#ifndef _SVX_LANGITEM_HXX //autogen
#include <svx/langitem.hxx>
#endif
#ifndef _SVX_FHGTITEM_HXX //autogen
#include <svx/fhgtitem.hxx>
#endif
#ifndef _SVX_COLRITEM_HXX //autogen
#include <svx/colritem.hxx>
#endif
#ifndef _SVX_ITEM_HXX //autogen
#include <svx/cntritem.hxx>
#endif
#ifndef _SVX_SHDDITEM_HXX //autogen
#include <svx/shdditem.hxx>
#endif
#ifndef _SVX_CRSDITEM_HXX //autogen
#include <svx/crsditem.hxx>
#endif
#ifndef _SVX_UDLNITEM_HXX //autogen
#include <svx/udlnitem.hxx>
#endif
#ifndef _SVX_WGHTITEM_HXX //autogen
#include <svx/wghtitem.hxx>
#endif
#ifndef _SVX_POSTITEM_HXX //autogen
#include <svx/postitem.hxx>
#endif
#ifndef _SVX_FONTITEM_HXX //autogen
#include <svx/fontitem.hxx>
#endif
#ifndef _SFXPOOLITEM_HXX //autogen
#include <svtools/poolitem.hxx>
#endif
#ifndef _SVX_TSPTITEM_HXX //autogen
#include <svx/tstpitem.hxx>
#endif
#ifndef _SVX_LRSPITEM_HXX //autogen
#include <svx/lrspitem.hxx>
#endif
#ifndef _SVX_PROTITEM_HXX //autogen
#include <svx/protitem.hxx>
#endif
#ifndef _SVX_CHRTITEM_HXX
#include <svx/chrtitem.hxx>
#endif
#include <svtools/globalnameitem.hxx>
#include <svx/hlnkitem.hxx>
#include <svx/postattr.hxx>
#include <svx/editdata.hxx>
#include <svx/srchdlg.hxx>
#include <svx/rulritem.hxx>
#include <svx/clipfmtitem.hxx>
#include <sfx2/srchitem.hxx>
#include <svx/sizeitem.hxx>
#include <svx/svxenum.hxx>
#include <svx/algitem.hxx>
#include <svx/zoomitem.hxx>
#include <svx/pageitem.hxx>
#include <svx/svdattr.hxx>
#include <svx/grafctrl.hxx>
#include "sdattr.hxx"
#ifndef _SVX_XFTSTIT_HXX //autogen
#include <svx/xftstit.hxx>
#endif
#ifndef _SVX_XLNWTIT_HXX //autogen
#include <svx/xlnwtit.hxx>
#endif
#ifndef _SVX_XLINEIT0_HXX //autogen
#include <svx/xlineit0.hxx>
#endif
#ifndef _SVX_XLNCLIT_HXX //autogen
#include <svx/xlnclit.hxx>
#endif
#ifndef _SVX_XLNDSIT_HXX //autogen
#include <svx/xlndsit.hxx>
#endif
#ifndef _SVX_XFLCLIT_HXX //autogen
#include <svx/xflclit.hxx>
#endif
#ifndef SVX_XFILLIT0_HXX //autogen
#include <svx/xfillit0.hxx>
#endif
#ifndef _SVX_XLNEDIT_HXX //autogen
#include <svx/xlnedit.hxx>
#endif
#ifndef _SVX_XLNSTIT_HXX //autogen
#include <svx/xlnstit.hxx>
#endif
#ifndef _SVX__XGRADIENT_HXX //autogen
#include <svx/xgrad.hxx>
#endif
#ifndef _SVX_XFLGRIT_HXX //autogen
#include <svx/xflgrit.hxx>
#endif
#ifndef _SVX_XFLHTIT_HXX //autogen
#include <svx/xflhtit.hxx>
#endif
#ifndef _SVX_XBTMPIT_HXX //autogen
#include <svx/xbtmpit.hxx>
#endif
#ifndef _SVX_TEXTIT0_HXX //autogen
#include <svx/xtextit0.hxx>
#endif
#ifndef _SVX_XFTADIT_HXX //autogen
#include <svx/xftadit.hxx>
#endif
#ifndef _SVX_XFTDIIT_HXX //autogen
#include <svx/xftdiit.hxx>
#endif
#ifndef _SVX_XFTMRIT_HXX //autogen
#include <svx/xftmrit.hxx>
#endif
#ifndef _SVX_XFTOUIT_HXX //autogen
#include <svx/xftouit.hxx>
#endif
#ifndef _SVX_XFTSHIT_HXX //autogen
#include <svx/xftshit.hxx>
#endif
#ifndef _SVX_XFTSHCLIT_HXX //autogen
#include <svx/xftshcit.hxx>
#endif
#ifndef _SVX_XFTSHXY_HXX //autogen
#include <svx/xftshxy.hxx>
#endif
#ifndef _SVX_XFTSFIT_HXX //autogen
#include <svx/xftsfit.hxx>
#endif
#ifndef _SVX_TEXTIT0_HXX //autogen
#include <svx/xtextit0.hxx>
#endif
#ifndef _AVMEDIA_MEDIAITEM_HXX
#include <avmedia/mediaitem.hxx>
#endif
#ifndef _SVX_DRAWITEM_HXX
#include <svx/drawitem.hxx>
#endif
// #UndoRedo#
#ifndef _SFXSLSTITM_HXX
#include <svtools/slstitm.hxx>
#endif
#include <svtools/lckbitem.hxx>
#define CharSetItem SfxUInt16Item
#define FontFamilyItem SfxUInt16Item
#define FontPitchItem SfxUInt16Item
#define FontAlignItem SfxUInt16Item
#define FontWeightItem SfxUInt16Item
#define FontUnderlineItem SfxUInt16Item
#define FontStrikeoutItem SfxUInt16Item
#define FontItalicItem SfxUInt16Item
#define SvxDbTypeItem SfxUInt16Item
#define SvxLineSpaceItem SfxUInt16Item
#define SvxInterLineSpaceItem SfxUInt16Item
#define SvxBreakItem SfxUInt16Item
#define BrushStyleItem SfxUInt16Item
#define SvxNumTypeItem SfxUInt16Item
#define SvxShadowLocationItem SfxUInt16Item
#define SvxDbTypeItem SfxUInt16Item
//#define SvxChooseControlEnumItem SfxUInt16Item
#define SvxDrawToolEnumItem SfxUInt16Item
#define SvxChooseControlItem SfxEnumItem
#define SvxDrawToolItem SfxUInt16Item
#define SvxCellHorJustifyEnumItem SfxUInt16Item
#define SvxCellVerJustifyEnumItem SfxUInt16Item
#define SvxCellOrientationEnumItem SfxUInt16Item
#define SvxLanguage SfxUInt16Item
//#define SfxLockBytesItem SfxPoolItem
#define OfaStringListItem SfxStringListItem
#define avmedia_MediaItem ::avmedia::MediaItem
#ifndef _SFX_TPLPITEM_HXX //autogen
#include <sfx2/tplpitem.hxx>
#endif
#ifndef _SFXPTITEM_HXX //autogen
#include <svtools/ptitem.hxx>
#endif
#ifndef _SFXRECTITEM_HXX //autogen
#include <svtools/rectitem.hxx>
#endif
#include <sfx2/frame.hxx>
#define SFX_TYPEMAP
#include "sdslots.hxx"
<|endoftext|> |
<commit_before>/*
* main.cpp
* Copyright (C) 2017 Pi-Yueh Chuang <pychuang@gwu.edu>
*
* Distributed under terms of the MIT license.
*/
# include <string>
# include <fstream>
# include <sstream>
# include <petscsys.h>
# include <yaml-cpp/yaml.h>
# include <petibm/type.h>
# include <petibm/parser.h>
# include <petibm/mesh.h>
PetscErrorCode writeSingleXDMF(
const std::string &directory, const std::string &name,
const PetscInt &dim, const petibm::type::IntVec1D &n,
const PetscInt &bg, const PetscInt &ed, const PetscInt &step);
int main(int argc, char **argv)
{
PetscErrorCode ierr;
ierr = PetscInitialize(&argc, &argv, nullptr, nullptr); CHKERRQ(ierr);
YAML::Node setting;
ierr = petibm::parser::getSettings(setting); CHKERRQ(ierr);
petibm::type::Mesh mesh;
ierr = petibm::mesh::createMesh(PETSC_COMM_WORLD, setting, mesh); CHKERRQ(ierr);
PetscInt bg;
PetscInt ed;
PetscInt step;
PetscBool isSet;
// get the range of solutions that are going to be calculated
ierr = PetscOptionsGetInt(nullptr, nullptr, "-bg", &bg, &isSet); CHKERRQ(ierr);
if (! isSet) bg = setting["parameters"]["startStep"].as<PetscInt>();
ierr = PetscOptionsGetInt(nullptr, nullptr, "-ed", &ed, &isSet); CHKERRQ(ierr);
if (! isSet) ed = bg + setting["parameters"]["nt"].as<PetscInt>();
ierr = PetscOptionsGetInt(nullptr, nullptr, "-step", &step, &isSet); CHKERRQ(ierr);
if (! isSet) step = setting["parameters"]["nsave"].as<PetscInt>();
// u
ierr = writeSingleXDMF(setting["directory"].as<std::string>(),
"u", mesh->dim, mesh->n[0], bg, ed, step); CHKERRQ(ierr);
// v
ierr = writeSingleXDMF(setting["directory"].as<std::string>(),
"v", mesh->dim, mesh->n[1], bg, ed, step); CHKERRQ(ierr);
// p
ierr = writeSingleXDMF(setting["directory"].as<std::string>(),
"p", mesh->dim, mesh->n[3], bg, ed, step); CHKERRQ(ierr);
// wz
petibm::type::IntVec1D wn(3);
wn[0] = mesh->n[4][0]; wn[1] = mesh->n[4][1]; wn[2] = mesh->n[3][2];
ierr = writeSingleXDMF(setting["directory"].as<std::string>(),
"wz", mesh->dim, wn, bg, ed, step); CHKERRQ(ierr);
if (mesh->dim == 3)
{
// w
ierr = writeSingleXDMF(setting["directory"].as<std::string>(),
"w", mesh->dim, mesh->n[2], bg, ed, step); CHKERRQ(ierr);
// wx
wn[0] = mesh->n[3][0]; wn[1] = mesh->n[4][1]; wn[2] = mesh->n[4][2];
ierr = writeSingleXDMF(setting["directory"].as<std::string>(),
"wx", mesh->dim, wn, bg, ed, step); CHKERRQ(ierr);
// wy
wn[0] = mesh->n[4][0]; wn[1] = mesh->n[3][1]; wn[2] = mesh->n[4][2];
ierr = writeSingleXDMF(setting["directory"].as<std::string>(),
"wy", mesh->dim, wn, bg, ed, step); CHKERRQ(ierr);
}
ierr = PetscFinalize(); CHKERRQ(ierr);
return 0;
}
PetscErrorCode writeSingleXDMF(
const std::string &directory, const std::string &name,
const PetscInt &dim, const petibm::type::IntVec1D &n,
const PetscInt &bg, const PetscInt &ed, const PetscInt &step)
{
using namespace petibm;
PetscFunctionBeginUser;
PetscErrorCode ierr;
PetscViewer viewer;
std::string file = directory + "/" + name + ".xmf";
ierr = PetscViewerASCIIOpen(
PETSC_COMM_WORLD, file.c_str(), &viewer); CHKERRQ(ierr);
// write header
ierr = PetscViewerASCIIPrintf(viewer,
"<?xml version=\'1.0\' encoding=\'ASCII\'?>\n\n"); CHKERRQ(ierr);
// write macro definitions
ierr = PetscViewerASCIIPrintf(viewer,
"<!DOCTYPE Xdmf SYSTEM \"Xdmf.dtd\" [\n"); CHKERRQ(ierr);
ierr = PetscViewerASCIIPrintf(viewer,
" <!ENTITY CaseDir \"%s\">\n", directory.c_str()); CHKERRQ(ierr);
for(unsigned int i=0; i<dim; ++i)
{
ierr = PetscViewerASCIIPrintf(viewer, " <!ENTITY N%s \"%d\">\n",
type::dir2str[type::Dir(i)].c_str(), n[i]); CHKERRQ(ierr);
}
ierr = PetscViewerASCIIPrintf(viewer, "]>\n\n"); CHKERRQ(ierr);
// write Xdmf block
ierr = PetscViewerASCIIPrintf(viewer,
"<Xdmf Version=\"2.2\">\n"); CHKERRQ(ierr);
ierr = PetscViewerASCIIPrintf(viewer, " "
"<Information Name=\"MeteData\" Value=\"ID-23454\"/>\n"); CHKERRQ(ierr);
ierr = PetscViewerASCIIPrintf(viewer, " " "<Domain>\n\n"); CHKERRQ(ierr);
// write topology
ierr = PetscViewerASCIIPrintf(viewer, " "
"<Topology Name=\"%s Topo\" ", name.c_str()); CHKERRQ(ierr);
ierr = PetscViewerASCIIPrintf(viewer,
"TopologyType=\"%dDRectMesh\" ", (dim==3)?3:2); CHKERRQ(ierr);
ierr = PetscViewerASCIIPrintf(viewer,
"NumberOfElements=\"%s&Ny; &Nx;\"/>\n\n",
(dim==3)?"&Nz; ":""); CHKERRQ(ierr);
// write geometry
ierr = PetscViewerASCIIPrintf(viewer, " "
"<Geometry Name=\"%s Geo\" ", name.c_str()); CHKERRQ(ierr);
ierr = PetscViewerASCIIPrintf(viewer,
"GeometryType=\"VXVY%s\">\n", (dim==3)?"VZ":""); CHKERRQ(ierr);
for(unsigned int i=0; i<dim; ++i)
{
std::string dir = type::dir2str[type::Dir(i)];
ierr = PetscViewerASCIIPrintf(viewer, " " " "
"<DataItem Dimensions=\"&N%s;\" ", dir.c_str()); CHKERRQ(ierr);
ierr = PetscViewerASCIIPrintf(viewer,
"Format=\"HDF\" NumberType=\"Float\" Precision=\"8\">\n"); CHKERRQ(ierr);
ierr = PetscViewerASCIIPrintf(viewer, " " " " " "
"&CaseDir;/grid.h5:/%s/%s\n", name.c_str(), dir.c_str()); CHKERRQ(ierr);
ierr = PetscViewerASCIIPrintf(viewer, " " " "
"</DataItem>\n"); CHKERRQ(ierr);
}
ierr = PetscViewerASCIIPrintf(viewer, " " "</Geometry>\n\n"); CHKERRQ(ierr);
//write temporal grid collection
ierr = PetscViewerASCIIPrintf(viewer, " "
"<Grid GridType=\"Collection\" CollectionType=\"Temporal\">\n\n"); CHKERRQ(ierr);
// write each step
for(PetscInt t=bg; t<ed; t+=step)
{
ierr = PetscViewerASCIIPrintf(viewer, " " " "
"<Grid GridType=\"Uniform\" Name=\"%s Grid\">\n", name.c_str()); CHKERRQ(ierr);
ierr = PetscViewerASCIIPrintf(viewer, " " " " " "
"<Time Value=\"%07d\" />\n", t); CHKERRQ(ierr);
ierr = PetscViewerASCIIPrintf(viewer, " " " " " "
"<Topology Reference=\"/Xdmf/Domain/Topology"
"[@Name=\'%s Topo\']\" />\n", name.c_str()); CHKERRQ(ierr);
ierr = PetscViewerASCIIPrintf(viewer, " " " " " "
"<Geometry Reference=\"/Xdmf/Domain/Geometry"
"[@Name=\'%s Geo\']\" />\n", name.c_str()); CHKERRQ(ierr);
ierr = PetscViewerASCIIPrintf(viewer, " " " " " "
"<Attribute Name=\"%s\" AttributeType=\"Scalar\" Center=\"Node\">\n",
name.c_str()); CHKERRQ(ierr);
ierr = PetscViewerASCIIPrintf(viewer, " " " " " " " "
"<DataItem Dimensions=\"%s&Ny; &Nx;\" ",
(dim==3)?"&Nz; ":""); CHKERRQ(ierr);
ierr = PetscViewerASCIIPrintf(viewer,
"Format=\"HDF\" NumberType=\"Float\" Precision=\"8\">\n"); CHKERRQ(ierr);
ierr = PetscViewerASCIIPrintf(viewer, " " " " " " " " " "
"&CaseDir;/solution/%07d.h5:/%s\n", t, name.c_str()); CHKERRQ(ierr);
ierr = PetscViewerASCIIPrintf(viewer, " " " " " " " "
"</DataItem>\n"); CHKERRQ(ierr);
ierr = PetscViewerASCIIPrintf(viewer, " " " " " "
"</Attribute>\n"); CHKERRQ(ierr);
ierr = PetscViewerASCIIPrintf(viewer, " " " " "</Grid>\n\n"); CHKERRQ(ierr);
}
ierr = PetscViewerASCIIPrintf(viewer, " "
"</Grid>\n\n"); CHKERRQ(ierr);
ierr = PetscViewerASCIIPrintf(viewer, " " "</Domain>\n"); CHKERRQ(ierr);
ierr = PetscViewerASCIIPrintf(viewer, "</Xdmf>\n"); CHKERRQ(ierr);
ierr = PetscViewerDestroy(&viewer); CHKERRQ(ierr);
PetscFunctionReturn(0);
}
<commit_msg>improvement in createxdmf<commit_after>/*
* main.cpp
* Copyright (C) 2017 Pi-Yueh Chuang <pychuang@gwu.edu>
*
* Distributed under terms of the MIT license.
*/
# include <string>
# include <fstream>
# include <sstream>
# include <petscsys.h>
# include <yaml-cpp/yaml.h>
# include <petibm/type.h>
# include <petibm/parser.h>
# include <petibm/mesh.h>
PetscErrorCode writeSingleXDMF(
const std::string &directory, const std::string &name,
const PetscInt &dim, const petibm::type::IntVec1D &n,
const PetscInt &bg, const PetscInt &ed, const PetscInt &step);
int main(int argc, char **argv)
{
PetscErrorCode ierr;
ierr = PetscInitialize(&argc, &argv, nullptr, nullptr); CHKERRQ(ierr);
YAML::Node setting;
ierr = petibm::parser::getSettings(setting); CHKERRQ(ierr);
petibm::type::Mesh mesh;
ierr = petibm::mesh::createMesh(PETSC_COMM_WORLD, setting, mesh); CHKERRQ(ierr);
PetscInt bg;
PetscInt ed;
PetscInt step;
PetscBool isSet;
// get the range of solutions that are going to be calculated
ierr = PetscOptionsGetInt(nullptr, nullptr, "-bg", &bg, &isSet); CHKERRQ(ierr);
if (! isSet) bg = setting["parameters"]["startStep"].as<PetscInt>();
ierr = PetscOptionsGetInt(nullptr, nullptr, "-ed", &ed, &isSet); CHKERRQ(ierr);
if (! isSet) ed = bg + setting["parameters"]["nt"].as<PetscInt>();
ierr = PetscOptionsGetInt(nullptr, nullptr, "-step", &step, &isSet); CHKERRQ(ierr);
if (! isSet) step = setting["parameters"]["nsave"].as<PetscInt>();
// u
ierr = writeSingleXDMF(setting["directory"].as<std::string>(),
"u", mesh->dim, mesh->n[0], bg, ed, step); CHKERRQ(ierr);
// v
ierr = writeSingleXDMF(setting["directory"].as<std::string>(),
"v", mesh->dim, mesh->n[1], bg, ed, step); CHKERRQ(ierr);
// p
ierr = writeSingleXDMF(setting["directory"].as<std::string>(),
"p", mesh->dim, mesh->n[3], bg, ed, step); CHKERRQ(ierr);
// wz
petibm::type::IntVec1D wn(3);
wn[0] = mesh->n[4][0]; wn[1] = mesh->n[4][1]; wn[2] = mesh->n[3][2];
ierr = writeSingleXDMF(setting["directory"].as<std::string>(),
"wz", mesh->dim, wn, bg, ed, step); CHKERRQ(ierr);
if (mesh->dim == 3)
{
// w
ierr = writeSingleXDMF(setting["directory"].as<std::string>(),
"w", mesh->dim, mesh->n[2], bg, ed, step); CHKERRQ(ierr);
// wx
wn[0] = mesh->n[3][0]; wn[1] = mesh->n[4][1]; wn[2] = mesh->n[4][2];
ierr = writeSingleXDMF(setting["directory"].as<std::string>(),
"wx", mesh->dim, wn, bg, ed, step); CHKERRQ(ierr);
// wy
wn[0] = mesh->n[4][0]; wn[1] = mesh->n[3][1]; wn[2] = mesh->n[4][2];
ierr = writeSingleXDMF(setting["directory"].as<std::string>(),
"wy", mesh->dim, wn, bg, ed, step); CHKERRQ(ierr);
}
ierr = PetscFinalize(); CHKERRQ(ierr);
return 0;
}
PetscErrorCode writeSingleXDMF(
const std::string &directory, const std::string &name,
const PetscInt &dim, const petibm::type::IntVec1D &n,
const PetscInt &bg, const PetscInt &ed, const PetscInt &step)
{
using namespace petibm;
PetscFunctionBeginUser;
PetscErrorCode ierr;
PetscViewer viewer;
std::string file = directory + "/" + name + ".xmf";
ierr = PetscViewerASCIIOpen(
PETSC_COMM_WORLD, file.c_str(), &viewer); CHKERRQ(ierr);
// write header
ierr = PetscViewerASCIIPrintf(viewer,
"<?xml version=\'1.0\' encoding=\'ASCII\'?>\n\n"); CHKERRQ(ierr);
// write macro definitions
ierr = PetscViewerASCIIPrintf(viewer,
"<!DOCTYPE Xdmf SYSTEM \"Xdmf.dtd\" [\n"); CHKERRQ(ierr);
ierr = PetscViewerASCIIPrintf(viewer,
" <!ENTITY CaseDir \"%s\">\n", "./"); CHKERRQ(ierr);
for(unsigned int i=0; i<dim; ++i)
{
ierr = PetscViewerASCIIPrintf(viewer, " <!ENTITY N%s \"%d\">\n",
type::dir2str[type::Dir(i)].c_str(), n[i]); CHKERRQ(ierr);
}
ierr = PetscViewerASCIIPrintf(viewer, "]>\n\n"); CHKERRQ(ierr);
// write Xdmf block
ierr = PetscViewerASCIIPrintf(viewer,
"<Xdmf Version=\"2.2\">\n"); CHKERRQ(ierr);
ierr = PetscViewerASCIIPrintf(viewer, " "
"<Information Name=\"MeteData\" Value=\"ID-23454\"/>\n"); CHKERRQ(ierr);
ierr = PetscViewerASCIIPrintf(viewer, " " "<Domain>\n\n"); CHKERRQ(ierr);
// write topology
ierr = PetscViewerASCIIPrintf(viewer, " "
"<Topology Name=\"%s Topo\" ", name.c_str()); CHKERRQ(ierr);
ierr = PetscViewerASCIIPrintf(viewer,
"TopologyType=\"%dDRectMesh\" ", (dim==3)?3:2); CHKERRQ(ierr);
ierr = PetscViewerASCIIPrintf(viewer,
"NumberOfElements=\"%s&Ny; &Nx;\"/>\n\n",
(dim==3)?"&Nz; ":""); CHKERRQ(ierr);
// write geometry
ierr = PetscViewerASCIIPrintf(viewer, " "
"<Geometry Name=\"%s Geo\" ", name.c_str()); CHKERRQ(ierr);
ierr = PetscViewerASCIIPrintf(viewer,
"GeometryType=\"VXVY%s\">\n", (dim==3)?"VZ":""); CHKERRQ(ierr);
for(unsigned int i=0; i<dim; ++i)
{
std::string dir = type::dir2str[type::Dir(i)];
ierr = PetscViewerASCIIPrintf(viewer, " " " "
"<DataItem Dimensions=\"&N%s;\" ", dir.c_str()); CHKERRQ(ierr);
ierr = PetscViewerASCIIPrintf(viewer,
"Format=\"HDF\" NumberType=\"Float\" Precision=\"8\">\n"); CHKERRQ(ierr);
ierr = PetscViewerASCIIPrintf(viewer, " " " " " "
"&CaseDir;/grid.h5:/%s/%s\n", name.c_str(), dir.c_str()); CHKERRQ(ierr);
ierr = PetscViewerASCIIPrintf(viewer, " " " "
"</DataItem>\n"); CHKERRQ(ierr);
}
ierr = PetscViewerASCIIPrintf(viewer, " " "</Geometry>\n\n"); CHKERRQ(ierr);
//write temporal grid collection
ierr = PetscViewerASCIIPrintf(viewer, " "
"<Grid GridType=\"Collection\" CollectionType=\"Temporal\">\n\n"); CHKERRQ(ierr);
// write each step
for(PetscInt t=bg; t<=ed; t+=step)
{
ierr = PetscViewerASCIIPrintf(viewer, " " " "
"<Grid GridType=\"Uniform\" Name=\"%s Grid\">\n", name.c_str()); CHKERRQ(ierr);
ierr = PetscViewerASCIIPrintf(viewer, " " " " " "
"<Time Value=\"%07d\" />\n", t); CHKERRQ(ierr);
ierr = PetscViewerASCIIPrintf(viewer, " " " " " "
"<Topology Reference=\"/Xdmf/Domain/Topology"
"[@Name=\'%s Topo\']\" />\n", name.c_str()); CHKERRQ(ierr);
ierr = PetscViewerASCIIPrintf(viewer, " " " " " "
"<Geometry Reference=\"/Xdmf/Domain/Geometry"
"[@Name=\'%s Geo\']\" />\n", name.c_str()); CHKERRQ(ierr);
ierr = PetscViewerASCIIPrintf(viewer, " " " " " "
"<Attribute Name=\"%s\" AttributeType=\"Scalar\" Center=\"Node\">\n",
name.c_str()); CHKERRQ(ierr);
ierr = PetscViewerASCIIPrintf(viewer, " " " " " " " "
"<DataItem Dimensions=\"%s&Ny; &Nx;\" ",
(dim==3)?"&Nz; ":""); CHKERRQ(ierr);
ierr = PetscViewerASCIIPrintf(viewer,
"Format=\"HDF\" NumberType=\"Float\" Precision=\"8\">\n"); CHKERRQ(ierr);
ierr = PetscViewerASCIIPrintf(viewer, " " " " " " " " " "
"&CaseDir;/solution/%07d.h5:/%s\n", t, name.c_str()); CHKERRQ(ierr);
ierr = PetscViewerASCIIPrintf(viewer, " " " " " " " "
"</DataItem>\n"); CHKERRQ(ierr);
ierr = PetscViewerASCIIPrintf(viewer, " " " " " "
"</Attribute>\n"); CHKERRQ(ierr);
ierr = PetscViewerASCIIPrintf(viewer, " " " " "</Grid>\n\n"); CHKERRQ(ierr);
}
ierr = PetscViewerASCIIPrintf(viewer, " "
"</Grid>\n\n"); CHKERRQ(ierr);
ierr = PetscViewerASCIIPrintf(viewer, " " "</Domain>\n"); CHKERRQ(ierr);
ierr = PetscViewerASCIIPrintf(viewer, "</Xdmf>\n"); CHKERRQ(ierr);
ierr = PetscViewerDestroy(&viewer); CHKERRQ(ierr);
PetscFunctionReturn(0);
}
<|endoftext|> |
<commit_before>#include "Halide.h"
using namespace Halide;
using namespace Halide::ConciseCasts;
int main(int argc, char **argv) {
Target target = get_target_from_environment();
std::cout << "Target: " << target.to_string() << "\n";
// We take two 8 bit matrices as input.
Var x("x"), y("y");
ImageParam A(UInt(8), 2);
ImageParam B(UInt(8), 2);
// Align the extent of the K dimension to the product of our split
// factors.
const int k_split_factor = 32;
Expr k_extent = A.dim(0).extent();
k_extent = (k_extent/(k_split_factor*4))*(k_split_factor*4);
A.dim(0).set_extent(k_extent);
B.dim(1).set_extent(k_extent);
// We split directly in the algorithm by a factor of 4, so we can
// generate vrmpy instructions on Hexagon.
RDom rk(0, k_extent/4, "k");
// Define the reordering of B as a separate stage so we can lift
// the interleaving required by vrmpy out of the inner loop.
Func B_swizzled("B_swizzled");
Var k("k");
B_swizzled(x, y, k) = B(x, 4*y + k);
Func AB("AB");
AB(x, y) = u32(0);
AB(x, y) +=
u32(u16(A(4*rk + 0, y))*u16(B_swizzled(x, rk, 0))) +
u32(u16(A(4*rk + 1, y))*u16(B_swizzled(x, rk, 1))) +
u32(u16(A(4*rk + 2, y))*u16(B_swizzled(x, rk, 2))) +
u32(u16(A(4*rk + 3, y))*u16(B_swizzled(x, rk, 3)));
// We need a wrapper for the output so we can schedule the
// multiply update in tiles.
Func output;
output(x, y) = AB(x, y);
// Schedule.
int vector_size_u8 = target.natural_vector_size<uint8_t>();
bool use_hexagon = false;
if (target.has_feature(Target::HVX_64)) {
vector_size_u8 = 64;
use_hexagon = true;
} else if (target.has_feature(Target::HVX_128)) {
vector_size_u8 = 128;
use_hexagon = true;
}
int vector_size_u32 = vector_size_u8 / 4;
if (use_hexagon) {
Var xo("xo"), yo("yo");
// Split the output into tiles, traversed in columns of tiles
// that we parallelize over.
output.compute_root()
.hexagon()
.tile(x, y, xo, yo, x, y, vector_size_u8, 4, TailStrategy::RoundUp)
.reorder(yo, xo)
.vectorize(x)
.unroll(y)
.parallel(xo);
// Compute the product at tiles of the output.
AB.compute_at(output, yo)
.vectorize(x)
.unroll(y);
AB.update(0)
.reorder(x, y, rk)
.vectorize(x)
.unroll(y);
// Lift the swizzling out of the inner loop.
B_swizzled.compute_at(output, xo)
.reorder_storage(k, x, y)
.reorder(k, x, y)
.vectorize(x, vector_size_u8, TailStrategy::RoundUp)
.unroll(k);
} else {
Var xi("xi"), xii("xii"), yi("yi"), yii("yii");
RVar rki("rki");
// This schedule taken from test/performance/matrix_multiplication.cpp
constexpr int kBlockSize = 32;
const int kBlockSizeXi = 8;
output.compute_root()
.tile(x, y, x, y, xi, yi, vector_size_u8, 4, TailStrategy::RoundUp)
.reorder(xi, yi, x, y)
.vectorize(xi)
.unroll(yi)
.parallel(y);
AB.compute_root()
.vectorize(x, vector_size_u32);
AB.update(0)
.split(x, x, xi, kBlockSize, TailStrategy::GuardWithIf)
.split(xi, xi, xii, kBlockSizeXi, TailStrategy::GuardWithIf)
.split(y, y, yi, kBlockSize, TailStrategy::GuardWithIf)
.split(yi, yi, yii, 4, TailStrategy::GuardWithIf)
.split(rk, rk, rki, kBlockSize, TailStrategy::GuardWithIf)
.reorder(xii, yii, xi, rki, yi, rk, x, y)
.parallel(y)
.vectorize(xii)
.unroll(xi)
.unroll(yii);
}
// Require scanlines of the input and output to be aligned, and
// tell Halide about our dimension convention.
for (auto i : {(OutputImageParam)A, (OutputImageParam)B, output.output_buffer()}) {
int align = vector_size_u8/i.type().bytes();
i.dim(0)
.set_bounds(0, (i.dim(0).extent()/align)*align);
i.dim(1)
.set_bounds(0, (i.dim(1).extent()/align)*align)
.set_stride((i.dim(1).stride()/align)*align);
}
std::stringstream hdr;
hdr << argv[2] << ".h";
output.compile_to_header(hdr.str(), {A, B}, argv[2], target);
std::stringstream obj;
obj << argv[1] << ".o";
output.compile_to_object(obj.str(), {A, B}, argv[2], target);
return 0;
}
<commit_msg>Require less alignment on the k dimension.<commit_after>#include "Halide.h"
using namespace Halide;
using namespace Halide::ConciseCasts;
int main(int argc, char **argv) {
Target target = get_target_from_environment();
std::cout << "Target: " << target.to_string() << "\n";
// We take two 8 bit matrices as input.
Var x("x"), y("y");
ImageParam A(UInt(8), 2);
ImageParam B(UInt(8), 2);
// Align the extent of the K dimension to the product of our split
// factors.
const int k_unroll_factor = 2;
Expr k_extent = A.dim(0).extent();
k_extent = (k_extent/(k_unroll_factor*4))*(k_unroll_factor*4);
A.dim(0).set_extent(k_extent);
B.dim(1).set_extent(k_extent);
// We split directly in the algorithm by a factor of 4, so we can
// generate vrmpy instructions on Hexagon.
RDom rk(0, k_extent/4, "k");
// Define the reordering of B as a separate stage so we can lift
// the interleaving required by vrmpy out of the inner loop.
Func B_swizzled("B_swizzled");
Var k("k");
B_swizzled(x, y, k) = B(x, 4*y + k);
Func AB("AB");
AB(x, y) = u32(0);
AB(x, y) +=
u32(u16(A(4*rk + 0, y))*u16(B_swizzled(x, rk, 0))) +
u32(u16(A(4*rk + 1, y))*u16(B_swizzled(x, rk, 1))) +
u32(u16(A(4*rk + 2, y))*u16(B_swizzled(x, rk, 2))) +
u32(u16(A(4*rk + 3, y))*u16(B_swizzled(x, rk, 3)));
// We need a wrapper for the output so we can schedule the
// multiply update in tiles.
Func output;
output(x, y) = AB(x, y);
// Schedule.
int vector_size_u8 = target.natural_vector_size<uint8_t>();
bool use_hexagon = false;
if (target.has_feature(Target::HVX_64)) {
vector_size_u8 = 64;
use_hexagon = true;
} else if (target.has_feature(Target::HVX_128)) {
vector_size_u8 = 128;
use_hexagon = true;
}
int vector_size_u32 = vector_size_u8 / 4;
if (use_hexagon) {
Var xo("xo"), yo("yo");
// Split the output into tiles, traversed in columns of tiles
// that we parallelize over.
output.compute_root()
.hexagon()
.tile(x, y, xo, yo, x, y, vector_size_u8, 4, TailStrategy::RoundUp)
.reorder(yo, xo)
.vectorize(x)
.unroll(y)
.parallel(xo);
// Compute the product at tiles of the output.
AB.compute_at(output, yo)
.vectorize(x)
.unroll(y);
AB.update(0)
.reorder(x, y, rk)
.vectorize(x)
.unroll(y)
.unroll(rk, k_unroll_factor);
// Lift the swizzling out of the inner loop.
B_swizzled.compute_at(output, xo)
.reorder_storage(k, x, y)
.reorder(k, x, y)
.vectorize(x, vector_size_u8, TailStrategy::RoundUp)
.unroll(k);
} else {
Var xi("xi"), xii("xii"), yi("yi"), yii("yii");
RVar rki("rki");
// This schedule taken from test/performance/matrix_multiplication.cpp
constexpr int kBlockSize = 32;
const int kBlockSizeXi = 8;
output.compute_root()
.tile(x, y, x, y, xi, yi, vector_size_u8, 4, TailStrategy::RoundUp)
.reorder(xi, yi, x, y)
.vectorize(xi)
.unroll(yi)
.parallel(y);
AB.compute_root()
.vectorize(x, vector_size_u32);
AB.update(0)
.split(x, x, xi, kBlockSize, TailStrategy::GuardWithIf)
.split(xi, xi, xii, kBlockSizeXi, TailStrategy::GuardWithIf)
.split(y, y, yi, kBlockSize, TailStrategy::GuardWithIf)
.split(yi, yi, yii, 4, TailStrategy::GuardWithIf)
.split(rk, rk, rki, kBlockSize, TailStrategy::GuardWithIf)
.reorder(xii, yii, xi, rki, yi, rk, x, y)
.parallel(y)
.vectorize(xii)
.unroll(xi)
.unroll(yii);
}
// Require scanlines of the input and output to be aligned, and
// tell Halide about our dimension convention.
for (auto i : {(OutputImageParam)A, (OutputImageParam)B, output.output_buffer()}) {
int align = vector_size_u8/i.type().bytes();
i.dim(0)
.set_bounds(0, (i.dim(0).extent()/align)*align);
i.dim(1)
.set_bounds(0, (i.dim(1).extent()/align)*align)
.set_stride((i.dim(1).stride()/align)*align);
}
std::stringstream hdr;
hdr << argv[2] << ".h";
output.compile_to_header(hdr.str(), {A, B}, argv[2], target);
std::stringstream obj;
obj << argv[1] << ".o";
output.compile_to_object(obj.str(), {A, B}, argv[2], target);
return 0;
}
<|endoftext|> |
<commit_before>/*
Copyright (c) 2003, Arvid Norberg
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions
are met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in
the documentation and/or other materials provided with the distribution.
* Neither the name of the author nor the names of its
contributors may be used to endorse or promote products derived
from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
POSSIBILITY OF SUCH DAMAGE.
*/
#include <iostream>
#include <fstream>
#include <iterator>
#include <iomanip>
#include "libtorrent/entry.hpp"
#include "libtorrent/bencode.hpp"
#include "libtorrent/torrent_info.hpp"
#include "libtorrent/lazy_entry.hpp"
#include "libtorrent/magnet_uri.hpp"
#include <boost/filesystem/operations.hpp>
int main(int argc, char* argv[])
{
using namespace libtorrent;
using namespace boost::filesystem;
if (argc != 2)
{
std::cerr << "usage: dump_torrent torrent-file\n";
return 1;
}
#if BOOST_VERSION < 103400
boost::filesystem::path::default_name_check(boost::filesystem::no_check);
#endif
int size = file_size(argv[1]);
if (size > 10 * 1000000)
{
std::cerr << "file too big (" << size << "), aborting\n";
return 1;
}
std::vector<char> buf(size);
std::ifstream(argv[1], std::ios_base::binary).read(&buf[0], size);
lazy_entry e;
int ret = lazy_bdecode(&buf[0], &buf[0] + buf.size(), e);
if (ret != 0)
{
std::cerr << "invalid bencoding: " << ret << std::endl;
return 1;
}
std::cout << "\n\n----- raw info -----\n\n";
std::cout << print_entry(e) << std::endl;
error_code ec;
torrent_info t(e, ec);
if (ec)
{
std::cout << ec.message() << std::endl;
return 1;
}
// print info about torrent
std::cout << "\n\n----- torrent file info -----\n\n";
std::cout << "nodes:\n";
typedef std::vector<std::pair<std::string, int> > node_vec;
node_vec const& nodes = t.nodes();
for (node_vec::const_iterator i = nodes.begin(), end(nodes.end());
i != end; ++i)
{
std::cout << i->first << ":" << i->second << "\n";
}
std::cout << "trackers:\n";
for (std::vector<announce_entry>::const_iterator i = t.trackers().begin();
i != t.trackers().end(); ++i)
{
std::cout << i->tier << ": " << i->url << "\n";
}
std::cout << "number of pieces: " << t.num_pieces() << "\n";
std::cout << "piece length: " << t.piece_length() << "\n";
char ih[41];
to_hex((char const*)&t.info_hash()[0], 20, ih);
std::cout << "info hash: " << ih << "\n";
std::cout << "comment: " << t.comment() << "\n";
std::cout << "created by: " << t.creator() << "\n";
std::cout << "magnet link: " << make_magnet_uri(t) << "\n";
std::cout << "name: " << t.name() << "\n";
std::cout << "files:\n";
int index = 0;
for (torrent_info::file_iterator i = t.begin_files();
i != t.end_files(); ++i, ++index)
{
int first = t.map_file(index, 0, 1).piece;
int last = t.map_file(index, i->size - 1, 1).piece;
std::cout << " " << std::setw(11) << i->size
<< " "
<< (i->pad_file?'p':'-')
<< (i->executable_attribute?'x':'-')
<< (i->hidden_attribute?'h':'-')
<< (i->symlink_attribute?'l':'-')
<< " "
<< "[ " << std::setw(3) << first << ", " << std::setw(3) << last << " ]\t"
<< i->path.string() ;
if (i->symlink_attribute)
std::cout << " -> " << i->symlink_path.string();
std::cout << std::endl;
}
return 0;
}
<commit_msg>fixed bug in dump_torrent when the last file was 0-sized<commit_after>/*
Copyright (c) 2003, Arvid Norberg
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions
are met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in
the documentation and/or other materials provided with the distribution.
* Neither the name of the author nor the names of its
contributors may be used to endorse or promote products derived
from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
POSSIBILITY OF SUCH DAMAGE.
*/
#include <iostream>
#include <fstream>
#include <iterator>
#include <iomanip>
#include "libtorrent/entry.hpp"
#include "libtorrent/bencode.hpp"
#include "libtorrent/torrent_info.hpp"
#include "libtorrent/lazy_entry.hpp"
#include "libtorrent/magnet_uri.hpp"
#include <boost/filesystem/operations.hpp>
int main(int argc, char* argv[])
{
using namespace libtorrent;
using namespace boost::filesystem;
if (argc != 2)
{
std::cerr << "usage: dump_torrent torrent-file\n";
return 1;
}
#if BOOST_VERSION < 103400
boost::filesystem::path::default_name_check(boost::filesystem::no_check);
#endif
int size = file_size(argv[1]);
if (size > 10 * 1000000)
{
std::cerr << "file too big (" << size << "), aborting\n";
return 1;
}
std::vector<char> buf(size);
std::ifstream(argv[1], std::ios_base::binary).read(&buf[0], size);
lazy_entry e;
int ret = lazy_bdecode(&buf[0], &buf[0] + buf.size(), e);
if (ret != 0)
{
std::cerr << "invalid bencoding: " << ret << std::endl;
return 1;
}
std::cout << "\n\n----- raw info -----\n\n";
std::cout << print_entry(e) << std::endl;
error_code ec;
torrent_info t(e, ec);
if (ec)
{
std::cout << ec.message() << std::endl;
return 1;
}
// print info about torrent
std::cout << "\n\n----- torrent file info -----\n\n";
std::cout << "nodes:\n";
typedef std::vector<std::pair<std::string, int> > node_vec;
node_vec const& nodes = t.nodes();
for (node_vec::const_iterator i = nodes.begin(), end(nodes.end());
i != end; ++i)
{
std::cout << i->first << ":" << i->second << "\n";
}
std::cout << "trackers:\n";
for (std::vector<announce_entry>::const_iterator i = t.trackers().begin();
i != t.trackers().end(); ++i)
{
std::cout << i->tier << ": " << i->url << "\n";
}
std::cout << "number of pieces: " << t.num_pieces() << "\n";
std::cout << "piece length: " << t.piece_length() << "\n";
char ih[41];
to_hex((char const*)&t.info_hash()[0], 20, ih);
std::cout << "info hash: " << ih << "\n";
std::cout << "comment: " << t.comment() << "\n";
std::cout << "created by: " << t.creator() << "\n";
std::cout << "magnet link: " << make_magnet_uri(t) << "\n";
std::cout << "name: " << t.name() << "\n";
std::cout << "files:\n";
int index = 0;
for (torrent_info::file_iterator i = t.begin_files();
i != t.end_files(); ++i, ++index)
{
int first = t.map_file(index, 0, 0).piece;
int last = t.map_file(index, (std::max)(i->size-1, size_type(0)), 0).piece;
std::cout << " " << std::setw(11) << i->size
<< " "
<< (i->pad_file?'p':'-')
<< (i->executable_attribute?'x':'-')
<< (i->hidden_attribute?'h':'-')
<< (i->symlink_attribute?'l':'-')
<< " "
<< "[ " << std::setw(4) << first << ", " << std::setw(4) << last << " ]\t"
<< i->path.string() ;
if (i->symlink_attribute)
std::cout << " -> " << i->symlink_path.string();
std::cout << std::endl;
}
return 0;
}
<|endoftext|> |
<commit_before>// Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "content/public/common/sandbox_init.h"
#if defined(OS_LINUX) && defined(__x86_64__)
#include <asm/unistd.h>
#include <errno.h>
#include <linux/audit.h>
#include <linux/filter.h>
#include <signal.h>
#include <string.h>
#include <sys/prctl.h>
#include <ucontext.h>
#include <unistd.h>
#include <vector>
#include "base/command_line.h"
#include "base/file_util.h"
#include "base/logging.h"
#include "base/time.h"
#include "content/public/common/content_switches.h"
#ifndef PR_SET_NO_NEW_PRIVS
#define PR_SET_NO_NEW_PRIVS 38
#endif
#ifndef SYS_SECCOMP
#define SYS_SECCOMP 1
#endif
#ifndef __NR_eventfd2
#define __NR_eventfd2 290
#endif
// Constants from very new header files that we can't yet include.
#ifndef SECCOMP_MODE_FILTER
#define SECCOMP_MODE_FILTER 2
#define SECCOMP_RET_KILL 0x00000000U
#define SECCOMP_RET_TRAP 0x00030000U
#define SECCOMP_RET_ERRNO 0x00050000U
#define SECCOMP_RET_ALLOW 0x7fff0000U
#endif
namespace {
static void CheckSingleThreaded() {
// Possibly racy, but it's ok because this is more of a debug check to catch
// new threaded situations arising during development.
// It also has to be a DCHECK() because production builds will be running
// the suid sandbox, which will prevent /proc access in some contexts.
DCHECK_EQ(file_util::CountFilesCreatedAfter(FilePath("/proc/self/task"),
base::Time::UnixEpoch()),
1);
}
static void SIGSYS_Handler(int signal, siginfo_t* info, void* void_context) {
if (signal != SIGSYS)
return;
if (info->si_code != SYS_SECCOMP)
return;
if (!void_context)
return;
ucontext_t* context = reinterpret_cast<ucontext_t*>(void_context);
unsigned int syscall = context->uc_mcontext.gregs[REG_RAX];
if (syscall >= 1024)
syscall = 0;
// Purposefully dereference the syscall as an address so it'll show up very
// clearly and easily in crash dumps.
volatile char* addr = reinterpret_cast<volatile char*>(syscall);
*addr = '\0';
_exit(1);
}
static void InstallSIGSYSHandler() {
struct sigaction sa;
memset(&sa, 0, sizeof(sa));
sa.sa_flags = SA_SIGINFO;
sa.sa_sigaction = SIGSYS_Handler;
int ret = sigaction(SIGSYS, &sa, NULL);
PLOG_IF(FATAL, ret != 0) << "Failed to install SIGSYS handler.";
}
static void EmitLoad(int offset, std::vector<struct sock_filter>* program) {
struct sock_filter filter;
filter.code = BPF_LD+BPF_W+BPF_ABS;
filter.jt = 0;
filter.jf = 0;
filter.k = offset;
program->push_back(filter);
}
static void EmitJEQJT1(int value, std::vector<struct sock_filter>* program) {
struct sock_filter filter;
filter.code = BPF_JMP+BPF_JEQ+BPF_K;
filter.jt = 1;
filter.jf = 0;
filter.k = value;
program->push_back(filter);
}
static void EmitJEQJF1(int value, std::vector<struct sock_filter>* program) {
struct sock_filter filter;
filter.code = BPF_JMP+BPF_JEQ+BPF_K;
filter.jt = 0;
filter.jf = 1;
filter.k = value;
program->push_back(filter);
}
static void EmitRet(int value, std::vector<struct sock_filter>* program) {
struct sock_filter filter;
filter.code = BPF_RET+BPF_K;
filter.jt = 0;
filter.jf = 0;
filter.k = value;
program->push_back(filter);
}
static void EmitPreamble(std::vector<struct sock_filter>* program) {
// First, check correct syscall arch.
// "4" is magic offset for the arch number.
EmitLoad(4, program);
EmitJEQJT1(AUDIT_ARCH_X86_64, program);
EmitRet(SECCOMP_RET_KILL, program);
// Load the syscall number.
// "0" is magic offset for the syscall number.
EmitLoad(0, program);
}
static void EmitAllowSyscall(int nr, std::vector<struct sock_filter>* program) {
EmitJEQJF1(nr, program);
EmitRet(SECCOMP_RET_ALLOW, program);
}
static void EmitFailSyscall(int nr, int err,
std::vector<struct sock_filter>* program) {
EmitJEQJF1(nr, program);
EmitRet(SECCOMP_RET_ERRNO | err, program);
}
static void EmitTrap(std::vector<struct sock_filter>* program) {
EmitRet(SECCOMP_RET_TRAP, program);
}
static void ApplyGPUPolicy(std::vector<struct sock_filter>* program) {
// "Hot" syscalls go first.
EmitAllowSyscall(__NR_read, program);
EmitAllowSyscall(__NR_ioctl, program);
EmitAllowSyscall(__NR_poll, program);
EmitAllowSyscall(__NR_epoll_wait, program);
EmitAllowSyscall(__NR_recvfrom, program);
EmitAllowSyscall(__NR_write, program);
EmitAllowSyscall(__NR_writev, program);
EmitAllowSyscall(__NR_gettid, program);
// Less hot syscalls.
EmitAllowSyscall(__NR_futex, program);
EmitAllowSyscall(__NR_madvise, program);
EmitAllowSyscall(__NR_sendmsg, program);
EmitAllowSyscall(__NR_recvmsg, program);
EmitAllowSyscall(__NR_eventfd2, program);
EmitAllowSyscall(__NR_pipe, program);
EmitAllowSyscall(__NR_mmap, program);
EmitAllowSyscall(__NR_mprotect, program);
EmitAllowSyscall(__NR_clone, program);
EmitAllowSyscall(__NR_set_robust_list, program);
EmitAllowSyscall(__NR_getuid, program);
EmitAllowSyscall(__NR_geteuid, program);
EmitAllowSyscall(__NR_getgid, program);
EmitAllowSyscall(__NR_getegid, program);
EmitAllowSyscall(__NR_epoll_create, program);
EmitAllowSyscall(__NR_fcntl, program);
EmitAllowSyscall(__NR_socketpair, program);
EmitAllowSyscall(__NR_epoll_ctl, program);
EmitAllowSyscall(__NR_prctl, program);
EmitAllowSyscall(__NR_fstat, program);
EmitAllowSyscall(__NR_close, program);
EmitAllowSyscall(__NR_restart_syscall, program);
EmitAllowSyscall(__NR_rt_sigreturn, program);
EmitAllowSyscall(__NR_brk, program);
EmitAllowSyscall(__NR_rt_sigprocmask, program);
EmitAllowSyscall(__NR_munmap, program);
EmitAllowSyscall(__NR_dup, program);
EmitAllowSyscall(__NR_mlock, program);
EmitAllowSyscall(__NR_munlock, program);
EmitAllowSyscall(__NR_exit, program);
EmitAllowSyscall(__NR_exit_group, program);
EmitFailSyscall(__NR_open, ENOENT, program);
EmitFailSyscall(__NR_access, ENOENT, program);
}
static void ApplyFlashPolicy(std::vector<struct sock_filter>* program) {
// "Hot" syscalls go first.
EmitAllowSyscall(__NR_futex, program);
EmitAllowSyscall(__NR_write, program);
EmitAllowSyscall(__NR_epoll_wait, program);
EmitAllowSyscall(__NR_read, program);
EmitAllowSyscall(__NR_times, program);
// Less hot syscalls.
EmitAllowSyscall(__NR_clone, program);
EmitAllowSyscall(__NR_set_robust_list, program);
EmitAllowSyscall(__NR_getuid, program);
EmitAllowSyscall(__NR_geteuid, program);
EmitAllowSyscall(__NR_getgid, program);
EmitAllowSyscall(__NR_getegid, program);
EmitAllowSyscall(__NR_epoll_create, program);
EmitAllowSyscall(__NR_fcntl, program);
EmitAllowSyscall(__NR_socketpair, program);
EmitAllowSyscall(__NR_pipe, program);
EmitAllowSyscall(__NR_epoll_ctl, program);
EmitAllowSyscall(__NR_gettid, program);
EmitAllowSyscall(__NR_prctl, program);
EmitAllowSyscall(__NR_fstat, program);
EmitAllowSyscall(__NR_sendmsg, program);
EmitAllowSyscall(__NR_mmap, program);
EmitAllowSyscall(__NR_munmap, program);
EmitAllowSyscall(__NR_mprotect, program);
EmitAllowSyscall(__NR_madvise, program);
EmitAllowSyscall(__NR_rt_sigaction, program);
EmitAllowSyscall(__NR_rt_sigprocmask, program);
EmitAllowSyscall(__NR_wait4, program);
EmitAllowSyscall(__NR_exit_group, program);
EmitAllowSyscall(__NR_exit, program);
EmitAllowSyscall(__NR_rt_sigreturn, program);
EmitAllowSyscall(__NR_restart_syscall, program);
EmitAllowSyscall(__NR_close, program);
EmitAllowSyscall(__NR_recvmsg, program);
EmitAllowSyscall(__NR_lseek, program);
EmitAllowSyscall(__NR_brk, program);
EmitAllowSyscall(__NR_sched_yield, program);
// These are under investigation, and hopefully not here for the long term.
EmitAllowSyscall(__NR_shmctl, program);
EmitAllowSyscall(__NR_shmat, program);
EmitAllowSyscall(__NR_shmdt, program);
EmitFailSyscall(__NR_open, ENOENT, program);
EmitFailSyscall(__NR_execve, ENOENT, program);
EmitFailSyscall(__NR_access, ENOENT, program);
}
static bool CanUseSeccompFilters() {
int ret = prctl(PR_SET_SECCOMP, SECCOMP_MODE_FILTER, 0, 0, 0);
if (ret != 0 && errno == EFAULT)
return true;
return false;
}
static void InstallFilter(const std::vector<struct sock_filter>& program) {
int ret = prctl(PR_SET_NO_NEW_PRIVS, 1, 0, 0, 0);
PLOG_IF(FATAL, ret != 0) << "prctl(PR_SET_NO_NEW_PRIVS) failed";
struct sock_fprog fprog;
fprog.len = program.size();
fprog.filter = const_cast<struct sock_filter*>(&program[0]);
ret = prctl(PR_SET_SECCOMP, SECCOMP_MODE_FILTER, &fprog, 0, 0);
PLOG_IF(FATAL, ret != 0) << "Failed to install filter.";
}
} // anonymous namespace
namespace content {
void InitializeSandbox() {
const CommandLine& command_line = *CommandLine::ForCurrentProcess();
if (command_line.HasSwitch(switches::kNoSandbox) ||
command_line.HasSwitch(switches::kDisableSeccompFilterSandbox))
return;
std::string process_type =
command_line.GetSwitchValueASCII(switches::kProcessType);
if (process_type == switches::kGpuProcess &&
command_line.HasSwitch(switches::kDisableGpuSandbox))
return;
if (!CanUseSeccompFilters())
return;
CheckSingleThreaded();
std::vector<struct sock_filter> program;
EmitPreamble(&program);
if (process_type == switches::kGpuProcess) {
ApplyGPUPolicy(&program);
} else if (process_type == switches::kPpapiPluginProcess) {
ApplyFlashPolicy(&program);
} else {
NOTREACHED();
}
EmitTrap(&program);
InstallSIGSYSHandler();
InstallFilter(program);
}
} // namespace content
#else
namespace content {
void InitializeSandbox() {
}
} // namespace content
#endif
<commit_msg>Handle three syscalls seen so far in crash logs.<commit_after>// Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "content/public/common/sandbox_init.h"
#if defined(OS_LINUX) && defined(__x86_64__)
#include <asm/unistd.h>
#include <errno.h>
#include <linux/audit.h>
#include <linux/filter.h>
#include <signal.h>
#include <string.h>
#include <sys/prctl.h>
#include <ucontext.h>
#include <unistd.h>
#include <vector>
#include "base/command_line.h"
#include "base/file_util.h"
#include "base/logging.h"
#include "base/time.h"
#include "content/public/common/content_switches.h"
#ifndef PR_SET_NO_NEW_PRIVS
#define PR_SET_NO_NEW_PRIVS 38
#endif
#ifndef SYS_SECCOMP
#define SYS_SECCOMP 1
#endif
#ifndef __NR_eventfd2
#define __NR_eventfd2 290
#endif
// Constants from very new header files that we can't yet include.
#ifndef SECCOMP_MODE_FILTER
#define SECCOMP_MODE_FILTER 2
#define SECCOMP_RET_KILL 0x00000000U
#define SECCOMP_RET_TRAP 0x00030000U
#define SECCOMP_RET_ERRNO 0x00050000U
#define SECCOMP_RET_ALLOW 0x7fff0000U
#endif
namespace {
static void CheckSingleThreaded() {
// Possibly racy, but it's ok because this is more of a debug check to catch
// new threaded situations arising during development.
// It also has to be a DCHECK() because production builds will be running
// the suid sandbox, which will prevent /proc access in some contexts.
DCHECK_EQ(file_util::CountFilesCreatedAfter(FilePath("/proc/self/task"),
base::Time::UnixEpoch()),
1);
}
static void SIGSYS_Handler(int signal, siginfo_t* info, void* void_context) {
if (signal != SIGSYS)
return;
if (info->si_code != SYS_SECCOMP)
return;
if (!void_context)
return;
ucontext_t* context = reinterpret_cast<ucontext_t*>(void_context);
uintptr_t syscall = context->uc_mcontext.gregs[REG_RAX];
if (syscall >= 1024)
syscall = 0;
// Encode 8-bits of the 1st two arguments too, so we can discern which socket
// type, which fcntl, ... etc., without being likely to hit a mapped
// address.
// Do not encode more bits here without thinking about increasing the
// likelihood of collision with mapped pages.
syscall |= ((context->uc_mcontext.gregs[REG_RDI] & 0xffUL) << 12);
syscall |= ((context->uc_mcontext.gregs[REG_RSI] & 0xffUL) << 20);
// Purposefully dereference the syscall as an address so it'll show up very
// clearly and easily in crash dumps.
volatile char* addr = reinterpret_cast<volatile char*>(syscall);
*addr = '\0';
// In case we hit a mapped address, hit the null page with just the syscall,
// for paranoia.
syscall &= 0xfffUL;
addr = reinterpret_cast<volatile char*>(syscall);
*addr = '\0';
_exit(1);
}
static void InstallSIGSYSHandler() {
struct sigaction sa;
memset(&sa, 0, sizeof(sa));
sa.sa_flags = SA_SIGINFO;
sa.sa_sigaction = SIGSYS_Handler;
int ret = sigaction(SIGSYS, &sa, NULL);
PLOG_IF(FATAL, ret != 0) << "Failed to install SIGSYS handler.";
}
static void EmitLoad(int offset, std::vector<struct sock_filter>* program) {
struct sock_filter filter;
filter.code = BPF_LD+BPF_W+BPF_ABS;
filter.jt = 0;
filter.jf = 0;
filter.k = offset;
program->push_back(filter);
}
static void EmitJEQJT1(int value, std::vector<struct sock_filter>* program) {
struct sock_filter filter;
filter.code = BPF_JMP+BPF_JEQ+BPF_K;
filter.jt = 1;
filter.jf = 0;
filter.k = value;
program->push_back(filter);
}
static void EmitJEQJF1(int value, std::vector<struct sock_filter>* program) {
struct sock_filter filter;
filter.code = BPF_JMP+BPF_JEQ+BPF_K;
filter.jt = 0;
filter.jf = 1;
filter.k = value;
program->push_back(filter);
}
static void EmitRet(int value, std::vector<struct sock_filter>* program) {
struct sock_filter filter;
filter.code = BPF_RET+BPF_K;
filter.jt = 0;
filter.jf = 0;
filter.k = value;
program->push_back(filter);
}
static void EmitPreamble(std::vector<struct sock_filter>* program) {
// First, check correct syscall arch.
// "4" is magic offset for the arch number.
EmitLoad(4, program);
EmitJEQJT1(AUDIT_ARCH_X86_64, program);
EmitRet(SECCOMP_RET_KILL, program);
// Load the syscall number.
// "0" is magic offset for the syscall number.
EmitLoad(0, program);
}
static void EmitAllowSyscall(int nr, std::vector<struct sock_filter>* program) {
EmitJEQJF1(nr, program);
EmitRet(SECCOMP_RET_ALLOW, program);
}
static void EmitFailSyscall(int nr, int err,
std::vector<struct sock_filter>* program) {
EmitJEQJF1(nr, program);
EmitRet(SECCOMP_RET_ERRNO | err, program);
}
static void EmitTrap(std::vector<struct sock_filter>* program) {
EmitRet(SECCOMP_RET_TRAP, program);
}
static void ApplyGPUPolicy(std::vector<struct sock_filter>* program) {
// "Hot" syscalls go first.
EmitAllowSyscall(__NR_read, program);
EmitAllowSyscall(__NR_ioctl, program);
EmitAllowSyscall(__NR_poll, program);
EmitAllowSyscall(__NR_epoll_wait, program);
EmitAllowSyscall(__NR_recvfrom, program);
EmitAllowSyscall(__NR_write, program);
EmitAllowSyscall(__NR_writev, program);
EmitAllowSyscall(__NR_gettid, program);
// Less hot syscalls.
EmitAllowSyscall(__NR_futex, program);
EmitAllowSyscall(__NR_madvise, program);
EmitAllowSyscall(__NR_sendmsg, program);
EmitAllowSyscall(__NR_recvmsg, program);
EmitAllowSyscall(__NR_eventfd2, program);
EmitAllowSyscall(__NR_pipe, program);
EmitAllowSyscall(__NR_mmap, program);
EmitAllowSyscall(__NR_mprotect, program);
EmitAllowSyscall(__NR_clone, program);
EmitAllowSyscall(__NR_set_robust_list, program);
EmitAllowSyscall(__NR_getuid, program);
EmitAllowSyscall(__NR_geteuid, program);
EmitAllowSyscall(__NR_getgid, program);
EmitAllowSyscall(__NR_getegid, program);
EmitAllowSyscall(__NR_epoll_create, program);
EmitAllowSyscall(__NR_fcntl, program);
EmitAllowSyscall(__NR_socketpair, program);
EmitAllowSyscall(__NR_epoll_ctl, program);
EmitAllowSyscall(__NR_prctl, program);
EmitAllowSyscall(__NR_fstat, program);
EmitAllowSyscall(__NR_close, program);
EmitAllowSyscall(__NR_restart_syscall, program);
EmitAllowSyscall(__NR_rt_sigreturn, program);
EmitAllowSyscall(__NR_brk, program);
EmitAllowSyscall(__NR_rt_sigprocmask, program);
EmitAllowSyscall(__NR_munmap, program);
EmitAllowSyscall(__NR_dup, program);
EmitAllowSyscall(__NR_mlock, program);
EmitAllowSyscall(__NR_munlock, program);
EmitAllowSyscall(__NR_exit, program);
EmitAllowSyscall(__NR_exit_group, program);
EmitAllowSyscall(__NR_getpid, program);
EmitAllowSyscall(__NR_getppid, program);
EmitFailSyscall(__NR_open, ENOENT, program);
EmitFailSyscall(__NR_access, ENOENT, program);
}
static void ApplyFlashPolicy(std::vector<struct sock_filter>* program) {
// "Hot" syscalls go first.
EmitAllowSyscall(__NR_futex, program);
EmitAllowSyscall(__NR_write, program);
EmitAllowSyscall(__NR_epoll_wait, program);
EmitAllowSyscall(__NR_read, program);
EmitAllowSyscall(__NR_times, program);
// Less hot syscalls.
EmitAllowSyscall(__NR_clone, program);
EmitAllowSyscall(__NR_set_robust_list, program);
EmitAllowSyscall(__NR_getuid, program);
EmitAllowSyscall(__NR_geteuid, program);
EmitAllowSyscall(__NR_getgid, program);
EmitAllowSyscall(__NR_getegid, program);
EmitAllowSyscall(__NR_epoll_create, program);
EmitAllowSyscall(__NR_fcntl, program);
EmitAllowSyscall(__NR_socketpair, program);
EmitAllowSyscall(__NR_pipe, program);
EmitAllowSyscall(__NR_epoll_ctl, program);
EmitAllowSyscall(__NR_gettid, program);
EmitAllowSyscall(__NR_prctl, program);
EmitAllowSyscall(__NR_fstat, program);
EmitAllowSyscall(__NR_sendmsg, program);
EmitAllowSyscall(__NR_mmap, program);
EmitAllowSyscall(__NR_munmap, program);
EmitAllowSyscall(__NR_mprotect, program);
EmitAllowSyscall(__NR_madvise, program);
EmitAllowSyscall(__NR_rt_sigaction, program);
EmitAllowSyscall(__NR_rt_sigprocmask, program);
EmitAllowSyscall(__NR_wait4, program);
EmitAllowSyscall(__NR_exit_group, program);
EmitAllowSyscall(__NR_exit, program);
EmitAllowSyscall(__NR_rt_sigreturn, program);
EmitAllowSyscall(__NR_restart_syscall, program);
EmitAllowSyscall(__NR_close, program);
EmitAllowSyscall(__NR_recvmsg, program);
EmitAllowSyscall(__NR_lseek, program);
EmitAllowSyscall(__NR_brk, program);
EmitAllowSyscall(__NR_sched_yield, program);
// These are under investigation, and hopefully not here for the long term.
EmitAllowSyscall(__NR_shmctl, program);
EmitAllowSyscall(__NR_shmat, program);
EmitAllowSyscall(__NR_shmdt, program);
EmitFailSyscall(__NR_open, ENOENT, program);
EmitFailSyscall(__NR_execve, ENOENT, program);
EmitFailSyscall(__NR_access, ENOENT, program);
}
static bool CanUseSeccompFilters() {
int ret = prctl(PR_SET_SECCOMP, SECCOMP_MODE_FILTER, 0, 0, 0);
if (ret != 0 && errno == EFAULT)
return true;
return false;
}
static void InstallFilter(const std::vector<struct sock_filter>& program) {
int ret = prctl(PR_SET_NO_NEW_PRIVS, 1, 0, 0, 0);
PLOG_IF(FATAL, ret != 0) << "prctl(PR_SET_NO_NEW_PRIVS) failed";
struct sock_fprog fprog;
fprog.len = program.size();
fprog.filter = const_cast<struct sock_filter*>(&program[0]);
ret = prctl(PR_SET_SECCOMP, SECCOMP_MODE_FILTER, &fprog, 0, 0);
PLOG_IF(FATAL, ret != 0) << "Failed to install filter.";
}
} // anonymous namespace
namespace content {
void InitializeSandbox() {
const CommandLine& command_line = *CommandLine::ForCurrentProcess();
if (command_line.HasSwitch(switches::kNoSandbox) ||
command_line.HasSwitch(switches::kDisableSeccompFilterSandbox))
return;
std::string process_type =
command_line.GetSwitchValueASCII(switches::kProcessType);
if (process_type == switches::kGpuProcess &&
command_line.HasSwitch(switches::kDisableGpuSandbox))
return;
if (!CanUseSeccompFilters())
return;
CheckSingleThreaded();
std::vector<struct sock_filter> program;
EmitPreamble(&program);
if (process_type == switches::kGpuProcess) {
ApplyGPUPolicy(&program);
} else if (process_type == switches::kPpapiPluginProcess) {
ApplyFlashPolicy(&program);
} else {
NOTREACHED();
}
EmitTrap(&program);
InstallSIGSYSHandler();
InstallFilter(program);
}
} // namespace content
#else
namespace content {
void InitializeSandbox() {
}
} // namespace content
#endif
<|endoftext|> |
<commit_before>/* IBM_PROLOG_BEGIN_TAG */
/* This is an automatically generated prolog. */
/* */
/* $Source: src/usr/diag/prdf/common/plat/p9/prdfP9Ex.C $ */
/* */
/* OpenPOWER HostBoot Project */
/* */
/* Contributors Listed Below - COPYRIGHT 2016 */
/* [+] International Business Machines Corp. */
/* */
/* */
/* Licensed under the Apache License, Version 2.0 (the "License"); */
/* you may not use this file except in compliance with the License. */
/* You may obtain a copy of the License at */
/* */
/* http://www.apache.org/licenses/LICENSE-2.0 */
/* */
/* Unless required by applicable law or agreed to in writing, software */
/* distributed under the License is distributed on an "AS IS" BASIS, */
/* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or */
/* implied. See the License for the specific language governing */
/* permissions and limitations under the License. */
/* */
/* IBM_PROLOG_END_TAG */
// Framework includes
#include <prdfPluginDef.H>
#include <iipServiceDataCollector.h>
#include <prdfExtensibleChip.H>
#include <prdfPluginMap.H>
#include <prdfP9ExDataBundle.H>
#include <prdfP9ExExtraSig.H>
#include <prdfMfgThresholdMgr.H>
#include <prdfMfgThreshold.H>
namespace PRDF
{
namespace p9_ex
{
/**
* @brief Plugin that initializes the EX data bundle.
* @param i_exChip An ex chip.
* @return SUCCESS
*/
int32_t Initialize( ExtensibleChip * i_exChip )
{
i_exChip->getDataBundle() = new P9ExDataBundle( i_exChip );
return SUCCESS;
}
PRDF_PLUGIN_DEFINE( p9_ex, Initialize );
/**
* @brief Handle an L3 CE
* @param i_chip Ex chip.
* @param i_stepcode Step Code data struct
* @return PRD return code
*/
int32_t L3CE( ExtensibleChip * i_chip,
STEP_CODE_DATA_STRUCT & i_stepcode )
{
P9ExDataBundle * l_bundle = getExDataBundle(i_chip);
uint16_t l_maxL3LineDelAllowed = 0;
l_maxL3LineDelAllowed =
MfgThresholdMgr::getInstance()->getThreshold(PlatServices::mfgMode() ?
TARGETING::ATTR_MNFG_TH_P8EX_L3_LINE_DELETES:
TARGETING::ATTR_FIELD_TH_P8EX_L3_LINE_DELETES);
// MfgThresholdMgr treats 0 as a special value for infinite threshold
// For this threshold, we want 0 to really represent 0 repairs allowed
if (l_maxL3LineDelAllowed == MfgThreshold::INFINITE_LIMIT_THR)
l_maxL3LineDelAllowed = 0;
// Ensure we're still allowed to issue repairs
if ((l_bundle->iv_L3LDCount < l_maxL3LineDelAllowed) &&
(CHECK_STOP != i_stepcode.service_data->getPrimaryAttnType()))
{
// Add to CE table and Check if we need to issue a repair on this CE
bool l_doDelete =
l_bundle->iv_L3CETable->addAddress(l_bundle->iv_L3LDCount,
i_stepcode);
if (l_doDelete)
{
l_bundle->iv_L3LDCount++;
// Do Delete
PRDF_TRAC( "[L3CE] HUID: 0x%08x apply line delete",
i_chip->GetId());
SCAN_COMM_REGISTER_CLASS * prgReg =
i_chip->getRegister("L3_PURGE_REG");
prgReg->clearAllBits();
prgReg->SetBit(5);
if (SUCCESS != prgReg->Write() )
{
PRDF_ERR( "[L3CE] HUID: 0x%08x l3LineDelete failed",
i_chip->GetId());
// Set signature to indicate L3 Line Delete failed
i_stepcode.service_data->SetErrorSig(
PRDFSIG_P9EX_L3CE_LD_FAILURE);
}
else
{
// Set signature to indicate L3 Line Delete issued
i_stepcode.service_data->SetErrorSig(
PRDFSIG_P9EX_L3CE_LD_ISSUED);
}
}
}
else
{
PRDF_TRAC( "[L3CE] HUID: 0x%08x No more repairs allowed",
i_chip->GetId());
// MFG wants to be able to ignore these errors
// If they have LD and array repairs set to 0, wait for
// predictive threshold
if (!PlatServices::mfgMode() ||
l_maxL3LineDelAllowed != 0 )
{
i_stepcode.service_data->SetThresholdMaskId(0);
}
}
return SUCCESS;
} PRDF_PLUGIN_DEFINE(p9_ex, L3CE);
}
}
<commit_msg>PRD: Disable line deletes during IPL<commit_after>/* IBM_PROLOG_BEGIN_TAG */
/* This is an automatically generated prolog. */
/* */
/* $Source: src/usr/diag/prdf/common/plat/p9/prdfP9Ex.C $ */
/* */
/* OpenPOWER HostBoot Project */
/* */
/* Contributors Listed Below - COPYRIGHT 2016 */
/* [+] International Business Machines Corp. */
/* */
/* */
/* Licensed under the Apache License, Version 2.0 (the "License"); */
/* you may not use this file except in compliance with the License. */
/* You may obtain a copy of the License at */
/* */
/* http://www.apache.org/licenses/LICENSE-2.0 */
/* */
/* Unless required by applicable law or agreed to in writing, software */
/* distributed under the License is distributed on an "AS IS" BASIS, */
/* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or */
/* implied. See the License for the specific language governing */
/* permissions and limitations under the License. */
/* */
/* IBM_PROLOG_END_TAG */
// Framework includes
#include <prdfPluginDef.H>
#include <iipServiceDataCollector.h>
#include <prdfExtensibleChip.H>
#include <prdfPluginMap.H>
#include <prdfP9ExDataBundle.H>
#include <prdfP9ExExtraSig.H>
#include <prdfMfgThresholdMgr.H>
#include <prdfMfgThreshold.H>
namespace PRDF
{
namespace p9_ex
{
/**
* @brief Plugin that initializes the EX data bundle.
* @param i_exChip An ex chip.
* @return SUCCESS
*/
int32_t Initialize( ExtensibleChip * i_exChip )
{
i_exChip->getDataBundle() = new P9ExDataBundle( i_exChip );
return SUCCESS;
}
PRDF_PLUGIN_DEFINE( p9_ex, Initialize );
/**
* @brief Handle an L3 CE
* @param i_chip Ex chip.
* @param i_stepcode Step Code data struct
* @return PRD return code
*/
int32_t L3CE( ExtensibleChip * i_chip,
STEP_CODE_DATA_STRUCT & i_stepcode )
{
#if defined(__HOSTBOOT_RUNTIME) || defined(ESW_SIM_COMPILE)
P9ExDataBundle * l_bundle = getExDataBundle(i_chip);
uint16_t l_maxL3LineDelAllowed = 0;
l_maxL3LineDelAllowed =
MfgThresholdMgr::getInstance()->getThreshold(PlatServices::mfgMode() ?
TARGETING::ATTR_MNFG_TH_P8EX_L3_LINE_DELETES:
TARGETING::ATTR_FIELD_TH_P8EX_L3_LINE_DELETES);
// MfgThresholdMgr treats 0 as a special value for infinite threshold
// For this threshold, we want 0 to really represent 0 repairs allowed
if (l_maxL3LineDelAllowed == MfgThreshold::INFINITE_LIMIT_THR)
l_maxL3LineDelAllowed = 0;
// Ensure we're still allowed to issue repairs
if ((l_bundle->iv_L3LDCount < l_maxL3LineDelAllowed) &&
(CHECK_STOP != i_stepcode.service_data->getPrimaryAttnType()))
{
// Add to CE table and Check if we need to issue a repair on this CE
bool l_doDelete =
l_bundle->iv_L3CETable->addAddress(l_bundle->iv_L3LDCount,
i_stepcode);
if (l_doDelete)
{
l_bundle->iv_L3LDCount++;
// Do Delete
PRDF_TRAC( "[L3CE] HUID: 0x%08x apply line delete",
i_chip->GetId());
SCAN_COMM_REGISTER_CLASS * prgReg =
i_chip->getRegister("L3_PURGE_REG");
prgReg->clearAllBits();
prgReg->SetBit(5);
if (SUCCESS != prgReg->Write() )
{
PRDF_ERR( "[L3CE] HUID: 0x%08x l3LineDelete failed",
i_chip->GetId());
// Set signature to indicate L3 Line Delete failed
i_stepcode.service_data->SetErrorSig(
PRDFSIG_P9EX_L3CE_LD_FAILURE);
}
else
{
// Set signature to indicate L3 Line Delete issued
i_stepcode.service_data->SetErrorSig(
PRDFSIG_P9EX_L3CE_LD_ISSUED);
}
}
}
else
{
PRDF_TRAC( "[L3CE] HUID: 0x%08x No more repairs allowed",
i_chip->GetId());
// MFG wants to be able to ignore these errors
// If they have LD and array repairs set to 0, wait for
// predictive threshold
if (!PlatServices::mfgMode() ||
l_maxL3LineDelAllowed != 0 )
{
i_stepcode.service_data->SetThresholdMaskId(0);
}
}
#endif
return SUCCESS;
} PRDF_PLUGIN_DEFINE(p9_ex, L3CE);
}
}
<|endoftext|> |
<commit_before><commit_msg>[Tizen] Make content fit to the viewport<commit_after><|endoftext|> |
<commit_before>// Copyright (c) 2011 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "content/test/content_browser_test.h"
#include "base/command_line.h"
#include "base/debug/stack_trace.h"
#include "base/file_path.h"
#include "base/logging.h"
#include "base/message_loop.h"
#include "base/path_service.h"
#include "content/public/browser/render_process_host.h"
#include "content/public/common/content_switches.h"
#include "content/public/common/url_constants.h"
#include "content/shell/shell.h"
#include "content/shell/shell_browser_context.h"
#include "content/shell/shell_content_browser_client.h"
#include "content/shell/shell_main_delegate.h"
#include "content/shell/shell_switches.h"
#include "content/test/test_content_client.h"
#if defined(OS_MACOSX)
#include "base/mac/scoped_nsautorelease_pool.h"
#endif
namespace content {
ContentBrowserTest::ContentBrowserTest() {
#if defined(OS_MACOSX)
// See comment in InProcessBrowserTest::InProcessBrowserTest().
FilePath content_shell_path;
CHECK(PathService::Get(base::FILE_EXE, &content_shell_path));
content_shell_path = content_shell_path.DirName();
content_shell_path = content_shell_path.Append(
FILE_PATH_LITERAL("Content Shell.app/Contents/MacOS/Content Shell"));
CHECK(PathService::Override(base::FILE_EXE, content_shell_path));
#endif
CreateTestServer("content/test/data");
}
ContentBrowserTest::~ContentBrowserTest() {
}
void ContentBrowserTest::SetUp() {
shell_main_delegate_.reset(new ShellMainDelegate);
shell_main_delegate_->PreSandboxStartup();
CommandLine* command_line = CommandLine::ForCurrentProcess();
command_line->AppendSwitch(switches::kContentBrowserTest);
#if defined(OS_LINUX)
// http://crbug.com/139209
command_line->AppendSwitch(switches::kDisableGpuProcessPrelaunch);
#endif
SetUpCommandLine(command_line);
#if defined(OS_MACOSX)
// See InProcessBrowserTest::PrepareTestCommandLine().
FilePath subprocess_path;
PathService::Get(base::FILE_EXE, &subprocess_path);
subprocess_path = subprocess_path.DirName().DirName();
DCHECK_EQ(subprocess_path.BaseName().value(), "Contents");
subprocess_path = subprocess_path.Append(
"Frameworks/Content Shell Helper.app/Contents/MacOS/Content Shell Helper");
command_line->AppendSwitchPath(switches::kBrowserSubprocessPath,
subprocess_path);
#endif
BrowserTestBase::SetUp();
}
void ContentBrowserTest::TearDown() {
BrowserTestBase::TearDown();
shell_main_delegate_.reset();
}
#if defined(OS_POSIX)
// On SIGTERM (sent by the runner on timeouts), dump a stack trace (to make
// debugging easier) and also exit with a known error code (so that the test
// framework considers this a failure -- http://crbug.com/57578).
static void DumpStackTraceSignalHandler(int signal) {
base::debug::StackTrace().PrintBacktrace();
_exit(128 + signal);
}
#endif // defined(OS_POSIX)
void ContentBrowserTest::RunTestOnMainThreadLoop() {
CHECK_EQ(Shell::windows().size(), 1u);
shell_ = Shell::windows()[0];
#if defined(OS_POSIX)
signal(SIGTERM, DumpStackTraceSignalHandler);
#endif // defined(OS_POSIX)
#if defined(OS_MACOSX)
// On Mac, without the following autorelease pool, code which is directly
// executed (as opposed to executed inside a message loop) would autorelease
// objects into a higher-level pool. This pool is not recycled in-sync with
// the message loops' pools and causes problems with code relying on
// deallocation via an autorelease pool (such as browser window closure and
// browser shutdown). To avoid this, the following pool is recycled after each
// time code is directly executed.
base::mac::ScopedNSAutoreleasePool pool;
#endif
// Pump startup related events.
MessageLoopForUI::current()->RunAllPending();
#if defined(OS_MACOSX)
pool.Recycle();
#endif
SetUpOnMainThread();
RunTestOnMainThread();
#if defined(OS_MACOSX)
pool.Recycle();
#endif
Shell::CloseAllWindows();
}
Shell* ContentBrowserTest::CreateBrowser() {
ShellContentBrowserClient* browser_client =
static_cast<ShellContentBrowserClient*>(GetContentClient()->browser());
return Shell::CreateNewWindow(
browser_client->browser_context(),
GURL(chrome::kAboutBlankURL),
NULL,
MSG_ROUTING_NONE,
NULL);
}
Shell* ContentBrowserTest::CreateOffTheRecordBrowser() {
ShellContentBrowserClient* browser_client =
static_cast<ShellContentBrowserClient*>(GetContentClient()->browser());
return Shell::CreateNewWindow(
browser_client->off_the_record_browser_context(),
GURL(chrome::kAboutBlankURL),
NULL,
MSG_ROUTING_NONE,
NULL);
}
} // namespace content
<commit_msg>Add the RenderProcessHost::FastShutdownIfPossible calls to ContentBrowserTest that I removed in r148507. It looks like this may be preventing the browser from shutting down child processes. Review URL: https://chromiumcodereview.appspot.com/10833043<commit_after>// Copyright (c) 2011 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "content/test/content_browser_test.h"
#include "base/command_line.h"
#include "base/debug/stack_trace.h"
#include "base/file_path.h"
#include "base/logging.h"
#include "base/message_loop.h"
#include "base/path_service.h"
#include "content/public/browser/render_process_host.h"
#include "content/public/common/content_switches.h"
#include "content/public/common/url_constants.h"
#include "content/shell/shell.h"
#include "content/shell/shell_browser_context.h"
#include "content/shell/shell_content_browser_client.h"
#include "content/shell/shell_main_delegate.h"
#include "content/shell/shell_switches.h"
#include "content/test/test_content_client.h"
#if defined(OS_MACOSX)
#include "base/mac/scoped_nsautorelease_pool.h"
#endif
namespace content {
ContentBrowserTest::ContentBrowserTest() {
#if defined(OS_MACOSX)
// See comment in InProcessBrowserTest::InProcessBrowserTest().
FilePath content_shell_path;
CHECK(PathService::Get(base::FILE_EXE, &content_shell_path));
content_shell_path = content_shell_path.DirName();
content_shell_path = content_shell_path.Append(
FILE_PATH_LITERAL("Content Shell.app/Contents/MacOS/Content Shell"));
CHECK(PathService::Override(base::FILE_EXE, content_shell_path));
#endif
CreateTestServer("content/test/data");
}
ContentBrowserTest::~ContentBrowserTest() {
}
void ContentBrowserTest::SetUp() {
shell_main_delegate_.reset(new ShellMainDelegate);
shell_main_delegate_->PreSandboxStartup();
CommandLine* command_line = CommandLine::ForCurrentProcess();
command_line->AppendSwitch(switches::kContentBrowserTest);
#if defined(OS_LINUX)
// http://crbug.com/139209
command_line->AppendSwitch(switches::kDisableGpuProcessPrelaunch);
#endif
SetUpCommandLine(command_line);
#if defined(OS_MACOSX)
// See InProcessBrowserTest::PrepareTestCommandLine().
FilePath subprocess_path;
PathService::Get(base::FILE_EXE, &subprocess_path);
subprocess_path = subprocess_path.DirName().DirName();
DCHECK_EQ(subprocess_path.BaseName().value(), "Contents");
subprocess_path = subprocess_path.Append(
"Frameworks/Content Shell Helper.app/Contents/MacOS/Content Shell Helper");
command_line->AppendSwitchPath(switches::kBrowserSubprocessPath,
subprocess_path);
#endif
BrowserTestBase::SetUp();
}
void ContentBrowserTest::TearDown() {
BrowserTestBase::TearDown();
shell_main_delegate_.reset();
}
#if defined(OS_POSIX)
// On SIGTERM (sent by the runner on timeouts), dump a stack trace (to make
// debugging easier) and also exit with a known error code (so that the test
// framework considers this a failure -- http://crbug.com/57578).
static void DumpStackTraceSignalHandler(int signal) {
base::debug::StackTrace().PrintBacktrace();
_exit(128 + signal);
}
#endif // defined(OS_POSIX)
void ContentBrowserTest::RunTestOnMainThreadLoop() {
CHECK_EQ(Shell::windows().size(), 1u);
shell_ = Shell::windows()[0];
#if defined(OS_POSIX)
signal(SIGTERM, DumpStackTraceSignalHandler);
#endif // defined(OS_POSIX)
#if defined(OS_MACOSX)
// On Mac, without the following autorelease pool, code which is directly
// executed (as opposed to executed inside a message loop) would autorelease
// objects into a higher-level pool. This pool is not recycled in-sync with
// the message loops' pools and causes problems with code relying on
// deallocation via an autorelease pool (such as browser window closure and
// browser shutdown). To avoid this, the following pool is recycled after each
// time code is directly executed.
base::mac::ScopedNSAutoreleasePool pool;
#endif
// Pump startup related events.
MessageLoopForUI::current()->RunAllPending();
#if defined(OS_MACOSX)
pool.Recycle();
#endif
SetUpOnMainThread();
RunTestOnMainThread();
#if defined(OS_MACOSX)
pool.Recycle();
#endif
for (RenderProcessHost::iterator i(RenderProcessHost::AllHostsIterator());
!i.IsAtEnd(); i.Advance()) {
i.GetCurrentValue()->FastShutdownIfPossible();
}
Shell::CloseAllWindows();
}
Shell* ContentBrowserTest::CreateBrowser() {
ShellContentBrowserClient* browser_client =
static_cast<ShellContentBrowserClient*>(GetContentClient()->browser());
return Shell::CreateNewWindow(
browser_client->browser_context(),
GURL(chrome::kAboutBlankURL),
NULL,
MSG_ROUTING_NONE,
NULL);
}
Shell* ContentBrowserTest::CreateOffTheRecordBrowser() {
ShellContentBrowserClient* browser_client =
static_cast<ShellContentBrowserClient*>(GetContentClient()->browser());
return Shell::CreateNewWindow(
browser_client->off_the_record_browser_context(),
GURL(chrome::kAboutBlankURL),
NULL,
MSG_ROUTING_NONE,
NULL);
}
} // namespace content
<|endoftext|> |
<commit_before>/*
* Copyright (c) 2012 The WebRTC project authors. All Rights Reserved.
*
* Use of this source code is governed by a BSD-style license
* that can be found in the LICENSE file in the root of the source
* tree. An additional intellectual property rights grant can be found
* in the file PATENTS. All contributing project authors may
* be found in the AUTHORS file in the root of the source tree.
*/
#include "webrtc/system_wrappers/interface/condition_variable_wrapper.h"
#include "testing/gtest/include/gtest/gtest.h"
#include "webrtc/system_wrappers/interface/critical_section_wrapper.h"
#include "webrtc/system_wrappers/interface/thread_wrapper.h"
#include "webrtc/system_wrappers/interface/trace.h"
namespace webrtc {
namespace {
const int kLongWaitMs = 100 * 1000; // A long time in testing terms
const int kShortWaitMs = 2 * 1000; // Long enough for process switches to happen
// A Baton is one possible control structure one can build using
// conditional variables.
// A Baton is always held by one and only one active thread - unlike
// a lock, it can never be free.
// One can pass it or grab it - both calls have timeouts.
// Note - a production tool would guard against passing it without
// grabbing it first. This one is for testing, so it doesn't.
class Baton {
public:
Baton()
: giver_sect_(CriticalSectionWrapper::CreateCriticalSection()),
crit_sect_(CriticalSectionWrapper::CreateCriticalSection()),
cond_var_(ConditionVariableWrapper::CreateConditionVariable()),
being_passed_(false),
pass_count_(0) {
}
~Baton() {
delete giver_sect_;
delete crit_sect_;
delete cond_var_;
}
// Pass the baton. Returns false if baton is not picked up in |max_msecs|.
// Only one process can pass at the same time; this property is
// ensured by the |giver_sect_| lock.
bool Pass(uint32_t max_msecs) {
CriticalSectionScoped cs_giver(giver_sect_);
CriticalSectionScoped cs(crit_sect_);
SignalBatonAvailable();
const bool result = TakeBatonIfStillFree(max_msecs);
if (result) {
++pass_count_;
}
return result;
}
// Grab the baton. Returns false if baton is not passed.
bool Grab(uint32_t max_msecs) {
CriticalSectionScoped cs(crit_sect_);
return WaitUntilBatonOffered(max_msecs);
}
int PassCount() {
// We don't allow polling PassCount() during a Pass()-call since there is
// no guarantee that |pass_count_| is incremented until the Pass()-call
// finishes. I.e. the Grab()-call may finish before |pass_count_| has been
// incremented.
// Thus, this function waits on giver_sect_.
CriticalSectionScoped cs(giver_sect_);
return pass_count_;
}
private:
// Wait/Signal forms a classical semaphore on |being_passed_|.
// These functions must be called with crit_sect_ held.
bool WaitUntilBatonOffered(int timeout_ms) {
while (!being_passed_) {
if (!cond_var_->SleepCS(*crit_sect_, timeout_ms)) {
return false;
}
}
being_passed_ = false;
cond_var_->Wake();
return true;
}
void SignalBatonAvailable() {
assert(!being_passed_);
being_passed_ = true;
cond_var_->Wake();
}
// Timeout extension: Wait for a limited time for someone else to
// take it, and take it if it's not taken.
// Returns true if resource is taken by someone else, false
// if it is taken back by the caller.
// This function must be called with both |giver_sect_| and
// |crit_sect_| held.
bool TakeBatonIfStillFree(int timeout_ms) {
bool not_timeout = true;
while (being_passed_ && not_timeout) {
not_timeout = cond_var_->SleepCS(*crit_sect_, timeout_ms);
// If we're woken up while variable is still held, we may have
// gotten a wakeup destined for a grabber thread.
// This situation is not treated specially here.
}
if (!being_passed_) {
return true;
} else {
assert(!not_timeout);
being_passed_ = false;
return false;
}
}
// Lock that ensures that there is only one thread in the active
// part of Pass() at a time.
// |giver_sect_| must always be acquired before |cond_var_|.
CriticalSectionWrapper* giver_sect_;
// Lock that protects |being_passed_|.
CriticalSectionWrapper* crit_sect_;
ConditionVariableWrapper* cond_var_;
bool being_passed_;
// Statistics information: Number of successfull passes.
int pass_count_;
};
// Function that waits on a Baton, and passes it right back.
// We expect these calls never to time out.
bool WaitingRunFunction(void* obj) {
Baton* the_baton = static_cast<Baton*> (obj);
EXPECT_TRUE(the_baton->Grab(kLongWaitMs));
EXPECT_TRUE(the_baton->Pass(kLongWaitMs));
return true;
}
class CondVarTest : public ::testing::Test {
public:
CondVarTest() {}
virtual void SetUp() {
thread_ = ThreadWrapper::CreateThread(&WaitingRunFunction,
&baton_, "CondVarTest");
ASSERT_TRUE(thread_->Start());
}
virtual void TearDown() {
// We have to wake the thread in order to make it obey the stop order.
// But we don't know if the thread has completed the run function, so
// we don't know if it will exit before or after the Pass.
// Thus, we need to pin it down inside its Run function (between Grab
// and Pass).
ASSERT_TRUE(baton_.Pass(kShortWaitMs));
ASSERT_TRUE(baton_.Grab(kShortWaitMs));
ASSERT_TRUE(thread_->Stop());
}
protected:
Baton baton_;
private:
rtc::scoped_ptr<ThreadWrapper> thread_;
};
// The SetUp and TearDown functions use condition variables.
// This test verifies those pieces in isolation.
// Disabled due to flakiness. See bug 4262 for details.
TEST_F(CondVarTest, DISABLED_InitFunctionsWork) {
// All relevant asserts are in the SetUp and TearDown functions.
}
// This test verifies that one can use the baton multiple times.
TEST_F(CondVarTest, DISABLED_PassBatonMultipleTimes) {
const int kNumberOfRounds = 2;
for (int i = 0; i < kNumberOfRounds; ++i) {
ASSERT_TRUE(baton_.Pass(kShortWaitMs));
ASSERT_TRUE(baton_.Grab(kShortWaitMs));
}
EXPECT_EQ(2 * kNumberOfRounds, baton_.PassCount());
}
} // anonymous namespace
} // namespace webrtc
<commit_msg>Testing that waiting for a condition variable waits.<commit_after>/*
* Copyright (c) 2012 The WebRTC project authors. All Rights Reserved.
*
* Use of this source code is governed by a BSD-style license
* that can be found in the LICENSE file in the root of the source
* tree. An additional intellectual property rights grant can be found
* in the file PATENTS. All contributing project authors may
* be found in the AUTHORS file in the root of the source tree.
*/
#include "webrtc/system_wrappers/interface/condition_variable_wrapper.h"
#include "testing/gtest/include/gtest/gtest.h"
#include "webrtc/base/scoped_ptr.h"
#include "webrtc/system_wrappers/interface/critical_section_wrapper.h"
#include "webrtc/system_wrappers/interface/thread_wrapper.h"
#include "webrtc/system_wrappers/interface/tick_util.h"
#include "webrtc/system_wrappers/interface/trace.h"
namespace webrtc {
namespace {
const int kLongWaitMs = 100 * 1000; // A long time in testing terms
const int kShortWaitMs = 2 * 1000; // Long enough for process switches to happen
const int kVeryShortWaitMs = 20; // Used when we want a timeout
// A Baton is one possible control structure one can build using
// conditional variables.
// A Baton is always held by one and only one active thread - unlike
// a lock, it can never be free.
// One can pass it or grab it - both calls have timeouts.
// Note - a production tool would guard against passing it without
// grabbing it first. This one is for testing, so it doesn't.
class Baton {
public:
Baton()
: giver_sect_(CriticalSectionWrapper::CreateCriticalSection()),
crit_sect_(CriticalSectionWrapper::CreateCriticalSection()),
cond_var_(ConditionVariableWrapper::CreateConditionVariable()),
being_passed_(false),
pass_count_(0) {
}
~Baton() {
delete giver_sect_;
delete crit_sect_;
delete cond_var_;
}
// Pass the baton. Returns false if baton is not picked up in |max_msecs|.
// Only one process can pass at the same time; this property is
// ensured by the |giver_sect_| lock.
bool Pass(uint32_t max_msecs) {
CriticalSectionScoped cs_giver(giver_sect_);
CriticalSectionScoped cs(crit_sect_);
SignalBatonAvailable();
const bool result = TakeBatonIfStillFree(max_msecs);
if (result) {
++pass_count_;
}
return result;
}
// Grab the baton. Returns false if baton is not passed.
bool Grab(uint32_t max_msecs) {
CriticalSectionScoped cs(crit_sect_);
return WaitUntilBatonOffered(max_msecs);
}
int PassCount() {
// We don't allow polling PassCount() during a Pass()-call since there is
// no guarantee that |pass_count_| is incremented until the Pass()-call
// finishes. I.e. the Grab()-call may finish before |pass_count_| has been
// incremented.
// Thus, this function waits on giver_sect_.
CriticalSectionScoped cs(giver_sect_);
return pass_count_;
}
private:
// Wait/Signal forms a classical semaphore on |being_passed_|.
// These functions must be called with crit_sect_ held.
bool WaitUntilBatonOffered(int timeout_ms) {
while (!being_passed_) {
if (!cond_var_->SleepCS(*crit_sect_, timeout_ms)) {
return false;
}
}
being_passed_ = false;
cond_var_->Wake();
return true;
}
void SignalBatonAvailable() {
assert(!being_passed_);
being_passed_ = true;
cond_var_->Wake();
}
// Timeout extension: Wait for a limited time for someone else to
// take it, and take it if it's not taken.
// Returns true if resource is taken by someone else, false
// if it is taken back by the caller.
// This function must be called with both |giver_sect_| and
// |crit_sect_| held.
bool TakeBatonIfStillFree(int timeout_ms) {
bool not_timeout = true;
while (being_passed_ && not_timeout) {
not_timeout = cond_var_->SleepCS(*crit_sect_, timeout_ms);
// If we're woken up while variable is still held, we may have
// gotten a wakeup destined for a grabber thread.
// This situation is not treated specially here.
}
if (!being_passed_) {
return true;
} else {
assert(!not_timeout);
being_passed_ = false;
return false;
}
}
// Lock that ensures that there is only one thread in the active
// part of Pass() at a time.
// |giver_sect_| must always be acquired before |cond_var_|.
CriticalSectionWrapper* giver_sect_;
// Lock that protects |being_passed_|.
CriticalSectionWrapper* crit_sect_;
ConditionVariableWrapper* cond_var_;
bool being_passed_;
// Statistics information: Number of successfull passes.
int pass_count_;
};
// Function that waits on a Baton, and passes it right back.
// We expect these calls never to time out.
bool WaitingRunFunction(void* obj) {
Baton* the_baton = static_cast<Baton*> (obj);
EXPECT_TRUE(the_baton->Grab(kLongWaitMs));
EXPECT_TRUE(the_baton->Pass(kLongWaitMs));
return true;
}
class CondVarTest : public ::testing::Test {
public:
CondVarTest() {}
virtual void SetUp() {
thread_ = ThreadWrapper::CreateThread(&WaitingRunFunction,
&baton_, "CondVarTest");
ASSERT_TRUE(thread_->Start());
}
virtual void TearDown() {
// We have to wake the thread in order to make it obey the stop order.
// But we don't know if the thread has completed the run function, so
// we don't know if it will exit before or after the Pass.
// Thus, we need to pin it down inside its Run function (between Grab
// and Pass).
ASSERT_TRUE(baton_.Pass(kShortWaitMs));
ASSERT_TRUE(baton_.Grab(kShortWaitMs));
ASSERT_TRUE(thread_->Stop());
}
protected:
Baton baton_;
private:
rtc::scoped_ptr<ThreadWrapper> thread_;
};
// The SetUp and TearDown functions use condition variables.
// This test verifies those pieces in isolation.
// Disabled due to flakiness. See bug 4262 for details.
TEST_F(CondVarTest, DISABLED_InitFunctionsWork) {
// All relevant asserts are in the SetUp and TearDown functions.
}
// This test verifies that one can use the baton multiple times.
TEST_F(CondVarTest, DISABLED_PassBatonMultipleTimes) {
const int kNumberOfRounds = 2;
for (int i = 0; i < kNumberOfRounds; ++i) {
ASSERT_TRUE(baton_.Pass(kShortWaitMs));
ASSERT_TRUE(baton_.Grab(kShortWaitMs));
}
EXPECT_EQ(2 * kNumberOfRounds, baton_.PassCount());
}
TEST(CondVarWaitTest, WaitingWaits) {
rtc::scoped_ptr<CriticalSectionWrapper> crit_sect(
CriticalSectionWrapper::CreateCriticalSection());
rtc::scoped_ptr<ConditionVariableWrapper> cond_var(
ConditionVariableWrapper::CreateConditionVariable());
CriticalSectionScoped cs(crit_sect.get());
int64_t start_ms = TickTime::MillisecondTimestamp();
EXPECT_FALSE(cond_var->SleepCS(*(crit_sect), kVeryShortWaitMs));
int64_t end_ms = TickTime::MillisecondTimestamp();
EXPECT_LE(start_ms + kVeryShortWaitMs, end_ms)
<< "actual elapsed:" << end_ms - start_ms;
}
} // anonymous namespace
} // namespace webrtc
<|endoftext|> |
<commit_before>/*******************************************************************************
Licensed to the OpenCOR team under one or more contributor license agreements.
See the NOTICE.txt file distributed with this work for additional information
regarding copyright ownership. The OpenCOR team 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.
*******************************************************************************/
//==============================================================================
// CVODE solver class
//==============================================================================
#include "cvodesolver.h"
//==============================================================================
#include "cvode/cvode.h"
#include "cvode/cvode_dense.h"
//==============================================================================
namespace OpenCOR {
namespace CVODESolver {
//==============================================================================
int rhsFunction(double pVoi, N_Vector pStates, N_Vector pRates, void *pUserData)
{
// Compute the RHS function
CvodeSolverUserData *userData = static_cast<CvodeSolverUserData *>(pUserData);
userData->computeRates()(pVoi, userData->constants(),
N_VGetArrayPointer_Serial(pRates),
N_VGetArrayPointer_Serial(pStates),
userData->algebraic());
return 0;
}
//==============================================================================
void errorHandler(int pErrorCode, const char *pModule, const char *pFunction,
char *pErrorMessage, void *pUserData)
{
Q_UNUSED(pModule);
Q_UNUSED(pFunction);
if (pErrorCode != CV_WARNING)
// CVODE generated an error, so forward it to the CvodeSolver object
reinterpret_cast<CvodeSolver *>(pUserData)->emitError(pErrorMessage);
}
//==============================================================================
CvodeSolverUserData::CvodeSolverUserData(double *pConstants, double *pAlgebraic,
CoreSolver::CoreOdeSolver::ComputeRatesFunction pComputeRates) :
mConstants(pConstants),
mAlgebraic(pAlgebraic),
mComputeRates(pComputeRates)
{
}
//==============================================================================
double * CvodeSolverUserData::constants() const
{
// Return our constants array
return mConstants;
}
//==============================================================================
double * CvodeSolverUserData::algebraic() const
{
// Return our algebraic array
return mAlgebraic;
}
//==============================================================================
CoreSolver::CoreOdeSolver::ComputeRatesFunction CvodeSolverUserData::computeRates() const
{
// Return our compute rates function
return mComputeRates;
}
//==============================================================================
CvodeSolver::CvodeSolver() :
mSolver(0),
mStatesVector(0),
mUserData(0),
mInterpolateSolution(InterpolateSolutionDefaultValue)
{
}
//==============================================================================
CvodeSolver::~CvodeSolver()
{
// Make sure that the solver has been initialised
if (!mSolver)
return;
// Delete some internal objects
N_VDestroy_Serial(mStatesVector);
CVodeFree(&mSolver);
delete mUserData;
}
//==============================================================================
void CvodeSolver::initialize(const double &pVoiStart,
const int &pRatesStatesCount, double *pConstants,
double *pRates, double *pStates,
double *pAlgebraic,
ComputeRatesFunction pComputeRates)
{
if (!mSolver) {
// Retrieve some of the CVODE properties
double maximumStep;
int maximumNumberOfSteps;
QString integrationMethod;
QString iteratorType;
double relativeTolerance;
double absoluteTolerance;
if (mProperties.contains(MaximumStepId)) {
maximumStep = mProperties.value(MaximumStepId).toDouble();
} else {
emit error(QObject::tr("the 'maximum step' property value could not be retrieved"));
return;
}
if (mProperties.contains(MaximumNumberOfStepsId)) {
maximumNumberOfSteps = mProperties.value(MaximumNumberOfStepsId).toInt();
} else {
emit error(QObject::tr("the 'maximum number of steps' property value could not be retrieved"));
return;
}
if (mProperties.contains(IntegrationMethodId)) {
integrationMethod = mProperties.value(IntegrationMethodId).toString();
} else {
emit error(QObject::tr("the 'integration method' property value could not be retrieved"));
return;
}
if (mProperties.contains(IteratorTypeId)) {
iteratorType = mProperties.value(IteratorTypeId).toString();
} else {
emit error(QObject::tr("the 'iterator type' property value could not be retrieved"));
return;
}
if (mProperties.contains(RelativeToleranceId)) {
relativeTolerance = mProperties.value(RelativeToleranceId).toDouble();
} else {
emit error(QObject::tr("the 'relative tolerance' property value could not be retrieved"));
return;
}
if (mProperties.contains(AbsoluteToleranceId)) {
absoluteTolerance = mProperties.value(AbsoluteToleranceId).toDouble();
} else {
emit error(QObject::tr("the 'absolute tolerance' property value could not be retrieved"));
return;
}
if (mProperties.contains(InterpolateSolutionId)) {
mInterpolateSolution = mProperties.value(InterpolateSolutionId).toBool();
} else {
emit error(QObject::tr("the 'interpolate solution' property value could not be retrieved"));
return;
}
// Initialise the ODE solver itself
OpenCOR::CoreSolver::CoreOdeSolver::initialize(pVoiStart,
pRatesStatesCount,
pConstants, pRates,
pStates, pAlgebraic,
pComputeRates);
// Create the states vector
mStatesVector = N_VMake_Serial(pRatesStatesCount, pStates);
// Create the CVODE solver
mSolver = CVodeCreate(!integrationMethod.compare(BdfMethod)?CV_BDF:CV_ADAMS,
!iteratorType.compare(NewtonIterator)?CV_NEWTON:CV_FUNCTIONAL);
// Use our own error handler
CVodeSetErrHandlerFn(mSolver, errorHandler, this);
// Initialise the CVODE solver
CVodeInit(mSolver, rhsFunction, pVoiStart, mStatesVector);
// Set some user data
mUserData = new CvodeSolverUserData(pConstants, pAlgebraic,
pComputeRates);
CVodeSetUserData(mSolver, mUserData);
// Set the linear solver, should we be using a Newton iterator
if (!iteratorType.compare(NewtonIterator))
CVDense(mSolver, pRatesStatesCount);
// Set the maximum step
CVodeSetMaxStep(mSolver, maximumStep);
// Set the maximum number of steps
CVodeSetMaxNumSteps(mSolver, maximumNumberOfSteps);
// Set the relative and absolute tolerances
CVodeSStolerances(mSolver, relativeTolerance, absoluteTolerance);
} else {
// Reinitialise the CVODE object
CVodeReInit(mSolver, pVoiStart, mStatesVector);
}
}
//==============================================================================
void CvodeSolver::solve(double &pVoi, const double &pVoiEnd) const
{
// Solve the model
if (!mInterpolateSolution)
CVodeSetStopTime(mSolver, pVoiEnd);
CVode(mSolver, pVoiEnd, mStatesVector, &pVoi, CV_NORMAL);
// Compute the rates one more time to get up to date values for the rates
// Note: another way of doing this would be to copy the contents of the
// calculated rates in rhsFunction, but that's bound to be more time
// consuming since a call to CVode() is likely to generate at least a
// few calls to rhsFunction(), so that would be quite a few memory
// transfers while here we 'only' compute the rates one more time...
mComputeRates(pVoiEnd, mConstants, mRates,
N_VGetArrayPointer_Serial(mStatesVector), mAlgebraic);
}
//==============================================================================
} // namespace CVODESolver
} // namespace OpenCOR
//==============================================================================
// End of file
//==============================================================================
<commit_msg>CVODE solver: some work on providing access to other COVDE parameters (#604).<commit_after>/*******************************************************************************
Licensed to the OpenCOR team under one or more contributor license agreements.
See the NOTICE.txt file distributed with this work for additional information
regarding copyright ownership. The OpenCOR team 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.
*******************************************************************************/
//==============================================================================
// CVODE solver class
//==============================================================================
#include "cvodesolver.h"
//==============================================================================
#include "cvode/cvode.h"
#include "cvode/cvode_band.h"
#include "cvode/cvode_bandpre.h"
#include "cvode/cvode_dense.h"
#include "cvode/cvode_diag.h"
#include "cvode/cvode_spbcgs.h"
#include "cvode/cvode_spgmr.h"
#include "cvode/cvode_sptfqmr.h"
//==============================================================================
namespace OpenCOR {
namespace CVODESolver {
//==============================================================================
int rhsFunction(double pVoi, N_Vector pStates, N_Vector pRates, void *pUserData)
{
// Compute the RHS function
CvodeSolverUserData *userData = static_cast<CvodeSolverUserData *>(pUserData);
userData->computeRates()(pVoi, userData->constants(),
N_VGetArrayPointer_Serial(pRates),
N_VGetArrayPointer_Serial(pStates),
userData->algebraic());
return 0;
}
//==============================================================================
void errorHandler(int pErrorCode, const char *pModule, const char *pFunction,
char *pErrorMessage, void *pUserData)
{
Q_UNUSED(pModule);
Q_UNUSED(pFunction);
if (pErrorCode != CV_WARNING)
// CVODE generated an error, so forward it to the CvodeSolver object
reinterpret_cast<CvodeSolver *>(pUserData)->emitError(pErrorMessage);
}
//==============================================================================
CvodeSolverUserData::CvodeSolverUserData(double *pConstants, double *pAlgebraic,
CoreSolver::CoreOdeSolver::ComputeRatesFunction pComputeRates) :
mConstants(pConstants),
mAlgebraic(pAlgebraic),
mComputeRates(pComputeRates)
{
}
//==============================================================================
double * CvodeSolverUserData::constants() const
{
// Return our constants array
return mConstants;
}
//==============================================================================
double * CvodeSolverUserData::algebraic() const
{
// Return our algebraic array
return mAlgebraic;
}
//==============================================================================
CoreSolver::CoreOdeSolver::ComputeRatesFunction CvodeSolverUserData::computeRates() const
{
// Return our compute rates function
return mComputeRates;
}
//==============================================================================
CvodeSolver::CvodeSolver() :
mSolver(0),
mStatesVector(0),
mUserData(0),
mInterpolateSolution(InterpolateSolutionDefaultValue)
{
}
//==============================================================================
CvodeSolver::~CvodeSolver()
{
// Make sure that the solver has been initialised
if (!mSolver)
return;
// Delete some internal objects
N_VDestroy_Serial(mStatesVector);
CVodeFree(&mSolver);
delete mUserData;
}
//==============================================================================
void CvodeSolver::initialize(const double &pVoiStart,
const int &pRatesStatesCount, double *pConstants,
double *pRates, double *pStates,
double *pAlgebraic,
ComputeRatesFunction pComputeRates)
{
if (!mSolver) {
// Retrieve some of the CVODE properties
double maximumStep;
int maximumNumberOfSteps;
QString integrationMethod;
QString iteratorType;
QString linearSolver;
QString preconditioner;
int upperHalfBandwidth;
int lowerHalfBandwidth;
double relativeTolerance;
double absoluteTolerance;
if (mProperties.contains(MaximumStepId)) {
maximumStep = mProperties.value(MaximumStepId).toDouble();
} else {
emit error(QObject::tr("the 'maximum step' property value could not be retrieved"));
return;
}
if (mProperties.contains(MaximumNumberOfStepsId)) {
maximumNumberOfSteps = mProperties.value(MaximumNumberOfStepsId).toInt();
} else {
emit error(QObject::tr("the 'maximum number of steps' property value could not be retrieved"));
return;
}
if (mProperties.contains(IntegrationMethodId)) {
integrationMethod = mProperties.value(IntegrationMethodId).toString();
} else {
emit error(QObject::tr("the 'integration method' property value could not be retrieved"));
return;
}
if (mProperties.contains(IteratorTypeId)) {
iteratorType = mProperties.value(IteratorTypeId).toString();
if (!iteratorType.compare(NewtonIterator)) {
// We are dealing with a Newton iterator, so retrieve and check
// its linear solver
if (mProperties.contains(LinearSolverId)) {
linearSolver = mProperties.value(LinearSolverId).toString();
} else {
emit error(QObject::tr("the 'linear solver' property value could not be retrieved"));
return;
}
bool needUpperAndLowerHalfBandwidths = false;
if ( !linearSolver.compare(DenseLinearSolver)
|| !linearSolver.compare(DiagonalLinearSolver)) {
// We are dealing with a dense/diagonal linear solver, so
// nothing more to do
} else if (!linearSolver.compare(BandedLinearSolver)) {
// We are dealing with a banded linear solver, so retrieve
// its upper/lower half bandwidth
needUpperAndLowerHalfBandwidths = true;
} else {
// We are dealing with a GMRES/Bi-CGStab/TFQMR linear
// solver, so retrieve and check its preconditioner
if (mProperties.contains(PreconditionerId)) {
preconditioner = mProperties.value(PreconditionerId).toString();
} else {
emit error(QObject::tr("the 'preconditioner' property value could not be retrieved"));
return;
}
if (!preconditioner.compare(BandedPreconditioner)) {
// We are dealing with a banded preconditioner, so
// retrieve its upper/lower half bandwidth
needUpperAndLowerHalfBandwidths = true;
}
}
if (needUpperAndLowerHalfBandwidths) {
if (mProperties.contains(UpperHalfBandwidthId)) {
upperHalfBandwidth = mProperties.value(UpperHalfBandwidthId).toInt();
if ( (upperHalfBandwidth < 0)
|| (upperHalfBandwidth >= pRatesStatesCount)) {
emit error(QObject::tr("the 'upper half-bandwidth' property must have a value between 0 and %1").arg(pRatesStatesCount-1));
return;
}
} else {
emit error(QObject::tr("the 'upper half-bandwidth' property value could not be retrieved"));
return;
}
if (mProperties.contains(LowerHalfBandwidthId)) {
lowerHalfBandwidth = mProperties.value(LowerHalfBandwidthId).toInt();
if ( (lowerHalfBandwidth < 0)
|| (lowerHalfBandwidth >= pRatesStatesCount)) {
emit error(QObject::tr("the 'lower half-bandwidth' property must have a value between 0 and %1").arg(pRatesStatesCount-1));
return;
}
} else {
emit error(QObject::tr("the 'lower half-bandwidth' property value could not be retrieved"));
return;
}
}
}
} else {
emit error(QObject::tr("the 'iterator type' property value could not be retrieved"));
return;
}
if (mProperties.contains(RelativeToleranceId)) {
relativeTolerance = mProperties.value(RelativeToleranceId).toDouble();
if (relativeTolerance < 0) {
emit error(QObject::tr("the 'relative tolerance' property must have a value greater than or equal to 0"));
return;
}
} else {
emit error(QObject::tr("the 'relative tolerance' property value could not be retrieved"));
return;
}
if (mProperties.contains(AbsoluteToleranceId)) {
absoluteTolerance = mProperties.value(AbsoluteToleranceId).toDouble();
if (absoluteTolerance < 0) {
emit error(QObject::tr("the 'absolute tolerance' property must have a value greater than or equal to 0"));
return;
}
} else {
emit error(QObject::tr("the 'absolute tolerance' property value could not be retrieved"));
return;
}
if (mProperties.contains(InterpolateSolutionId)) {
mInterpolateSolution = mProperties.value(InterpolateSolutionId).toBool();
} else {
emit error(QObject::tr("the 'interpolate solution' property value could not be retrieved"));
return;
}
// Initialise the ODE solver itself
OpenCOR::CoreSolver::CoreOdeSolver::initialize(pVoiStart,
pRatesStatesCount,
pConstants, pRates,
pStates, pAlgebraic,
pComputeRates);
// Create the states vector
mStatesVector = N_VMake_Serial(pRatesStatesCount, pStates);
// Create the CVODE solver
bool newtonIterator = !iteratorType.compare(NewtonIterator);
mSolver = CVodeCreate(!integrationMethod.compare(BdfMethod)?CV_BDF:CV_ADAMS,
newtonIterator?CV_NEWTON:CV_FUNCTIONAL);
// Use our own error handler
CVodeSetErrHandlerFn(mSolver, errorHandler, this);
// Initialise the CVODE solver
CVodeInit(mSolver, rhsFunction, pVoiStart, mStatesVector);
// Set some user data
mUserData = new CvodeSolverUserData(pConstants, pAlgebraic,
pComputeRates);
CVodeSetUserData(mSolver, mUserData);
// Set the maximum step
CVodeSetMaxStep(mSolver, maximumStep);
// Set the maximum number of steps
CVodeSetMaxNumSteps(mSolver, maximumNumberOfSteps);
// Set the linear solver, if needed
if (newtonIterator) {
// We are dealing with a Newton iterator
if (!linearSolver.compare(DenseLinearSolver)) {
// We are dealing with a dense linear solver
CVDense(mSolver, pRatesStatesCount);
} else if (!linearSolver.compare(BandedLinearSolver)) {
// We are dealing with a banded linear solver
CVBand(mSolver, pRatesStatesCount, upperHalfBandwidth, lowerHalfBandwidth);
} else if (!linearSolver.compare(DiagonalLinearSolver)) {
// We are dealing with a diagonal linear solver
CVDiag(mSolver);
} else {
// We are dealing with a GMRES/Bi-CGStab/TFQMR linear solver
if (!preconditioner.compare(BandedPreconditioner)) {
// We are using a banded preconditioner with our
// GMRES/Bi-CGStab/TFQMR linear solver
if (!linearSolver.compare(GmresLinearSolver))
CVSpgmr(mSolver, PREC_LEFT, 0);
else if (!linearSolver.compare(BiCgStabLinearSolver))
CVSpbcg(mSolver, PREC_LEFT, 0);
else
CVSptfqmr(mSolver, PREC_LEFT, 0);
CVBandPrecInit(mSolver, pRatesStatesCount, upperHalfBandwidth, lowerHalfBandwidth);
} else {
// We are not using any preconditioner with our
// GMRES/Bi-CGStab/TFQMR linear solver
if (!linearSolver.compare(GmresLinearSolver))
CVSpgmr(mSolver, PREC_NONE, 0);
else if (!linearSolver.compare(BiCgStabLinearSolver))
CVSpbcg(mSolver, PREC_NONE, 0);
else
CVSptfqmr(mSolver, PREC_NONE, 0);
}
}
}
// Set the relative and absolute tolerances
CVodeSStolerances(mSolver, relativeTolerance, absoluteTolerance);
} else {
// Reinitialise the CVODE object
CVodeReInit(mSolver, pVoiStart, mStatesVector);
}
}
//==============================================================================
void CvodeSolver::solve(double &pVoi, const double &pVoiEnd) const
{
// Solve the model
if (!mInterpolateSolution)
CVodeSetStopTime(mSolver, pVoiEnd);
CVode(mSolver, pVoiEnd, mStatesVector, &pVoi, CV_NORMAL);
// Compute the rates one more time to get up to date values for the rates
// Note: another way of doing this would be to copy the contents of the
// calculated rates in rhsFunction, but that's bound to be more time
// consuming since a call to CVode() is likely to generate at least a
// few calls to rhsFunction(), so that would be quite a few memory
// transfers while here we 'only' compute the rates one more time...
mComputeRates(pVoiEnd, mConstants, mRates,
N_VGetArrayPointer_Serial(mStatesVector), mAlgebraic);
}
//==============================================================================
} // namespace CVODESolver
} // namespace OpenCOR
//==============================================================================
// End of file
//==============================================================================
<|endoftext|> |
<commit_before>/*
* The Apache Software License, Version 1.1
*
* Copyright (c) 2001 The Apache Software Foundation. All rights
* reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
*
* 3. The end-user documentation included with the redistribution,
* if any, must include the following acknowledgment:
* "This product includes software developed by the
* Apache Software Foundation (http://www.apache.org/)."
* Alternately, this acknowledgment may appear in the software itself,
* if and wherever such third-party acknowledgments normally appear.
*
* 4. The names "Xerces" and "Apache Software Foundation" must
* not be used to endorse or promote products derived from this
* software without prior written permission. For written
* permission, please contact apache\@apache.org.
*
* 5. Products derived from this software may not be called "Apache",
* nor may "Apache" appear in their name, without prior written
* permission of the Apache Software Foundation.
*
* THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED
* WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
* OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR
* ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
* USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
* OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation, and was
* originally based on software copyright (c) 2001, International
* Business Machines, Inc., http://www.ibm.com . For more information
* on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*/
/*
* $Id$
* $Log$
* Revision 1.10 2003/03/10 20:55:58 peiyongz
* Schema Errata E2-40 double/float
*
* Revision 1.9 2003/02/02 23:54:43 peiyongz
* getFormattedString() added to return original and converted value.
*
* Revision 1.8 2003/01/30 21:55:22 tng
* Performance: create getRawData which is similar to toString but return the internal data directly, user is not required to delete the returned memory.
*
* Revision 1.7 2002/12/11 00:20:02 peiyongz
* Doing businesss in value space. Converting out-of-bound value into special values.
*
* Revision 1.6 2002/11/04 15:22:05 tng
* C++ Namespace Support.
*
* Revision 1.5 2002/09/24 19:51:24 tng
* Performance: use XMLString::equals instead of XMLString::compareString
*
* Revision 1.4 2002/05/03 16:05:45 peiyongz
* Bug 7341: Missing newline at end of util and DOM source files,
* patch from Martin Kalen.
*
* Revision 1.3 2002/03/06 19:13:12 peiyongz
* Patch: more valid lexcial representation for positive/negative zero
*
* Revision 1.2 2002/03/01 18:47:37 peiyongz
* fix: more valid lexcial representation forms for "neural zero"
*
* Revision 1.1.1.1 2002/02/01 22:22:14 peiyongz
* sane_include
*
* Revision 1.2 2001/11/22 21:39:00 peiyongz
* Allow "0.0" to be a valid lexcial representation of ZERO.
*
* Revision 1.1 2001/11/19 21:33:42 peiyongz
* Reorganization: Double/Float
*
*
*/
// ---------------------------------------------------------------------------
// Includes
// ---------------------------------------------------------------------------
#include <xercesc/util/XMLAbstractDoubleFloat.hpp>
#include <xercesc/util/XMLUniDefs.hpp>
#include <xercesc/util/NumberFormatException.hpp>
#include <xercesc/util/XMLString.hpp>
#include <xercesc/util/Janitor.hpp>
XERCES_CPP_NAMESPACE_BEGIN
// ---------------------------------------------------------------------------
// local data member
// ---------------------------------------------------------------------------
static const int BUF_LEN = 64;
static XMLCh value1[BUF_LEN+1];
// ---------------------------------------------------------------------------
// ctor/dtor
// ---------------------------------------------------------------------------
XMLAbstractDoubleFloat::XMLAbstractDoubleFloat()
:fValue(0)
,fType(Normal)
,fDataConverted(false)
,fSign(0)
,fRawData(0)
,fFormattedString(0)
{
}
XMLAbstractDoubleFloat::~XMLAbstractDoubleFloat()
{
delete [] fRawData;
delete [] fFormattedString;
}
void XMLAbstractDoubleFloat::init(const XMLCh* const strValue)
{
if ((!strValue) || (!*strValue))
ThrowXML(NumberFormatException, XMLExcepts::XMLNUM_emptyString);
fRawData = XMLString::replicate(strValue); // preserve the raw data form
XMLCh* tmpStrValue = XMLString::replicate(strValue);
ArrayJanitor<XMLCh> janTmpName(tmpStrValue);
XMLString::trim(tmpStrValue);
normalizeZero(tmpStrValue);
if (XMLString::equals(tmpStrValue, XMLUni::fgNegINFString) )
{
fType = NegINF;
fSign = -1;
}
else if (XMLString::equals(tmpStrValue, XMLUni::fgPosINFString) )
{
fType = PosINF;
fSign = 1;
}
else if (XMLString::equals(tmpStrValue, XMLUni::fgNaNString) )
{
fType = NaN;
fSign = 1;
}
else
//
// Normal case
//
{
checkBoundary(tmpStrValue);
}
}
//
//
//
XMLCh* XMLAbstractDoubleFloat::toString() const
{
return XMLString::replicate(fRawData);
}
XMLCh* XMLAbstractDoubleFloat::getRawData() const
{
return fRawData;
}
const XMLCh* XMLAbstractDoubleFloat::getFormattedString() const
{
if (!fDataConverted)
{
return fRawData;
}
else
{
if (!fFormattedString)
{
XMLAbstractDoubleFloat *temp = (XMLAbstractDoubleFloat *) this;
temp->formatString();
}
return fFormattedString;
}
}
void XMLAbstractDoubleFloat::formatString()
{
unsigned int rawDataLen = XMLString::stringLen(fRawData);
fFormattedString = new XMLCh [ rawDataLen + 8];
for (unsigned int i = 0; i < rawDataLen + 8; i++)
fFormattedString[i] = chNull;
XMLString::copyString(fFormattedString, fRawData);
fFormattedString[rawDataLen] = chSpace;
fFormattedString[rawDataLen + 1] = chOpenParen;
switch (fType)
{
case NegINF:
XMLString::catString(fFormattedString, XMLUni::fgNegINFString);
break;
case PosINF:
XMLString::catString(fFormattedString, XMLUni::fgPosINFString);
break;
case NaN:
XMLString::catString(fFormattedString, XMLUni::fgNaNString);
break;
}
fFormattedString[XMLString::stringLen(fFormattedString)] = chCloseParen;
}
int XMLAbstractDoubleFloat::getSign() const
{
return fSign;
}
//
//
//
int XMLAbstractDoubleFloat::compareValues(const XMLAbstractDoubleFloat* const lValue
, const XMLAbstractDoubleFloat* const rValue)
{
//
// case#1: lValue normal
// rValue normal
//
if ((!lValue->isSpecialValue()) &&
(!rValue->isSpecialValue()) )
{
if (lValue->fValue == rValue->fValue)
return EQUAL;
else
return (lValue->fValue > rValue->fValue) ? GREATER_THAN : LESS_THAN;
}
//
// case#2: lValue special
// rValue special
//
// Schema Errata E2-40
//
// Positive Infinity is greater than all other non-NAN value.
// Nan equals itself but is not comparable with (neither greater than nor less than)
// any other value in the value space
// Negative Infinity is less than all other non-NAN values.
//
else
if ((lValue->isSpecialValue()) &&
(rValue->isSpecialValue()) )
{
if (lValue->fType == rValue->fType)
return EQUAL;
else
{
if ((lValue->fType == NaN) ||
(rValue->fType == NaN) )
{
return INDETERMINATE;
}
else
{
return (lValue->fType > rValue->fType) ? GREATER_THAN : LESS_THAN;
}
}
}
//
// case#3: lValue special
// rValue normal
//
else
if ((lValue->isSpecialValue()) &&
(!rValue->isSpecialValue()) )
{
return compareSpecial(lValue, rValue);
}
//
// case#4: lValue normal
// rValue special
//
else
{
return (-1) * compareSpecial(rValue, lValue);
}
return 0;
}
int XMLAbstractDoubleFloat::compareSpecial(const XMLAbstractDoubleFloat* const specialValue
, const XMLAbstractDoubleFloat* const normalValue)
{
switch (specialValue->fType)
{
case NegINF:
return LESS_THAN;
case PosINF:
return GREATER_THAN;
case NaN:
// NaN is not comparable to any other value
return INDETERMINATE;
default:
XMLString::binToText(specialValue->fType, value1, 16, 10);
ThrowXML1(NumberFormatException
, XMLExcepts::XMLNUM_DBL_FLT_InvalidType
, value1);
//internal error
return 0;
}
}
//
// Assumption: no leading space
//
// 1. The valid char set is "+-.0"
// 2. There shall be only one sign at the first position, if there is one.
// 3. There shall be only one dot '.', if there is one.
//
// Return:
//
// for input comforming to [+]? [0]* '.'? [0]*,
// normalize the input to positive zero string
// for input comforming to '-' [0]* '.'? [0]*,
// normalize the input to negative zero string
// otherwise, do nothing
//
void XMLAbstractDoubleFloat::normalizeZero(XMLCh* const inData)
{
// do a quick check
if (!inData ||
!*inData ||
(XMLString::equals(inData, XMLUni::fgNegZeroString) ) ||
(XMLString::equals(inData, XMLUni::fgPosZeroString) ) )
return;
XMLCh* srcStr = inData;
bool minusSeen = false;
// process sign if any
if (*srcStr == chDash)
{
minusSeen = true;
srcStr++;
}
else if (*srcStr == chPlus)
{
srcStr++;
}
// scan the string
bool dotSeen = false;
bool isValidStr = true;
XMLCh theChar;
while ((theChar=*srcStr++) && isValidStr)
{
if ( theChar != chPeriod && theChar != chDigit_0 )
isValidStr = false; // invalid char
else if (theChar == chPeriod) // process dot
dotSeen ? isValidStr = false : dotSeen = true;
}
// need not to worry about the memory problem
// since either fgNegZeroString or fgPosZeroString
// is the canonical form (meaning the shortest in length)
// of their category respectively.
if (isValidStr)
{
if (minusSeen)
XMLString::copyString(inData, XMLUni::fgNegZeroString);
else
XMLString::copyString(inData, XMLUni::fgPosZeroString);
}
else
{
// we got to set the sign first, since this string may
// eventaully turn out to be beyond the minimum representable
// number and reduced to -0 or +0.
fSign = minusSeen ? -1 : 1;
}
return;
}
XERCES_CPP_NAMESPACE_END
<commit_msg>format string for value converted to Zero.<commit_after>/*
* The Apache Software License, Version 1.1
*
* Copyright (c) 2001 The Apache Software Foundation. All rights
* reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
*
* 3. The end-user documentation included with the redistribution,
* if any, must include the following acknowledgment:
* "This product includes software developed by the
* Apache Software Foundation (http://www.apache.org/)."
* Alternately, this acknowledgment may appear in the software itself,
* if and wherever such third-party acknowledgments normally appear.
*
* 4. The names "Xerces" and "Apache Software Foundation" must
* not be used to endorse or promote products derived from this
* software without prior written permission. For written
* permission, please contact apache\@apache.org.
*
* 5. Products derived from this software may not be called "Apache",
* nor may "Apache" appear in their name, without prior written
* permission of the Apache Software Foundation.
*
* THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED
* WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
* OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR
* ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
* USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
* OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation, and was
* originally based on software copyright (c) 2001, International
* Business Machines, Inc., http://www.ibm.com . For more information
* on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*/
/*
* $Id$
* $Log$
* Revision 1.11 2003/03/12 20:45:46 peiyongz
* format string for value converted to Zero.
*
* Revision 1.10 2003/03/10 20:55:58 peiyongz
* Schema Errata E2-40 double/float
*
* Revision 1.9 2003/02/02 23:54:43 peiyongz
* getFormattedString() added to return original and converted value.
*
* Revision 1.8 2003/01/30 21:55:22 tng
* Performance: create getRawData which is similar to toString but return the internal data directly, user is not required to delete the returned memory.
*
* Revision 1.7 2002/12/11 00:20:02 peiyongz
* Doing businesss in value space. Converting out-of-bound value into special values.
*
* Revision 1.6 2002/11/04 15:22:05 tng
* C++ Namespace Support.
*
* Revision 1.5 2002/09/24 19:51:24 tng
* Performance: use XMLString::equals instead of XMLString::compareString
*
* Revision 1.4 2002/05/03 16:05:45 peiyongz
* Bug 7341: Missing newline at end of util and DOM source files,
* patch from Martin Kalen.
*
* Revision 1.3 2002/03/06 19:13:12 peiyongz
* Patch: more valid lexcial representation for positive/negative zero
*
* Revision 1.2 2002/03/01 18:47:37 peiyongz
* fix: more valid lexcial representation forms for "neural zero"
*
* Revision 1.1.1.1 2002/02/01 22:22:14 peiyongz
* sane_include
*
* Revision 1.2 2001/11/22 21:39:00 peiyongz
* Allow "0.0" to be a valid lexcial representation of ZERO.
*
* Revision 1.1 2001/11/19 21:33:42 peiyongz
* Reorganization: Double/Float
*
*
*/
// ---------------------------------------------------------------------------
// Includes
// ---------------------------------------------------------------------------
#include <xercesc/util/XMLAbstractDoubleFloat.hpp>
#include <xercesc/util/XMLUniDefs.hpp>
#include <xercesc/util/NumberFormatException.hpp>
#include <xercesc/util/XMLString.hpp>
#include <xercesc/util/Janitor.hpp>
XERCES_CPP_NAMESPACE_BEGIN
// ---------------------------------------------------------------------------
// local data member
// ---------------------------------------------------------------------------
static const int BUF_LEN = 64;
static XMLCh value1[BUF_LEN+1];
// ---------------------------------------------------------------------------
// ctor/dtor
// ---------------------------------------------------------------------------
XMLAbstractDoubleFloat::XMLAbstractDoubleFloat()
:fValue(0)
,fType(Normal)
,fDataConverted(false)
,fSign(0)
,fRawData(0)
,fFormattedString(0)
{
}
XMLAbstractDoubleFloat::~XMLAbstractDoubleFloat()
{
delete [] fRawData;
delete [] fFormattedString;
}
void XMLAbstractDoubleFloat::init(const XMLCh* const strValue)
{
if ((!strValue) || (!*strValue))
ThrowXML(NumberFormatException, XMLExcepts::XMLNUM_emptyString);
fRawData = XMLString::replicate(strValue); // preserve the raw data form
XMLCh* tmpStrValue = XMLString::replicate(strValue);
ArrayJanitor<XMLCh> janTmpName(tmpStrValue);
XMLString::trim(tmpStrValue);
normalizeZero(tmpStrValue);
if (XMLString::equals(tmpStrValue, XMLUni::fgNegINFString) )
{
fType = NegINF;
fSign = -1;
}
else if (XMLString::equals(tmpStrValue, XMLUni::fgPosINFString) )
{
fType = PosINF;
fSign = 1;
}
else if (XMLString::equals(tmpStrValue, XMLUni::fgNaNString) )
{
fType = NaN;
fSign = 1;
}
else
//
// Normal case
//
{
checkBoundary(tmpStrValue);
}
}
//
//
//
XMLCh* XMLAbstractDoubleFloat::toString() const
{
return XMLString::replicate(fRawData);
}
XMLCh* XMLAbstractDoubleFloat::getRawData() const
{
return fRawData;
}
const XMLCh* XMLAbstractDoubleFloat::getFormattedString() const
{
if (!fDataConverted)
{
return fRawData;
}
else
{
if (!fFormattedString)
{
XMLAbstractDoubleFloat *temp = (XMLAbstractDoubleFloat *) this;
temp->formatString();
}
return fFormattedString;
}
}
void XMLAbstractDoubleFloat::formatString()
{
unsigned int rawDataLen = XMLString::stringLen(fRawData);
fFormattedString = new XMLCh [ rawDataLen + 8];
for (unsigned int i = 0; i < rawDataLen + 8; i++)
fFormattedString[i] = chNull;
XMLString::copyString(fFormattedString, fRawData);
fFormattedString[rawDataLen] = chSpace;
fFormattedString[rawDataLen + 1] = chOpenParen;
switch (fType)
{
case NegINF:
XMLString::catString(fFormattedString, XMLUni::fgNegINFString);
break;
case PosINF:
XMLString::catString(fFormattedString, XMLUni::fgPosINFString);
break;
case NaN:
XMLString::catString(fFormattedString, XMLUni::fgNaNString);
break;
default:
// its zero
XMLString::catString(fFormattedString, XMLUni::fgPosZeroString);
break;
}
fFormattedString[XMLString::stringLen(fFormattedString)] = chCloseParen;
}
int XMLAbstractDoubleFloat::getSign() const
{
return fSign;
}
//
//
//
int XMLAbstractDoubleFloat::compareValues(const XMLAbstractDoubleFloat* const lValue
, const XMLAbstractDoubleFloat* const rValue)
{
//
// case#1: lValue normal
// rValue normal
//
if ((!lValue->isSpecialValue()) &&
(!rValue->isSpecialValue()) )
{
if (lValue->fValue == rValue->fValue)
return EQUAL;
else
return (lValue->fValue > rValue->fValue) ? GREATER_THAN : LESS_THAN;
}
//
// case#2: lValue special
// rValue special
//
// Schema Errata E2-40
//
// Positive Infinity is greater than all other non-NAN value.
// Nan equals itself but is not comparable with (neither greater than nor less than)
// any other value in the value space
// Negative Infinity is less than all other non-NAN values.
//
else
if ((lValue->isSpecialValue()) &&
(rValue->isSpecialValue()) )
{
if (lValue->fType == rValue->fType)
return EQUAL;
else
{
if ((lValue->fType == NaN) ||
(rValue->fType == NaN) )
{
return INDETERMINATE;
}
else
{
return (lValue->fType > rValue->fType) ? GREATER_THAN : LESS_THAN;
}
}
}
//
// case#3: lValue special
// rValue normal
//
else
if ((lValue->isSpecialValue()) &&
(!rValue->isSpecialValue()) )
{
return compareSpecial(lValue, rValue);
}
//
// case#4: lValue normal
// rValue special
//
else
{
return (-1) * compareSpecial(rValue, lValue);
}
return 0;
}
int XMLAbstractDoubleFloat::compareSpecial(const XMLAbstractDoubleFloat* const specialValue
, const XMLAbstractDoubleFloat* const normalValue)
{
switch (specialValue->fType)
{
case NegINF:
return LESS_THAN;
case PosINF:
return GREATER_THAN;
case NaN:
// NaN is not comparable to any other value
return INDETERMINATE;
default:
XMLString::binToText(specialValue->fType, value1, 16, 10);
ThrowXML1(NumberFormatException
, XMLExcepts::XMLNUM_DBL_FLT_InvalidType
, value1);
//internal error
return 0;
}
}
//
// Assumption: no leading space
//
// 1. The valid char set is "+-.0"
// 2. There shall be only one sign at the first position, if there is one.
// 3. There shall be only one dot '.', if there is one.
//
// Return:
//
// for input comforming to [+]? [0]* '.'? [0]*,
// normalize the input to positive zero string
// for input comforming to '-' [0]* '.'? [0]*,
// normalize the input to negative zero string
// otherwise, do nothing
//
void XMLAbstractDoubleFloat::normalizeZero(XMLCh* const inData)
{
// do a quick check
if (!inData ||
!*inData ||
(XMLString::equals(inData, XMLUni::fgNegZeroString) ) ||
(XMLString::equals(inData, XMLUni::fgPosZeroString) ) )
return;
XMLCh* srcStr = inData;
bool minusSeen = false;
// process sign if any
if (*srcStr == chDash)
{
minusSeen = true;
srcStr++;
}
else if (*srcStr == chPlus)
{
srcStr++;
}
// scan the string
bool dotSeen = false;
bool isValidStr = true;
XMLCh theChar;
while ((theChar=*srcStr++) && isValidStr)
{
if ( theChar != chPeriod && theChar != chDigit_0 )
isValidStr = false; // invalid char
else if (theChar == chPeriod) // process dot
dotSeen ? isValidStr = false : dotSeen = true;
}
// need not to worry about the memory problem
// since either fgNegZeroString or fgPosZeroString
// is the canonical form (meaning the shortest in length)
// of their category respectively.
if (isValidStr)
{
if (minusSeen)
XMLString::copyString(inData, XMLUni::fgNegZeroString);
else
XMLString::copyString(inData, XMLUni::fgPosZeroString);
}
else
{
// we got to set the sign first, since this string may
// eventaully turn out to be beyond the minimum representable
// number and reduced to -0 or +0.
fSign = minusSeen ? -1 : 1;
}
return;
}
XERCES_CPP_NAMESPACE_END
<|endoftext|> |
<commit_before>//! @Alan
//!
//! Exercise 10.14:
//! Write a lambda that takes two ints and returns their sum.
//!
//! Exercise 10.15:
//! Write a lambda that captures an int from its enclosing function
//! and takes an int parameter. The lambda should return the sum of
//! the captured int and the int parameter.
//!
//! Exercise 10.16:
//! Write your own version of the biggies function using lambdas.
//!
//! Exercise 10.18:
//! Rewrite biggies to use partition instead of find_if.
//!
//! Exercise 10.19:
//! Rewrite the previous exercise to use stable_partition, which like
//! stable_sort maintains the original element order in the paritioned
//! sequence.
//!
#include <iostream>
#include <string>
#include <vector>
#include <algorithm>
//! Exercise 10.14
auto sum = [](const int i1, const int i2 )
{ return i1 + i2; };
//! ^
//! @note There is a ";" here, just like that used after a body of a class.
//! Exercise 10.15
void f()
{
int i = 0;
auto sum = [i](const int j)
{
return i + j;
};
}
//! Exercise 10.16
void
wy_elimdups(std::vector<std::string> &vs);
void
wy_biggies(std::vector<std::string> &vs,const std::vector<std::string>::size_type sz);
//! Exercise 10.18
void
wy_biggies_partition(std::vector<std::string> &vs, const std::vector<std::string>::size_type sz);
//! Exercise 10.19
void
wy_biggies_STpartition(std::vector<std::string> &vs, const std::vector<std::string>::size_type sz);
int main()
{
return 0;
}
void wy_elimdups(std::vector<std::string> &vs)
{
for (auto element : vs)
std::cout << element
<<" ";
std::cout <<"\n";
//! sort alphabetically
std::sort(vs.begin(), vs.end());
for (auto element : vs)
std::cout << element
<<" ";
std::cout <<"\n";
//! put all duplicates at the end of the vector
//! and get the iterator pointing to the one past
//! the last unique element.
auto unique_iterator = std::unique(vs.begin(),vs.end());
for (auto element : vs)
std::cout << element
<<" ";
std::cout <<"\n";
vs.erase(unique_iterator, vs.end());
for (auto element : vs)
std::cout << element
<<" ";
std::cout <<"\n";
}
//! Exercise 10.16
void
wy_biggies(std::vector<std::string> &vs, const std::vector<std::string>::size_type sz)
{
wy_elimdups(vs);
// sort words by size, but maintain alphabetical order for words of the same size
std::stable_sort(vs.begin(), vs.end(),
[](const std::string &s1, const std::string &s2){return s1.size() < s2.size();});
// get an iterator to the first element whose size() is >= sz
auto wc = std::find_if(vs.begin(), vs.end(),
[sz](const std::string &s)
{return s.size() > sz;});
std::for_each(wc, vs.end(), [](const std::string &s)
{std::cout << s;});
}
//! Exercise 10.18
void wy_biggies_partition(std::vector<std::string> &vs, const std::vector<std::string>::size_type sz)
{
wy_elimdups(vs);
// sort words by size, but maintain alphabetical order for words of the same size
std::stable_sort(vs.begin(), vs.end(),
[](const std::string &s1, const std::string &s2){return s1.size() < s2.size();});
auto wc = std::partition(vs.begin(), vs.end(),
[sz](const std::string &s)
{return s.size() > sz;});
std::for_each(vs.begin(),wc, [](const std::string &s)
{std::cout << s<<" ";});
}
//! Exercise 10.19
void wy_biggies_STpartition(std::vector<std::string> &vs, const std::vector<std::string>::size_type sz)
{
wy_elimdups(vs);
// sort words by size, but maintain alphabetical order for words of the same size
std::stable_sort(vs.begin(), vs.end(),
[](const std::string &s1, const std::string &s2){return s1.size() < s2.size();});
auto wc = std::stable_partition(vs.begin(), vs.end(),
[sz](const std::string &s)
{return s.size() > sz;});
std::for_each(wc, vs.end(), [](const std::string &s)
{std::cout << s;});
}
<commit_msg>Update ex10_14_15_16_18_19.cpp<commit_after>//! @Alan
//!
//! Exercise 10.14:
//! Write a lambda that takes two ints and returns their sum.
//!
//! Exercise 10.15:
//! Write a lambda that captures an int from its enclosing function
//! and takes an int parameter. The lambda should return the sum of
//! the captured int and the int parameter.
//!
//! Exercise 10.16:
//! Write your own version of the biggies function using lambdas.
//!
//! Exercise 10.18:
//! Rewrite biggies to use partition instead of find_if.
//!
//! Exercise 10.19:
//! Rewrite the previous exercise to use stable_partition, which like
//! stable_sort maintains the original element order in the paritioned
//! sequence.
//!
#include <iostream>
#include <string>
#include <vector>
#include <algorithm>
//! Exercise 10.14
auto sum = [](const int i1, const int i2 )
{ return i1 + i2; };
//! ^
//! @note There is a ";" here, just like that used after a body of a class.
//! Exercise 10.15
void f()
{
int i = 0;
auto sum = [i](const int j)
{
return i + j;
};
}
//! Exercise 10.16
void
wy_elimdups(std::vector<std::string> &vs);
void
wy_biggies(std::vector<std::string> &vs,const std::vector<std::string>::size_type sz);
//! Exercise 10.18
void
wy_biggies_partition(std::vector<std::string> &vs, const std::vector<std::string>::size_type sz);
//! Exercise 10.19
void
wy_biggies_STpartition(std::vector<std::string> &vs, const std::vector<std::string>::size_type sz);
int main()
{
return 0;
}
void wy_elimdups(std::vector<std::string> &vs)
{
for (auto element : vs)
std::cout << element
<<" ";
std::cout <<"\n";
//! sort alphabetically
std::sort(vs.begin(), vs.end());
for (auto element : vs)
std::cout << element
<<" ";
std::cout <<"\n";
//! put all duplicates at the end of the vector
//! and get the iterator pointing to the one past
//! the last unique element.
auto unique_iterator = std::unique(vs.begin(),vs.end());
for (auto element : vs)
std::cout << element
<<" ";
std::cout <<"\n";
vs.erase(unique_iterator, vs.end());
for (auto element : vs)
std::cout << element
<<" ";
std::cout <<"\n";
}
//! Exercise 10.16
void
wy_biggies(std::vector<std::string> &vs, const std::vector<std::string>::size_type sz)
{
wy_elimdups(vs);
// sort words by size, but maintain alphabetical order for words of the same size
std::stable_sort(vs.begin(), vs.end(),
[](const std::string &s1, const std::string &s2){return s1.size() < s2.size();});
// get an iterator to the first element whose size() is >= sz
auto wc = std::find_if(vs.begin(), vs.end(),
[sz](const std::string &s)
{return s.size() > sz;});
std::for_each(wc, vs.end(), [](const std::string &s)
{std::cout << s;});
}
//! Exercise 10.18
void wy_biggies_partition(std::vector<std::string> &vs, const std::vector<std::string>::size_type sz)
{
wy_elimdups(vs);
// sort words by size, but maintain alphabetical order for words of the same size
std::stable_sort(vs.begin(), vs.end(),
[](const std::string &s1, const std::string &s2){return s1.size() < s2.size();});
auto wc = std::partition(vs.begin(), vs.end(),
[sz](const std::string &s)
{return s.size() >= sz;});
std::for_each(vs.begin(),wc, [](const std::string &s)
{std::cout << s<<" ";});
}
//! Exercise 10.19
void wy_biggies_STpartition(std::vector<std::string> &vs, const std::vector<std::string>::size_type sz)
{
wy_elimdups(vs);
// sort words by size, but maintain alphabetical order for words of the same size
std::stable_sort(vs.begin(), vs.end(),
[](const std::string &s1, const std::string &s2){return s1.size() < s2.size();});
auto wc = std::stable_partition(vs.begin(), vs.end(),
[sz](const std::string &s)
{return s.size() > sz;});
std::for_each(wc, vs.end(), [](const std::string &s)
{std::cout << s;});
}
<|endoftext|> |
<commit_before>/* Copyright 2015 The TensorFlow Authors. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
==============================================================================*/
// See docs in ../ops/linalg_ops.cc.
#include "third_party/eigen3/Eigen/Core"
#include "tensorflow/core/framework/kernel_def_builder.h"
#include "tensorflow/core/framework/op_kernel.h"
#include "tensorflow/core/framework/tensor_shape.h"
#include "tensorflow/core/kernels/linalg_ops_common.h"
#include "tensorflow/core/lib/core/errors.h"
#include "tensorflow/core/platform/logging.h"
#include "tensorflow/core/platform/macros.h"
#include "tensorflow/core/platform/types.h"
#if GOOGLE_CUDA
#include "tensorflow/core/platform/stream_executor.h"
#endif // GOOGLE_CUDA
namespace tensorflow {
#if GOOGLE_CUDA
namespace {
template <typename Scalar>
se::DeviceMemory<Scalar> AsDeviceMemory(const Scalar* cuda_memory) {
se::DeviceMemoryBase wrapped(const_cast<Scalar*>(cuda_memory));
se::DeviceMemory<Scalar> typed(wrapped);
return typed;
}
} // namespace
#endif // GOOGLE_CUDA
template <class Scalar>
class MatrixTriangularSolveOp : public LinearAlgebraOp<Scalar> {
public:
INHERIT_LINALG_TYPEDEFS(Scalar);
explicit MatrixTriangularSolveOp(OpKernelConstruction* context)
: Base(context), lower_(true), adjoint_(false) {
OP_REQUIRES_OK(context, context->GetAttr("lower", &lower_));
OP_REQUIRES_OK(context, context->GetAttr("adjoint", &adjoint_));
}
void ValidateInputMatrixShapes(
OpKernelContext* context,
const TensorShapes& input_matrix_shapes) const final {
Base::ValidateSquareSolver(context, input_matrix_shapes);
}
TensorShapes GetOutputMatrixShapes(
const TensorShapes& input_matrix_shapes) const final {
return TensorShapes({TensorShape({input_matrix_shapes[0].dim_size(1),
input_matrix_shapes[1].dim_size(1)})});
}
int64 GetCostPerUnit(const TensorShapes& input_matrix_shapes) const final {
double rows = static_cast<double>(input_matrix_shapes[0].dim_size(0));
double num_rhss = static_cast<double>(input_matrix_shapes[1].dim_size(1));
double cost = rows * rows * num_rhss *
(Eigen::TensorOpCost::AddCost<Scalar>() +
Eigen::TensorOpCost::MulCost<Scalar>());
return cost >= static_cast<double>(kint64max) ? kint64max
: static_cast<int64>(cost);
}
bool EnableInputForwarding() const final { return false; }
void ComputeMatrix(OpKernelContext* context, const ConstMatrixMaps& inputs,
MatrixMaps* outputs) final {
const ConstMatrixMap& matrix = inputs[0];
const ConstMatrixMap& rhs = inputs[1];
MatrixMap& output = outputs->at(0);
if (matrix.rows() == 0 || rhs.cols() == 0) {
// To be consistent with the MatrixInverse op, we define the solution for
// an empty set of equation as the empty matrix.
return;
}
const RealScalar min_abs_pivot = matrix.diagonal().cwiseAbs().minCoeff();
OP_REQUIRES(context, min_abs_pivot > RealScalar(0),
errors::InvalidArgument("Input matrix is not invertible."));
if (lower_) {
auto triangle = matrix.template triangularView<Eigen::Lower>();
if (adjoint_) {
output.noalias() = triangle.adjoint().solve(rhs);
} else {
output.noalias() = triangle.solve(rhs);
}
} else {
auto triangle = matrix.template triangularView<Eigen::Upper>();
if (adjoint_) {
output.noalias() = triangle.adjoint().solve(rhs);
} else {
output.noalias() = triangle.solve(rhs);
}
}
}
private:
bool lower_;
bool adjoint_;
TF_DISALLOW_COPY_AND_ASSIGN(MatrixTriangularSolveOp);
};
REGISTER_LINALG_OP_CPU("MatrixTriangularSolve",
(MatrixTriangularSolveOp<float>), float);
REGISTER_LINALG_OP_CPU("MatrixTriangularSolve",
(MatrixTriangularSolveOp<double>), double);
REGISTER_LINALG_OP_CPU("MatrixTriangularSolve",
(MatrixTriangularSolveOp<complex64>), complex64);
REGISTER_LINALG_OP_CPU("MatrixTriangularSolve",
(MatrixTriangularSolveOp<complex128>), complex128);
REGISTER_LINALG_OP_CPU("BatchMatrixTriangularSolve",
(MatrixTriangularSolveOp<float>), float);
REGISTER_LINALG_OP_CPU("BatchMatrixTriangularSolve",
(MatrixTriangularSolveOp<double>), double);
#ifdef GOOGLE_CUDA
// TODO(rmlarsen): Re-factor to
// 1. Enable buffer forwarding from rhs->out.
// 2. Save Memcpy when buffer forwarding is used.
// 3. Copy entire rhs in a single Memcpy when forwarding is not used.
template <class Scalar>
class MatrixTriangularSolveOpGPU : public LinearAlgebraOp<Scalar> {
public:
INHERIT_LINALG_TYPEDEFS(Scalar);
explicit MatrixTriangularSolveOpGPU(OpKernelConstruction* context)
: Base(context), lower_(true), adjoint_(false) {
OP_REQUIRES_OK(context, context->GetAttr("lower", &lower_));
OP_REQUIRES_OK(context, context->GetAttr("adjoint", &adjoint_));
}
void ValidateInputMatrixShapes(
OpKernelContext* context,
const TensorShapes& input_matrix_shapes) const final {
Base::ValidateSquareSolver(context, input_matrix_shapes);
}
TensorShapes GetOutputMatrixShapes(
const TensorShapes& input_matrix_shapes) const final {
return TensorShapes({TensorShape({input_matrix_shapes[0].dim_size(1),
input_matrix_shapes[1].dim_size(1)})});
}
int64 GetCostPerUnit(const TensorShapes& input_matrix_shapes) const final {
double rows = static_cast<double>(input_matrix_shapes[0].dim_size(0));
double num_rhss = static_cast<double>(input_matrix_shapes[1].dim_size(1));
double cost = rows * rows * num_rhss *
(Eigen::TensorOpCost::AddCost<Scalar>() +
Eigen::TensorOpCost::MulCost<Scalar>());
return cost >= static_cast<double>(kint64max) ? kint64max
: static_cast<int64>(cost);
}
bool EnableInputForwarding() const final { return false; }
void ComputeMatrix(OpKernelContext* context, const ConstMatrixMaps& inputs,
MatrixMaps* outputs) final {
const ConstMatrixMap& matrix = inputs[0];
const ConstMatrixMap& rhs = inputs[1];
MatrixMap& output = outputs->at(0);
if (matrix.rows() == 0 || rhs.cols() == 0) {
// To be consistent with the MatrixInverse op, we define the solution for
// an empty set of equation as the empty matrix.
return;
}
auto matrix_ptr = AsDeviceMemory(matrix.data());
auto rhs_ptr = AsDeviceMemory(rhs.data());
auto out_ptr = AsDeviceMemory(output.data());
auto* stream = context->op_device_context()->stream();
uint64 rhs_elems = rhs.rows() * rhs.cols();
bool copy_status =
stream->ThenMemcpyD2D(&out_ptr, rhs_ptr, sizeof(Scalar) * rhs_elems)
.ok();
if (!copy_status) {
context->SetStatus(
errors::Internal("Failed to copy rhs into output before solve"));
}
// Cublas does
// output = matrix \ rhs
// where matrix, rhs and output are assumed to be in column major.
// We want the output to be in row-major, so we can compute
// output' = rhs' / matrix' (' stands for transpose)
// Upper/lower needs to be swapped for this.
se::blas::UpperLower upper_lower_matrix;
se::blas::Transpose transpose_matrix;
if (lower_) {
upper_lower_matrix = se::blas::UpperLower::kUpper;
} else {
upper_lower_matrix = se::blas::UpperLower::kLower;
}
if (adjoint_) {
transpose_matrix = se::blas::Transpose::kConjugateTranspose;
} else {
transpose_matrix = se::blas::Transpose::kNoTranspose;
}
uint64 leading_dim_matrix = matrix.cols();
uint64 leading_dim_output = output.cols();
uint64 colmajor_rows = output.cols();
uint64 colmajor_cols = output.rows();
bool blas_launch_status =
stream
->ThenBlasTrsm(
se::blas::Side::kRight /*side*/, upper_lower_matrix /*uplo*/,
transpose_matrix /*trans*/,
se::blas::Diagonal::kNonUnit /*diag*/, colmajor_rows /*m*/,
colmajor_cols /*n*/, Scalar(1.0) /*alpha*/, matrix_ptr,
leading_dim_matrix /*lda*/, &out_ptr,
leading_dim_output /*ldb*/)
.ok();
if (!blas_launch_status) {
context->SetStatus(errors::Internal("Blas TRSM launch failed"));
}
}
private:
bool lower_;
bool adjoint_;
TF_DISALLOW_COPY_AND_ASSIGN(MatrixTriangularSolveOpGPU);
};
REGISTER_LINALG_OP_GPU("MatrixTriangularSolve",
(MatrixTriangularSolveOpGPU<float>), float);
REGISTER_LINALG_OP_GPU("MatrixTriangularSolve",
(MatrixTriangularSolveOpGPU<double>), double);
REGISTER_LINALG_OP_GPU("MatrixTriangularSolve",
(MatrixTriangularSolveOpGPU<complex64>), complex64);
REGISTER_LINALG_OP_GPU("MatrixTriangularSolve",
(MatrixTriangularSolveOpGPU<complex128>), complex128);
REGISTER_LINALG_OP_GPU("BatchMatrixTriangularSolve",
(MatrixTriangularSolveOpGPU<float>), float);
REGISTER_LINALG_OP_GPU("BatchMatrixTriangularSolve",
(MatrixTriangularSolveOpGPU<double>), double);
#endif // GOOGLE_CUDA
} // namespace tensorflow
<commit_msg>Adding ROCm support for the matrix_triangular_solve op<commit_after>/* Copyright 2015 The TensorFlow Authors. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
==============================================================================*/
// See docs in ../ops/linalg_ops.cc.
#include "third_party/eigen3/Eigen/Core"
#include "tensorflow/core/framework/kernel_def_builder.h"
#include "tensorflow/core/framework/op_kernel.h"
#include "tensorflow/core/framework/tensor_shape.h"
#include "tensorflow/core/kernels/linalg_ops_common.h"
#include "tensorflow/core/lib/core/errors.h"
#include "tensorflow/core/platform/logging.h"
#include "tensorflow/core/platform/macros.h"
#include "tensorflow/core/platform/types.h"
#if GOOGLE_CUDA || TENSORFLOW_USE_ROCM
#include "tensorflow/core/platform/stream_executor.h"
#endif // GOOGLE_CUDA || TENSORFLOW_USE_ROCM
namespace tensorflow {
#if GOOGLE_CUDA || TENSORFLOW_USE_ROCM
namespace {
template <typename Scalar>
se::DeviceMemory<Scalar> AsDeviceMemory(const Scalar* gpu_memory) {
se::DeviceMemoryBase wrapped(const_cast<Scalar*>(gpu_memory));
se::DeviceMemory<Scalar> typed(wrapped);
return typed;
}
} // namespace
#endif // GOOGLE_CUDA || TENSORFLOW_USE_ROCM
template <class Scalar>
class MatrixTriangularSolveOp : public LinearAlgebraOp<Scalar> {
public:
INHERIT_LINALG_TYPEDEFS(Scalar);
explicit MatrixTriangularSolveOp(OpKernelConstruction* context)
: Base(context), lower_(true), adjoint_(false) {
OP_REQUIRES_OK(context, context->GetAttr("lower", &lower_));
OP_REQUIRES_OK(context, context->GetAttr("adjoint", &adjoint_));
}
void ValidateInputMatrixShapes(
OpKernelContext* context,
const TensorShapes& input_matrix_shapes) const final {
Base::ValidateSquareSolver(context, input_matrix_shapes);
}
TensorShapes GetOutputMatrixShapes(
const TensorShapes& input_matrix_shapes) const final {
return TensorShapes({TensorShape({input_matrix_shapes[0].dim_size(1),
input_matrix_shapes[1].dim_size(1)})});
}
int64 GetCostPerUnit(const TensorShapes& input_matrix_shapes) const final {
double rows = static_cast<double>(input_matrix_shapes[0].dim_size(0));
double num_rhss = static_cast<double>(input_matrix_shapes[1].dim_size(1));
double cost = rows * rows * num_rhss *
(Eigen::TensorOpCost::AddCost<Scalar>() +
Eigen::TensorOpCost::MulCost<Scalar>());
return cost >= static_cast<double>(kint64max) ? kint64max
: static_cast<int64>(cost);
}
bool EnableInputForwarding() const final { return false; }
void ComputeMatrix(OpKernelContext* context, const ConstMatrixMaps& inputs,
MatrixMaps* outputs) final {
const ConstMatrixMap& matrix = inputs[0];
const ConstMatrixMap& rhs = inputs[1];
MatrixMap& output = outputs->at(0);
if (matrix.rows() == 0 || rhs.cols() == 0) {
// To be consistent with the MatrixInverse op, we define the solution for
// an empty set of equation as the empty matrix.
return;
}
const RealScalar min_abs_pivot = matrix.diagonal().cwiseAbs().minCoeff();
OP_REQUIRES(context, min_abs_pivot > RealScalar(0),
errors::InvalidArgument("Input matrix is not invertible."));
if (lower_) {
auto triangle = matrix.template triangularView<Eigen::Lower>();
if (adjoint_) {
output.noalias() = triangle.adjoint().solve(rhs);
} else {
output.noalias() = triangle.solve(rhs);
}
} else {
auto triangle = matrix.template triangularView<Eigen::Upper>();
if (adjoint_) {
output.noalias() = triangle.adjoint().solve(rhs);
} else {
output.noalias() = triangle.solve(rhs);
}
}
}
private:
bool lower_;
bool adjoint_;
TF_DISALLOW_COPY_AND_ASSIGN(MatrixTriangularSolveOp);
};
REGISTER_LINALG_OP_CPU("MatrixTriangularSolve",
(MatrixTriangularSolveOp<float>), float);
REGISTER_LINALG_OP_CPU("MatrixTriangularSolve",
(MatrixTriangularSolveOp<double>), double);
REGISTER_LINALG_OP_CPU("MatrixTriangularSolve",
(MatrixTriangularSolveOp<complex64>), complex64);
REGISTER_LINALG_OP_CPU("MatrixTriangularSolve",
(MatrixTriangularSolveOp<complex128>), complex128);
REGISTER_LINALG_OP_CPU("BatchMatrixTriangularSolve",
(MatrixTriangularSolveOp<float>), float);
REGISTER_LINALG_OP_CPU("BatchMatrixTriangularSolve",
(MatrixTriangularSolveOp<double>), double);
#if GOOGLE_CUDA || TENSORFLOW_USE_ROCM
// TODO(rmlarsen): Re-factor to
// 1. Enable buffer forwarding from rhs->out.
// 2. Save Memcpy when buffer forwarding is used.
// 3. Copy entire rhs in a single Memcpy when forwarding is not used.
template <class Scalar>
class MatrixTriangularSolveOpGPU : public LinearAlgebraOp<Scalar> {
public:
INHERIT_LINALG_TYPEDEFS(Scalar);
explicit MatrixTriangularSolveOpGPU(OpKernelConstruction* context)
: Base(context), lower_(true), adjoint_(false) {
OP_REQUIRES_OK(context, context->GetAttr("lower", &lower_));
OP_REQUIRES_OK(context, context->GetAttr("adjoint", &adjoint_));
}
void ValidateInputMatrixShapes(
OpKernelContext* context,
const TensorShapes& input_matrix_shapes) const final {
Base::ValidateSquareSolver(context, input_matrix_shapes);
}
TensorShapes GetOutputMatrixShapes(
const TensorShapes& input_matrix_shapes) const final {
return TensorShapes({TensorShape({input_matrix_shapes[0].dim_size(1),
input_matrix_shapes[1].dim_size(1)})});
}
int64 GetCostPerUnit(const TensorShapes& input_matrix_shapes) const final {
double rows = static_cast<double>(input_matrix_shapes[0].dim_size(0));
double num_rhss = static_cast<double>(input_matrix_shapes[1].dim_size(1));
double cost = rows * rows * num_rhss *
(Eigen::TensorOpCost::AddCost<Scalar>() +
Eigen::TensorOpCost::MulCost<Scalar>());
return cost >= static_cast<double>(kint64max) ? kint64max
: static_cast<int64>(cost);
}
bool EnableInputForwarding() const final { return false; }
void ComputeMatrix(OpKernelContext* context, const ConstMatrixMaps& inputs,
MatrixMaps* outputs) final {
const ConstMatrixMap& matrix = inputs[0];
const ConstMatrixMap& rhs = inputs[1];
MatrixMap& output = outputs->at(0);
if (matrix.rows() == 0 || rhs.cols() == 0) {
// To be consistent with the MatrixInverse op, we define the solution for
// an empty set of equation as the empty matrix.
return;
}
auto matrix_ptr = AsDeviceMemory(matrix.data());
auto rhs_ptr = AsDeviceMemory(rhs.data());
auto out_ptr = AsDeviceMemory(output.data());
auto* stream = context->op_device_context()->stream();
uint64 rhs_elems = rhs.rows() * rhs.cols();
bool copy_status =
stream->ThenMemcpyD2D(&out_ptr, rhs_ptr, sizeof(Scalar) * rhs_elems)
.ok();
if (!copy_status) {
context->SetStatus(
errors::Internal("Failed to copy rhs into output before solve"));
}
// Cublas does
// output = matrix \ rhs
// where matrix, rhs and output are assumed to be in column major.
// We want the output to be in row-major, so we can compute
// output' = rhs' / matrix' (' stands for transpose)
// Upper/lower needs to be swapped for this.
se::blas::UpperLower upper_lower_matrix;
se::blas::Transpose transpose_matrix;
if (lower_) {
upper_lower_matrix = se::blas::UpperLower::kUpper;
} else {
upper_lower_matrix = se::blas::UpperLower::kLower;
}
if (adjoint_) {
transpose_matrix = se::blas::Transpose::kConjugateTranspose;
} else {
transpose_matrix = se::blas::Transpose::kNoTranspose;
}
uint64 leading_dim_matrix = matrix.cols();
uint64 leading_dim_output = output.cols();
uint64 colmajor_rows = output.cols();
uint64 colmajor_cols = output.rows();
bool blas_launch_status =
stream
->ThenBlasTrsm(
se::blas::Side::kRight /*side*/, upper_lower_matrix /*uplo*/,
transpose_matrix /*trans*/,
se::blas::Diagonal::kNonUnit /*diag*/, colmajor_rows /*m*/,
colmajor_cols /*n*/, Scalar(1.0) /*alpha*/, matrix_ptr,
leading_dim_matrix /*lda*/, &out_ptr,
leading_dim_output /*ldb*/)
.ok();
if (!blas_launch_status) {
context->SetStatus(errors::Internal("Blas TRSM launch failed"));
}
}
private:
bool lower_;
bool adjoint_;
TF_DISALLOW_COPY_AND_ASSIGN(MatrixTriangularSolveOpGPU);
};
REGISTER_LINALG_OP_GPU("MatrixTriangularSolve",
(MatrixTriangularSolveOpGPU<float>), float);
REGISTER_LINALG_OP_GPU("MatrixTriangularSolve",
(MatrixTriangularSolveOpGPU<double>), double);
REGISTER_LINALG_OP_GPU("MatrixTriangularSolve",
(MatrixTriangularSolveOpGPU<complex64>), complex64);
REGISTER_LINALG_OP_GPU("MatrixTriangularSolve",
(MatrixTriangularSolveOpGPU<complex128>), complex128);
REGISTER_LINALG_OP_GPU("BatchMatrixTriangularSolve",
(MatrixTriangularSolveOpGPU<float>), float);
REGISTER_LINALG_OP_GPU("BatchMatrixTriangularSolve",
(MatrixTriangularSolveOpGPU<double>), double);
#endif // GOOGLE_CUDA || TENSORFLOW_USE_ROCM
} // namespace tensorflow
<|endoftext|> |
<commit_before>// Copyright Toru Niina 2019.
// Distributed under the MIT License.
#ifndef TOML11_LITERAL_HPP
#define TOML11_LITERAL_HPP
#include "parser.hpp"
namespace toml
{
inline namespace literals
{
inline namespace toml_literals
{
inline ::toml::value operator"" _toml(const char* str, std::size_t len)
{
::toml::detail::location<std::vector<char>>
loc(/* filename = */ std::string("TOML literal encoded in a C++ code"),
/* contents = */ std::vector<char>(str, str + len));
// if there are some comments or empty lines, skip them.
using skip_line = ::toml::detail::repeat<toml::detail::sequence<
::toml::detail::maybe<::toml::detail::lex_ws>,
::toml::detail::maybe<::toml::detail::lex_comment>,
::toml::detail::lex_newline
>, ::toml::detail::at_least<1>>;
skip_line::invoke(loc);
// if there are some whitespaces before a value, skip them.
using skip_ws = ::toml::detail::repeat<
::toml::detail::lex_ws, ::toml::detail::at_least<1>>;
skip_ws::invoke(loc);
// to distinguish arrays and tables, first check it is a table or not.
//
// "[1,2,3]"_toml; // this is an array
// "[table]"_toml; // a table that has an empty table named "table" inside.
// "[[1,2,3]]"_toml; // this is an array of arrays
// "[[table]]"_toml; // this is a table that has an array of tables inside.
//
// "[[1]]"_toml; // this can be both... (currently it becomes a table)
// "1 = [{}]"_toml; // this is a table that has an array of table named 1.
// "[[1,]]"_toml; // this is an array of arrays.
// "[[1],]"_toml; // this also.
const auto the_front = loc.iter();
const bool is_table_key = ::toml::detail::lex_std_table::invoke(loc);
loc.reset(the_front);
const bool is_aots_key = ::toml::detail::lex_array_table::invoke(loc);
loc.reset(the_front);
// If it is neither a table-key or a array-of-table-key, it may be a value.
if(!is_table_key && !is_aots_key)
{
if(auto data = ::toml::detail::parse_value<::toml::value>(loc))
{
return data.unwrap();
}
}
// Note that still it can be a table, because the literal might be something
// like the following.
// ```cpp
// R"( // c++11 raw string literals
// key = "value"
// int = 42
// )"_toml;
// ```
// It is a valid toml file.
// It should be parsed as if we parse a file with this content.
if(auto data = ::toml::detail::parse_toml_file<::toml::value>(loc))
{
// TODO later I need to move this logic to parse_toml_file
// loc.reset(loc.begin()); // rollback to the top of the literal
// // skip needless characters for error message
// skip_line::invoke(loc); // skip the first several needless lines
// skip_ws::invoke(loc); // skip the first several needless whitespaces
return data.unwrap();
}
else // none of them.
{
throw ::toml::syntax_error(data.unwrap_err());
}
}
} // toml_literals
} // literals
} // toml
#endif//TOML11_LITERAL_HPP
<commit_msg>refactor: remove needless code snippet<commit_after>// Copyright Toru Niina 2019.
// Distributed under the MIT License.
#ifndef TOML11_LITERAL_HPP
#define TOML11_LITERAL_HPP
#include "parser.hpp"
namespace toml
{
inline namespace literals
{
inline namespace toml_literals
{
inline ::toml::value operator"" _toml(const char* str, std::size_t len)
{
::toml::detail::location<std::vector<char>>
loc(/* filename = */ std::string("TOML literal encoded in a C++ code"),
/* contents = */ std::vector<char>(str, str + len));
// if there are some comments or empty lines, skip them.
using skip_line = ::toml::detail::repeat<toml::detail::sequence<
::toml::detail::maybe<::toml::detail::lex_ws>,
::toml::detail::maybe<::toml::detail::lex_comment>,
::toml::detail::lex_newline
>, ::toml::detail::at_least<1>>;
skip_line::invoke(loc);
// if there are some whitespaces before a value, skip them.
using skip_ws = ::toml::detail::repeat<
::toml::detail::lex_ws, ::toml::detail::at_least<1>>;
skip_ws::invoke(loc);
// to distinguish arrays and tables, first check it is a table or not.
//
// "[1,2,3]"_toml; // this is an array
// "[table]"_toml; // a table that has an empty table named "table" inside.
// "[[1,2,3]]"_toml; // this is an array of arrays
// "[[table]]"_toml; // this is a table that has an array of tables inside.
//
// "[[1]]"_toml; // this can be both... (currently it becomes a table)
// "1 = [{}]"_toml; // this is a table that has an array of table named 1.
// "[[1,]]"_toml; // this is an array of arrays.
// "[[1],]"_toml; // this also.
const auto the_front = loc.iter();
const bool is_table_key = ::toml::detail::lex_std_table::invoke(loc);
loc.reset(the_front);
const bool is_aots_key = ::toml::detail::lex_array_table::invoke(loc);
loc.reset(the_front);
// If it is neither a table-key or a array-of-table-key, it may be a value.
if(!is_table_key && !is_aots_key)
{
if(auto data = ::toml::detail::parse_value<::toml::value>(loc))
{
return data.unwrap();
}
}
// Note that still it can be a table, because the literal might be something
// like the following.
// ```cpp
// R"( // c++11 raw string literals
// key = "value"
// int = 42
// )"_toml;
// ```
// It is a valid toml file.
// It should be parsed as if we parse a file with this content.
if(auto data = ::toml::detail::parse_toml_file<::toml::value>(loc))
{
return data.unwrap();
}
else // none of them.
{
throw ::toml::syntax_error(data.unwrap_err());
}
}
} // toml_literals
} // literals
} // toml
#endif//TOML11_LITERAL_HPP
<|endoftext|> |
<commit_before>/*
<one line to give the program's name and a brief idea of what it does.>
Copyright (C) <year> <name of author>
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include "keyboardinputcomponent.h"
#include "input/inputdetection.h"
#include <QtCore/QEvent>
#include <core/debughelper.h>
REGISTER_OBJECTTYPE(GluonEngine,KeyboardInputComponent);
using namespace GluonEngine;
KeyboardInputComponent::KeyboardInputComponent(QObject* parent)
: Component(parent)
{
m_actionHeld = false;
m_actionStarted = false;
m_actionStopped = false;
m_keyCode = Key_Space;
}
void
KeyboardInputComponent::start()
{
DEBUG_FUNC_NAME
foreach(const GluonInput::InputDevice *input, GluonInput::InputDetection::instance()->keyboardList())
{
DEBUG_TEXT(QString("Enabling input for device: %1").arg(input->deviceName()));
connect(input, SIGNAL(eventSent(GluonInput::InputEvent*)), this, SLOT(inputEvent(GluonInput::InputEvent*)));
connect(input, SIGNAL(buttonPressed(int)), this, SLOT(buttonPressed(int)));
}
GluonEngine::Component::start();
}
void
KeyboardInputComponent::update(int elapsedMilliseconds)
{
if (m_actionStarted)
m_actionStarted = false;
if (m_actionStopped)
{
m_actionStopped = false;
m_actionHeld = false;
}
/* if ( (m_distanceMovement == QVector3D(0,0,0)) && m_actionHeld )
m_actionStopped = true;
m_lastFrame = m_distanceMovement;
m_distanceMovement = QVector3D(0,0,0);
m_axisMovement = 0;*/
}
void KeyboardInputComponent::stop()
{
disconnect(this, SLOT(inputEvent(GluonInput::InputEvent*)));
GluonEngine::Component::stop();
}
void
KeyboardInputComponent::inputEvent(GluonInput::InputEvent *inputEvent)
{
DEBUG_FUNC_NAME
if(inputEvent->code() == m_keyCode)
{
if(inputEvent->value() == 0)
{
m_actionStopped = true;
}
else if(inputEvent->value() == 1)
{
m_actionStarted = true;
m_actionHeld = true;
}
}
}
void KeyboardInputComponent::buttonPressed(int key)
{
DEBUG_FUNC_NAME
DEBUG_TEXT(QString("Key %1 was pressed.").arg(key));
}
bool
KeyboardInputComponent::isActionStarted()
{
return m_actionStarted;
}
bool
KeyboardInputComponent::isActionHeld()
{
return m_actionHeld;
}
bool
KeyboardInputComponent::isActionStopped()
{
return m_actionStopped;
}
KeyboardInputComponent::KeyName
KeyboardInputComponent::keyCode() const
{
return m_keyCode;
}
void
KeyboardInputComponent::setKeyCode(const KeyName& newKeyCode)
{
m_keyCode = newKeyCode;
}
// QVector3D
// KeyboardInputComponent::getDistanceMovement(const QString &actionName)
// {
// return m_distanceMovement;
// }
//
// float
// KeyboardInputComponent::getAxisMovement(const QString &actionName)
// {
// return m_distanceMovement.length();
// }
Q_EXPORT_PLUGIN2(gluon_component_keyboardinput, GluonEngine::KeyboardInputComponent);
#include "keyboardinputcomponent.moc"
<commit_msg>Remove debug output<commit_after>/*
<one line to give the program's name and a brief idea of what it does.>
Copyright (C) <year> <name of author>
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include "keyboardinputcomponent.h"
#include "input/inputdetection.h"
#include <QtCore/QEvent>
#include <core/debughelper.h>
REGISTER_OBJECTTYPE(GluonEngine,KeyboardInputComponent);
using namespace GluonEngine;
KeyboardInputComponent::KeyboardInputComponent(QObject* parent)
: Component(parent)
{
m_actionHeld = false;
m_actionStarted = false;
m_actionStopped = false;
m_keyCode = Key_Space;
}
void
KeyboardInputComponent::start()
{
foreach(const GluonInput::InputDevice *input, GluonInput::InputDetection::instance()->keyboardList())
{
connect(input, SIGNAL(eventSent(GluonInput::InputEvent*)), this, SLOT(inputEvent(GluonInput::InputEvent*)));
connect(input, SIGNAL(buttonPressed(int)), this, SLOT(buttonPressed(int)));
}
GluonEngine::Component::start();
}
void
KeyboardInputComponent::update(int elapsedMilliseconds)
{
if (m_actionStarted)
m_actionStarted = false;
if (m_actionStopped)
{
m_actionStopped = false;
m_actionHeld = false;
}
/* if ( (m_distanceMovement == QVector3D(0,0,0)) && m_actionHeld )
m_actionStopped = true;
m_lastFrame = m_distanceMovement;
m_distanceMovement = QVector3D(0,0,0);
m_axisMovement = 0;*/
}
void KeyboardInputComponent::stop()
{
disconnect(this, SLOT(inputEvent(GluonInput::InputEvent*)));
GluonEngine::Component::stop();
}
void
KeyboardInputComponent::inputEvent(GluonInput::InputEvent *inputEvent)
{
if(inputEvent->code() == m_keyCode)
{
if(inputEvent->value() == 0)
{
m_actionStopped = true;
}
else if(inputEvent->value() == 1)
{
m_actionStarted = true;
m_actionHeld = true;
}
}
}
void KeyboardInputComponent::buttonPressed(int key)
{
DEBUG_FUNC_NAME
DEBUG_TEXT(QString("Key %1 was pressed.").arg(key));
}
bool
KeyboardInputComponent::isActionStarted()
{
return m_actionStarted;
}
bool
KeyboardInputComponent::isActionHeld()
{
return m_actionHeld;
}
bool
KeyboardInputComponent::isActionStopped()
{
return m_actionStopped;
}
KeyboardInputComponent::KeyName
KeyboardInputComponent::keyCode() const
{
return m_keyCode;
}
void
KeyboardInputComponent::setKeyCode(const KeyName& newKeyCode)
{
m_keyCode = newKeyCode;
}
// QVector3D
// KeyboardInputComponent::getDistanceMovement(const QString &actionName)
// {
// return m_distanceMovement;
// }
//
// float
// KeyboardInputComponent::getAxisMovement(const QString &actionName)
// {
// return m_distanceMovement.length();
// }
Q_EXPORT_PLUGIN2(gluon_component_keyboardinput, GluonEngine::KeyboardInputComponent);
#include "keyboardinputcomponent.moc"
<|endoftext|> |
<commit_before>/*!
* \file painter_clip_equations.hpp
* \brief file painter_clip_equations.hpp
*
* Copyright 2016 by Intel.
*
* Contact: kevin.rogovin@intel.com
*
* This Source Code Form is subject to the
* terms of the Mozilla Public License, v. 2.0.
* If a copy of the MPL was not distributed with
* this file, You can obtain one at
* http://mozilla.org/MPL/2.0/.
*
* \author Kevin Rogovin <kevin.rogovin@intel.com>
*
*/
#pragma once
#include <fastuidraw/util/util.hpp>
#include <fastuidraw/util/vecN.hpp>
#include <fastuidraw/util/c_array.hpp>
namespace fastuidraw
{
/*!\addtogroup PainterPacker
* @{
*/
/*!
* \brief
* A PainterClipEquations stores the clip equation for
* PainterPacker.
*
* Each vec3 gives a clip equation in
* 3D API clip coordinats (i.e. after PainterItemMatrix
* transformation is applied) as dot(clip_vector, p) >= 0.
*/
class PainterClipEquations
{
public:
/*!
* \brief
* Enumeration that provides offsets for the
* elements of the clip equation offsets
* (clip_equations_offset)
*/
enum clip_equations_data_offset_t
{
clip0_coeff_x, /*!< offset to x-coefficient for clip equation 0 (i.e. m_clip_equations[0].x) */
clip0_coeff_y, /*!< offset to y-coefficient for clip equation 0 (i.e. m_clip_equations[0].y) */
clip0_coeff_w, /*!< offset to w-coefficient for clip equation 0 (i.e. m_clip_equations[0].z) */
clip1_coeff_x, /*!< offset to x-coefficient for clip equation 1 (i.e. m_clip_equations[1].x) */
clip1_coeff_y, /*!< offset to y-coefficient for clip equation 1 (i.e. m_clip_equations[1].y) */
clip1_coeff_w, /*!< offset to w-coefficient for clip equation 1 (i.e. m_clip_equations[1].z) */
clip2_coeff_x, /*!< offset to x-coefficient for clip equation 2 (i.e. m_clip_equations[2].x) */
clip2_coeff_y, /*!< offset to y-coefficient for clip equation 2 (i.e. m_clip_equations[2].y) */
clip2_coeff_w, /*!< offset to w-coefficient for clip equation 2 (i.e. m_clip_equations[2].z) */
clip3_coeff_x, /*!< offset to x-coefficient for clip equation 3 (i.e. m_clip_equations[3].x) */
clip3_coeff_y, /*!< offset to y-coefficient for clip equation 3 (i.e. m_clip_equations[3].y) */
clip3_coeff_w, /*!< offset to w-coefficient for clip equation 3 (i.e. m_clip_equations[3].z) */
clip_data_size /*!< number of elements for clip equations */
};
/*!
* Ctor, initializes all clip equations as \f$ z \geq 0\f$
*/
PainterClipEquations(void):
m_clip_equations(vec3(0.0f, 0.0f, 1.0f))
{}
/*!
* Pack the values of this ClipEquations
* \param dst place to which to pack data
*/
void
pack_data(c_array<generic_data> dst) const;
/*!
* Returns the length of the data needed to encode the data.
* Data is padded to be multiple of 4.
*/
unsigned int
data_size(void) const
{
return FASTUIDRAW_ROUND_UP_MULTIPLE_OF4(clip_data_size);
}
/*!
* Each element of m_clip_equations specifies a
* clipping plane in 3D API clip-space as
* \code
* dot(m_clip_equations[i], p) >= 0
* \endcode
*/
vecN<vec3, 4> m_clip_equations;
};
/*! @} */
} //namespace fastuidraw
<commit_msg>fastuidraw/painter/packing/painter_clip_equations: fix doxytag group<commit_after>/*!
* \file painter_clip_equations.hpp
* \brief file painter_clip_equations.hpp
*
* Copyright 2016 by Intel.
*
* Contact: kevin.rogovin@intel.com
*
* This Source Code Form is subject to the
* terms of the Mozilla Public License, v. 2.0.
* If a copy of the MPL was not distributed with
* this file, You can obtain one at
* http://mozilla.org/MPL/2.0/.
*
* \author Kevin Rogovin <kevin.rogovin@intel.com>
*
*/
#pragma once
#include <fastuidraw/util/util.hpp>
#include <fastuidraw/util/vecN.hpp>
#include <fastuidraw/util/c_array.hpp>
namespace fastuidraw
{
/*!\addtogroup PainterPacking
* @{
*/
/*!
* \brief
* A PainterClipEquations stores the clip equation for
* PainterPacker.
*
* Each vec3 gives a clip equation in
* 3D API clip coordinats (i.e. after PainterItemMatrix
* transformation is applied) as dot(clip_vector, p) >= 0.
*/
class PainterClipEquations
{
public:
/*!
* \brief
* Enumeration that provides offsets for the
* elements of the clip equation offsets
* (clip_equations_offset)
*/
enum clip_equations_data_offset_t
{
clip0_coeff_x, /*!< offset to x-coefficient for clip equation 0 (i.e. m_clip_equations[0].x) */
clip0_coeff_y, /*!< offset to y-coefficient for clip equation 0 (i.e. m_clip_equations[0].y) */
clip0_coeff_w, /*!< offset to w-coefficient for clip equation 0 (i.e. m_clip_equations[0].z) */
clip1_coeff_x, /*!< offset to x-coefficient for clip equation 1 (i.e. m_clip_equations[1].x) */
clip1_coeff_y, /*!< offset to y-coefficient for clip equation 1 (i.e. m_clip_equations[1].y) */
clip1_coeff_w, /*!< offset to w-coefficient for clip equation 1 (i.e. m_clip_equations[1].z) */
clip2_coeff_x, /*!< offset to x-coefficient for clip equation 2 (i.e. m_clip_equations[2].x) */
clip2_coeff_y, /*!< offset to y-coefficient for clip equation 2 (i.e. m_clip_equations[2].y) */
clip2_coeff_w, /*!< offset to w-coefficient for clip equation 2 (i.e. m_clip_equations[2].z) */
clip3_coeff_x, /*!< offset to x-coefficient for clip equation 3 (i.e. m_clip_equations[3].x) */
clip3_coeff_y, /*!< offset to y-coefficient for clip equation 3 (i.e. m_clip_equations[3].y) */
clip3_coeff_w, /*!< offset to w-coefficient for clip equation 3 (i.e. m_clip_equations[3].z) */
clip_data_size /*!< number of elements for clip equations */
};
/*!
* Ctor, initializes all clip equations as \f$ z \geq 0\f$
*/
PainterClipEquations(void):
m_clip_equations(vec3(0.0f, 0.0f, 1.0f))
{}
/*!
* Pack the values of this ClipEquations
* \param dst place to which to pack data
*/
void
pack_data(c_array<generic_data> dst) const;
/*!
* Returns the length of the data needed to encode the data.
* Data is padded to be multiple of 4.
*/
unsigned int
data_size(void) const
{
return FASTUIDRAW_ROUND_UP_MULTIPLE_OF4(clip_data_size);
}
/*!
* Each element of m_clip_equations specifies a
* clipping plane in 3D API clip-space as
* \code
* dot(m_clip_equations[i], p) >= 0
* \endcode
*/
vecN<vec3, 4> m_clip_equations;
};
/*! @} */
} //namespace fastuidraw
<|endoftext|> |
<commit_before>#include <test/test-models/good/variational/eta_should_be_small.hpp>
#include <stan/variational/advi.hpp>
#include <stan/callbacks/stream_logger.hpp>
#include <gtest/gtest.h>
#include <test/unit/util.hpp>
#include <vector>
#include <string>
#include <iostream>
#include <boost/random/additive_combine.hpp> // L'Ecuyer RNG
#include <boost/version.hpp>
typedef boost::ecuyer1988 rng_t;
class eta_adapt_small_test : public ::testing::Test {
public:
eta_adapt_small_test()
: logger(log_stream_, log_stream_, log_stream_, log_stream_, log_stream_) { }
void SetUp() {
static const std::string DATA = "";
std::stringstream data_stream(DATA);
stan::io::dump data_var_context(data_stream);
model_ = new stan_model(data_var_context, &model_stream_);
cont_params_ = Eigen::VectorXd::Zero(model_->num_params_r());
base_rng_.seed(727802408);
model_stream_.str("");
log_stream_.str("");
advi_meanfield_ = new stan::variational::advi<stan_model, stan::variational::normal_meanfield, rng_t>
(*model_, cont_params_, base_rng_,
1, 100,
100, 1);
advi_fullrank_ = new stan::variational::advi<stan_model, stan::variational::normal_fullrank, rng_t>
(*model_, cont_params_, base_rng_,
1, 100,
100, 1);
}
void TearDown() {
delete advi_meanfield_;
delete advi_fullrank_;
delete model_;
}
stan::variational::advi<stan_model, stan::variational::normal_meanfield, rng_t> *advi_meanfield_;
stan::variational::advi<stan_model, stan::variational::normal_fullrank, rng_t> *advi_fullrank_;
std::stringstream model_stream_;
std::stringstream log_stream_;
stan::callbacks::stream_logger logger;
stan_model *model_;
rng_t base_rng_;
Eigen::VectorXd cont_params_;
};
TEST_F(eta_adapt_small_test, eta_should_be_small) {
stan::variational::normal_meanfield meanfield_init =
stan::variational::normal_meanfield(cont_params_);
stan::variational::normal_fullrank fullrank_init =
stan::variational::normal_fullrank(cont_params_);
#if BOOST_VERSION > 106400
EXPECT_EQ(0.1, advi_meanfield_->adapt_eta(meanfield_init, 1000, logger));
EXPECT_EQ(0.1, advi_fullrank_->adapt_eta(fullrank_init, 1000, logger));
#else
EXPECT_EQ(0.1, advi_meanfield_->adapt_eta(meanfield_init, 50, logger));
EXPECT_EQ(0.1, advi_fullrank_->adapt_eta(fullrank_init, 50, logger));
#endif
}
<commit_msg>boost version ifdef >=, fixes #2446<commit_after>#include <test/test-models/good/variational/eta_should_be_small.hpp>
#include <stan/variational/advi.hpp>
#include <stan/callbacks/stream_logger.hpp>
#include <gtest/gtest.h>
#include <test/unit/util.hpp>
#include <vector>
#include <string>
#include <iostream>
#include <boost/random/additive_combine.hpp> // L'Ecuyer RNG
#include <boost/version.hpp>
typedef boost::ecuyer1988 rng_t;
class eta_adapt_small_test : public ::testing::Test {
public:
eta_adapt_small_test()
: logger(log_stream_, log_stream_, log_stream_, log_stream_, log_stream_) { }
void SetUp() {
static const std::string DATA = "";
std::stringstream data_stream(DATA);
stan::io::dump data_var_context(data_stream);
model_ = new stan_model(data_var_context, &model_stream_);
cont_params_ = Eigen::VectorXd::Zero(model_->num_params_r());
base_rng_.seed(727802408);
model_stream_.str("");
log_stream_.str("");
advi_meanfield_ = new stan::variational::advi<stan_model, stan::variational::normal_meanfield, rng_t>
(*model_, cont_params_, base_rng_,
1, 100,
100, 1);
advi_fullrank_ = new stan::variational::advi<stan_model, stan::variational::normal_fullrank, rng_t>
(*model_, cont_params_, base_rng_,
1, 100,
100, 1);
}
void TearDown() {
delete advi_meanfield_;
delete advi_fullrank_;
delete model_;
}
stan::variational::advi<stan_model, stan::variational::normal_meanfield, rng_t> *advi_meanfield_;
stan::variational::advi<stan_model, stan::variational::normal_fullrank, rng_t> *advi_fullrank_;
std::stringstream model_stream_;
std::stringstream log_stream_;
stan::callbacks::stream_logger logger;
stan_model *model_;
rng_t base_rng_;
Eigen::VectorXd cont_params_;
};
TEST_F(eta_adapt_small_test, eta_should_be_small) {
stan::variational::normal_meanfield meanfield_init =
stan::variational::normal_meanfield(cont_params_);
stan::variational::normal_fullrank fullrank_init =
stan::variational::normal_fullrank(cont_params_);
#if BOOST_VERSION >= 106400
EXPECT_EQ(0.1, advi_meanfield_->adapt_eta(meanfield_init, 1000, logger));
EXPECT_EQ(0.1, advi_fullrank_->adapt_eta(fullrank_init, 1000, logger));
#else
EXPECT_EQ(0.1, advi_meanfield_->adapt_eta(meanfield_init, 50, logger));
EXPECT_EQ(0.1, advi_fullrank_->adapt_eta(fullrank_init, 50, logger));
#endif
}
<|endoftext|> |
<commit_before>// Copyright (c) 2010 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
//
// This file is based on the SMSLib library.
//
// SMSLib Sudden Motion Sensor Access Library
// Copyright (c) 2010 Suitable Systems
// All rights reserved.
//
// Developed by: Daniel Griscom
// Suitable Systems
// http://www.suitable.com
//
// Permission is hereby granted, free of charge, to any person obtaining a
// copy of this software and associated documentation files (the
// "Software"), to deal with 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:
//
// - Redistributions of source code must retain the above copyright notice,
// this list of conditions and the following disclaimers.
//
// - Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimers in the
// documentation and/or other materials provided with the distribution.
//
// - Neither the names of Suitable Systems nor the names of its
// contributors may be used to endorse or promote products derived from
// this Software without specific prior written permission.
//
// 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 CONTRIBUTORS 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 WITH THE SOFTWARE.
//
// For more information about SMSLib, see
// <http://www.suitable.com/tools/smslib.html>
// or contact
// Daniel Griscom
// Suitable Systems
// 1 Centre Street, Suite 204
// Wakefield, MA 01880
// (781) 665-0053
#include "chrome/browser/device_orientation/accelerometer_mac.h"
#include <math.h> // For isfinite.
#include <sys/sysctl.h>
#include "base/logging.h"
#include "base/scoped_ptr.h"
#include "chrome/browser/device_orientation/orientation.h"
namespace device_orientation {
struct AccelerometerMac::GenericMacbookSensor {
// Name of device to be read.
const char* service_name;
// Number of bytes of the axis data.
int axis_size;
// Default calibration value for zero g.
float zero_g;
// Default calibration value for one g (negative when axis is inverted).
float one_g;
// Kernel function index.
unsigned int function;
// Size of the sensor record to be sent/received.
unsigned int record_size;
};
struct AccelerometerMac::AxisData {
// Location of the first byte representing the axis in the sensor data.
int index;
// Axis inversion flag. The value changes often between models.
bool inverted;
};
// Sudden Motion Sensor descriptor.
struct AccelerometerMac::SensorDescriptor {
// Prefix of model to be tested.
const char* model_name;
// Axis-specific data (x,y,z order).
AxisData axis[3];
};
// Typical sensor parameters in MacBook models.
const AccelerometerMac::GenericMacbookSensor
AccelerometerMac::kGenericSensor = {
"SMCMotionSensor", 2,
0, 251,
5, 40
};
// Supported sensor descriptors. Add entries here to enhance compatibility.
// All non-tested entries from SMSLib have been removed.
const AccelerometerMac::SensorDescriptor
AccelerometerMac::kSupportedSensors[] = {
// Tested by leandrogracia on a 15'' MacBook Pro.
{ "MacBookPro2,2", { { 0, true }, { 2, true }, { 4, false } } },
// Tested by leandrogracia on a 15'' MacBook Pro.
{ "MacBookPro3,1", { { 0, false }, { 2, true }, { 4, true } } },
// Tested by leandrogracia on a 15'' MacBook Pro.
{ "MacBookPro4,1", { { 0, true }, { 2, true }, { 4, false } } },
// Tested by leandrogracia on a 15'' MacBook Pro.
{ "MacBookPro5,1", { { 0, false }, { 2, false }, { 4, false } } },
// Tested by leandrogracia on a 15'' MacBook Pro.
{ "MacBookPro5,4", { { 0, false }, { 2, false }, { 4, false } } },
// Tested by leandrogracia on a 13'' MacBook Pro.
{ "MacBookPro5,5", { { 0, true }, { 2, true }, { 4, false } } },
// Tested by leandrogracia on a 15'' MacBook Pro.
{ "MacBookPro6,2", { { 0, true }, { 2, false }, { 4, true } } },
// Tested by leandrogracia on a 13'' MacBook Pro.
{ "MacBookPro7,1", { { 0, true }, { 2, true }, { 4, false } } },
// Generic MacBook accelerometer sensor data.
// Added for compatibility with non-tested models
// Note: there may be problems with inverted axes.
{ "", { { 0, true }, { 2, true }, { 4, false } } }
};
// Create a AccelerometerMac object and return NULL if no valid sensor found.
DataFetcher* AccelerometerMac::Create() {
scoped_ptr<AccelerometerMac> accelerometer(new AccelerometerMac);
return accelerometer->Init() ? accelerometer.release() : NULL;
}
AccelerometerMac::~AccelerometerMac() {
IOServiceClose(io_connection_);
}
AccelerometerMac::AccelerometerMac()
: sensor_(NULL),
io_connection_(0) {
}
// Retrieve per-axis accelerometer values.
//
// Axes and angles are defined according to the W3C DeviceOrientation Draft.
// See here: http://dev.w3.org/geo/api/spec-source-orientation.html
//
// Note: only beta and gamma angles are provided. Alpha is set to zero.
//
// Returns false in case of error or non-properly initialized object.
//
bool AccelerometerMac::GetOrientation(Orientation* orientation) {
DCHECK(sensor_);
// Reset output record memory buffer.
std::fill(output_record_.begin(), output_record_.end(), 0x00);
// Read record data from memory.
const size_t kInputSize = kGenericSensor.record_size;
size_t output_size = kGenericSensor.record_size;
if (IOConnectCallStructMethod(io_connection_, kGenericSensor.function,
static_cast<const char *>(&input_record_[0]), kInputSize,
&output_record_[0], &output_size) != KERN_SUCCESS) {
return false;
}
// Calculate per-axis calibrated values.
float axis_value[3];
for (int i = 0; i < 3; ++i) {
int sensor_value = 0;
int size = kGenericSensor.axis_size;
int index = sensor_->axis[i].index;
// Important Note: little endian is assumed as this code is mac-only
// and PowerPC is currently not supported.
memcpy(&sensor_value, &output_record_[index], size);
sensor_value = ExtendSign(sensor_value, size);
// Correct value using the current calibration.
axis_value[i] = static_cast<float>(sensor_value - kGenericSensor.zero_g) /
kGenericSensor.one_g;
// Make sure we reject any NaN or infinite values.
if (!isfinite(axis_value[i]))
return false;
// Clamp value to the [-1, 1] range.
if (axis_value[i] < -1.0)
axis_value[i] = -1.0;
else if (axis_value[i] > 1.0)
axis_value[i] = 1.0;
// Apply axis inversion.
if (sensor_->axis[i].inverted)
axis_value[i] = -axis_value[i];
}
// Transform the accelerometer values to W3C draft angles.
//
// Accelerometer values are just dot products of the sensor axes
// by the gravity vector 'g' with the result for the z axis inverted.
//
// To understand this transformation calculate the 3rd row of the z-x-y
// Euler angles rotation matrix (because of the 'g' vector, only 3rd row
// affects to the result). Note that z-x-y matrix means R = Ry * Rx * Rz.
// Then, assume alpha = 0 and you get this:
//
// x_acc = sin(gamma)
// y_acc = - cos(gamma) * sin(beta)
// z_acc = cos(beta) * cos(gamma)
//
// After that the rest is just a bit of trigonometry.
//
// Also note that alpha can't be provided but it's assumed to be always zero.
// This is necessary in order to provide enough information to solve
// the equations.
//
const double kRad2deg = 180.0 / M_PI;
orientation->alpha_ = 0.0;
orientation->beta_ = kRad2deg * atan2(-axis_value[1], axis_value[2]);
orientation->gamma_ = kRad2deg * asin(axis_value[0]);
// Make sure that the interval boundaries comply with the specification.
if (orientation->beta_ >= 180.0)
orientation->beta_ -= 360.0;
if (orientation->gamma_ >= 90.0)
orientation->gamma_ -= 180.0;
DCHECK_GE(orientation->beta_, -180.0);
DCHECK_LT(orientation->beta_, 180.0);
DCHECK_GE(orientation->gamma_, -90.0);
DCHECK_LT(orientation->gamma_, 90.0);
orientation->can_provide_alpha_ = false;
orientation->can_provide_beta_ = true;
orientation->can_provide_gamma_ = true;
return true;
}
// Probe the local hardware looking for a supported sensor device
// and initialize an I/O connection to it.
bool AccelerometerMac::Init() {
// Allocate local variables for model name string (size from SMSLib).
static const int kNameSize = 32;
char local_model[kNameSize];
// Request model name to the kernel.
size_t name_size = kNameSize;
int params[2] = { CTL_HW, HW_MODEL };
if (sysctl(params, 2, local_model, &name_size, NULL, 0) != 0)
return NULL;
const SensorDescriptor* sensor_candidate = NULL;
// Look for the current model in the supported sensor list.
io_object_t device = 0;
const int kNumSensors = arraysize(kSupportedSensors);
for (int i = 0; i < kNumSensors; ++i) {
// Check if the supported sensor model name is a prefix
// of the local hardware model (empty names are accepted).
const char* p1 = kSupportedSensors[i].model_name;
for (const char* p2 = local_model; *p1 != '\0' && *p1 == *p2; ++p1, ++p2)
continue;
if (*p1 != '\0')
continue;
// Local hardware found in the supported sensor list.
sensor_candidate = &kSupportedSensors[i];
// Get a dictionary of the services matching to the one in the sensor.
CFMutableDictionaryRef dict =
IOServiceMatching(kGenericSensor.service_name);
if (dict == NULL)
continue;
// Get an iterator for the matching services.
io_iterator_t device_iterator;
if (IOServiceGetMatchingServices(kIOMasterPortDefault, dict,
&device_iterator) != KERN_SUCCESS) {
continue;
}
// Get the first device in the list.
if ((device = IOIteratorNext(device_iterator)) == 0)
continue;
// Try to open device.
kern_return_t result;
result = IOServiceOpen(device, mach_task_self(), 0, &io_connection_);
IOObjectRelease(device);
if (result != KERN_SUCCESS || io_connection_ == 0)
return false;
// Local sensor service confirmed by IOKit.
sensor_ = sensor_candidate;
break;
}
if (sensor_ == NULL)
return false;
// Allocate and initialize input/output records.
input_record_.resize(kGenericSensor.record_size, 0x01);
output_record_.resize(kGenericSensor.record_size, 0x00);
// Try to retrieve the current orientation.
Orientation test_orientation;
return GetOrientation(&test_orientation);
}
// Extend the sign of an integer of less than 32 bits to a 32-bit integer.
int AccelerometerMac::ExtendSign(int value, size_t size) {
switch (size) {
case 1:
if (value & 0x00000080)
return value | 0xffffff00;
break;
case 2:
if (value & 0x00008000)
return value | 0xffff0000;
break;
case 3:
if (value & 0x00800000)
return value | 0xff000000;
break;
default:
LOG(FATAL) << "Invalid integer size for sign extension: " << size;
}
return value;
}
} // namespace device_orientation
<commit_msg>Fix reversed axis on MacBookPro6,1. Verified with user.<commit_after>// Copyright (c) 2010 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
//
// This file is based on the SMSLib library.
//
// SMSLib Sudden Motion Sensor Access Library
// Copyright (c) 2010 Suitable Systems
// All rights reserved.
//
// Developed by: Daniel Griscom
// Suitable Systems
// http://www.suitable.com
//
// Permission is hereby granted, free of charge, to any person obtaining a
// copy of this software and associated documentation files (the
// "Software"), to deal with 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:
//
// - Redistributions of source code must retain the above copyright notice,
// this list of conditions and the following disclaimers.
//
// - Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimers in the
// documentation and/or other materials provided with the distribution.
//
// - Neither the names of Suitable Systems nor the names of its
// contributors may be used to endorse or promote products derived from
// this Software without specific prior written permission.
//
// 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 CONTRIBUTORS 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 WITH THE SOFTWARE.
//
// For more information about SMSLib, see
// <http://www.suitable.com/tools/smslib.html>
// or contact
// Daniel Griscom
// Suitable Systems
// 1 Centre Street, Suite 204
// Wakefield, MA 01880
// (781) 665-0053
#include "chrome/browser/device_orientation/accelerometer_mac.h"
#include <math.h> // For isfinite.
#include <sys/sysctl.h>
#include "base/logging.h"
#include "base/scoped_ptr.h"
#include "chrome/browser/device_orientation/orientation.h"
namespace device_orientation {
struct AccelerometerMac::GenericMacbookSensor {
// Name of device to be read.
const char* service_name;
// Number of bytes of the axis data.
int axis_size;
// Default calibration value for zero g.
float zero_g;
// Default calibration value for one g (negative when axis is inverted).
float one_g;
// Kernel function index.
unsigned int function;
// Size of the sensor record to be sent/received.
unsigned int record_size;
};
struct AccelerometerMac::AxisData {
// Location of the first byte representing the axis in the sensor data.
int index;
// Axis inversion flag. The value changes often between models.
bool inverted;
};
// Sudden Motion Sensor descriptor.
struct AccelerometerMac::SensorDescriptor {
// Prefix of model to be tested.
const char* model_name;
// Axis-specific data (x,y,z order).
AxisData axis[3];
};
// Typical sensor parameters in MacBook models.
const AccelerometerMac::GenericMacbookSensor
AccelerometerMac::kGenericSensor = {
"SMCMotionSensor", 2,
0, 251,
5, 40
};
// Supported sensor descriptors. Add entries here to enhance compatibility.
// All non-tested entries from SMSLib have been removed.
const AccelerometerMac::SensorDescriptor
AccelerometerMac::kSupportedSensors[] = {
// Tested by leandrogracia on a 15'' MacBook Pro.
{ "MacBookPro2,2", { { 0, true }, { 2, true }, { 4, false } } },
// Tested by leandrogracia on a 15'' MacBook Pro.
{ "MacBookPro3,1", { { 0, false }, { 2, true }, { 4, true } } },
// Tested by leandrogracia on a 15'' MacBook Pro.
{ "MacBookPro4,1", { { 0, true }, { 2, true }, { 4, false } } },
// Tested by leandrogracia on a 15'' MacBook Pro.
{ "MacBookPro5,1", { { 0, false }, { 2, false }, { 4, false } } },
// Tested by leandrogracia on a 15'' MacBook Pro.
{ "MacBookPro5,4", { { 0, false }, { 2, false }, { 4, false } } },
// Tested by leandrogracia on a 13'' MacBook Pro.
{ "MacBookPro5,5", { { 0, true }, { 2, true }, { 4, false } } },
// Tested by khom on a 17'' MacBook Pro.
{ "MacBookPro6,1", { { 0, false }, { 2, false }, { 4, false } } },
// Tested by leandrogracia on a 15'' MacBook Pro.
{ "MacBookPro6,2", { { 0, true }, { 2, false }, { 4, true } } },
// Tested by leandrogracia on a 13'' MacBook Pro.
{ "MacBookPro7,1", { { 0, true }, { 2, true }, { 4, false } } },
// Generic MacBook accelerometer sensor data.
// Added for compatibility with non-tested models
// Note: there may be problems with inverted axes.
{ "", { { 0, true }, { 2, true }, { 4, false } } }
};
// Create a AccelerometerMac object and return NULL if no valid sensor found.
DataFetcher* AccelerometerMac::Create() {
scoped_ptr<AccelerometerMac> accelerometer(new AccelerometerMac);
return accelerometer->Init() ? accelerometer.release() : NULL;
}
AccelerometerMac::~AccelerometerMac() {
IOServiceClose(io_connection_);
}
AccelerometerMac::AccelerometerMac()
: sensor_(NULL),
io_connection_(0) {
}
// Retrieve per-axis accelerometer values.
//
// Axes and angles are defined according to the W3C DeviceOrientation Draft.
// See here: http://dev.w3.org/geo/api/spec-source-orientation.html
//
// Note: only beta and gamma angles are provided. Alpha is set to zero.
//
// Returns false in case of error or non-properly initialized object.
//
bool AccelerometerMac::GetOrientation(Orientation* orientation) {
DCHECK(sensor_);
// Reset output record memory buffer.
std::fill(output_record_.begin(), output_record_.end(), 0x00);
// Read record data from memory.
const size_t kInputSize = kGenericSensor.record_size;
size_t output_size = kGenericSensor.record_size;
if (IOConnectCallStructMethod(io_connection_, kGenericSensor.function,
static_cast<const char *>(&input_record_[0]), kInputSize,
&output_record_[0], &output_size) != KERN_SUCCESS) {
return false;
}
// Calculate per-axis calibrated values.
float axis_value[3];
for (int i = 0; i < 3; ++i) {
int sensor_value = 0;
int size = kGenericSensor.axis_size;
int index = sensor_->axis[i].index;
// Important Note: little endian is assumed as this code is mac-only
// and PowerPC is currently not supported.
memcpy(&sensor_value, &output_record_[index], size);
sensor_value = ExtendSign(sensor_value, size);
// Correct value using the current calibration.
axis_value[i] = static_cast<float>(sensor_value - kGenericSensor.zero_g) /
kGenericSensor.one_g;
// Make sure we reject any NaN or infinite values.
if (!isfinite(axis_value[i]))
return false;
// Clamp value to the [-1, 1] range.
if (axis_value[i] < -1.0)
axis_value[i] = -1.0;
else if (axis_value[i] > 1.0)
axis_value[i] = 1.0;
// Apply axis inversion.
if (sensor_->axis[i].inverted)
axis_value[i] = -axis_value[i];
}
// Transform the accelerometer values to W3C draft angles.
//
// Accelerometer values are just dot products of the sensor axes
// by the gravity vector 'g' with the result for the z axis inverted.
//
// To understand this transformation calculate the 3rd row of the z-x-y
// Euler angles rotation matrix (because of the 'g' vector, only 3rd row
// affects to the result). Note that z-x-y matrix means R = Ry * Rx * Rz.
// Then, assume alpha = 0 and you get this:
//
// x_acc = sin(gamma)
// y_acc = - cos(gamma) * sin(beta)
// z_acc = cos(beta) * cos(gamma)
//
// After that the rest is just a bit of trigonometry.
//
// Also note that alpha can't be provided but it's assumed to be always zero.
// This is necessary in order to provide enough information to solve
// the equations.
//
const double kRad2deg = 180.0 / M_PI;
orientation->alpha_ = 0.0;
orientation->beta_ = kRad2deg * atan2(-axis_value[1], axis_value[2]);
orientation->gamma_ = kRad2deg * asin(axis_value[0]);
// Make sure that the interval boundaries comply with the specification.
if (orientation->beta_ >= 180.0)
orientation->beta_ -= 360.0;
if (orientation->gamma_ >= 90.0)
orientation->gamma_ -= 180.0;
DCHECK_GE(orientation->beta_, -180.0);
DCHECK_LT(orientation->beta_, 180.0);
DCHECK_GE(orientation->gamma_, -90.0);
DCHECK_LT(orientation->gamma_, 90.0);
orientation->can_provide_alpha_ = false;
orientation->can_provide_beta_ = true;
orientation->can_provide_gamma_ = true;
return true;
}
// Probe the local hardware looking for a supported sensor device
// and initialize an I/O connection to it.
bool AccelerometerMac::Init() {
// Allocate local variables for model name string (size from SMSLib).
static const int kNameSize = 32;
char local_model[kNameSize];
// Request model name to the kernel.
size_t name_size = kNameSize;
int params[2] = { CTL_HW, HW_MODEL };
if (sysctl(params, 2, local_model, &name_size, NULL, 0) != 0)
return NULL;
const SensorDescriptor* sensor_candidate = NULL;
// Look for the current model in the supported sensor list.
io_object_t device = 0;
const int kNumSensors = arraysize(kSupportedSensors);
for (int i = 0; i < kNumSensors; ++i) {
// Check if the supported sensor model name is a prefix
// of the local hardware model (empty names are accepted).
const char* p1 = kSupportedSensors[i].model_name;
for (const char* p2 = local_model; *p1 != '\0' && *p1 == *p2; ++p1, ++p2)
continue;
if (*p1 != '\0')
continue;
// Local hardware found in the supported sensor list.
sensor_candidate = &kSupportedSensors[i];
// Get a dictionary of the services matching to the one in the sensor.
CFMutableDictionaryRef dict =
IOServiceMatching(kGenericSensor.service_name);
if (dict == NULL)
continue;
// Get an iterator for the matching services.
io_iterator_t device_iterator;
if (IOServiceGetMatchingServices(kIOMasterPortDefault, dict,
&device_iterator) != KERN_SUCCESS) {
continue;
}
// Get the first device in the list.
if ((device = IOIteratorNext(device_iterator)) == 0)
continue;
// Try to open device.
kern_return_t result;
result = IOServiceOpen(device, mach_task_self(), 0, &io_connection_);
IOObjectRelease(device);
if (result != KERN_SUCCESS || io_connection_ == 0)
return false;
// Local sensor service confirmed by IOKit.
sensor_ = sensor_candidate;
break;
}
if (sensor_ == NULL)
return false;
// Allocate and initialize input/output records.
input_record_.resize(kGenericSensor.record_size, 0x01);
output_record_.resize(kGenericSensor.record_size, 0x00);
// Try to retrieve the current orientation.
Orientation test_orientation;
return GetOrientation(&test_orientation);
}
// Extend the sign of an integer of less than 32 bits to a 32-bit integer.
int AccelerometerMac::ExtendSign(int value, size_t size) {
switch (size) {
case 1:
if (value & 0x00000080)
return value | 0xffffff00;
break;
case 2:
if (value & 0x00008000)
return value | 0xffff0000;
break;
case 3:
if (value & 0x00800000)
return value | 0xff000000;
break;
default:
LOG(FATAL) << "Invalid integer size for sign extension: " << size;
}
return value;
}
} // namespace device_orientation
<|endoftext|> |
<commit_before>/* Luwra
* Minimal-overhead Lua wrapper for C++
*
* Copyright (C) 2016, Ole Krüger <ole@vprsm.de>
*/
#ifndef LUWRA_TYPES_TABLE_H_
#define LUWRA_TYPES_TABLE_H_
#include "../common.hpp"
#include "../auxiliary.hpp"
#include "../stack.hpp"
#include "reference.hpp"
#include <utility>
LUWRA_NS_BEGIN
namespace internal {
// This represents a "path" which will be resolved lazily. It is useful for chained table
// access. An access like 'table.field1.field2' would be represented similar to
// `Path<Path<Table, std::string>, std::string> table {{table, "field1"}, "field"}`.
template <typename Parent, typename Key>
struct Path {
Parent parent;
Key key;
// Read the value to which this path points to.
template <typename V> inline
V read(State* state) const {
push(state, *this);
V value = luwra::read<V>(state, -1);
lua_pop(state, 1);
return value;
}
// Change the value to which this path points to.
template <typename V> inline
void write(State* state, V&& value) const {
push(state, parent);
push(state, key);
push(state, std::forward<V>(value));
lua_rawset(state, -3);
lua_pop(state, 1);
}
};
}
template <typename Parent, typename Key>
struct Value<internal::Path<Parent, Key>> {
// Push the value to which the path points onto the stack.
static inline
void push(State* state, const internal::Path<Parent, Key>& accessor) {
luwra::push(state, accessor.parent);
luwra::push(state, accessor.key);
lua_rawget(state, -2);
lua_remove(state, -2);
}
};
namespace internal {
template <typename Accessor>
struct TableAccessor {
State* state;
Accessor accessor;
template <typename Type> inline
Type read() const && {
return accessor.template read<Type>(state);
}
template <typename Type> inline
operator Type() const && {
return accessor.template read<Type>(state);
}
template <typename Type> inline
const TableAccessor&& write(Type&& value) const && {
accessor.write(state, std::forward<Type>(value));
return std::move(*this);
}
template <typename Type> inline
const TableAccessor&& operator =(Type&& value) const && {
accessor.write(state, std::forward<Type>(value));
return std::move(*this);
}
template <typename Key> inline
TableAccessor<Path<Accessor, Key>> access(Key&& subkey) const && {
return TableAccessor<Path<Accessor, Key>> {
state,
Path<Accessor, Key> {
accessor,
std::forward<Key>(subkey)
}
};
}
template <typename Key> inline
TableAccessor<Path<Accessor, Key>> operator [](Key&& subkey) const && {
return TableAccessor<Path<Accessor, Key>> {
state,
Path<Accessor, Key> {
accessor,
std::forward<Key>(subkey)
}
};
}
};
}
template <typename Accessor>
struct Value<internal::TableAccessor<Accessor>> {
static inline
void push(State* state, internal::TableAccessor<Accessor>& ta) {
luwra::push(state, ta.accessor);
}
};
/// Lua table
struct Table {
Reference ref;
/// Create from reference.
Table(const Reference& ref):
ref(ref)
{}
/// Create from table on the stack.
Table(State* state, int index):
ref(state, index, true)
{
luaL_checktype(state, index, LUA_TTABLE);
}
/// Create a new table.
Table(State* state):
Table(state, (lua_newtable(state), -1))
{
lua_pop(state, 1);
}
/// Create a new table with the given fields.
Table(State* state, const MemberMap& fields):
Table(state, (luwra::push(state, fields), -1))
{
lua_pop(state, 1);
}
/// Access a field of the table.
template <typename Key> inline
internal::TableAccessor<internal::Path<const Reference&, Key>> access(Key&& key) const {
return internal::TableAccessor<internal::Path<const Reference&, Key>> {
ref.impl->state,
internal::Path<const Reference&, Key> {
ref,
std::forward<Key>(key)
}
};
}
/// Alias for @ref access
template <typename Key> inline
internal::TableAccessor<internal::Path<const Reference&, Key>> operator [](Key&& key) const {
return access(std::forward<Key>(key));
}
/// Update the fields.
inline
void update(const MemberMap& fields) const {
State* state = ref.impl->state;
push(state, ref);
setFields(state, -1, fields);
lua_pop(state, 1);
}
/// Check if the value associated with a key is not `nil`.
template <typename Key> inline
bool has(Key&& key) const {
State* state = ref.impl->state;
push(state, ref);
push(state, std::forward<Key>(key));
lua_rawget(state, -2);
bool isNil = lua_isnil(state, -1);
lua_pop(state, 2);
return !isNil;
}
/// Update a field.
template <typename Type, typename Key> inline
void set(Key&& key, Type&& value) const {
State* state = ref.impl->state;
push(state, ref);
push(state, std::forward<Key>(key));
push(state, std::forward<Type>(value));
lua_rawset(state, -3);
lua_pop(state, 1);
}
/// Retrieve the value of a field.
template <typename Type, typename Key> inline
Type get(Key&& key) const {
State* state = ref.impl->state;
push(state, ref);
push(state, std::forward<Key>(key));
lua_rawget(state, -2);
Type ret = read<Type>(state, -1);
lua_pop(state, 2);
return ret;
}
};
/// Enables reading/pushing tables
template <>
struct Value<Table> {
static inline
Table read(State* state, int index) {
return {state, index};
}
static inline
void push(State* state, const Table& value) {
value.ref.impl->push(state);
}
};
LUWRA_NS_END
#endif
<commit_msg>Fix table pushing<commit_after>/* Luwra
* Minimal-overhead Lua wrapper for C++
*
* Copyright (C) 2016, Ole Krüger <ole@vprsm.de>
*/
#ifndef LUWRA_TYPES_TABLE_H_
#define LUWRA_TYPES_TABLE_H_
#include "../common.hpp"
#include "../auxiliary.hpp"
#include "../stack.hpp"
#include "reference.hpp"
#include <utility>
LUWRA_NS_BEGIN
namespace internal {
// This represents a "path" which will be resolved lazily. It is useful for chained table
// access. An access like 'table.field1.field2' would be represented similar to
// `Path<Path<Table, std::string>, std::string> table {{table, "field1"}, "field"}`.
template <typename Parent, typename Key>
struct Path {
Parent parent;
Key key;
// Read the value to which this path points to.
template <typename V> inline
V read(State* state) const {
push(state, *this);
V value = luwra::read<V>(state, -1);
lua_pop(state, 1);
return value;
}
// Change the value to which this path points to.
template <typename V> inline
void write(State* state, V&& value) const {
push(state, parent);
push(state, key);
push(state, std::forward<V>(value));
lua_rawset(state, -3);
lua_pop(state, 1);
}
};
}
template <typename Parent, typename Key>
struct Value<internal::Path<Parent, Key>> {
// Push the value to which the path points onto the stack.
static inline
void push(State* state, const internal::Path<Parent, Key>& accessor) {
luwra::push(state, accessor.parent);
luwra::push(state, accessor.key);
lua_rawget(state, -2);
lua_remove(state, -2);
}
};
namespace internal {
template <typename Accessor>
struct TableAccessor {
State* state;
Accessor accessor;
template <typename Type> inline
Type read() const && {
return accessor.template read<Type>(state);
}
template <typename Type> inline
operator Type() const && {
return accessor.template read<Type>(state);
}
template <typename Type> inline
const TableAccessor&& write(Type&& value) const && {
accessor.write(state, std::forward<Type>(value));
return std::move(*this);
}
template <typename Type> inline
const TableAccessor&& operator =(Type&& value) const && {
accessor.write(state, std::forward<Type>(value));
return std::move(*this);
}
template <typename Key> inline
TableAccessor<Path<Accessor, Key>> access(Key&& subkey) const && {
return TableAccessor<Path<Accessor, Key>> {
state,
Path<Accessor, Key> {
accessor,
std::forward<Key>(subkey)
}
};
}
template <typename Key> inline
TableAccessor<Path<Accessor, Key>> operator [](Key&& subkey) const && {
return TableAccessor<Path<Accessor, Key>> {
state,
Path<Accessor, Key> {
accessor,
std::forward<Key>(subkey)
}
};
}
};
}
template <typename Accessor>
struct Value<internal::TableAccessor<Accessor>> {
static inline
void push(State* state, internal::TableAccessor<Accessor>& ta) {
luwra::push(state, ta.accessor);
}
};
/// Lua table
struct Table {
Reference ref;
/// Create from reference.
Table(const Reference& ref):
ref(ref)
{}
/// Create from table on the stack.
Table(State* state, int index):
ref(state, index, true)
{
luaL_checktype(state, index, LUA_TTABLE);
}
/// Create a new table.
Table(State* state):
Table(state, (lua_newtable(state), -1))
{
lua_pop(state, 1);
}
/// Create a new table with the given fields.
Table(State* state, const MemberMap& fields):
Table(state, (luwra::push(state, fields), -1))
{
lua_pop(state, 1);
}
/// Access a field of the table.
template <typename Key> inline
internal::TableAccessor<internal::Path<const Reference&, Key>> access(Key&& key) const {
return internal::TableAccessor<internal::Path<const Reference&, Key>> {
ref.impl->state,
internal::Path<const Reference&, Key> {
ref,
std::forward<Key>(key)
}
};
}
/// Alias for @ref access
template <typename Key> inline
internal::TableAccessor<internal::Path<const Reference&, Key>> operator [](Key&& key) const {
return access(std::forward<Key>(key));
}
/// Update the fields.
inline
void update(const MemberMap& fields) const {
State* state = ref.impl->state;
push(state, ref);
setFields(state, -1, fields);
lua_pop(state, 1);
}
/// Check if the value associated with a key is not `nil`.
template <typename Key> inline
bool has(Key&& key) const {
State* state = ref.impl->state;
push(state, ref);
push(state, std::forward<Key>(key));
lua_rawget(state, -2);
bool isNil = lua_isnil(state, -1);
lua_pop(state, 2);
return !isNil;
}
/// Update a field.
template <typename Type, typename Key> inline
void set(Key&& key, Type&& value) const {
State* state = ref.impl->state;
push(state, ref);
push(state, std::forward<Key>(key));
push(state, std::forward<Type>(value));
lua_rawset(state, -3);
lua_pop(state, 1);
}
/// Retrieve the value of a field.
template <typename Type, typename Key> inline
Type get(Key&& key) const {
State* state = ref.impl->state;
push(state, ref);
push(state, std::forward<Key>(key));
lua_rawget(state, -2);
Type ret = read<Type>(state, -1);
lua_pop(state, 2);
return ret;
}
};
/// Enables reading/pushing tables
template <>
struct Value<Table> {
static inline
Table read(State* state, int index) {
return {state, index};
}
static inline
void push(State* state, const Table& value) {
luwra::push(state, value.ref);
}
};
LUWRA_NS_END
#endif
<|endoftext|> |
<commit_before><commit_msg>From Gerri: Fix problem with checking of a return code found by Isidro Gonzales.<commit_after><|endoftext|> |
<commit_before><commit_msg>Updated simple sample (removed commented code).<commit_after><|endoftext|> |
<commit_before>//===--- MetadataSource.cpp - Swift Metadata Sources for Reflection -------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See http://swift.org/LICENSE.txt for license information
// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
#include "swift/Reflection/MetadataSource.h"
#include <sstream>
using namespace swift;
using namespace reflection;
class PrintMetadataSource
: public MetadataSourceVisitor<PrintMetadataSource, void> {
std::ostream &OS;
unsigned Indent;
std::ostream &indent(unsigned Amount) {
for (unsigned i = 0; i < Amount; ++i)
OS << ' ';
return OS;
}
std::ostream &printHeader(std::string Name) {
indent(Indent) << '(' << Name;
return OS;
}
template<typename T>
std::ostream &printField(std::string name, const T &value) {
if (!name.empty())
OS << " " << name << "=" << value;
else
OS << " " << value;
return OS;
}
void printRec(const MetadataSource *MS) {
OS << "\n";
Indent += 2;
visit(MS);
Indent -= 2;
}
void closeForm() {
OS << ')';
}
public:
PrintMetadataSource(std::ostream &OS, unsigned Indent)
: OS(OS), Indent(Indent) {}
void
visitClosureBindingMetadataSource(const ClosureBindingMetadataSource *CB) {
printHeader("closure-binding");
printField("index", CB->getIndex());
closeForm();
}
void
visitReferenceCaptureMetadataSource(const ReferenceCaptureMetadataSource *RC){
printHeader("reference-capture");
printField("index", RC->getIndex());
closeForm();
}
void
visitMetadataCaptureMetadataSource(const MetadataCaptureMetadataSource *MC){
printHeader("metadata-capture");
printField("index", MC->getIndex());
closeForm();
}
void
visitGenericArgumentMetadataSource(const GenericArgumentMetadataSource *GA) {
printHeader("generic-argument");
printField("index", GA->getIndex());
printRec(GA->getSource());
closeForm();
}
void
visitParentMetadataSource(const ParentMetadataSource *P) {
printHeader("parent-of");
printRec(P->getChild());
closeForm();
}
void visitSelfMetadataSource(const SelfMetadataSource *S) {
printHeader("self");
closeForm();
}
void
visitSelfWitnessTableMetadataSource(const SelfWitnessTableMetadataSource *W) {
printHeader("self-witness-table");
closeForm();
}
};
void MetadataSource::dump() const {
dump(std::cerr, 0);
}
void MetadataSource::dump(std::ostream &OS, unsigned Indent) const {
PrintMetadataSource(OS, Indent).visit(this);
OS << std::endl;
}
<commit_msg>Reflection: Use _ instead of - as word separator in metadata source s-expression output<commit_after>//===--- MetadataSource.cpp - Swift Metadata Sources for Reflection -------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See http://swift.org/LICENSE.txt for license information
// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
#include "swift/Reflection/MetadataSource.h"
#include <sstream>
using namespace swift;
using namespace reflection;
class PrintMetadataSource
: public MetadataSourceVisitor<PrintMetadataSource, void> {
std::ostream &OS;
unsigned Indent;
std::ostream &indent(unsigned Amount) {
for (unsigned i = 0; i < Amount; ++i)
OS << ' ';
return OS;
}
std::ostream &printHeader(std::string Name) {
indent(Indent) << '(' << Name;
return OS;
}
template<typename T>
std::ostream &printField(std::string name, const T &value) {
if (!name.empty())
OS << " " << name << "=" << value;
else
OS << " " << value;
return OS;
}
void printRec(const MetadataSource *MS) {
OS << "\n";
Indent += 2;
visit(MS);
Indent -= 2;
}
void closeForm() {
OS << ')';
}
public:
PrintMetadataSource(std::ostream &OS, unsigned Indent)
: OS(OS), Indent(Indent) {}
void
visitClosureBindingMetadataSource(const ClosureBindingMetadataSource *CB) {
printHeader("closure_binding");
printField("index", CB->getIndex());
closeForm();
}
void
visitReferenceCaptureMetadataSource(const ReferenceCaptureMetadataSource *RC){
printHeader("reference_capture");
printField("index", RC->getIndex());
closeForm();
}
void
visitMetadataCaptureMetadataSource(const MetadataCaptureMetadataSource *MC){
printHeader("metadata_capture");
printField("index", MC->getIndex());
closeForm();
}
void
visitGenericArgumentMetadataSource(const GenericArgumentMetadataSource *GA) {
printHeader("generic_argument");
printField("index", GA->getIndex());
printRec(GA->getSource());
closeForm();
}
void
visitParentMetadataSource(const ParentMetadataSource *P) {
printHeader("parent_of");
printRec(P->getChild());
closeForm();
}
void visitSelfMetadataSource(const SelfMetadataSource *S) {
printHeader("self");
closeForm();
}
void
visitSelfWitnessTableMetadataSource(const SelfWitnessTableMetadataSource *W) {
printHeader("self_witness_table");
closeForm();
}
};
void MetadataSource::dump() const {
dump(std::cerr, 0);
}
void MetadataSource::dump(std::ostream &OS, unsigned Indent) const {
PrintMetadataSource(OS, Indent).visit(this);
OS << std::endl;
}
<|endoftext|> |
<commit_before><commit_msg>Fix wrong API call<commit_after><|endoftext|> |
<commit_before>/****************************************************************************
**
** Copyright (C) 2016 The Qt Company Ltd.
** Contact: https://www.qt.io/licensing/
**
** This file is part of Qbs.
**
** $QT_BEGIN_LICENSE:GPL-EXCEPT$
** Commercial License Usage
** Licensees holding valid commercial Qt licenses may use this file in
** accordance with the commercial license agreement provided with the
** Software or, alternatively, in accordance with the terms contained in
** a written agreement between you and The Qt Company. For licensing terms
** and conditions see https://www.qt.io/terms-conditions. For further
** information use the contact form at https://www.qt.io/contact-us.
**
** GNU General Public License Usage
** Alternatively, this file may be used under the terms of the GNU
** General Public License version 3 as published by the Free Software
** Foundation with exceptions as appearing in the file LICENSE.GPL3-EXCEPT
** included in the packaging of this file. Please review the following
** information to ensure the GNU General Public License requirements will
** be met: https://www.gnu.org/licenses/gpl-3.0.html.
**
** $QT_END_LICENSE$
**
****************************************************************************/
#include <fstream>
#include <iostream>
#include <string>
int main(int argc, char *argv[])
{
if (argc != 1)
return 1;
std::string s = argv[0];
std::ifstream in(s.substr(0, s.find_last_of("/")) + "/../share/main.cpp");
std::string str((std::istreambuf_iterator<char>(in)),
std::istreambuf_iterator<char>());
std::cout << str << std::endl;
return 0;
}
<commit_msg>More compilation fixes for localDeployment() autotest<commit_after>/****************************************************************************
**
** Copyright (C) 2016 The Qt Company Ltd.
** Contact: https://www.qt.io/licensing/
**
** This file is part of Qbs.
**
** $QT_BEGIN_LICENSE:GPL-EXCEPT$
** Commercial License Usage
** Licensees holding valid commercial Qt licenses may use this file in
** accordance with the commercial license agreement provided with the
** Software or, alternatively, in accordance with the terms contained in
** a written agreement between you and The Qt Company. For licensing terms
** and conditions see https://www.qt.io/terms-conditions. For further
** information use the contact form at https://www.qt.io/contact-us.
**
** GNU General Public License Usage
** Alternatively, this file may be used under the terms of the GNU
** General Public License version 3 as published by the Free Software
** Foundation with exceptions as appearing in the file LICENSE.GPL3-EXCEPT
** included in the packaging of this file. Please review the following
** information to ensure the GNU General Public License requirements will
** be met: https://www.gnu.org/licenses/gpl-3.0.html.
**
** $QT_END_LICENSE$
**
****************************************************************************/
#include <fstream>
#include <iostream>
#include <string>
int main(int argc, char *argv[])
{
if (argc != 1)
return 1;
std::string s = argv[0];
std::ifstream in(std::string(s.substr(0, s.find_last_of("/")) + "/../share/main.cpp").c_str());
std::string str((std::istreambuf_iterator<char>(in)),
std::istreambuf_iterator<char>());
std::cout << str << std::endl;
return 0;
}
<|endoftext|> |
<commit_before>// @(#)root/thread:$Id$
// Authors: Enric Tejedor CERN 12/09/2016
// Philippe Canal FNAL 12/09/2016
/*************************************************************************
* Copyright (C) 1995-2016, Rene Brun and Fons Rademakers. *
* All rights reserved. *
* *
* For the licensing terms see $ROOTSYS/LICENSE. *
* For the list of contributors see $ROOTSYS/README/CREDITS. *
*************************************************************************/
/** \class TReentrantRWLock
\brief An implementation of a reentrant read-write lock with a
configurable internal mutex/lock (default Spin Lock).
This class provides an implementation of a reentrant read-write lock
that uses an internal lock and a condition variable to synchronize
readers and writers when necessary.
The implementation allows a single reader to take the write lock without
releasing the reader lock. It also allows the writer to take a read lock.
In other word, the lock is re-entrant for both reading and writing.
The implementation tries to make faster the scenario when readers come
and go but there is no writer. In that case, readers will not pay the
price of taking the internal spin lock.
Moreover, this RW lock tries to be fair with writers, giving them the
possibility to claim the lock and wait for only the remaining readers,
thus preventing starvation.
*/
#include "ROOT/TReentrantRWLock.hxx"
#include "ROOT/TSpinMutex.hxx"
#include "TMutex.h"
#include "TError.h"
#include <assert.h>
using namespace ROOT;
#ifdef NDEBUG
# define R__MAYBE_AssertReadCountLocIsFromCurrentThread(READERSCOUNTLOC)
#else
# define R__MAYBE_AssertReadCountLocIsFromCurrentThread(READERSCOUNTLOC) \
AssertReadCountLocIsFromCurrentThread(READERSCOUNTLOC)
#endif
Internal::UniqueLockRecurseCount::UniqueLockRecurseCount()
{
static bool singleton = false;
if (singleton) {
::Fatal("UniqueLockRecurseCount Ctor", "Only one TReentrantRWLock using a UniqueLockRecurseCount is allowed.");
}
singleton = true;
}
////////////////////////////////////////////////////////////////////////////
/// Acquire the lock in read mode.
template <typename MutexT, typename RecurseCountsT>
TVirtualRWMutex::Hint_t *TReentrantRWLock<MutexT, RecurseCountsT>::ReadLock()
{
++fReaderReservation;
// if (fReaders == std::numeric_limits<decltype(fReaders)>::max()) {
// ::Fatal("TRWSpinLock::WriteLock", "Too many recursions in TRWSpinLock!");
// }
auto local = fRecurseCounts.GetLocal();
TVirtualRWMutex::Hint_t *hint = nullptr;
if (!fWriter) {
// There is no writer, go freely to the critical section
++fReaders;
--fReaderReservation;
hint = fRecurseCounts.IncrementReadCount(local, fMutex);
} else if (fRecurseCounts.IsCurrentWriter(local)) {
--fReaderReservation;
// This can run concurrently with another thread trying to get
// the read lock and ending up in the next section ("Wait for writers, if any")
// which need to also get the local readers count and thus can
// modify the map.
hint = fRecurseCounts.IncrementReadCount(local, fMutex);
++fReaders;
} else {
// A writer claimed the RW lock, we will need to wait on the
// internal lock
--fReaderReservation;
std::unique_lock<MutexT> lock(fMutex);
// Wait for writers, if any
if (fWriter && fRecurseCounts.IsNotCurrentWriter(local)) {
auto readerCount = fRecurseCounts.GetLocalReadersCount(local);
if (readerCount == 0)
fCond.wait(lock, [this] { return !fWriter; });
// else
// There is a writer **but** we have outstanding readers
// locks, this must mean that the writer is actually
// waiting on this thread to release its read locks.
// This can be done in only two ways:
// * request the writer lock
// * release the reader lock
// Either way, this thread needs to proceed to
// be able to reach a point whether it does one
// of the two.
}
hint = fRecurseCounts.IncrementReadCount(local);
// This RW lock now belongs to the readers
++fReaders;
lock.unlock();
}
return hint;
}
//////////////////////////////////////////////////////////////////////////
/// Release the lock in read mode.
template <typename MutexT, typename RecurseCountsT>
void TReentrantRWLock<MutexT, RecurseCountsT>::ReadUnLock(TVirtualRWMutex::Hint_t *hint)
{
size_t *localReaderCount;
if (!hint) {
// This should be very rare.
auto local = fRecurseCounts.GetLocal();
std::lock_guard<MutexT> lock(fMutex);
localReaderCount = &(fRecurseCounts.GetLocalReadersCount(local));
} else {
localReaderCount = reinterpret_cast<size_t*>(hint);
}
--fReaders;
if (fWriterReservation && fReaders == 0) {
// We still need to lock here to prevent interleaving with a writer
std::lock_guard<MutexT> lock(fMutex);
--(*localReaderCount);
// Make sure you wake up a writer, if any
// Note: spurrious wakeups are okay, fReaders
// will be checked again in WriteLock
fCond.notify_all();
} else {
--(*localReaderCount);
}
}
//////////////////////////////////////////////////////////////////////////
/// Acquire the lock in write mode.
template <typename MutexT, typename RecurseCountsT>
TVirtualRWMutex::Hint_t *TReentrantRWLock<MutexT, RecurseCountsT>::WriteLock()
{
++fWriterReservation;
std::unique_lock<MutexT> lock(fMutex);
auto local = fRecurseCounts.GetLocal();
// Release this thread's reader lock(s)
auto &readerCount = fRecurseCounts.GetLocalReadersCount(local);
TVirtualRWMutex::Hint_t *hint = reinterpret_cast<TVirtualRWMutex::Hint_t *>(&readerCount);
fReaders -= readerCount;
// Wait for other writers, if any
if (fWriter && fRecurseCounts.IsNotCurrentWriter(local)) {
if (readerCount && fReaders == 0) {
// we decrease fReaders to zero, let's wake up the
// other writer.
fCond.notify_all();
}
fCond.wait(lock, [this] { return !fWriter; });
}
// Claim the lock for this writer
fWriter = true;
fRecurseCounts.SetIsWriter(local);
// Wait until all reader reservations finish
while (fReaderReservation) {
};
// Wait for remaining readers
fCond.wait(lock, [this] { return fReaders == 0; });
// Restore this thread's reader lock(s)
fReaders += readerCount;
--fWriterReservation;
lock.unlock();
return hint;
}
//////////////////////////////////////////////////////////////////////////
/// Release the lock in write mode.
template <typename MutexT, typename RecurseCountsT>
void TReentrantRWLock<MutexT, RecurseCountsT>::WriteUnLock(TVirtualRWMutex::Hint_t *)
{
// We need to lock here to prevent interleaving with a reader
std::lock_guard<MutexT> lock(fMutex);
if (!fWriter || fRecurseCounts.fWriteRecurse == 0) {
Error("TReentrantRWLock::WriteUnLock", "Write lock already released for %p", this);
return;
}
fRecurseCounts.DecrementWriteCount();
if (!fRecurseCounts.fWriteRecurse) {
fWriter = false;
auto local = fRecurseCounts.GetLocal();
fRecurseCounts.ResetIsWriter(local);
// Notify all potential readers/writers that are waiting
fCond.notify_all();
}
}
namespace {
template <typename MutexT, typename RecurseCountsT>
struct TReentrantRWLockState: public TVirtualRWMutex::State {
size_t *fReadersCountLoc = nullptr;
int fReadersCount = 0;
size_t fWriteRecurse = 0;
};
template <typename MutexT, typename RecurseCountsT>
struct TReentrantRWLockStateDelta: public TVirtualRWMutex::StateDelta {
size_t *fReadersCountLoc = nullptr;
int fDeltaReadersCount = 0;
int fDeltaWriteRecurse = 0;
};
}
//////////////////////////////////////////////////////////////////////////
/// Get the lock state before the most recent write lock was taken.
template <typename MutexT, typename RecurseCountsT>
std::unique_ptr<TVirtualRWMutex::State>
TReentrantRWLock<MutexT, RecurseCountsT>::GetStateBefore()
{
using State_t = TReentrantRWLockState<MutexT, RecurseCountsT>;
if (!fWriter) {
Error("TReentrantRWLock::GetStateBefore()", "Must be write locked!");
return nullptr;
}
auto local = fRecurseCounts.GetLocal();
if (fRecurseCounts.IsNotCurrentWriter(local)) {
Error("TReentrantRWLock::GetStateBefore()", "Not holding the write lock!");
return nullptr;
}
std::unique_ptr<State_t> pState(new State_t);
{
std::lock_guard<MutexT> lock(fMutex);
pState->fReadersCountLoc = &(fRecurseCounts.GetLocalReadersCount(local));
}
pState->fReadersCount = *(pState->fReadersCountLoc);
// *Before* the most recent write lock (that is required by GetStateBefore())
// was taken, the write recursion level was `fWriteRecurse - 1`
pState->fWriteRecurse = fRecurseCounts.fWriteRecurse - 1;
return std::move(pState);
}
//////////////////////////////////////////////////////////////////////////
/// Rewind to an earlier mutex state, returning the delta.
template <typename MutexT, typename RecurseCountsT>
std::unique_ptr<TVirtualRWMutex::StateDelta>
TReentrantRWLock<MutexT, RecurseCountsT>::Rewind(const State &earlierState) {
using State_t = TReentrantRWLockState<MutexT, RecurseCountsT>;
using StateDelta_t = TReentrantRWLockStateDelta<MutexT, RecurseCountsT>;
auto& typedState = static_cast<const State_t&>(earlierState);
R__MAYBE_AssertReadCountLocIsFromCurrentThread(typedState.fReadersCountLoc);
std::unique_ptr<StateDelta_t> pStateDelta(new StateDelta_t);
pStateDelta->fReadersCountLoc = typedState.fReadersCountLoc;
pStateDelta->fDeltaReadersCount = *typedState.fReadersCountLoc - typedState.fReadersCount;
pStateDelta->fDeltaWriteRecurse = fRecurseCounts.fWriteRecurse - typedState.fWriteRecurse;
if (pStateDelta->fDeltaReadersCount < 0) {
Error("TReentrantRWLock::Rewind", "Inconsistent read lock count!");
return nullptr;
}
if (pStateDelta->fDeltaWriteRecurse < 0) {
Error("TReentrantRWLock::Rewind", "Inconsistent write lock count!");
return nullptr;
}
auto hint = reinterpret_cast<TVirtualRWMutex::Hint_t *>(typedState.fReadersCountLoc);
if (pStateDelta->fDeltaWriteRecurse != 0) {
// Claim a recurse-state +1 to be able to call Unlock() below.
fRecurseCounts.fWriteRecurse = typedState.fWriteRecurse + 1;
// Release this thread's write lock
WriteUnLock(hint);
}
if (pStateDelta->fDeltaReadersCount != 0) {
// Claim a recurse-state +1 to be able to call Unlock() below.
*typedState.fReadersCountLoc = typedState.fReadersCount + 1;
fReaders = typedState.fReadersCount + 1;
// Release this thread's reader lock(s)
ReadUnLock(hint);
}
// else earlierState and *this are identical!
return std::unique_ptr<TVirtualRWMutex::StateDelta>(std::move(pStateDelta));
}
//////////////////////////////////////////////////////////////////////////
/// Re-apply a delta.
template <typename MutexT, typename RecurseCountsT>
void TReentrantRWLock<MutexT, RecurseCountsT>::Apply(std::unique_ptr<StateDelta> &&state) {
if (!state) {
Error("TReentrantRWLock::Apply", "Cannot apply empty delta!");
return;
}
using StateDelta_t = TReentrantRWLockStateDelta<MutexT, RecurseCountsT>;
const StateDelta_t* typedDelta = static_cast<const StateDelta_t*>(state.get());
if (typedDelta->fDeltaWriteRecurse < 0) {
Error("TReentrantRWLock::Apply", "Negative write recurse count delta!");
return;
}
if (typedDelta->fDeltaReadersCount < 0) {
Error("TReentrantRWLock::Apply", "Negative read count delta!");
return;
}
R__MAYBE_AssertReadCountLocIsFromCurrentThread(typedDelta->fReadersCountLoc);
if (typedDelta->fDeltaWriteRecurse != 0) {
WriteLock();
fRecurseCounts.fWriteRecurse += typedDelta->fDeltaWriteRecurse - 1;
}
if (typedDelta->fDeltaReadersCount != 0) {
ReadLock();
// "- 1" due to ReadLock() above.
fReaders += typedDelta->fDeltaReadersCount - 1;
*typedDelta->fReadersCountLoc += typedDelta->fDeltaReadersCount - 1;
}
}
//////////////////////////////////////////////////////////////////////////
/// Assert that presumedLocalReadersCount really matches the local read count.
/// Print an error message if not.
template <typename MutexT, typename RecurseCountsT>
void TReentrantRWLock<MutexT, RecurseCountsT>::AssertReadCountLocIsFromCurrentThread(const size_t* presumedLocalReadersCount)
{
auto local = fRecurseCounts.GetLocal();
size_t* localReadersCount;
{
std::lock_guard<MutexT> lock(fMutex);
localReadersCount = &(fRecurseCounts.GetLocalReadersCount(local));
}
if (localReadersCount != presumedLocalReadersCount) {
Error("TReentrantRWLock::AssertReadCountLocIsFromCurrentThread", "ReadersCount is from different thread!");
}
}
namespace ROOT {
template class TReentrantRWLock<ROOT::TSpinMutex, ROOT::Internal::RecurseCounts>;
template class TReentrantRWLock<TMutex, ROOT::Internal::RecurseCounts>;
template class TReentrantRWLock<std::mutex, ROOT::Internal::RecurseCounts>;
template class TReentrantRWLock<ROOT::TSpinMutex, ROOT::Internal::UniqueLockRecurseCount>;
template class TReentrantRWLock<TMutex, ROOT::Internal::UniqueLockRecurseCount>;
}
<commit_msg>std::move is redundant and can prevent NRVO.<commit_after>// @(#)root/thread:$Id$
// Authors: Enric Tejedor CERN 12/09/2016
// Philippe Canal FNAL 12/09/2016
/*************************************************************************
* Copyright (C) 1995-2016, Rene Brun and Fons Rademakers. *
* All rights reserved. *
* *
* For the licensing terms see $ROOTSYS/LICENSE. *
* For the list of contributors see $ROOTSYS/README/CREDITS. *
*************************************************************************/
/** \class TReentrantRWLock
\brief An implementation of a reentrant read-write lock with a
configurable internal mutex/lock (default Spin Lock).
This class provides an implementation of a reentrant read-write lock
that uses an internal lock and a condition variable to synchronize
readers and writers when necessary.
The implementation allows a single reader to take the write lock without
releasing the reader lock. It also allows the writer to take a read lock.
In other word, the lock is re-entrant for both reading and writing.
The implementation tries to make faster the scenario when readers come
and go but there is no writer. In that case, readers will not pay the
price of taking the internal spin lock.
Moreover, this RW lock tries to be fair with writers, giving them the
possibility to claim the lock and wait for only the remaining readers,
thus preventing starvation.
*/
#include "ROOT/TReentrantRWLock.hxx"
#include "ROOT/TSpinMutex.hxx"
#include "TMutex.h"
#include "TError.h"
#include <assert.h>
using namespace ROOT;
#ifdef NDEBUG
# define R__MAYBE_AssertReadCountLocIsFromCurrentThread(READERSCOUNTLOC)
#else
# define R__MAYBE_AssertReadCountLocIsFromCurrentThread(READERSCOUNTLOC) \
AssertReadCountLocIsFromCurrentThread(READERSCOUNTLOC)
#endif
Internal::UniqueLockRecurseCount::UniqueLockRecurseCount()
{
static bool singleton = false;
if (singleton) {
::Fatal("UniqueLockRecurseCount Ctor", "Only one TReentrantRWLock using a UniqueLockRecurseCount is allowed.");
}
singleton = true;
}
////////////////////////////////////////////////////////////////////////////
/// Acquire the lock in read mode.
template <typename MutexT, typename RecurseCountsT>
TVirtualRWMutex::Hint_t *TReentrantRWLock<MutexT, RecurseCountsT>::ReadLock()
{
++fReaderReservation;
// if (fReaders == std::numeric_limits<decltype(fReaders)>::max()) {
// ::Fatal("TRWSpinLock::WriteLock", "Too many recursions in TRWSpinLock!");
// }
auto local = fRecurseCounts.GetLocal();
TVirtualRWMutex::Hint_t *hint = nullptr;
if (!fWriter) {
// There is no writer, go freely to the critical section
++fReaders;
--fReaderReservation;
hint = fRecurseCounts.IncrementReadCount(local, fMutex);
} else if (fRecurseCounts.IsCurrentWriter(local)) {
--fReaderReservation;
// This can run concurrently with another thread trying to get
// the read lock and ending up in the next section ("Wait for writers, if any")
// which need to also get the local readers count and thus can
// modify the map.
hint = fRecurseCounts.IncrementReadCount(local, fMutex);
++fReaders;
} else {
// A writer claimed the RW lock, we will need to wait on the
// internal lock
--fReaderReservation;
std::unique_lock<MutexT> lock(fMutex);
// Wait for writers, if any
if (fWriter && fRecurseCounts.IsNotCurrentWriter(local)) {
auto readerCount = fRecurseCounts.GetLocalReadersCount(local);
if (readerCount == 0)
fCond.wait(lock, [this] { return !fWriter; });
// else
// There is a writer **but** we have outstanding readers
// locks, this must mean that the writer is actually
// waiting on this thread to release its read locks.
// This can be done in only two ways:
// * request the writer lock
// * release the reader lock
// Either way, this thread needs to proceed to
// be able to reach a point whether it does one
// of the two.
}
hint = fRecurseCounts.IncrementReadCount(local);
// This RW lock now belongs to the readers
++fReaders;
lock.unlock();
}
return hint;
}
//////////////////////////////////////////////////////////////////////////
/// Release the lock in read mode.
template <typename MutexT, typename RecurseCountsT>
void TReentrantRWLock<MutexT, RecurseCountsT>::ReadUnLock(TVirtualRWMutex::Hint_t *hint)
{
size_t *localReaderCount;
if (!hint) {
// This should be very rare.
auto local = fRecurseCounts.GetLocal();
std::lock_guard<MutexT> lock(fMutex);
localReaderCount = &(fRecurseCounts.GetLocalReadersCount(local));
} else {
localReaderCount = reinterpret_cast<size_t*>(hint);
}
--fReaders;
if (fWriterReservation && fReaders == 0) {
// We still need to lock here to prevent interleaving with a writer
std::lock_guard<MutexT> lock(fMutex);
--(*localReaderCount);
// Make sure you wake up a writer, if any
// Note: spurrious wakeups are okay, fReaders
// will be checked again in WriteLock
fCond.notify_all();
} else {
--(*localReaderCount);
}
}
//////////////////////////////////////////////////////////////////////////
/// Acquire the lock in write mode.
template <typename MutexT, typename RecurseCountsT>
TVirtualRWMutex::Hint_t *TReentrantRWLock<MutexT, RecurseCountsT>::WriteLock()
{
++fWriterReservation;
std::unique_lock<MutexT> lock(fMutex);
auto local = fRecurseCounts.GetLocal();
// Release this thread's reader lock(s)
auto &readerCount = fRecurseCounts.GetLocalReadersCount(local);
TVirtualRWMutex::Hint_t *hint = reinterpret_cast<TVirtualRWMutex::Hint_t *>(&readerCount);
fReaders -= readerCount;
// Wait for other writers, if any
if (fWriter && fRecurseCounts.IsNotCurrentWriter(local)) {
if (readerCount && fReaders == 0) {
// we decrease fReaders to zero, let's wake up the
// other writer.
fCond.notify_all();
}
fCond.wait(lock, [this] { return !fWriter; });
}
// Claim the lock for this writer
fWriter = true;
fRecurseCounts.SetIsWriter(local);
// Wait until all reader reservations finish
while (fReaderReservation) {
};
// Wait for remaining readers
fCond.wait(lock, [this] { return fReaders == 0; });
// Restore this thread's reader lock(s)
fReaders += readerCount;
--fWriterReservation;
lock.unlock();
return hint;
}
//////////////////////////////////////////////////////////////////////////
/// Release the lock in write mode.
template <typename MutexT, typename RecurseCountsT>
void TReentrantRWLock<MutexT, RecurseCountsT>::WriteUnLock(TVirtualRWMutex::Hint_t *)
{
// We need to lock here to prevent interleaving with a reader
std::lock_guard<MutexT> lock(fMutex);
if (!fWriter || fRecurseCounts.fWriteRecurse == 0) {
Error("TReentrantRWLock::WriteUnLock", "Write lock already released for %p", this);
return;
}
fRecurseCounts.DecrementWriteCount();
if (!fRecurseCounts.fWriteRecurse) {
fWriter = false;
auto local = fRecurseCounts.GetLocal();
fRecurseCounts.ResetIsWriter(local);
// Notify all potential readers/writers that are waiting
fCond.notify_all();
}
}
namespace {
template <typename MutexT, typename RecurseCountsT>
struct TReentrantRWLockState: public TVirtualRWMutex::State {
size_t *fReadersCountLoc = nullptr;
int fReadersCount = 0;
size_t fWriteRecurse = 0;
};
template <typename MutexT, typename RecurseCountsT>
struct TReentrantRWLockStateDelta: public TVirtualRWMutex::StateDelta {
size_t *fReadersCountLoc = nullptr;
int fDeltaReadersCount = 0;
int fDeltaWriteRecurse = 0;
};
}
//////////////////////////////////////////////////////////////////////////
/// Get the lock state before the most recent write lock was taken.
template <typename MutexT, typename RecurseCountsT>
std::unique_ptr<TVirtualRWMutex::State>
TReentrantRWLock<MutexT, RecurseCountsT>::GetStateBefore()
{
using State_t = TReentrantRWLockState<MutexT, RecurseCountsT>;
if (!fWriter) {
Error("TReentrantRWLock::GetStateBefore()", "Must be write locked!");
return nullptr;
}
auto local = fRecurseCounts.GetLocal();
if (fRecurseCounts.IsNotCurrentWriter(local)) {
Error("TReentrantRWLock::GetStateBefore()", "Not holding the write lock!");
return nullptr;
}
std::unique_ptr<State_t> pState(new State_t);
{
std::lock_guard<MutexT> lock(fMutex);
pState->fReadersCountLoc = &(fRecurseCounts.GetLocalReadersCount(local));
}
pState->fReadersCount = *(pState->fReadersCountLoc);
// *Before* the most recent write lock (that is required by GetStateBefore())
// was taken, the write recursion level was `fWriteRecurse - 1`
pState->fWriteRecurse = fRecurseCounts.fWriteRecurse - 1;
return pState;
}
//////////////////////////////////////////////////////////////////////////
/// Rewind to an earlier mutex state, returning the delta.
template <typename MutexT, typename RecurseCountsT>
std::unique_ptr<TVirtualRWMutex::StateDelta>
TReentrantRWLock<MutexT, RecurseCountsT>::Rewind(const State &earlierState) {
using State_t = TReentrantRWLockState<MutexT, RecurseCountsT>;
using StateDelta_t = TReentrantRWLockStateDelta<MutexT, RecurseCountsT>;
auto& typedState = static_cast<const State_t&>(earlierState);
R__MAYBE_AssertReadCountLocIsFromCurrentThread(typedState.fReadersCountLoc);
std::unique_ptr<StateDelta_t> pStateDelta(new StateDelta_t);
pStateDelta->fReadersCountLoc = typedState.fReadersCountLoc;
pStateDelta->fDeltaReadersCount = *typedState.fReadersCountLoc - typedState.fReadersCount;
pStateDelta->fDeltaWriteRecurse = fRecurseCounts.fWriteRecurse - typedState.fWriteRecurse;
if (pStateDelta->fDeltaReadersCount < 0) {
Error("TReentrantRWLock::Rewind", "Inconsistent read lock count!");
return nullptr;
}
if (pStateDelta->fDeltaWriteRecurse < 0) {
Error("TReentrantRWLock::Rewind", "Inconsistent write lock count!");
return nullptr;
}
auto hint = reinterpret_cast<TVirtualRWMutex::Hint_t *>(typedState.fReadersCountLoc);
if (pStateDelta->fDeltaWriteRecurse != 0) {
// Claim a recurse-state +1 to be able to call Unlock() below.
fRecurseCounts.fWriteRecurse = typedState.fWriteRecurse + 1;
// Release this thread's write lock
WriteUnLock(hint);
}
if (pStateDelta->fDeltaReadersCount != 0) {
// Claim a recurse-state +1 to be able to call Unlock() below.
*typedState.fReadersCountLoc = typedState.fReadersCount + 1;
fReaders = typedState.fReadersCount + 1;
// Release this thread's reader lock(s)
ReadUnLock(hint);
}
// else earlierState and *this are identical!
return std::unique_ptr<TVirtualRWMutex::StateDelta>(std::move(pStateDelta));
}
//////////////////////////////////////////////////////////////////////////
/// Re-apply a delta.
template <typename MutexT, typename RecurseCountsT>
void TReentrantRWLock<MutexT, RecurseCountsT>::Apply(std::unique_ptr<StateDelta> &&state) {
if (!state) {
Error("TReentrantRWLock::Apply", "Cannot apply empty delta!");
return;
}
using StateDelta_t = TReentrantRWLockStateDelta<MutexT, RecurseCountsT>;
const StateDelta_t* typedDelta = static_cast<const StateDelta_t*>(state.get());
if (typedDelta->fDeltaWriteRecurse < 0) {
Error("TReentrantRWLock::Apply", "Negative write recurse count delta!");
return;
}
if (typedDelta->fDeltaReadersCount < 0) {
Error("TReentrantRWLock::Apply", "Negative read count delta!");
return;
}
R__MAYBE_AssertReadCountLocIsFromCurrentThread(typedDelta->fReadersCountLoc);
if (typedDelta->fDeltaWriteRecurse != 0) {
WriteLock();
fRecurseCounts.fWriteRecurse += typedDelta->fDeltaWriteRecurse - 1;
}
if (typedDelta->fDeltaReadersCount != 0) {
ReadLock();
// "- 1" due to ReadLock() above.
fReaders += typedDelta->fDeltaReadersCount - 1;
*typedDelta->fReadersCountLoc += typedDelta->fDeltaReadersCount - 1;
}
}
//////////////////////////////////////////////////////////////////////////
/// Assert that presumedLocalReadersCount really matches the local read count.
/// Print an error message if not.
template <typename MutexT, typename RecurseCountsT>
void TReentrantRWLock<MutexT, RecurseCountsT>::AssertReadCountLocIsFromCurrentThread(const size_t* presumedLocalReadersCount)
{
auto local = fRecurseCounts.GetLocal();
size_t* localReadersCount;
{
std::lock_guard<MutexT> lock(fMutex);
localReadersCount = &(fRecurseCounts.GetLocalReadersCount(local));
}
if (localReadersCount != presumedLocalReadersCount) {
Error("TReentrantRWLock::AssertReadCountLocIsFromCurrentThread", "ReadersCount is from different thread!");
}
}
namespace ROOT {
template class TReentrantRWLock<ROOT::TSpinMutex, ROOT::Internal::RecurseCounts>;
template class TReentrantRWLock<TMutex, ROOT::Internal::RecurseCounts>;
template class TReentrantRWLock<std::mutex, ROOT::Internal::RecurseCounts>;
template class TReentrantRWLock<ROOT::TSpinMutex, ROOT::Internal::UniqueLockRecurseCount>;
template class TReentrantRWLock<TMutex, ROOT::Internal::UniqueLockRecurseCount>;
}
<|endoftext|> |
<commit_before><commit_msg>Use SOCK_CLOEXEC when possible.<commit_after><|endoftext|> |
<commit_before>/**
* This file is part of Slideshow.
* Copyright (C) 2008-2010 David Sveningsson <ext@sidvind.com>
*
* Slideshow is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* Slideshow is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with Slideshow. If not, see <http://www.gnu.org/licenses/>.
*/
#include "Browser.h"
#include "exception.h"
#include "Log.h"
#include <sqlite3.h>
#include <cstring>
#include <vector>
class SQLiteBrowser: public Browser {
public:
SQLiteBrowser(const browser_context_t& context);
virtual ~SQLiteBrowser();
virtual void change_bin(unsigned int id);
virtual slide_context_t get_next_file();
virtual void reload();
virtual void dump_queue();
private:
void connect();
void disconnect();
void pop_intermediate(int id) const;
bool _loop;
int _old_id;
sqlite3* _conn;
sqlite3_stmt* _query;
sqlite3_stmt* _query_looping;
sqlite3_stmt* _query_pop_intermediate;
};
REGISTER_BROWSER_FACTORY(SQLiteBrowser, sqlite);
SQLiteBrowser::SQLiteBrowser(const browser_context_t& context)
: Browser(context)
, _loop(true)
, _old_id(-1)
, _conn(NULL)
, _query(NULL) {
connect();
}
SQLiteBrowser::~SQLiteBrowser(){
disconnect();
}
void SQLiteBrowser::change_bin(unsigned int id){
/* if we change queue we reset the position back to the start */
if ( current_bin() != id ){
_old_id = -1;
}
Browser::change_bin(id);
/* query whenever to loop this queue */
sqlite3_bind_int(_query_looping, 1, current_bin());
int ret = sqlite3_step(_query_looping);
_loop = true;
switch ( ret ){
case SQLITE_DONE:
break;
case SQLITE_ROW:
_loop = sqlite3_column_int(_query_looping, 0) == 1;
break;
case SQLITE_MISUSE:
Log::message(Log::Info, "query_loop::sqlite3_step failed: SQLITE_MISUSE\n");
break;
default:
Log::message(Log::Info, "query_loop::sqlite3_step failed: %d\n", ret);
break;
}
sqlite3_reset(_query_looping);
}
slide_context_t SQLiteBrowser::get_next_file(){
slide_context_t slide;
slide.filename = NULL;
slide.assembler = NULL;
sqlite3_bind_int(_query, 1, current_bin());
sqlite3_bind_int(_query, 2, _old_id);
int ret = sqlite3_step(_query);
if ( ret == SQLITE_DONE ){
sqlite3_reset(_query);
if ( !_loop ){
Log::message(Log::Debug, "queue finished\n");
return slide;
}
Log::message(Log::Debug, "queue wrapping\n");
_old_id = -1;
sqlite3_bind_int(_query, 1, current_bin());
sqlite3_bind_int(_query, 2, _old_id);
ret = sqlite3_step(_query);
if ( ret == SQLITE_DONE ){
sqlite3_reset(_query);
return slide;
}
}
int id = -1;
int sort_order = -1;
int queue_id = -1;
switch ( ret ){
case SQLITE_ROW:
/* read columns */
id = sqlite3_column_int(_query, 0);
slide.filename = strdup((const char*)sqlite3_column_text(_query, 1));
sort_order = sqlite3_column_int(_query, 2);
queue_id = sqlite3_column_int(_query, 3);
slide.assembler = strdup((const char*)sqlite3_column_text(_query, 4));
Log::message(Log::Info, "slide: %s\n", slide.filename);
Log::message(Log::Debug, "\tid: %d\n", id);
Log::message(Log::Debug, "\tsort_order: %d\n", sort_order);
Log::message(Log::Debug, "\tqueue_id: %d\n", queue_id);
/* only update id if it comes from a regular queue, i.e., not from intermediate queue. */
if ( queue_id > 0 ){
_old_id = sort_order;
} else {
/* pop intermediate slides back to unsorted */
Log::message(Log::Debug, "popping intermediate slide\n", slide.filename, id, queue_id);
pop_intermediate(id);
}
break;
case SQLITE_MISUSE:
Log::message(Log::Info, "query_slide::sqlite3_step failed: SQLITE_MISUSE\n");
Log::message(Log::Debug, "\tqueue_id: %d\n", current_bin());
Log::message(Log::Debug, "\told_id: %d\n", _old_id);
break;
default:
Log::message(Log::Info, "query_slide::sqlite3_step failed: %d\n", ret);
break;
}
sqlite3_reset(_query);
return slide;
}
void SQLiteBrowser::pop_intermediate(int id) const {
sqlite3_bind_int(_query_pop_intermediate, 1, id);
int ret = sqlite3_step(_query_pop_intermediate);
sqlite3_reset(_query_pop_intermediate);
switch ( ret ){
case SQLITE_DONE:
case SQLITE_ROW:
return;
case SQLITE_MISUSE:
Log::message(Log::Info, "pop_intermediate::sqlite3_step failed: SQLITE_MISUSE\n");
break;
default:
Log::message(Log::Info, "pop_intermediate::sqlite3_step failed: %d\n", ret);
break;
}
}
void SQLiteBrowser::connect(){
int ret;
if ( (ret = sqlite3_open(database(), &_conn)) != SQLITE_OK ){
Log::message(Log::Fatal, "sqlite3_open failed with %d\n", ret);
}
const char* q =
" SELECT" /* select from intermediate queue */
" id, "
" path, "
" sortorder, "
" queue_id, "
" assembler "
" FROM"
" slide "
" WHERE"
" queue_id = -1 " /* -1 is intermediate queue */
"UNION "
" SELECT" /* select next slide from regular queue */
" id, "
" path, "
" sortorder, "
" queue_id, "
" assembler "
" FROM"
" slide "
" WHERE"
" queue_id = ? AND "
" sortorder > ? "
"ORDER BY"
" queue_id, "
" sortorder "
"LIMIT 1";
if ( (ret = sqlite3_prepare_v2(_conn, q, (int)(strlen(q)+1), &_query, NULL)) != SQLITE_OK ){
Log::message(Log::Fatal, "query_slide::sqlite3_prepare_v2 failed with %d\n", ret);
}
q =
"SELECT "
" loop "
"FROM "
" queue "
"WHERE "
" id = ? "
"LIMIT 1";
if ( (ret = sqlite3_prepare_v2(_conn, q, (int)(strlen(q)+1), &_query_looping, NULL)) != SQLITE_OK ){
Log::message(Log::Fatal, "query_loop::sqlite3_prepare_v2 failed with %d\n", ret);
}
q =
"UPDATE "
" slide "
"SET "
" queue_id = 0 "
"WHERE "
" id = ?";
if ( (ret = sqlite3_prepare_v2(_conn, q, (int)(strlen(q)+1), &_query_pop_intermediate, NULL)) != SQLITE_OK ){
Log::message(Log::Fatal, "pop_intermediate::sqlite3_prepare_v2 failed with %d\n", ret);
}
}
void SQLiteBrowser::disconnect(){
sqlite3_finalize(_query_looping);
sqlite3_finalize(_query);
sqlite3_close(_conn);
}
void SQLiteBrowser::reload(){
}
void SQLiteBrowser::dump_queue(){
}
<commit_msg>register sqlite3 browser (retaining old name for compability, even thought only sqlite3 should be used)<commit_after>/**
* This file is part of Slideshow.
* Copyright (C) 2008-2010 David Sveningsson <ext@sidvind.com>
*
* Slideshow is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* Slideshow is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with Slideshow. If not, see <http://www.gnu.org/licenses/>.
*/
#include "Browser.h"
#include "exception.h"
#include "Log.h"
#include <sqlite3.h>
#include <cstring>
#include <vector>
class SQLiteBrowser: public Browser {
public:
SQLiteBrowser(const browser_context_t& context);
virtual ~SQLiteBrowser();
virtual void change_bin(unsigned int id);
virtual slide_context_t get_next_file();
virtual void reload();
virtual void dump_queue();
private:
void connect();
void disconnect();
void pop_intermediate(int id) const;
bool _loop;
int _old_id;
sqlite3* _conn;
sqlite3_stmt* _query;
sqlite3_stmt* _query_looping;
sqlite3_stmt* _query_pop_intermediate;
};
REGISTER_BROWSER_FACTORY(SQLiteBrowser, sqlite);
REGISTER_BROWSER_FACTORY(SQLiteBrowser, sqlite3);
SQLiteBrowser::SQLiteBrowser(const browser_context_t& context)
: Browser(context)
, _loop(true)
, _old_id(-1)
, _conn(NULL)
, _query(NULL) {
connect();
}
SQLiteBrowser::~SQLiteBrowser(){
disconnect();
}
void SQLiteBrowser::change_bin(unsigned int id){
/* if we change queue we reset the position back to the start */
if ( current_bin() != id ){
_old_id = -1;
}
Browser::change_bin(id);
/* query whenever to loop this queue */
sqlite3_bind_int(_query_looping, 1, current_bin());
int ret = sqlite3_step(_query_looping);
_loop = true;
switch ( ret ){
case SQLITE_DONE:
break;
case SQLITE_ROW:
_loop = sqlite3_column_int(_query_looping, 0) == 1;
break;
case SQLITE_MISUSE:
Log::message(Log::Info, "query_loop::sqlite3_step failed: SQLITE_MISUSE\n");
break;
default:
Log::message(Log::Info, "query_loop::sqlite3_step failed: %d\n", ret);
break;
}
sqlite3_reset(_query_looping);
}
slide_context_t SQLiteBrowser::get_next_file(){
slide_context_t slide;
slide.filename = NULL;
slide.assembler = NULL;
sqlite3_bind_int(_query, 1, current_bin());
sqlite3_bind_int(_query, 2, _old_id);
int ret = sqlite3_step(_query);
if ( ret == SQLITE_DONE ){
sqlite3_reset(_query);
if ( !_loop ){
Log::message(Log::Debug, "queue finished\n");
return slide;
}
Log::message(Log::Debug, "queue wrapping\n");
_old_id = -1;
sqlite3_bind_int(_query, 1, current_bin());
sqlite3_bind_int(_query, 2, _old_id);
ret = sqlite3_step(_query);
if ( ret == SQLITE_DONE ){
sqlite3_reset(_query);
return slide;
}
}
int id = -1;
int sort_order = -1;
int queue_id = -1;
switch ( ret ){
case SQLITE_ROW:
/* read columns */
id = sqlite3_column_int(_query, 0);
slide.filename = strdup((const char*)sqlite3_column_text(_query, 1));
sort_order = sqlite3_column_int(_query, 2);
queue_id = sqlite3_column_int(_query, 3);
slide.assembler = strdup((const char*)sqlite3_column_text(_query, 4));
Log::message(Log::Info, "slide: %s\n", slide.filename);
Log::message(Log::Debug, "\tid: %d\n", id);
Log::message(Log::Debug, "\tsort_order: %d\n", sort_order);
Log::message(Log::Debug, "\tqueue_id: %d\n", queue_id);
/* only update id if it comes from a regular queue, i.e., not from intermediate queue. */
if ( queue_id > 0 ){
_old_id = sort_order;
} else {
/* pop intermediate slides back to unsorted */
Log::message(Log::Debug, "popping intermediate slide\n", slide.filename, id, queue_id);
pop_intermediate(id);
}
break;
case SQLITE_MISUSE:
Log::message(Log::Info, "query_slide::sqlite3_step failed: SQLITE_MISUSE\n");
Log::message(Log::Debug, "\tqueue_id: %d\n", current_bin());
Log::message(Log::Debug, "\told_id: %d\n", _old_id);
break;
default:
Log::message(Log::Info, "query_slide::sqlite3_step failed: %d\n", ret);
break;
}
sqlite3_reset(_query);
return slide;
}
void SQLiteBrowser::pop_intermediate(int id) const {
sqlite3_bind_int(_query_pop_intermediate, 1, id);
int ret = sqlite3_step(_query_pop_intermediate);
sqlite3_reset(_query_pop_intermediate);
switch ( ret ){
case SQLITE_DONE:
case SQLITE_ROW:
return;
case SQLITE_MISUSE:
Log::message(Log::Info, "pop_intermediate::sqlite3_step failed: SQLITE_MISUSE\n");
break;
default:
Log::message(Log::Info, "pop_intermediate::sqlite3_step failed: %d\n", ret);
break;
}
}
void SQLiteBrowser::connect(){
int ret;
if ( (ret = sqlite3_open(database(), &_conn)) != SQLITE_OK ){
Log::message(Log::Fatal, "sqlite3_open failed with %d\n", ret);
}
const char* q =
" SELECT" /* select from intermediate queue */
" id, "
" path, "
" sortorder, "
" queue_id, "
" assembler "
" FROM"
" slide "
" WHERE"
" queue_id = -1 " /* -1 is intermediate queue */
"UNION "
" SELECT" /* select next slide from regular queue */
" id, "
" path, "
" sortorder, "
" queue_id, "
" assembler "
" FROM"
" slide "
" WHERE"
" queue_id = ? AND "
" sortorder > ? "
"ORDER BY"
" queue_id, "
" sortorder "
"LIMIT 1";
if ( (ret = sqlite3_prepare_v2(_conn, q, (int)(strlen(q)+1), &_query, NULL)) != SQLITE_OK ){
Log::message(Log::Fatal, "query_slide::sqlite3_prepare_v2 failed with %d\n", ret);
}
q =
"SELECT "
" loop "
"FROM "
" queue "
"WHERE "
" id = ? "
"LIMIT 1";
if ( (ret = sqlite3_prepare_v2(_conn, q, (int)(strlen(q)+1), &_query_looping, NULL)) != SQLITE_OK ){
Log::message(Log::Fatal, "query_loop::sqlite3_prepare_v2 failed with %d\n", ret);
}
q =
"UPDATE "
" slide "
"SET "
" queue_id = 0 "
"WHERE "
" id = ?";
if ( (ret = sqlite3_prepare_v2(_conn, q, (int)(strlen(q)+1), &_query_pop_intermediate, NULL)) != SQLITE_OK ){
Log::message(Log::Fatal, "pop_intermediate::sqlite3_prepare_v2 failed with %d\n", ret);
}
}
void SQLiteBrowser::disconnect(){
sqlite3_finalize(_query_looping);
sqlite3_finalize(_query);
sqlite3_close(_conn);
}
void SQLiteBrowser::reload(){
}
void SQLiteBrowser::dump_queue(){
}
<|endoftext|> |
<commit_before>/** @file
@brief Implementation
@date 2015
@author
Sensics, Inc.
<http://sensics.com/osvr>
*/
// Copyright 2015 Sensics, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// Internal Includes
#include "MediaSampleExchange.h"
#include "SignalEvent.h"
// Library/third-party includes
#include <boost/assert.hpp>
// Standard includes
// - none
struct MediaSampleExchange::Impl {
SignalEvent produced;
SignalEvent consumed;
};
MediaSampleExchange::MediaSampleExchange()
: impl_(new MediaSampleExchange::Impl) {}
MediaSampleExchange::~MediaSampleExchange() {
// Required for unique_ptr pimpl - see http://herbsutter.com/gotw/_100/
}
void MediaSampleExchange::signalSampleProduced(IMediaSample *sample) {
BOOST_ASSERT_MSG(sample_ == nullptr,
"Sample should be consumed before the next one produced!");
sample_ = sample;
impl_->produced.set();
}
bool MediaSampleExchange::waitForSample(std::chrono::milliseconds timeout) {
return impl_->produced.wait(timeout.count());
}
void MediaSampleExchange::signalSampleConsumed() {
BOOST_ASSERT_MSG(sample_ != nullptr,
"Sample pointer should not be null when consumed!");
sample_ = nullptr;
impl_->consumed.set();
}
bool MediaSampleExchange::waitForSampleConsumed(
std::chrono::milliseconds timeout) {
return impl_->consumed.wait(timeout.count());
}
<commit_msg>Add some assertions.<commit_after>/** @file
@brief Implementation
@date 2015
@author
Sensics, Inc.
<http://sensics.com/osvr>
*/
// Copyright 2015 Sensics, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// Internal Includes
#include "MediaSampleExchange.h"
#include "SignalEvent.h"
// Library/third-party includes
#include <boost/assert.hpp>
// Standard includes
// - none
struct MediaSampleExchange::Impl {
SignalEvent produced;
SignalEvent consumed;
};
MediaSampleExchange::MediaSampleExchange()
: impl_(new MediaSampleExchange::Impl) {}
MediaSampleExchange::~MediaSampleExchange() {
// Required for unique_ptr pimpl - see http://herbsutter.com/gotw/_100/
}
void MediaSampleExchange::signalSampleProduced(IMediaSample *sample) {
BOOST_ASSERT_MSG(
sample != nullptr,
"Should not be signalling that there is a null sample available!");
BOOST_ASSERT_MSG(sample_ == nullptr,
"Sample should be consumed before the next one produced!");
sample_ = sample;
impl_->produced.set();
}
bool MediaSampleExchange::waitForSample(std::chrono::milliseconds timeout) {
return impl_->produced.wait(timeout.count());
}
void MediaSampleExchange::signalSampleConsumed() {
BOOST_ASSERT_MSG(sample_ != nullptr,
"Sample pointer should not be null when consumed!");
sample_ = nullptr;
impl_->consumed.set();
}
bool MediaSampleExchange::waitForSampleConsumed(
std::chrono::milliseconds timeout) {
BOOST_ASSERT_MSG(
sample_ != nullptr,
"Sample pointer should not be null when waiting for consumer!");
return impl_->consumed.wait(timeout.count());
}
<|endoftext|> |
<commit_before>/* bzflag
* Copyright (c) 1993 - 2005 Tim Riker
*
* This package is free software; you can redistribute it and/or
* modify it under the terms of the license found in the file
* named COPYING that should have accompanied this file.
*
* THIS PACKAGE IS PROVIDED ``AS IS'' AND WITHOUT ANY EXPRESS OR
* IMPLIED WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED
* WARRANTIES OF MERCHANTIBILITY AND FITNESS FOR A PARTICULAR PURPOSE.
*/
/* interface header */
#include "JoinMenu.h"
/* common implementation headers */
#include "FontManager.h"
#include "Protocol.h"
#include "ServerList.h"
#include "StartupInfo.h"
#include "TimeKeeper.h"
#include "cURLManager.h"
#include "StateDatabase.h"
#include "Bundle.h"
#include "BundleMgr.h"
/* local implementation headers */
#include "HUDDialogStack.h"
#include "MainMenu.h"
#include "MenuDefaultKey.h"
#include "ServerMenu.h"
#include "ServerStartMenu.h"
#include "TextureManager.h"
/* from playing.h */
extern StartupInfo* getStartupInfo();
extern void joinGame();
JoinMenu* JoinMenu::activeMenu = NULL;
JoinMenu::JoinMenu() : serverStartMenu(NULL), serverMenu(NULL)
{
// cache font face ID
int fontFace = MainMenu::getFontFace();
// add controls
std::vector<HUDuiControl*>& listHUD = getControls();
StartupInfo* info = getStartupInfo();
HUDuiLabel* label = new HUDuiLabel;
label->setFontFace(fontFace);
label->setString("Join Game");
listHUD.push_back(label);
findServer = new HUDuiLabel;
findServer->setFontFace(fontFace);
findServer->setString("Find Server");
listHUD.push_back(findServer);
connectLabel = new HUDuiLabel;
connectLabel->setFontFace(fontFace);
connectLabel->setString("Connect");
listHUD.push_back(connectLabel);
callsign = new HUDuiTypeIn;
callsign->setFontFace(fontFace);
callsign->setLabel("Callsign:");
callsign->setMaxLength(CallSignLen - 1);
callsign->setString(info->callsign);
listHUD.push_back(callsign);
password = new HUDuiTypeIn;
password->setObfuscation(true);
password->setFontFace(fontFace);
password->setLabel("Password:");
password->setMaxLength(CallSignLen - 1);
password->setString(info->password);
listHUD.push_back(password);
team = new HUDuiList;
team->setFontFace(fontFace);
team->setLabel("Team:");
team->setCallback(teamCallback, this);
std::vector<std::string>& teams = team->getList();
// these do not need to be in enum order, but must match getTeam() & setTeam()
teams.push_back(std::string(Team::getName(AutomaticTeam)));
teams.push_back(std::string(Team::getName(RogueTeam)));
teams.push_back(std::string(Team::getName(RedTeam)));
teams.push_back(std::string(Team::getName(GreenTeam)));
teams.push_back(std::string(Team::getName(BlueTeam)));
teams.push_back(std::string(Team::getName(PurpleTeam)));
teams.push_back(std::string(Team::getName(ObserverTeam)));
team->update();
setTeam(info->team);
listHUD.push_back(team);
teamIcon = new HUDuiTextureLabel;
teamIcon->setFontFace(fontFace);
teamIcon->setString(" ");
updateTeamTexture();
listHUD.push_back(teamIcon);
server = new HUDuiTypeIn;
server->setFontFace(fontFace);
server->setLabel("Server:");
server->setMaxLength(64);
server->setString(info->serverName);
listHUD.push_back(server);
char buffer[10];
sprintf(buffer, "%d", info->serverPort);
port = new HUDuiTypeIn;
port->setFontFace(fontFace);
port->setLabel("Port:");
port->setMaxLength(5);
port->setString(buffer);
listHUD.push_back(port);
email = new HUDuiTypeIn;
email->setFontFace(fontFace);
email->setLabel("Email:");
email->setMaxLength(EmailLen - 1);
email->setString(info->email);
listHUD.push_back(email);
startServer = new HUDuiLabel;
startServer->setFontFace(fontFace);
startServer->setString("Start Server");
listHUD.push_back(startServer);
status = new HUDuiLabel;
status->setFontFace(fontFace);
status->setString("");
listHUD.push_back(status);
failedMessage = new HUDuiLabel;
failedMessage->setFontFace(fontFace);
failedMessage->setString("");
listHUD.push_back(failedMessage);
initNavigation(listHUD, 1, listHUD.size() - 3);
// cut teamIcon out of the nav loop
team->setNext(server);
server->setPrev(team);
}
JoinMenu::~JoinMenu()
{
delete serverStartMenu;
delete serverMenu;
}
HUDuiDefaultKey* JoinMenu::getDefaultKey()
{
return MenuDefaultKey::getInstance();
}
void JoinMenu::show()
{
activeMenu = this;
StartupInfo* info = getStartupInfo();
// set fields
callsign->setString(info->callsign);
password->setString(info->password);
setTeam(info->team);
server->setString(info->serverName);
char buffer[10];
sprintf(buffer, "%d", info->serverPort);
port->setString(buffer);
// clear status
setStatus("");
setFailedMessage("");
}
void JoinMenu::dismiss()
{
loadInfo();
activeMenu = NULL;
}
void JoinMenu::loadInfo()
{
// load startup info with current settings
StartupInfo* info = getStartupInfo();
strcpy(info->callsign, callsign->getString().c_str());
strcpy(info->password, password->getString().c_str());
info->team = getTeam();
strcpy(info->serverName, server->getString().c_str());
info->serverPort = atoi(port->getString().c_str());
strcpy(info->email, email->getString().c_str());
}
void JoinMenu::execute()
{
HUDuiControl* _focus = HUDui::getFocus();
if (_focus == startServer) {
if (!serverStartMenu) serverStartMenu = new ServerStartMenu;
HUDDialogStack::get()->push(serverStartMenu);
} else if (_focus == findServer) {
if (!serverMenu) serverMenu = new ServerMenu;
HUDDialogStack::get()->push(serverMenu);
} else if (_focus == connectLabel) {
// load startup info
loadInfo();
// make sure we've got what we need
StartupInfo* info = getStartupInfo();
if (info->callsign[0] == '\0') {
setStatus("You must enter a callsign.");
return;
}
if (info->serverName[0] == '\0') {
setStatus("You must enter a server.");
return;
}
if (info->serverPort <= 0 || info->serverPort > 65535) {
char buffer[60];
sprintf(buffer, "Port is invalid. Try %d.", ServerPort);
setStatus(buffer);
return;
}
// get token if we need to (have a password but no token)
if ((info->token[0] == '\0') && (info->password[0] != '\0')) {
ServerList* serverList = new ServerList;
serverList->startServerPings(info);
// wait no more than 10 seconds for a token
for (int i = 0; i < 40; i++) {
serverList->checkEchos(getStartupInfo());
cURLManager::perform();
if (info->token[0] != '\0') break;
TimeKeeper::sleep(0.25f);
}
delete serverList;
}
// let user know we're trying
setStatus("Trying...");
// don't let the bad token specifier slip through to the server, just erase it
if (strcmp(info->token, "badtoken") == 0)
info->token[0] = '\0';
// schedule attempt to join game
joinGame();
}
}
void JoinMenu::setFailedMessage(const char* msg)
{
failedMessage->setString(msg);
FontManager &fm = FontManager::instance();
const float _width = fm.getStrLength(MainMenu::getFontFace(),
failedMessage->getFontSize(), failedMessage->getString());
failedMessage->setPosition(center - 0.5f * _width, failedMessage->getY());
}
TeamColor JoinMenu::getTeam() const
{
return team->getIndex() == 0 ? AutomaticTeam : TeamColor(team->getIndex() - 1);
}
void JoinMenu::setTeam(TeamColor teamcol)
{
team->setIndex(teamcol == AutomaticTeam ? 0 : int(teamcol) + 1);
}
void JoinMenu::setStatus(const char* msg, const std::vector<std::string> *)
{
status->setString(msg);
FontManager &fm = FontManager::instance();
const float _width = fm.getStrLength(status->getFontFace(),
status->getFontSize(), status->getString());
status->setPosition(center - 0.5f * _width, status->getY());
}
void JoinMenu::teamCallback(HUDuiControl*, void* source)
{
((JoinMenu*)source)->updateTeamTexture();
}
void JoinMenu::updateTeamTexture()
{
TextureManager &tm = TextureManager::instance();
FontManager &fm = FontManager::instance();
// load the appropriate texture
std::string texture;
texture = Team::getImagePrefix(getTeam());
texture += "icon";
int id = tm.getTextureID(texture.c_str());
teamIcon->setTexture(id);
// make it big enough
teamIcon->setFontSize(team->getFontSize() * 1.5f);
// put it at the end of the text
Bundle *bdl = BundleMgr::getCurrentBundle();
const float x = team->getX() + fm.getStrLength(team->getFontFace(),
team->getFontSize(),
bdl->getLocalString(team->getList()[team->getIndex()]) + "x");
teamIcon->setPosition(x, team->getY());
}
void JoinMenu::resize(int _width, int _height)
{
HUDDialog::resize(_width, _height);
// use a big font for title, smaller font for the rest
const float titleFontSize = (float)_height / 15.0f;
const float fontSize = (float)_height / 36.0f;
center = 0.5f * (float)_width;
FontManager &fm = FontManager::instance();
// reposition title
std::vector<HUDuiControl*>& listHUD = getControls();
HUDuiLabel* title = (HUDuiLabel*)listHUD[0];
title->setFontSize(titleFontSize);
const float titleWidth = fm.getStrLength(MainMenu::getFontFace(), titleFontSize, title->getString());
const float titleHeight = fm.getStrHeight(MainMenu::getFontFace(), titleFontSize, "");
float x = 0.5f * ((float)_width - titleWidth);
float y = (float)_height - titleHeight;
title->setPosition(x, y);
// reposition options
x = 0.5f * ((float)_width - 0.5f * titleWidth);
y -= 0.6f * titleHeight;
listHUD[1]->setFontSize(fontSize);
const float h = fm.getStrHeight(MainMenu::getFontFace(), fontSize, "");
const int count = listHUD.size();
for (int i = 1; i < count; i++) {
listHUD[i]->setFontSize(fontSize);
listHUD[i]->setPosition(x, y);
if (i != 5)
y -= 1.0f * h;
if (i <= 2 || i == 9) y -= 0.5f * h;
}
updateTeamTexture();
}
// Local Variables: ***
// mode: C++ ***
// tab-width: 8 ***
// c-basic-offset: 2 ***
// indent-tabs-mode: t ***
// End: ***
// ex: shiftwidth=2 tabstop=8
<commit_msg>load automatic team icon separately<commit_after>/* bzflag
* Copyright (c) 1993 - 2005 Tim Riker
*
* This package is free software; you can redistribute it and/or
* modify it under the terms of the license found in the file
* named COPYING that should have accompanied this file.
*
* THIS PACKAGE IS PROVIDED ``AS IS'' AND WITHOUT ANY EXPRESS OR
* IMPLIED WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED
* WARRANTIES OF MERCHANTIBILITY AND FITNESS FOR A PARTICULAR PURPOSE.
*/
/* interface header */
#include "JoinMenu.h"
/* common implementation headers */
#include "FontManager.h"
#include "Protocol.h"
#include "ServerList.h"
#include "StartupInfo.h"
#include "TimeKeeper.h"
#include "cURLManager.h"
#include "StateDatabase.h"
#include "Bundle.h"
#include "BundleMgr.h"
/* local implementation headers */
#include "HUDDialogStack.h"
#include "MainMenu.h"
#include "MenuDefaultKey.h"
#include "ServerMenu.h"
#include "ServerStartMenu.h"
#include "TextureManager.h"
/* from playing.h */
extern StartupInfo* getStartupInfo();
extern void joinGame();
JoinMenu* JoinMenu::activeMenu = NULL;
JoinMenu::JoinMenu() : serverStartMenu(NULL), serverMenu(NULL)
{
// cache font face ID
int fontFace = MainMenu::getFontFace();
// add controls
std::vector<HUDuiControl*>& listHUD = getControls();
StartupInfo* info = getStartupInfo();
HUDuiLabel* label = new HUDuiLabel;
label->setFontFace(fontFace);
label->setString("Join Game");
listHUD.push_back(label);
findServer = new HUDuiLabel;
findServer->setFontFace(fontFace);
findServer->setString("Find Server");
listHUD.push_back(findServer);
connectLabel = new HUDuiLabel;
connectLabel->setFontFace(fontFace);
connectLabel->setString("Connect");
listHUD.push_back(connectLabel);
callsign = new HUDuiTypeIn;
callsign->setFontFace(fontFace);
callsign->setLabel("Callsign:");
callsign->setMaxLength(CallSignLen - 1);
callsign->setString(info->callsign);
listHUD.push_back(callsign);
password = new HUDuiTypeIn;
password->setObfuscation(true);
password->setFontFace(fontFace);
password->setLabel("Password:");
password->setMaxLength(CallSignLen - 1);
password->setString(info->password);
listHUD.push_back(password);
team = new HUDuiList;
team->setFontFace(fontFace);
team->setLabel("Team:");
team->setCallback(teamCallback, this);
std::vector<std::string>& teams = team->getList();
// these do not need to be in enum order, but must match getTeam() & setTeam()
teams.push_back(std::string(Team::getName(AutomaticTeam)));
teams.push_back(std::string(Team::getName(RogueTeam)));
teams.push_back(std::string(Team::getName(RedTeam)));
teams.push_back(std::string(Team::getName(GreenTeam)));
teams.push_back(std::string(Team::getName(BlueTeam)));
teams.push_back(std::string(Team::getName(PurpleTeam)));
teams.push_back(std::string(Team::getName(ObserverTeam)));
team->update();
setTeam(info->team);
listHUD.push_back(team);
teamIcon = new HUDuiTextureLabel;
teamIcon->setFontFace(fontFace);
teamIcon->setString(" ");
updateTeamTexture();
listHUD.push_back(teamIcon);
server = new HUDuiTypeIn;
server->setFontFace(fontFace);
server->setLabel("Server:");
server->setMaxLength(64);
server->setString(info->serverName);
listHUD.push_back(server);
char buffer[10];
sprintf(buffer, "%d", info->serverPort);
port = new HUDuiTypeIn;
port->setFontFace(fontFace);
port->setLabel("Port:");
port->setMaxLength(5);
port->setString(buffer);
listHUD.push_back(port);
email = new HUDuiTypeIn;
email->setFontFace(fontFace);
email->setLabel("Email:");
email->setMaxLength(EmailLen - 1);
email->setString(info->email);
listHUD.push_back(email);
startServer = new HUDuiLabel;
startServer->setFontFace(fontFace);
startServer->setString("Start Server");
listHUD.push_back(startServer);
status = new HUDuiLabel;
status->setFontFace(fontFace);
status->setString("");
listHUD.push_back(status);
failedMessage = new HUDuiLabel;
failedMessage->setFontFace(fontFace);
failedMessage->setString("");
listHUD.push_back(failedMessage);
initNavigation(listHUD, 1, listHUD.size() - 3);
// cut teamIcon out of the nav loop
team->setNext(server);
server->setPrev(team);
}
JoinMenu::~JoinMenu()
{
delete serverStartMenu;
delete serverMenu;
}
HUDuiDefaultKey* JoinMenu::getDefaultKey()
{
return MenuDefaultKey::getInstance();
}
void JoinMenu::show()
{
activeMenu = this;
StartupInfo* info = getStartupInfo();
// set fields
callsign->setString(info->callsign);
password->setString(info->password);
setTeam(info->team);
server->setString(info->serverName);
char buffer[10];
sprintf(buffer, "%d", info->serverPort);
port->setString(buffer);
// clear status
setStatus("");
setFailedMessage("");
}
void JoinMenu::dismiss()
{
loadInfo();
activeMenu = NULL;
}
void JoinMenu::loadInfo()
{
// load startup info with current settings
StartupInfo* info = getStartupInfo();
strcpy(info->callsign, callsign->getString().c_str());
strcpy(info->password, password->getString().c_str());
info->team = getTeam();
strcpy(info->serverName, server->getString().c_str());
info->serverPort = atoi(port->getString().c_str());
strcpy(info->email, email->getString().c_str());
}
void JoinMenu::execute()
{
HUDuiControl* _focus = HUDui::getFocus();
if (_focus == startServer) {
if (!serverStartMenu) serverStartMenu = new ServerStartMenu;
HUDDialogStack::get()->push(serverStartMenu);
} else if (_focus == findServer) {
if (!serverMenu) serverMenu = new ServerMenu;
HUDDialogStack::get()->push(serverMenu);
} else if (_focus == connectLabel) {
// load startup info
loadInfo();
// make sure we've got what we need
StartupInfo* info = getStartupInfo();
if (info->callsign[0] == '\0') {
setStatus("You must enter a callsign.");
return;
}
if (info->serverName[0] == '\0') {
setStatus("You must enter a server.");
return;
}
if (info->serverPort <= 0 || info->serverPort > 65535) {
char buffer[60];
sprintf(buffer, "Port is invalid. Try %d.", ServerPort);
setStatus(buffer);
return;
}
// get token if we need to (have a password but no token)
if ((info->token[0] == '\0') && (info->password[0] != '\0')) {
ServerList* serverList = new ServerList;
serverList->startServerPings(info);
// wait no more than 10 seconds for a token
for (int i = 0; i < 40; i++) {
serverList->checkEchos(getStartupInfo());
cURLManager::perform();
if (info->token[0] != '\0') break;
TimeKeeper::sleep(0.25f);
}
delete serverList;
}
// let user know we're trying
setStatus("Trying...");
// don't let the bad token specifier slip through to the server, just erase it
if (strcmp(info->token, "badtoken") == 0)
info->token[0] = '\0';
// schedule attempt to join game
joinGame();
}
}
void JoinMenu::setFailedMessage(const char* msg)
{
failedMessage->setString(msg);
FontManager &fm = FontManager::instance();
const float _width = fm.getStrLength(MainMenu::getFontFace(),
failedMessage->getFontSize(), failedMessage->getString());
failedMessage->setPosition(center - 0.5f * _width, failedMessage->getY());
}
TeamColor JoinMenu::getTeam() const
{
return team->getIndex() == 0 ? AutomaticTeam : TeamColor(team->getIndex() - 1);
}
void JoinMenu::setTeam(TeamColor teamcol)
{
team->setIndex(teamcol == AutomaticTeam ? 0 : int(teamcol) + 1);
}
void JoinMenu::setStatus(const char* msg, const std::vector<std::string> *)
{
status->setString(msg);
FontManager &fm = FontManager::instance();
const float _width = fm.getStrLength(status->getFontFace(),
status->getFontSize(), status->getString());
status->setPosition(center - 0.5f * _width, status->getY());
}
void JoinMenu::teamCallback(HUDuiControl*, void* source)
{
((JoinMenu*)source)->updateTeamTexture();
}
void JoinMenu::updateTeamTexture()
{
TextureManager &tm = TextureManager::instance();
FontManager &fm = FontManager::instance();
// load the appropriate texture
std::string texture;
if (getTeam() == AutomaticTeam)
texture = "automatic_";
else
texture = Team::getImagePrefix(getTeam());
texture += "icon";
int id = tm.getTextureID(texture.c_str());
teamIcon->setTexture(id);
// make it big enough
teamIcon->setFontSize(team->getFontSize() * 1.5f);
// put it at the end of the text
Bundle *bdl = BundleMgr::getCurrentBundle();
const float x = team->getX() + fm.getStrLength(team->getFontFace(),
team->getFontSize(),
bdl->getLocalString(team->getList()[team->getIndex()]) + "x");
teamIcon->setPosition(x, team->getY());
}
void JoinMenu::resize(int _width, int _height)
{
HUDDialog::resize(_width, _height);
// use a big font for title, smaller font for the rest
const float titleFontSize = (float)_height / 15.0f;
const float fontSize = (float)_height / 36.0f;
center = 0.5f * (float)_width;
FontManager &fm = FontManager::instance();
// reposition title
std::vector<HUDuiControl*>& listHUD = getControls();
HUDuiLabel* title = (HUDuiLabel*)listHUD[0];
title->setFontSize(titleFontSize);
const float titleWidth = fm.getStrLength(MainMenu::getFontFace(), titleFontSize, title->getString());
const float titleHeight = fm.getStrHeight(MainMenu::getFontFace(), titleFontSize, "");
float x = 0.5f * ((float)_width - titleWidth);
float y = (float)_height - titleHeight;
title->setPosition(x, y);
// reposition options
x = 0.5f * ((float)_width - 0.5f * titleWidth);
y -= 0.6f * titleHeight;
listHUD[1]->setFontSize(fontSize);
const float h = fm.getStrHeight(MainMenu::getFontFace(), fontSize, "");
const int count = listHUD.size();
for (int i = 1; i < count; i++) {
listHUD[i]->setFontSize(fontSize);
listHUD[i]->setPosition(x, y);
if (i != 5)
y -= 1.0f * h;
if (i <= 2 || i == 9) y -= 0.5f * h;
}
updateTeamTexture();
}
// Local Variables: ***
// mode: C++ ***
// tab-width: 8 ***
// c-basic-offset: 2 ***
// indent-tabs-mode: t ***
// End: ***
// ex: shiftwidth=2 tabstop=8
<|endoftext|> |
<commit_before>#ifndef STAN_MATH_PRIM_MAT_PROB_CATEGORICAL_LOGIT_LPMF_HPP
#define STAN_MATH_PRIM_MAT_PROB_CATEGORICAL_LOGIT_LPMF_HPP
#include <stan/math/prim/scal/err/check_bounded.hpp>
#include <stan/math/prim/scal/err/check_finite.hpp>
#include <stan/math/prim/arr/fun/log_sum_exp.hpp>
#include <stan/math/prim/mat/fun/log_softmax.hpp>
#include <stan/math/prim/mat/fun/log_sum_exp.hpp>
#include <stan/math/prim/mat/fun/sum.hpp>
#include <stan/math/prim/scal/meta/include_summand.hpp>
#include <boost/math/tools/promotion.hpp>
#include <vector>
namespace stan {
namespace math {
// CategoricalLog(n|theta) [0 < n <= N, theta unconstrained], no checking
template <bool propto,
typename T_prob>
typename boost::math::tools::promote_args<T_prob>::type
categorical_logit_lpmf(int n,
const Eigen::Matrix<T_prob, Eigen::Dynamic, 1>&
beta) {
static const char* function("categorical_logit_lpmf");
check_bounded(function, "categorical outcome out of support", n,
1, beta.size());
check_finite(function, "log odds parameter", beta);
if (!include_summand<propto, T_prob>::value)
return 0.0;
// FIXME: wasteful vs. creating term (n-1) if not vectorized
return beta(n-1) - log_sum_exp(beta); // == log_softmax(beta)(n-1);
}
template <typename T_prob>
inline
typename boost::math::tools::promote_args<T_prob>::type
categorical_logit_lpmf(int n,
const Eigen::Matrix<T_prob, Eigen::Dynamic, 1>&
beta) {
return categorical_logit_lpmf<false>(n, beta);
}
template <bool propto,
typename T_prob>
typename boost::math::tools::promote_args<T_prob>::type
categorical_logit_lpmf(const std::vector<int>& ns,
const Eigen::Matrix<T_prob, Eigen::Dynamic, 1>&
beta) {
static const char* function("categorical_logit_lpmf");
for (size_t k = 0; k < ns.size(); ++k)
check_bounded(function, "categorical outcome out of support",
ns[k], 1, beta.size());
check_finite(function, "log odds parameter", beta);
if (!include_summand<propto, T_prob>::value)
return 0.0;
if (ns.size() == 0)
return 0.0;
Eigen::Matrix<T_prob, Eigen::Dynamic, 1> log_softmax_beta
= log_softmax(beta);
// FIXME: replace with more efficient sum()
Eigen::Matrix<typename boost::math::tools::promote_args<T_prob>::type,
Eigen::Dynamic, 1> results(ns.size());
for (size_t i = 0; i < ns.size(); ++i)
results[i] = log_softmax_beta(ns[i] - 1);
return sum(results);
}
template <typename T_prob>
inline
typename boost::math::tools::promote_args<T_prob>::type
categorical_logit_lpmf(const std::vector<int>& ns,
const Eigen::Matrix<T_prob, Eigen::Dynamic, 1>&
beta) {
return categorical_logit_lpmf<false>(ns, beta);
}
}
}
#endif
<commit_msg>restoring categorical<commit_after>#ifndef STAN_MATH_PRIM_MAT_PROB_CATEGORICAL_LOGIT_LPMF_HPP
#define STAN_MATH_PRIM_MAT_PROB_CATEGORICAL_LOGIT_LPMF_HPP
#include <stan/math/prim/scal/err/check_bounded.hpp>
#include <stan/math/prim/scal/err/check_finite.hpp>
#include <stan/math/prim/arr/fun/log_sum_exp.hpp>
#include <stan/math/prim/mat/fun/log_softmax.hpp>
#include <stan/math/prim/mat/fun/log_sum_exp.hpp>
#include <stan/math/prim/mat/fun/sum.hpp>
#include <stan/math/prim/scal/meta/include_summand.hpp>
#include <boost/math/tools/promotion.hpp>
#include <string>
#include <vector>
namespace stan {
namespace math {
// CategoricalLog(n|theta) [0 < n <= N, theta unconstrained], no checking
template <bool propto,
typename T_prob>
typename boost::math::tools::promote_args<T_prob>::type
categorical_logit_lpmf(int n,
const Eigen::Matrix<T_prob, Eigen::Dynamic, 1>&
beta) {
static const std::string function = "categorical_logit_lpmf";
check_bounded(function, "categorical outcome out of support", n,
1, beta.size());
check_finite(function, "log odds parameter", beta);
if (!include_summand<propto, T_prob>::value)
return 0.0;
// FIXME: wasteful vs. creating term (n-1) if not vectorized
return beta(n - 1) - log_sum_exp(beta); // == log_softmax(beta)(n-1);
}
template <typename T_prob>
inline
typename boost::math::tools::promote_args<T_prob>::type
categorical_logit_lpmf(int n,
const Eigen::Matrix<T_prob, Eigen::Dynamic, 1>&
beta) {
return categorical_logit_lpmf<false>(n, beta);
}
template <bool propto,
typename T_prob>
typename boost::math::tools::promote_args<T_prob>::type
categorical_logit_lpmf(const std::vector<int>& ns,
const Eigen::Matrix<T_prob, Eigen::Dynamic, 1>&
beta) {
static const std::string function = "categorical_logit_lpmf";
for (size_t k = 0; k < ns.size(); ++k)
check_bounded(function, "categorical outcome out of support",
ns[k], 1, beta.size());
check_finite(function, "log odds parameter", beta);
if (!include_summand<propto, T_prob>::value)
return 0.0;
if (ns.size() == 0)
return 0.0;
Eigen::Matrix<T_prob, Eigen::Dynamic, 1> log_softmax_beta
= log_softmax(beta);
// FIXME: replace with more efficient sum()
Eigen::Matrix<typename boost::math::tools::promote_args<T_prob>::type,
Eigen::Dynamic, 1> results(ns.size());
for (size_t i = 0; i < ns.size(); ++i)
results[i] = log_softmax_beta(ns[i] - 1);
return sum(results);
}
template <typename T_prob>
inline
typename boost::math::tools::promote_args<T_prob>::type
categorical_logit_lpmf(const std::vector<int>& ns,
const Eigen::Matrix<T_prob, Eigen::Dynamic, 1>&
beta) {
return categorical_logit_lpmf<false>(ns, beta);
}
}
}
#endif
<|endoftext|> |
<commit_before>/** \file extract_normdata_translations.cc
* \brief Extract IxTheo and MACS translations from the normdata file and write it to
* language specific text files
* \author Johannes Riedl
*/
/*
Copyright (C) 2016, Library of the University of Tübingen
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as
published by the Free Software Foundation, either version 3 of the
License, or (at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
/* The German term is found in Field 150
Currently there are two different kinds of translations:
IxTheo-Translations with the following definitions:
710: Körperschaft - fremdsprachige Äquivalenz
711: Konferenz - fremdsprachige Äquivalenz
700: Person - fremdsprachige Äquivalenz
730: Titel - fremdsprachige Äquivalenz
750: Sachbegriff - fremdsprachige Äquivalenz
751: Geografikum - fremdsprachige Äquivalenz
LoC/Rameau Translations:
700: Person - Bevorzugter Name in einem anderen Datenbestand
710: Körperschaft - Bevorzugter Name in einem anderen Datenbestand
711: Konferenz - Bevorzugte Benennung in einem anderen Datenbestand
730: Einheitstitel - Bevorzugter Name in einem anderen Datenbestand
750: Sachbegriff - Bevorzugte Benennung in einem anderen Datenbestand
751: Geografikum - Bevorzugter Name in einem anderen Datenbestand
*/
#include <iostream>
#include <vector>
#include <cstdlib>
#include "Compiler.h"
#include "MarcUtil.h"
#include "MediaTypeUtil.h"
#include "StringUtil.h"
#include "Subfields.h"
#include "util.h"
// Languages to handle
const unsigned int NUMBER_OF_LANGUAGES = 2;
const std::vector<std::string> languages_to_create{ "en", "fr" };
enum languages { en, fr };
void Usage() {
std::cerr << "Usage: " << ::progname << " norm_data_marc_input extracted_translations\n";
std::exit(EXIT_FAILURE);
}
void AugmentIxTheoTagWithLanguage(const MarcUtil::Record &record, const std::string &tag, std::vector<std::string> * const translations) {
auto ixtheo_pos = std::find(translations->begin(), translations->end(), "IxTheo");
if (ixtheo_pos != translations->end()) {
std::vector<std::string> ixtheo_lang_code;
record.extractSubfields(tag, "9", &ixtheo_lang_code);
bool already_found_ixtheo_translation = false;
for (auto lang_code : ixtheo_lang_code) {
if (lang_code[0] != 'L')
continue;
if (already_found_ixtheo_translation)
continue;
if (lang_code.find("eng") != std::string::npos and *ixtheo_pos != "IxTheo_eng") {
*ixtheo_pos = *ixtheo_pos + "_eng";
already_found_ixtheo_translation = true;
}
else if (lang_code.find("fra") != std::string::npos and *ixtheo_pos != "IxTheo_fra") {
*ixtheo_pos = *ixtheo_pos + "_fra";
already_found_ixtheo_translation = true;
}
else
Warning("Unsupported language code \"" + lang_code + "\" for PPN " + record.getFields()[0]);
}
}
}
void ExtractTranslations(File* const marc_norm_input,
const std::string german_term_field_spec,
const std::string translation_field_spec,
std::map<std::string, std::string> term_to_translation_maps[])
{
std::set<std::string> german_tags_and_subfield_codes;
if (unlikely(StringUtil::Split(german_term_field_spec, ':', &german_tags_and_subfield_codes) < 1))
Error("ExtractTranslations: Need at least one translation field");
std::set<std::string> translation_tags_and_subfield_codes;
if (unlikely(StringUtil::Split(translation_field_spec, ':', &translation_tags_and_subfield_codes) < 1))
Error("ExtractTranslations: Need at least one translation field");
unsigned count(0);
while (const MarcUtil::Record record = MarcUtil::Record::XmlFactory(marc_norm_input)) {
std::vector<std::string> german_terms;
// Determine the German term we will have translations for
for (const auto tag_and_subfields : german_tags_and_subfield_codes) {
const std::string tag(tag_and_subfields.substr(0, 3));
const std::string subfields(tag_and_subfields.substr(3));
std::vector<std::string> german_term_for_one_field;
record.extractSubfields(tag, subfields, &german_term_for_one_field);
// We may get the german term from only one field
if (german_terms.size() > 1)
Warning("We have german terms in more than one field for PPN: " + record.getFields()[0]);
if (not german_term_for_one_field.empty())
german_terms = german_term_for_one_field;
}
std::vector<std::string> all_translations;
// Extract all additional translations
for (auto tag_and_subfields : translation_tags_and_subfield_codes) {
const std::string tag(tag_and_subfields.substr(0, 3));
const std::string subfields(tag_and_subfields.substr(3));
std::vector<std::string> translations;
record.extractSubfields(tag, subfields, &translations);
// For IxTheo-Translations add the language code in the same field
AugmentIxTheoTagWithLanguage(record, tag, &translations);
all_translations.insert(all_translations.end(), translations.begin(), translations.end());
}
for (auto it = all_translations.begin(); it != all_translations.end(); ++it) {
if (*it == "IxTheo_eng") {
term_to_translation_maps[en].emplace(StringUtil::Join(german_terms, ' '), *(it + 1));
++it;
} else if (*it == "IxTheo_fra") {
term_to_translation_maps[fr].emplace(StringUtil::Join(german_terms, ' '), *(it + 1));
++it;
} else if (*it == "lcsh") {
term_to_translation_maps[en].emplace(StringUtil::Join(german_terms, ' '), *(it + 1));
++it;
} else if (*it == "ram") {
term_to_translation_maps[fr].emplace(StringUtil::Join(german_terms, ' '), *(it + 1));
++it;
}
}
}
++count;
}
std::unique_ptr<File> OpenInputFile(const std::string &filename) {
std::string mode("r");
if (MediaTypeUtil::GetFileMediaType(filename) == "application/lz4")
mode += "u";
std::unique_ptr<File> file(new File(filename, mode));
if (file->fail())
Error("can't open \"" + filename + "\" for reading!");
return file;
}
int main(int argc, char **argv) {
::progname = argv[0];
if (argc != 3)
Usage();
const std::string norm_data_marc_input_filename(argv[1]);
std::unique_ptr<File> norm_data_marc_input(OpenInputFile(norm_data_marc_input_filename));
const std::string extracted_translations_filename(argv[2]);
if (unlikely(norm_data_marc_input_filename == extracted_translations_filename))
Error("Norm data input file name equals output file name!");
std::string output_mode("w");
if (norm_data_marc_input->isCompressingOrUncompressing())
output_mode += 'c';
// Create a file for each language
std::vector<std::string> output_file_components;
if (unlikely(StringUtil::Split(extracted_translations_filename, ".", &output_file_components) < 1))
Error("extracted_translations_filename " + extracted_translations_filename + " is not valid");
File *lang_files[NUMBER_OF_LANGUAGES];
unsigned i(0);
// Derive output components from given input filename
std::string extension = (output_file_components.size() > 1) ? output_file_components.back() : "";
std::string basename;
if (not extension.empty())
output_file_components.pop_back();
basename = StringUtil::Join(output_file_components, ".");
// Assemble output filename
for (auto lang : languages_to_create) {
lang = StringUtil::Trim(lang);
std::string lang_file_name_str =
(extension != "") ? basename + "_" + lang + "." + extension : basename + "_" + lang;
lang_files[i] = new File(lang_file_name_str, output_mode);
if (lang_files[i]->fail())
Error("can't open \"" + lang_file_name_str + "\" for writing!");
++i;
}
try {
std::map<std::string, std::string> term_to_translation_maps[NUMBER_OF_LANGUAGES];
ExtractTranslations(norm_data_marc_input.get(), "100a:150a", "750a2", term_to_translation_maps);
for (auto line : term_to_translation_maps[en]) {
*(lang_files[en]) << line.first << "|" << line.second << "\n";
}
for (auto line : term_to_translation_maps[fr]) {
*(lang_files[fr]) << line.first << "|" << line.second << "\n";
}
} catch (const std::exception &x) {
Error("caught exception: " + std::string(x.what()));
}
}
<commit_msg>Required adjustments<commit_after>/** \file extract_normdata_translations.cc
* \brief Extract IxTheo and MACS translations from the normdata file and write it to
* language specific text files
* \author Johannes Riedl
*/
/*
Copyright (C) 2016, Library of the University of Tübingen
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as
published by the Free Software Foundation, either version 3 of the
License, or (at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
/* The German term is found in Field 150
Currently there are two different kinds of translations:
IxTheo-Translations with the following definitions:
710: Körperschaft - fremdsprachige Äquivalenz
711: Konferenz - fremdsprachige Äquivalenz
700: Person - fremdsprachige Äquivalenz
730: Titel - fremdsprachige Äquivalenz
750: Sachbegriff - fremdsprachige Äquivalenz
751: Geografikum - fremdsprachige Äquivalenz
LoC/Rameau Translations:
700: Person - Bevorzugter Name in einem anderen Datenbestand
710: Körperschaft - Bevorzugter Name in einem anderen Datenbestand
711: Konferenz - Bevorzugte Benennung in einem anderen Datenbestand
730: Einheitstitel - Bevorzugter Name in einem anderen Datenbestand
750: Sachbegriff - Bevorzugte Benennung in einem anderen Datenbestand
751: Geografikum - Bevorzugter Name in einem anderen Datenbestand
*/
#include <iostream>
#include <vector>
#include <cstdlib>
#include "Compiler.h"
#include "MarcUtil.h"
#include "MediaTypeUtil.h"
#include "StringUtil.h"
#include "Subfields.h"
#include "util.h"
// Languages to handle
const unsigned int NUMBER_OF_LANGUAGES = 2;
const std::vector<std::string> languages_to_create{ "en", "fr" };
enum languages { en, fr };
void Usage() {
std::cerr << "Usage: " << ::progname << " norm_data_marc_input extracted_translations\n";
std::exit(EXIT_FAILURE);
}
void AugmentIxTheoTagWithLanguage(const MarcUtil::Record &record, const std::string &tag, std::vector<std::string> * const translations) {
auto ixtheo_pos = std::find(translations->begin(), translations->end(), "IxTheo");
if (ixtheo_pos != translations->end()) {
std::vector<std::string> ixtheo_lang_code;
record.extractSubfields(tag, "9", &ixtheo_lang_codes);
bool already_found_ixtheo_translation(false);
for (const auto &lang_code : ixtheo_lang_codes) {
if (lang_code[0] != 'L')
continue;
if (already_found_ixtheo_translation)
continue;
if (lang_code.find("eng") != std::string::npos and *ixtheo_pos != "IxTheo_eng") {
*ixtheo_pos += + "_eng";
already_found_ixtheo_translation = true;
} else if (lang_code.find("fra") != std::string::npos and *ixtheo_pos != "IxTheo_fra") {
*ixtheo_pos += "_fra";
already_found_ixtheo_translation = true;
} else
Warning("Unsupported language code \"" + lang_code + "\" for PPN " + record.getFields()[0]);
}
}
}
void ExtractTranslations(File* const marc_norm_input,
const std::string german_term_field_spec,
const std::string translation_field_spec,
std::map<std::string, std::string> term_to_translation_maps[])
{
std::set<std::string> german_tags_and_subfield_codes;
if (unlikely(StringUtil::Split(german_term_field_spec, ':', &german_tags_and_subfield_codes) < 1))
Error("ExtractTranslations: Need at least one translation field");
std::set<std::string> translation_tags_and_subfield_codes;
if (unlikely(StringUtil::Split(translation_field_spec, ':', &translation_tags_and_subfield_codes) < 1))
Error("ExtractTranslations: Need at least one translation field");
unsigned count(0);
while (const MarcUtil::Record record = MarcUtil::Record::XmlFactory(marc_norm_input)) {
std::vector<std::string> german_terms;
// Determine the German term we will have translations for
for (const auto tag_and_subfields : german_tags_and_subfield_codes) {
const std::string tag(tag_and_subfields.substr(0, 3));
const std::string subfields(tag_and_subfields.substr(3));
std::vector<std::string> german_term_for_one_field;
record.extractSubfields(tag, subfields, &german_term_for_one_field);
// We may get the german term from only one field
if (german_terms.size() > 1)
Warning("We have german terms in more than one field for PPN: " + record.getFields()[0]);
if (not german_term_for_one_field.empty())
german_terms = german_term_for_one_field;
}
std::vector<std::string> all_translations;
// Extract all additional translations
for (auto tag_and_subfields : translation_tags_and_subfield_codes) {
const std::string tag(tag_and_subfields.substr(0, 3));
const std::string subfields(tag_and_subfields.substr(3));
std::vector<std::string> translations;
record.extractSubfields(tag, subfields, &translations);
// For IxTheo-Translations add the language code in the same field
AugmentIxTheoTagWithLanguage(record, tag, &translations);
all_translations.insert(all_translations.end(), translations.begin(), translations.end());
}
for (auto it = all_translations.begin(); it != all_translations.end(); ++it) {
if (*it == "IxTheo_eng") {
term_to_translation_maps[en].emplace(StringUtil::Join(german_terms, ' '), *(it + 1));
++it;
} else if (*it == "IxTheo_fra") {
term_to_translation_maps[fr].emplace(StringUtil::Join(german_terms, ' '), *(it + 1));
++it;
} else if (*it == "lcsh") {
term_to_translation_maps[en].emplace(StringUtil::Join(german_terms, ' '), *(it + 1));
++it;
} else if (*it == "ram") {
term_to_translation_maps[fr].emplace(StringUtil::Join(german_terms, ' '), *(it + 1));
++it;
}
}
}
++count;
}
std::unique_ptr<File> OpenInputFile(const std::string &filename) {
std::string mode("r");
if (MediaTypeUtil::GetFileMediaType(filename) == "application/lz4")
mode += "u";
std::unique_ptr<File> file(new File(filename, mode));
if (file->fail())
Error("can't open \"" + filename + "\" for reading!");
return file;
}
int main(int argc, char **argv) {
::progname = argv[0];
if (argc != 3)
Usage();
const std::string norm_data_marc_input_filename(argv[1]);
std::unique_ptr<File> norm_data_marc_input(OpenInputFile(norm_data_marc_input_filename));
const std::string extracted_translations_filename(argv[2]);
if (unlikely(norm_data_marc_input_filename == extracted_translations_filename))
Error("Norm data input file name equals output file name!");
std::string output_mode("w");
if (norm_data_marc_input->isCompressingOrUncompressing())
output_mode += 'c';
// Create a file for each language
std::vector<std::string> output_file_components;
if (unlikely(StringUtil::Split(extracted_translations_filename, ".", &output_file_components) < 1))
Error("extracted_translations_filename " + extracted_translations_filename + " is not valid");
File *lang_files[NUMBER_OF_LANGUAGES];
unsigned i(0);
// Derive output components from given input filename
std::string extension = (output_file_components.size() > 1) ? output_file_components.back() : "";
std::string basename;
if (not extension.empty())
output_file_components.pop_back();
basename = StringUtil::Join(output_file_components, ".");
// Assemble output filename
for (auto lang : languages_to_create) {
lang = StringUtil::Trim(lang);
std::string lang_file_name_str =
(extension != "") ? basename + "_" + lang + "." + extension : basename + "_" + lang;
lang_files[i] = new File(lang_file_name_str, output_mode);
if (lang_files[i]->fail())
Error("can't open \"" + lang_file_name_str + "\" for writing!");
++i;
}
try {
std::map<std::string, std::string> term_to_translation_maps[NUMBER_OF_LANGUAGES];
ExtractTranslations(norm_data_marc_input.get(), "100a:150a", "750a2", term_to_translation_maps);
for (auto line : term_to_translation_maps[en]) {
*(lang_files[en]) << line.first << "|" << line.second << "\n";
}
for (auto line : term_to_translation_maps[fr]) {
*(lang_files[fr]) << line.first << "|" << line.second << "\n";
}
} catch (const std::exception &x) {
Error("caught exception: " + std::string(x.what()));
}
}
<|endoftext|> |
<commit_before> /*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: environmentofanchoredobject.hxx,v $
*
* $Revision: 1.4 $
*
* last change: $Author: rt $ $Date: 2005-09-09 03:46:20 $
*
* The Contents of this file are made available subject to
* the terms of GNU Lesser General Public License Version 2.1.
*
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2005 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
************************************************************************/
#ifndef _ENVIRONMENTOFANCHOREDOBJECT_HXX
#define _ENVIRONMENTOFANCHOREDOBJECT_HXX
class SwFrm;
class SwLayoutFrm;
namespace objectpositioning
{
class SwEnvironmentOfAnchoredObject
{
private:
const bool mbFollowTextFlow;
public:
/** construtor
OD 05.11.2003
@author OD
@param _bFollowTextFlow
input parameter - indicates, if the anchored object, for which
this environment is instantiated, follow the text flow or not
*/
SwEnvironmentOfAnchoredObject( const bool _bFollowTextFlow );
/** destructor
OD 05.11.2003
@author OD
*/
~SwEnvironmentOfAnchoredObject();
/** determine environment layout frame for possible horizontal object
positions respectively for alignment to 'page areas'
OD 05.11.2003
this is, if object has to follow the text flow:
- cell frame, if anchored inside a cell
- fly frame, if anchored inside a fly frame
otherwise it's the page frame
this is, if object hasn't to follow the text flow:
- page frame.
OD 2005-01-20 #118546# - no exception any more. Thus remove
parameter <_bForPageAlignment>
@author OD
@param _rHoriOrientFrm
input parameter - frame, at which the horizontal position is
oriented at (typically it's the anchor frame).
starting point for the search of the layout frame.
@return reference to the layout frame, which determines the
the horizontal environment the object has to be positioned in.
*/
const SwLayoutFrm& GetHoriEnvironmentLayoutFrm( const SwFrm& _rHoriOrientFrm ) const;
/** determine environment layout frame for possible vertical object
positions respectively for alignments to 'page areas'
OD 05.11.2003
this is, if object has to follow the text flow:
- cell frame, if anchored inside a cell
- fly frame, if anchored inside a fly frame
- header/footer frame, if anchored inside page header/footer
- footnote frame, if anchored inside footnote
otherwise it's the document body frame
this is, if object hasn't to follow the text flow:
- page frame.
OD 2005-01-20 #118546# - no exception any more. Thus remove
parameter <_bForPageAlignment>
@author OD
@param _rVertOrientFrm
input parameter - frame, at which the vertical position is
oriented at (typically it's the anchor frame).
starting point for the search of the layout frame.
@return reference to the layout frame, which determines the
the vertical environment the object has to be positioned in.
*/
const SwLayoutFrm& GetVertEnvironmentLayoutFrm( const SwFrm& _rVertOrientFrm ) const;
};
};
#endif
<commit_msg>INTEGRATION: CWS swwarnings (1.4.710); FILE MERGED 2007/03/05 12:45:26 tl 1.4.710.1: #i69287# warning-free code<commit_after> /*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: environmentofanchoredobject.hxx,v $
*
* $Revision: 1.5 $
*
* last change: $Author: hr $ $Date: 2007-09-27 08:55:55 $
*
* The Contents of this file are made available subject to
* the terms of GNU Lesser General Public License Version 2.1.
*
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2005 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
************************************************************************/
#ifndef _ENVIRONMENTOFANCHOREDOBJECT_HXX
#define _ENVIRONMENTOFANCHOREDOBJECT_HXX
class SwFrm;
class SwLayoutFrm;
namespace objectpositioning
{
class SwEnvironmentOfAnchoredObject
{
private:
const bool mbFollowTextFlow;
public:
/** construtor
OD 05.11.2003
@author OD
@param _bFollowTextFlow
input parameter - indicates, if the anchored object, for which
this environment is instantiated, follow the text flow or not
*/
SwEnvironmentOfAnchoredObject( const bool _bFollowTextFlow );
/** destructor
OD 05.11.2003
@author OD
*/
~SwEnvironmentOfAnchoredObject();
/** determine environment layout frame for possible horizontal object
positions respectively for alignment to 'page areas'
OD 05.11.2003
this is, if object has to follow the text flow:
- cell frame, if anchored inside a cell
- fly frame, if anchored inside a fly frame
otherwise it's the page frame
this is, if object hasn't to follow the text flow:
- page frame.
OD 2005-01-20 #118546# - no exception any more. Thus remove
parameter <_bForPageAlignment>
@author OD
@param _rHoriOrientFrm
input parameter - frame, at which the horizontal position is
oriented at (typically it's the anchor frame).
starting point for the search of the layout frame.
@return reference to the layout frame, which determines the
the horizontal environment the object has to be positioned in.
*/
const SwLayoutFrm& GetHoriEnvironmentLayoutFrm( const SwFrm& _rHoriOrientFrm ) const;
/** determine environment layout frame for possible vertical object
positions respectively for alignments to 'page areas'
OD 05.11.2003
this is, if object has to follow the text flow:
- cell frame, if anchored inside a cell
- fly frame, if anchored inside a fly frame
- header/footer frame, if anchored inside page header/footer
- footnote frame, if anchored inside footnote
otherwise it's the document body frame
this is, if object hasn't to follow the text flow:
- page frame.
OD 2005-01-20 #118546# - no exception any more. Thus remove
parameter <_bForPageAlignment>
@author OD
@param _rVertOrientFrm
input parameter - frame, at which the vertical position is
oriented at (typically it's the anchor frame).
starting point for the search of the layout frame.
@return reference to the layout frame, which determines the
the vertical environment the object has to be positioned in.
*/
const SwLayoutFrm& GetVertEnvironmentLayoutFrm( const SwFrm& _rVertOrientFrm ) const;
};
} // namespace objectpositioning
#endif
<|endoftext|> |
<commit_before>/** \brief Detect missing references in title data records
* \author Johannes Riedl
*
* \copyright 2019-2020 Universitätsbibliothek Tübingen. All rights reserved.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include <iostream>
#include <unordered_map>
#include <cstdio>
#include <cstdlib>
#include "Compiler.h"
#include "FileUtil.h"
#include "StringUtil.h"
#include "MARC.h"
#include "util.h"
namespace {
[[noreturn]] void Usage() {
::Usage("[--consider-only-reviews] marc_input dangling_log");
}
void CollectAllPPNs(MARC::Reader * const reader, std::unordered_set<std::string> * const all_ppns) {
while (const auto record = reader->read())
all_ppns->emplace(record.getControlNumber());
}
inline bool IsPartOfTitleData(const std::unordered_set<std::string> &all_ppns, const std::string &referenced_ppn) {
return all_ppns.find(referenced_ppn) != all_ppns.cend();
}
const std::vector<MARC::Tag> REFERENCE_FIELDS{ MARC::Tag("775"), MARC::Tag("776"), MARC::Tag("780"),
MARC::Tag("785"), MARC::Tag("787") };
void FindDanglingCrossReferences(MARC::Reader * const reader, const bool consider_only_reviews,
const std::unordered_set<std::string> &all_ppns, File * const dangling_log)
{
unsigned unreferenced_ppns(0);
while (const auto record = reader->read()) {
for (const auto &field : record) {
std::string referenced_ppn;
if ((not consider_only_reviews or record.isReviewArticle())
and MARC::IsCrossLinkField(field, &referenced_ppn, REFERENCE_FIELDS)
and not IsPartOfTitleData(all_ppns, referenced_ppn))
{
*dangling_log << record.getControlNumber() << "," << referenced_ppn << '\n';
++unreferenced_ppns;
}
}
}
LOG_INFO("Detected " + std::to_string(unreferenced_ppns) + " unreferenced ppns");
}
} // unnamed namespace
int Main(int argc, char *argv[]) {
if (argc != 3 and argc != 4)
Usage();
bool consider_only_reviews(false);
if (__builtin_strcmp(argv[1], "--consider-only-reviews") == 0) {
consider_only_reviews = true;
--argc, ++argv;
}
if (argc != 3)
Usage();
auto marc_reader(MARC::Reader::Factory(argv[1]));
const auto dangling_log(FileUtil::OpenOutputFileOrDie(argv[2]));
std::unordered_set<std::string> all_ppns;
CollectAllPPNs(marc_reader.get(), &all_ppns);
marc_reader->rewind();
FindDanglingCrossReferences(marc_reader.get(), consider_only_reviews, all_ppns, dangling_log.get());
return EXIT_SUCCESS;
}
<commit_msg>More efficient.<commit_after>/** \brief Detect missing references in title data records
* \author Johannes Riedl
*
* \copyright 2019-2020 Universitätsbibliothek Tübingen. All rights reserved.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include <iostream>
#include <unordered_map>
#include <cstdio>
#include <cstdlib>
#include "Compiler.h"
#include "FileUtil.h"
#include "StringUtil.h"
#include "MARC.h"
#include "util.h"
namespace {
[[noreturn]] void Usage() {
::Usage("[--consider-only-reviews] marc_input dangling_log");
}
void CollectAllPPNs(MARC::Reader * const reader, std::unordered_set<std::string> * const all_ppns) {
while (const auto record = reader->read())
all_ppns->emplace(record.getControlNumber());
}
inline bool IsPartOfTitleData(const std::unordered_set<std::string> &all_ppns, const std::string &referenced_ppn) {
return all_ppns.find(referenced_ppn) != all_ppns.cend();
}
const std::vector<MARC::Tag> REFERENCE_FIELDS{ MARC::Tag("775"), MARC::Tag("776"), MARC::Tag("780"),
MARC::Tag("785"), MARC::Tag("787") };
void FindDanglingCrossReferences(MARC::Reader * const reader, const bool consider_only_reviews,
const std::unordered_set<std::string> &all_ppns, File * const dangling_log)
{
unsigned unreferenced_ppns(0);
while (const auto record = reader->read()) {
if (consider_only_reviews and not record.isReviewArticle())
continue;
for (const auto &field : record) {
std::string referenced_ppn;
if (MARC::IsCrossLinkField(field, &referenced_ppn, REFERENCE_FIELDS)
and not IsPartOfTitleData(all_ppns, referenced_ppn))
{
*dangling_log << record.getControlNumber() << "," << referenced_ppn << '\n';
++unreferenced_ppns;
}
}
}
LOG_INFO("Detected " + std::to_string(unreferenced_ppns) + " unreferenced ppns");
}
} // unnamed namespace
int Main(int argc, char *argv[]) {
if (argc != 3 and argc != 4)
Usage();
bool consider_only_reviews(false);
if (__builtin_strcmp(argv[1], "--consider-only-reviews") == 0) {
consider_only_reviews = true;
--argc, ++argv;
}
if (argc != 3)
Usage();
auto marc_reader(MARC::Reader::Factory(argv[1]));
const auto dangling_log(FileUtil::OpenOutputFileOrDie(argv[2]));
std::unordered_set<std::string> all_ppns;
CollectAllPPNs(marc_reader.get(), &all_ppns);
marc_reader->rewind();
FindDanglingCrossReferences(marc_reader.get(), consider_only_reviews, all_ppns, dangling_log.get());
return EXIT_SUCCESS;
}
<|endoftext|> |
<commit_before>/* Copyright 2017 The TensorFlow Authors. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
==============================================================================*/
// XLA-specific sequence and range Ops.
#include "tensorflow/compiler/tf2xla/xla_helpers.h"
#include "tensorflow/compiler/tf2xla/xla_op_kernel.h"
#include "tensorflow/compiler/tf2xla/xla_op_registry.h"
#include "tensorflow/compiler/xla/client/lib/constants.h"
#include "tensorflow/compiler/xla/client/xla_builder.h"
#include "tensorflow/compiler/xla/literal.h"
#include "tensorflow/compiler/xla/primitive_util.h"
#include "tensorflow/core/framework/op_kernel.h"
#include "tensorflow/core/framework/register_types.h"
#include "tensorflow/core/framework/tensor.h"
#include "tensorflow/core/framework/tensor_shape.h"
#include "tensorflow/core/framework/types.h"
namespace tensorflow {
namespace {
// The type-specific part of the implementation of Range.
template <typename T>
xla::StatusOr<xla::XlaOp> CreateRangeTensor(
const xla::LiteralSlice& start_literal,
const xla::LiteralSlice& limit_literal,
const xla::LiteralSlice& delta_literal, xla::XlaBuilder* builder) {
T start = start_literal.Get<T>({});
T limit = limit_literal.Get<T>({});
T delta = delta_literal.Get<T>({});
if (delta == 0) {
return errors::InvalidArgument("Requires delta != 0: ", delta);
}
if (delta > 0) {
if (start > limit) {
return errors::InvalidArgument(
"Requires start <= limit when delta > 0: ", start, "/", limit);
}
} else {
if (start < limit) {
return errors::InvalidArgument(
"Requires start >= limit when delta < 0: ", start, "/", limit);
}
}
int64 size =
(std::is_integral<T>::value
? ((std::abs(limit - start) + std::abs(delta) - 1) / std::abs(delta))
: std::ceil(std::abs((limit - start) / delta)));
return xla::ConstantR0(builder, start) +
xla::ConstantR0(builder, delta) *
xla::Iota(builder, xla::primitive_util::NativeToPrimitiveType<T>(),
size);
}
class RangeOp : public XlaOpKernel {
public:
explicit RangeOp(OpKernelConstruction* ctx) : XlaOpKernel(ctx) {}
void Compile(XlaOpKernelContext* ctx) override {
const TensorShape start_in_shape = ctx->InputShape(0);
const TensorShape limit_in_shape = ctx->InputShape(1);
const TensorShape delta_in_shape = ctx->InputShape(2);
OP_REQUIRES(ctx, TensorShapeUtils::IsScalar(start_in_shape),
errors::InvalidArgument("start must be a scalar, not shape ",
start_in_shape.DebugString()));
OP_REQUIRES(ctx, TensorShapeUtils::IsScalar(limit_in_shape),
errors::InvalidArgument("limit must be a scalar, not shape ",
limit_in_shape.DebugString()));
OP_REQUIRES(ctx, TensorShapeUtils::IsScalar(delta_in_shape),
errors::InvalidArgument("delta must be a scalar, not shape ",
delta_in_shape.DebugString()));
xla::Literal start, limit, delta;
OP_REQUIRES_OK(ctx, ctx->ConstantInput(
0, &start, xla::ValueInferenceMode::kLowerBound));
OP_REQUIRES_OK(ctx, ctx->ConstantInput(
1, &limit, xla::ValueInferenceMode::kUpperBound));
OP_REQUIRES_OK(ctx, ctx->ConstantInput(2, &delta));
DataType type = input_type(0);
xla::StatusOr<xla::XlaOp> output;
switch (type) {
case DT_INT32:
output = CreateRangeTensor<int32>(start, limit, delta, ctx->builder());
break;
case DT_INT64:
output = CreateRangeTensor<int64>(start, limit, delta, ctx->builder());
break;
case DT_FLOAT:
output = CreateRangeTensor<float>(start, limit, delta, ctx->builder());
break;
case DT_DOUBLE:
output = CreateRangeTensor<double>(start, limit, delta, ctx->builder());
break;
default:
output = errors::InvalidArgument("Invalid type for Range ",
DataTypeString(type));
}
OP_REQUIRES_OK(ctx, output.status());
bool start_is_dynamic = false;
OP_REQUIRES_OK(ctx,
ctx->ResolveInputDynamismIntoPred(0, &start_is_dynamic));
bool limit_is_dynamic = false;
OP_REQUIRES_OK(ctx,
ctx->ResolveInputDynamismIntoPred(1, &limit_is_dynamic));
if (start_is_dynamic || limit_is_dynamic) {
xla::XlaOp delta = ctx->Input(2);
xla::XlaOp limit = ctx->Input(1);
xla::XlaOp start = ctx->Input(0);
if (type == DT_INT32 || type == DT_INT64) {
auto dynamic_size =
((xla::Abs(limit - start) + xla::Abs(delta) -
xla::One(ctx->builder(), ctx->input_xla_type(0))) /
xla::Abs(delta));
output = xla::SetDimensionSize(output.ValueOrDie(), dynamic_size, 0);
} else {
auto dynamic_size = (xla::Ceil(xla::Abs((limit - start) / delta)));
output = xla::SetDimensionSize(output.ValueOrDie(), dynamic_size, 0);
}
}
ctx->SetOutput(0, output.ValueOrDie());
}
};
REGISTER_XLA_OP(Name("Range")
.CompileTimeConstantInput("start")
.CompileTimeConstantInput("limit")
.CompileTimeConstantInput("delta"),
RangeOp);
class LinSpaceOp : public XlaOpKernel {
public:
explicit LinSpaceOp(OpKernelConstruction* ctx) : XlaOpKernel(ctx) {}
void Compile(XlaOpKernelContext* ctx) override {
const TensorShape start_in_shape = ctx->InputShape("start");
const TensorShape stop_in_shape = ctx->InputShape("stop");
const TensorShape num_in_shape = ctx->InputShape("num");
OP_REQUIRES(ctx, TensorShapeUtils::IsScalar(start_in_shape),
errors::InvalidArgument("start must be a scalar, not shape ",
start_in_shape.DebugString()));
OP_REQUIRES(ctx, TensorShapeUtils::IsScalar(stop_in_shape),
errors::InvalidArgument("stop must be a scalar, not shape ",
stop_in_shape.DebugString()));
OP_REQUIRES(ctx, TensorShapeUtils::IsScalar(num_in_shape),
errors::InvalidArgument("num must be a scalar, not shape ",
num_in_shape.DebugString()));
int64 num;
OP_REQUIRES_OK(ctx, ctx->ConstantInputAsIntScalar("num", &num));
OP_REQUIRES(ctx, num > 0,
errors::InvalidArgument("Requires num > 0: ", num));
xla::XlaOp start = ctx->Input("start");
xla::XlaOp stop = ctx->Input("stop");
xla::XlaOp iota = xla::Iota(ctx->builder(), ctx->output_xla_type(0), num);
xla::XlaOp step =
(stop - start) / xla::ScalarLike(start, (num > 1 ? num - 1 : num));
xla::XlaOp result = iota * step + start;
if (num > 1) {
// According to linspace spec, start has to be the first element and end
// has to be last element.
xla::XlaOp mask = xla::Iota(ctx->builder(), xla::S64, num);
xla::XlaOp eq = xla::Eq(mask, xla::ScalarLike(mask, num - 1));
result = xla::Select(eq, stop, result);
}
ctx->SetOutput(0, result);
}
};
REGISTER_XLA_OP(Name("LinSpace").CompileTimeConstantInput("num"), LinSpaceOp);
} // namespace
} // namespace tensorflow
<commit_msg>Correctly support floating point size in tf.range.<commit_after>/* Copyright 2017 The TensorFlow Authors. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
==============================================================================*/
// XLA-specific sequence and range Ops.
#include "tensorflow/compiler/tf2xla/xla_helpers.h"
#include "tensorflow/compiler/tf2xla/xla_op_kernel.h"
#include "tensorflow/compiler/tf2xla/xla_op_registry.h"
#include "tensorflow/compiler/xla/client/lib/constants.h"
#include "tensorflow/compiler/xla/client/xla_builder.h"
#include "tensorflow/compiler/xla/literal.h"
#include "tensorflow/compiler/xla/primitive_util.h"
#include "tensorflow/compiler/xla/xla_data.pb.h"
#include "tensorflow/core/framework/op_kernel.h"
#include "tensorflow/core/framework/register_types.h"
#include "tensorflow/core/framework/tensor.h"
#include "tensorflow/core/framework/tensor_shape.h"
#include "tensorflow/core/framework/types.h"
namespace tensorflow {
namespace {
// The type-specific part of the implementation of Range.
template <typename T>
xla::StatusOr<xla::XlaOp> CreateRangeTensor(
const xla::LiteralSlice& start_literal,
const xla::LiteralSlice& limit_literal,
const xla::LiteralSlice& delta_literal, xla::XlaBuilder* builder) {
T start = start_literal.Get<T>({});
T limit = limit_literal.Get<T>({});
T delta = delta_literal.Get<T>({});
if (delta == 0) {
return errors::InvalidArgument("Requires delta != 0: ", delta);
}
if (delta > 0) {
if (start > limit) {
return errors::InvalidArgument(
"Requires start <= limit when delta > 0: ", start, "/", limit);
}
} else {
if (start < limit) {
return errors::InvalidArgument(
"Requires start >= limit when delta < 0: ", start, "/", limit);
}
}
int64 size =
(std::is_integral<T>::value
? ((std::abs(limit - start) + std::abs(delta) - 1) / std::abs(delta))
: std::ceil(std::abs((limit - start) / delta)));
return xla::ConstantR0(builder, start) +
xla::ConstantR0(builder, delta) *
xla::Iota(builder, xla::primitive_util::NativeToPrimitiveType<T>(),
size);
}
class RangeOp : public XlaOpKernel {
public:
explicit RangeOp(OpKernelConstruction* ctx) : XlaOpKernel(ctx) {}
void Compile(XlaOpKernelContext* ctx) override {
const TensorShape start_in_shape = ctx->InputShape(0);
const TensorShape limit_in_shape = ctx->InputShape(1);
const TensorShape delta_in_shape = ctx->InputShape(2);
OP_REQUIRES(ctx, TensorShapeUtils::IsScalar(start_in_shape),
errors::InvalidArgument("start must be a scalar, not shape ",
start_in_shape.DebugString()));
OP_REQUIRES(ctx, TensorShapeUtils::IsScalar(limit_in_shape),
errors::InvalidArgument("limit must be a scalar, not shape ",
limit_in_shape.DebugString()));
OP_REQUIRES(ctx, TensorShapeUtils::IsScalar(delta_in_shape),
errors::InvalidArgument("delta must be a scalar, not shape ",
delta_in_shape.DebugString()));
xla::Literal start, limit, delta;
OP_REQUIRES_OK(ctx, ctx->ConstantInput(
0, &start, xla::ValueInferenceMode::kLowerBound));
OP_REQUIRES_OK(ctx, ctx->ConstantInput(
1, &limit, xla::ValueInferenceMode::kUpperBound));
OP_REQUIRES_OK(ctx, ctx->ConstantInput(2, &delta));
DataType type = input_type(0);
xla::StatusOr<xla::XlaOp> output;
switch (type) {
case DT_INT32:
output = CreateRangeTensor<int32>(start, limit, delta, ctx->builder());
break;
case DT_INT64:
output = CreateRangeTensor<int64>(start, limit, delta, ctx->builder());
break;
case DT_FLOAT:
output = CreateRangeTensor<float>(start, limit, delta, ctx->builder());
break;
case DT_DOUBLE:
output = CreateRangeTensor<double>(start, limit, delta, ctx->builder());
break;
default:
output = errors::InvalidArgument("Invalid type for Range ",
DataTypeString(type));
}
OP_REQUIRES_OK(ctx, output.status());
bool start_is_dynamic = false;
OP_REQUIRES_OK(ctx,
ctx->ResolveInputDynamismIntoPred(0, &start_is_dynamic));
bool limit_is_dynamic = false;
OP_REQUIRES_OK(ctx,
ctx->ResolveInputDynamismIntoPred(1, &limit_is_dynamic));
if (start_is_dynamic || limit_is_dynamic) {
xla::XlaOp delta = ctx->Input(2);
xla::XlaOp limit = ctx->Input(1);
xla::XlaOp start = ctx->Input(0);
if (type == DT_INT32 || type == DT_INT64) {
auto dynamic_size = (xla::Abs(limit - start) + xla::Abs(delta) -
xla::One(ctx->builder(), ctx->input_xla_type(0))) /
xla::Abs(delta);
dynamic_size = xla::ConvertElementType(dynamic_size, xla::S32);
output = xla::SetDimensionSize(output.ValueOrDie(), dynamic_size, 0);
} else {
auto dynamic_size = (xla::Ceil(xla::Abs((limit - start) / delta)));
dynamic_size = xla::ConvertElementType(dynamic_size, xla::S32);
output = xla::SetDimensionSize(output.ValueOrDie(), dynamic_size, 0);
}
}
ctx->SetOutput(0, output.ValueOrDie());
}
};
REGISTER_XLA_OP(Name("Range")
.CompileTimeConstantInput("start")
.CompileTimeConstantInput("limit")
.CompileTimeConstantInput("delta"),
RangeOp);
class LinSpaceOp : public XlaOpKernel {
public:
explicit LinSpaceOp(OpKernelConstruction* ctx) : XlaOpKernel(ctx) {}
void Compile(XlaOpKernelContext* ctx) override {
const TensorShape start_in_shape = ctx->InputShape("start");
const TensorShape stop_in_shape = ctx->InputShape("stop");
const TensorShape num_in_shape = ctx->InputShape("num");
OP_REQUIRES(ctx, TensorShapeUtils::IsScalar(start_in_shape),
errors::InvalidArgument("start must be a scalar, not shape ",
start_in_shape.DebugString()));
OP_REQUIRES(ctx, TensorShapeUtils::IsScalar(stop_in_shape),
errors::InvalidArgument("stop must be a scalar, not shape ",
stop_in_shape.DebugString()));
OP_REQUIRES(ctx, TensorShapeUtils::IsScalar(num_in_shape),
errors::InvalidArgument("num must be a scalar, not shape ",
num_in_shape.DebugString()));
int64 num;
OP_REQUIRES_OK(ctx, ctx->ConstantInputAsIntScalar("num", &num));
OP_REQUIRES(ctx, num > 0,
errors::InvalidArgument("Requires num > 0: ", num));
xla::XlaOp start = ctx->Input("start");
xla::XlaOp stop = ctx->Input("stop");
xla::XlaOp iota = xla::Iota(ctx->builder(), ctx->output_xla_type(0), num);
xla::XlaOp step =
(stop - start) / xla::ScalarLike(start, (num > 1 ? num - 1 : num));
xla::XlaOp result = iota * step + start;
if (num > 1) {
// According to linspace spec, start has to be the first element and end
// has to be last element.
xla::XlaOp mask = xla::Iota(ctx->builder(), xla::S64, num);
xla::XlaOp eq = xla::Eq(mask, xla::ScalarLike(mask, num - 1));
result = xla::Select(eq, stop, result);
}
ctx->SetOutput(0, result);
}
};
REGISTER_XLA_OP(Name("LinSpace").CompileTimeConstantInput("num"), LinSpaceOp);
} // namespace
} // namespace tensorflow
<|endoftext|> |
<commit_before>/* Copyright 2017 The TensorFlow Authors. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
==============================================================================*/
#include <string>
#include <vector>
#include "absl/strings/numbers.h"
#include "absl/strings/str_join.h"
#include "absl/strings/str_split.h"
#include "absl/strings/strip.h"
#include "tensorflow/contrib/lite/toco/toco_cmdline_flags.h"
#include "tensorflow/contrib/lite/toco/toco_port.h"
#include "tensorflow/core/platform/logging.h"
#include "tensorflow/core/util/command_line_flags.h"
namespace toco {
bool ParseTocoFlagsFromCommandLineFlags(
int* argc, char* argv[], string* msg,
ParsedTocoFlags* parsed_toco_flags_ptr) {
using tensorflow::Flag;
ParsedTocoFlags& parsed_flags = *parsed_toco_flags_ptr;
std::vector<tensorflow::Flag> flags = {
Flag("input_file", parsed_flags.input_file.bind(),
parsed_flags.input_file.default_value(),
"Input file (model of any supported format). For Protobuf "
"formats, both text and binary are supported regardless of file "
"extension."),
Flag("output_file", parsed_flags.output_file.bind(),
parsed_flags.output_file.default_value(),
"Output file. "
"For Protobuf formats, the binary format will be used."),
Flag("input_format", parsed_flags.input_format.bind(),
parsed_flags.input_format.default_value(),
"Input file format. One of: tensorflow_graphdef, "),
Flag("output_format", parsed_flags.output_format.bind(),
parsed_flags.output_format.default_value(), "Output file format."),
Flag("default_ranges_min", parsed_flags.default_ranges_min.bind(),
parsed_flags.default_ranges_min.default_value(),
"If defined, will be used as the default value for the min bound "
"of min/max ranges used for quantization."),
Flag("default_ranges_max", parsed_flags.default_ranges_max.bind(),
parsed_flags.default_ranges_max.default_value(),
"If defined, will be used as the default value for the max bound "
"of min/max ranges used for quantization."),
Flag("inference_type", parsed_flags.inference_type.bind(),
parsed_flags.inference_type.default_value(),
"Target data type of arrays in the output file (for input_arrays, "
"this may be overridden by inference_input_type)."),
Flag("inference_input_type", parsed_flags.inference_input_type.bind(),
parsed_flags.inference_input_type.default_value(),
"Target data type of input arrays. If not specified, inference_type "
"is used."),
Flag("input_type", parsed_flags.input_type.bind(),
parsed_flags.input_type.default_value(),
"Deprecated old name of inference_input_type."),
Flag("input_types", parsed_flags.input_types.bind(),
parsed_flags.input_types.default_value(),
"Deprecated old name of inference_input_type. Was meant to be a "
"comma-separated list, but this was deprecated before "
"multiple-input-types was ever properly supported."),
Flag("drop_fake_quant", parsed_flags.drop_fake_quant.bind(),
parsed_flags.drop_fake_quant.default_value(),
"Ignore and discard FakeQuant nodes. For instance, that can be used "
"to "
"generate plain float code without fake-quantization from a "
"quantized "
"graph."),
Flag(
"reorder_across_fake_quant",
parsed_flags.reorder_across_fake_quant.bind(),
parsed_flags.reorder_across_fake_quant.default_value(),
"Normally, FakeQuant nodes must be strict boundaries for graph "
"transformations, in order to ensure that quantized inference has "
"the "
"exact same arithmetic behavior as quantized training --- which is "
"the "
"whole point of quantized training and of FakeQuant nodes in the "
"first "
"place. However, that entails subtle requirements on where exactly "
"FakeQuant nodes must be placed in the graph. Some quantized graphs "
"have FakeQuant nodes at unexpected locations, that prevent graph "
"transformations that are necessary in order to generate inference "
"code for these graphs. Such graphs should be fixed, but as a "
"temporary work-around, setting this reorder_across_fake_quant flag "
"allows toco to perform necessary graph transformaitons on them, "
"at the cost of no longer faithfully matching inference and training "
"arithmetic."),
Flag("allow_custom_ops", parsed_flags.allow_custom_ops.bind(),
parsed_flags.allow_custom_ops.default_value(),
"If true, allow TOCO to create TF Lite Custom operators for all the"
"unsupported Tensorflow ops."),
Flag(
"drop_control_dependency",
parsed_flags.drop_control_dependency.bind(),
parsed_flags.drop_control_dependency.default_value(),
"If true, ignore control dependency requirements in input TensorFlow "
"GraphDef. Otherwise an error will be raised upon control dependency "
"inputs."),
};
bool asked_for_help =
*argc == 2 && (!strcmp(argv[1], "--help") || !strcmp(argv[1], "-help"));
if (asked_for_help) {
*msg += tensorflow::Flags::Usage(argv[0], flags);
return false;
} else {
return tensorflow::Flags::Parse(argc, argv, flags);
}
}
void ReadTocoFlagsFromCommandLineFlags(const ParsedTocoFlags& parsed_toco_flags,
TocoFlags* toco_flags) {
namespace port = toco::port;
port::CheckInitGoogleIsDone("InitGoogle is not done yet");
enum class FlagRequirement { kNone, kMustBeSpecified, kMustNotBeSpecified };
#define ENFORCE_FLAG_REQUIREMENT(name, requirement) \
do { \
if (requirement == FlagRequirement::kMustBeSpecified) { \
QCHECK(parsed_toco_flags.name.specified()) \
<< "Missing required flag: " << #name; \
} \
if (requirement == FlagRequirement::kMustNotBeSpecified) { \
QCHECK(!parsed_toco_flags.name.specified()) \
<< "Given other flags, this flag should not have been specified: " \
<< #name; \
} \
} while (false)
#define READ_TOCO_FLAG(name, requirement) \
ENFORCE_FLAG_REQUIREMENT(name, requirement); \
do { \
if (parsed_toco_flags.name.specified()) { \
toco_flags->set_##name(parsed_toco_flags.name.value()); \
} \
} while (false)
#define PARSE_TOCO_FLAG(Type, name, requirement) \
ENFORCE_FLAG_REQUIREMENT(name, requirement); \
do { \
if (parsed_toco_flags.name.specified()) { \
Type x; \
QCHECK(Type##_Parse(parsed_toco_flags.name.value(), &x)) \
<< "Unrecognized " << #Type << " value " \
<< parsed_toco_flags.name.value(); \
toco_flags->set_##name(x); \
} \
} while (false)
PARSE_TOCO_FLAG(FileFormat, input_format, FlagRequirement::kMustBeSpecified);
PARSE_TOCO_FLAG(FileFormat, output_format, FlagRequirement::kMustBeSpecified);
PARSE_TOCO_FLAG(IODataType, inference_type, FlagRequirement::kNone);
PARSE_TOCO_FLAG(IODataType, inference_input_type, FlagRequirement::kNone);
READ_TOCO_FLAG(default_ranges_min, FlagRequirement::kNone);
READ_TOCO_FLAG(default_ranges_max, FlagRequirement::kNone);
READ_TOCO_FLAG(drop_fake_quant, FlagRequirement::kNone);
READ_TOCO_FLAG(reorder_across_fake_quant, FlagRequirement::kNone);
READ_TOCO_FLAG(allow_custom_ops, FlagRequirement::kNone);
READ_TOCO_FLAG(drop_control_dependency, FlagRequirement::kNone);
// Deprecated flag handling.
if (parsed_toco_flags.input_type.specified()) {
LOG(WARNING) << "--input_type is deprecated. Use --inference_input_type.";
toco::IODataType input_type;
QCHECK(toco::IODataType_Parse(parsed_toco_flags.input_type.value(),
&input_type));
toco_flags->set_inference_input_type(input_type);
}
if (parsed_toco_flags.input_types.specified()) {
LOG(WARNING) << "--input_types is deprecated. Use --inference_input_type.";
std::vector<string> input_types =
absl::StrSplit(parsed_toco_flags.input_types.value(), ',');
QCHECK(!input_types.empty());
for (int i = 1; i < input_types.size(); i++) {
QCHECK_EQ(input_types[i], input_types[0]);
}
toco::IODataType input_type;
QCHECK(toco::IODataType_Parse(input_types[0], &input_type));
toco_flags->set_inference_input_type(input_type);
}
#undef READ_TOCO_FLAG
#undef PARSE_TOCO_FLAG
}
} // namespace toco
<commit_msg>Better deprecation message for --input_type[s].<commit_after>/* Copyright 2017 The TensorFlow Authors. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
==============================================================================*/
#include <string>
#include <vector>
#include "absl/strings/numbers.h"
#include "absl/strings/str_join.h"
#include "absl/strings/str_split.h"
#include "absl/strings/strip.h"
#include "tensorflow/contrib/lite/toco/toco_cmdline_flags.h"
#include "tensorflow/contrib/lite/toco/toco_port.h"
#include "tensorflow/core/platform/logging.h"
#include "tensorflow/core/util/command_line_flags.h"
namespace toco {
bool ParseTocoFlagsFromCommandLineFlags(
int* argc, char* argv[], string* msg,
ParsedTocoFlags* parsed_toco_flags_ptr) {
using tensorflow::Flag;
ParsedTocoFlags& parsed_flags = *parsed_toco_flags_ptr;
std::vector<tensorflow::Flag> flags = {
Flag("input_file", parsed_flags.input_file.bind(),
parsed_flags.input_file.default_value(),
"Input file (model of any supported format). For Protobuf "
"formats, both text and binary are supported regardless of file "
"extension."),
Flag("output_file", parsed_flags.output_file.bind(),
parsed_flags.output_file.default_value(),
"Output file. "
"For Protobuf formats, the binary format will be used."),
Flag("input_format", parsed_flags.input_format.bind(),
parsed_flags.input_format.default_value(),
"Input file format. One of: tensorflow_graphdef, "),
Flag("output_format", parsed_flags.output_format.bind(),
parsed_flags.output_format.default_value(), "Output file format."),
Flag("default_ranges_min", parsed_flags.default_ranges_min.bind(),
parsed_flags.default_ranges_min.default_value(),
"If defined, will be used as the default value for the min bound "
"of min/max ranges used for quantization."),
Flag("default_ranges_max", parsed_flags.default_ranges_max.bind(),
parsed_flags.default_ranges_max.default_value(),
"If defined, will be used as the default value for the max bound "
"of min/max ranges used for quantization."),
Flag("inference_type", parsed_flags.inference_type.bind(),
parsed_flags.inference_type.default_value(),
"Target data type of arrays in the output file (for input_arrays, "
"this may be overridden by inference_input_type)."),
Flag("inference_input_type", parsed_flags.inference_input_type.bind(),
parsed_flags.inference_input_type.default_value(),
"Target data type of input arrays. If not specified, inference_type "
"is used."),
Flag("input_type", parsed_flags.input_type.bind(),
parsed_flags.input_type.default_value(),
"Deprecated ambiguous flag that set both --input_data_types and "
"--inference_input_type."),
Flag("input_types", parsed_flags.input_types.bind(),
parsed_flags.input_types.default_value(),
"Deprecated ambiguous flag that set both --input_data_types and "
"--inference_input_type. Was meant to be a "
"comma-separated list, but this was deprecated before "
"multiple-input-types was ever properly supported."),
Flag("drop_fake_quant", parsed_flags.drop_fake_quant.bind(),
parsed_flags.drop_fake_quant.default_value(),
"Ignore and discard FakeQuant nodes. For instance, that can be used "
"to "
"generate plain float code without fake-quantization from a "
"quantized "
"graph."),
Flag(
"reorder_across_fake_quant",
parsed_flags.reorder_across_fake_quant.bind(),
parsed_flags.reorder_across_fake_quant.default_value(),
"Normally, FakeQuant nodes must be strict boundaries for graph "
"transformations, in order to ensure that quantized inference has "
"the "
"exact same arithmetic behavior as quantized training --- which is "
"the "
"whole point of quantized training and of FakeQuant nodes in the "
"first "
"place. However, that entails subtle requirements on where exactly "
"FakeQuant nodes must be placed in the graph. Some quantized graphs "
"have FakeQuant nodes at unexpected locations, that prevent graph "
"transformations that are necessary in order to generate inference "
"code for these graphs. Such graphs should be fixed, but as a "
"temporary work-around, setting this reorder_across_fake_quant flag "
"allows toco to perform necessary graph transformaitons on them, "
"at the cost of no longer faithfully matching inference and training "
"arithmetic."),
Flag("allow_custom_ops", parsed_flags.allow_custom_ops.bind(),
parsed_flags.allow_custom_ops.default_value(),
"If true, allow TOCO to create TF Lite Custom operators for all the"
"unsupported Tensorflow ops."),
Flag(
"drop_control_dependency",
parsed_flags.drop_control_dependency.bind(),
parsed_flags.drop_control_dependency.default_value(),
"If true, ignore control dependency requirements in input TensorFlow "
"GraphDef. Otherwise an error will be raised upon control dependency "
"inputs."),
};
bool asked_for_help =
*argc == 2 && (!strcmp(argv[1], "--help") || !strcmp(argv[1], "-help"));
if (asked_for_help) {
*msg += tensorflow::Flags::Usage(argv[0], flags);
return false;
} else {
return tensorflow::Flags::Parse(argc, argv, flags);
}
}
void ReadTocoFlagsFromCommandLineFlags(const ParsedTocoFlags& parsed_toco_flags,
TocoFlags* toco_flags) {
namespace port = toco::port;
port::CheckInitGoogleIsDone("InitGoogle is not done yet");
enum class FlagRequirement { kNone, kMustBeSpecified, kMustNotBeSpecified };
#define ENFORCE_FLAG_REQUIREMENT(name, requirement) \
do { \
if (requirement == FlagRequirement::kMustBeSpecified) { \
QCHECK(parsed_toco_flags.name.specified()) \
<< "Missing required flag: " << #name; \
} \
if (requirement == FlagRequirement::kMustNotBeSpecified) { \
QCHECK(!parsed_toco_flags.name.specified()) \
<< "Given other flags, this flag should not have been specified: " \
<< #name; \
} \
} while (false)
#define READ_TOCO_FLAG(name, requirement) \
ENFORCE_FLAG_REQUIREMENT(name, requirement); \
do { \
if (parsed_toco_flags.name.specified()) { \
toco_flags->set_##name(parsed_toco_flags.name.value()); \
} \
} while (false)
#define PARSE_TOCO_FLAG(Type, name, requirement) \
ENFORCE_FLAG_REQUIREMENT(name, requirement); \
do { \
if (parsed_toco_flags.name.specified()) { \
Type x; \
QCHECK(Type##_Parse(parsed_toco_flags.name.value(), &x)) \
<< "Unrecognized " << #Type << " value " \
<< parsed_toco_flags.name.value(); \
toco_flags->set_##name(x); \
} \
} while (false)
PARSE_TOCO_FLAG(FileFormat, input_format, FlagRequirement::kMustBeSpecified);
PARSE_TOCO_FLAG(FileFormat, output_format, FlagRequirement::kMustBeSpecified);
PARSE_TOCO_FLAG(IODataType, inference_type, FlagRequirement::kNone);
PARSE_TOCO_FLAG(IODataType, inference_input_type, FlagRequirement::kNone);
READ_TOCO_FLAG(default_ranges_min, FlagRequirement::kNone);
READ_TOCO_FLAG(default_ranges_max, FlagRequirement::kNone);
READ_TOCO_FLAG(drop_fake_quant, FlagRequirement::kNone);
READ_TOCO_FLAG(reorder_across_fake_quant, FlagRequirement::kNone);
READ_TOCO_FLAG(allow_custom_ops, FlagRequirement::kNone);
READ_TOCO_FLAG(drop_control_dependency, FlagRequirement::kNone);
// Deprecated flag handling.
if (parsed_toco_flags.input_type.specified()) {
LOG(WARNING)
<< "--input_type is deprecated. It was an ambiguous flag that set both "
"--input_data_types and --inference_input_type. If you are trying "
"to complement the input file with information about the type of "
"input arrays, use --input_data_type. If you are trying to control "
"the quantization/dequantization of real-numbers input arrays in "
"the output file, use --inference_input_type.";
toco::IODataType input_type;
QCHECK(toco::IODataType_Parse(parsed_toco_flags.input_type.value(),
&input_type));
toco_flags->set_inference_input_type(input_type);
}
if (parsed_toco_flags.input_types.specified()) {
LOG(WARNING)
<< "--input_types is deprecated. It was an ambiguous flag that set "
"both --input_data_types and --inference_input_type. If you are "
"trying to complement the input file with information about the "
"type of input arrays, use --input_data_type. If you are trying to "
"control the quantization/dequantization of real-numbers input "
"arrays in the output file, use --inference_input_type.";
std::vector<string> input_types =
absl::StrSplit(parsed_toco_flags.input_types.value(), ',');
QCHECK(!input_types.empty());
for (int i = 1; i < input_types.size(); i++) {
QCHECK_EQ(input_types[i], input_types[0]);
}
toco::IODataType input_type;
QCHECK(toco::IODataType_Parse(input_types[0], &input_type));
toco_flags->set_inference_input_type(input_type);
}
#undef READ_TOCO_FLAG
#undef PARSE_TOCO_FLAG
}
} // namespace toco
<|endoftext|> |
<commit_before>/* Copyright 2016 The TensorFlow Authors. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
==============================================================================*/
#if TENSORFLOW_USE_SYCL
#include "tensorflow/core/common_runtime/sycl/sycl_device.h"
#include "third_party/eigen3/unsupported/Eigen/CXX11/Tensor"
#include "tensorflow/core/framework/tensor.pb_text.h"
#include "tensorflow/core/platform/tracing.h"
namespace tensorflow {
static std::unordered_set<SYCLDevice*> live_devices;
void ShutdownSycl() {
for (auto device : live_devices) {
device->EnterLameDuckMode();
}
live_devices.clear();
}
bool first_time = true;
void SYCLDevice::RegisterDevice() {
if (first_time) {
first_time = false;
atexit(ShutdownSycl);
}
live_devices.insert(this);
}
SYCLDevice::~SYCLDevice() {
device_context_->Unref();
sycl_allocator_->EnterLameDuckMode();
delete sycl_device_;
delete sycl_queue_;
live_devices.erase(this);
}
void SYCLDevice::EnterLameDuckMode() {
sycl_allocator_->EnterLameDuckMode();
delete sycl_device_;
sycl_device_ = nullptr;
delete sycl_queue_;
sycl_queue_ = nullptr;
}
void SYCLDevice::Compute(OpKernel *op_kernel, OpKernelContext *context) {
assert(context);
if (port::Tracing::IsActive()) {
// TODO(pbar) We really need a useful identifier of the graph node.
const uint64 id = Hash64(op_kernel->name());
port::Tracing::ScopedActivity region(port::Tracing::EventCategory::kCompute,
id);
}
op_kernel->Compute(context);
}
Allocator *SYCLDevice::GetAllocator(AllocatorAttributes attr) {
if (attr.on_host())
return cpu_allocator_;
else
return sycl_allocator_;
}
Status SYCLDevice::MakeTensorFromProto(const TensorProto &tensor_proto,
const AllocatorAttributes alloc_attrs,
Tensor *tensor) {
Tensor parsed(tensor_proto.dtype());
if (!parsed.FromProto(cpu_allocator_, tensor_proto)) {
return errors::InvalidArgument("Cannot parse tensor from proto: ",
tensor_proto.DebugString());
}
Status status;
if (alloc_attrs.on_host()) {
*tensor = parsed;
} else {
Tensor copy(GetAllocator(alloc_attrs), parsed.dtype(), parsed.shape());
device_context_->CopyCPUTensorToDevice(&parsed, this, ©,
[&status](const Status &s) {
status = s;
});
*tensor = copy;
}
return status;
}
Status SYCLDevice::FillContextMap(const Graph *graph,
DeviceContextMap *device_context_map) {
// Fill in the context map. It is OK for this map to contain
// duplicate DeviceContexts so long as we increment the refcount.
device_context_map->resize(graph->num_node_ids());
for (Node *n : graph->nodes()) {
device_context_->Ref();
(*device_context_map)[n->id()] = device_context_;
}
return Status::OK();
}
Status SYCLDevice::Sync() {
sycl_device_->synchronize();
return Status::OK();
}
} // namespace tensorflow
#endif // TENSORFLOW_USE_SYCL
<commit_msg>Made a variable static<commit_after>/* Copyright 2016 The TensorFlow Authors. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
==============================================================================*/
#if TENSORFLOW_USE_SYCL
#include "tensorflow/core/common_runtime/sycl/sycl_device.h"
#include "third_party/eigen3/unsupported/Eigen/CXX11/Tensor"
#include "tensorflow/core/framework/tensor.pb_text.h"
#include "tensorflow/core/platform/tracing.h"
namespace tensorflow {
static std::unordered_set<SYCLDevice*> live_devices;
static bool first_time = true;
void ShutdownSycl() {
for (auto device : live_devices) {
device->EnterLameDuckMode();
}
live_devices.clear();
}
void SYCLDevice::RegisterDevice() {
if (first_time) {
first_time = false;
atexit(ShutdownSycl);
}
live_devices.insert(this);
}
SYCLDevice::~SYCLDevice() {
device_context_->Unref();
sycl_allocator_->EnterLameDuckMode();
delete sycl_device_;
delete sycl_queue_;
live_devices.erase(this);
}
void SYCLDevice::EnterLameDuckMode() {
sycl_allocator_->EnterLameDuckMode();
delete sycl_device_;
sycl_device_ = nullptr;
delete sycl_queue_;
sycl_queue_ = nullptr;
}
void SYCLDevice::Compute(OpKernel *op_kernel, OpKernelContext *context) {
assert(context);
if (port::Tracing::IsActive()) {
// TODO(pbar) We really need a useful identifier of the graph node.
const uint64 id = Hash64(op_kernel->name());
port::Tracing::ScopedActivity region(port::Tracing::EventCategory::kCompute,
id);
}
op_kernel->Compute(context);
}
Allocator *SYCLDevice::GetAllocator(AllocatorAttributes attr) {
if (attr.on_host())
return cpu_allocator_;
else
return sycl_allocator_;
}
Status SYCLDevice::MakeTensorFromProto(const TensorProto &tensor_proto,
const AllocatorAttributes alloc_attrs,
Tensor *tensor) {
Tensor parsed(tensor_proto.dtype());
if (!parsed.FromProto(cpu_allocator_, tensor_proto)) {
return errors::InvalidArgument("Cannot parse tensor from proto: ",
tensor_proto.DebugString());
}
Status status;
if (alloc_attrs.on_host()) {
*tensor = parsed;
} else {
Tensor copy(GetAllocator(alloc_attrs), parsed.dtype(), parsed.shape());
device_context_->CopyCPUTensorToDevice(&parsed, this, ©,
[&status](const Status &s) {
status = s;
});
*tensor = copy;
}
return status;
}
Status SYCLDevice::FillContextMap(const Graph *graph,
DeviceContextMap *device_context_map) {
// Fill in the context map. It is OK for this map to contain
// duplicate DeviceContexts so long as we increment the refcount.
device_context_map->resize(graph->num_node_ids());
for (Node *n : graph->nodes()) {
device_context_->Ref();
(*device_context_map)[n->id()] = device_context_;
}
return Status::OK();
}
Status SYCLDevice::Sync() {
sycl_device_->synchronize();
return Status::OK();
}
} // namespace tensorflow
#endif // TENSORFLOW_USE_SYCL
<|endoftext|> |
<commit_before>
#include "XXX/websocket_protocol.h"
#include "XXX/utils.h"
#include "XXX/io_handle.h"
#include "XXX/http_parser.h"
#include <iostream>
#include <string.h>
#include <openssl/sha.h>
#include <arpa/inet.h>
namespace XXX
{
websocket_protocol::websocket_protocol(io_handle* h, t_msg_cb msg_cb, connection_mode _mode)
: protocol(h, msg_cb, _mode),
m_state(_mode==protocol::connection_mode::ePassive? eHandlingHttpRequest : eSendingHttpRequest),
m_http_parser(new http_parser())
{
}
const char cb64[]="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
std::string base64Encode(const void* dataVoid, size_t length) {
std::string output;
auto data = reinterpret_cast<const uint8_t*>(dataVoid);
for (auto i = 0u; i < length; i += 3) {
auto bytesLeft = length - i;
auto b0 = data[i];
auto b1 = bytesLeft > 1 ? data[i + 1] : 0;
auto b2 = bytesLeft > 2 ? data[i + 2] : 0;
output.push_back(cb64[b0 >> 2]);
output.push_back(cb64[((b0 & 0x03) << 4) | ((b1 & 0xf0) >> 4)]);
output.push_back((bytesLeft > 1 ? cb64[((b1 & 0x0f) << 2) | ((b2 & 0xc0) >> 6)] : '='));
output.push_back((bytesLeft > 2 ? cb64[b2 & 0x3f] : '='));
}
return output;
}
inline std::string make_accept_key(const std::string& challenge)
{
auto full_key = challenge + websocket_protocol::MAGIC;
unsigned char obuf[20];
SHA1((const unsigned char*)full_key.c_str(), full_key.size(), obuf);
// SHA1 hasher;
// hasher.Input(fullString.c_str(), fullString.size());
// unsigned hash[5];
// hasher.Result(hash);
// for (int i = 0; i < 5; ++i) {
// hash[i] = htonl(hash[i]);
// }
return base64Encode(obuf, 20);
}
static bool string_list_contains(const std::string & source,
const std::string & match)
{
for (auto & i : tokenize(source.c_str(), ',', true))
{
std::string trimmed = trim(i);
if (case_insensitive_same(trimmed, match)) return true;
}
return false;
}
// Two byte conversion union
union uint16_converter
{
uint16_t i;
uint8_t m[2];
};
// Four byte conversion union
union uint32_converter
{
uint32_t i;
uint8_t m[4];
};
// Eight byte conversion union
union uint64_converter
{
uint64_t i;
uint8_t m[8];
};
struct frame_builder
{
// Minimum length of a WebSocket frame header.
static unsigned int const BASIC_HEADER_LENGTH = 2;
// Maximum length of a WebSocket header (2+8+4)
static unsigned int const MAX_HEADER_LENGTH = 14;
static uint8_t const FRAME_OPCODE = 0x0F;
static uint8_t const FRAME_FIN = 0x80;
static uint8_t const FRAME_MASKED = 0x80;
/** Construct */
frame_builder(int opcode, bool is_fin, size_t payload_len)
{
unsigned char is_fin_bit = is_fin?FRAME_FIN:0;
image[0] = is_fin_bit | (FRAME_OPCODE & opcode);
if (payload_len < 126)
{
image[1] = (unsigned char)(payload_len);
header_len = 2;
}
else if (payload_len < 65536)
{
uint16_converter temp;
temp.i = htons(payload_len & 0xFFFF);
image[1] = (unsigned char)126;
image[2] = temp.m[0];
image[3] = temp.m[1];
header_len = 4;
}
else
{
uint64_converter temp;
temp.i = __bswap_64(payload_len);
image[1] = (unsigned char)127;
for (int i = 0; i<8; ++i) image[2+i]=temp.m[i];
header_len = 10;
}
}
frame_builder(int opcode, bool is_fin, size_t payload_len, std::array<char,4> mask)
: frame_builder(opcode, is_fin, payload_len)
{
image[1] |= FRAME_MASKED;
image[header_len+0] = mask[0];
image[header_len+1] = mask[1];
image[header_len+2] = mask[2];
image[header_len+3] = mask[3];
header_len += 4;
}
char * data() { return image; }
const char * data() const { return image; }
size_t size() const { return header_len; }
std::pair<const char*, size_t> buf() const
{
return { data(), size() };
}
private:
// Storage for frame being created.
char image[MAX_HEADER_LENGTH];
// Actual frame size, since frame size depends on payload size and masking
size_t header_len;
};
void websocket_protocol::send_msg(const jalson::json_array& ja)
{
std::string msg ( jalson::encode( ja ) );
// prepare frame
frame_builder fb(OPCODE_TEXT, true, msg.size());
std::pair<const char*, size_t> bufs[2];
bufs[0].first = (char*)fb.data();
bufs[0].second = fb.size();
bufs[1].first = (const char*)msg.c_str();;
bufs[1].second = msg.size();
m_iohandle->write_bufs(bufs, 2, false);
}
void websocket_protocol::io_on_read(char* src, size_t len)
{
while (len) /* IO thread */
{
size_t consume_len = m_buf.consume(src, len);
src += consume_len;
len -= consume_len;
auto rd = m_buf.read_ptr();
while (rd.avail())
{
if (m_state == eHandlingHttpRequest)
{
auto consumed = m_http_parser->handle_input(rd.ptr(), rd.avail());
rd.advance(consumed);
if (m_http_parser->fail())
throw handshake_error("bad http header: " + m_http_parser->error_text());
if (m_http_parser->complete() )
{
if ( m_http_parser->is_upgrade() &&
m_http_parser->count("Upgrade") &&
string_list_contains(m_http_parser->get("Upgrade"), "websocket") &&
m_http_parser->count("Connection") &&
string_list_contains(m_http_parser->get("Connection"), "Upgrade") &&
m_http_parser->count("Sec-WebSocket-Key") &&
m_http_parser->count("Sec-WebSocket-Version") )
{
auto websocket_version = std::stoi(m_http_parser->get("Sec-WebSocket-Version").c_str());
// TODO: hande version 0 ?
if (websocket_version == 13) // RFC6455
{
std::ostringstream os;
os << "HTTP/1.1 101 Switching Protocols" << "\r\n";
os << "Upgrade: websocket" << "\r\n";
os << "Connection: Upgrade" << "\r\n";
os << "Sec-WebSocket-Accept: " << make_accept_key(m_http_parser->get("Sec-WebSocket-Key")) << "\r\n";
os << "\r\n";
std::string msg = os.str();
std::pair<const char*, size_t> buf;
buf.first = msg.c_str();
buf.second = msg.size();
std::cout << "websocket header sent back\n";
m_iohandle->write_bufs(&buf, 1, false);
m_state = eHandlingWebsocket;
}
else
{
throw handshake_error("invalid websocket version");
}
}
else
throw handshake_error("http header is not a websocket upgrade");
}
}
else if (m_state == eHandlingWebsocket)
{
if (rd.avail() < 2) break;
bool fin_bit = rd[0] & 0x80;
int opcode = rd[0] & 0x0F;
bool mask_bit = rd[1] & 0x80;
size_t payload_len = rd[1] & 0x7F;
size_t frame_len = 2 + (mask_bit? 4:0);
int mask_pos = 2;
int payload_pos;
if (payload_len == 126)
{
if (rd.avail() < 4) break;
frame_len += 2;
mask_pos += 2;
uint16_t raw_length;
memcpy(&raw_length, &rd[2], 2);
payload_len = ntohs(raw_length);
}
else if (payload_len == 127)
{
if (rd.avail() < 10) break;
frame_len += 8;
mask_pos += 8;
uint64_t raw_length;
memcpy(&raw_length, &rd[2], 8);
payload_len = __bswap_64(raw_length);
}
frame_len += payload_len;
payload_pos = mask_pos + (mask_bit? 4:0);
if (rd.avail() < frame_len) break;
for (size_t i = 0; i < (mask_bit?payload_len:0); ++i)
rd[payload_pos+i] ^= rd[mask_pos + (i%4)];
std::cout << "fin=" << fin_bit << ", opcode=" << opcode << ", "
<< "framelen=" << frame_len << ", ";
if (mask_bit) std::cout << "mask=" << to_hex(&rd[mask_pos], 4) << ", ";
std::cout << "payloadlen=" << payload_len << ", ";
std::string payload(&rd[payload_pos], payload_len);
std::cout << "payload=" << payload << "\n";
if (!fin_bit)
throw protocol_error("websocket continuations not yet supported");
switch (opcode)
{
case 0x00: /* cont. */ break;
case 0x01: /* text */ break;
case 0x02: /* bin. */ break;
case OPCODE_CLOSE :
{
// issue a close frame -- TODO: should coordinate this from the wamp_session?
m_state = eClosing;
frame_builder fb(OPCODE_CLOSE, true, 0);
auto buf = fb.buf();
m_iohandle->write_bufs(&buf, 1, false);
m_iohandle->request_close();
break;
};
default: break;
}
if (fin_bit && opcode == OPCODE_TEXT)
decode_json(rd.ptr()+payload_pos, payload_len);
rd.advance(frame_len);
}
else
{
// TODO: abort the connection
}
}
m_buf.discard_read( rd ); /* shift unused bytes to front of buffer */
} // while(len)
}
void websocket_protocol::initiate(t_initiate_cb)
{
throw std::runtime_error("websocket_protocol::initiate not implemented");
}
void websocket_protocol::ev_on_timer()
{
if (m_state == eHandlingWebsocket)
{
frame_builder fb(OPCODE_PING, true, 0);
auto buf = fb.buf();
m_iohandle->write_bufs(&buf, 1, false);
}
}
}
<commit_msg>minor tidy up<commit_after>
#include "XXX/websocket_protocol.h"
#include "XXX/utils.h"
#include "XXX/io_handle.h"
#include "XXX/http_parser.h"
#include <iostream>
#include <string.h>
#include <openssl/sha.h>
#include <arpa/inet.h>
namespace XXX
{
websocket_protocol::websocket_protocol(io_handle* h, t_msg_cb msg_cb, connection_mode _mode)
: protocol(h, msg_cb, _mode),
m_state(_mode==protocol::connection_mode::ePassive? eHandlingHttpRequest : eSendingHttpRequest),
m_http_parser(new http_parser())
{
}
const char cb64[]="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
std::string base64Encode(const void* dataVoid, size_t length) {
std::string output;
auto data = reinterpret_cast<const uint8_t*>(dataVoid);
for (auto i = 0u; i < length; i += 3) {
auto bytesLeft = length - i;
auto b0 = data[i];
auto b1 = bytesLeft > 1 ? data[i + 1] : 0;
auto b2 = bytesLeft > 2 ? data[i + 2] : 0;
output.push_back(cb64[b0 >> 2]);
output.push_back(cb64[((b0 & 0x03) << 4) | ((b1 & 0xf0) >> 4)]);
output.push_back((bytesLeft > 1 ? cb64[((b1 & 0x0f) << 2) | ((b2 & 0xc0) >> 6)] : '='));
output.push_back((bytesLeft > 2 ? cb64[b2 & 0x3f] : '='));
}
return output;
}
inline std::string make_accept_key(const std::string& challenge)
{
auto full_key = challenge + websocket_protocol::MAGIC;
unsigned char obuf[20];
SHA1((const unsigned char*)full_key.c_str(), full_key.size(), obuf);
// SHA1 hasher;
// hasher.Input(fullString.c_str(), fullString.size());
// unsigned hash[5];
// hasher.Result(hash);
// for (int i = 0; i < 5; ++i) {
// hash[i] = htonl(hash[i]);
// }
return base64Encode(obuf, 20);
}
static bool string_list_contains(const std::string & source,
const std::string & match)
{
for (auto & i : tokenize(source.c_str(), ',', true))
{
std::string trimmed = trim(i);
if (case_insensitive_same(trimmed, match)) return true;
}
return false;
}
// Two byte conversion union
union uint16_converter
{
uint16_t i;
uint8_t m[2];
};
// Four byte conversion union
union uint32_converter
{
uint32_t i;
uint8_t m[4];
};
// Eight byte conversion union
union uint64_converter
{
uint64_t i;
uint8_t m[8];
};
struct frame_builder
{
// Minimum length of a WebSocket frame header.
static unsigned int const BASIC_HEADER_LENGTH = 2;
// Maximum length of a WebSocket header (2+8+4)
static unsigned int const MAX_HEADER_LENGTH = 14;
static uint8_t const FRAME_OPCODE = 0x0F;
static uint8_t const FRAME_FIN = 0x80;
static uint8_t const FRAME_MASKED = 0x80;
/** Construct */
frame_builder(int opcode, bool is_fin, size_t payload_len)
{
unsigned char is_fin_bit = is_fin?FRAME_FIN:0;
m_image[0] = is_fin_bit | (FRAME_OPCODE & opcode);
if (payload_len < 126)
{
m_image[1] = (unsigned char)(payload_len);
m_header_len = 2;
}
else if (payload_len < 65536)
{
uint16_converter temp;
temp.i = htons(payload_len & 0xFFFF);
m_image[1] = (unsigned char)126;
m_image[2] = temp.m[0];
m_image[3] = temp.m[1];
m_header_len = 4;
}
else
{
uint64_converter temp;
temp.i = __bswap_64(payload_len);
m_image[1] = (unsigned char)127;
for (int i = 0; i<8; ++i) m_image[2+i]=temp.m[i];
m_header_len = 10;
}
}
frame_builder(int opcode, bool is_fin, size_t payload_len, std::array<char,4> mask)
: frame_builder(opcode, is_fin, payload_len)
{
m_image[1] |= FRAME_MASKED;
m_image[m_header_len+0] = mask[0];
m_image[m_header_len+1] = mask[1];
m_image[m_header_len+2] = mask[2];
m_image[m_header_len+3] = mask[3];
m_header_len += 4;
}
char * data() { return m_image; }
const char * data() const { return m_image; }
size_t size() const { return m_header_len; }
std::pair<const char*, size_t> buf() const
{
return { data(), size() };
}
private:
// Storage for frame being created.
char m_image[MAX_HEADER_LENGTH];
// Actual frame size, since frame size depends on payload size and masking
size_t m_header_len;
};
void websocket_protocol::send_msg(const jalson::json_array& ja)
{
std::string msg ( jalson::encode( ja ) );
frame_builder fb(OPCODE_TEXT, true, msg.size());
std::pair<const char*, size_t> bufs[2];
bufs[0] = fb.buf();
bufs[1].first = (const char*)msg.c_str();;
bufs[1].second = msg.size();
m_iohandle->write_bufs(bufs, 2, false);
}
void websocket_protocol::io_on_read(char* src, size_t len)
{
while (len) /* IO thread */
{
size_t consume_len = m_buf.consume(src, len);
src += consume_len;
len -= consume_len;
auto rd = m_buf.read_ptr();
while (rd.avail())
{
if (m_state == eHandlingHttpRequest)
{
auto consumed = m_http_parser->handle_input(rd.ptr(), rd.avail());
rd.advance(consumed);
if (m_http_parser->fail())
throw handshake_error("bad http header: " + m_http_parser->error_text());
if (m_http_parser->complete() )
{
if ( m_http_parser->is_upgrade() &&
m_http_parser->count("Upgrade") &&
string_list_contains(m_http_parser->get("Upgrade"), "websocket") &&
m_http_parser->count("Connection") &&
string_list_contains(m_http_parser->get("Connection"), "Upgrade") &&
m_http_parser->count("Sec-WebSocket-Key") &&
m_http_parser->count("Sec-WebSocket-Version") )
{
auto websocket_version = std::stoi(m_http_parser->get("Sec-WebSocket-Version").c_str());
// TODO: hande version 0 ?
if (websocket_version == 13) // RFC6455
{
std::ostringstream os;
os << "HTTP/1.1 101 Switching Protocols" << "\r\n";
os << "Upgrade: websocket" << "\r\n";
os << "Connection: Upgrade" << "\r\n";
os << "Sec-WebSocket-Accept: " << make_accept_key(m_http_parser->get("Sec-WebSocket-Key")) << "\r\n";
os << "\r\n";
std::string msg = os.str();
std::pair<const char*, size_t> buf;
buf.first = msg.c_str();
buf.second = msg.size();
std::cout << "websocket header sent back\n";
m_iohandle->write_bufs(&buf, 1, false);
m_state = eHandlingWebsocket;
}
else
{
throw handshake_error("unsupported websocket version");
}
}
else
throw handshake_error("http header is not a websocket upgrade");
}
}
else if (m_state == eHandlingWebsocket)
{
if (rd.avail() < 2) break;
bool fin_bit = rd[0] & 0x80;
int opcode = rd[0] & 0x0F;
bool mask_bit = rd[1] & 0x80;
size_t payload_len = rd[1] & 0x7F;
size_t frame_len = 2 + (mask_bit? 4:0);
int mask_pos = 2;
int payload_pos;
if (payload_len == 126)
{
if (rd.avail() < 4) break;
frame_len += 2;
mask_pos += 2;
uint16_t raw_length;
memcpy(&raw_length, &rd[2], 2);
payload_len = ntohs(raw_length);
}
else if (payload_len == 127)
{
if (rd.avail() < 10) break;
frame_len += 8;
mask_pos += 8;
uint64_t raw_length;
memcpy(&raw_length, &rd[2], 8);
payload_len = __bswap_64(raw_length);
}
frame_len += payload_len;
payload_pos = mask_pos + (mask_bit? 4:0);
if (rd.avail() < frame_len) break;
for (size_t i = 0; i < (mask_bit?payload_len:0); ++i)
rd[payload_pos+i] ^= rd[mask_pos + (i%4)];
std::cout << "fin=" << fin_bit << ", opcode=" << opcode << ", "
<< "framelen=" << frame_len << ", ";
if (mask_bit) std::cout << "mask=" << to_hex(&rd[mask_pos], 4) << ", ";
std::cout << "payloadlen=" << payload_len << ", ";
std::string payload(&rd[payload_pos], payload_len);
std::cout << "payload=" << payload << "\n";
if (!fin_bit)
throw protocol_error("websocket continuations not yet supported");
switch (opcode)
{
case 0x00: /* cont. */ break;
case 0x01: /* text */ break;
case 0x02: /* bin. */
{
throw protocol_error("websocket binary messages not supported");
}
case OPCODE_CLOSE :
{
// issue a close frame
m_state = eClosing;
frame_builder fb(OPCODE_CLOSE, true, 0);
auto buf = fb.buf();
m_iohandle->write_bufs(&buf, 1, false);
// TODO: request for close should be initiaied from the owning session?
m_iohandle->request_close();
break;
};
default: break;
}
if (fin_bit && opcode == OPCODE_TEXT)
decode_json(rd.ptr()+payload_pos, payload_len);
rd.advance(frame_len);
}
else
{
throw protocol_error("websocket not ready to receive data");
}
}
m_buf.discard_read( rd ); /* shift unused bytes to front of buffer */
} // while(len)
}
void websocket_protocol::initiate(t_initiate_cb)
{
// TODO: implement websocket client
throw std::runtime_error("websocket_protocol::initiate not implemented");
}
void websocket_protocol::ev_on_timer()
{
if (m_state == eHandlingWebsocket)
{
frame_builder fb(OPCODE_PING, true, 0);
auto buf = fb.buf();
m_iohandle->write_bufs(&buf, 1, false);
}
}
}
<|endoftext|> |
<commit_before>// Copyright 2019 Oath Inc. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
#include "nearest_neighbor_iterator.h"
using search::tensor::DenseTensorAttribute;
using vespalib::ConstArrayRef;
using vespalib::tensor::DenseTensorView;
using vespalib::tensor::MutableDenseTensorView;
using vespalib::tensor::TypedCells;
using CellType = vespalib::eval::ValueType::CellType;
namespace search::queryeval {
/**
* Search iterator for K nearest neighbor matching.
* Uses unpack() as feedback mechanism to track which matches actually became hits.
* Keeps a heap of the K best hit distances.
* Currently always does brute-force scanning, which is very expensive.
**/
template <bool strict, typename LCT, typename RCT>
class NearestNeighborImpl : public NearestNeighborIterator
{
public:
NearestNeighborImpl(Params params_in)
: NearestNeighborIterator(params_in),
_lhs(params().queryTensor.cellsRef().typify<LCT>()),
_fieldTensor(params().tensorAttribute.getTensorType()),
_lastScore(0.0)
{
assert(_fieldTensor.fast_type() == params().queryTensor.fast_type());
}
~NearestNeighborImpl();
void doSeek(uint32_t docId) override {
double distanceLimit = params().distanceHeap.distanceLimit();
while (__builtin_expect((docId < getEndId()), true)) {
double d = computeDistance(docId, distanceLimit);
if (d <= distanceLimit) {
_lastScore = d;
setDocId(docId);
return;
}
if (strict) {
++docId;
} else {
return;
}
}
setAtEnd();
}
void doUnpack(uint32_t docId) override {
params().tfmd.setRawScore(docId, sqrt(_lastScore));
params().distanceHeap.used(_lastScore);
}
Trinary is_strict() const override { return strict ? Trinary::True : Trinary::False ; }
private:
static double computeSum(ConstArrayRef<LCT> lhs, ConstArrayRef<RCT> rhs, double limit) {
double sum = 0.0;
size_t sz = lhs.size();
assert(sz == rhs.size());
for (size_t i = 0; i < sz && sum <= limit; ++i) {
double diff = lhs[i] - rhs[i];
sum += diff*diff;
}
return sum;
}
double computeDistance(uint32_t docId, double limit) {
params().tensorAttribute.getTensor(docId, _fieldTensor);
return computeSum(_lhs, _fieldTensor.cellsRef().typify<RCT>(), limit);
}
ConstArrayRef<LCT> _lhs;
MutableDenseTensorView _fieldTensor;
double _lastScore;
};
template <bool strict, typename LCT, typename RCT>
NearestNeighborImpl<strict, LCT, RCT>::~NearestNeighborImpl() = default;
namespace {
template<bool strict, typename LCT, typename RCT>
std::unique_ptr<NearestNeighborIterator>
create_impl(const NearestNeighborIterator::Params ¶ms)
{
using NNI = NearestNeighborImpl<strict, LCT, RCT>;
return std::make_unique<NNI>(params);
}
template<bool strict, typename LCT>
std::unique_ptr<NearestNeighborIterator>
resolve_RCT(const NearestNeighborIterator::Params ¶ms)
{
CellType ct = params.tensorAttribute.getTensorType().cell_type();
if (ct == CellType::FLOAT) {
return create_impl<strict, LCT, float>(params);
}
if (ct == CellType::DOUBLE) {
return create_impl<strict, LCT, double>(params);
}
abort();
}
template<bool strict>
std::unique_ptr<NearestNeighborIterator>
resolve_LCT_RCT(const NearestNeighborIterator::Params ¶ms)
{
CellType ct = params.queryTensor.fast_type().cell_type();
if (ct == CellType::FLOAT) {
return resolve_RCT<strict, float>(params);
}
if (ct == CellType::DOUBLE) {
return resolve_RCT<strict, double>(params);
}
abort();
}
std::unique_ptr<NearestNeighborIterator>
resolve_strict_LCT_RCT(bool strict, const NearestNeighborIterator::Params ¶ms)
{
if (strict) {
return resolve_LCT_RCT<true>(params);
} else {
return resolve_LCT_RCT<false>(params);
}
}
} // namespace <unnamed>
std::unique_ptr<NearestNeighborIterator>
NearestNeighborIterator::create(
bool strict,
fef::TermFieldMatchData &tfmd,
const vespalib::tensor::DenseTensorView &queryTensor,
const search::tensor::DenseTensorAttribute &tensorAttribute,
NearestNeighborDistanceHeap &distanceHeap)
{
Params params(tfmd, queryTensor, tensorAttribute, distanceHeap);
return resolve_strict_LCT_RCT(strict, params);
}
} // namespace
<commit_msg>use select_2 for cell type resolving<commit_after>// Copyright 2019 Oath Inc. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
#include "nearest_neighbor_iterator.h"
using search::tensor::DenseTensorAttribute;
using vespalib::ConstArrayRef;
using vespalib::tensor::DenseTensorView;
using vespalib::tensor::MutableDenseTensorView;
using vespalib::tensor::TypedCells;
using CellType = vespalib::eval::ValueType::CellType;
namespace search::queryeval {
/**
* Search iterator for K nearest neighbor matching.
* Uses unpack() as feedback mechanism to track which matches actually became hits.
* Keeps a heap of the K best hit distances.
* Currently always does brute-force scanning, which is very expensive.
**/
template <bool strict, typename LCT, typename RCT>
class NearestNeighborImpl : public NearestNeighborIterator
{
public:
NearestNeighborImpl(Params params_in)
: NearestNeighborIterator(params_in),
_lhs(params().queryTensor.cellsRef().typify<LCT>()),
_fieldTensor(params().tensorAttribute.getTensorType()),
_lastScore(0.0)
{
assert(_fieldTensor.fast_type() == params().queryTensor.fast_type());
}
~NearestNeighborImpl();
void doSeek(uint32_t docId) override {
double distanceLimit = params().distanceHeap.distanceLimit();
while (__builtin_expect((docId < getEndId()), true)) {
double d = computeDistance(docId, distanceLimit);
if (d <= distanceLimit) {
_lastScore = d;
setDocId(docId);
return;
}
if (strict) {
++docId;
} else {
return;
}
}
setAtEnd();
}
void doUnpack(uint32_t docId) override {
params().tfmd.setRawScore(docId, sqrt(_lastScore));
params().distanceHeap.used(_lastScore);
}
Trinary is_strict() const override { return strict ? Trinary::True : Trinary::False ; }
private:
static double computeSum(ConstArrayRef<LCT> lhs, ConstArrayRef<RCT> rhs, double limit) {
double sum = 0.0;
size_t sz = lhs.size();
assert(sz == rhs.size());
for (size_t i = 0; i < sz && sum <= limit; ++i) {
double diff = lhs[i] - rhs[i];
sum += diff*diff;
}
return sum;
}
double computeDistance(uint32_t docId, double limit) {
params().tensorAttribute.getTensor(docId, _fieldTensor);
return computeSum(_lhs, _fieldTensor.cellsRef().typify<RCT>(), limit);
}
ConstArrayRef<LCT> _lhs;
MutableDenseTensorView _fieldTensor;
double _lastScore;
};
template <bool strict, typename LCT, typename RCT>
NearestNeighborImpl<strict, LCT, RCT>::~NearestNeighborImpl() = default;
namespace {
template<bool strict, typename LCT, typename RCT>
std::unique_ptr<NearestNeighborIterator>
create_impl(const NearestNeighborIterator::Params ¶ms)
{
using NNI = NearestNeighborImpl<strict, LCT, RCT>;
return std::make_unique<NNI>(params);
}
using Creator = std::unique_ptr<NearestNeighborIterator>(*)(const NearestNeighborIterator::Params ¶ms);
template <bool strict>
struct CellTypeResolver
{
template <typename LCT, typename RCT>
static Creator
get_fun() { return create_impl<strict, LCT, RCT>; }
};
std::unique_ptr<NearestNeighborIterator>
resolve_strict_LCT_RCT(bool strict, const NearestNeighborIterator::Params ¶ms)
{
CellType lct = params.queryTensor.fast_type().cell_type();
CellType rct = params.tensorAttribute.getTensorType().cell_type();
if (strict) {
using Resolver = CellTypeResolver<true>;
auto fun = vespalib::tensor::select_2<Resolver>(lct, rct);
return fun(params);
} else {
using Resolver = CellTypeResolver<false>;
auto fun = vespalib::tensor::select_2<Resolver>(lct, rct);
return fun(params);
}
}
} // namespace <unnamed>
std::unique_ptr<NearestNeighborIterator>
NearestNeighborIterator::create(
bool strict,
fef::TermFieldMatchData &tfmd,
const vespalib::tensor::DenseTensorView &queryTensor,
const search::tensor::DenseTensorAttribute &tensorAttribute,
NearestNeighborDistanceHeap &distanceHeap)
{
Params params(tfmd, queryTensor, tensorAttribute, distanceHeap);
return resolve_strict_LCT_RCT(strict, params);
}
} // namespace
<|endoftext|> |
<commit_before>//===----------------------------------------------------------------------===//
//
// Peloton
//
// serializable_transaction_test.cpp
//
// Identification: test/concurrency/serializable_transaction_test.cpp
//
// Copyright (c) 2015-16, Carnegie Mellon University Database Group
//
//===----------------------------------------------------------------------===//
#include "common/harness.h"
#include "concurrency/testing_transaction_util.h"
namespace peloton {
namespace test {
//===--------------------------------------------------------------------===//
// Serializable Transaction Tests
//===--------------------------------------------------------------------===//
class SerializableTransactionTests : public PelotonTest {};
static std::vector<ProtocolType> PROTOCOL_TYPES = {
ProtocolType::TIMESTAMP_ORDERING
};
static IsolationLevelType ISOLATION_LEVEL_TYPE =
IsolationLevelType::SERIALIZABLE;
void TransactionTest(concurrency::TransactionManager *txn_manager,
UNUSED_ATTRIBUTE uint64_t thread_itr) {
uint64_t thread_id = TestingHarness::GetInstance().GetThreadId();
for (oid_t txn_itr = 1; txn_itr <= 50; txn_itr++) {
auto txn = txn_manager->BeginTransaction();
if (thread_id % 2 == 0) {
std::chrono::microseconds sleep_time(1);
std::this_thread::sleep_for(sleep_time);
}
if (txn_itr % 25 != 0) {
txn_manager->CommitTransaction(txn);
} else {
txn_manager->AbortTransaction(txn);
}
}
}
TEST_F(SerializableTransactionTests, TransactionTest) {
for (auto protocol_type : PROTOCOL_TYPES) {
concurrency::TransactionManagerFactory::Configure(protocol_type);
auto &txn_manager = concurrency::TransactionManagerFactory::GetInstance();
LaunchParallelTest(8, TransactionTest, &txn_manager);
}
}
// test predeclared read-only transaction
TEST_F(SerializableTransactionTests, ReadOnlyTransactionTest) {
for (auto protocol_type : PROTOCOL_TYPES) {
concurrency::TransactionManagerFactory::Configure(protocol_type, ISOLATION_LEVEL_TYPE);
auto &txn_manager = concurrency::TransactionManagerFactory::GetInstance();
// Just scan the table
{
storage::DataTable *table = TestingTransactionUtil::CreateTable();
TransactionScheduler scheduler(1, table, &txn_manager, true);
scheduler.Txn(0).Scan(0);
scheduler.Txn(0).Commit();
scheduler.Run();
// Snapshot read cannot read the recent insert
EXPECT_EQ(0, scheduler.schedules[0].results.size());
}
}
}
TEST_F(SerializableTransactionTests, SingleTransactionTest) {
for (auto protocol_type : PROTOCOL_TYPES) {
concurrency::TransactionManagerFactory::Configure(protocol_type, ISOLATION_LEVEL_TYPE);
auto &txn_manager = concurrency::TransactionManagerFactory::GetInstance();
// Just scan the table
{
concurrency::EpochManagerFactory::GetInstance().Reset();
storage::DataTable *table = TestingTransactionUtil::CreateTable();
TransactionScheduler scheduler(1, table, &txn_manager);
scheduler.Txn(0).Scan(0);
scheduler.Txn(0).Commit();
scheduler.Run();
EXPECT_EQ(10, scheduler.schedules[0].results.size());
}
// read, read, read, read, update, read, read not exist
{
concurrency::EpochManagerFactory::GetInstance().Reset();
storage::DataTable *table = TestingTransactionUtil::CreateTable();
TransactionScheduler scheduler(1, table, &txn_manager);
scheduler.Txn(0).Read(0);
scheduler.Txn(0).Read(0);
scheduler.Txn(0).Read(0);
scheduler.Txn(0).Read(0);
scheduler.Txn(0).Update(0, 1);
scheduler.Txn(0).Read(0);
scheduler.Txn(0).Read(100);
scheduler.Txn(0).Commit();
scheduler.Run();
EXPECT_EQ(ResultType::SUCCESS, scheduler.schedules[0].txn_result);
EXPECT_EQ(0, scheduler.schedules[0].results[0]);
EXPECT_EQ(0, scheduler.schedules[0].results[1]);
EXPECT_EQ(0, scheduler.schedules[0].results[2]);
EXPECT_EQ(0, scheduler.schedules[0].results[3]);
EXPECT_EQ(1, scheduler.schedules[0].results[4]);
EXPECT_EQ(-1, scheduler.schedules[0].results[5]);
}
// update, update, update, update, read
{
concurrency::EpochManagerFactory::GetInstance().Reset();
storage::DataTable *table = TestingTransactionUtil::CreateTable();
TransactionScheduler scheduler(1, table, &txn_manager);
scheduler.Txn(0).Update(0, 1);
scheduler.Txn(0).Read(0);
scheduler.Txn(0).Update(0, 2);
scheduler.Txn(0).Read(0);
scheduler.Txn(0).Update(0, 3);
scheduler.Txn(0).Read(0);
scheduler.Txn(0).Update(0, 4);
scheduler.Txn(0).Read(0);
scheduler.Txn(0).Commit();
scheduler.Run();
EXPECT_EQ(ResultType::SUCCESS, scheduler.schedules[0].txn_result);
EXPECT_EQ(1, scheduler.schedules[0].results[0]);
EXPECT_EQ(2, scheduler.schedules[0].results[1]);
EXPECT_EQ(3, scheduler.schedules[0].results[2]);
EXPECT_EQ(4, scheduler.schedules[0].results[3]);
}
// delete not exist, delete exist, read deleted, update deleted,
// read deleted, insert back, update inserted, read newly updated,
// delete inserted, read deleted
{
concurrency::EpochManagerFactory::GetInstance().Reset();
storage::DataTable *table = TestingTransactionUtil::CreateTable();
TransactionScheduler scheduler(1, table, &txn_manager);
scheduler.Txn(0).Delete(100);
scheduler.Txn(0).Delete(0);
scheduler.Txn(0).Read(0);
scheduler.Txn(0).Update(0, 1);
scheduler.Txn(0).Read(0);
scheduler.Txn(0).Insert(0, 2);
scheduler.Txn(0).Update(0, 3);
scheduler.Txn(0).Read(0);
scheduler.Txn(0).Delete(0);
scheduler.Txn(0).Read(0);
scheduler.Txn(0).Commit();
scheduler.Run();
EXPECT_EQ(ResultType::SUCCESS, scheduler.schedules[0].txn_result);
EXPECT_EQ(-1, scheduler.schedules[0].results[0]);
EXPECT_EQ(-1, scheduler.schedules[0].results[1]);
EXPECT_EQ(3, scheduler.schedules[0].results[2]);
EXPECT_EQ(-1, scheduler.schedules[0].results[3]);
// LOG_INFO("FINISH THIS");
}
// insert, delete inserted, read deleted, insert again, delete again
// read deleted, insert again, read inserted, update inserted, read updated
{
concurrency::EpochManagerFactory::GetInstance().Reset();
storage::DataTable *table = TestingTransactionUtil::CreateTable();
TransactionScheduler scheduler(1, table, &txn_manager);
scheduler.Txn(0).Insert(1000, 0);
scheduler.Txn(0).Read(1000);
scheduler.Txn(0).Delete(1000);
scheduler.Txn(0).Read(1000);
scheduler.Txn(0).Insert(1000, 1);
scheduler.Txn(0).Delete(1000);
scheduler.Txn(0).Read(1000);
scheduler.Txn(0).Insert(1000, 2);
scheduler.Txn(0).Read(1000);
scheduler.Txn(0).Update(1000, 3);
scheduler.Txn(0).Read(1000);
scheduler.Txn(0).Commit();
scheduler.Run();
EXPECT_EQ(ResultType::SUCCESS, scheduler.schedules[0].txn_result);
EXPECT_EQ(0, scheduler.schedules[0].results[0]);
EXPECT_EQ(-1, scheduler.schedules[0].results[1]);
EXPECT_EQ(-1, scheduler.schedules[0].results[2]);
EXPECT_EQ(2, scheduler.schedules[0].results[3]);
EXPECT_EQ(3, scheduler.schedules[0].results[4]);
}
}
}
TEST_F(SerializableTransactionTests, AbortTest) {
for (auto protocol_type : PROTOCOL_TYPES) {
concurrency::TransactionManagerFactory::Configure(protocol_type);
auto &txn_manager = concurrency::TransactionManagerFactory::GetInstance();
storage::DataTable *table = TestingTransactionUtil::CreateTable();
{
TransactionScheduler scheduler(2, table, &txn_manager);
scheduler.Txn(0).Update(0, 100);
scheduler.Txn(0).Abort();
scheduler.Txn(1).Read(0);
scheduler.Txn(1).Commit();
scheduler.Run();
EXPECT_EQ(ResultType::ABORTED, scheduler.schedules[0].txn_result);
EXPECT_EQ(ResultType::SUCCESS, scheduler.schedules[1].txn_result);
EXPECT_EQ(0, scheduler.schedules[1].results[0]);
}
{
TransactionScheduler scheduler(2, table, &txn_manager);
scheduler.Txn(0).Insert(100, 0);
scheduler.Txn(0).Abort();
scheduler.Txn(1).Read(100);
scheduler.Txn(1).Commit();
scheduler.Run();
EXPECT_EQ(ResultType::ABORTED, scheduler.schedules[0].txn_result);
EXPECT_EQ(ResultType::SUCCESS, scheduler.schedules[1].txn_result);
EXPECT_EQ(-1, scheduler.schedules[1].results[0]);
}
}
}
} // End test namespace
} // End peloton namespace
<commit_msg>add test cases for serializable isolation<commit_after>//===----------------------------------------------------------------------===//
//
// Peloton
//
// serializable_transaction_test.cpp
//
// Identification: test/concurrency/serializable_transaction_test.cpp
//
// Copyright (c) 2015-16, Carnegie Mellon University Database Group
//
//===----------------------------------------------------------------------===//
#include "common/harness.h"
#include "concurrency/testing_transaction_util.h"
namespace peloton {
namespace test {
//===--------------------------------------------------------------------===//
// Serializable Transaction Tests
//===--------------------------------------------------------------------===//
class SerializableTransactionTests : public PelotonTest {};
static std::vector<ProtocolType> PROTOCOL_TYPES = {
ProtocolType::TIMESTAMP_ORDERING
};
static IsolationLevelType ISOLATION_LEVEL_TYPE =
IsolationLevelType::SERIALIZABLE;
void TransactionTest(concurrency::TransactionManager *txn_manager,
UNUSED_ATTRIBUTE uint64_t thread_itr) {
uint64_t thread_id = TestingHarness::GetInstance().GetThreadId();
for (oid_t txn_itr = 1; txn_itr <= 50; txn_itr++) {
auto txn = txn_manager->BeginTransaction();
if (thread_id % 2 == 0) {
std::chrono::microseconds sleep_time(1);
std::this_thread::sleep_for(sleep_time);
}
if (txn_itr % 25 != 0) {
txn_manager->CommitTransaction(txn);
} else {
txn_manager->AbortTransaction(txn);
}
}
}
TEST_F(SerializableTransactionTests, TransactionTest) {
for (auto protocol_type : PROTOCOL_TYPES) {
concurrency::TransactionManagerFactory::Configure(protocol_type);
auto &txn_manager = concurrency::TransactionManagerFactory::GetInstance();
LaunchParallelTest(8, TransactionTest, &txn_manager);
}
}
// test predeclared read-only transaction
TEST_F(SerializableTransactionTests, ReadOnlyTransactionTest) {
for (auto protocol_type : PROTOCOL_TYPES) {
concurrency::TransactionManagerFactory::Configure(protocol_type, ISOLATION_LEVEL_TYPE);
auto &txn_manager = concurrency::TransactionManagerFactory::GetInstance();
// Just scan the table
{
concurrency::EpochManagerFactory::GetInstance().Reset();
storage::DataTable *table = TestingTransactionUtil::CreateTable();
TransactionScheduler scheduler(1, table, &txn_manager, true);
scheduler.Txn(0).Scan(0);
scheduler.Txn(0).Commit();
scheduler.Run();
// Snapshot read cannot read the recent insert
EXPECT_EQ(0, scheduler.schedules[0].results.size());
}
}
}
// test with single transaction
TEST_F(SerializableTransactionTests, SingleTransactionTest) {
for (auto protocol_type : PROTOCOL_TYPES) {
concurrency::TransactionManagerFactory::Configure(protocol_type, ISOLATION_LEVEL_TYPE);
auto &txn_manager = concurrency::TransactionManagerFactory::GetInstance();
// Just scan the table
{
concurrency::EpochManagerFactory::GetInstance().Reset();
storage::DataTable *table = TestingTransactionUtil::CreateTable();
TransactionScheduler scheduler(1, table, &txn_manager);
scheduler.Txn(0).Scan(0);
scheduler.Txn(0).Commit();
scheduler.Run();
EXPECT_EQ(10, scheduler.schedules[0].results.size());
}
// read, read, read, read, update, read, read not exist
{
concurrency::EpochManagerFactory::GetInstance().Reset();
storage::DataTable *table = TestingTransactionUtil::CreateTable();
TransactionScheduler scheduler(1, table, &txn_manager);
scheduler.Txn(0).Read(0);
scheduler.Txn(0).Read(0);
scheduler.Txn(0).Read(0);
scheduler.Txn(0).Read(0);
scheduler.Txn(0).Update(0, 1);
scheduler.Txn(0).Read(0);
scheduler.Txn(0).Read(100);
scheduler.Txn(0).Commit();
scheduler.Run();
EXPECT_EQ(ResultType::SUCCESS, scheduler.schedules[0].txn_result);
EXPECT_EQ(0, scheduler.schedules[0].results[0]);
EXPECT_EQ(0, scheduler.schedules[0].results[1]);
EXPECT_EQ(0, scheduler.schedules[0].results[2]);
EXPECT_EQ(0, scheduler.schedules[0].results[3]);
EXPECT_EQ(1, scheduler.schedules[0].results[4]);
EXPECT_EQ(-1, scheduler.schedules[0].results[5]);
}
// update, update, update, update, read
{
concurrency::EpochManagerFactory::GetInstance().Reset();
storage::DataTable *table = TestingTransactionUtil::CreateTable();
TransactionScheduler scheduler(1, table, &txn_manager);
scheduler.Txn(0).Update(0, 1);
scheduler.Txn(0).Read(0);
scheduler.Txn(0).Update(0, 2);
scheduler.Txn(0).Read(0);
scheduler.Txn(0).Update(0, 3);
scheduler.Txn(0).Read(0);
scheduler.Txn(0).Update(0, 4);
scheduler.Txn(0).Read(0);
scheduler.Txn(0).Commit();
scheduler.Run();
EXPECT_EQ(ResultType::SUCCESS, scheduler.schedules[0].txn_result);
EXPECT_EQ(1, scheduler.schedules[0].results[0]);
EXPECT_EQ(2, scheduler.schedules[0].results[1]);
EXPECT_EQ(3, scheduler.schedules[0].results[2]);
EXPECT_EQ(4, scheduler.schedules[0].results[3]);
}
// delete not exist, delete exist, read deleted, update deleted,
// read deleted, insert back, update inserted, read newly updated,
// delete inserted, read deleted
{
concurrency::EpochManagerFactory::GetInstance().Reset();
storage::DataTable *table = TestingTransactionUtil::CreateTable();
TransactionScheduler scheduler(1, table, &txn_manager);
scheduler.Txn(0).Delete(100);
scheduler.Txn(0).Delete(0);
scheduler.Txn(0).Read(0);
scheduler.Txn(0).Update(0, 1);
scheduler.Txn(0).Read(0);
scheduler.Txn(0).Insert(0, 2);
scheduler.Txn(0).Update(0, 3);
scheduler.Txn(0).Read(0);
scheduler.Txn(0).Delete(0);
scheduler.Txn(0).Read(0);
scheduler.Txn(0).Commit();
scheduler.Run();
EXPECT_EQ(ResultType::SUCCESS, scheduler.schedules[0].txn_result);
EXPECT_EQ(-1, scheduler.schedules[0].results[0]);
EXPECT_EQ(-1, scheduler.schedules[0].results[1]);
EXPECT_EQ(3, scheduler.schedules[0].results[2]);
EXPECT_EQ(-1, scheduler.schedules[0].results[3]);
}
// insert, delete inserted, read deleted, insert again, delete again
// read deleted, insert again, read inserted, update inserted, read updated
{
concurrency::EpochManagerFactory::GetInstance().Reset();
storage::DataTable *table = TestingTransactionUtil::CreateTable();
TransactionScheduler scheduler(1, table, &txn_manager);
scheduler.Txn(0).Insert(1000, 0);
scheduler.Txn(0).Read(1000);
scheduler.Txn(0).Delete(1000);
scheduler.Txn(0).Read(1000);
scheduler.Txn(0).Insert(1000, 1);
scheduler.Txn(0).Delete(1000);
scheduler.Txn(0).Read(1000);
scheduler.Txn(0).Insert(1000, 2);
scheduler.Txn(0).Read(1000);
scheduler.Txn(0).Update(1000, 3);
scheduler.Txn(0).Read(1000);
scheduler.Txn(0).Commit();
scheduler.Run();
EXPECT_EQ(ResultType::SUCCESS, scheduler.schedules[0].txn_result);
EXPECT_EQ(0, scheduler.schedules[0].results[0]);
EXPECT_EQ(-1, scheduler.schedules[0].results[1]);
EXPECT_EQ(-1, scheduler.schedules[0].results[2]);
EXPECT_EQ(2, scheduler.schedules[0].results[3]);
EXPECT_EQ(3, scheduler.schedules[0].results[4]);
}
}
}
// test with concurrent transactions
TEST_F(SerializableTransactionTests, ConcurrentTransactionsTest) {
for (auto protocol_type : PROTOCOL_TYPES) {
concurrency::TransactionManagerFactory::Configure(protocol_type, ISOLATION_LEVEL_TYPE);
auto &txn_manager = concurrency::TransactionManagerFactory::GetInstance();
{
concurrency::EpochManagerFactory::GetInstance().Reset();
storage::DataTable *table = TestingTransactionUtil::CreateTable();
TransactionScheduler scheduler(2, table, &txn_manager);
scheduler.Txn(0).Insert(100, 1);
scheduler.Txn(1).Read(100);
scheduler.Txn(0).Read(100);
scheduler.Txn(0).Commit();
scheduler.Txn(1).Read(100);
scheduler.Txn(1).Commit();
scheduler.Run();
EXPECT_EQ(ResultType::SUCCESS, scheduler.schedules[0].txn_result);
EXPECT_EQ(ResultType::SUCCESS, scheduler.schedules[1].txn_result);
EXPECT_EQ(1, scheduler.schedules[0].results[0]);
EXPECT_EQ(-1, scheduler.schedules[1].results[0]);
// TODO: phantom problem.
// In fact, txn 1 should not see the inserted tuple.
EXPECT_EQ(1, scheduler.schedules[1].results[1]);
}
{
concurrency::EpochManagerFactory::GetInstance().Reset();
storage::DataTable *table = TestingTransactionUtil::CreateTable();
TransactionScheduler scheduler(2, table, &txn_manager);
scheduler.Txn(0).Update(0, 1);
scheduler.Txn(1).Read(0);
scheduler.Txn(0).Read(0);
scheduler.Txn(0).Commit();
scheduler.Txn(1).Read(0);
scheduler.Txn(1).Commit();
scheduler.Run();
EXPECT_EQ(ResultType::SUCCESS, scheduler.schedules[0].txn_result);
EXPECT_EQ(ResultType::ABORTED, scheduler.schedules[1].txn_result);
EXPECT_EQ(1, scheduler.schedules[0].results[0]);
}
}
}
TEST_F(SerializableTransactionTests, AbortTest) {
for (auto protocol_type : PROTOCOL_TYPES) {
concurrency::TransactionManagerFactory::Configure(protocol_type);
auto &txn_manager = concurrency::TransactionManagerFactory::GetInstance();
storage::DataTable *table = TestingTransactionUtil::CreateTable();
{
TransactionScheduler scheduler(2, table, &txn_manager);
scheduler.Txn(0).Update(0, 100);
scheduler.Txn(0).Abort();
scheduler.Txn(1).Read(0);
scheduler.Txn(1).Commit();
scheduler.Run();
EXPECT_EQ(ResultType::ABORTED, scheduler.schedules[0].txn_result);
EXPECT_EQ(ResultType::SUCCESS, scheduler.schedules[1].txn_result);
EXPECT_EQ(0, scheduler.schedules[1].results[0]);
}
{
TransactionScheduler scheduler(2, table, &txn_manager);
scheduler.Txn(0).Insert(100, 0);
scheduler.Txn(0).Abort();
scheduler.Txn(1).Read(100);
scheduler.Txn(1).Commit();
scheduler.Run();
EXPECT_EQ(ResultType::ABORTED, scheduler.schedules[0].txn_result);
EXPECT_EQ(ResultType::SUCCESS, scheduler.schedules[1].txn_result);
EXPECT_EQ(-1, scheduler.schedules[1].results[0]);
}
}
}
} // End test namespace
} // End peloton namespace
<|endoftext|> |
<commit_before>/*
MIT License
Copyright (c) 2019 Bart Bilos
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/
#ifndef BOARD_HPP
#define BOARD_HPP
#define CLOCK_MAIN_SOURCE SYSCTL_MAINCLKSRC_PLLOUT
#define CLOCK_XTAL (12000000u)
#define CLOCK_EXT_IN (0u)
#define CLOCK_CPU (30000000u)
#define CLOCK_AHB (30000000u)
#define CLOCK_MAIN (60000000u)
#define TICKS_PER_S (100u)
#define IOCON_XTAL_IN IOCON_PIO8
#define IOCON_XTAL_OUT IOCON_PIO9
#define IOCON_UART_TX IOCON_PIO25
#define PIN_UART_TX (25u)
#define IOCON_UART_RX IOCON_PIO24
#define PIN_UART_RX (24u)
#define IOCON_LED_ALIVE IOCON_PIO12
#define PIN_LED_ALIVE (12u)
#define IOCON_LED_ACT IOCON_PIO13
#define PIN_LED_ACT (13u)
#define IOCON_SPI_FLASH_SIO0 IOCON_PIO17
#define IOCON_SPI_FLASH_SIO1 IOCON_PIO18
#define IOCON_SPI_FLASH_SIO2 IOCON_PIO19
#define IOCON_SPI_FLASH_SIO3 IOCON_PIO20
#define IOCON_SPI_FLASH_CE IOCON_PIO21
#define IOCON_SPI_FLASH_SCK IOCON_PIO22
#define PIN_SPI_FLASH_SIO0 (17u)
#define PIN_SPI_FLASH_SIO1 (18u)
#define PIN_SPI_FLASH_SIO2 (19u)
#define PIN_SPI_FLASH_SIO3 (20u)
#define PIN_SPI_FLASH_CE (21u)
#define PIN_SPI_FLASH_SCK (22u)
#define UART_DEBUG LPC_USART0
#define UART_BAUD_RATE (115200u)
void boardInit(void);
#endif<commit_msg>added SPI information to QSPI definition<commit_after>/*
MIT License
Copyright (c) 2019 Bart Bilos
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/
#ifndef BOARD_HPP
#define BOARD_HPP
#define CLOCK_MAIN_SOURCE SYSCTL_MAINCLKSRC_PLLOUT
#define CLOCK_XTAL (12000000u)
#define CLOCK_EXT_IN (0u)
#define CLOCK_CPU (30000000u)
#define CLOCK_AHB (30000000u)
#define CLOCK_MAIN (60000000u)
#define TICKS_PER_S (100u)
#define IOCON_XTAL_IN IOCON_PIO8
#define IOCON_XTAL_OUT IOCON_PIO9
#define IOCON_UART_TX IOCON_PIO25
#define PIN_UART_TX (25u)
#define IOCON_UART_RX IOCON_PIO24
#define PIN_UART_RX (24u)
#define IOCON_LED_ALIVE IOCON_PIO12
#define PIN_LED_ALIVE (12u)
#define IOCON_LED_ACT IOCON_PIO13
#define PIN_LED_ACT (13u)
#define IOCON_SPI_FLASH_SIO0 IOCON_PIO17 // MOSI
#define IOCON_SPI_FLASH_SIO1 IOCON_PIO18 // MISO
#define IOCON_SPI_FLASH_SIO2 IOCON_PIO19 // !WP
#define IOCON_SPI_FLASH_SIO3 IOCON_PIO20 // !HOLD
#define IOCON_SPI_FLASH_CE IOCON_PIO21 // CE
#define IOCON_SPI_FLASH_SCK IOCON_PIO22 // SCK
#define PIN_SPI_FLASH_SIO0 (17u)
#define PIN_SPI_FLASH_SIO1 (18u)
#define PIN_SPI_FLASH_SIO2 (19u)
#define PIN_SPI_FLASH_SIO3 (20u)
#define PIN_SPI_FLASH_CE (21u)
#define PIN_SPI_FLASH_SCK (22u)
#define UART_DEBUG LPC_USART0
#define UART_BAUD_RATE (115200u)
void boardInit(void);
#endif<|endoftext|> |
<commit_before>/*****************************************************************************
* Copyright (C) 2011-2012 Michael Krufky
*
* Author: Michael Krufky <mkrufky@linuxtv.org>
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*
*****************************************************************************/
#include <stdio.h>
#include <string>
#include "text.h"
const char * html_dump_epg_header_footer_callback(void *, bool header, bool channel)
{
//fprintf(stderr, "%s(%s, %s)\n", __func__, (header) ? "header" : "footer", (channel) ? "channel" : "body");
const char *str = NULL;
if (header)
if (channel)
str = "<tr>";
else
str = "<html><body><table border=1>";
else
if (channel)
str = "</tr>";
else
str = "</table></body></html>";
// fprintf(stderr, "%s", str);
return str;
}
const char * json_dump_epg_header_footer_callback(void *, bool header, bool channel)
{
//fprintf(stderr, "%s(%s, %s)\n", __func__, (header) ? "header" : "footer", (channel) ? "channel" : "body");
const char *str = NULL;
if (header)
if (channel)
str = "{\"Entries\":\n[";
else
str = "[";
else
if (channel)
str = "]}";
else
str = "]";
// fprintf(stderr, "%s", str);
return str;
}
const char * html_dump_epg_event_callback(void * context,
const char * channel_name,
uint16_t chan_major,
uint16_t chan_minor,
//
uint16_t event_id,
time_t start_time,
uint32_t length_sec,
const char * name,
const char * text)
{
//fprintf(stderr, "%s()\n", __func__);
std::string str;
str.clear();
str.append("<td>");
//str.append("channel: ");
if (channel_name) {
char chan_nbr[12] = { 0 };
snprintf(chan_nbr, sizeof(chan_nbr), "%d.%d: ", chan_major, chan_minor);
str.append("<nobr>");
str.append(chan_nbr);
str.append(channel_name);
str.append("</nobr>");
}
//str.append("show: ");
if (name) {
time_t end_time = start_time + length_sec;
struct tm tms = *localtime( &start_time );
struct tm tme = *localtime( &end_time );
char time_str[14] = { 0 };
str.append(name);
snprintf(time_str, sizeof(time_str), "%02d:%02d - %02d:%02d", tms.tm_hour, tms.tm_min, tme.tm_hour, tme.tm_min);
str.append("<hr><nobr>");
str.append(time_str);
str.append("</nobr>");
}
str.append("</td>");
// fprintf(stderr, "%s", str.c_str());
return str.c_str();
}
const char * json_dump_epg_event_callback(void * context,
const char * channel_name,
uint16_t chan_major,
uint16_t chan_minor,
//
uint16_t event_id,
time_t start_time,
uint32_t length_sec,
const char * name,
const char * text)
{
time_t end_time = start_time + length_sec;
char time_str[15] = { 0 };
//fprintf(stderr, "%s()\n", __func__);
std::string str;
str.clear();
str.append("{");
str.append("\"StartTime\":");
#if 1
snprintf(time_str, sizeof(time_str), "%lld", (long long int)start_time);
str.append(time_str);
#else
str.append(ctime(&start_time));
#endif
str.append(",");
str.append("\"EndTime\":");
#if 1
snprintf(time_str, sizeof(time_str), "%lld", (long long int)end_time); // "%jd", (intmax_t)end_time);
str.append(time_str);
#else
str.append(ctime(&end_time));
#endif
str.append(",");
str.append("\"Title\":\"");
str.append(name);
str.append("\",");
str.append("\"ShortDescription\":\"");
//str.append(text);
str.append("\"");
str.append("}");
// fprintf(stderr, "%s", str.c_str());
return str.c_str();
}
const char * html_dump_channels(void *context,
uint16_t lcn, uint16_t major, uint16_t minor,
uint16_t physical_channel, uint32_t freq, const char *modulation,
unsigned char *service_name, uint16_t vpid, uint16_t apid, uint16_t program_number)
{
std::string str;
str.clear();
char channelno[7]; /* XXX.XXX */
if (major + minor > 1)
sprintf(channelno, "%d.%d", major, minor);
else if (lcn)
sprintf(channelno, "%d", lcn);
else
sprintf(channelno, "%d", physical_channel);
fprintf(stdout, "%s-%s:%d:%s:%d:%d:%d\n",
channelno,
service_name,
freq,//iter_vct->second.carrier_freq,
modulation,
vpid, apid, program_number);
char phy_chan[4] = { 0 };
char svc_id[6] = { 0 };
sprintf(phy_chan, "%d", physical_channel);
sprintf(svc_id, "%d", program_number);
str.append("<table>");
str.append("<tr>");
str.append("<td>");
str.append("<a href='/tune=");
str.append(phy_chan);
str.append("+");
str.append(svc_id);
str.append("'>");
str.append(channelno);
str.append(": ");
str.append((const char *)service_name);
str.append("</a>");
#if 0
str.append("</td>");
str.append("</tr>");
str.append("<tr>");
str.append("<td>");
str.append("<hr>");
#endif
str.append("</td>");
str.append("</tr>");
str.append("</table>");
return str.c_str();
}
const char * json_dump_channels(void *context,
uint16_t lcn, uint16_t major, uint16_t minor,
uint16_t physical_channel, uint32_t freq, const char *modulation,
unsigned char *service_name, uint16_t vpid, uint16_t apid, uint16_t program_number)
{
std::string str;
str.clear();
char channelno[7] = { 0 }; /* XXX.XXX */
char chan_major[3] = { 0 };
char chan_minor[3] = { 0 };
if (major + minor > 1) {
sprintf(channelno, "%d.%d", major, minor);
sprintf(chan_major, "%d", major);
sprintf(chan_minor, "%d", minor);
} else if (lcn) {
sprintf(channelno, "%d", lcn);
sprintf(chan_major, "%d", lcn);
sprintf(chan_minor, "%d", 0);
} else {
sprintf(channelno, "%d", physical_channel);
sprintf(chan_major, "%d", physical_channel);
sprintf(chan_minor, "%d", program_number);
}
fprintf(stdout, "%s-%s:%d:%s:%d:%d:%d\n",
channelno,
service_name,
freq,//iter_vct->second.carrier_freq,
modulation,
vpid, apid, program_number);
char phy_chan[4] = { 0 };
char svc_id[6] = { 0 };
sprintf(phy_chan, "%d", physical_channel);
sprintf(svc_id, "%d", program_number);
str.append("{");
str.append("\"Id\":\"");
str.append("tune");
str.append("&channel=");
str.append(phy_chan);
str.append("&service=");
str.append(svc_id);
str.append("\"");
str.append(",");
str.append("\"DisplayName\":\"");
str.append((const char *)service_name);
str.append("\"");
str.append(",");
str.append("\"MajorChannelNo\":\"");
str.append(chan_major);
str.append("\"");
str.append(",");
str.append("\"MinorChannelNo\":\"");
str.append(chan_minor);
str.append("\"");
str.append("}");
str.append(",");
return str.c_str();
}
const char * html_playing_video(void *)
{
std::string str;
str.clear();
str.append("<html><body>");
// str.append("<video height=\"1280\" width=\"720\" controls>");
str.append("<div style=\"position:relative;width:604px;height:256px;float:center;\">");
str.append("<video controls=\"controls\" autoplay=\"autoplay\" poster=\"http://easyhtml5video.com/images/happyfit2.jpg\" width=\"604\" height=\"256\" onclick=\"if(/Android/.test(navigator.userAgent))this.play();\">");
// str.append("<video controls>");
str.append("<source src=\"/stream/\"");
str.append(" type='video/mp2ts");
str.append("; codecs=\"ac-3\"");
str.append("'>");
str.append("<source src=\"http://easyhtml5video.com/images/happyfit2.mp4\" type=\"video/mp4\">");
str.append("</video>");
str.append("</div>");
str.append("</body></html>");
return str.c_str();
}
<commit_msg>text: allow use of www interface as 'channel flipper'<commit_after>/*****************************************************************************
* Copyright (C) 2011-2012 Michael Krufky
*
* Author: Michael Krufky <mkrufky@linuxtv.org>
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*
*****************************************************************************/
#include <stdio.h>
#include <string>
#include "text.h"
const char * html_dump_epg_header_footer_callback(void *, bool header, bool channel)
{
//fprintf(stderr, "%s(%s, %s)\n", __func__, (header) ? "header" : "footer", (channel) ? "channel" : "body");
const char *str = NULL;
if (header)
if (channel)
str = "<tr>";
else
str = "<html><body><table border=1>";
else
if (channel)
str = "</tr>";
else
str = "</table></body></html>";
// fprintf(stderr, "%s", str);
return str;
}
const char * json_dump_epg_header_footer_callback(void *, bool header, bool channel)
{
//fprintf(stderr, "%s(%s, %s)\n", __func__, (header) ? "header" : "footer", (channel) ? "channel" : "body");
const char *str = NULL;
if (header)
if (channel)
str = "{\"Entries\":\n[";
else
str = "[";
else
if (channel)
str = "]}";
else
str = "]";
// fprintf(stderr, "%s", str);
return str;
}
const char * html_dump_epg_event_callback(void * context,
const char * channel_name,
uint16_t chan_major,
uint16_t chan_minor,
//
uint16_t event_id,
time_t start_time,
uint32_t length_sec,
const char * name,
const char * text)
{
//fprintf(stderr, "%s()\n", __func__);
std::string str;
str.clear();
str.append("<td>");
//str.append("channel: ");
if (channel_name) {
char chan_nbr[12] = { 0 };
snprintf(chan_nbr, sizeof(chan_nbr), "%d.%d: ", chan_major, chan_minor);
str.append("<nobr>");
str.append(chan_nbr);
str.append(channel_name);
str.append("</nobr>");
}
//str.append("show: ");
if (name) {
time_t end_time = start_time + length_sec;
struct tm tms = *localtime( &start_time );
struct tm tme = *localtime( &end_time );
char time_str[14] = { 0 };
str.append(name);
snprintf(time_str, sizeof(time_str), "%02d:%02d - %02d:%02d", tms.tm_hour, tms.tm_min, tme.tm_hour, tme.tm_min);
str.append("<hr><nobr>");
str.append(time_str);
str.append("</nobr>");
}
str.append("</td>");
// fprintf(stderr, "%s", str.c_str());
return str.c_str();
}
const char * json_dump_epg_event_callback(void * context,
const char * channel_name,
uint16_t chan_major,
uint16_t chan_minor,
//
uint16_t event_id,
time_t start_time,
uint32_t length_sec,
const char * name,
const char * text)
{
time_t end_time = start_time + length_sec;
char time_str[15] = { 0 };
//fprintf(stderr, "%s()\n", __func__);
std::string str;
str.clear();
str.append("{");
str.append("\"StartTime\":");
#if 1
snprintf(time_str, sizeof(time_str), "%lld", (long long int)start_time);
str.append(time_str);
#else
str.append(ctime(&start_time));
#endif
str.append(",");
str.append("\"EndTime\":");
#if 1
snprintf(time_str, sizeof(time_str), "%lld", (long long int)end_time); // "%jd", (intmax_t)end_time);
str.append(time_str);
#else
str.append(ctime(&end_time));
#endif
str.append(",");
str.append("\"Title\":\"");
str.append(name);
str.append("\",");
str.append("\"ShortDescription\":\"");
//str.append(text);
str.append("\"");
str.append("}");
// fprintf(stderr, "%s", str.c_str());
return str.c_str();
}
const char * html_dump_channels(void *context,
uint16_t lcn, uint16_t major, uint16_t minor,
uint16_t physical_channel, uint32_t freq, const char *modulation,
unsigned char *service_name, uint16_t vpid, uint16_t apid, uint16_t program_number)
{
std::string str;
str.clear();
char channelno[7]; /* XXX.XXX */
if (major + minor > 1)
sprintf(channelno, "%d.%d", major, minor);
else if (lcn)
sprintf(channelno, "%d", lcn);
else
sprintf(channelno, "%d", physical_channel);
fprintf(stdout, "%s-%s:%d:%s:%d:%d:%d\n",
channelno,
service_name,
freq,//iter_vct->second.carrier_freq,
modulation,
vpid, apid, program_number);
char phy_chan[4] = { 0 };
char svc_id[6] = { 0 };
sprintf(phy_chan, "%d", physical_channel);
sprintf(svc_id, "%d", program_number);
str.append("<table>");
str.append("<tr>");
str.append("<td>");
str.append("<a href='/tune=");
str.append(phy_chan);
str.append("+");
str.append(svc_id);
str.append("&channels'>");
str.append(channelno);
str.append(": ");
str.append((const char *)service_name);
str.append("</a>");
#if 0
str.append("</td>");
str.append("</tr>");
str.append("<tr>");
str.append("<td>");
str.append("<hr>");
#endif
str.append("</td>");
str.append("</tr>");
str.append("</table>");
return str.c_str();
}
const char * json_dump_channels(void *context,
uint16_t lcn, uint16_t major, uint16_t minor,
uint16_t physical_channel, uint32_t freq, const char *modulation,
unsigned char *service_name, uint16_t vpid, uint16_t apid, uint16_t program_number)
{
std::string str;
str.clear();
char channelno[7] = { 0 }; /* XXX.XXX */
char chan_major[3] = { 0 };
char chan_minor[3] = { 0 };
if (major + minor > 1) {
sprintf(channelno, "%d.%d", major, minor);
sprintf(chan_major, "%d", major);
sprintf(chan_minor, "%d", minor);
} else if (lcn) {
sprintf(channelno, "%d", lcn);
sprintf(chan_major, "%d", lcn);
sprintf(chan_minor, "%d", 0);
} else {
sprintf(channelno, "%d", physical_channel);
sprintf(chan_major, "%d", physical_channel);
sprintf(chan_minor, "%d", program_number);
}
fprintf(stdout, "%s-%s:%d:%s:%d:%d:%d\n",
channelno,
service_name,
freq,//iter_vct->second.carrier_freq,
modulation,
vpid, apid, program_number);
char phy_chan[4] = { 0 };
char svc_id[6] = { 0 };
sprintf(phy_chan, "%d", physical_channel);
sprintf(svc_id, "%d", program_number);
str.append("{");
str.append("\"Id\":\"");
str.append("tune");
str.append("&channel=");
str.append(phy_chan);
str.append("&service=");
str.append(svc_id);
str.append("\"");
str.append(",");
str.append("\"DisplayName\":\"");
str.append((const char *)service_name);
str.append("\"");
str.append(",");
str.append("\"MajorChannelNo\":\"");
str.append(chan_major);
str.append("\"");
str.append(",");
str.append("\"MinorChannelNo\":\"");
str.append(chan_minor);
str.append("\"");
str.append("}");
str.append(",");
return str.c_str();
}
const char * html_playing_video(void *)
{
std::string str;
str.clear();
str.append("<html><body>");
// str.append("<video height=\"1280\" width=\"720\" controls>");
str.append("<div style=\"position:relative;width:604px;height:256px;float:center;\">");
str.append("<video controls=\"controls\" autoplay=\"autoplay\" poster=\"http://easyhtml5video.com/images/happyfit2.jpg\" width=\"604\" height=\"256\" onclick=\"if(/Android/.test(navigator.userAgent))this.play();\">");
// str.append("<video controls>");
str.append("<source src=\"/stream/\"");
str.append(" type='video/mp2ts");
str.append("; codecs=\"ac-3\"");
str.append("'>");
str.append("<source src=\"http://easyhtml5video.com/images/happyfit2.mp4\" type=\"video/mp4\">");
str.append("</video>");
str.append("</div>");
str.append("</body></html>");
return str.c_str();
}
<|endoftext|> |
<commit_before>/****************************************************************************
**
** Copyright (C) 2013 Digia Plc and/or its subsidiary(-ies).
** Contact: http://www.qt-project.org/legal
**
** This file is part of Qt Creator.
**
** Commercial License Usage
** Licensees holding valid commercial Qt licenses may use this file in
** accordance with the commercial license agreement provided with the
** Software or, alternatively, in accordance with the terms contained in
** a written agreement between you and Digia. For licensing terms and
** conditions see http://qt.digia.com/licensing. For further information
** use the contact form at http://qt.digia.com/contact-us.
**
** GNU Lesser General Public License Usage
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 as published by the Free Software
** Foundation and appearing in the file LICENSE.LGPL included in the
** packaging of this file. Please review the following information to
** ensure the GNU Lesser General Public License version 2.1 requirements
** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, Digia gives you certain additional
** rights. These rights are described in the Digia Qt LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
****************************************************************************/
#include "qbsinstallstep.h"
#include "qbsbuildconfiguration.h"
#include "qbsproject.h"
#include "qbsprojectmanagerconstants.h"
#include "ui_qbsinstallstepconfigwidget.h"
#include <projectexplorer/buildsteplist.h>
#include <projectexplorer/deployconfiguration.h>
#include <projectexplorer/kit.h>
#include <projectexplorer/projectexplorerconstants.h>
#include <projectexplorer/target.h>
#include <utils/qtcassert.h>
#include <QFileInfo>
// --------------------------------------------------------------------
// Constants:
// --------------------------------------------------------------------
static const char QBS_INSTALL_ROOT[] = "Qbs.InstallRoot";
static const char QBS_REMOVE_FIRST[] = "Qbs.RemoveFirst";
static const char QBS_DRY_RUN[] = "Qbs.DryRun";
static const char QBS_KEEP_GOING[] = "Qbs.DryKeepGoing";
namespace QbsProjectManager {
namespace Internal {
// --------------------------------------------------------------------
// QbsInstallStep:
// --------------------------------------------------------------------
QbsInstallStep::QbsInstallStep(ProjectExplorer::BuildStepList *bsl) :
ProjectExplorer::BuildStep(bsl, Core::Id(Constants::QBS_INSTALLSTEP_ID)),
m_job(0), m_showCompilerOutput(true), m_parser(0)
{
setDisplayName(tr("Qbs Install"));
}
QbsInstallStep::QbsInstallStep(ProjectExplorer::BuildStepList *bsl, const QbsInstallStep *other) :
ProjectExplorer::BuildStep(bsl, Core::Id(Constants::QBS_INSTALLSTEP_ID)),
m_qbsInstallOptions(other->m_qbsInstallOptions), m_job(0),
m_showCompilerOutput(other->m_showCompilerOutput), m_parser(0)
{ }
QbsInstallStep::~QbsInstallStep()
{
cancel();
if (m_job)
m_job->deleteLater();
m_job = 0;
}
bool QbsInstallStep::init()
{
QTC_ASSERT(!static_cast<QbsProject *>(project())->isParsing() && !m_job, return false);
return true;
}
void QbsInstallStep::run(QFutureInterface<bool> &fi)
{
m_fi = &fi;
QbsProject *pro = static_cast<QbsProject *>(project());
m_job = pro->install(m_qbsInstallOptions);
if (!m_job) {
m_fi->reportResult(false);
return;
}
m_progressBase = 0;
connect(m_job, SIGNAL(finished(bool,qbs::AbstractJob*)), this, SLOT(installDone(bool)));
connect(m_job, SIGNAL(taskStarted(QString,int,qbs::AbstractJob*)),
this, SLOT(handleTaskStarted(QString,int)));
connect(m_job, SIGNAL(taskProgress(int,qbs::AbstractJob*)),
this, SLOT(handleProgress(int)));
}
ProjectExplorer::BuildStepConfigWidget *QbsInstallStep::createConfigWidget()
{
return new QbsInstallStepConfigWidget(this);
}
bool QbsInstallStep::runInGuiThread() const
{
return true;
}
void QbsInstallStep::cancel()
{
if (m_job)
m_job->cancel();
}
QString QbsInstallStep::installRoot() const
{
if (!m_qbsInstallOptions.installRoot().isEmpty())
return m_qbsInstallOptions.installRoot();
return qbs::InstallOptions::defaultInstallRoot();
}
QString QbsInstallStep::absoluteInstallRoot() const
{
const qbs::ProjectData data = static_cast<QbsProject *>(project())->qbsProjectData();
QString path = installRoot();
if (data.isValid() && !data.buildDirectory().isEmpty() && !path.isEmpty())
path = QDir(data.buildDirectory()).absoluteFilePath(path);
return path;
}
bool QbsInstallStep::removeFirst() const
{
return m_qbsInstallOptions.removeExistingInstallation();
}
bool QbsInstallStep::dryRun() const
{
return m_qbsInstallOptions.dryRun();
}
bool QbsInstallStep::keepGoing() const
{
return m_qbsInstallOptions.keepGoing();
}
bool QbsInstallStep::fromMap(const QVariantMap &map)
{
if (!ProjectExplorer::BuildStep::fromMap(map))
return false;
setInstallRoot(map.value(QLatin1String(QBS_INSTALL_ROOT)).toString());
m_qbsInstallOptions.setRemoveExistingInstallation(map.value(QLatin1String(QBS_REMOVE_FIRST), false).toBool());
m_qbsInstallOptions.setDryRun(map.value(QLatin1String(QBS_DRY_RUN), false).toBool());
m_qbsInstallOptions.setKeepGoing(map.value(QLatin1String(QBS_KEEP_GOING), false).toBool());
return true;
}
QVariantMap QbsInstallStep::toMap() const
{
QVariantMap map = ProjectExplorer::BuildStep::toMap();
map.insert(QLatin1String(QBS_INSTALL_ROOT), m_qbsInstallOptions.installRoot());
map.insert(QLatin1String(QBS_REMOVE_FIRST), m_qbsInstallOptions.removeExistingInstallation());
map.insert(QLatin1String(QBS_DRY_RUN), m_qbsInstallOptions.dryRun());
map.insert(QLatin1String(QBS_KEEP_GOING), m_qbsInstallOptions.keepGoing());
return map;
}
qbs::InstallOptions QbsInstallStep::installOptions() const
{
return m_qbsInstallOptions;
}
void QbsInstallStep::installDone(bool success)
{
// Report errors:
foreach (const qbs::ErrorItem &item, m_job->error().items()) {
createTaskAndOutput(ProjectExplorer::Task::Error, item.description(),
item.codeLocation().fileName(), item.codeLocation().line());
}
QTC_ASSERT(m_fi, return);
m_fi->reportResult(success);
m_fi = 0; // do not delete, it is not ours
m_job->deleteLater();
m_job = 0;
emit finished();
}
void QbsInstallStep::handleTaskStarted(const QString &desciption, int max)
{
Q_UNUSED(desciption);
QTC_ASSERT(m_fi, return);
m_progressBase = m_fi->progressValue();
m_fi->setProgressRange(0, m_progressBase + max);
}
void QbsInstallStep::handleProgress(int value)
{
QTC_ASSERT(m_fi, return);
m_fi->setProgressValue(m_progressBase + value);
}
void QbsInstallStep::createTaskAndOutput(ProjectExplorer::Task::TaskType type,
const QString &message, const QString &file, int line)
{
emit addTask(ProjectExplorer::Task(type, message,
Utils::FileName::fromString(file), line,
ProjectExplorer::Constants::TASK_CATEGORY_COMPILE));
emit addOutput(message, NormalOutput);
}
void QbsInstallStep::setInstallRoot(const QString &ir)
{
if (m_qbsInstallOptions.installRoot() == ir)
return;
m_qbsInstallOptions.installRoot() = ir;
emit changed();
}
void QbsInstallStep::setRemoveFirst(bool rf)
{
if (m_qbsInstallOptions.removeExistingInstallation() == rf)
return;
m_qbsInstallOptions.setRemoveExistingInstallation(rf);
emit changed();
}
void QbsInstallStep::setDryRun(bool dr)
{
if (m_qbsInstallOptions.dryRun() == dr)
return;
m_qbsInstallOptions.setDryRun(dr);
emit changed();
}
void QbsInstallStep::setKeepGoing(bool kg)
{
if (m_qbsInstallOptions.keepGoing() == kg)
return;
m_qbsInstallOptions.setKeepGoing(kg);
emit changed();
}
// --------------------------------------------------------------------
// QbsInstallStepConfigWidget:
// --------------------------------------------------------------------
QbsInstallStepConfigWidget::QbsInstallStepConfigWidget(QbsInstallStep *step) :
m_step(step), m_ignoreChange(false)
{
connect(m_step, SIGNAL(displayNameChanged()), this, SLOT(updateState()));
connect(m_step, SIGNAL(changed()), this, SLOT(updateState()));
setContentsMargins(0, 0, 0, 0);
QbsProject *project = static_cast<QbsProject *>(m_step->project());
m_ui = new Ui::QbsInstallStepConfigWidget;
m_ui->setupUi(this);
m_ui->installRootChooser->setPromptDialogTitle(tr("Qbs Install Prefix"));
m_ui->installRootChooser->setExpectedKind(Utils::PathChooser::Directory);
connect(m_ui->installRootChooser, SIGNAL(changed(QString)), this, SLOT(changeInstallRoot()));
connect(m_ui->removeFirstCheckBox, SIGNAL(toggled(bool)), this, SLOT(changeRemoveFirst(bool)));
connect(m_ui->dryRunCheckBox, SIGNAL(toggled(bool)), this, SLOT(changeDryRun(bool)));
connect(m_ui->keepGoingCheckBox, SIGNAL(toggled(bool)), this, SLOT(changeKeepGoing(bool)));
connect(project, SIGNAL(projectParsingDone(bool)), this, SLOT(updateState()));
updateState();
}
QString QbsInstallStepConfigWidget::summaryText() const
{
return m_summary;
}
QString QbsInstallStepConfigWidget::displayName() const
{
return m_step->displayName();
}
void QbsInstallStepConfigWidget::updateState()
{
if (!m_ignoreChange) {
m_ui->installRootChooser->setPath(m_step->installRoot());
m_ui->removeFirstCheckBox->setChecked(m_step->removeFirst());
m_ui->dryRunCheckBox->setChecked(m_step->dryRun());
m_ui->keepGoingCheckBox->setChecked(m_step->keepGoing());
}
const qbs::ProjectData data = static_cast<QbsProject *>(m_step->project())->qbsProjectData();
if (data.isValid())
m_ui->installRootChooser->setBaseDirectory(data.buildDirectory());
QString command = QLatin1String("qbs install ");
if (m_step->dryRun())
command += QLatin1String("--dry-run ");
if (m_step->keepGoing())
command += QLatin1String("--keep-going ");
if (m_step->removeFirst())
command += QLatin1String("--remove-first ");
command += QString::fromLatin1("--install-root \"%1\"").arg(m_step->absoluteInstallRoot());
QString summary = tr("<b>Qbs:</b> %1").arg(command);
if (m_summary != summary) {
m_summary = summary;
emit updateSummary();
}
}
void QbsInstallStepConfigWidget::changeInstallRoot()
{
const QString path = m_ui->installRootChooser->path();
if (m_step->installRoot() == path)
return;
m_ignoreChange = true;
m_step->setInstallRoot(path);
m_ignoreChange = false;
}
void QbsInstallStepConfigWidget::changeRemoveFirst(bool rf)
{
m_step->setRemoveFirst(rf);
}
void QbsInstallStepConfigWidget::changeDryRun(bool dr)
{
m_step->setDryRun(dr);
}
void QbsInstallStepConfigWidget::changeKeepGoing(bool kg)
{
m_step->setKeepGoing(kg);
}
// --------------------------------------------------------------------
// QbsInstallStepFactory:
// --------------------------------------------------------------------
QbsInstallStepFactory::QbsInstallStepFactory(QObject *parent) :
ProjectExplorer::IBuildStepFactory(parent)
{ }
QList<Core::Id> QbsInstallStepFactory::availableCreationIds(ProjectExplorer::BuildStepList *parent) const
{
if (parent->id() == ProjectExplorer::Constants::BUILDSTEPS_DEPLOY
&& qobject_cast<ProjectExplorer::DeployConfiguration *>(parent->parent())
&& qobject_cast<QbsProject *>(parent->target()->project()))
return QList<Core::Id>() << Core::Id(Constants::QBS_INSTALLSTEP_ID);
return QList<Core::Id>();
}
QString QbsInstallStepFactory::displayNameForId(const Core::Id id) const
{
if (id == Core::Id(Constants::QBS_INSTALLSTEP_ID))
return tr("Qbs Install");
return QString();
}
bool QbsInstallStepFactory::canCreate(ProjectExplorer::BuildStepList *parent, const Core::Id id) const
{
if (parent->id() != Core::Id(ProjectExplorer::Constants::BUILDSTEPS_DEPLOY)
|| !qobject_cast<ProjectExplorer::DeployConfiguration *>(parent->parent())
|| !qobject_cast<QbsProject *>(parent->target()->project()))
return false;
return id == Core::Id(Constants::QBS_INSTALLSTEP_ID);
}
ProjectExplorer::BuildStep *QbsInstallStepFactory::create(ProjectExplorer::BuildStepList *parent,
const Core::Id id)
{
if (!canCreate(parent, id))
return 0;
return new QbsInstallStep(parent);
}
bool QbsInstallStepFactory::canRestore(ProjectExplorer::BuildStepList *parent, const QVariantMap &map) const
{
return canCreate(parent, ProjectExplorer::idFromMap(map));
}
ProjectExplorer::BuildStep *QbsInstallStepFactory::restore(ProjectExplorer::BuildStepList *parent,
const QVariantMap &map)
{
if (!canRestore(parent, map))
return 0;
QbsInstallStep *bs = new QbsInstallStep(parent);
if (!bs->fromMap(map)) {
delete bs;
return 0;
}
return bs;
}
bool QbsInstallStepFactory::canClone(ProjectExplorer::BuildStepList *parent,
ProjectExplorer::BuildStep *product) const
{
return canCreate(parent, product->id());
}
ProjectExplorer::BuildStep *QbsInstallStepFactory::clone(ProjectExplorer::BuildStepList *parent,
ProjectExplorer::BuildStep *product)
{
if (!canClone(parent, product))
return 0;
return new QbsInstallStep(parent, static_cast<QbsInstallStep *>(product));
}
} // namespace Internal
} // namespace QbsProjectManager
<commit_msg>Qbs: Fix qbs install step<commit_after>/****************************************************************************
**
** Copyright (C) 2013 Digia Plc and/or its subsidiary(-ies).
** Contact: http://www.qt-project.org/legal
**
** This file is part of Qt Creator.
**
** Commercial License Usage
** Licensees holding valid commercial Qt licenses may use this file in
** accordance with the commercial license agreement provided with the
** Software or, alternatively, in accordance with the terms contained in
** a written agreement between you and Digia. For licensing terms and
** conditions see http://qt.digia.com/licensing. For further information
** use the contact form at http://qt.digia.com/contact-us.
**
** GNU Lesser General Public License Usage
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 as published by the Free Software
** Foundation and appearing in the file LICENSE.LGPL included in the
** packaging of this file. Please review the following information to
** ensure the GNU Lesser General Public License version 2.1 requirements
** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, Digia gives you certain additional
** rights. These rights are described in the Digia Qt LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
****************************************************************************/
#include "qbsinstallstep.h"
#include "qbsbuildconfiguration.h"
#include "qbsproject.h"
#include "qbsprojectmanagerconstants.h"
#include "ui_qbsinstallstepconfigwidget.h"
#include <projectexplorer/buildsteplist.h>
#include <projectexplorer/deployconfiguration.h>
#include <projectexplorer/kit.h>
#include <projectexplorer/projectexplorerconstants.h>
#include <projectexplorer/target.h>
#include <utils/qtcassert.h>
#include <QFileInfo>
// --------------------------------------------------------------------
// Constants:
// --------------------------------------------------------------------
static const char QBS_INSTALL_ROOT[] = "Qbs.InstallRoot";
static const char QBS_REMOVE_FIRST[] = "Qbs.RemoveFirst";
static const char QBS_DRY_RUN[] = "Qbs.DryRun";
static const char QBS_KEEP_GOING[] = "Qbs.DryKeepGoing";
namespace QbsProjectManager {
namespace Internal {
// --------------------------------------------------------------------
// QbsInstallStep:
// --------------------------------------------------------------------
QbsInstallStep::QbsInstallStep(ProjectExplorer::BuildStepList *bsl) :
ProjectExplorer::BuildStep(bsl, Core::Id(Constants::QBS_INSTALLSTEP_ID)),
m_job(0), m_showCompilerOutput(true), m_parser(0)
{
setDisplayName(tr("Qbs Install"));
}
QbsInstallStep::QbsInstallStep(ProjectExplorer::BuildStepList *bsl, const QbsInstallStep *other) :
ProjectExplorer::BuildStep(bsl, Core::Id(Constants::QBS_INSTALLSTEP_ID)),
m_qbsInstallOptions(other->m_qbsInstallOptions), m_job(0),
m_showCompilerOutput(other->m_showCompilerOutput), m_parser(0)
{ }
QbsInstallStep::~QbsInstallStep()
{
cancel();
if (m_job)
m_job->deleteLater();
m_job = 0;
}
bool QbsInstallStep::init()
{
QTC_ASSERT(!static_cast<QbsProject *>(project())->isParsing() && !m_job, return false);
return true;
}
void QbsInstallStep::run(QFutureInterface<bool> &fi)
{
m_fi = &fi;
QbsProject *pro = static_cast<QbsProject *>(project());
m_job = pro->install(m_qbsInstallOptions);
if (!m_job) {
m_fi->reportResult(false);
return;
}
m_progressBase = 0;
connect(m_job, SIGNAL(finished(bool,qbs::AbstractJob*)), this, SLOT(installDone(bool)));
connect(m_job, SIGNAL(taskStarted(QString,int,qbs::AbstractJob*)),
this, SLOT(handleTaskStarted(QString,int)));
connect(m_job, SIGNAL(taskProgress(int,qbs::AbstractJob*)),
this, SLOT(handleProgress(int)));
}
ProjectExplorer::BuildStepConfigWidget *QbsInstallStep::createConfigWidget()
{
return new QbsInstallStepConfigWidget(this);
}
bool QbsInstallStep::runInGuiThread() const
{
return true;
}
void QbsInstallStep::cancel()
{
if (m_job)
m_job->cancel();
}
QString QbsInstallStep::installRoot() const
{
if (!m_qbsInstallOptions.installRoot().isEmpty())
return m_qbsInstallOptions.installRoot();
return qbs::InstallOptions::defaultInstallRoot();
}
QString QbsInstallStep::absoluteInstallRoot() const
{
const qbs::ProjectData data = static_cast<QbsProject *>(project())->qbsProjectData();
QString path = installRoot();
if (data.isValid() && !data.buildDirectory().isEmpty() && !path.isEmpty())
path = QDir(data.buildDirectory()).absoluteFilePath(path);
return path;
}
bool QbsInstallStep::removeFirst() const
{
return m_qbsInstallOptions.removeExistingInstallation();
}
bool QbsInstallStep::dryRun() const
{
return m_qbsInstallOptions.dryRun();
}
bool QbsInstallStep::keepGoing() const
{
return m_qbsInstallOptions.keepGoing();
}
bool QbsInstallStep::fromMap(const QVariantMap &map)
{
if (!ProjectExplorer::BuildStep::fromMap(map))
return false;
setInstallRoot(map.value(QLatin1String(QBS_INSTALL_ROOT)).toString());
m_qbsInstallOptions.setRemoveExistingInstallation(map.value(QLatin1String(QBS_REMOVE_FIRST), false).toBool());
m_qbsInstallOptions.setDryRun(map.value(QLatin1String(QBS_DRY_RUN), false).toBool());
m_qbsInstallOptions.setKeepGoing(map.value(QLatin1String(QBS_KEEP_GOING), false).toBool());
return true;
}
QVariantMap QbsInstallStep::toMap() const
{
QVariantMap map = ProjectExplorer::BuildStep::toMap();
map.insert(QLatin1String(QBS_INSTALL_ROOT), m_qbsInstallOptions.installRoot());
map.insert(QLatin1String(QBS_REMOVE_FIRST), m_qbsInstallOptions.removeExistingInstallation());
map.insert(QLatin1String(QBS_DRY_RUN), m_qbsInstallOptions.dryRun());
map.insert(QLatin1String(QBS_KEEP_GOING), m_qbsInstallOptions.keepGoing());
return map;
}
qbs::InstallOptions QbsInstallStep::installOptions() const
{
return m_qbsInstallOptions;
}
void QbsInstallStep::installDone(bool success)
{
// Report errors:
foreach (const qbs::ErrorItem &item, m_job->error().items()) {
createTaskAndOutput(ProjectExplorer::Task::Error, item.description(),
item.codeLocation().fileName(), item.codeLocation().line());
}
QTC_ASSERT(m_fi, return);
m_fi->reportResult(success);
m_fi = 0; // do not delete, it is not ours
m_job->deleteLater();
m_job = 0;
emit finished();
}
void QbsInstallStep::handleTaskStarted(const QString &desciption, int max)
{
Q_UNUSED(desciption);
QTC_ASSERT(m_fi, return);
m_progressBase = m_fi->progressValue();
m_fi->setProgressRange(0, m_progressBase + max);
}
void QbsInstallStep::handleProgress(int value)
{
QTC_ASSERT(m_fi, return);
m_fi->setProgressValue(m_progressBase + value);
}
void QbsInstallStep::createTaskAndOutput(ProjectExplorer::Task::TaskType type,
const QString &message, const QString &file, int line)
{
emit addTask(ProjectExplorer::Task(type, message,
Utils::FileName::fromString(file), line,
ProjectExplorer::Constants::TASK_CATEGORY_COMPILE));
emit addOutput(message, NormalOutput);
}
void QbsInstallStep::setInstallRoot(const QString &ir)
{
if (m_qbsInstallOptions.installRoot() == ir)
return;
m_qbsInstallOptions.setInstallRoot(ir);
emit changed();
}
void QbsInstallStep::setRemoveFirst(bool rf)
{
if (m_qbsInstallOptions.removeExistingInstallation() == rf)
return;
m_qbsInstallOptions.setRemoveExistingInstallation(rf);
emit changed();
}
void QbsInstallStep::setDryRun(bool dr)
{
if (m_qbsInstallOptions.dryRun() == dr)
return;
m_qbsInstallOptions.setDryRun(dr);
emit changed();
}
void QbsInstallStep::setKeepGoing(bool kg)
{
if (m_qbsInstallOptions.keepGoing() == kg)
return;
m_qbsInstallOptions.setKeepGoing(kg);
emit changed();
}
// --------------------------------------------------------------------
// QbsInstallStepConfigWidget:
// --------------------------------------------------------------------
QbsInstallStepConfigWidget::QbsInstallStepConfigWidget(QbsInstallStep *step) :
m_step(step), m_ignoreChange(false)
{
connect(m_step, SIGNAL(displayNameChanged()), this, SLOT(updateState()));
connect(m_step, SIGNAL(changed()), this, SLOT(updateState()));
setContentsMargins(0, 0, 0, 0);
QbsProject *project = static_cast<QbsProject *>(m_step->project());
m_ui = new Ui::QbsInstallStepConfigWidget;
m_ui->setupUi(this);
m_ui->installRootChooser->setPromptDialogTitle(tr("Qbs Install Prefix"));
m_ui->installRootChooser->setExpectedKind(Utils::PathChooser::Directory);
connect(m_ui->installRootChooser, SIGNAL(changed(QString)), this, SLOT(changeInstallRoot()));
connect(m_ui->removeFirstCheckBox, SIGNAL(toggled(bool)), this, SLOT(changeRemoveFirst(bool)));
connect(m_ui->dryRunCheckBox, SIGNAL(toggled(bool)), this, SLOT(changeDryRun(bool)));
connect(m_ui->keepGoingCheckBox, SIGNAL(toggled(bool)), this, SLOT(changeKeepGoing(bool)));
connect(project, SIGNAL(projectParsingDone(bool)), this, SLOT(updateState()));
updateState();
}
QString QbsInstallStepConfigWidget::summaryText() const
{
return m_summary;
}
QString QbsInstallStepConfigWidget::displayName() const
{
return m_step->displayName();
}
void QbsInstallStepConfigWidget::updateState()
{
if (!m_ignoreChange) {
m_ui->installRootChooser->setPath(m_step->installRoot());
m_ui->removeFirstCheckBox->setChecked(m_step->removeFirst());
m_ui->dryRunCheckBox->setChecked(m_step->dryRun());
m_ui->keepGoingCheckBox->setChecked(m_step->keepGoing());
}
const qbs::ProjectData data = static_cast<QbsProject *>(m_step->project())->qbsProjectData();
if (data.isValid())
m_ui->installRootChooser->setBaseDirectory(data.buildDirectory());
QString command = QLatin1String("qbs install ");
if (m_step->dryRun())
command += QLatin1String("--dry-run ");
if (m_step->keepGoing())
command += QLatin1String("--keep-going ");
if (m_step->removeFirst())
command += QLatin1String("--remove-first ");
command += QString::fromLatin1("--install-root \"%1\"").arg(m_step->absoluteInstallRoot());
QString summary = tr("<b>Qbs:</b> %1").arg(command);
if (m_summary != summary) {
m_summary = summary;
emit updateSummary();
}
}
void QbsInstallStepConfigWidget::changeInstallRoot()
{
const QString path = m_ui->installRootChooser->path();
if (m_step->installRoot() == path)
return;
m_ignoreChange = true;
m_step->setInstallRoot(path);
m_ignoreChange = false;
}
void QbsInstallStepConfigWidget::changeRemoveFirst(bool rf)
{
m_step->setRemoveFirst(rf);
}
void QbsInstallStepConfigWidget::changeDryRun(bool dr)
{
m_step->setDryRun(dr);
}
void QbsInstallStepConfigWidget::changeKeepGoing(bool kg)
{
m_step->setKeepGoing(kg);
}
// --------------------------------------------------------------------
// QbsInstallStepFactory:
// --------------------------------------------------------------------
QbsInstallStepFactory::QbsInstallStepFactory(QObject *parent) :
ProjectExplorer::IBuildStepFactory(parent)
{ }
QList<Core::Id> QbsInstallStepFactory::availableCreationIds(ProjectExplorer::BuildStepList *parent) const
{
if (parent->id() == ProjectExplorer::Constants::BUILDSTEPS_DEPLOY
&& qobject_cast<ProjectExplorer::DeployConfiguration *>(parent->parent())
&& qobject_cast<QbsProject *>(parent->target()->project()))
return QList<Core::Id>() << Core::Id(Constants::QBS_INSTALLSTEP_ID);
return QList<Core::Id>();
}
QString QbsInstallStepFactory::displayNameForId(const Core::Id id) const
{
if (id == Core::Id(Constants::QBS_INSTALLSTEP_ID))
return tr("Qbs Install");
return QString();
}
bool QbsInstallStepFactory::canCreate(ProjectExplorer::BuildStepList *parent, const Core::Id id) const
{
if (parent->id() != Core::Id(ProjectExplorer::Constants::BUILDSTEPS_DEPLOY)
|| !qobject_cast<ProjectExplorer::DeployConfiguration *>(parent->parent())
|| !qobject_cast<QbsProject *>(parent->target()->project()))
return false;
return id == Core::Id(Constants::QBS_INSTALLSTEP_ID);
}
ProjectExplorer::BuildStep *QbsInstallStepFactory::create(ProjectExplorer::BuildStepList *parent,
const Core::Id id)
{
if (!canCreate(parent, id))
return 0;
return new QbsInstallStep(parent);
}
bool QbsInstallStepFactory::canRestore(ProjectExplorer::BuildStepList *parent, const QVariantMap &map) const
{
return canCreate(parent, ProjectExplorer::idFromMap(map));
}
ProjectExplorer::BuildStep *QbsInstallStepFactory::restore(ProjectExplorer::BuildStepList *parent,
const QVariantMap &map)
{
if (!canRestore(parent, map))
return 0;
QbsInstallStep *bs = new QbsInstallStep(parent);
if (!bs->fromMap(map)) {
delete bs;
return 0;
}
return bs;
}
bool QbsInstallStepFactory::canClone(ProjectExplorer::BuildStepList *parent,
ProjectExplorer::BuildStep *product) const
{
return canCreate(parent, product->id());
}
ProjectExplorer::BuildStep *QbsInstallStepFactory::clone(ProjectExplorer::BuildStepList *parent,
ProjectExplorer::BuildStep *product)
{
if (!canClone(parent, product))
return 0;
return new QbsInstallStep(parent, static_cast<QbsInstallStep *>(product));
}
} // namespace Internal
} // namespace QbsProjectManager
<|endoftext|> |
<commit_before>/*
* Copyright (c) 2011 The Native Client 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 "native_client/src/shared/ppapi_proxy/plugin_ppb_graphics_3d.h"
#include "gpu/command_buffer/client/gles2_implementation.h"
#include "native_client/src/shared/ppapi_proxy/command_buffer_nacl.h"
#include "native_client/src/shared/ppapi_proxy/object_serialize.h"
#include "native_client/src/shared/ppapi_proxy/plugin_callback.h"
#include "native_client/src/shared/ppapi_proxy/plugin_globals.h"
#include "native_client/src/shared/ppapi_proxy/plugin_instance_data.h"
#include "native_client/src/shared/ppapi_proxy/plugin_ppb_core.h"
#include "native_client/src/shared/ppapi_proxy/plugin_ppb_var.h"
#include "native_client/src/shared/ppapi_proxy/utility.h"
#include "native_client/src/shared/srpc/nacl_srpc.h"
#include "native_client/src/third_party/ppapi/c/pp_completion_callback.h"
#include "native_client/src/third_party/ppapi/c/pp_errors.h"
#include "native_client/src/third_party/ppapi/c/pp_rect.h"
#include "native_client/src/third_party/ppapi/c/pp_var.h"
#include "srpcgen/ppb_rpc.h"
namespace ppapi_proxy {
namespace {
const int32 kTransferBufferSize = 512 * 1024;
int32_t GetNumAttribs(const int32_t* attrib_list) {
int32_t num = 0;
if (attrib_list) {
// skip over attrib pairs
while (attrib_list[num] != PP_GRAPHICS3DATTRIB_NONE)
num += 2;
// Add one more for PP_GRAPHICS3DATTRIB_NONE.
num += 1;
}
return num;
}
PP_Resource Create(PP_Instance instance,
PP_Resource share_context,
const int32_t* attrib_list) {
DebugPrintf("PPB_Graphics3D::Create: instance=%"NACL_PRIu32"\n", instance);
PP_Resource graphics3d_id = kInvalidResourceId;
nacl_abi_size_t num_attribs = GetNumAttribs(attrib_list);
NaClSrpcError retval =
PpbGraphics3DRpcClient::PPB_Graphics3DTrusted_CreateRaw(
GetMainSrpcChannel(),
instance,
share_context,
num_attribs, const_cast<int32_t *>(attrib_list),
&graphics3d_id);
if (retval == NACL_SRPC_RESULT_OK) {
scoped_refptr<PluginGraphics3D> graphics_3d =
PluginResource::AdoptAs<PluginGraphics3D>(graphics3d_id);
if (graphics_3d.get()) {
graphics_3d->set_instance_id(instance);
return graphics3d_id;
}
}
return kInvalidResourceId;
}
PP_Bool IsGraphics3D(PP_Resource resource) {
DebugPrintf("PPB_Graphics3D::IsGraphics3D: resource=%"NACL_PRIu32"\n",
resource);
return PluginResource::GetAs<PluginGraphics3D>(resource).get()
? PP_TRUE : PP_FALSE;
}
int32_t GetAttribs(PP_Resource graphics3d_id,
int32_t* attrib_list) {
int32_t pp_error;
nacl_abi_size_t num_attribs = GetNumAttribs(attrib_list);
NaClSrpcError retval =
PpbGraphics3DRpcClient::PPB_Graphics3D_GetAttribs(
GetMainSrpcChannel(),
graphics3d_id,
num_attribs, attrib_list,
&num_attribs, attrib_list,
&pp_error);
if (retval != NACL_SRPC_RESULT_OK) {
return PP_ERROR_BADARGUMENT;
}
return pp_error;
}
int32_t SetAttribs(PP_Resource graphics3d_id,
int32_t* attrib_list) {
int32_t pp_error;
nacl_abi_size_t num_attribs = GetNumAttribs(attrib_list);
NaClSrpcError retval =
PpbGraphics3DRpcClient::PPB_Graphics3D_SetAttribs(
GetMainSrpcChannel(),
graphics3d_id,
num_attribs, attrib_list,
&pp_error);
if (retval != NACL_SRPC_RESULT_OK) {
return PP_ERROR_BADARGUMENT;
}
return pp_error;
}
int32_t ResizeBuffers(PP_Resource graphics3d_id,
int32_t width,
int32_t height) {
int32_t pp_error;
NaClSrpcError retval =
PpbGraphics3DRpcClient::PPB_Graphics3D_ResizeBuffers(
GetMainSrpcChannel(),
graphics3d_id,
width,
height,
&pp_error);
if (retval != NACL_SRPC_RESULT_OK) {
return PP_ERROR_BADARGUMENT;
}
return pp_error;
}
int32_t SwapBuffs(PP_Resource graphics3d_id,
struct PP_CompletionCallback callback) {
DebugPrintf("PPB_Graphics3D::SwapBuffers: graphics3d_id=%"NACL_PRIu32"\n",
graphics3d_id);
scoped_refptr<PluginGraphics3D> graphics3d =
PluginResource::GetAs<PluginGraphics3D>(graphics3d_id).get();
if (!graphics3d.get())
return MayForceCallback(callback, PP_ERROR_BADRESOURCE);
return MayForceCallback(callback,
graphics3d->SwapBuffers(graphics3d_id, callback));
}
} // namespace
__thread PP_Resource PluginGraphics3D::cached_graphics3d_id = 0;
__thread gpu::gles2::GLES2Implementation*
PluginGraphics3D::cached_implementation = NULL;
PluginGraphics3D::PluginGraphics3D() : instance_id_(0) { }
PluginGraphics3D::~PluginGraphics3D() {
// Invalidate the cache.
cached_graphics3d_id = 0;
cached_implementation = NULL;
}
// static
gpu::gles2::GLES2Implementation* PluginGraphics3D::implFromResourceSlow(
PP_Resource graphics3d_id) {
DebugPrintf("PluginGraphics3D::implFromResourceSlow: "
"resource=%"NACL_PRIu32"\n", graphics3d_id);
// For performance reasons, we don't error-check the context, but crash on
// NULL instead.
gpu::gles2::GLES2Implementation* impl =
PluginResource::GetAs<PluginGraphics3D>(graphics3d_id)->impl();
cached_graphics3d_id = graphics3d_id;
cached_implementation = impl;
return impl;
}
bool PluginGraphics3D::InitFromBrowserResource(PP_Resource res) {
DebugPrintf("PluginGraphics3D::InitFromBrowserResource: "
"resource=%"NACL_PRIu32"\n", res);
// Create and initialize the objects required to issue GLES2 calls.
command_buffer_.reset(new CommandBufferNacl(res, PluginCore::GetInterface()));
command_buffer_->Initialize(kTransferBufferSize);
gles2_helper_.reset(new gpu::gles2::GLES2CmdHelper(command_buffer_.get()));
gpu::Buffer buffer = command_buffer_->GetRingBuffer();
if (gles2_helper_->Initialize(buffer.size)) {
// Request id -1 to signify 'don't care'
int32 transfer_buffer_id =
command_buffer_->CreateTransferBuffer(kTransferBufferSize, -1);
gpu::Buffer transfer_buffer =
command_buffer_->GetTransferBuffer(transfer_buffer_id);
if (transfer_buffer.ptr) {
gles2_implementation_.reset(new gpu::gles2::GLES2Implementation(
gles2_helper_.get(),
transfer_buffer.size,
transfer_buffer.ptr,
transfer_buffer_id,
false));
return true;
}
}
return false;
}
int32_t PluginGraphics3D::SwapBuffers(PP_Resource graphics3d_id,
struct PP_CompletionCallback callback) {
int32_t callback_id = CompletionCallbackTable::Get()->AddCallback(callback);
if (callback_id == 0) // Just like Chrome, for now disallow blocking calls.
return PP_ERROR_BADARGUMENT;
int32_t pp_error;
NaClSrpcError retval =
PpbGraphics3DRpcClient::PPB_Graphics3D_SwapBuffers(
GetMainSrpcChannel(),
graphics3d_id,
callback_id,
&pp_error);
if (retval != NACL_SRPC_RESULT_OK)
return PP_ERROR_FAILED;
if ((PP_OK_COMPLETIONPENDING != pp_error) && (PP_OK != pp_error))
return pp_error;
impl()->SwapBuffers();
return PP_OK_COMPLETIONPENDING;
}
// static
const PPB_Graphics3D_Dev* PluginGraphics3D::GetInterface() {
static const PPB_Graphics3D_Dev intf = {
&Create,
&IsGraphics3D,
&GetAttribs,
&SetAttribs,
&ResizeBuffers,
&SwapBuffs,
};
return &intf;
}
} // namespace ppapi_proxy
<commit_msg>Increase size of ring & transfer buffers for increased framerates (use --show-fps-counter from chrome) BUG= http://code.google.com/p/chromium/issues/detail?id=93170 TEST= naclgfx benchmark provided by outside developer Review URL: http://codereview.chromium.org/7701006<commit_after>/*
* Copyright (c) 2011 The Native Client 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 "native_client/src/shared/ppapi_proxy/plugin_ppb_graphics_3d.h"
#include "gpu/command_buffer/client/gles2_implementation.h"
#include "native_client/src/shared/ppapi_proxy/command_buffer_nacl.h"
#include "native_client/src/shared/ppapi_proxy/object_serialize.h"
#include "native_client/src/shared/ppapi_proxy/plugin_callback.h"
#include "native_client/src/shared/ppapi_proxy/plugin_globals.h"
#include "native_client/src/shared/ppapi_proxy/plugin_instance_data.h"
#include "native_client/src/shared/ppapi_proxy/plugin_ppb_core.h"
#include "native_client/src/shared/ppapi_proxy/plugin_ppb_var.h"
#include "native_client/src/shared/ppapi_proxy/utility.h"
#include "native_client/src/shared/srpc/nacl_srpc.h"
#include "native_client/src/third_party/ppapi/c/pp_completion_callback.h"
#include "native_client/src/third_party/ppapi/c/pp_errors.h"
#include "native_client/src/third_party/ppapi/c/pp_rect.h"
#include "native_client/src/third_party/ppapi/c/pp_var.h"
#include "srpcgen/ppb_rpc.h"
namespace ppapi_proxy {
namespace {
const int32 kRingBufferSize = 4096 * 1024;
const int32 kTransferBufferSize = 4096 * 1024;
int32_t GetNumAttribs(const int32_t* attrib_list) {
int32_t num = 0;
if (attrib_list) {
// skip over attrib pairs
while (attrib_list[num] != PP_GRAPHICS3DATTRIB_NONE)
num += 2;
// Add one more for PP_GRAPHICS3DATTRIB_NONE.
num += 1;
}
return num;
}
PP_Resource Create(PP_Instance instance,
PP_Resource share_context,
const int32_t* attrib_list) {
DebugPrintf("PPB_Graphics3D::Create: instance=%"NACL_PRIu32"\n", instance);
PP_Resource graphics3d_id = kInvalidResourceId;
nacl_abi_size_t num_attribs = GetNumAttribs(attrib_list);
NaClSrpcError retval =
PpbGraphics3DRpcClient::PPB_Graphics3DTrusted_CreateRaw(
GetMainSrpcChannel(),
instance,
share_context,
num_attribs, const_cast<int32_t *>(attrib_list),
&graphics3d_id);
if (retval == NACL_SRPC_RESULT_OK) {
scoped_refptr<PluginGraphics3D> graphics_3d =
PluginResource::AdoptAs<PluginGraphics3D>(graphics3d_id);
if (graphics_3d.get()) {
graphics_3d->set_instance_id(instance);
return graphics3d_id;
}
}
return kInvalidResourceId;
}
PP_Bool IsGraphics3D(PP_Resource resource) {
DebugPrintf("PPB_Graphics3D::IsGraphics3D: resource=%"NACL_PRIu32"\n",
resource);
return PluginResource::GetAs<PluginGraphics3D>(resource).get()
? PP_TRUE : PP_FALSE;
}
int32_t GetAttribs(PP_Resource graphics3d_id,
int32_t* attrib_list) {
int32_t pp_error;
nacl_abi_size_t num_attribs = GetNumAttribs(attrib_list);
NaClSrpcError retval =
PpbGraphics3DRpcClient::PPB_Graphics3D_GetAttribs(
GetMainSrpcChannel(),
graphics3d_id,
num_attribs, attrib_list,
&num_attribs, attrib_list,
&pp_error);
if (retval != NACL_SRPC_RESULT_OK) {
return PP_ERROR_BADARGUMENT;
}
return pp_error;
}
int32_t SetAttribs(PP_Resource graphics3d_id,
int32_t* attrib_list) {
int32_t pp_error;
nacl_abi_size_t num_attribs = GetNumAttribs(attrib_list);
NaClSrpcError retval =
PpbGraphics3DRpcClient::PPB_Graphics3D_SetAttribs(
GetMainSrpcChannel(),
graphics3d_id,
num_attribs, attrib_list,
&pp_error);
if (retval != NACL_SRPC_RESULT_OK) {
return PP_ERROR_BADARGUMENT;
}
return pp_error;
}
int32_t ResizeBuffers(PP_Resource graphics3d_id,
int32_t width,
int32_t height) {
int32_t pp_error;
NaClSrpcError retval =
PpbGraphics3DRpcClient::PPB_Graphics3D_ResizeBuffers(
GetMainSrpcChannel(),
graphics3d_id,
width,
height,
&pp_error);
if (retval != NACL_SRPC_RESULT_OK) {
return PP_ERROR_BADARGUMENT;
}
return pp_error;
}
int32_t SwapBuffs(PP_Resource graphics3d_id,
struct PP_CompletionCallback callback) {
DebugPrintf("PPB_Graphics3D::SwapBuffers: graphics3d_id=%"NACL_PRIu32"\n",
graphics3d_id);
scoped_refptr<PluginGraphics3D> graphics3d =
PluginResource::GetAs<PluginGraphics3D>(graphics3d_id).get();
if (!graphics3d.get())
return MayForceCallback(callback, PP_ERROR_BADRESOURCE);
return MayForceCallback(callback,
graphics3d->SwapBuffers(graphics3d_id, callback));
}
} // namespace
__thread PP_Resource PluginGraphics3D::cached_graphics3d_id = 0;
__thread gpu::gles2::GLES2Implementation*
PluginGraphics3D::cached_implementation = NULL;
PluginGraphics3D::PluginGraphics3D() : instance_id_(0) { }
PluginGraphics3D::~PluginGraphics3D() {
// Invalidate the cache.
cached_graphics3d_id = 0;
cached_implementation = NULL;
}
// static
gpu::gles2::GLES2Implementation* PluginGraphics3D::implFromResourceSlow(
PP_Resource graphics3d_id) {
DebugPrintf("PluginGraphics3D::implFromResourceSlow: "
"resource=%"NACL_PRIu32"\n", graphics3d_id);
// For performance reasons, we don't error-check the context, but crash on
// NULL instead.
gpu::gles2::GLES2Implementation* impl =
PluginResource::GetAs<PluginGraphics3D>(graphics3d_id)->impl();
cached_graphics3d_id = graphics3d_id;
cached_implementation = impl;
return impl;
}
bool PluginGraphics3D::InitFromBrowserResource(PP_Resource res) {
DebugPrintf("PluginGraphics3D::InitFromBrowserResource: "
"resource=%"NACL_PRIu32"\n", res);
// Create and initialize the objects required to issue GLES2 calls.
command_buffer_.reset(new CommandBufferNacl(res, PluginCore::GetInterface()));
command_buffer_->Initialize(kRingBufferSize);
gles2_helper_.reset(new gpu::gles2::GLES2CmdHelper(command_buffer_.get()));
gpu::Buffer buffer = command_buffer_->GetRingBuffer();
DebugPrintf("PluginGraphics3D::InitFromBrowserResource: buffer size: %d\n",
buffer.size);
if (gles2_helper_->Initialize(buffer.size)) {
// Request id -1 to signify 'don't care'
int32 transfer_buffer_id =
command_buffer_->CreateTransferBuffer(kTransferBufferSize, -1);
gpu::Buffer transfer_buffer =
command_buffer_->GetTransferBuffer(transfer_buffer_id);
if (transfer_buffer.ptr) {
gles2_implementation_.reset(new gpu::gles2::GLES2Implementation(
gles2_helper_.get(),
transfer_buffer.size,
transfer_buffer.ptr,
transfer_buffer_id,
false));
return true;
}
}
return false;
}
int32_t PluginGraphics3D::SwapBuffers(PP_Resource graphics3d_id,
struct PP_CompletionCallback callback) {
int32_t callback_id = CompletionCallbackTable::Get()->AddCallback(callback);
if (callback_id == 0) // Just like Chrome, for now disallow blocking calls.
return PP_ERROR_BADARGUMENT;
int32_t pp_error;
NaClSrpcError retval =
PpbGraphics3DRpcClient::PPB_Graphics3D_SwapBuffers(
GetMainSrpcChannel(),
graphics3d_id,
callback_id,
&pp_error);
if (retval != NACL_SRPC_RESULT_OK)
return PP_ERROR_FAILED;
if ((PP_OK_COMPLETIONPENDING != pp_error) && (PP_OK != pp_error))
return pp_error;
impl()->SwapBuffers();
return PP_OK_COMPLETIONPENDING;
}
// static
const PPB_Graphics3D_Dev* PluginGraphics3D::GetInterface() {
static const PPB_Graphics3D_Dev intf = {
&Create,
&IsGraphics3D,
&GetAttribs,
&SetAttribs,
&ResizeBuffers,
&SwapBuffs,
};
return &intf;
}
} // namespace ppapi_proxy
<|endoftext|> |
<commit_before>#include <eosio/chain/block.hpp>
namespace eosio { namespace chain {
void additional_block_signatures_extension::reflector_init() {
static_assert( fc::raw::has_feature_reflector_init_on_unpacked_reflected_types,
"additional_block_signatures_extension expects FC to support reflector_init" );
EOS_ASSERT( signatures.size() > 0, ill_formed_additional_block_signatures_extension,
"Additional block signatures extension must contain at least one signature",
);
set<signature_type> unique_sigs;
for( const auto& s : signatures ) {
auto res = unique_sigs.insert( s );
EOS_ASSERT( res.second, ill_formed_additional_block_signatures_extension,
"Signature ${s} was repeated in the additional block signatures extension",
("s", s)
);
}
}
static fc::static_variant<transaction_id_type, pruned_transaction> translate_transaction_receipt(const transaction_id_type& tid, bool) {
return tid;
}
static fc::static_variant<transaction_id_type, pruned_transaction> translate_transaction_receipt(const packed_transaction& ptrx, bool legacy) {
return pruned_transaction(ptrx, legacy);
}
pruned_transaction_receipt::pruned_transaction_receipt(const transaction_receipt& other, bool legacy)
: transaction_receipt_header(static_cast<const transaction_receipt_header&>(other)),
trx(other.trx.visit([&](const auto& obj) { return translate_transaction_receipt(obj, legacy); }))
{}
flat_multimap<uint16_t, block_extension> signed_block::validate_and_extract_extensions()const {
using decompose_t = block_extension_types::decompose_t;
flat_multimap<uint16_t, block_extension> results;
uint16_t id_type_lower_bound = 0;
for( size_t i = 0; i < block_extensions.size(); ++i ) {
const auto& e = block_extensions[i];
auto id = e.first;
EOS_ASSERT( id >= id_type_lower_bound, invalid_block_extension,
"Block extensions are not in the correct order (ascending id types required)"
);
auto iter = results.emplace(std::piecewise_construct,
std::forward_as_tuple(id),
std::forward_as_tuple()
);
auto match = decompose_t::extract<block_extension>( id, e.second, iter->second );
EOS_ASSERT( match, invalid_block_extension,
"Block extension with id type ${id} is not supported",
("id", id)
);
if( match->enforce_unique ) {
EOS_ASSERT( i == 0 || id > id_type_lower_bound, invalid_block_header_extension,
"Block extension with id type ${id} is not allowed to repeat",
("id", id)
);
}
id_type_lower_bound = id;
}
return results;
}
pruned_block::pruned_block( const signed_block& other, bool legacy )
: signed_block_header(static_cast<const signed_block_header&>(other)),
prune_state(legacy ? prune_state_type::complete_legacy : prune_state_type::complete),
block_extensions(other.block_extensions)
{
for(const auto& trx : other.transactions) {
transactions.emplace_back(trx, legacy);
}
}
static std::size_t pruned_trx_receipt_packed_size(const pruned_transaction& obj, pruned_transaction::cf_compression_type segment_compression) {
return obj.maximum_pruned_pack_size(segment_compression);
}
static std::size_t pruned_trx_receipt_packed_size(const transaction_id_type& obj, pruned_transaction::cf_compression_type) {
return fc::raw::pack_size(obj);
}
std::size_t pruned_transaction_receipt::maximum_pruned_pack_size( pruned_transaction::cf_compression_type segment_compression ) const {
return fc::raw::pack_size(*static_cast<const transaction_receipt_header*>(this)) + 1 +
trx.visit([&](const auto& obj){ return pruned_trx_receipt_packed_size(obj, segment_compression); });
}
std::size_t pruned_block::maximum_pruned_pack_size( pruned_transaction::cf_compression_type segment_compression ) const {
std::size_t result = fc::raw::pack_size(fc::unsigned_int(transactions.size()));
for(const pruned_transaction_receipt& r: transactions) {
result += r.maximum_pruned_pack_size( segment_compression );
}
return fc::raw::pack_size(*static_cast<const signed_block_header*>(this)) + fc::raw::pack_size(prune_state) + result + fc::raw::pack_size(block_extensions);
}
} } /// namespace eosio::chain
<commit_msg>Implement pruned_block::validate_and_extract_extensions.<commit_after>#include <eosio/chain/block.hpp>
namespace eosio { namespace chain {
void additional_block_signatures_extension::reflector_init() {
static_assert( fc::raw::has_feature_reflector_init_on_unpacked_reflected_types,
"additional_block_signatures_extension expects FC to support reflector_init" );
EOS_ASSERT( signatures.size() > 0, ill_formed_additional_block_signatures_extension,
"Additional block signatures extension must contain at least one signature",
);
set<signature_type> unique_sigs;
for( const auto& s : signatures ) {
auto res = unique_sigs.insert( s );
EOS_ASSERT( res.second, ill_formed_additional_block_signatures_extension,
"Signature ${s} was repeated in the additional block signatures extension",
("s", s)
);
}
}
static fc::static_variant<transaction_id_type, pruned_transaction> translate_transaction_receipt(const transaction_id_type& tid, bool) {
return tid;
}
static fc::static_variant<transaction_id_type, pruned_transaction> translate_transaction_receipt(const packed_transaction& ptrx, bool legacy) {
return pruned_transaction(ptrx, legacy);
}
pruned_transaction_receipt::pruned_transaction_receipt(const transaction_receipt& other, bool legacy)
: transaction_receipt_header(static_cast<const transaction_receipt_header&>(other)),
trx(other.trx.visit([&](const auto& obj) { return translate_transaction_receipt(obj, legacy); }))
{}
static flat_multimap<uint16_t, block_extension> validate_and_extract_block_extensions(const extensions_type& block_extensions) {
using decompose_t = block_extension_types::decompose_t;
flat_multimap<uint16_t, block_extension> results;
uint16_t id_type_lower_bound = 0;
for( size_t i = 0; i < block_extensions.size(); ++i ) {
const auto& e = block_extensions[i];
auto id = e.first;
EOS_ASSERT( id >= id_type_lower_bound, invalid_block_extension,
"Block extensions are not in the correct order (ascending id types required)"
);
auto iter = results.emplace(std::piecewise_construct,
std::forward_as_tuple(id),
std::forward_as_tuple()
);
auto match = decompose_t::extract<block_extension>( id, e.second, iter->second );
EOS_ASSERT( match, invalid_block_extension,
"Block extension with id type ${id} is not supported",
("id", id)
);
if( match->enforce_unique ) {
EOS_ASSERT( i == 0 || id > id_type_lower_bound, invalid_block_header_extension,
"Block extension with id type ${id} is not allowed to repeat",
("id", id)
);
}
id_type_lower_bound = id;
}
return results;
}
flat_multimap<uint16_t, block_extension> signed_block::validate_and_extract_extensions()const {
return validate_and_extract_block_extensions( block_extensions );
}
pruned_block::pruned_block( const signed_block& other, bool legacy )
: signed_block_header(static_cast<const signed_block_header&>(other)),
prune_state(legacy ? prune_state_type::complete_legacy : prune_state_type::complete),
block_extensions(other.block_extensions)
{
for(const auto& trx : other.transactions) {
transactions.emplace_back(trx, legacy);
}
}
static std::size_t pruned_trx_receipt_packed_size(const pruned_transaction& obj, pruned_transaction::cf_compression_type segment_compression) {
return obj.maximum_pruned_pack_size(segment_compression);
}
static std::size_t pruned_trx_receipt_packed_size(const transaction_id_type& obj, pruned_transaction::cf_compression_type) {
return fc::raw::pack_size(obj);
}
std::size_t pruned_transaction_receipt::maximum_pruned_pack_size( pruned_transaction::cf_compression_type segment_compression ) const {
return fc::raw::pack_size(*static_cast<const transaction_receipt_header*>(this)) + 1 +
trx.visit([&](const auto& obj){ return pruned_trx_receipt_packed_size(obj, segment_compression); });
}
std::size_t pruned_block::maximum_pruned_pack_size( pruned_transaction::cf_compression_type segment_compression ) const {
std::size_t result = fc::raw::pack_size(fc::unsigned_int(transactions.size()));
for(const pruned_transaction_receipt& r: transactions) {
result += r.maximum_pruned_pack_size( segment_compression );
}
return fc::raw::pack_size(*static_cast<const signed_block_header*>(this)) + fc::raw::pack_size(prune_state) + result + fc::raw::pack_size(block_extensions);
}
flat_multimap<uint16_t, block_extension> pruned_block::validate_and_extract_extensions()const {
return validate_and_extract_block_extensions( block_extensions );
}
} } /// namespace eosio::chain
<|endoftext|> |
<commit_before>// This file is part of the AliceVision project.
// This Source Code Form is subject to the terms of the Mozilla Public License,
// v. 2.0. If a copy of the MPL was not distributed with this file,
// You can obtain one at https://mozilla.org/MPL/2.0/.
#include <aliceVision/config.hpp>
#include <aliceVision/alicevision_omp.hpp>
#include <aliceVision/image/all.hpp>
#include <aliceVision/sfm/sfm.hpp>
#include <aliceVision/feature/imageDescriberCommon.hpp>
#include <aliceVision/feature/feature.hpp>
#include <aliceVision/system/MemoryInfo.hpp>
#include <aliceVision/system/Timer.hpp>
#include <aliceVision/system/Logger.hpp>
#include <aliceVision/system/cmdline.hpp>
#include <boost/program_options.hpp>
#include <boost/filesystem.hpp>
#include <boost/progress.hpp>
#include <string>
#include <fstream>
#include <sstream>
#include <iostream>
#include <functional>
#include <memory>
#include <limits>
using namespace aliceVision;
namespace po = boost::program_options;
namespace fs = boost::filesystem;
class FeatureExtractor
{
struct ViewJob
{
const sfm::View& view;
std::size_t memoryConsuption = 0;
std::string outputBasename;
std::vector<std::size_t> cpuImageDescriberIndexes;
std::vector<std::size_t> gpuImageDescriberIndexes;
ViewJob(const sfm::View& view,
const std::string& outputFolder)
: view(view)
, outputBasename(fs::path(fs::path(outputFolder) / fs::path(std::to_string(view.getViewId()))).string())
{}
bool useGPU() const
{
return !gpuImageDescriberIndexes.empty();
}
bool useCPU() const
{
return !cpuImageDescriberIndexes.empty();
}
std::string getFeaturesPath(feature::EImageDescriberType imageDescriberType) const
{
return outputBasename + "." + feature::EImageDescriberType_enumToString(imageDescriberType) + ".feat";
}
std::string getDescriptorPath(feature::EImageDescriberType imageDescriberType) const
{
return outputBasename + "." + feature::EImageDescriberType_enumToString(imageDescriberType) + ".desc";
}
void setImageDescribers(const std::vector<std::shared_ptr<feature::ImageDescriber>>& imageDescribers)
{
for(std::size_t i = 0; i < imageDescribers.size(); ++i)
{
const std::shared_ptr<feature::ImageDescriber>& imageDescriber = imageDescribers.at(i);
feature::EImageDescriberType imageDescriberType = imageDescriber->getDescriberType();
if(fs::exists(getFeaturesPath(imageDescriberType)) &&
fs::exists(getDescriptorPath(imageDescriberType)))
continue;
memoryConsuption += imageDescriber->getMemoryConsumption(view.getWidth(), view.getHeight());
if(imageDescriber->useCuda())
gpuImageDescriberIndexes.push_back(i);
else
cpuImageDescriberIndexes.push_back(i);
}
}
};
public:
FeatureExtractor(const sfm::SfMData& sfmData)
: _sfmData(sfmData)
{}
void setRange(int rangeStart, int rangeSize)
{
_rangeStart = rangeStart;
_rangeSize = rangeSize;
}
void setOutputFolder(const std::string& folder)
{
_outputFolder = folder;
}
void addImageDescriber(std::shared_ptr<feature::ImageDescriber>& imageDescriber)
{
_imageDescribers.push_back(imageDescriber);
}
void process()
{
// iteration on each view in the range in order
// to prepare viewJob stack
sfm::Views::const_iterator itViewBegin = _sfmData.GetViews().begin();
sfm::Views::const_iterator itViewEnd = _sfmData.GetViews().end();
if(_rangeStart != -1)
{
std::advance(itViewBegin, _rangeStart);
std::advance(itViewEnd, _rangeStart + _rangeSize);
}
std::size_t jobMaxMemoryConsuption = 0;
for(auto it = itViewBegin; it != itViewEnd; ++it)
{
const sfm::View& view = *(it->second.get());
ViewJob viewJob(view, _outputFolder);
viewJob.setImageDescribers(_imageDescribers);
jobMaxMemoryConsuption = std::max(jobMaxMemoryConsuption, viewJob.memoryConsuption);
if(viewJob.useCPU())
_cpuJobs.push_back(viewJob);
if(viewJob.useGPU())
_gpuJobs.push_back(viewJob);
}
if(!_cpuJobs.empty())
{
system::MemoryInfo memoryInformation = system::getMemoryInfo();
ALICEVISION_LOG_DEBUG("Job max memory consumption: " << jobMaxMemoryConsuption << " B");
ALICEVISION_LOG_DEBUG("Memory information: " << std::endl <<memoryInformation);
if(jobMaxMemoryConsuption == 0)
throw std::runtime_error("Can't compute feature extraction job max memory consuption.");
std::size_t nbThreads = (0.9 * memoryInformation.freeRam) / jobMaxMemoryConsuption;
if(memoryInformation.freeRam == 0)
{
ALICEVISION_LOG_WARNING("Can't find available system memory, this can be due to OS limitations.\n"
"Use only one thread for CPU feature extraction.");
nbThreads = 1;
}
// nbThreads should not be higher than the core number
nbThreads = std::min(static_cast<std::size_t>(omp_get_num_procs()), nbThreads);
ALICEVISION_LOG_DEBUG("# threads for extraction: " << nbThreads);
omp_set_nested(1);
#pragma omp parallel for num_threads(nbThreads)
for(int i = 0; i < _cpuJobs.size(); ++i)
computeViewJob(_cpuJobs.at(i));
}
if(!_gpuJobs.empty())
{
for(const auto& job : _gpuJobs)
computeViewJob(job, true);
}
}
private:
void computeViewJob(const ViewJob& job, bool useGPU = false)
{
image::Image<float> imageGrayFloat;
image::Image<unsigned char> imageGrayUChar;
image::readImage(job.view.getImagePath(), imageGrayFloat);
const auto imageDescriberIndexes = useGPU ? job.gpuImageDescriberIndexes : job.cpuImageDescriberIndexes;
for(auto& imageDescriberIndex : imageDescriberIndexes)
{
const auto& imageDescriber = _imageDescribers.at(imageDescriberIndex);
const feature::EImageDescriberType imageDescriberType = imageDescriber->getDescriberType();
const std::string imageDescriberTypeName = feature::EImageDescriberType_enumToString(imageDescriberType);
// Compute features and descriptors and export them to files
ALICEVISION_LOG_INFO("Extracting " + imageDescriberTypeName + " features from view '" + job.view.getImagePath() + "' " + (useGPU ? "[gpu]" : "[cpu]"));
std::unique_ptr<feature::Regions> regions;
if(imageDescriber->useFloatImage())
{
// image buffer use float image, use the read buffer
imageDescriber->describe(imageGrayFloat, regions);
}
else
{
// image buffer can't use float image
if(imageGrayUChar.Width() == 0) // the first time, convert the float buffer to uchar
imageGrayUChar = (imageGrayFloat.GetMat() * 255.f).cast<unsigned char>();
imageDescriber->describe(imageGrayUChar, regions);
}
imageDescriber->Save(regions.get(), job.getFeaturesPath(imageDescriberType), job.getDescriptorPath(imageDescriberType));
ALICEVISION_LOG_INFO("Extraction of " + imageDescriberTypeName + " features from view '" + job.view.getImagePath() + "' done.");
}
}
const sfm::SfMData& _sfmData;
std::vector<std::shared_ptr<feature::ImageDescriber>> _imageDescribers;
std::string _outputFolder;
int _rangeStart = -1;
int _rangeSize = -1;
std::vector<ViewJob> _cpuJobs;
std::vector<ViewJob> _gpuJobs;
};
/// - Compute view image description (feature & descriptor extraction)
/// - Export computed data
int main(int argc, char **argv)
{
// command-line parameters
std::string verboseLevel = system::EVerboseLevel_enumToString(system::Logger::getDefaultVerboseLevel());
std::string sfmDataFilename;
std::string outputFolder;
// user optional parameters
std::string describerTypesName = feature::EImageDescriberType_enumToString(feature::EImageDescriberType::SIFT);
std::string describerPreset = feature::EImageDescriberPreset_enumToString(feature::EImageDescriberPreset::NORMAL);
bool describersAreUpRight = false;
int rangeStart = -1;
int rangeSize = 1;
int maxJobs = 0;
bool forceCpuExtraction = false;
po::options_description allParams("AliceVision featureExtraction");
po::options_description requiredParams("Required parameters");
requiredParams.add_options()
("input,i", po::value<std::string>(&sfmDataFilename)->required(),
"SfMData file.")
("output,o", po::value<std::string>(&outputFolder)->required(),
"Output path for the features and descriptors files (*.feat, *.desc).");
po::options_description optionalParams("Optional parameters");
optionalParams.add_options()
("describerTypes,d", po::value<std::string>(&describerTypesName)->default_value(describerTypesName),
feature::EImageDescriberType_informations().c_str())
("describerPreset,p", po::value<std::string>(&describerPreset)->default_value(describerPreset),
"Control the ImageDescriber configuration (low, medium, normal, high, ultra).\n"
"Configuration 'ultra' can take long time !")
("upright,u", po::value<bool>(&describersAreUpRight)->default_value(describersAreUpRight),
"Use Upright feature.")
("forceCpuExtraction", po::value<bool>(&forceCpuExtraction)->default_value(forceCpuExtraction),
"Use only CPU feature extraction methods.")
("rangeStart", po::value<int>(&rangeStart)->default_value(rangeStart),
"Range image index start.")
("rangeSize", po::value<int>(&rangeSize)->default_value(rangeSize),
"Range size.")
("jobs", po::value<int>(&maxJobs)->default_value(maxJobs),
"Specifies the number of jobs to run simultaneously (0 for automatic mode).");
po::options_description logParams("Log parameters");
logParams.add_options()
("verboseLevel,v", po::value<std::string>(&verboseLevel)->default_value(verboseLevel),
"verbosity level (fatal, error, warning, info, debug, trace).");
allParams.add(requiredParams).add(optionalParams).add(logParams);
po::variables_map vm;
try
{
po::store(po::parse_command_line(argc, argv, allParams), vm);
if(vm.count("help") || (argc == 1))
{
ALICEVISION_COUT(allParams);
return EXIT_SUCCESS;
}
po::notify(vm);
}
catch(boost::program_options::required_option& e)
{
ALICEVISION_CERR("ERROR: " << e.what());
ALICEVISION_COUT("Usage:\n\n" << allParams);
return EXIT_FAILURE;
}
catch(boost::program_options::error& e)
{
ALICEVISION_CERR("ERROR: " << e.what());
ALICEVISION_COUT("Usage:\n\n" << allParams);
return EXIT_FAILURE;
}
ALICEVISION_COUT("Program called with the following parameters:");
ALICEVISION_COUT(vm);
// set verbose level
system::Logger::get()->setLogLevel(verboseLevel);
if(describerTypesName.empty())
{
ALICEVISION_LOG_ERROR("--describerTypes option is empty.");
return EXIT_FAILURE;
}
// create output folder
if(!fs::exists(outputFolder))
{
if(!fs::create_directory(outputFolder))
{
ALICEVISION_LOG_ERROR("Cannot create output folder");
return EXIT_FAILURE;
}
}
// load input scene
sfm::SfMData sfmData;
if(!sfm::Load(sfmData, sfmDataFilename, sfm::ESfMData(sfm::VIEWS|sfm::INTRINSICS)))
{
ALICEVISION_LOG_ERROR("The input file '" + sfmDataFilename + "' cannot be read");
return EXIT_FAILURE;
}
// create feature extractor
FeatureExtractor extractor(sfmData);
extractor.setOutputFolder(outputFolder);
// set extraction range
if(rangeStart != -1)
{
if(rangeStart < 0 || rangeSize < 0 ||
rangeStart > sfmData.GetViews().size())
{
ALICEVISION_LOG_ERROR("Range is incorrect");
return EXIT_FAILURE;
}
if(rangeStart + rangeSize > sfmData.views.size())
rangeSize = sfmData.views.size() - rangeStart;
extractor.setRange(rangeStart, rangeSize);
}
// initialize feature extractor imageDescribers
{
std::vector<feature::EImageDescriberType> imageDescriberTypes = feature::EImageDescriberType_stringToEnums(describerTypesName);
for(const auto& imageDescriberType: imageDescriberTypes)
{
std::shared_ptr<feature::ImageDescriber> imageDescriber = feature::createImageDescriber(imageDescriberType);
imageDescriber->setConfigurationPreset(describerPreset);
imageDescriber->setUpRight(describersAreUpRight);
if(forceCpuExtraction)
imageDescriber->setUseCuda(false);
extractor.addImageDescriber(imageDescriber);
}
}
// feature extraction routines
// for each View of the SfMData container:
// - if regions file exist continue,
// - if no file, compute features
{
system::Timer timer;
extractor.process();
ALICEVISION_LOG_INFO("Task done in (s): " + std::to_string(timer.elapsed()));
}
return EXIT_SUCCESS;
}
<commit_msg>[software] `featureExtraction` fix : add `explicit` keyword to `FeatureExtractor` constructor<commit_after>// This file is part of the AliceVision project.
// This Source Code Form is subject to the terms of the Mozilla Public License,
// v. 2.0. If a copy of the MPL was not distributed with this file,
// You can obtain one at https://mozilla.org/MPL/2.0/.
#include <aliceVision/config.hpp>
#include <aliceVision/alicevision_omp.hpp>
#include <aliceVision/image/all.hpp>
#include <aliceVision/sfm/sfm.hpp>
#include <aliceVision/feature/imageDescriberCommon.hpp>
#include <aliceVision/feature/feature.hpp>
#include <aliceVision/system/MemoryInfo.hpp>
#include <aliceVision/system/Timer.hpp>
#include <aliceVision/system/Logger.hpp>
#include <aliceVision/system/cmdline.hpp>
#include <boost/program_options.hpp>
#include <boost/filesystem.hpp>
#include <boost/progress.hpp>
#include <string>
#include <fstream>
#include <sstream>
#include <iostream>
#include <functional>
#include <memory>
#include <limits>
using namespace aliceVision;
namespace po = boost::program_options;
namespace fs = boost::filesystem;
class FeatureExtractor
{
struct ViewJob
{
const sfm::View& view;
std::size_t memoryConsuption = 0;
std::string outputBasename;
std::vector<std::size_t> cpuImageDescriberIndexes;
std::vector<std::size_t> gpuImageDescriberIndexes;
ViewJob(const sfm::View& view,
const std::string& outputFolder)
: view(view)
, outputBasename(fs::path(fs::path(outputFolder) / fs::path(std::to_string(view.getViewId()))).string())
{}
bool useGPU() const
{
return !gpuImageDescriberIndexes.empty();
}
bool useCPU() const
{
return !cpuImageDescriberIndexes.empty();
}
std::string getFeaturesPath(feature::EImageDescriberType imageDescriberType) const
{
return outputBasename + "." + feature::EImageDescriberType_enumToString(imageDescriberType) + ".feat";
}
std::string getDescriptorPath(feature::EImageDescriberType imageDescriberType) const
{
return outputBasename + "." + feature::EImageDescriberType_enumToString(imageDescriberType) + ".desc";
}
void setImageDescribers(const std::vector<std::shared_ptr<feature::ImageDescriber>>& imageDescribers)
{
for(std::size_t i = 0; i < imageDescribers.size(); ++i)
{
const std::shared_ptr<feature::ImageDescriber>& imageDescriber = imageDescribers.at(i);
feature::EImageDescriberType imageDescriberType = imageDescriber->getDescriberType();
if(fs::exists(getFeaturesPath(imageDescriberType)) &&
fs::exists(getDescriptorPath(imageDescriberType)))
continue;
memoryConsuption += imageDescriber->getMemoryConsumption(view.getWidth(), view.getHeight());
if(imageDescriber->useCuda())
gpuImageDescriberIndexes.push_back(i);
else
cpuImageDescriberIndexes.push_back(i);
}
}
};
public:
explicit FeatureExtractor(const sfm::SfMData& sfmData)
: _sfmData(sfmData)
{}
void setRange(int rangeStart, int rangeSize)
{
_rangeStart = rangeStart;
_rangeSize = rangeSize;
}
void setOutputFolder(const std::string& folder)
{
_outputFolder = folder;
}
void addImageDescriber(std::shared_ptr<feature::ImageDescriber>& imageDescriber)
{
_imageDescribers.push_back(imageDescriber);
}
void process()
{
// iteration on each view in the range in order
// to prepare viewJob stack
sfm::Views::const_iterator itViewBegin = _sfmData.GetViews().begin();
sfm::Views::const_iterator itViewEnd = _sfmData.GetViews().end();
if(_rangeStart != -1)
{
std::advance(itViewBegin, _rangeStart);
std::advance(itViewEnd, _rangeStart + _rangeSize);
}
std::size_t jobMaxMemoryConsuption = 0;
for(auto it = itViewBegin; it != itViewEnd; ++it)
{
const sfm::View& view = *(it->second.get());
ViewJob viewJob(view, _outputFolder);
viewJob.setImageDescribers(_imageDescribers);
jobMaxMemoryConsuption = std::max(jobMaxMemoryConsuption, viewJob.memoryConsuption);
if(viewJob.useCPU())
_cpuJobs.push_back(viewJob);
if(viewJob.useGPU())
_gpuJobs.push_back(viewJob);
}
if(!_cpuJobs.empty())
{
system::MemoryInfo memoryInformation = system::getMemoryInfo();
ALICEVISION_LOG_DEBUG("Job max memory consumption: " << jobMaxMemoryConsuption << " B");
ALICEVISION_LOG_DEBUG("Memory information: " << std::endl <<memoryInformation);
if(jobMaxMemoryConsuption == 0)
throw std::runtime_error("Can't compute feature extraction job max memory consuption.");
std::size_t nbThreads = (0.9 * memoryInformation.freeRam) / jobMaxMemoryConsuption;
if(memoryInformation.freeRam == 0)
{
ALICEVISION_LOG_WARNING("Can't find available system memory, this can be due to OS limitations.\n"
"Use only one thread for CPU feature extraction.");
nbThreads = 1;
}
// nbThreads should not be higher than the core number
nbThreads = std::min(static_cast<std::size_t>(omp_get_num_procs()), nbThreads);
ALICEVISION_LOG_DEBUG("# threads for extraction: " << nbThreads);
omp_set_nested(1);
#pragma omp parallel for num_threads(nbThreads)
for(int i = 0; i < _cpuJobs.size(); ++i)
computeViewJob(_cpuJobs.at(i));
}
if(!_gpuJobs.empty())
{
for(const auto& job : _gpuJobs)
computeViewJob(job, true);
}
}
private:
void computeViewJob(const ViewJob& job, bool useGPU = false)
{
image::Image<float> imageGrayFloat;
image::Image<unsigned char> imageGrayUChar;
image::readImage(job.view.getImagePath(), imageGrayFloat);
const auto imageDescriberIndexes = useGPU ? job.gpuImageDescriberIndexes : job.cpuImageDescriberIndexes;
for(auto& imageDescriberIndex : imageDescriberIndexes)
{
const auto& imageDescriber = _imageDescribers.at(imageDescriberIndex);
const feature::EImageDescriberType imageDescriberType = imageDescriber->getDescriberType();
const std::string imageDescriberTypeName = feature::EImageDescriberType_enumToString(imageDescriberType);
// Compute features and descriptors and export them to files
ALICEVISION_LOG_INFO("Extracting " + imageDescriberTypeName + " features from view '" + job.view.getImagePath() + "' " + (useGPU ? "[gpu]" : "[cpu]"));
std::unique_ptr<feature::Regions> regions;
if(imageDescriber->useFloatImage())
{
// image buffer use float image, use the read buffer
imageDescriber->describe(imageGrayFloat, regions);
}
else
{
// image buffer can't use float image
if(imageGrayUChar.Width() == 0) // the first time, convert the float buffer to uchar
imageGrayUChar = (imageGrayFloat.GetMat() * 255.f).cast<unsigned char>();
imageDescriber->describe(imageGrayUChar, regions);
}
imageDescriber->Save(regions.get(), job.getFeaturesPath(imageDescriberType), job.getDescriptorPath(imageDescriberType));
ALICEVISION_LOG_INFO("Extraction of " + imageDescriberTypeName + " features from view '" + job.view.getImagePath() + "' done.");
}
}
const sfm::SfMData& _sfmData;
std::vector<std::shared_ptr<feature::ImageDescriber>> _imageDescribers;
std::string _outputFolder;
int _rangeStart = -1;
int _rangeSize = -1;
std::vector<ViewJob> _cpuJobs;
std::vector<ViewJob> _gpuJobs;
};
/// - Compute view image description (feature & descriptor extraction)
/// - Export computed data
int main(int argc, char **argv)
{
// command-line parameters
std::string verboseLevel = system::EVerboseLevel_enumToString(system::Logger::getDefaultVerboseLevel());
std::string sfmDataFilename;
std::string outputFolder;
// user optional parameters
std::string describerTypesName = feature::EImageDescriberType_enumToString(feature::EImageDescriberType::SIFT);
std::string describerPreset = feature::EImageDescriberPreset_enumToString(feature::EImageDescriberPreset::NORMAL);
bool describersAreUpRight = false;
int rangeStart = -1;
int rangeSize = 1;
int maxJobs = 0;
bool forceCpuExtraction = false;
po::options_description allParams("AliceVision featureExtraction");
po::options_description requiredParams("Required parameters");
requiredParams.add_options()
("input,i", po::value<std::string>(&sfmDataFilename)->required(),
"SfMData file.")
("output,o", po::value<std::string>(&outputFolder)->required(),
"Output path for the features and descriptors files (*.feat, *.desc).");
po::options_description optionalParams("Optional parameters");
optionalParams.add_options()
("describerTypes,d", po::value<std::string>(&describerTypesName)->default_value(describerTypesName),
feature::EImageDescriberType_informations().c_str())
("describerPreset,p", po::value<std::string>(&describerPreset)->default_value(describerPreset),
"Control the ImageDescriber configuration (low, medium, normal, high, ultra).\n"
"Configuration 'ultra' can take long time !")
("upright,u", po::value<bool>(&describersAreUpRight)->default_value(describersAreUpRight),
"Use Upright feature.")
("forceCpuExtraction", po::value<bool>(&forceCpuExtraction)->default_value(forceCpuExtraction),
"Use only CPU feature extraction methods.")
("rangeStart", po::value<int>(&rangeStart)->default_value(rangeStart),
"Range image index start.")
("rangeSize", po::value<int>(&rangeSize)->default_value(rangeSize),
"Range size.")
("jobs", po::value<int>(&maxJobs)->default_value(maxJobs),
"Specifies the number of jobs to run simultaneously (0 for automatic mode).");
po::options_description logParams("Log parameters");
logParams.add_options()
("verboseLevel,v", po::value<std::string>(&verboseLevel)->default_value(verboseLevel),
"verbosity level (fatal, error, warning, info, debug, trace).");
allParams.add(requiredParams).add(optionalParams).add(logParams);
po::variables_map vm;
try
{
po::store(po::parse_command_line(argc, argv, allParams), vm);
if(vm.count("help") || (argc == 1))
{
ALICEVISION_COUT(allParams);
return EXIT_SUCCESS;
}
po::notify(vm);
}
catch(boost::program_options::required_option& e)
{
ALICEVISION_CERR("ERROR: " << e.what());
ALICEVISION_COUT("Usage:\n\n" << allParams);
return EXIT_FAILURE;
}
catch(boost::program_options::error& e)
{
ALICEVISION_CERR("ERROR: " << e.what());
ALICEVISION_COUT("Usage:\n\n" << allParams);
return EXIT_FAILURE;
}
ALICEVISION_COUT("Program called with the following parameters:");
ALICEVISION_COUT(vm);
// set verbose level
system::Logger::get()->setLogLevel(verboseLevel);
if(describerTypesName.empty())
{
ALICEVISION_LOG_ERROR("--describerTypes option is empty.");
return EXIT_FAILURE;
}
// create output folder
if(!fs::exists(outputFolder))
{
if(!fs::create_directory(outputFolder))
{
ALICEVISION_LOG_ERROR("Cannot create output folder");
return EXIT_FAILURE;
}
}
// load input scene
sfm::SfMData sfmData;
if(!sfm::Load(sfmData, sfmDataFilename, sfm::ESfMData(sfm::VIEWS|sfm::INTRINSICS)))
{
ALICEVISION_LOG_ERROR("The input file '" + sfmDataFilename + "' cannot be read");
return EXIT_FAILURE;
}
// create feature extractor
FeatureExtractor extractor(sfmData);
extractor.setOutputFolder(outputFolder);
// set extraction range
if(rangeStart != -1)
{
if(rangeStart < 0 || rangeSize < 0 ||
rangeStart > sfmData.GetViews().size())
{
ALICEVISION_LOG_ERROR("Range is incorrect");
return EXIT_FAILURE;
}
if(rangeStart + rangeSize > sfmData.views.size())
rangeSize = sfmData.views.size() - rangeStart;
extractor.setRange(rangeStart, rangeSize);
}
// initialize feature extractor imageDescribers
{
std::vector<feature::EImageDescriberType> imageDescriberTypes = feature::EImageDescriberType_stringToEnums(describerTypesName);
for(const auto& imageDescriberType: imageDescriberTypes)
{
std::shared_ptr<feature::ImageDescriber> imageDescriber = feature::createImageDescriber(imageDescriberType);
imageDescriber->setConfigurationPreset(describerPreset);
imageDescriber->setUpRight(describersAreUpRight);
if(forceCpuExtraction)
imageDescriber->setUseCuda(false);
extractor.addImageDescriber(imageDescriber);
}
}
// feature extraction routines
// for each View of the SfMData container:
// - if regions file exist continue,
// - if no file, compute features
{
system::Timer timer;
extractor.process();
ALICEVISION_LOG_INFO("Task done in (s): " + std::to_string(timer.elapsed()));
}
return EXIT_SUCCESS;
}
<|endoftext|> |
<commit_before>#include <gtest/gtest.h>
#include <test/models/utility.hpp>
#include <fstream>
#include <stan/mcmc/chains.hpp>
const size_t num_chains = 4;
bool has_R = false;
bool has_jags = false;
std::vector<std::string> model_path;
std::string Rscript;
std::vector<std::string> data_files;
TEST(LogisticSpeedTest,Prerequisites) {
std::string command;
command = "Rscript --version";
try {
run_command(command);
has_R = true;
} catch (...) {
std::cout << "System does not have Rscript available" << std::endl
<< "Failed to run: " << command << std::endl;
}
std::vector<std::string> test_file;
test_file.push_back("src");
test_file.push_back("models");
test_file.push_back("speed");
test_file.push_back("empty.jags");
command = "jags ";
command += convert_model_path(test_file);
try {
run_command(command);
has_jags = true;
} catch (...) {
std::cout << "System does not have jags available" << std::endl
<< "Failed to run: " << command << std::endl;
}
model_path.push_back("models");
model_path.push_back("speed");
model_path.push_back("logistic");
Rscript = "logistic_generate_data.R";
data_files.push_back("logistic_128_2");
// data_files.push_back("logistic_1000_10");
// data_files.push_back("logistic_1000_100");
// data_files.push_back("logistic_1000_500");
// data_files.push_back("logistic_5000_1");
// data_files.push_back("logistic_5000_10");
// data_files.push_back("logistic_5000_100");
// data_files.push_back("logistic_5000_500");
// data_files.push_back("logistic_5000_1000");
// data_files.push_back("logistic_10000_1");
// data_files.push_back("logistic_10000_10");
// data_files.push_back("logistic_10000_100");
// data_files.push_back("logistic_10000_500");
// data_files.push_back("logistic_10000_1000");
//
}
TEST(LogisticSpeedTest,GenerateData) {
if (!has_R) {
std::cout << "No R available" << std::endl;
return; // should this fail? probably
}
bool has_data = true;
std::string path = convert_model_path(model_path);
for (size_t i = 0; i < data_files.size() && has_data; i++) {
std::string data_file = path;
data_file += get_path_separator();
data_file += data_files[i];
data_file += ".Rdata";
std::ifstream file(data_file.c_str());
if (!file)
has_data = false;
}
if (has_data)
return;
// generate data using R script
std::string command;
command = "cd ";
command += convert_model_path(model_path);
command += " && ";
command += "Rscript ";
command += Rscript;
// no guarantee here that we have the right files
ASSERT_NO_THROW(run_command(command))
<< command;
SUCCEED();
}
void test_logistic_speed_stan(std::string filename, size_t iterations) {
if (!has_R)
return;
std::stringstream command;
std::string path = convert_model_path(model_path);
command << path << get_path_separator() << "logistic"
<< " --data=" << path << get_path_separator() << filename << ".Rdata"
<< " --iter=" << iterations;
std::vector<std::string> command_outputs;
for (size_t chain = 0; chain < num_chains; chain++) {
std::stringstream command_chain;
command_chain << command.str();
command_chain << " --chain_id=" << chain
<< " --samples=" << path << get_path_separator()
<< filename << ".chain_" << chain << ".csv";
// start timer
std::string command_output;
EXPECT_NO_THROW(command_output = run_command(command_chain.str()))
<< "Failed running command: " << command_chain.str();
// end timer
command_outputs.push_back(command_output);
}
std::stringstream samples;
samples << path << get_path_separator()
<< filename << ".chain_0.csv";
std::vector<std::string> names;
std::vector<std::vector<size_t> > dimss;
stan::mcmc::read_variables(samples.str(), 2U,
names, dimss);
stan::mcmc::chains<> chains(num_chains, names, dimss);
for (size_t chain = 0; chain < num_chains; chain++) {
samples.str("");
samples << path << get_path_separator()
<< filename << ".chain_" << chain << ".csv";
stan::mcmc::add_chain(chains, chain, samples.str(), 2U);
}
size_t num_params = chains.num_params();
for (size_t i = 0; i < num_params; i++) {
std::cout << "------------------------------------------------------------\n";
std::cout << "beta[" << i << "]" << std::endl;
std::cout << "\tmean: " << chains.mean(i) << std::endl;
std::cout << "\tsd: " << chains.sd(i) << std::endl;
std::cout << "\tneff: " << chains.effective_sample_size(i) << std::endl;
std::cout << "\tsplit R hat: " << chains.split_potential_scale_reduction(i) << std::endl;
}
SUCCEED();
}
TEST(LogisticSpeedTest,Stan_128_2) {
test_logistic_speed_stan("logistic_128_2", 250U);
}
<commit_msg>speed-test: refactoring test<commit_after>#include <gtest/gtest.h>
#include <test/models/utility.hpp>
#include <fstream>
#include <stan/mcmc/chains.hpp>
#include <boost/date_time/posix_time/posix_time_types.hpp>
const size_t num_chains = 4;
bool has_R = false;
bool has_jags = false;
std::vector<std::string> model_path;
std::string Rscript;
std::vector<std::string> data_files;
TEST(LogisticSpeedTest,Prerequisites) {
std::string command;
command = "Rscript --version";
try {
run_command(command);
has_R = true;
} catch (...) {
std::cout << "System does not have Rscript available" << std::endl
<< "Failed to run: " << command << std::endl;
}
std::vector<std::string> test_file;
test_file.push_back("src");
test_file.push_back("models");
test_file.push_back("speed");
test_file.push_back("empty.jags");
command = "jags ";
command += convert_model_path(test_file);
try {
run_command(command);
has_jags = true;
} catch (...) {
std::cout << "System does not have jags available" << std::endl
<< "Failed to run: " << command << std::endl;
}
model_path.push_back("models");
model_path.push_back("speed");
model_path.push_back("logistic");
Rscript = "logistic_generate_data.R";
data_files.push_back("logistic_128_2");
// data_files.push_back("logistic_1000_10");
// data_files.push_back("logistic_1000_100");
// data_files.push_back("logistic_1000_500");
// data_files.push_back("logistic_5000_1");
// data_files.push_back("logistic_5000_10");
// data_files.push_back("logistic_5000_100");
// data_files.push_back("logistic_5000_500");
// data_files.push_back("logistic_5000_1000");
// data_files.push_back("logistic_10000_1");
// data_files.push_back("logistic_10000_10");
// data_files.push_back("logistic_10000_100");
// data_files.push_back("logistic_10000_500");
// data_files.push_back("logistic_10000_1000");
//
}
TEST(LogisticSpeedTest,GenerateData) {
if (!has_R) {
std::cout << "No R available" << std::endl;
return; // should this fail? probably
}
bool has_data = true;
std::string path = convert_model_path(model_path);
for (size_t i = 0; i < data_files.size() && has_data; i++) {
std::string data_file = path;
data_file += get_path_separator();
data_file += data_files[i];
data_file += ".Rdata";
std::ifstream file(data_file.c_str());
if (!file)
has_data = false;
}
if (has_data)
return;
// generate data using R script
std::string command;
command = "cd ";
command += convert_model_path(model_path);
command += " && ";
command += "Rscript ";
command += Rscript;
// no guarantee here that we have the right files
ASSERT_NO_THROW(run_command(command))
<< command;
SUCCEED();
}
// returns number of milliseconds to execute commands;
long run_stan(const std::string& command, const std::string& filename, std::vector<std::string> command_outputs) {
long time;
std::string path = convert_model_path(model_path);
//random_seed
//= (boost::posix_time::microsec_clock::universal_time() -
//boost::posix_time::ptime(boost::posix_time::min_date_time))
// .total_milliseconds();
for (size_t chain = 0; chain < num_chains; chain++) {
std::stringstream command_chain;
command_chain << command;
command_chain << " --chain_id=" << chain
<< " --samples=" << path << get_path_separator()
<< filename << ".chain_" << chain << ".csv";
std::string command_output;
try {
// start timer
command_output = run_command(command_chain.str());
// end timer
} catch(...) {
ADD_FAILURE() << "Failed running command: " << command_chain.str();
}
command_outputs.push_back(command_output);
}
return 0;
}
void test_logistic_speed_stan(std::string filename, size_t iterations) {
if (!has_R)
return;
std::stringstream command;
std::string path = convert_model_path(model_path);
command << path << get_path_separator() << "logistic"
<< " --data=" << path << get_path_separator() << filename << ".Rdata"
<< " --iter=" << iterations;
std::vector<std::string> command_outputs;
long time = run_stan(command.str(), filename, command_outputs);
std::stringstream samples;
samples << path << get_path_separator()
<< filename << ".chain_0.csv";
std::vector<std::string> names;
std::vector<std::vector<size_t> > dimss;
stan::mcmc::read_variables(samples.str(), 2U,
names, dimss);
stan::mcmc::chains<> chains(num_chains, names, dimss);
for (size_t chain = 0; chain < num_chains; chain++) {
samples.str("");
samples << path << get_path_separator()
<< filename << ".chain_" << chain << ".csv";
stan::mcmc::add_chain(chains, chain, samples.str(), 2U);
}
size_t num_params = chains.num_params();
for (size_t i = 0; i < num_params; i++) {
std::cout << "------------------------------------------------------------\n";
std::cout << "beta[" << i << "]" << std::endl;
std::cout << "\tmean: " << chains.mean(i) << std::endl;
std::cout << "\tsd: " << chains.sd(i) << std::endl;
std::cout << "\tneff: " << chains.effective_sample_size(i) << std::endl;
std::cout << "\tsplit R hat: " << chains.split_potential_scale_reduction(i) << std::endl;
}
SUCCEED();
}
TEST(LogisticSpeedTest,Stan_128_2) {
test_logistic_speed_stan("logistic_128_2", 250U);
}
<|endoftext|> |
<commit_before>/*
* The Apache Software License, Version 1.1
*
* Copyright (c) 1999 The Apache Software Foundation. All rights
* reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
*
* 3. The end-user documentation included with the redistribution,
* if any, must include the following acknowledgment:
* "This product includes software developed by the
* Apache Software Foundation (http://www.apache.org/)."
* Alternately, this acknowledgment may appear in the software itself,
* if and wherever such third-party acknowledgments normally appear.
*
* 4. The names "Xerces" and "Apache Software Foundation" must
* not be used to endorse or promote products derived from this
* software without prior written permission. For written
* permission, please contact apache\@apache.org.
*
* 5. Products derived from this software may not be called "Apache",
* nor may "Apache" appear in their name, without prior written
* permission of the Apache Software Foundation.
*
* THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED
* WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
* OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR
* ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
* USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
* OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation, and was
* originally based on software copyright (c) 1999, International
* Business Machines, Inc., http://www.ibm.com . For more information
* on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*/
/**
* $Log$
* Revision 1.3 1999/11/20 00:28:19 rahulj
* Added code for case-insensitive wide character string compares
*
* Revision 1.2 1999/11/17 21:52:49 abagchi
* Changed wcscasecmp() to wcscmp() to make it work on Solaris and AIX
* PR:
* Obtained from:
* Submitted by:
* Reviewed by:
*
* Revision 1.1.1.1 1999/11/09 01:06:10 twl
* Initial checkin
*
* Revision 1.7 1999/11/08 20:45:34 rahul
* Swat for adding in Product name and CVS comment log variable.
*
*/
// ---------------------------------------------------------------------------
// Includes
// ---------------------------------------------------------------------------
#include "IconvTransService.hpp"
#include <wchar.h>
#if defined (XML_GNUG)
#include <wctype.h>
#endif
#include <string.h>
#include <stdlib.h>
#include <stdio.h>
static const int gTempBuffArraySize = 1024;
static unsigned int getWideCharLength(const XMLCh* const src)
{
if (!src)
return 0;
unsigned int len = 0;
const XMLCh* pTmp = src;
while (*pTmp++)
len++;
return len;
}
// ---------------------------------------------------------------------------
// IconvTransService: Constructors and Destructor
// ---------------------------------------------------------------------------
IconvTransService::IconvTransService()
{
}
IconvTransService::~IconvTransService()
{
}
// ---------------------------------------------------------------------------
// IconvTransService: The virtual transcoding service API
// ---------------------------------------------------------------------------
int IconvTransService::compareIString( const XMLCh* const comp1
, const XMLCh* const comp2)
{
const XMLCh* cptr1 = comp1;
const XMLCh* cptr2 = comp2;
while ((*cptr1 != NULL) && (*cptr2 != NULL))
{
wint_t wch1 = towupper(*cptr1);
wint_t wch2 = towupper(*cptr2);
if (wch1 < wch2)
return -1;
if (wch1 > wch2)
return 1;
cptr1++;
cptr2++;
}
return 0;
}
int IconvTransService::compareNIString( const XMLCh* const comp1
, const XMLCh* const comp2
, const unsigned int maxChars)
{
const XMLCh* cptr1 = comp1;
const XMLCh* cptr2 = comp2;
unsigned int n = 0;
while ((*cptr1 != NULL) && (*cptr2 != NULL) && (n < maxChars))
{
wint_t wch1 = towupper(*cptr1);
wint_t wch2 = towupper(*cptr2);
if (wch1 < wch2)
return -1;
if (wch1 > wch2)
return 1;
cptr1++;
cptr2++;
n++;
}
return 0;
}
bool IconvTransService::isSpace(const XMLCh toCheck) const
{
return (iswspace(toCheck) != 0);
}
XMLTranscoder* IconvTransService::makeNewDefTranscoder()
{
// Just allocate a new transcoder of our type
return new IconvTranscoder;
}
XMLTranscoder*
IconvTransService::makeNewTranscoderFor(const XMLCh* const encodingName
, XMLTransService::Codes& resValue
, const unsigned int )
{
//
// NOTE: We don't use the block size here
//
//
// This is a minimalist transcoding service, that only supports a local
// default transcoder. All named encodings return zero as a failure,
// which means that only the intrinsic encodings supported by the parser
// itself will work for XML data.
//
resValue = XMLTransService::UnsupportedEncoding;
return 0;
}
// ---------------------------------------------------------------------------
// IconvTranscoder: Constructors and Destructor
// ---------------------------------------------------------------------------
IconvTranscoder::IconvTranscoder()
{
}
IconvTranscoder::~IconvTranscoder()
{
}
// ---------------------------------------------------------------------------
// IconvTranscoder: The virtual transcoder API
// ---------------------------------------------------------------------------
unsigned int IconvTranscoder::calcRequiredSize(const char* const srcText)
{
if (!srcText)
return 0;
const unsigned int retVal = ::mbstowcs(NULL, srcText, 0);
if (retVal == -1)
return 0;
return retVal;
}
unsigned int IconvTranscoder::calcRequiredSize(const XMLCh* const srcText)
{
if (!srcText)
return 0;
unsigned int wLent = getWideCharLength(srcText);
wchar_t tmpWideCharArr[gTempBuffArraySize];
wchar_t* allocatedArray = 0;
wchar_t* wideCharBuf = 0;
if (wLent >= gTempBuffArraySize)
wideCharBuf = allocatedArray = new wchar_t[wLent + 1];
else
wideCharBuf = tmpWideCharArr;
for (unsigned int i = 0; i < wLent; i++)
{
wideCharBuf[i] = srcText[i];
}
wideCharBuf[wLent] = 0x00;
const unsigned int retVal = ::wcstombs(NULL, wideCharBuf, 0);
delete [] allocatedArray;
if (retVal == -1)
return 0;
return retVal;
}
XMLCh IconvTranscoder::transcodeOne(const char* const srcData
, const unsigned int srcBytes
, unsigned int& bytesEaten)
{
wchar_t toFill;
int eaten = ::mbtowc(&toFill, srcData, srcBytes);
if (eaten == -1)
{
bytesEaten = 0;
return 0;
}
// Return the bytes we ate and the resulting char.
bytesEaten = eaten;
return toFill;
}
char* IconvTranscoder::transcode(const XMLCh* const toTranscode)
{
if (!toTranscode)
return 0;
char* retVal = 0;
if (toTranscode)
{
unsigned int wLent = getWideCharLength(toTranscode);
wchar_t tmpWideCharArr[gTempBuffArraySize];
wchar_t* allocatedArray = 0;
wchar_t* wideCharBuf = 0;
if (wLent >= gTempBuffArraySize)
wideCharBuf = allocatedArray = new wchar_t[wLent + 1];
else
wideCharBuf = tmpWideCharArr;
for (unsigned int i = 0; i < wLent; i++)
{
wideCharBuf[i] = toTranscode[i];
}
wideCharBuf[wLent] = 0x00;
// Calc the needed size.
const size_t neededLen = ::wcstombs(NULL, wideCharBuf, 0);
if (neededLen == 0)
{
delete [] allocatedArray;
return 0;
}
retVal = new char[neededLen + 1];
::wcstombs(retVal, wideCharBuf, neededLen);
retVal[neededLen] = 0;
delete [] allocatedArray;
}
else
{
retVal = new char[1];
retVal[0] = 0;
}
return retVal;
}
bool IconvTranscoder::transcode(const XMLCh* const toTranscode
, char* const toFill
, const unsigned int maxBytes)
{
// Watch for a couple of pyscho corner cases
if (!toTranscode || !maxBytes)
{
toFill[0] = 0;
return true;
}
if (!*toTranscode)
{
toFill[0] = 0;
return true;
}
wchar_t tmpWideCharArr[gTempBuffArraySize];
wchar_t* allocatedArray = 0;
wchar_t* wideCharBuf = 0;
if (maxBytes >= gTempBuffArraySize)
wideCharBuf = allocatedArray = new wchar_t[maxBytes + 1];
else
wideCharBuf = tmpWideCharArr;
for (unsigned int i = 0; i < maxBytes; i++)
{
wideCharBuf[i] = toTranscode[i];
}
wideCharBuf[maxBytes] = 0x00;
// Ok, go ahead and try the transcoding. If it fails, then ...
//
if (::wcstombs(toFill, wideCharBuf, maxBytes) == -1)
{
delete [] allocatedArray;
return false;
}
// Cap it off just in case
toFill[maxBytes] = 0;
delete [] allocatedArray;
return true;
}
XMLCh* IconvTranscoder::transcode(const char* const toTranscode)
{
XMLCh* retVal = 0;
if (toTranscode)
{
const unsigned int len = calcRequiredSize(toTranscode);
if (len == 0)
return 0;
wchar_t tmpWideCharArr[gTempBuffArraySize];
wchar_t* allocatedArray = 0;
wchar_t* wideCharBuf = 0;
if (len >= gTempBuffArraySize)
wideCharBuf = allocatedArray = new wchar_t[len + 1];
else
wideCharBuf = tmpWideCharArr;
::mbstowcs(wideCharBuf, toTranscode, len);
retVal = new XMLCh[len + 1];
for (unsigned int i = 0; i < len; i++)
{
retVal[i] = (XMLCh) wideCharBuf[i];
}
retVal[len] = 0x00;
delete [] allocatedArray;
}
else
{
retVal = new XMLCh[1];
retVal[0] = 0;
}
return retVal;
}
bool IconvTranscoder::transcode(const char* const toTranscode
, XMLCh* const toFill
, const unsigned int maxChars)
{
// Check for a couple of psycho corner cases
if (!toTranscode || !maxChars)
{
toFill[0] = 0;
return true;
}
if (!*toTranscode)
{
toFill[0] = 0;
return true;
}
wchar_t tmpWideCharArr[gTempBuffArraySize];
wchar_t* allocatedArray = 0;
wchar_t* wideCharBuf = 0;
if (maxChars >= gTempBuffArraySize)
wideCharBuf = allocatedArray = new wchar_t[maxChars + 1];
else
wideCharBuf = tmpWideCharArr;
if (::mbstowcs(wideCharBuf, toTranscode, maxChars) == -1)
{
delete [] allocatedArray;
return false;
}
for (unsigned int i = 0; i < maxChars; i++)
{
toFill[i] = (XMLCh) wideCharBuf[i];
}
toFill[maxChars] = 0x00;
delete [] allocatedArray;
return true;
}
unsigned int
IconvTranscoder::transcodeXML( const char* const srcData
, const unsigned int srcCount
, XMLCh* const toFill
, const unsigned int maxChars
, unsigned int& bytesEaten)
{
//
// For this one, because we have to maintain the offset table, we have
// to do them one char at a time until we run out of source data.
//
unsigned int countIn = 0;
unsigned int countOut = 0;
while (countOut < maxChars)
{
wchar_t oneWideChar;
const int bytesEaten =
::mbtowc(&oneWideChar, &srcData[countIn], srcCount - countIn);
// We are done, so break out
if (bytesEaten == -1)
break;
toFill[countOut] = (XMLCh) oneWideChar;
countIn += (unsigned int) bytesEaten;
countOut++;
}
// Give back the counts of eaten and transcoded
bytesEaten = countIn;
return countOut;
}
<commit_msg>Fixed incorrect comparision of int with a pointer. Got burnt because definition of NULL varies on different platforms, though use of NULL was not correct in the first place.<commit_after>/*
* The Apache Software License, Version 1.1
*
* Copyright (c) 1999 The Apache Software Foundation. All rights
* reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
*
* 3. The end-user documentation included with the redistribution,
* if any, must include the following acknowledgment:
* "This product includes software developed by the
* Apache Software Foundation (http://www.apache.org/)."
* Alternately, this acknowledgment may appear in the software itself,
* if and wherever such third-party acknowledgments normally appear.
*
* 4. The names "Xerces" and "Apache Software Foundation" must
* not be used to endorse or promote products derived from this
* software without prior written permission. For written
* permission, please contact apache\@apache.org.
*
* 5. Products derived from this software may not be called "Apache",
* nor may "Apache" appear in their name, without prior written
* permission of the Apache Software Foundation.
*
* THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED
* WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
* OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR
* ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
* USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
* OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation, and was
* originally based on software copyright (c) 1999, International
* Business Machines, Inc., http://www.ibm.com . For more information
* on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*/
/**
* $Log$
* Revision 1.4 1999/12/02 20:20:16 rahulj
* Fixed incorrect comparision of int with a pointer.
Got burnt because definition of NULL varies on different platforms,
though use of NULL was not correct in the first place.
*
* Revision 1.3 1999/11/20 00:28:19 rahulj
* Added code for case-insensitive wide character string compares
*
* Revision 1.2 1999/11/17 21:52:49 abagchi
* Changed wcscasecmp() to wcscmp() to make it work on Solaris and AIX
* PR:
* Obtained from:
* Submitted by:
* Reviewed by:
*
* Revision 1.1.1.1 1999/11/09 01:06:10 twl
* Initial checkin
*
* Revision 1.7 1999/11/08 20:45:34 rahul
* Swat for adding in Product name and CVS comment log variable.
*
*/
// ---------------------------------------------------------------------------
// Includes
// ---------------------------------------------------------------------------
#include "IconvTransService.hpp"
#include <wchar.h>
#if defined (XML_GNUG)
#include <wctype.h>
#endif
#include <string.h>
#include <stdlib.h>
#include <stdio.h>
static const int gTempBuffArraySize = 1024;
static unsigned int getWideCharLength(const XMLCh* const src)
{
if (!src)
return 0;
unsigned int len = 0;
const XMLCh* pTmp = src;
while (*pTmp++)
len++;
return len;
}
// ---------------------------------------------------------------------------
// IconvTransService: Constructors and Destructor
// ---------------------------------------------------------------------------
IconvTransService::IconvTransService()
{
}
IconvTransService::~IconvTransService()
{
}
// ---------------------------------------------------------------------------
// IconvTransService: The virtual transcoding service API
// ---------------------------------------------------------------------------
int IconvTransService::compareIString( const XMLCh* const comp1
, const XMLCh* const comp2)
{
const XMLCh* cptr1 = comp1;
const XMLCh* cptr2 = comp2;
while ((*cptr1 != 0) && (*cptr2 != 0))
{
wint_t wch1 = towupper(*cptr1);
wint_t wch2 = towupper(*cptr2);
if (wch1 < wch2)
return -1;
if (wch1 > wch2)
return 1;
cptr1++;
cptr2++;
}
return 0;
}
int IconvTransService::compareNIString( const XMLCh* const comp1
, const XMLCh* const comp2
, const unsigned int maxChars)
{
const XMLCh* cptr1 = comp1;
const XMLCh* cptr2 = comp2;
unsigned int n = 0;
while ((*cptr1 != 0) && (*cptr2 != 0) && (n < maxChars))
{
wint_t wch1 = towupper(*cptr1);
wint_t wch2 = towupper(*cptr2);
if (wch1 < wch2)
return -1;
if (wch1 > wch2)
return 1;
cptr1++;
cptr2++;
n++;
}
return 0;
}
bool IconvTransService::isSpace(const XMLCh toCheck) const
{
return (iswspace(toCheck) != 0);
}
XMLTranscoder* IconvTransService::makeNewDefTranscoder()
{
// Just allocate a new transcoder of our type
return new IconvTranscoder;
}
XMLTranscoder*
IconvTransService::makeNewTranscoderFor(const XMLCh* const encodingName
, XMLTransService::Codes& resValue
, const unsigned int )
{
//
// NOTE: We don't use the block size here
//
//
// This is a minimalist transcoding service, that only supports a local
// default transcoder. All named encodings return zero as a failure,
// which means that only the intrinsic encodings supported by the parser
// itself will work for XML data.
//
resValue = XMLTransService::UnsupportedEncoding;
return 0;
}
// ---------------------------------------------------------------------------
// IconvTranscoder: Constructors and Destructor
// ---------------------------------------------------------------------------
IconvTranscoder::IconvTranscoder()
{
}
IconvTranscoder::~IconvTranscoder()
{
}
// ---------------------------------------------------------------------------
// IconvTranscoder: The virtual transcoder API
// ---------------------------------------------------------------------------
unsigned int IconvTranscoder::calcRequiredSize(const char* const srcText)
{
if (!srcText)
return 0;
const unsigned int retVal = ::mbstowcs(NULL, srcText, 0);
if (retVal == -1)
return 0;
return retVal;
}
unsigned int IconvTranscoder::calcRequiredSize(const XMLCh* const srcText)
{
if (!srcText)
return 0;
unsigned int wLent = getWideCharLength(srcText);
wchar_t tmpWideCharArr[gTempBuffArraySize];
wchar_t* allocatedArray = 0;
wchar_t* wideCharBuf = 0;
if (wLent >= gTempBuffArraySize)
wideCharBuf = allocatedArray = new wchar_t[wLent + 1];
else
wideCharBuf = tmpWideCharArr;
for (unsigned int i = 0; i < wLent; i++)
{
wideCharBuf[i] = srcText[i];
}
wideCharBuf[wLent] = 0x00;
const unsigned int retVal = ::wcstombs(NULL, wideCharBuf, 0);
delete [] allocatedArray;
if (retVal == -1)
return 0;
return retVal;
}
XMLCh IconvTranscoder::transcodeOne(const char* const srcData
, const unsigned int srcBytes
, unsigned int& bytesEaten)
{
wchar_t toFill;
int eaten = ::mbtowc(&toFill, srcData, srcBytes);
if (eaten == -1)
{
bytesEaten = 0;
return 0;
}
// Return the bytes we ate and the resulting char.
bytesEaten = eaten;
return toFill;
}
char* IconvTranscoder::transcode(const XMLCh* const toTranscode)
{
if (!toTranscode)
return 0;
char* retVal = 0;
if (toTranscode)
{
unsigned int wLent = getWideCharLength(toTranscode);
wchar_t tmpWideCharArr[gTempBuffArraySize];
wchar_t* allocatedArray = 0;
wchar_t* wideCharBuf = 0;
if (wLent >= gTempBuffArraySize)
wideCharBuf = allocatedArray = new wchar_t[wLent + 1];
else
wideCharBuf = tmpWideCharArr;
for (unsigned int i = 0; i < wLent; i++)
{
wideCharBuf[i] = toTranscode[i];
}
wideCharBuf[wLent] = 0x00;
// Calc the needed size.
const size_t neededLen = ::wcstombs(NULL, wideCharBuf, 0);
if (neededLen == 0)
{
delete [] allocatedArray;
return 0;
}
retVal = new char[neededLen + 1];
::wcstombs(retVal, wideCharBuf, neededLen);
retVal[neededLen] = 0;
delete [] allocatedArray;
}
else
{
retVal = new char[1];
retVal[0] = 0;
}
return retVal;
}
bool IconvTranscoder::transcode(const XMLCh* const toTranscode
, char* const toFill
, const unsigned int maxBytes)
{
// Watch for a couple of pyscho corner cases
if (!toTranscode || !maxBytes)
{
toFill[0] = 0;
return true;
}
if (!*toTranscode)
{
toFill[0] = 0;
return true;
}
wchar_t tmpWideCharArr[gTempBuffArraySize];
wchar_t* allocatedArray = 0;
wchar_t* wideCharBuf = 0;
if (maxBytes >= gTempBuffArraySize)
wideCharBuf = allocatedArray = new wchar_t[maxBytes + 1];
else
wideCharBuf = tmpWideCharArr;
for (unsigned int i = 0; i < maxBytes; i++)
{
wideCharBuf[i] = toTranscode[i];
}
wideCharBuf[maxBytes] = 0x00;
// Ok, go ahead and try the transcoding. If it fails, then ...
//
if (::wcstombs(toFill, wideCharBuf, maxBytes) == -1)
{
delete [] allocatedArray;
return false;
}
// Cap it off just in case
toFill[maxBytes] = 0;
delete [] allocatedArray;
return true;
}
XMLCh* IconvTranscoder::transcode(const char* const toTranscode)
{
XMLCh* retVal = 0;
if (toTranscode)
{
const unsigned int len = calcRequiredSize(toTranscode);
if (len == 0)
return 0;
wchar_t tmpWideCharArr[gTempBuffArraySize];
wchar_t* allocatedArray = 0;
wchar_t* wideCharBuf = 0;
if (len >= gTempBuffArraySize)
wideCharBuf = allocatedArray = new wchar_t[len + 1];
else
wideCharBuf = tmpWideCharArr;
::mbstowcs(wideCharBuf, toTranscode, len);
retVal = new XMLCh[len + 1];
for (unsigned int i = 0; i < len; i++)
{
retVal[i] = (XMLCh) wideCharBuf[i];
}
retVal[len] = 0x00;
delete [] allocatedArray;
}
else
{
retVal = new XMLCh[1];
retVal[0] = 0;
}
return retVal;
}
bool IconvTranscoder::transcode(const char* const toTranscode
, XMLCh* const toFill
, const unsigned int maxChars)
{
// Check for a couple of psycho corner cases
if (!toTranscode || !maxChars)
{
toFill[0] = 0;
return true;
}
if (!*toTranscode)
{
toFill[0] = 0;
return true;
}
wchar_t tmpWideCharArr[gTempBuffArraySize];
wchar_t* allocatedArray = 0;
wchar_t* wideCharBuf = 0;
if (maxChars >= gTempBuffArraySize)
wideCharBuf = allocatedArray = new wchar_t[maxChars + 1];
else
wideCharBuf = tmpWideCharArr;
if (::mbstowcs(wideCharBuf, toTranscode, maxChars) == -1)
{
delete [] allocatedArray;
return false;
}
for (unsigned int i = 0; i < maxChars; i++)
{
toFill[i] = (XMLCh) wideCharBuf[i];
}
toFill[maxChars] = 0x00;
delete [] allocatedArray;
return true;
}
unsigned int
IconvTranscoder::transcodeXML( const char* const srcData
, const unsigned int srcCount
, XMLCh* const toFill
, const unsigned int maxChars
, unsigned int& bytesEaten)
{
//
// For this one, because we have to maintain the offset table, we have
// to do them one char at a time until we run out of source data.
//
unsigned int countIn = 0;
unsigned int countOut = 0;
while (countOut < maxChars)
{
wchar_t oneWideChar;
const int bytesEaten =
::mbtowc(&oneWideChar, &srcData[countIn], srcCount - countIn);
// We are done, so break out
if (bytesEaten == -1)
break;
toFill[countOut] = (XMLCh) oneWideChar;
countIn += (unsigned int) bytesEaten;
countOut++;
}
// Give back the counts of eaten and transcoded
bytesEaten = countIn;
return countOut;
}
<|endoftext|> |
<commit_before>##var callbackType
##var callbackParam
##ifneq($(operation.params.$count),0)
/// ######### deserialize request ###########
##ifneq($(operation.params.$count)-$(operation.params.param.dataType.name),1-MessageContext)
NGREST_ASSERT(context->request->node, "Request expected for $(service.serviceNsName)/$(operation.name)");
NGREST_ASSERT_PARAM(context->request->node->type == ::ngrest::NodeType::Object);
const ::ngrest::Object* request = static_cast<const ::ngrest::Object*>(context->request->node);
##endif
######### parameters ###########
\
######### deserialize request parameters ###########
##foreach $(operation.params)
\
##ifneq($(param.dataType.name),Callback||MessageContext)
$(param.dataType.nsName) $(param.name);
##endif
##endfor
##foreach $(operation.params)
\
##switch $(param.dataType.type)
\
##case generic||string
##ifneq($(param.dataType.name),MessageContext)
::ngrest::ObjectModelUtils::getChildValue(request, "$(param.name)", $(param.name));
##endif
##case enum
$(param.name) = $(param.dataType.ns)$(param.dataType.name.!replace/::/Serializer::/)Serializer::fromCString(::ngrest::ObjectModelUtils::getChildValue(request, "$(param.name)"));
##case struct
const ::ngrest::NamedNode* $(param.name)Obj = ::ngrest::ObjectModelUtils::getNamedChild(request, "$(param.name)", ::ngrest::NodeType::Object);
$(param.dataType.ns)$(param.dataType.name.!replace/::/Serializer::/)Serializer::deserialize($(param.name)Obj->node, $(param.name));
### we dont know typedef type here, so take any
##case typedef
const ::ngrest::NamedNode* $(param.name)Obj = ::ngrest::ObjectModelUtils::getNamedChild(request, "$(param.name)");
$(param.dataType.ns)$(param.dataType.name.!replace/::/Serializer::/)Serializer::deserialize($(param.name)Obj->node, $(param.name));
##case template
\
// count = $(param.dataType.templateParams.$count)
##switch $(param.dataType.name)
\
### /// Callback for asynchronous operations
##case Callback
##ifneq($($callbackType),)
##error More than one callback defined for $(service.name)/$(operation.name)
##endif
##ifneq($(operation.return),void)
##error Return type of asynchronous operation must be void: $(service.name)/$(operation.name)
##endif
##var callbackType $(param.dataType.templateParams.templateParam1)
##var callbackParam $(param.name)
### /// list
##case vector||list
const ::ngrest::NamedNode* $(param.name)Node = ::ngrest::ObjectModelUtils::getNamedChild(request, "$(param.name)", ::ngrest::NodeType::Array);
for (const ::ngrest::LinkedNode* $(param.name)Child = static_cast<const ::ngrest::Array*>($(param.name)Node->node)->firstChild; $(param.name)Child; $(param.name)Child = $(param.name)Child->nextSibling) {
##ifneq($(param.dataType.templateParams.templateParam1.type),generic||enum)
$(param.name).push_back($(param.dataType.templateParams.templateParam1.nsName)());
$(param.dataType.templateParams.templateParam1.nsName)& $(param.name)Item = $(param.name).back();
##else
$(param.dataType.templateParams.templateParam1.nsName) $(param.name)Item;
##endif
\
##context $(param.dataType.templateParams.templateParam1)
##pushvars
##var var $(param.name)Item
##var node $(param.name)Child->node
##var name $(param.name)Item
##indent +2
##include <common/deserialization.cpp>
##indent -2
##popvars
##endcontext
\
##ifeq($(param.dataType.templateParams.templateParam1.type),generic||enum)
$(param.name).push_back($(param.name)Item);
##endif
}
\
### /// map
##case map||unordered_map
const ::ngrest::NamedNode* $(param.name)Node = ::ngrest::ObjectModelUtils::getNamedChild(request, "$(param.name)", ::ngrest::NodeType::Object);
for (const ::ngrest::NamedNode* $(param.name)Child = static_cast<const ::ngrest::Object*>($(param.name)Node->node)->firstChild; $(param.name)Child; $(param.name)Child = $(param.name)Child->nextSibling) {
NGREST_ASSERT_NULL($(param.name)Child->name);
##switch $(param.dataType.templateParams.templateParam1.type)
##case generic
$(param.dataType.templateParams.templateParam1.nsName) $(param.name)Key;
NGREST_ASSERT(::ngrest::fromCString($(param.name)Child->name, $(param.name)Key), "Cannot deserialize key of $(param.name)");
##case enum
$(param.dataType.templateParams.templateParam1.nsName) $(param.name)Key = $(param.dataType.templateParams.templateParam1.nsName)Serializer::fromCString($(param.name)Child->name);
##case string
// inline $(param.name)Child->name
##default
##error Cannot deserialize $(param.dataType.templateParams.templateParam1.nsName) as map key
##endswitch
$(param.dataType.templateParams.templateParam2.nsName)& $(param.name)Value = $(param.name)\
##ifeq($(param.dataType.templateParams.templateParam1.type),string)
[$(param.name)Child->name];
##else
[$(param.name)Key];
##endif
\
##context $(param.dataType.templateParams.templateParam2)
##pushvars
##var var $(param.name)Value
##var node $(param.name)Child->node
##var name $(param.name)Value
##indent +2
##include <common/deserialization.cpp>
##indent -2
##popvars
##endcontext
\
}
\
##case Nullable
##context $(param.dataType.templateParams.templateParam1)
##pushvars
##var name $(param.name)
##var node namedNode$($name)->node
const ::ngrest::NamedNode* namedNode$($name) = request->findChildByName("$(param.name)");
if (namedNode$($name) != nullptr && namedNode$($name)->node != nullptr) {
##ifeq($(.type),generic||string||enum)
##var var $(param.name).get()
##else
##var var $(param.name)Nullable
$(.nsName)& $($var) = $(param.name).get();
##endif
##indent +2
##include <common/deserialization.cpp>
##indent -2
}
##popvars
##endcontext
### /// unsupported
##default
##error Deserialization of template type $(param.dataType.nsName) is not supported
### /// end of template
##endswitch
\
##default
##error Deserialization of type is not supported: $(param): $(param.dataType.type) :: $(param.dataType) :: $(operation.name)
##endswitch
\
##endfor
/// ######### deserialize request end ###########
##endif // parameters count
<commit_msg>Don't generate code to parse request, if only Callback is passed as argument (fixes #30)<commit_after>##var callbackType
##var callbackParam
##ifneq($(operation.params.$count),0)
/// ######### deserialize request ###########
##ifneq($(operation.params.$count)-$(operation.params.param.dataType.name),1-MessageContext||1-Callback)
NGREST_ASSERT(context->request->node, "Request expected for $(service.serviceNsName)/$(operation.name)");
NGREST_ASSERT_PARAM(context->request->node->type == ::ngrest::NodeType::Object);
const ::ngrest::Object* request = static_cast<const ::ngrest::Object*>(context->request->node);
##endif
######### parameters ###########
\
######### deserialize request parameters ###########
##foreach $(operation.params)
\
##ifneq($(param.dataType.name),Callback||MessageContext)
$(param.dataType.nsName) $(param.name);
##endif
##endfor
##foreach $(operation.params)
\
##switch $(param.dataType.type)
\
##case generic||string
##ifneq($(param.dataType.name),MessageContext)
::ngrest::ObjectModelUtils::getChildValue(request, "$(param.name)", $(param.name));
##endif
##case enum
$(param.name) = $(param.dataType.ns)$(param.dataType.name.!replace/::/Serializer::/)Serializer::fromCString(::ngrest::ObjectModelUtils::getChildValue(request, "$(param.name)"));
##case struct
const ::ngrest::NamedNode* $(param.name)Obj = ::ngrest::ObjectModelUtils::getNamedChild(request, "$(param.name)", ::ngrest::NodeType::Object);
$(param.dataType.ns)$(param.dataType.name.!replace/::/Serializer::/)Serializer::deserialize($(param.name)Obj->node, $(param.name));
### we dont know typedef type here, so take any
##case typedef
const ::ngrest::NamedNode* $(param.name)Obj = ::ngrest::ObjectModelUtils::getNamedChild(request, "$(param.name)");
$(param.dataType.ns)$(param.dataType.name.!replace/::/Serializer::/)Serializer::deserialize($(param.name)Obj->node, $(param.name));
##case template
\
// count = $(param.dataType.templateParams.$count)
##switch $(param.dataType.name)
\
### /// Callback for asynchronous operations
##case Callback
##ifneq($($callbackType),)
##error More than one callback defined for $(service.name)/$(operation.name)
##endif
##ifneq($(operation.return),void)
##error Return type of asynchronous operation must be void: $(service.name)/$(operation.name)
##endif
##var callbackType $(param.dataType.templateParams.templateParam1)
##var callbackParam $(param.name)
### /// list
##case vector||list
const ::ngrest::NamedNode* $(param.name)Node = ::ngrest::ObjectModelUtils::getNamedChild(request, "$(param.name)", ::ngrest::NodeType::Array);
for (const ::ngrest::LinkedNode* $(param.name)Child = static_cast<const ::ngrest::Array*>($(param.name)Node->node)->firstChild; $(param.name)Child; $(param.name)Child = $(param.name)Child->nextSibling) {
##ifneq($(param.dataType.templateParams.templateParam1.type),generic||enum)
$(param.name).push_back($(param.dataType.templateParams.templateParam1.nsName)());
$(param.dataType.templateParams.templateParam1.nsName)& $(param.name)Item = $(param.name).back();
##else
$(param.dataType.templateParams.templateParam1.nsName) $(param.name)Item;
##endif
\
##context $(param.dataType.templateParams.templateParam1)
##pushvars
##var var $(param.name)Item
##var node $(param.name)Child->node
##var name $(param.name)Item
##indent +2
##include <common/deserialization.cpp>
##indent -2
##popvars
##endcontext
\
##ifeq($(param.dataType.templateParams.templateParam1.type),generic||enum)
$(param.name).push_back($(param.name)Item);
##endif
}
\
### /// map
##case map||unordered_map
const ::ngrest::NamedNode* $(param.name)Node = ::ngrest::ObjectModelUtils::getNamedChild(request, "$(param.name)", ::ngrest::NodeType::Object);
for (const ::ngrest::NamedNode* $(param.name)Child = static_cast<const ::ngrest::Object*>($(param.name)Node->node)->firstChild; $(param.name)Child; $(param.name)Child = $(param.name)Child->nextSibling) {
NGREST_ASSERT_NULL($(param.name)Child->name);
##switch $(param.dataType.templateParams.templateParam1.type)
##case generic
$(param.dataType.templateParams.templateParam1.nsName) $(param.name)Key;
NGREST_ASSERT(::ngrest::fromCString($(param.name)Child->name, $(param.name)Key), "Cannot deserialize key of $(param.name)");
##case enum
$(param.dataType.templateParams.templateParam1.nsName) $(param.name)Key = $(param.dataType.templateParams.templateParam1.nsName)Serializer::fromCString($(param.name)Child->name);
##case string
// inline $(param.name)Child->name
##default
##error Cannot deserialize $(param.dataType.templateParams.templateParam1.nsName) as map key
##endswitch
$(param.dataType.templateParams.templateParam2.nsName)& $(param.name)Value = $(param.name)\
##ifeq($(param.dataType.templateParams.templateParam1.type),string)
[$(param.name)Child->name];
##else
[$(param.name)Key];
##endif
\
##context $(param.dataType.templateParams.templateParam2)
##pushvars
##var var $(param.name)Value
##var node $(param.name)Child->node
##var name $(param.name)Value
##indent +2
##include <common/deserialization.cpp>
##indent -2
##popvars
##endcontext
\
}
\
##case Nullable
##context $(param.dataType.templateParams.templateParam1)
##pushvars
##var name $(param.name)
##var node namedNode$($name)->node
const ::ngrest::NamedNode* namedNode$($name) = request->findChildByName("$(param.name)");
if (namedNode$($name) != nullptr && namedNode$($name)->node != nullptr) {
##ifeq($(.type),generic||string||enum)
##var var $(param.name).get()
##else
##var var $(param.name)Nullable
$(.nsName)& $($var) = $(param.name).get();
##endif
##indent +2
##include <common/deserialization.cpp>
##indent -2
}
##popvars
##endcontext
### /// unsupported
##default
##error Deserialization of template type $(param.dataType.nsName) is not supported
### /// end of template
##endswitch
\
##default
##error Deserialization of type is not supported: $(param): $(param.dataType.type) :: $(param.dataType) :: $(operation.name)
##endswitch
\
##endfor
/// ######### deserialize request end ###########
##endif // parameters count
<|endoftext|> |
<commit_before>/* Copyright 2016 Stanford University
*
* 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 <cstdio>
#include <cassert>
#include <cstdlib>
#include "legion.h"
using namespace Legion;
/*
* To illustrate task launches and futures in Legion
* we implement a program to compute the first N
* Fibonacci numbers. While we note that this is not
* the fastest way to compute Fibonacci numbers, it
* is designed to showcase the functional nature of
* Legion tasks and futures.
*/
enum TaskIDs {
TOP_LEVEL_TASK_ID,
FIBONACCI_TASK_ID,
SUM_TASK_ID,
};
void top_level_task(const Task *task,
const std::vector<PhysicalRegion> ®ions,
Context ctx, Runtime *runtime)
{
int num_fibonacci = 7;
// The command line arguments to a Legion application are
// available through the runtime 'get_input_args' call. We'll
// use this to get the number of Fibonacci numbers to compute.
const InputArgs &command_args = Runtime::get_input_args();
for (int i = 1; i < command_args.argc; i++) {
if (command_args.argv[i][0] == '-') {
i++;
continue;
}
num_fibonacci = atoi(command_args.argv[i]);
assert(num_fibonacci >= 0);
break;
}
printf("Computing the first %d Fibonacci numbers...\n", num_fibonacci);
// This is a vector which we'll use to store the future
// results of all the tasks that we launch. The goal here
// is to launch all of our tasks up front to get them in
// flight before waiting on a future value. This exposes
// as many tasks as possible to the Legion runtime to
// maximize performance.
std::vector<Future> fib_results;
// Compute the first num_fibonacci numbers
for (int i = 0; i < num_fibonacci; i++)
{
// All Legion tasks are spawned from a launcher object. A
// 'TaskLauncher' is a struct used for specifying the arguments
// necessary for launching a task. Launchers contain many
// fields which we will explore throughout the examples. Here
// we look at the first two arguments: the ID of the kind of
// task to launch and a 'TaskArgument'. The ID of the task
// must correspond to one of the IDs registered with the Legion
// runtime before the application began. A 'TaskArgument' points
// to a buffer and specifies the size in bytes to copy by value
// from the buffer. It is important to note that this buffer is
// not actually copied until 'execute_task' is called. The buffer
// should remain live until the launcher goes out of scope.
TaskLauncher launcher(FIBONACCI_TASK_ID, TaskArgument(&i,sizeof(i)));
// To launch a task, a TaskLauncher object is passed to the runtime
// along with the context. Legion tasks are asynchronous which means
// that this call returns immediately and returns a future value which
// we store in our vector of future results. Note that launchers can
// be reused to launch as many tasks as desired, and can be modified
// immediately after the 'execute_task' call returns.
fib_results.push_back(runtime->execute_task(ctx, launcher));
}
// Print out our results
for (int i = 0; i < num_fibonacci; i++)
{
// One way to use a future is to explicitly ask for its value using
// the 'get_result' method. This is a blocking call which will cause
// this task (the top-level task) to pause until the sub-task which
// is generating the future returns. Note that waiting on a future
// that is not ready blocks this task, but does not block the processor
// on which the task is running. If additional tasks have been mapped
// onto this processor and they are ready to execute, then they will
// begin running as soon as the call to 'get_result' is made.
//
// The 'get_result' method is templated on the type of the return
// value which tells the Legion runtime how to interpret the bits
// being returned. In most cases the bits are cast, however, if
// the type passed in the template has the methods 'legion_buffer_size',
// 'legion_serialize', and 'legion_deserialize' defined, then Legion
// automatically supports deep copies of more complex types (see the
// ColoringSerializer class in legion.h for an example). While this
// way of using features requires blocking this task, we examine a
// non-blocking way of using future below.
int result = fib_results[i].get_result<int>();
printf("Fibonacci(%d) = %d\n", i, result);
}
// Implementation detail for those who are interested: since futures
// are shared between the runtime and the application, we reference
// count them and automatically delete their resources when there
// are no longer any references to them. The 'Future' type is
// actually a light-weight handle which simply contains a pointer
// to the actual future implementation, so copying future values
// around is inexpensive. Here we explicitly clear the vector
// which invokes the Future destructor and removes the references.
// This would have happened anyway when the vector went out of
// scope, but we have the statement so we could put this comment here.
fib_results.clear();
}
int fibonacci_task(const Task *task,
const std::vector<PhysicalRegion> ®ions,
Context ctx, Runtime *runtime)
{
// The 'TaskArgument' value passed to a task and its size
// in bytes is available in the 'args' and 'arglen' fields
// on the 'Task' object.
//
// Since there is no type checking when writing to
// the runtime API (a benefit provided by our Legion compiler)
// we encourage programmers to check that they are getting
// what they expect in their values.
assert(task->arglen == sizeof(int));
int fib_num = *(const int*)task->args;
// Fibonacci base cases
// Note that tasks return values the same as C functions.
// If a task is running remotely from its parent task then
// Legion automatically packages up the result and returns
// it to the origin location.
if (fib_num == 0)
return 0;
if (fib_num == 1)
return 1;
// Launch fib-1
const int fib1 = fib_num-1;
TaskLauncher t1(FIBONACCI_TASK_ID, TaskArgument(&fib1,sizeof(fib1)));
Future f1 = runtime->execute_task(ctx, t1);
// Launch fib-2
const int fib2 = fib_num-2;
TaskLauncher t2(FIBONACCI_TASK_ID, TaskArgument(&fib2,sizeof(fib2)));
Future f2 = runtime->execute_task(ctx, t2);
// Here will illustrate a non-blocking way of using a future.
// Rather than waiting for the values and passing the results
// directly to the summation task, we instead pass the futures
// through the TaskLauncher object. Legion then will
// ensure that the sum task does not begin until both futures
// are ready and that the future values are available wherever
// the sum task is run (even if it is run remotely). Futures
// should NEVER be passed through a TaskArgument.
TaskLauncher sum(SUM_TASK_ID, TaskArgument(NULL, 0));
sum.add_future(f1);
sum.add_future(f2);
Future result = runtime->execute_task(ctx, sum);
// Our API does not permit returning Futures as the result of
// a task. Any attempt to do so will result in a failed static
// assertion at compile-time. In general, waiting for one or
// more futures at the end of a task is inexpensive since we
// have already exposed the available sub-tasks for execution
// to the Legion runtime so we can extract as much task-level
// parallelism as possible from the application.
return result.get_result<int>();
}
int sum_task(const Task *task,
const std::vector<PhysicalRegion> ®ions,
Context ctx, Runtime *runtime)
{
assert(task->futures.size() == 2);
// Note that even though it looks like we are performing
// blocking calls to get these future results, the
// Legion runtime is smart enough to not run this task
// until all the future values passed through the
// task launcher have completed.
Future f1 = task->futures[0];
int r1 = f1.get_result<int>();
Future f2 = task->futures[1];
int r2 = f2.get_result<int>();
return (r1 + r2);
}
int main(int argc, char **argv)
{
Runtime::set_top_level_task_id(TOP_LEVEL_TASK_ID);
Runtime::register_legion_task<top_level_task>(TOP_LEVEL_TASK_ID,
Processor::LOC_PROC, true/*single*/, false/*index*/);
// Note that tasks which return values must pass the type of
// the return argument as the first template paramenter.
Runtime::register_legion_task<int,fibonacci_task>(FIBONACCI_TASK_ID,
Processor::LOC_PROC, true/*single*/, false/*index*/);
// The sum-task has a very special property which is that it is
// guaranteed never to make any runtime calls. We call these
// kinds of tasks "leaf" tasks and tell the runtime system
// about them using the 'TaskConfigOptions' struct. Being
// a leaf task allows the runtime to perform significant
// optimizations that minimize the overhead of leaf task
// execution. Note that we also tell the runtime to
// automatically generate the variant ID for this task
// with the 'AUTO_GENERATE_ID' argument.
Runtime::register_legion_task<int,sum_task>(SUM_TASK_ID,
Processor::LOC_PROC, true/*single*/, false/*index*/,
AUTO_GENERATE_ID, TaskConfigOptions(true/*leaf*/), "sum_task");
return Runtime::start(argc, argv);
}
<commit_msg>tutorial: add example of get_current_time<commit_after>/* Copyright 2016 Stanford University
*
* 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 <cstdio>
#include <cassert>
#include <cstdlib>
#include "legion.h"
using namespace Legion;
/*
* To illustrate task launches and futures in Legion
* we implement a program to compute the first N
* Fibonacci numbers. While we note that this is not
* the fastest way to compute Fibonacci numbers, it
* is designed to showcase the functional nature of
* Legion tasks and futures.
*/
enum TaskIDs {
TOP_LEVEL_TASK_ID,
FIBONACCI_TASK_ID,
SUM_TASK_ID,
};
void top_level_task(const Task *task,
const std::vector<PhysicalRegion> ®ions,
Context ctx, Runtime *runtime)
{
int num_fibonacci = 7;
// The command line arguments to a Legion application are
// available through the runtime 'get_input_args' call. We'll
// use this to get the number of Fibonacci numbers to compute.
const InputArgs &command_args = Runtime::get_input_args();
for (int i = 1; i < command_args.argc; i++) {
if (command_args.argv[i][0] == '-') {
i++;
continue;
}
num_fibonacci = atoi(command_args.argv[i]);
assert(num_fibonacci >= 0);
break;
}
printf("Computing the first %d Fibonacci numbers...\n", num_fibonacci);
// This is a vector which we'll use to store the future
// results of all the tasks that we launch. The goal here
// is to launch all of our tasks up front to get them in
// flight before waiting on a future value. This exposes
// as many tasks as possible to the Legion runtime to
// maximize performance.
std::vector<Future> fib_results;
// We'll also time how long these tasks take to run. Since
// tasks in Legion execute in a deferred fashion, we ask the
// runtime for the "current_time" for our context, which doesn't
// actually record it until some other Future becomes ready.
// We are given a Future that will hold the timer value once it
// has been recorded so that we can keep issuing more tasks.
Future fib_start_time = runtime->get_current_time(ctx);
std::vector<Future> fib_finish_times;
// Compute the first num_fibonacci numbers
for (int i = 0; i < num_fibonacci; i++)
{
// All Legion tasks are spawned from a launcher object. A
// 'TaskLauncher' is a struct used for specifying the arguments
// necessary for launching a task. Launchers contain many
// fields which we will explore throughout the examples. Here
// we look at the first two arguments: the ID of the kind of
// task to launch and a 'TaskArgument'. The ID of the task
// must correspond to one of the IDs registered with the Legion
// runtime before the application began. A 'TaskArgument' points
// to a buffer and specifies the size in bytes to copy by value
// from the buffer. It is important to note that this buffer is
// not actually copied until 'execute_task' is called. The buffer
// should remain live until the launcher goes out of scope.
TaskLauncher launcher(FIBONACCI_TASK_ID, TaskArgument(&i,sizeof(i)));
// To launch a task, a TaskLauncher object is passed to the runtime
// along with the context. Legion tasks are asynchronous which means
// that this call returns immediately and returns a future value which
// we store in our vector of future results. Note that launchers can
// be reused to launch as many tasks as desired, and can be modified
// immediately after the 'execute_task' call returns.
fib_results.push_back(runtime->execute_task(ctx, launcher));
// We can use the future for the task's result to make sure we record
// the execution time only once that task has finished
fib_finish_times.push_back(runtime->get_current_time(ctx, fib_results.back()));
}
// Print out our results
for (int i = 0; i < num_fibonacci; i++)
{
// One way to use a future is to explicitly ask for its value using
// the 'get_result' method. This is a blocking call which will cause
// this task (the top-level task) to pause until the sub-task which
// is generating the future returns. Note that waiting on a future
// that is not ready blocks this task, but does not block the processor
// on which the task is running. If additional tasks have been mapped
// onto this processor and they are ready to execute, then they will
// begin running as soon as the call to 'get_result' is made.
//
// The 'get_result' method is templated on the type of the return
// value which tells the Legion runtime how to interpret the bits
// being returned. In most cases the bits are cast, however, if
// the type passed in the template has the methods 'legion_buffer_size',
// 'legion_serialize', and 'legion_deserialize' defined, then Legion
// automatically supports deep copies of more complex types (see the
// ColoringSerializer class in legion.h for an example). While this
// way of using features requires blocking this task, we examine a
// non-blocking way of using future below.
int result = fib_results[i].get_result<int>();
// We used 'get_current_time', which returns a double containing the
// number of seconds since the runtime started up.
double elapsed = (fib_finish_times[i].get_result<double>() -
fib_start_time.get_result<double>());
printf("Fibonacci(%d) = %d (elapsed = %.2f s)\n", i, result, elapsed);
}
// Implementation detail for those who are interested: since futures
// are shared between the runtime and the application, we reference
// count them and automatically delete their resources when there
// are no longer any references to them. The 'Future' type is
// actually a light-weight handle which simply contains a pointer
// to the actual future implementation, so copying future values
// around is inexpensive. Here we explicitly clear the vector
// which invokes the Future destructor and removes the references.
// This would have happened anyway when the vector went out of
// scope, but we have the statement so we could put this comment here.
fib_results.clear();
}
int fibonacci_task(const Task *task,
const std::vector<PhysicalRegion> ®ions,
Context ctx, Runtime *runtime)
{
// The 'TaskArgument' value passed to a task and its size
// in bytes is available in the 'args' and 'arglen' fields
// on the 'Task' object.
//
// Since there is no type checking when writing to
// the runtime API (a benefit provided by our Legion compiler)
// we encourage programmers to check that they are getting
// what they expect in their values.
assert(task->arglen == sizeof(int));
int fib_num = *(const int*)task->args;
// Fibonacci base cases
// Note that tasks return values the same as C functions.
// If a task is running remotely from its parent task then
// Legion automatically packages up the result and returns
// it to the origin location.
if (fib_num == 0)
return 0;
if (fib_num == 1)
return 1;
// Launch fib-1
const int fib1 = fib_num-1;
TaskLauncher t1(FIBONACCI_TASK_ID, TaskArgument(&fib1,sizeof(fib1)));
Future f1 = runtime->execute_task(ctx, t1);
// Launch fib-2
const int fib2 = fib_num-2;
TaskLauncher t2(FIBONACCI_TASK_ID, TaskArgument(&fib2,sizeof(fib2)));
Future f2 = runtime->execute_task(ctx, t2);
// Here will illustrate a non-blocking way of using a future.
// Rather than waiting for the values and passing the results
// directly to the summation task, we instead pass the futures
// through the TaskLauncher object. Legion then will
// ensure that the sum task does not begin until both futures
// are ready and that the future values are available wherever
// the sum task is run (even if it is run remotely). Futures
// should NEVER be passed through a TaskArgument.
TaskLauncher sum(SUM_TASK_ID, TaskArgument(NULL, 0));
sum.add_future(f1);
sum.add_future(f2);
Future result = runtime->execute_task(ctx, sum);
// Our API does not permit returning Futures as the result of
// a task. Any attempt to do so will result in a failed static
// assertion at compile-time. In general, waiting for one or
// more futures at the end of a task is inexpensive since we
// have already exposed the available sub-tasks for execution
// to the Legion runtime so we can extract as much task-level
// parallelism as possible from the application.
return result.get_result<int>();
}
int sum_task(const Task *task,
const std::vector<PhysicalRegion> ®ions,
Context ctx, Runtime *runtime)
{
assert(task->futures.size() == 2);
// Note that even though it looks like we are performing
// blocking calls to get these future results, the
// Legion runtime is smart enough to not run this task
// until all the future values passed through the
// task launcher have completed.
Future f1 = task->futures[0];
int r1 = f1.get_result<int>();
Future f2 = task->futures[1];
int r2 = f2.get_result<int>();
return (r1 + r2);
}
int main(int argc, char **argv)
{
Runtime::set_top_level_task_id(TOP_LEVEL_TASK_ID);
Runtime::register_legion_task<top_level_task>(TOP_LEVEL_TASK_ID,
Processor::LOC_PROC, true/*single*/, false/*index*/);
// Note that tasks which return values must pass the type of
// the return argument as the first template paramenter.
Runtime::register_legion_task<int,fibonacci_task>(FIBONACCI_TASK_ID,
Processor::LOC_PROC, true/*single*/, false/*index*/);
// The sum-task has a very special property which is that it is
// guaranteed never to make any runtime calls. We call these
// kinds of tasks "leaf" tasks and tell the runtime system
// about them using the 'TaskConfigOptions' struct. Being
// a leaf task allows the runtime to perform significant
// optimizations that minimize the overhead of leaf task
// execution. Note that we also tell the runtime to
// automatically generate the variant ID for this task
// with the 'AUTO_GENERATE_ID' argument.
Runtime::register_legion_task<int,sum_task>(SUM_TASK_ID,
Processor::LOC_PROC, true/*single*/, false/*index*/,
AUTO_GENERATE_ID, TaskConfigOptions(true/*leaf*/), "sum_task");
return Runtime::start(argc, argv);
}
<|endoftext|> |
<commit_before>/*
This tutorial shows how to write a simple matrix multiplication (C = A * B)
for i = 0 .. N
for j = 0 .. N
C[i,j] = 0;
for k = 0 .. N
C[i,j] = C[i,j] + A[i,k] * B[k,j];
To run this tutorial
cd build/
make run_developers_tutorial_04A
*/
#include <tiramisu/tiramisu.h>
#define SIZE0 1000
using namespace tiramisu;
int main(int argc, char **argv)
{
tiramisu::init("matmul");
// -------------------------------------------------------
// Layer I
// -------------------------------------------------------
constant p0("N", expr((int32_t) SIZE0));
var i("i", 0, p0), j("j", 0, p0), k("k", 0, p0);
// Declare computations that represents the input buffers (b_A and b_B)
input c_A({i, j}, p_uint8);
input c_B({i, j}, p_uint8);
// Declare a computation to initialize the reduction c[i,j]
computation C_init({i,j}, expr((uint8_t) 0));
// Declare the reduction operation.
computation c_C({i,j,k}, p_uint8);
// Note that the previous computation has an empty expression (because we can only use c_C in an expression after its declaration)
c_C.set_expression(c_C(i, j, k - 1) + c_A(i, k) * c_B(k, j));
// In this example, c_C does not read the value of C_init, but later
// we indicate that C_init and c_C both are stored in the same buffer,
// therefore c_C will read values written by C_init.
// We are working on adding an operator for reduction to perform reduction
// in a straight forward way.
// -------------------------------------------------------
// Layer II
// -------------------------------------------------------
// Tile both computations: C_init and c_C
// This tiles the loop levels i and j and produces the loop levels by a 32x32 tile.
// i0, j0, i1 and j1 where i0 is the outermost loop level and j1 is the innermost.
var i0("i0"), j0("j0"), i1("i1"), j1("j1");
C_init.tile(i, j, 32, 32, i0, j0, i1, j1);
c_C.tile(i, j, 32, 32, i0, j0, i1, j1);
// Parallelize the outermost loop level i0
c_C.parallelize(i0);
// Indicate that c_C is after C_init at the loop level j0 (this means,
// they share the two outermost loops i0 and j0 and starting from j0 c_C
// is ordered after C_init).
c_C.after(C_init, j0);
// -------------------------------------------------------
// Layer III
// -------------------------------------------------------
// Declare the buffers.
buffer b_A("b_A", {expr(SIZE0), expr(SIZE0)}, p_uint8, a_input);
buffer b_B("b_B", {expr(SIZE0), expr(SIZE0)}, p_uint8, a_input);
buffer b_C("b_C", {expr(SIZE0), expr(SIZE0)}, p_uint8, a_output);
// Map the computations to a buffer.
c_A.store_in(&b_A);
c_B.store_in(&b_B);
// Store C_init[i,j,k] in b_C[i,j]
C_init.store_in(&b_C, {i,j});
// Store c_C[i,j,k] in b_C[i,j]
c_C.store_in(&b_C, {i,j});
// Note that both of the computations C_init and c_C store their
// results in the buffer b_C.
// -------------------------------------------------------
// Code Generation
// -------------------------------------------------------
tiramisu::codegen({&b_A, &b_B, &b_C}, "build/generated_fct_developers_tutorial_04A.o");
return 0;
}
<commit_msg>Update tutorial_04A.cpp<commit_after>/*
This tutorial shows how to write a simple matrix multiplication (C = A * B)
for i = 0 .. N
for j = 0 .. N
C[i,j] = 0;
for k = 0 .. N
C[i,j] = C[i,j] + A[i,k] * B[k,j];
To run this tutorial
cd build/
make run_developers_tutorial_04A
*/
#include <tiramisu/tiramisu.h>
#define SIZE0 1000
using namespace tiramisu;
int main(int argc, char **argv)
{
tiramisu::init("matmul");
// -------------------------------------------------------
// Layer I
// -------------------------------------------------------
constant p0("N", expr((int32_t) SIZE0));
var i("i", 0, p0), j("j", 0, p0), k("k", 0, p0);
// Declare computations that represents the input buffers (b_A and b_B)
input c_A({i, j}, p_uint8);
input c_B({i, j}, p_uint8);
// Declare a computation to initialize the reduction c[i,j]
computation C_init({i,j}, expr((uint8_t) 0));
// Declare the reduction operation. Do not provide any expression during declaration.
computation c_C({i,j,k}, p_uint8);
// Note that the previous computation has an empty expression (because we can only use c_C in an expression after its declaration)
c_C.set_expression(c_C(i, j, k - 1) + c_A(i, k) * c_B(k, j));
// In this example, c_C does not read the value of C_init, but later
// we indicate that C_init and c_C both are stored in the same buffer,
// therefore c_C will read values written by C_init.
// We are working on adding an operator for reduction to perform reduction
// in a straight forward way.
// -------------------------------------------------------
// Layer II
// -------------------------------------------------------
// Tile both computations: C_init and c_C
// This tiles the loop levels i and j and produces the loop levels by a 32x32 tile.
// i0, j0, i1 and j1 where i0 is the outermost loop level and j1 is the innermost.
var i0("i0"), j0("j0"), i1("i1"), j1("j1");
C_init.tile(i, j, 32, 32, i0, j0, i1, j1);
c_C.tile(i, j, 32, 32, i0, j0, i1, j1);
// Parallelize the outermost loop level i0
c_C.parallelize(i0);
// Indicate that c_C is after C_init at the loop level j0 (this means,
// they share the two outermost loops i0 and j0 and starting from j0 c_C
// is ordered after C_init).
c_C.after(C_init, j0);
// -------------------------------------------------------
// Layer III
// -------------------------------------------------------
// Declare the buffers.
buffer b_A("b_A", {expr(SIZE0), expr(SIZE0)}, p_uint8, a_input);
buffer b_B("b_B", {expr(SIZE0), expr(SIZE0)}, p_uint8, a_input);
buffer b_C("b_C", {expr(SIZE0), expr(SIZE0)}, p_uint8, a_output);
// Map the computations to a buffer.
c_A.store_in(&b_A);
c_B.store_in(&b_B);
// Store C_init[i,j,k] in b_C[i,j]
C_init.store_in(&b_C, {i,j});
// Store c_C[i,j,k] in b_C[i,j]
c_C.store_in(&b_C, {i,j});
// Note that both of the computations C_init and c_C store their
// results in the buffer b_C.
// -------------------------------------------------------
// Code Generation
// -------------------------------------------------------
tiramisu::codegen({&b_A, &b_B, &b_C}, "build/generated_fct_developers_tutorial_04A.o");
return 0;
}
<|endoftext|> |
<commit_before>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: simpleioerrorrequest.cxx,v $
*
* $Revision: 1.8 $
*
* last change: $Author: obo $ $Date: 2006-09-16 17:24:44 $
*
* The Contents of this file are made available subject to
* the terms of GNU Lesser General Public License Version 2.1.
*
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2005 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
************************************************************************/
// MARKER(update_precomp.py): autogen include statement, do not remove
#include "precompiled_ucbhelper.hxx"
#ifndef _COM_SUN_STAR_UCB_INTERACTIVEAUGMENTEDIOEXCEPTION_HPP_
#include <com/sun/star/ucb/InteractiveAugmentedIOException.hpp>
#endif
#ifndef _UCBHELPER_SIMPLEIOERRORREQUEST_HXX
#include <ucbhelper/simpleioerrorrequest.hxx>
#endif
using namespace com::sun::star;
using namespace ucbhelper;
//=========================================================================
SimpleIOErrorRequest::SimpleIOErrorRequest(
const ucb::IOErrorCode eError,
const uno::Sequence< uno::Any > & rArgs,
const rtl::OUString & rMessage,
const uno::Reference< ucb::XCommandProcessor > & xContext )
{
// Fill request...
ucb::InteractiveAugmentedIOException aRequest;
aRequest.Message = rMessage;
aRequest.Context = xContext;
aRequest.Classification = task::InteractionClassification_ERROR;
aRequest.Code = eError;
aRequest.Arguments = rArgs;
setRequest( uno::makeAny( aRequest ) );
// Fill continuations...
uno::Sequence< uno::Reference<
task::XInteractionContinuation > > aContinuations( 1 );
aContinuations[ 0 ] = new InteractionAbort( this );
setContinuations( aContinuations );
}
<commit_msg>INTEGRATION: CWS changefileheader (1.8.70); FILE MERGED 2008/04/01 12:58:51 thb 1.8.70.2: #i85898# Stripping all external header guards 2008/03/31 15:31:36 rt 1.8.70.1: #i87441# Change license header to LPGL v3.<commit_after>/*************************************************************************
*
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* Copyright 2008 by Sun Microsystems, Inc.
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: simpleioerrorrequest.cxx,v $
* $Revision: 1.9 $
*
* This file is part of OpenOffice.org.
*
* OpenOffice.org is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License version 3
* only, as published by the Free Software Foundation.
*
* OpenOffice.org is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License version 3 for more details
* (a copy is included in the LICENSE file that accompanied this code).
*
* You should have received a copy of the GNU Lesser General Public License
* version 3 along with OpenOffice.org. If not, see
* <http://www.openoffice.org/license.html>
* for a copy of the LGPLv3 License.
*
************************************************************************/
// MARKER(update_precomp.py): autogen include statement, do not remove
#include "precompiled_ucbhelper.hxx"
#include <com/sun/star/ucb/InteractiveAugmentedIOException.hpp>
#include <ucbhelper/simpleioerrorrequest.hxx>
using namespace com::sun::star;
using namespace ucbhelper;
//=========================================================================
SimpleIOErrorRequest::SimpleIOErrorRequest(
const ucb::IOErrorCode eError,
const uno::Sequence< uno::Any > & rArgs,
const rtl::OUString & rMessage,
const uno::Reference< ucb::XCommandProcessor > & xContext )
{
// Fill request...
ucb::InteractiveAugmentedIOException aRequest;
aRequest.Message = rMessage;
aRequest.Context = xContext;
aRequest.Classification = task::InteractionClassification_ERROR;
aRequest.Code = eError;
aRequest.Arguments = rArgs;
setRequest( uno::makeAny( aRequest ) );
// Fill continuations...
uno::Sequence< uno::Reference<
task::XInteractionContinuation > > aContinuations( 1 );
aContinuations[ 0 ] = new InteractionAbort( this );
setContinuations( aContinuations );
}
<|endoftext|> |
<commit_before>/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/*
* $Id$
*/
#include <windows.h>
#include <xercesc/util/FileManagers/WindowsFileMgr.hpp>
#include <xercesc/util/Janitor.hpp>
#include <xercesc/util/XMLString.hpp>
#include <xercesc/util/XMLUniDefs.hpp>
XERCES_CPP_NAMESPACE_BEGIN
static bool isBackSlash(XMLCh c) {
return c == chBackSlash ||
c == chYenSign ||
c == chWonSign;
}
WindowsFileMgr::WindowsFileMgr()
{
// Figure out if we are on NT and save that flag for later use
OSVERSIONINFO OSVer;
OSVer.dwOSVersionInfoSize = sizeof(OSVERSIONINFO);
::GetVersionEx(&OSVer);
_onNT = (OSVer.dwPlatformId == VER_PLATFORM_WIN32_NT);
}
WindowsFileMgr::~WindowsFileMgr()
{
}
FileHandle
WindowsFileMgr::fileOpen(const XMLCh* fileName, bool toWrite, MemoryManager* const manager)
{
// Watch for obvious wierdness
if (!fileName)
return 0;
//
// We have to play a little trick here. If its /x:.....
// style fully qualified path, we have to toss the leading /
// character.
//
const XMLCh* nameToOpen = fileName;
if (*fileName == chForwardSlash)
{
if (XMLString::stringLen(fileName) > 3)
{
if (*(fileName + 2) == chColon)
{
const XMLCh chDrive = *(fileName + 1);
if (((chDrive >= chLatin_A) && (chDrive <= chLatin_Z))
|| ((chDrive >= chLatin_a) && (chDrive <= chLatin_z)))
{
nameToOpen = fileName + 1;
}
}
// Similarly for UNC paths
if ( *(fileName + 1) == *(fileName + 2) &&
(*(fileName + 1) == chForwardSlash ||
*(fileName + 1) == chBackSlash) )
{
nameToOpen = fileName + 1;
}
}
}
// Ok, this might look stupid but its a semi-expedient way to deal
// with a thorny problem. Shift-JIS and some other Asian encodings
// are fundamentally broken and map both the backslash and the Yen
// sign to the same code point. Transcoders have to pick one or the
// other to map '\' to Unicode and tend to choose the Yen sign.
//
// Unicode Yen or Won signs as directory separators will fail.
//
// So, we will check this path name for Yen or won signs and, if they are
// there, we'll replace them with slashes.
//
// A further twist: we replace Yen and Won with forward slashes rather
// than back slashes. Either form of slash will work as a directory
// separator. On Win 95 and 98, though, Unicode back-slashes may
// fail to transode back to 8-bit 0x5C with some Unicode converters
// to some of the problematic code pages. Forward slashes always
// transcode correctly back to 8 bit char * form.
//
XMLCh *tmpUName = 0;
const XMLCh* srcPtr = nameToOpen;
while (*srcPtr)
{
if (*srcPtr == chYenSign ||
*srcPtr == chWonSign)
break;
srcPtr++;
}
//
// If we found a yen, then we have to create a temp file name. Else
// go with the file name as is and save the overhead.
//
if (*srcPtr)
{
tmpUName = XMLString::replicate(nameToOpen, manager);
XMLCh* tmpPtr = tmpUName;
while (*tmpPtr)
{
if (*tmpPtr == chYenSign ||
*tmpPtr == chWonSign)
*tmpPtr = chForwardSlash;
tmpPtr++;
}
nameToOpen = tmpUName;
}
FileHandle retVal = 0;
if (_onNT)
{
retVal = ::CreateFileW
(
(LPCWSTR) nameToOpen
, toWrite?GENERIC_WRITE:GENERIC_READ
, FILE_SHARE_READ
, 0
, toWrite?CREATE_ALWAYS:OPEN_EXISTING
, toWrite?FILE_ATTRIBUTE_NORMAL:FILE_FLAG_SEQUENTIAL_SCAN
, 0
);
}
else
{
//
// We are Win 95 / 98. Take the Unicode file name back to (char *)
// so that we can open it.
//
char* tmpName = XMLString::transcode(nameToOpen, manager);
retVal = ::CreateFileA
(
tmpName
, toWrite?GENERIC_WRITE:GENERIC_READ
, FILE_SHARE_READ
, 0
, toWrite?CREATE_ALWAYS:OPEN_EXISTING
, toWrite?FILE_ATTRIBUTE_NORMAL:FILE_FLAG_SEQUENTIAL_SCAN
, 0
);
manager->deallocate(tmpName);//delete [] tmpName;
}
if (tmpUName)
manager->deallocate(tmpUName);//delete [] tmpUName;
if (retVal == INVALID_HANDLE_VALUE)
return 0;
return retVal;
}
FileHandle
WindowsFileMgr::fileOpen(const char* path, bool toWrite, MemoryManager* const manager)
{
XMLCh* tmpFileName = XMLString::transcode(path, manager);
ArrayJanitor<XMLCh> janText(tmpFileName, manager);
return fileOpen(tmpFileName, toWrite, manager);
}
FileHandle
WindowsFileMgr::openStdIn(MemoryManager* const manager)
{
//
// Get the standard input handle. Duplicate it and return that copy
// since the outside world cannot tell the difference and will shut
// down this handle when its done with it. If we gave out the orignal,
// shutting it would prevent any further output.
//
HANDLE stdInOrg = ::GetStdHandle(STD_INPUT_HANDLE);
if (stdInOrg == INVALID_HANDLE_VALUE) {
XMLCh stdinStr[] = {chLatin_s, chLatin_t, chLatin_d, chLatin_i, chLatin_n, chNull};
ThrowXMLwithMemMgr1(XMLPlatformUtilsException, XMLExcepts::File_CouldNotOpenFile, stdinStr, manager);
}
HANDLE retHandle;
if (!::DuplicateHandle
(
::GetCurrentProcess()
, stdInOrg
, ::GetCurrentProcess()
, &retHandle
, 0
, FALSE
, DUPLICATE_SAME_ACCESS))
{
ThrowXMLwithMemMgr(XMLPlatformUtilsException, XMLExcepts::File_CouldNotDupHandle, manager);
}
return retHandle;
}
void
WindowsFileMgr::fileClose(FileHandle f, MemoryManager* const manager)
{
if (!f)
ThrowXMLwithMemMgr(XMLPlatformUtilsException, XMLExcepts::CPtr_PointerIsZero, manager);
if (!::CloseHandle(f))
ThrowXMLwithMemMgr(XMLPlatformUtilsException, XMLExcepts::File_CouldNotCloseFile, manager);
}
void
WindowsFileMgr::fileReset(FileHandle f, MemoryManager* const manager)
{
if (!f)
ThrowXMLwithMemMgr(XMLPlatformUtilsException, XMLExcepts::CPtr_PointerIsZero, manager);
// Seek to the start of the file
if (::SetFilePointer(f, 0, 0, FILE_BEGIN) == 0xFFFFFFFF)
ThrowXMLwithMemMgr(XMLPlatformUtilsException, XMLExcepts::File_CouldNotResetFile, manager);
}
XMLFilePos
WindowsFileMgr::curPos(FileHandle f, MemoryManager* const manager)
{
if (!f)
ThrowXMLwithMemMgr(XMLPlatformUtilsException, XMLExcepts::CPtr_PointerIsZero, manager);
// Get the current position
LONG high=0;
DWORD low = ::SetFilePointer(f, 0, &high, FILE_CURRENT);
if (low == INVALID_SET_FILE_POINTER && GetLastError()!=NO_ERROR)
ThrowXMLwithMemMgr(XMLPlatformUtilsException, XMLExcepts::File_CouldNotGetCurPos, manager);
return (((XMLFilePos)high) << 32) | low;
}
XMLFilePos
WindowsFileMgr::fileSize(FileHandle f, MemoryManager* const manager)
{
if (!f)
ThrowXMLwithMemMgr(XMLPlatformUtilsException, XMLExcepts::CPtr_PointerIsZero, manager);
DWORD high=0;
DWORD low=GetFileSize(f, &high);
if(low==INVALID_FILE_SIZE && GetLastError()!=NO_ERROR)
// TODO: find a better exception
ThrowXMLwithMemMgr(XMLPlatformUtilsException, XMLExcepts::File_CouldNotGetCurPos, manager);
return (((XMLFilePos)high) << 32) | low;
}
XMLSize_t
WindowsFileMgr::fileRead(FileHandle f, XMLSize_t byteCount, XMLByte* buffer, MemoryManager* const manager)
{
if (!f || !buffer)
ThrowXMLwithMemMgr(XMLPlatformUtilsException, XMLExcepts::CPtr_PointerIsZero, manager);
DWORD bytesRead = 0;
if (!::ReadFile(f, buffer, (DWORD)byteCount, &bytesRead, 0))
{
//
// Check specially for a broken pipe error. If we get this, it just
// means no more data from the pipe, so return zero.
//
if (::GetLastError() != ERROR_BROKEN_PIPE)
ThrowXMLwithMemMgr(XMLPlatformUtilsException, XMLExcepts::File_CouldNotReadFromFile, manager);
}
return (unsigned int)bytesRead;
}
void
WindowsFileMgr::fileWrite(FileHandle f, XMLSize_t byteCount, const XMLByte* buffer, MemoryManager* const manager)
{
if (!f || !buffer)
ThrowXMLwithMemMgr(XMLPlatformUtilsException, XMLExcepts::CPtr_PointerIsZero, manager);
const XMLByte* tmpFlush = buffer;
while (byteCount > 0)
{
DWORD bytesWritten = 0;
if (!::WriteFile(f, tmpFlush, (DWORD)byteCount, &bytesWritten, 0))
ThrowXMLwithMemMgr(XMLPlatformUtilsException, XMLExcepts::File_CouldNotWriteToFile, manager);
tmpFlush+=bytesWritten;
byteCount-=bytesWritten;
}
}
XMLCh*
WindowsFileMgr::getFullPath(const XMLCh* const srcPath, MemoryManager* const manager)
{
//
// If we are on NT, then use wide character APIs, else use ASCII APIs.
// We have to do it manually since we are only built in ASCII mode from
// the standpoint of the APIs.
//
if (_onNT)
{
// Use a local buffer that is big enough for the largest legal path
const unsigned int bufSize = 1024;
XMLCh tmpPath[bufSize + 1];
XMLCh* namePart = 0;
if (!::GetFullPathNameW((LPCWSTR)srcPath, bufSize, (LPWSTR)tmpPath, (LPWSTR*)&namePart))
return 0;
// Return a copy of the path
return XMLString::replicate(tmpPath, manager);
}
else
{
// Transcode the incoming string
char* tmpSrcPath = XMLString::transcode(srcPath, manager);
ArrayJanitor<char> janSrcPath(tmpSrcPath, manager);
// Use a local buffer that is big enough for the largest legal path
const unsigned int bufSize = 511;
char tmpPath[511 + 1];
char* namePart = 0;
if (!::GetFullPathNameA(tmpSrcPath, bufSize, tmpPath, &namePart))
return 0;
// Return a transcoded copy of the path
return XMLString::transcode(tmpPath, manager);
}
}
XMLCh*
WindowsFileMgr::getCurrentDirectory(MemoryManager* const manager)
{
//
// If we are on NT, then use wide character APIs, else use ASCII APIs.
// We have to do it manually since we are only built in ASCII mode from
// the standpoint of the APIs.
//
if (_onNT)
{
// Use a local buffer that is big enough for the largest legal path
const unsigned int bufSize = 1024;
XMLCh tmpPath[bufSize + 1];
if (!::GetCurrentDirectoryW(bufSize, (LPWSTR)tmpPath))
return 0;
// Return a copy of the path
return XMLString::replicate(tmpPath, manager);
}
else
{
// Use a local buffer that is big enough for the largest legal path
const unsigned int bufSize = 511;
char tmpPath[511 + 1];
if (!::GetCurrentDirectoryA(bufSize, tmpPath))
return 0;
// Return a transcoded copy of the path
return XMLString::transcode(tmpPath, manager);
}
}
bool
WindowsFileMgr::isRelative(const XMLCh* const toCheck, MemoryManager* const /*manager*/)
{
// Check for pathological case of empty path
if (!toCheck || !toCheck[0])
return false;
//
// If its starts with a drive, then it cannot be relative. Note that
// we checked the drive not being empty above, so worst case its one
// char long and the check of the 1st char will fail because its really
// a null character.
//
if (toCheck[1] == chColon)
{
if (((toCheck[0] >= chLatin_A) && (toCheck[0] <= chLatin_Z))
|| ((toCheck[0] >= chLatin_a) && (toCheck[0] <= chLatin_z)))
{
return false;
}
}
//
// If it starts with a double slash, then it cannot be relative since
// it's a remote file.
//
if (isBackSlash(toCheck[0]))
return false;
// Else assume its a relative path
return true;
}
XERCES_CPP_NAMESPACE_END
<commit_msg>Be compatible with Platform SDK older than 2003<commit_after>/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/*
* $Id$
*/
#include <windows.h>
#include <xercesc/util/FileManagers/WindowsFileMgr.hpp>
#include <xercesc/util/Janitor.hpp>
#include <xercesc/util/XMLString.hpp>
#include <xercesc/util/XMLUniDefs.hpp>
#ifndef INVALID_SET_FILE_POINTER
#define INVALID_SET_FILE_POINTER ((DWORD)-1)
#endif
XERCES_CPP_NAMESPACE_BEGIN
static bool isBackSlash(XMLCh c) {
return c == chBackSlash ||
c == chYenSign ||
c == chWonSign;
}
WindowsFileMgr::WindowsFileMgr()
{
// Figure out if we are on NT and save that flag for later use
OSVERSIONINFO OSVer;
OSVer.dwOSVersionInfoSize = sizeof(OSVERSIONINFO);
::GetVersionEx(&OSVer);
_onNT = (OSVer.dwPlatformId == VER_PLATFORM_WIN32_NT);
}
WindowsFileMgr::~WindowsFileMgr()
{
}
FileHandle
WindowsFileMgr::fileOpen(const XMLCh* fileName, bool toWrite, MemoryManager* const manager)
{
// Watch for obvious wierdness
if (!fileName)
return 0;
//
// We have to play a little trick here. If its /x:.....
// style fully qualified path, we have to toss the leading /
// character.
//
const XMLCh* nameToOpen = fileName;
if (*fileName == chForwardSlash)
{
if (XMLString::stringLen(fileName) > 3)
{
if (*(fileName + 2) == chColon)
{
const XMLCh chDrive = *(fileName + 1);
if (((chDrive >= chLatin_A) && (chDrive <= chLatin_Z))
|| ((chDrive >= chLatin_a) && (chDrive <= chLatin_z)))
{
nameToOpen = fileName + 1;
}
}
// Similarly for UNC paths
if ( *(fileName + 1) == *(fileName + 2) &&
(*(fileName + 1) == chForwardSlash ||
*(fileName + 1) == chBackSlash) )
{
nameToOpen = fileName + 1;
}
}
}
// Ok, this might look stupid but its a semi-expedient way to deal
// with a thorny problem. Shift-JIS and some other Asian encodings
// are fundamentally broken and map both the backslash and the Yen
// sign to the same code point. Transcoders have to pick one or the
// other to map '\' to Unicode and tend to choose the Yen sign.
//
// Unicode Yen or Won signs as directory separators will fail.
//
// So, we will check this path name for Yen or won signs and, if they are
// there, we'll replace them with slashes.
//
// A further twist: we replace Yen and Won with forward slashes rather
// than back slashes. Either form of slash will work as a directory
// separator. On Win 95 and 98, though, Unicode back-slashes may
// fail to transode back to 8-bit 0x5C with some Unicode converters
// to some of the problematic code pages. Forward slashes always
// transcode correctly back to 8 bit char * form.
//
XMLCh *tmpUName = 0;
const XMLCh* srcPtr = nameToOpen;
while (*srcPtr)
{
if (*srcPtr == chYenSign ||
*srcPtr == chWonSign)
break;
srcPtr++;
}
//
// If we found a yen, then we have to create a temp file name. Else
// go with the file name as is and save the overhead.
//
if (*srcPtr)
{
tmpUName = XMLString::replicate(nameToOpen, manager);
XMLCh* tmpPtr = tmpUName;
while (*tmpPtr)
{
if (*tmpPtr == chYenSign ||
*tmpPtr == chWonSign)
*tmpPtr = chForwardSlash;
tmpPtr++;
}
nameToOpen = tmpUName;
}
FileHandle retVal = 0;
if (_onNT)
{
retVal = ::CreateFileW
(
(LPCWSTR) nameToOpen
, toWrite?GENERIC_WRITE:GENERIC_READ
, FILE_SHARE_READ
, 0
, toWrite?CREATE_ALWAYS:OPEN_EXISTING
, toWrite?FILE_ATTRIBUTE_NORMAL:FILE_FLAG_SEQUENTIAL_SCAN
, 0
);
}
else
{
//
// We are Win 95 / 98. Take the Unicode file name back to (char *)
// so that we can open it.
//
char* tmpName = XMLString::transcode(nameToOpen, manager);
retVal = ::CreateFileA
(
tmpName
, toWrite?GENERIC_WRITE:GENERIC_READ
, FILE_SHARE_READ
, 0
, toWrite?CREATE_ALWAYS:OPEN_EXISTING
, toWrite?FILE_ATTRIBUTE_NORMAL:FILE_FLAG_SEQUENTIAL_SCAN
, 0
);
manager->deallocate(tmpName);//delete [] tmpName;
}
if (tmpUName)
manager->deallocate(tmpUName);//delete [] tmpUName;
if (retVal == INVALID_HANDLE_VALUE)
return 0;
return retVal;
}
FileHandle
WindowsFileMgr::fileOpen(const char* path, bool toWrite, MemoryManager* const manager)
{
XMLCh* tmpFileName = XMLString::transcode(path, manager);
ArrayJanitor<XMLCh> janText(tmpFileName, manager);
return fileOpen(tmpFileName, toWrite, manager);
}
FileHandle
WindowsFileMgr::openStdIn(MemoryManager* const manager)
{
//
// Get the standard input handle. Duplicate it and return that copy
// since the outside world cannot tell the difference and will shut
// down this handle when its done with it. If we gave out the orignal,
// shutting it would prevent any further output.
//
HANDLE stdInOrg = ::GetStdHandle(STD_INPUT_HANDLE);
if (stdInOrg == INVALID_HANDLE_VALUE) {
XMLCh stdinStr[] = {chLatin_s, chLatin_t, chLatin_d, chLatin_i, chLatin_n, chNull};
ThrowXMLwithMemMgr1(XMLPlatformUtilsException, XMLExcepts::File_CouldNotOpenFile, stdinStr, manager);
}
HANDLE retHandle;
if (!::DuplicateHandle
(
::GetCurrentProcess()
, stdInOrg
, ::GetCurrentProcess()
, &retHandle
, 0
, FALSE
, DUPLICATE_SAME_ACCESS))
{
ThrowXMLwithMemMgr(XMLPlatformUtilsException, XMLExcepts::File_CouldNotDupHandle, manager);
}
return retHandle;
}
void
WindowsFileMgr::fileClose(FileHandle f, MemoryManager* const manager)
{
if (!f)
ThrowXMLwithMemMgr(XMLPlatformUtilsException, XMLExcepts::CPtr_PointerIsZero, manager);
if (!::CloseHandle(f))
ThrowXMLwithMemMgr(XMLPlatformUtilsException, XMLExcepts::File_CouldNotCloseFile, manager);
}
void
WindowsFileMgr::fileReset(FileHandle f, MemoryManager* const manager)
{
if (!f)
ThrowXMLwithMemMgr(XMLPlatformUtilsException, XMLExcepts::CPtr_PointerIsZero, manager);
// Seek to the start of the file
if (::SetFilePointer(f, 0, 0, FILE_BEGIN) == INVALID_SET_FILE_POINTER)
ThrowXMLwithMemMgr(XMLPlatformUtilsException, XMLExcepts::File_CouldNotResetFile, manager);
}
XMLFilePos
WindowsFileMgr::curPos(FileHandle f, MemoryManager* const manager)
{
if (!f)
ThrowXMLwithMemMgr(XMLPlatformUtilsException, XMLExcepts::CPtr_PointerIsZero, manager);
// Get the current position
LONG high=0;
DWORD low = ::SetFilePointer(f, 0, &high, FILE_CURRENT);
if (low == INVALID_SET_FILE_POINTER && GetLastError()!=NO_ERROR)
ThrowXMLwithMemMgr(XMLPlatformUtilsException, XMLExcepts::File_CouldNotGetCurPos, manager);
return (((XMLFilePos)high) << 32) | low;
}
XMLFilePos
WindowsFileMgr::fileSize(FileHandle f, MemoryManager* const manager)
{
if (!f)
ThrowXMLwithMemMgr(XMLPlatformUtilsException, XMLExcepts::CPtr_PointerIsZero, manager);
DWORD high=0;
DWORD low=::GetFileSize(f, &high);
if(low==INVALID_FILE_SIZE && GetLastError()!=NO_ERROR)
// TODO: find a better exception
ThrowXMLwithMemMgr(XMLPlatformUtilsException, XMLExcepts::File_CouldNotGetCurPos, manager);
return (((XMLFilePos)high) << 32) | low;
}
XMLSize_t
WindowsFileMgr::fileRead(FileHandle f, XMLSize_t byteCount, XMLByte* buffer, MemoryManager* const manager)
{
if (!f || !buffer)
ThrowXMLwithMemMgr(XMLPlatformUtilsException, XMLExcepts::CPtr_PointerIsZero, manager);
DWORD bytesRead = 0;
if (!::ReadFile(f, buffer, (DWORD)byteCount, &bytesRead, 0))
{
//
// Check specially for a broken pipe error. If we get this, it just
// means no more data from the pipe, so return zero.
//
if (::GetLastError() != ERROR_BROKEN_PIPE)
ThrowXMLwithMemMgr(XMLPlatformUtilsException, XMLExcepts::File_CouldNotReadFromFile, manager);
}
return (unsigned int)bytesRead;
}
void
WindowsFileMgr::fileWrite(FileHandle f, XMLSize_t byteCount, const XMLByte* buffer, MemoryManager* const manager)
{
if (!f || !buffer)
ThrowXMLwithMemMgr(XMLPlatformUtilsException, XMLExcepts::CPtr_PointerIsZero, manager);
const XMLByte* tmpFlush = buffer;
while (byteCount > 0)
{
DWORD bytesWritten = 0;
if (!::WriteFile(f, tmpFlush, (DWORD)byteCount, &bytesWritten, 0))
ThrowXMLwithMemMgr(XMLPlatformUtilsException, XMLExcepts::File_CouldNotWriteToFile, manager);
tmpFlush+=bytesWritten;
byteCount-=bytesWritten;
}
}
XMLCh*
WindowsFileMgr::getFullPath(const XMLCh* const srcPath, MemoryManager* const manager)
{
//
// If we are on NT, then use wide character APIs, else use ASCII APIs.
// We have to do it manually since we are only built in ASCII mode from
// the standpoint of the APIs.
//
if (_onNT)
{
// Use a local buffer that is big enough for the largest legal path
const unsigned int bufSize = 1024;
XMLCh tmpPath[bufSize + 1];
XMLCh* namePart = 0;
if (!::GetFullPathNameW((LPCWSTR)srcPath, bufSize, (LPWSTR)tmpPath, (LPWSTR*)&namePart))
return 0;
// Return a copy of the path
return XMLString::replicate(tmpPath, manager);
}
else
{
// Transcode the incoming string
char* tmpSrcPath = XMLString::transcode(srcPath, manager);
ArrayJanitor<char> janSrcPath(tmpSrcPath, manager);
// Use a local buffer that is big enough for the largest legal path
const unsigned int bufSize = 511;
char tmpPath[511 + 1];
char* namePart = 0;
if (!::GetFullPathNameA(tmpSrcPath, bufSize, tmpPath, &namePart))
return 0;
// Return a transcoded copy of the path
return XMLString::transcode(tmpPath, manager);
}
}
XMLCh*
WindowsFileMgr::getCurrentDirectory(MemoryManager* const manager)
{
//
// If we are on NT, then use wide character APIs, else use ASCII APIs.
// We have to do it manually since we are only built in ASCII mode from
// the standpoint of the APIs.
//
if (_onNT)
{
// Use a local buffer that is big enough for the largest legal path
const unsigned int bufSize = 1024;
XMLCh tmpPath[bufSize + 1];
if (!::GetCurrentDirectoryW(bufSize, (LPWSTR)tmpPath))
return 0;
// Return a copy of the path
return XMLString::replicate(tmpPath, manager);
}
else
{
// Use a local buffer that is big enough for the largest legal path
const unsigned int bufSize = 511;
char tmpPath[511 + 1];
if (!::GetCurrentDirectoryA(bufSize, tmpPath))
return 0;
// Return a transcoded copy of the path
return XMLString::transcode(tmpPath, manager);
}
}
bool
WindowsFileMgr::isRelative(const XMLCh* const toCheck, MemoryManager* const /*manager*/)
{
// Check for pathological case of empty path
if (!toCheck || !toCheck[0])
return false;
//
// If its starts with a drive, then it cannot be relative. Note that
// we checked the drive not being empty above, so worst case its one
// char long and the check of the 1st char will fail because its really
// a null character.
//
if (toCheck[1] == chColon)
{
if (((toCheck[0] >= chLatin_A) && (toCheck[0] <= chLatin_Z))
|| ((toCheck[0] >= chLatin_a) && (toCheck[0] <= chLatin_z)))
{
return false;
}
}
//
// If it starts with a double slash, then it cannot be relative since
// it's a remote file.
//
if (isBackSlash(toCheck[0]))
return false;
// Else assume its a relative path
return true;
}
XERCES_CPP_NAMESPACE_END
<|endoftext|> |
<commit_before>#include <iostream>
#include <exception>
#include <cstdlib>
#include <QDebug>
#include <QTimer>
#include <QThread>
#include <QCoreApplication>
#include <chillout.h>
#include "Connectivity/curlinithelper.h"
#include <Helpers/logger.h>
#include "integrationtestsenvironment.h"
#include "xpikstestsapp.h"
#include "exiv2iohelpers.h"
#include "testshelpers.h"
#include "integrationtestbase.h"
#include "addfilesbasictest.h"
#include "autoattachvectorstest.h"
#include "savefilebasictest.h"
#include "spellcheckmultireplacetest.h"
#include "spellcheckcombinedmodeltest.h"
#include "zipartworkstest.h"
#include "spellcheckundotest.h"
#include "autocompletebasictest.h"
#include "spellingproduceswarningstest.h"
#include "undoaddwithvectorstest.h"
#include "readlegacysavedtest.h"
#include "clearmetadatatest.h"
#include "savewithemptytitletest.h"
#include "combinededitfixspellingtest.h"
#include "findandreplacemodeltest.h"
#include "addtouserdictionarytest.h"
#include "autodetachvectortest.h"
#include "removefromuserdictionarytest.h"
#include "artworkuploaderbasictest.h"
#include "plaintextedittest.h"
#include "fixspellingmarksmodifiedtest.h"
#include "presetstest.h"
#include "translatorbasictest.h"
#include "userdictedittest.h"
#include "weirdnamesreadtest.h"
#include "restoresessiontest.h"
#include "savefilelegacytest.h"
#include "locallibrarysearchtest.h"
#include "metadatacachesavetest.h"
#include "savevideobasictest.h"
#include "duplicatesearchtest.h"
#include "autocompletepresetstest.h"
#include "csvexporttest.h"
#include "unicodeiotest.h"
#include "faileduploadstest.h"
#include "undoadddirectorytest.h"
#include "undorestoresessiontest.h"
#include "masterpasswordtest.h"
#include "reimporttest.h"
#include "autoimporttest.h"
#include "importlostmetadatatest.h"
#include "warningscombinedtest.h"
#include "csvdefaultexporttest.h"
#include "loadpluginbasictest.h"
#include "stockftpautocompletetest.h"
void myMessageHandler(QtMsgType type, const QMessageLogContext &context, const QString &msg) {
Q_UNUSED(context);
#if (QT_VERSION >= QT_VERSION_CHECK(5, 4, 0))
QString logLine = qFormatLogMessage(type, context, msg);
#else
QString msgType;
switch (type) {
case QtDebugMsg:
msgType = "debug";
break;
case QtWarningMsg:
msgType = "warning";
break;
case QtCriticalMsg:
msgType = "critical";
break;
case QtFatalMsg:
msgType = "fatal";
break;
#if (QT_VERSION >= QT_VERSION_CHECK(5, 5, 1))
case QtInfoMsg:
msgType = "info";
break;
#endif
}
// %{time hh:mm:ss.zzz} %{type} T#%{threadid} %{function} - %{message}
QString time = QDateTime::currentDateTimeUtc().toString("hh:mm:ss.zzz");
QString logLine = QString("%1 %2 T#%3 %4 - %5")
.arg(time).arg(msgType)
.arg(0).arg(context.function)
.arg(msg);
#endif
Helpers::Logger &logger = Helpers::Logger::getInstance();
logger.log(type, logLine);
if ((type == QtFatalMsg) || (type == QtWarningMsg)) {
logger.abortFlush();
}
if (type == QtFatalMsg) {
abort();
}
}
void initCrashRecovery(Common::ISystemEnvironment &environment) {
auto &chillout = Debug::Chillout::getInstance();
QString crashesDirPath = QDir::toNativeSeparators(environment.path({Constants::CRASHES_DIR}));
#ifdef Q_OS_WIN
chillout.init(L"xpiks-tests-integration", crashesDirPath.toStdWString());
#else
chillout.init("xpiks-tests-integration", crashesDirPath.toStdString());
#endif
Helpers::Logger &logger = Helpers::Logger::getInstance();
chillout.setBacktraceCallback([&logger](const char * const stackTrace) {
logger.emergencyLog(stackTrace);
});
chillout.setCrashCallback([&logger, &chillout]() {
chillout.backtrace();
logger.emergencyFlush();
#ifdef Q_OS_WIN
chillout.createCrashDump(Debug::CrashDumpFull);
#endif
});
}
void initQSettings() {
QCoreApplication::setOrganizationName(Constants::ORGANIZATION_NAME);
QCoreApplication::setApplicationName(Constants::APPLICATION_NAME);
}
int main(int argc, char *argv[]) {
initQSettings();
std::cout << "Started integration tests" << std::endl;
std::cout << "Current working directory: " << QDir::currentPath().toStdString() << std::endl;
// will call curl_global_init and cleanup
Connectivity::CurlInitHelper curlInitHelper;
Q_UNUSED(curlInitHelper);
Exiv2InitHelper exiv2InitHelper;
Q_UNUSED(exiv2InitHelper);
qSetMessagePattern("%{time hh:mm:ss.zzz} %{type} T#%{threadid} %{function} - %{message}");
qInstallMessageHandler(myMessageHandler);
qRegisterMetaType<Common::SpellCheckFlags>("Common::SpellCheckFlags");
// -----------------------------------------------
QCoreApplication app(argc, argv);
IntegrationTestsEnvironment environment(app.arguments());
environment.ensureSystemDirectoriesExist();
initCrashRecovery(environment);
// -----------------------------------------------
std::cout << "Initialized application" << std::endl;
#ifdef WITH_LOGS
{
QString time = QDateTime::currentDateTimeUtc().toString("ddMMyyyy-hhmmss-zzz");
QString logFilename = QString("xpiks-qt-%1.log").arg(time);
QString logFilePath = environment.path({Constants::LOGS_DIR, logFilename});
Helpers::Logger &logger = Helpers::Logger::getInstance();
logger.setLogFilePath(logFilePath);
logger.setMemoryOnly(environment.getIsInMemoryOnly());
}
#endif
XpiksTestsApp xpiksTests(environment);
xpiksTests.startLogging();
xpiksTests.initialize();
xpiksTests.start();
xpiksTests.waitInitialized();
int result = 0;
std::vector<std::shared_ptr<IntegrationTestBase>> integrationTests;
// always the first one
integrationTests.emplace_back(std::make_shared<MetadataCacheSaveTest>(environment, xpiksTests));
// and all others
integrationTests.emplace_back(std::make_shared<AddFilesBasicTest>(environment, xpiksTests));
integrationTests.emplace_back(std::make_shared<AutoAttachVectorsTest>(environment, xpiksTests));
integrationTests.emplace_back(std::make_shared<SaveFileBasicTest>(environment, xpiksTests));
integrationTests.emplace_back(std::make_shared<SaveFileLegacyTest>(environment, xpiksTests));
#ifndef TRAVIS_CI
integrationTests.emplace_back(std::make_shared<SaveVideoBasicTest>(environment, xpiksTests));
#endif
integrationTests.emplace_back(std::make_shared<FailedUploadsTest>(environment, xpiksTests));
integrationTests.emplace_back(std::make_shared<SpellCheckMultireplaceTest>(environment, xpiksTests));
integrationTests.emplace_back(std::make_shared<SpellCheckCombinedModelTest>(environment, xpiksTests));
integrationTests.emplace_back(std::make_shared<ZipArtworksTest>(environment, xpiksTests));
integrationTests.emplace_back(std::make_shared<SpellCheckUndoTest>(environment, xpiksTests));
integrationTests.emplace_back(std::make_shared<AutoCompleteBasicTest>(environment, xpiksTests));
integrationTests.emplace_back(std::make_shared<SpellingProducesWarningsTest>(environment, xpiksTests));
integrationTests.emplace_back(std::make_shared<UndoAddWithVectorsTest>(environment, xpiksTests));
integrationTests.emplace_back(std::make_shared<ReadLegacySavedTest>(environment, xpiksTests));
integrationTests.emplace_back(std::make_shared<ClearMetadataTest>(environment, xpiksTests));
integrationTests.emplace_back(std::make_shared<SaveWithEmptyTitleTest>(environment, xpiksTests));
integrationTests.emplace_back(std::make_shared<CombinedEditFixSpellingTest>(environment, xpiksTests));
integrationTests.emplace_back(std::make_shared<FindAndReplaceModelTest>(environment, xpiksTests));
integrationTests.emplace_back(std::make_shared<AddToUserDictionaryTest>(environment, xpiksTests));
integrationTests.emplace_back(std::make_shared<AutoDetachVectorTest>(environment, xpiksTests));
integrationTests.emplace_back(std::make_shared<RemoveFromUserDictionaryTest>(environment, xpiksTests));
integrationTests.emplace_back(std::make_shared<ArtworkUploaderBasicTest>(environment, xpiksTests));
integrationTests.emplace_back(std::make_shared<PlainTextEditTest>(environment, xpiksTests));
integrationTests.emplace_back(std::make_shared<FixSpellingMarksModifiedTest>(environment, xpiksTests));
integrationTests.emplace_back(std::make_shared<PresetsTest>(environment, xpiksTests));
integrationTests.emplace_back(std::make_shared<TranslatorBasicTest>(environment, xpiksTests));
integrationTests.emplace_back(std::make_shared<UserDictEditTest>(environment, xpiksTests));
integrationTests.emplace_back(std::make_shared<WeirdNamesReadTest>(environment, xpiksTests));
integrationTests.emplace_back(std::make_shared<RestoreSessionTest>(environment, xpiksTests));
integrationTests.emplace_back(std::make_shared<DuplicateSearchTest>(environment, xpiksTests));
integrationTests.emplace_back(std::make_shared<AutoCompletePresetsTest>(environment, xpiksTests));
integrationTests.emplace_back(std::make_shared<CsvExportTest>(environment, xpiksTests));
integrationTests.emplace_back(std::make_shared<UnicodeIoTest>(environment, xpiksTests));
integrationTests.emplace_back(std::make_shared<UndoAddDirectoryTest>(environment, xpiksTests));
integrationTests.emplace_back(std::make_shared<UndoRestoreSessionTest>(environment, xpiksTests));
integrationTests.emplace_back(std::make_shared<MasterPasswordTest>(environment, xpiksTests));
integrationTests.emplace_back(std::make_shared<ReimportTest>(environment, xpiksTests));
integrationTests.emplace_back(std::make_shared<AutoImportTest>(environment, xpiksTests));
integrationTests.emplace_back(std::make_shared<ImportLostMetadataTest>(environment, xpiksTests));
integrationTests.emplace_back(std::make_shared<WarningsCombinedTest>(environment, xpiksTests));
integrationTests.emplace_back(std::make_shared<CsvDefaultExportTest>(environment, xpiksTests));
integrationTests.emplace_back(std::make_shared<LoadPluginBasicTest>(environment, xpiksTests));
integrationTests.emplace_back(std::make_shared<StockFtpAutoCompleteTest>(environment, xpiksTests));
// always the last one. insert new tests above
integrationTests.emplace_back(std::make_shared<LocalLibrarySearchTest>(environment, xpiksTests));
qInfo("\n");
int succeededTestsCount = 0, failedTestsCount = 0;
QStringList failedTests;
for (auto &test: integrationTests) {
QThread::msleep(500);
qInfo("---------------------------------------------------------");
qInfo("Running test: %s", test->testName().toStdString().c_str());
test->setup();
const int testResult = test->doTest();
test->teardown();
result += testResult;
if (testResult == 0) {
succeededTestsCount++;
qInfo("Test %s PASSED", test->testName().toStdString().c_str());
} else {
failedTestsCount++;
qInfo("Test %s FAILED", test->testName().toStdString().c_str());
failedTests.append(test->testName());
}
qInfo("\n");
}
qInfo() << "--------------------------";
qInfo() << "In memory run:" << environment.getIsInMemoryOnly();
qInfo() << "Integration Tests Results:" << succeededTestsCount << "succeeded," << failedTestsCount << "failed";
qInfo() << "Tests return code" << result;
if (!failedTests.empty()) {
qInfo() << "FAILED TESTS:" << failedTests.join(", ");
}
qInfo() << "--------------------------";
QTimer debuggingTimer;
debuggingTimer.setSingleShot(true);
QObject::connect(&debuggingTimer, &QTimer::timeout,
[]() {
Q_ASSERT(false);
});
// assert in 1 minute to see hung threads
debuggingTimer.start(60*1000);
qInfo() << "--";
qInfo() << "-----> Crash timer started...";
qInfo() << "--";
xpiksTests.stop();
// for the logs to appear
app.processEvents();
QThread::sleep(1);
std::cout << "Integration tests finished" << std::endl;
return result;
}
<commit_msg>Improve integration tests crashing<commit_after>#include <iostream>
#include <exception>
#include <cstdlib>
#include <QDebug>
#include <QTimer>
#include <QThread>
#include <QCoreApplication>
#include <chillout.h>
#include "Connectivity/curlinithelper.h"
#include <Helpers/logger.h>
#include "integrationtestsenvironment.h"
#include "xpikstestsapp.h"
#include "exiv2iohelpers.h"
#include "testshelpers.h"
#include "integrationtestbase.h"
#include "addfilesbasictest.h"
#include "autoattachvectorstest.h"
#include "savefilebasictest.h"
#include "spellcheckmultireplacetest.h"
#include "spellcheckcombinedmodeltest.h"
#include "zipartworkstest.h"
#include "spellcheckundotest.h"
#include "autocompletebasictest.h"
#include "spellingproduceswarningstest.h"
#include "undoaddwithvectorstest.h"
#include "readlegacysavedtest.h"
#include "clearmetadatatest.h"
#include "savewithemptytitletest.h"
#include "combinededitfixspellingtest.h"
#include "findandreplacemodeltest.h"
#include "addtouserdictionarytest.h"
#include "autodetachvectortest.h"
#include "removefromuserdictionarytest.h"
#include "artworkuploaderbasictest.h"
#include "plaintextedittest.h"
#include "fixspellingmarksmodifiedtest.h"
#include "presetstest.h"
#include "translatorbasictest.h"
#include "userdictedittest.h"
#include "weirdnamesreadtest.h"
#include "restoresessiontest.h"
#include "savefilelegacytest.h"
#include "locallibrarysearchtest.h"
#include "metadatacachesavetest.h"
#include "savevideobasictest.h"
#include "duplicatesearchtest.h"
#include "autocompletepresetstest.h"
#include "csvexporttest.h"
#include "unicodeiotest.h"
#include "faileduploadstest.h"
#include "undoadddirectorytest.h"
#include "undorestoresessiontest.h"
#include "masterpasswordtest.h"
#include "reimporttest.h"
#include "autoimporttest.h"
#include "importlostmetadatatest.h"
#include "warningscombinedtest.h"
#include "csvdefaultexporttest.h"
#include "loadpluginbasictest.h"
#include "stockftpautocompletetest.h"
void myMessageHandler(QtMsgType type, const QMessageLogContext &context, const QString &msg) {
Q_UNUSED(context);
#if (QT_VERSION >= QT_VERSION_CHECK(5, 4, 0))
QString logLine = qFormatLogMessage(type, context, msg);
#else
QString msgType;
switch (type) {
case QtDebugMsg:
msgType = "debug";
break;
case QtWarningMsg:
msgType = "warning";
break;
case QtCriticalMsg:
msgType = "critical";
break;
case QtFatalMsg:
msgType = "fatal";
break;
#if (QT_VERSION >= QT_VERSION_CHECK(5, 5, 1))
case QtInfoMsg:
msgType = "info";
break;
#endif
}
// %{time hh:mm:ss.zzz} %{type} T#%{threadid} %{function} - %{message}
QString time = QDateTime::currentDateTimeUtc().toString("hh:mm:ss.zzz");
QString logLine = QString("%1 %2 T#%3 %4 - %5")
.arg(time).arg(msgType)
.arg(0).arg(context.function)
.arg(msg);
#endif
Helpers::Logger &logger = Helpers::Logger::getInstance();
logger.log(type, logLine);
if ((type == QtFatalMsg) || (type == QtWarningMsg)) {
logger.abortFlush();
}
if (type == QtFatalMsg) {
abort();
}
}
void initCrashRecovery(Common::ISystemEnvironment &environment) {
auto &chillout = Debug::Chillout::getInstance();
QString crashesDirPath = QDir::toNativeSeparators(environment.path({Constants::CRASHES_DIR}));
#ifdef Q_OS_WIN
#ifdef APPVEYOR
// crash next to exe so appveyor could make artifact out of dump
chillout.init(L"xpiks-tests-integration", L".");
#else
chillout.init(L"xpiks-tests-integration", crashesDirPath.toStdWString());
#endif
#else
chillout.init("xpiks-tests-integration", crashesDirPath.toStdString());
#endif
Helpers::Logger &logger = Helpers::Logger::getInstance();
chillout.setBacktraceCallback([&logger](const char * const stackTrace) {
logger.emergencyLog(stackTrace);
});
chillout.setCrashCallback([&logger, &chillout]() {
chillout.backtrace();
logger.emergencyFlush();
#ifdef Q_OS_WIN
chillout.createCrashDump(Debug::CrashDumpFull);
#endif
});
}
void initQSettings() {
QCoreApplication::setOrganizationName(Constants::ORGANIZATION_NAME);
QCoreApplication::setApplicationName(Constants::APPLICATION_NAME);
}
int main(int argc, char *argv[]) {
initQSettings();
std::cout << "Started integration tests" << std::endl;
std::cout << "Current working directory: " << QDir::currentPath().toStdString() << std::endl;
// will call curl_global_init and cleanup
Connectivity::CurlInitHelper curlInitHelper;
Q_UNUSED(curlInitHelper);
Exiv2InitHelper exiv2InitHelper;
Q_UNUSED(exiv2InitHelper);
qSetMessagePattern("%{time hh:mm:ss.zzz} %{type} T#%{threadid} %{function} - %{message}");
qInstallMessageHandler(myMessageHandler);
qRegisterMetaType<Common::SpellCheckFlags>("Common::SpellCheckFlags");
// -----------------------------------------------
QCoreApplication app(argc, argv);
IntegrationTestsEnvironment environment(app.arguments());
environment.ensureSystemDirectoriesExist();
initCrashRecovery(environment);
// -----------------------------------------------
std::cout << "Initialized application" << std::endl;
#ifdef WITH_LOGS
{
QString time = QDateTime::currentDateTimeUtc().toString("ddMMyyyy-hhmmss-zzz");
QString logFilename = QString("xpiks-qt-%1.log").arg(time);
QString logFilePath = environment.path({Constants::LOGS_DIR, logFilename});
Helpers::Logger &logger = Helpers::Logger::getInstance();
logger.setLogFilePath(logFilePath);
logger.setMemoryOnly(environment.getIsInMemoryOnly());
}
#endif
XpiksTestsApp xpiksTests(environment);
xpiksTests.startLogging();
xpiksTests.initialize();
xpiksTests.start();
xpiksTests.waitInitialized();
int result = 0;
std::vector<std::shared_ptr<IntegrationTestBase>> integrationTests;
// always the first one
integrationTests.emplace_back(std::make_shared<MetadataCacheSaveTest>(environment, xpiksTests));
// and all others
integrationTests.emplace_back(std::make_shared<AddFilesBasicTest>(environment, xpiksTests));
integrationTests.emplace_back(std::make_shared<AutoAttachVectorsTest>(environment, xpiksTests));
integrationTests.emplace_back(std::make_shared<SaveFileBasicTest>(environment, xpiksTests));
integrationTests.emplace_back(std::make_shared<SaveFileLegacyTest>(environment, xpiksTests));
#ifndef TRAVIS_CI
integrationTests.emplace_back(std::make_shared<SaveVideoBasicTest>(environment, xpiksTests));
#endif
integrationTests.emplace_back(std::make_shared<FailedUploadsTest>(environment, xpiksTests));
integrationTests.emplace_back(std::make_shared<SpellCheckMultireplaceTest>(environment, xpiksTests));
integrationTests.emplace_back(std::make_shared<SpellCheckCombinedModelTest>(environment, xpiksTests));
integrationTests.emplace_back(std::make_shared<ZipArtworksTest>(environment, xpiksTests));
integrationTests.emplace_back(std::make_shared<SpellCheckUndoTest>(environment, xpiksTests));
integrationTests.emplace_back(std::make_shared<AutoCompleteBasicTest>(environment, xpiksTests));
integrationTests.emplace_back(std::make_shared<SpellingProducesWarningsTest>(environment, xpiksTests));
integrationTests.emplace_back(std::make_shared<UndoAddWithVectorsTest>(environment, xpiksTests));
integrationTests.emplace_back(std::make_shared<ReadLegacySavedTest>(environment, xpiksTests));
integrationTests.emplace_back(std::make_shared<ClearMetadataTest>(environment, xpiksTests));
integrationTests.emplace_back(std::make_shared<SaveWithEmptyTitleTest>(environment, xpiksTests));
integrationTests.emplace_back(std::make_shared<CombinedEditFixSpellingTest>(environment, xpiksTests));
integrationTests.emplace_back(std::make_shared<FindAndReplaceModelTest>(environment, xpiksTests));
integrationTests.emplace_back(std::make_shared<AddToUserDictionaryTest>(environment, xpiksTests));
integrationTests.emplace_back(std::make_shared<AutoDetachVectorTest>(environment, xpiksTests));
integrationTests.emplace_back(std::make_shared<RemoveFromUserDictionaryTest>(environment, xpiksTests));
integrationTests.emplace_back(std::make_shared<ArtworkUploaderBasicTest>(environment, xpiksTests));
integrationTests.emplace_back(std::make_shared<PlainTextEditTest>(environment, xpiksTests));
integrationTests.emplace_back(std::make_shared<FixSpellingMarksModifiedTest>(environment, xpiksTests));
integrationTests.emplace_back(std::make_shared<PresetsTest>(environment, xpiksTests));
integrationTests.emplace_back(std::make_shared<TranslatorBasicTest>(environment, xpiksTests));
integrationTests.emplace_back(std::make_shared<UserDictEditTest>(environment, xpiksTests));
integrationTests.emplace_back(std::make_shared<WeirdNamesReadTest>(environment, xpiksTests));
integrationTests.emplace_back(std::make_shared<RestoreSessionTest>(environment, xpiksTests));
integrationTests.emplace_back(std::make_shared<DuplicateSearchTest>(environment, xpiksTests));
integrationTests.emplace_back(std::make_shared<AutoCompletePresetsTest>(environment, xpiksTests));
integrationTests.emplace_back(std::make_shared<CsvExportTest>(environment, xpiksTests));
integrationTests.emplace_back(std::make_shared<UnicodeIoTest>(environment, xpiksTests));
integrationTests.emplace_back(std::make_shared<UndoAddDirectoryTest>(environment, xpiksTests));
integrationTests.emplace_back(std::make_shared<UndoRestoreSessionTest>(environment, xpiksTests));
integrationTests.emplace_back(std::make_shared<MasterPasswordTest>(environment, xpiksTests));
integrationTests.emplace_back(std::make_shared<ReimportTest>(environment, xpiksTests));
integrationTests.emplace_back(std::make_shared<AutoImportTest>(environment, xpiksTests));
integrationTests.emplace_back(std::make_shared<ImportLostMetadataTest>(environment, xpiksTests));
integrationTests.emplace_back(std::make_shared<WarningsCombinedTest>(environment, xpiksTests));
integrationTests.emplace_back(std::make_shared<CsvDefaultExportTest>(environment, xpiksTests));
integrationTests.emplace_back(std::make_shared<LoadPluginBasicTest>(environment, xpiksTests));
integrationTests.emplace_back(std::make_shared<StockFtpAutoCompleteTest>(environment, xpiksTests));
// always the last one. insert new tests above
integrationTests.emplace_back(std::make_shared<LocalLibrarySearchTest>(environment, xpiksTests));
qInfo("\n");
int succeededTestsCount = 0, failedTestsCount = 0;
QStringList failedTests;
for (auto &test: integrationTests) {
QThread::msleep(500);
qInfo("---------------------------------------------------------");
qInfo("Running test: %s", test->testName().toStdString().c_str());
test->setup();
const int testResult = test->doTest();
test->teardown();
result += testResult;
if (testResult == 0) {
succeededTestsCount++;
qInfo("Test %s PASSED", test->testName().toStdString().c_str());
} else {
failedTestsCount++;
qInfo("Test %s FAILED", test->testName().toStdString().c_str());
failedTests.append(test->testName());
}
qInfo("\n");
}
qInfo() << "--------------------------";
qInfo() << "In memory run:" << environment.getIsInMemoryOnly();
qInfo() << "Integration Tests Results:" << succeededTestsCount << "succeeded," << failedTestsCount << "failed";
qInfo() << "Tests return code" << result;
if (!failedTests.empty()) {
qInfo() << "FAILED TESTS:" << failedTests.join(", ");
}
qInfo() << "--------------------------";
QTimer debuggingTimer;
debuggingTimer.setSingleShot(true);
QObject::connect(&debuggingTimer, &QTimer::timeout,
[]() {
Q_ASSERT(false);
});
// assert in 1 minute to see hung threads
debuggingTimer.start(60*1000);
qInfo() << "--";
qInfo() << "-----> Crash timer started...";
qInfo() << "--";
xpiksTests.stop();
// for the logs to appear
app.processEvents();
QThread::sleep(1);
std::cout << "Integration tests finished" << std::endl;
return result;
}
<|endoftext|> |
<commit_before>/* IBM_PROLOG_BEGIN_TAG */
/* This is an automatically generated prolog. */
/* */
/* $Source: chips/p9/common/include/perv_scom_addresses_fld_fixes.H $ */
/* */
/* IBM CONFIDENTIAL */
/* */
/* EKB Project */
/* */
/* COPYRIGHT 2015 */
/* [+] International Business Machines Corp. */
/* */
/* */
/* The source code for this program is not published or otherwise */
/* divested of its trade secrets, irrespective of what has been */
/* deposited with the U.S. Copyright Office. */
/* */
/* IBM_PROLOG_END_TAG */
///
/// @file perv_scom_addresses_fld_fixes.H
/// @brief The *scom_addresses_fld.H files are generated form figtree,
/// but the figree can be wrong. This file is included in
/// *_scom_addresses_fld.H and allows incorrect constants to be
/// fixed manually.
///
// *HWP HWP Owner: Ben Gass <bgass@us.ibm.com>
// *HWP FW Owner: ? <?>
// *HWP Team: SAO
// *HWP Level: 1
// *HWP Consumed by: FSP:HB:HS:OCC:SBE:CME:SGPE:PGPE:FPPE:IPPE
#ifndef __P9_PERV_SCOM_ADDRESSES_FLD_FIXES_H
#define __P9_PERV_SCOM_ADDRESSES_FLD_FIXES_H
//Example
//Copy the whole line from the *scom_addresses_fld.H file. Then add FIX in front of REG
//and add another paramter that is the new value you want.
//
//FIXREG64_FLD( PU_ALTD_CMD_REG_FBC_WITH_TM_QUIESCE, 24, SH_UNT, SH_ACS_SCOM, SH_FLD_FBC_WITH_TM_QUIESCE,
// 12);
#endif
<commit_msg>Fix all incorrect copyright prologs<commit_after>/* IBM_PROLOG_BEGIN_TAG */
/* This is an automatically generated prolog. */
/* */
/* $Source: chips/p9/common/include/p9_perv_scom_addresses_fld_fixes.H $ */
/* */
/* IBM CONFIDENTIAL */
/* */
/* EKB Project */
/* */
/* COPYRIGHT 2015 */
/* [+] International Business Machines Corp. */
/* */
/* */
/* The source code for this program is not published or otherwise */
/* divested of its trade secrets, irrespective of what has been */
/* deposited with the U.S. Copyright Office. */
/* */
/* IBM_PROLOG_END_TAG */
///
/// @file perv_scom_addresses_fld_fixes.H
/// @brief The *scom_addresses_fld.H files are generated form figtree,
/// but the figree can be wrong. This file is included in
/// *_scom_addresses_fld.H and allows incorrect constants to be
/// fixed manually.
///
// *HWP HWP Owner: Ben Gass <bgass@us.ibm.com>
// *HWP FW Owner: ? <?>
// *HWP Team: SAO
// *HWP Level: 1
// *HWP Consumed by: FSP:HB:HS:OCC:SBE:CME:SGPE:PGPE:FPPE:IPPE
#ifndef __P9_PERV_SCOM_ADDRESSES_FLD_FIXES_H
#define __P9_PERV_SCOM_ADDRESSES_FLD_FIXES_H
//Example
//Copy the whole line from the *scom_addresses_fld.H file. Then add FIX in front of REG
//and add another paramter that is the new value you want.
//
//FIXREG64_FLD( PU_ALTD_CMD_REG_FBC_WITH_TM_QUIESCE, 24, SH_UNT, SH_ACS_SCOM, SH_FLD_FBC_WITH_TM_QUIESCE,
// 12);
#endif
<|endoftext|> |
<commit_before>// SSSSCpp.cpp : Defines the entry point for the console application.
//
#include "stdafx.h"
#include "GF256.h"
#include "SSSSCpp.h"
#include <vector>
#include <stdio.h>
#include <iostream>
#include <fstream>
#include <sstream>
#include <iomanip>
#include <time.h>
#include "boost/filesystem.hpp"
#include "boost/program_options.hpp"
#include "boost/lexical_cast.hpp"
#include <assert.h>
#define UINT unsigned int
namespace
{
const size_t ERROR_IN_COMMAND_LINE = 1;
const size_t SUCCESS = 0;
const size_t ERROR_UNHANDLED_EXCEPTION = 2;
} // namespace
using std::vector; using std::string;
using boost::filesystem::path;
int main(int argc, char* argv[])
{
GF256init();
srand(time(NULL));
try
{
/** Define and parse the program options
*/
namespace po = boost::program_options;
po::options_description desc("Program Usage");
desc.add_options()
("help,h", "Print help messages")
("split,s", po::value<vector<string>>()->multitoken(), "Split a file")
("reconstruct,r", po::value<vector<string>>()->multitoken(), "Reconstruct a file from its shares");
//("reconstruct,r", po::value<vector<string>>(&reconInputPaths), "Reconstruct a file from its shares");
//("options,o", "additional options")
po::variables_map vm;
try
{
po::store(po::parse_command_line(argc, argv, desc),
vm); // throws on error
/** --help option
*/
if (vm.count("help"))
{
std::cout << "Basic Command Line Parameter App" << std::endl
<< desc << std::endl;
return SUCCESS;
}
if (vm.count("split")) {
std::cout << "Splitting" << std::endl;
vector<string> const &splitInputs = vm["split"].as<vector<string>>();
if (splitInputs.size() != 3) {
throw po::error("Split usage: [Input File] [Total Share #] [Share Number Required to Reconstruct]");
}
path inputPath(splitInputs[0]);
try {
int n = boost::lexical_cast<int>(splitInputs[1].c_str());
int k = boost::lexical_cast<int>(splitInputs[2].c_str());
if (n <= 0 || k <= 0 || n > 255 || k > 255) {
throw po::error("n and k must be between 1 and 255 (inclusive)");
}
if (n < k) {
throw po::error("n must be larger or equal to k");
}
splitSecretFile(inputPath, n, k);
}
catch (boost::bad_any_cast &e) {
throw po::error("[Total Share Number] and [Share Number Required to Reconstruct] must be numbers");
}
catch (std::exception &e) {
throw po::error(e.what());
}
return SUCCESS;
}
if (vm.count("reconstruct")) {
std::cout << "Reconstructing" << std::endl;
vector<string> const &reconInputs = vm["reconstruct"].as<vector<string>>();
if (reconInputs.size() != 2)
throw po::error("Reconstruct Usage: [Original File Name (and the folder path containing the shares)] [Output File Name (and folder path)]");
path inputFile(reconInputs[0]);
path outputFile(reconInputs[1]);
try {
reconstructSecretFile(inputFile, outputFile);
}
catch (std::exception &e) {
throw po::error(e.what());
}
}
po::notify(vm); // throws on error, so do after help in case there are any problems
}
catch(po::error& e)
{
std::cerr << "ERROR: " << e.what() << std::endl << std::endl;
std::cerr << desc << std::endl;
return ERROR_IN_COMMAND_LINE;
}
// application code here //
}
catch(std::exception& e)
{
std::cerr << "Unhandled Exception reached the top of main: "
<< e.what() << ", application will now exit" << std::endl;
return ERROR_UNHANDLED_EXCEPTION;
}
return SUCCESS;
return 0;
}<commit_msg>splitting: fixed typo in catching bad_lexical_cast<commit_after>// SSSSCpp.cpp : Defines the entry point for the console application.
//
#include "stdafx.h"
#include "GF256.h"
#include "SSSSCpp.h"
#include <vector>
#include <stdio.h>
#include <iostream>
#include <fstream>
#include <sstream>
#include <iomanip>
#include <time.h>
#include "boost/filesystem.hpp"
#include "boost/program_options.hpp"
#include "boost/lexical_cast.hpp"
#include <assert.h>
#define UINT unsigned int
namespace
{
const size_t ERROR_IN_COMMAND_LINE = 1;
const size_t SUCCESS = 0;
const size_t ERROR_UNHANDLED_EXCEPTION = 2;
} // namespace
using std::vector; using std::string;
using boost::filesystem::path;
int main(int argc, char* argv[])
{
GF256init();
srand(time(NULL));
try
{
/** Define and parse the program options
*/
namespace po = boost::program_options;
po::options_description desc("Program Usage");
desc.add_options()
("help,h", "Print help messages")
("split,s", po::value<vector<string>>()->multitoken(), "Split a file")
("reconstruct,r", po::value<vector<string>>()->multitoken(), "Reconstruct a file from its shares");
//("reconstruct,r", po::value<vector<string>>(&reconInputPaths), "Reconstruct a file from its shares");
//("options,o", "additional options")
po::variables_map vm;
try
{
po::store(po::parse_command_line(argc, argv, desc),
vm); // throws on error
/** --help option
*/
if (vm.count("help"))
{
std::cout << "Basic Command Line Parameter App" << std::endl
<< desc << std::endl;
return SUCCESS;
}
if (vm.count("split")) {
std::cout << "Splitting" << std::endl;
vector<string> const &splitInputs = vm["split"].as<vector<string>>();
if (splitInputs.size() != 3) {
throw po::error("Split usage: [Input File] [Total Share #] [Share Number Required to Reconstruct]");
}
path inputPath(splitInputs[0]);
try {
int n = boost::lexical_cast<int>(splitInputs[1].c_str());
int k = boost::lexical_cast<int>(splitInputs[2].c_str());
if (n <= 0 || k <= 0 || n > 255 || k > 255) {
throw po::error("n and k must be between 1 and 255 (inclusive)");
}
if (n < k) {
throw po::error("n must be larger or equal to k");
}
splitSecretFile(inputPath, n, k);
}
catch (boost::bad_lexical_cast &e) {
throw po::error("[Total Share Number] and [Share Number Required to Reconstruct] must be numbers");
}
catch (std::exception &e) {
throw po::error(e.what());
}
return SUCCESS;
}
if (vm.count("reconstruct")) {
std::cout << "Reconstructing" << std::endl;
vector<string> const &reconInputs = vm["reconstruct"].as<vector<string>>();
if (reconInputs.size() != 2)
throw po::error("Reconstruct Usage: [Original File Name (and the folder path containing the shares)] [Output File Name (and folder path)]");
path inputFile(reconInputs[0]);
path outputFile(reconInputs[1]);
try {
reconstructSecretFile(inputFile, outputFile);
}
catch (std::exception &e) {
throw po::error(e.what());
}
}
po::notify(vm); // throws on error, so do after help in case there are any problems
}
catch(po::error& e)
{
std::cerr << "ERROR: " << e.what() << std::endl << std::endl;
std::cerr << desc << std::endl;
return ERROR_IN_COMMAND_LINE;
}
// application code here //
}
catch(std::exception& e)
{
std::cerr << "Unhandled Exception reached the top of main: "
<< e.what() << ", application will now exit" << std::endl;
return ERROR_UNHANDLED_EXCEPTION;
}
return SUCCESS;
return 0;
}<|endoftext|> |
<commit_before>/****************************************************************************
*
* Copyright (c) 2016 PX4 Development Team. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
* 3. Neither the name PX4 nor the names of its contributors may be
* used to endorse or promote products derived from this software
* without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS
* OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED
* AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
* ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*
****************************************************************************/
/**
* @file df_hmc5883_wrapper.cpp
* Lightweight driver to access the HMC5883 of the DriverFramework.
*
* @author Julian Oes <julian@oes.ch>
*/
#include <px4_config.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <stdint.h>
#include <stddef.h>
#include <stdlib.h>
#include <string.h>
#include <math.h>
#include <unistd.h>
#include <px4_getopt.h>
#include <errno.h>
#include <systemlib/perf_counter.h>
#include <systemlib/err.h>
#include <drivers/drv_mag.h>
#include <uORB/topics/parameter_update.h>
#include <board_config.h>
#include <lib/conversion/rotation.h>
#include <hmc5883/HMC5883.hpp>
#include <DevMgr.hpp>
extern "C" { __EXPORT int df_hmc5883_wrapper_main(int argc, char *argv[]); }
using namespace DriverFramework;
class DfHmc9250Wrapper : public HMC5883
{
public:
DfHmc9250Wrapper(enum Rotation rotation);
~DfHmc9250Wrapper();
/**
* Start automatic measurement.
*
* @return 0 on success
*/
int start();
/**
* Stop automatic measurement.
*
* @return 0 on success
*/
int stop();
private:
int _publish(struct mag_sensor_data &data);
void _update_mag_calibration();
orb_advert_t _mag_topic;
int _param_update_sub;
struct mag_calibration_s {
float x_offset;
float x_scale;
float y_offset;
float y_scale;
float z_offset;
float z_scale;
} _mag_calibration;
math::Matrix<3, 3> _rotation_matrix;
int _mag_orb_class_instance;
perf_counter_t _mag_sample_perf;
};
DfHmc9250Wrapper::DfHmc9250Wrapper(enum Rotation rotation) :
HMC5883(MAG_DEVICE_PATH),
_mag_topic(nullptr),
_param_update_sub(-1),
_mag_calibration{},
_mag_orb_class_instance(-1),
_mag_sample_perf(perf_alloc(PC_ELAPSED, "df_mag_read"))
{
// Set sane default calibration values
_mag_calibration.x_scale = 1.0f;
_mag_calibration.y_scale = 1.0f;
_mag_calibration.z_scale = 1.0f;
_mag_calibration.x_offset = 0.0f;
_mag_calibration.y_offset = 0.0f;
_mag_calibration.z_offset = 0.0f;
// Get sensor rotation matrix
get_rot_matrix(rotation, &_rotation_matrix);
}
DfHmc9250Wrapper::~DfHmc9250Wrapper()
{
perf_free(_mag_sample_perf);
}
int DfHmc9250Wrapper::start()
{
/* Subscribe to param update topic. */
if (_param_update_sub < 0) {
_param_update_sub = orb_subscribe(ORB_ID(parameter_update));
}
/* Init device and start sensor. */
int ret = init();
if (ret != 0) {
PX4_ERR("HMC5883 init fail: %d", ret);
return ret;
}
ret = HMC5883::start();
if (ret != 0) {
PX4_ERR("HMC5883 start fail: %d", ret);
return ret;
}
/* Force getting the calibration values. */
_update_mag_calibration();
return 0;
}
int DfHmc9250Wrapper::stop()
{
/* Stop sensor. */
int ret = HMC5883::stop();
if (ret != 0) {
PX4_ERR("HMC5883 stop fail: %d", ret);
return ret;
}
return 0;
}
void DfHmc9250Wrapper::_update_mag_calibration()
{
// TODO: replace magic number
for (unsigned i = 0; i < 3; ++i) {
// TODO: remove printfs and add error counter
char str[30];
(void)sprintf(str, "CAL_MAG%u_ID", i);
int32_t device_id;
int res = param_get(param_find(str), &device_id);
if (res != OK) {
PX4_ERR("Could not access param %s", str);
continue;
}
if ((uint32_t)device_id != m_id.dev_id) {
continue;
}
(void)sprintf(str, "CAL_MAG%u_XSCALE", i);
res = param_get(param_find(str), &_mag_calibration.x_scale);
if (res != OK) {
PX4_ERR("Could not access param %s", str);
}
(void)sprintf(str, "CAL_MAG%u_YSCALE", i);
res = param_get(param_find(str), &_mag_calibration.y_scale);
if (res != OK) {
PX4_ERR("Could not access param %s", str);
}
(void)sprintf(str, "CAL_MAG%u_ZSCALE", i);
res = param_get(param_find(str), &_mag_calibration.z_scale);
if (res != OK) {
PX4_ERR("Could not access param %s", str);
}
(void)sprintf(str, "CAL_MAG%u_XOFF", i);
res = param_get(param_find(str), &_mag_calibration.x_offset);
if (res != OK) {
PX4_ERR("Could not access param %s", str);
}
(void)sprintf(str, "CAL_MAG%u_YOFF", i);
res = param_get(param_find(str), &_mag_calibration.y_offset);
if (res != OK) {
PX4_ERR("Could not access param %s", str);
}
(void)sprintf(str, "CAL_MAG%u_ZOFF", i);
res = param_get(param_find(str), &_mag_calibration.z_offset);
if (res != OK) {
PX4_ERR("Could not access param %s", str);
}
}
}
int DfHmc9250Wrapper::_publish(struct mag_sensor_data &data)
{
/* Check if calibration values are still up-to-date. */
bool updated;
orb_check(_param_update_sub, &updated);
if (updated) {
parameter_update_s parameter_update;
orb_copy(ORB_ID(parameter_update), _param_update_sub, ¶meter_update);
_update_mag_calibration();
}
/* Publish mag first. */
perf_begin(_mag_sample_perf);
mag_report mag_report = {};
mag_report.timestamp = hrt_absolute_time();
/* The standard external mag by 3DR has x pointing to the
* right, y pointing backwards, and z down, therefore switch x
* and y and invert y. */
const float tmp = data.field_x_ga;
data.field_x_ga = -data.field_y_ga;
data.field_y_ga = tmp;
// TODO: remove these (or get the values)
mag_report.x_raw = NAN;
mag_report.y_raw = NAN;
mag_report.z_raw = NAN;
math::Vector<3> mag_val((data.mag_ga_x - _mag_calibration.x_offset) * _mag_calibration.x_scale,
(data.mag_ga_y - _mag_calibration.y_offset) * _mag_calibration.y_scale,
(data.mag_ga_z - _mag_calibration.z_offset) * _mag_calibration.z_scale);
// apply sensor rotation on the accel measurement
mag_val = _rotation_matrix * mag_val;
mag_report.x = mag_val(0);
mag_report.y = mag_val(1);
mag_report.z = mag_val(2);
// TODO: get these right
//mag_report.scaling = -1.0f;
//mag_report.range_m_s2 = -1.0f;
mag_report.device_id = m_id.dev_id;
// TODO: when is this ever blocked?
if (!(m_pub_blocked)) {
if (_mag_topic == nullptr) {
_mag_topic = orb_advertise_multi(ORB_ID(sensor_mag), &mag_report,
&_mag_orb_class_instance, ORB_PRIO_HIGH);
} else {
orb_publish(ORB_ID(sensor_mag), _mag_topic, &mag_report);
}
}
perf_end(_mag_sample_perf);
/* Notify anyone waiting for data. */
DevMgr::updateNotify(*this);
return 0;
};
namespace df_hmc5883_wrapper
{
DfHmc9250Wrapper *g_dev = nullptr;
int start(enum Rotation rotation);
int stop();
int info();
void usage();
int start(enum Rotation rotation)
{
g_dev = new DfHmc9250Wrapper(rotation);
if (g_dev == nullptr) {
PX4_ERR("failed instantiating DfHmc9250Wrapper object");
return -1;
}
int ret = g_dev->start();
if (ret != 0) {
PX4_ERR("DfHmc9250Wrapper start failed");
return ret;
}
// Open the MAG sensor
DevHandle h;
DevMgr::getHandle(MAG_DEVICE_PATH, h);
if (!h.isValid()) {
DF_LOG_INFO("Error: unable to obtain a valid handle for the receiver at: %s (%d)",
MAG_DEVICE_PATH, h.getError());
return -1;
}
DevMgr::releaseHandle(h);
return 0;
}
int stop()
{
if (g_dev == nullptr) {
PX4_ERR("driver not running");
return 1;
}
int ret = g_dev->stop();
if (ret != 0) {
PX4_ERR("driver could not be stopped");
return ret;
}
delete g_dev;
g_dev = nullptr;
return 0;
}
/**
* Print a little info about the driver.
*/
int
info()
{
if (g_dev == nullptr) {
PX4_ERR("driver not running");
return 1;
}
PX4_DEBUG("state @ %p", g_dev);
return 0;
}
void
usage()
{
PX4_INFO("Usage: df_hmc5883_wrapper 'start', 'info', 'stop'");
PX4_INFO("options:");
PX4_INFO(" -R rotation");
}
} // namespace df_hmc5883_wrapper
int
df_hmc5883_wrapper_main(int argc, char *argv[])
{
int ch;
enum Rotation rotation = ROTATION_NONE;
int ret = 0;
int myoptind = 1;
const char *myoptarg = NULL;
/* jump over start/off/etc and look at options first */
while ((ch = px4_getopt(argc, argv, "R:", &myoptind, &myoptarg)) != EOF) {
switch (ch) {
case 'R':
rotation = (enum Rotation)atoi(myoptarg);
break;
default:
df_hmc5883_wrapper::usage();
return 0;
}
}
if (argc <= 1) {
df_hmc5883_wrapper::usage();
return 1;
}
const char *verb = argv[myoptind];
if (!strcmp(verb, "start")) {
ret = df_hmc5883_wrapper::start(rotation);
}
else if (!strcmp(verb, "stop")) {
ret = df_hmc5883_wrapper::stop();
}
else if (!strcmp(verb, "info")) {
ret = df_hmc5883_wrapper::info();
}
else {
df_hmc5883_wrapper::usage();
return 1;
}
return ret;
}
<commit_msg>df_hmc5883_wrapper: fix wrong variable name<commit_after>/****************************************************************************
*
* Copyright (c) 2016 PX4 Development Team. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
* 3. Neither the name PX4 nor the names of its contributors may be
* used to endorse or promote products derived from this software
* without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS
* OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED
* AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
* ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*
****************************************************************************/
/**
* @file df_hmc5883_wrapper.cpp
* Lightweight driver to access the HMC5883 of the DriverFramework.
*
* @author Julian Oes <julian@oes.ch>
*/
#include <px4_config.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <stdint.h>
#include <stddef.h>
#include <stdlib.h>
#include <string.h>
#include <math.h>
#include <unistd.h>
#include <px4_getopt.h>
#include <errno.h>
#include <systemlib/perf_counter.h>
#include <systemlib/err.h>
#include <drivers/drv_mag.h>
#include <uORB/topics/parameter_update.h>
#include <board_config.h>
#include <lib/conversion/rotation.h>
#include <hmc5883/HMC5883.hpp>
#include <DevMgr.hpp>
extern "C" { __EXPORT int df_hmc5883_wrapper_main(int argc, char *argv[]); }
using namespace DriverFramework;
class DfHmc9250Wrapper : public HMC5883
{
public:
DfHmc9250Wrapper(enum Rotation rotation);
~DfHmc9250Wrapper();
/**
* Start automatic measurement.
*
* @return 0 on success
*/
int start();
/**
* Stop automatic measurement.
*
* @return 0 on success
*/
int stop();
private:
int _publish(struct mag_sensor_data &data);
void _update_mag_calibration();
orb_advert_t _mag_topic;
int _param_update_sub;
struct mag_calibration_s {
float x_offset;
float x_scale;
float y_offset;
float y_scale;
float z_offset;
float z_scale;
} _mag_calibration;
math::Matrix<3, 3> _rotation_matrix;
int _mag_orb_class_instance;
perf_counter_t _mag_sample_perf;
};
DfHmc9250Wrapper::DfHmc9250Wrapper(enum Rotation rotation) :
HMC5883(MAG_DEVICE_PATH),
_mag_topic(nullptr),
_param_update_sub(-1),
_mag_calibration{},
_mag_orb_class_instance(-1),
_mag_sample_perf(perf_alloc(PC_ELAPSED, "df_mag_read"))
{
// Set sane default calibration values
_mag_calibration.x_scale = 1.0f;
_mag_calibration.y_scale = 1.0f;
_mag_calibration.z_scale = 1.0f;
_mag_calibration.x_offset = 0.0f;
_mag_calibration.y_offset = 0.0f;
_mag_calibration.z_offset = 0.0f;
// Get sensor rotation matrix
get_rot_matrix(rotation, &_rotation_matrix);
}
DfHmc9250Wrapper::~DfHmc9250Wrapper()
{
perf_free(_mag_sample_perf);
}
int DfHmc9250Wrapper::start()
{
/* Subscribe to param update topic. */
if (_param_update_sub < 0) {
_param_update_sub = orb_subscribe(ORB_ID(parameter_update));
}
/* Init device and start sensor. */
int ret = init();
if (ret != 0) {
PX4_ERR("HMC5883 init fail: %d", ret);
return ret;
}
ret = HMC5883::start();
if (ret != 0) {
PX4_ERR("HMC5883 start fail: %d", ret);
return ret;
}
/* Force getting the calibration values. */
_update_mag_calibration();
return 0;
}
int DfHmc9250Wrapper::stop()
{
/* Stop sensor. */
int ret = HMC5883::stop();
if (ret != 0) {
PX4_ERR("HMC5883 stop fail: %d", ret);
return ret;
}
return 0;
}
void DfHmc9250Wrapper::_update_mag_calibration()
{
// TODO: replace magic number
for (unsigned i = 0; i < 3; ++i) {
// TODO: remove printfs and add error counter
char str[30];
(void)sprintf(str, "CAL_MAG%u_ID", i);
int32_t device_id;
int res = param_get(param_find(str), &device_id);
if (res != OK) {
PX4_ERR("Could not access param %s", str);
continue;
}
if ((uint32_t)device_id != m_id.dev_id) {
continue;
}
(void)sprintf(str, "CAL_MAG%u_XSCALE", i);
res = param_get(param_find(str), &_mag_calibration.x_scale);
if (res != OK) {
PX4_ERR("Could not access param %s", str);
}
(void)sprintf(str, "CAL_MAG%u_YSCALE", i);
res = param_get(param_find(str), &_mag_calibration.y_scale);
if (res != OK) {
PX4_ERR("Could not access param %s", str);
}
(void)sprintf(str, "CAL_MAG%u_ZSCALE", i);
res = param_get(param_find(str), &_mag_calibration.z_scale);
if (res != OK) {
PX4_ERR("Could not access param %s", str);
}
(void)sprintf(str, "CAL_MAG%u_XOFF", i);
res = param_get(param_find(str), &_mag_calibration.x_offset);
if (res != OK) {
PX4_ERR("Could not access param %s", str);
}
(void)sprintf(str, "CAL_MAG%u_YOFF", i);
res = param_get(param_find(str), &_mag_calibration.y_offset);
if (res != OK) {
PX4_ERR("Could not access param %s", str);
}
(void)sprintf(str, "CAL_MAG%u_ZOFF", i);
res = param_get(param_find(str), &_mag_calibration.z_offset);
if (res != OK) {
PX4_ERR("Could not access param %s", str);
}
}
}
int DfHmc9250Wrapper::_publish(struct mag_sensor_data &data)
{
/* Check if calibration values are still up-to-date. */
bool updated;
orb_check(_param_update_sub, &updated);
if (updated) {
parameter_update_s parameter_update;
orb_copy(ORB_ID(parameter_update), _param_update_sub, ¶meter_update);
_update_mag_calibration();
}
/* Publish mag first. */
perf_begin(_mag_sample_perf);
mag_report mag_report = {};
mag_report.timestamp = hrt_absolute_time();
/* The standard external mag by 3DR has x pointing to the
* right, y pointing backwards, and z down, therefore switch x
* and y and invert y. */
const float tmp = data.field_x_ga;
data.field_x_ga = -data.field_y_ga;
data.field_y_ga = tmp;
// TODO: remove these (or get the values)
mag_report.x_raw = NAN;
mag_report.y_raw = NAN;
mag_report.z_raw = NAN;
math::Vector<3> mag_val((data.field_x_ga - _mag_calibration.x_offset) * _mag_calibration.x_scale,
(data.field_y_ga - _mag_calibration.y_offset) * _mag_calibration.y_scale,
(data.field_z_ga - _mag_calibration.z_offset) * _mag_calibration.z_scale);
// apply sensor rotation on the accel measurement
mag_val = _rotation_matrix * mag_val;
mag_report.x = mag_val(0);
mag_report.y = mag_val(1);
mag_report.z = mag_val(2);
// TODO: get these right
//mag_report.scaling = -1.0f;
//mag_report.range_m_s2 = -1.0f;
mag_report.device_id = m_id.dev_id;
// TODO: when is this ever blocked?
if (!(m_pub_blocked)) {
if (_mag_topic == nullptr) {
_mag_topic = orb_advertise_multi(ORB_ID(sensor_mag), &mag_report,
&_mag_orb_class_instance, ORB_PRIO_HIGH);
} else {
orb_publish(ORB_ID(sensor_mag), _mag_topic, &mag_report);
}
}
perf_end(_mag_sample_perf);
/* Notify anyone waiting for data. */
DevMgr::updateNotify(*this);
return 0;
};
namespace df_hmc5883_wrapper
{
DfHmc9250Wrapper *g_dev = nullptr;
int start(enum Rotation rotation);
int stop();
int info();
void usage();
int start(enum Rotation rotation)
{
g_dev = new DfHmc9250Wrapper(rotation);
if (g_dev == nullptr) {
PX4_ERR("failed instantiating DfHmc9250Wrapper object");
return -1;
}
int ret = g_dev->start();
if (ret != 0) {
PX4_ERR("DfHmc9250Wrapper start failed");
return ret;
}
// Open the MAG sensor
DevHandle h;
DevMgr::getHandle(MAG_DEVICE_PATH, h);
if (!h.isValid()) {
DF_LOG_INFO("Error: unable to obtain a valid handle for the receiver at: %s (%d)",
MAG_DEVICE_PATH, h.getError());
return -1;
}
DevMgr::releaseHandle(h);
return 0;
}
int stop()
{
if (g_dev == nullptr) {
PX4_ERR("driver not running");
return 1;
}
int ret = g_dev->stop();
if (ret != 0) {
PX4_ERR("driver could not be stopped");
return ret;
}
delete g_dev;
g_dev = nullptr;
return 0;
}
/**
* Print a little info about the driver.
*/
int
info()
{
if (g_dev == nullptr) {
PX4_ERR("driver not running");
return 1;
}
PX4_DEBUG("state @ %p", g_dev);
return 0;
}
void
usage()
{
PX4_INFO("Usage: df_hmc5883_wrapper 'start', 'info', 'stop'");
PX4_INFO("options:");
PX4_INFO(" -R rotation");
}
} // namespace df_hmc5883_wrapper
int
df_hmc5883_wrapper_main(int argc, char *argv[])
{
int ch;
enum Rotation rotation = ROTATION_NONE;
int ret = 0;
int myoptind = 1;
const char *myoptarg = NULL;
/* jump over start/off/etc and look at options first */
while ((ch = px4_getopt(argc, argv, "R:", &myoptind, &myoptarg)) != EOF) {
switch (ch) {
case 'R':
rotation = (enum Rotation)atoi(myoptarg);
break;
default:
df_hmc5883_wrapper::usage();
return 0;
}
}
if (argc <= 1) {
df_hmc5883_wrapper::usage();
return 1;
}
const char *verb = argv[myoptind];
if (!strcmp(verb, "start")) {
ret = df_hmc5883_wrapper::start(rotation);
}
else if (!strcmp(verb, "stop")) {
ret = df_hmc5883_wrapper::stop();
}
else if (!strcmp(verb, "info")) {
ret = df_hmc5883_wrapper::info();
}
else {
df_hmc5883_wrapper::usage();
return 1;
}
return ret;
}
<|endoftext|> |
<commit_before>/****************************************************************************
**
** Copyright (C) 2015 The Qt Company Ltd.
** Contact: http://www.qt.io/licensing
**
** This file is part of Qt Creator.
**
** Commercial License Usage
** Licensees holding valid commercial Qt licenses may use this file in
** accordance with the commercial license agreement provided with the
** Software or, alternatively, in accordance with the terms contained in
** a written agreement between you and The Qt Company. For licensing terms and
** conditions see http://www.qt.io/terms-conditions. For further information
** use the contact form at http://www.qt.io/contact-us.
**
** GNU Lesser General Public License Usage
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 or version 3 as published by the Free
** Software Foundation and appearing in the file LICENSE.LGPLv21 and
** LICENSE.LGPLv3 included in the packaging of this file. Please review the
** following information to ensure the GNU Lesser General Public License
** requirements will be met: https://www.gnu.org/licenses/lgpl.html and
** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, The Qt Company gives you certain additional
** rights. These rights are described in The Qt Company LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
****************************************************************************/
#include "subcomponentmanager.h"
#include <qmldesignerconstants.h>
#include "model.h"
#include "metainforeader.h"
#include <utils/algorithm.h>
#include <utils/hostosinfo.h>
#include <coreplugin/messagebox.h>
#include <QDir>
#include <QMessageBox>
#include <QUrl>
#include <qmljs/qmljslink.h>
#include <qmljs/parser/qmljsast_p.h>
#include <qmljs/parser/qmljsengine_p.h>
#include <qmljs/qmljsmodelmanagerinterface.h>
enum { debug = false };
QT_BEGIN_NAMESPACE
// Allow usage of QFileInfo in Utils::sort
static bool operator<(const QFileInfo &file1, const QFileInfo &file2)
{
return file1.filePath() < file2.filePath();
}
QT_END_NAMESPACE
static inline bool checkIfDerivedFromItem(const QString &fileName)
{
return true;
QmlJS::Snapshot snapshot;
QmlJS::ModelManagerInterface *modelManager = QmlJS::ModelManagerInterface::instance();
if (modelManager)
snapshot = modelManager->snapshot();
QFile file(fileName);
if (!file.open(QIODevice::ReadOnly))
return false;
QByteArray source = file.readAll();
file.close();
QmlJS::Document::MutablePtr document =
QmlJS::Document::create(fileName.isEmpty() ?
QStringLiteral("<internal>") : fileName, QmlJS::Dialect::Qml);
document->setSource(source);
document->parseQml();
if (!document->isParsedCorrectly())
return false;
snapshot.insert(document);
QmlJS::Link link(snapshot, modelManager->defaultVContext(document->language(), document), QmlJS::ModelManagerInterface::instance()->builtins(document));
QList<QmlJS::DiagnosticMessage> diagnosticLinkMessages;
QmlJS::ContextPtr context = link(document, &diagnosticLinkMessages);
QmlJS::AST::UiObjectMember *astRootNode = 0;
if (QmlJS::AST::UiProgram *program = document->qmlProgram())
if (program->members)
astRootNode = program->members->member;
QmlJS::AST::UiObjectDefinition *definition = QmlJS::AST::cast<QmlJS::AST::UiObjectDefinition *>(astRootNode);
if (!definition)
return false;
const QmlJS::ObjectValue *objectValue = context->lookupType(document.data(), definition->qualifiedTypeNameId);
QList<const QmlJS::ObjectValue *> prototypes = QmlJS::PrototypeIterator(objectValue, context).all();
foreach (const QmlJS::ObjectValue *prototype, prototypes) {
if (prototype->className() == "Item")
return true;
}
return false;
}
namespace QmlDesigner {
static const QString s_qmlFilePattern = QStringLiteral("*.qml");
SubComponentManager::SubComponentManager(Model *model, QObject *parent)
: QObject(parent),
m_model(model)
{
connect(&m_watcher, SIGNAL(directoryChanged(QString)), this, SLOT(parseDirectory(QString)));
}
void SubComponentManager::addImport(int pos, const Import &import)
{
if (debug)
qDebug() << Q_FUNC_INFO << pos << import.file().toUtf8();
if (import.isFileImport()) {
QFileInfo dirInfo = QFileInfo(m_filePath.resolved(import.file()).toLocalFile());
if (dirInfo.exists() && dirInfo.isDir()) {
const QString canonicalDirPath = dirInfo.canonicalFilePath();
m_watcher.addPath(canonicalDirPath);
//m_dirToQualifier.insertMulti(canonicalDirPath, import.qualifier()); ### todo: proper support for import as
}
} else {
QString url = import.url();
url.replace(QLatin1Char('.'), QLatin1Char('/'));
foreach (const QString &path, importPaths()) {
url = path + QLatin1Char('/') + url;
QFileInfo dirInfo = QFileInfo(url);
if (dirInfo.exists() && dirInfo.isDir()) {
const QString canonicalDirPath = dirInfo.canonicalFilePath();
m_watcher.addPath(canonicalDirPath);
//m_dirToQualifier.insertMulti(canonicalDirPath, import.qualifier()); ### todo: proper support for import as
}
}
// TODO: QDeclarativeDomImport::Library
}
m_imports.insert(pos, import);
}
void SubComponentManager::removeImport(int pos)
{
const Import import = m_imports.takeAt(pos);
if (import.isFileImport()) {
const QFileInfo dirInfo = QFileInfo(m_filePath.resolved(import.file()).toLocalFile());
const QString canonicalDirPath = dirInfo.canonicalFilePath();
//m_dirToQualifier.remove(canonicalDirPath, import.qualifier()); ### todo: proper support for import as
if (!m_dirToQualifier.contains(canonicalDirPath))
m_watcher.removePath(canonicalDirPath);
// foreach (const QFileInfo &monitoredFile, watchedFiles(canonicalDirPath)) { ### todo: proper support for import as
// if (!m_dirToQualifier.contains(canonicalDirPath))
// unregisterQmlFile(monitoredFile, import.qualifier());
// }
} else {
// TODO: QDeclarativeDomImport::Library
}
}
void SubComponentManager::parseDirectories()
{
if (!m_filePath.isEmpty()) {
const QString file = m_filePath.toLocalFile();
QFileInfo dirInfo = QFileInfo(QFileInfo(file).path());
if (dirInfo.exists() && dirInfo.isDir())
parseDirectory(dirInfo.canonicalFilePath());
foreach (const QString &subDir, QDir(QFileInfo(file).path()).entryList(QDir::Dirs | QDir::NoDot | QDir::NoDotDot)) {
parseDirectory(dirInfo.canonicalFilePath() + "/" + subDir, true, subDir.toUtf8());
}
}
foreach (const Import &import, m_imports) {
if (import.isFileImport()) {
QFileInfo dirInfo = QFileInfo(m_filePath.resolved(import.file()).toLocalFile());
if (dirInfo.exists() && dirInfo.isDir())
parseDirectory(dirInfo.canonicalFilePath(), true, dirInfo.baseName().toUtf8());
} else {
QString url = import.url();
url.replace(QLatin1Char('.'), QLatin1Char('/'));
QFileInfo dirInfo = QFileInfo(url);
foreach (const QString &path, importPaths()) {
QString fullUrl = path + QLatin1Char('/') + url;
dirInfo = QFileInfo(fullUrl);
if (dirInfo.exists() && dirInfo.isDir()) {
//### todo full qualified names QString nameSpace = import.uri();
parseDirectory(dirInfo.canonicalFilePath(), false);
}
}
}
}
}
void SubComponentManager::parseDirectory(const QString &canonicalDirPath, bool addToLibrary, const TypeName& qualification)
{
if (!model() || !model()->rewriterView())
return;
QDir designerDir(canonicalDirPath + Constants::QML_DESIGNER_SUBFOLDER);
if (designerDir.exists()) {
QStringList filter;
filter << "*.metainfo";
designerDir.setNameFilters(filter);
QStringList metaFiles = designerDir.entryList(QDir::Files);
foreach (const QFileInfo &metaInfoFile, designerDir.entryInfoList(QDir::Files)) {
if (model() && model()->metaInfo().itemLibraryInfo()) {
Internal::MetaInfoReader reader(model()->metaInfo());
reader.setQualifcation(qualification);
try {
reader.readMetaInfoFile(metaInfoFile.absoluteFilePath(), true);
} catch (const InvalidMetaInfoException &e) {
qWarning() << e.description();
const QString errorMessage = metaInfoFile.absoluteFilePath() + QLatin1Char('\n') + QLatin1Char('\n') + reader.errors().join(QLatin1Char('\n'));
Core::AsynchronousMessageBox::warning(QCoreApplication::translate("SubComponentManager::parseDirectory", "Invalid meta info"),
errorMessage);
}
}
}
if (!metaFiles.isEmpty())
return;
}
if (debug)
qDebug() << Q_FUNC_INFO << canonicalDirPath;
QDir dir(canonicalDirPath);
dir.setNameFilters(QStringList(s_qmlFilePattern));
dir.setFilter(QDir::Files | QDir::Readable | QDir::CaseSensitive);
QList<QFileInfo> monitoredList = watchedFiles(canonicalDirPath);
QList<QFileInfo> newList;
foreach (const QFileInfo &qmlFile, dir.entryInfoList()) {
if (QFileInfo(m_filePath.toLocalFile()) == qmlFile) {
// do not parse main file
continue;
}
if (!qmlFile.fileName().at(0).isUpper()) {
// QML sub components must be upper case
continue;
}
newList << qmlFile;
}
Utils::sort(monitoredList);
Utils::sort(newList);
if (debug)
qDebug() << "monitored list " << monitoredList.size() << "new list " << newList.size();
auto oldIter = monitoredList.constBegin();
auto newIter = newList.constBegin();
while (oldIter != monitoredList.constEnd() && newIter != newList.constEnd()) {
const QFileInfo oldFileInfo = *oldIter;
const QFileInfo newFileInfo = *newIter;
if (oldFileInfo == newFileInfo) {
++oldIter;
++newIter;
continue;
}
if (oldFileInfo < newFileInfo) {
foreach (const QString &qualifier, m_dirToQualifier.value(canonicalDirPath))
unregisterQmlFile(oldFileInfo, qualifier);
m_watcher.removePath(oldFileInfo.filePath());
++oldIter;
continue;
}
// oldFileInfo > newFileInfo
parseFile(newFileInfo.filePath(), addToLibrary, qualification);
++newIter;
}
while (oldIter != monitoredList.constEnd()) {
foreach (const QString &qualifier, m_dirToQualifier.value(canonicalDirPath))
unregisterQmlFile(*oldIter, qualifier);
++oldIter;
}
while (newIter != newList.constEnd()) {
parseFile(newIter->filePath(), addToLibrary, qualification);
if (debug)
qDebug() << "m_watcher.addPath(" << newIter->filePath() << ')';
++newIter;
}
}
void SubComponentManager::parseFile(const QString &canonicalFilePath, bool addToLibrary, const QString& qualification)
{
if (debug)
qDebug() << Q_FUNC_INFO << canonicalFilePath;
QFile file(canonicalFilePath);
if (!file.open(QIODevice::ReadOnly | QIODevice::Text))
return;
QString dir = QFileInfo(canonicalFilePath).path();
foreach (const QString &qualifier, m_dirToQualifier.values(dir)) {
registerQmlFile(canonicalFilePath, qualifier, addToLibrary);
}
registerQmlFile(canonicalFilePath, qualification, addToLibrary);
}
void SubComponentManager::parseFile(const QString &canonicalFilePath)
{
parseFile(canonicalFilePath, true, QString());
}
// dirInfo must already contain a canonical path
QList<QFileInfo> SubComponentManager::watchedFiles(const QString &canonicalDirPath)
{
QList<QFileInfo> files;
foreach (const QString &monitoredFile, m_watcher.files()) {
QFileInfo fileInfo(monitoredFile);
if (fileInfo.dir().absolutePath() == canonicalDirPath)
files.append(fileInfo);
}
return files;
}
void SubComponentManager::unregisterQmlFile(const QFileInfo &fileInfo, const QString &qualifier)
{
QString componentName = fileInfo.baseName();
if (!qualifier.isEmpty())
componentName = qualifier + '.' + componentName;
}
void SubComponentManager::registerQmlFile(const QFileInfo &fileInfo, const QString &qualifier,
bool addToLibrary)
{
if (!model())
return;
if (!checkIfDerivedFromItem(fileInfo.absoluteFilePath()))
return;
QString componentName = fileInfo.baseName();
const QString baseComponentName = componentName;
QString fixedQualifier = qualifier;
if (!qualifier.isEmpty()) {
fixedQualifier = qualifier;
if (qualifier.right(1) == QStringLiteral("."))
fixedQualifier.chop(1); //remove last char if it is a dot
componentName = fixedQualifier + '.' + componentName;
}
if (debug)
qDebug() << "SubComponentManager" << __FUNCTION__ << componentName;
if (addToLibrary) {
// Add file components to the library
ItemLibraryEntry itemLibraryEntry;
itemLibraryEntry.setType(componentName.toUtf8(), -1, -1);
itemLibraryEntry.setName(baseComponentName);
itemLibraryEntry.setCategory("QML Components");
if (!qualifier.isEmpty()) {
itemLibraryEntry.setRequiredImport(fixedQualifier);
}
if (!model()->metaInfo().itemLibraryInfo()->containsEntry(itemLibraryEntry)) {
model()->metaInfo().itemLibraryInfo()->addEntry(itemLibraryEntry);
}
}
}
Model *SubComponentManager::model() const
{
return m_model.data();
}
QStringList SubComponentManager::importPaths() const
{
if (model())
return model()->importPaths();
return QStringList();
}
/*!
\class SubComponentManager
Detects & monitors (potential) component files in a list of directories, and registers
these in the metatype system.
*/
QStringList SubComponentManager::directories() const
{
return m_watcher.directories();
}
QStringList SubComponentManager::qmlFiles() const
{
return m_watcher.files();
}
void SubComponentManager::update(const QUrl &filePath, const QList<Import> &imports)
{
if (debug)
qDebug() << Q_FUNC_INFO << filePath << imports.size();
QFileInfo oldDir, newDir;
if (!m_filePath.isEmpty()) {
const QString file = m_filePath.toLocalFile();
oldDir = QFileInfo(QFileInfo(file).path());
}
if (!filePath.isEmpty()) {
const QString file = filePath.toLocalFile();
newDir = QFileInfo(QFileInfo(file).path());
}
m_filePath = filePath;
//
// (implicit) import of local directory
//
if (oldDir != newDir) {
if (!oldDir.filePath().isEmpty()) {
m_dirToQualifier.remove(oldDir.canonicalFilePath(), QString());
if (!m_dirToQualifier.contains(oldDir.canonicalFilePath()))
m_watcher.removePath(oldDir.filePath());
}
if (!newDir.filePath().isEmpty())
m_dirToQualifier.insertMulti(newDir.canonicalFilePath(), QString());
}
//
// Imports
//
// skip first list items until the lists differ
int i = 0;
while (i < qMin(imports.size(), m_imports.size())) {
if (!(imports.at(i) == m_imports.at(i)))
break;
++i;
}
for (int ii = m_imports.size() - 1; ii >= i; --ii)
removeImport(ii);
for (int ii = i; ii < imports.size(); ++ii) {
addImport(ii, imports.at(ii));
}
parseDirectories();
}
} // namespace QmlDesigner
<commit_msg>QmlDesigner: Parse .metainfo file if plugin path contains version<commit_after>/****************************************************************************
**
** Copyright (C) 2015 The Qt Company Ltd.
** Contact: http://www.qt.io/licensing
**
** This file is part of Qt Creator.
**
** Commercial License Usage
** Licensees holding valid commercial Qt licenses may use this file in
** accordance with the commercial license agreement provided with the
** Software or, alternatively, in accordance with the terms contained in
** a written agreement between you and The Qt Company. For licensing terms and
** conditions see http://www.qt.io/terms-conditions. For further information
** use the contact form at http://www.qt.io/contact-us.
**
** GNU Lesser General Public License Usage
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 or version 3 as published by the Free
** Software Foundation and appearing in the file LICENSE.LGPLv21 and
** LICENSE.LGPLv3 included in the packaging of this file. Please review the
** following information to ensure the GNU Lesser General Public License
** requirements will be met: https://www.gnu.org/licenses/lgpl.html and
** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, The Qt Company gives you certain additional
** rights. These rights are described in The Qt Company LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
****************************************************************************/
#include "subcomponentmanager.h"
#include <qmldesignerconstants.h>
#include "model.h"
#include "metainforeader.h"
#include <utils/algorithm.h>
#include <utils/hostosinfo.h>
#include <coreplugin/messagebox.h>
#include <QDir>
#include <QMessageBox>
#include <QUrl>
#include <qmljs/qmljslink.h>
#include <qmljs/parser/qmljsast_p.h>
#include <qmljs/parser/qmljsengine_p.h>
#include <qmljs/qmljsmodelmanagerinterface.h>
enum { debug = false };
QT_BEGIN_NAMESPACE
// Allow usage of QFileInfo in Utils::sort
static bool operator<(const QFileInfo &file1, const QFileInfo &file2)
{
return file1.filePath() < file2.filePath();
}
QT_END_NAMESPACE
static inline bool checkIfDerivedFromItem(const QString &fileName)
{
return true;
QmlJS::Snapshot snapshot;
QmlJS::ModelManagerInterface *modelManager = QmlJS::ModelManagerInterface::instance();
if (modelManager)
snapshot = modelManager->snapshot();
QFile file(fileName);
if (!file.open(QIODevice::ReadOnly))
return false;
QByteArray source = file.readAll();
file.close();
QmlJS::Document::MutablePtr document =
QmlJS::Document::create(fileName.isEmpty() ?
QStringLiteral("<internal>") : fileName, QmlJS::Dialect::Qml);
document->setSource(source);
document->parseQml();
if (!document->isParsedCorrectly())
return false;
snapshot.insert(document);
QmlJS::Link link(snapshot, modelManager->defaultVContext(document->language(), document), QmlJS::ModelManagerInterface::instance()->builtins(document));
QList<QmlJS::DiagnosticMessage> diagnosticLinkMessages;
QmlJS::ContextPtr context = link(document, &diagnosticLinkMessages);
QmlJS::AST::UiObjectMember *astRootNode = 0;
if (QmlJS::AST::UiProgram *program = document->qmlProgram())
if (program->members)
astRootNode = program->members->member;
QmlJS::AST::UiObjectDefinition *definition = QmlJS::AST::cast<QmlJS::AST::UiObjectDefinition *>(astRootNode);
if (!definition)
return false;
const QmlJS::ObjectValue *objectValue = context->lookupType(document.data(), definition->qualifiedTypeNameId);
QList<const QmlJS::ObjectValue *> prototypes = QmlJS::PrototypeIterator(objectValue, context).all();
foreach (const QmlJS::ObjectValue *prototype, prototypes) {
if (prototype->className() == "Item")
return true;
}
return false;
}
namespace QmlDesigner {
static const QString s_qmlFilePattern = QStringLiteral("*.qml");
SubComponentManager::SubComponentManager(Model *model, QObject *parent)
: QObject(parent),
m_model(model)
{
connect(&m_watcher, SIGNAL(directoryChanged(QString)), this, SLOT(parseDirectory(QString)));
}
void SubComponentManager::addImport(int pos, const Import &import)
{
if (debug)
qDebug() << Q_FUNC_INFO << pos << import.file().toUtf8();
if (import.isFileImport()) {
QFileInfo dirInfo = QFileInfo(m_filePath.resolved(import.file()).toLocalFile());
if (dirInfo.exists() && dirInfo.isDir()) {
const QString canonicalDirPath = dirInfo.canonicalFilePath();
m_watcher.addPath(canonicalDirPath);
//m_dirToQualifier.insertMulti(canonicalDirPath, import.qualifier()); ### todo: proper support for import as
}
} else {
QString url = import.url();
url.replace(QLatin1Char('.'), QLatin1Char('/'));
foreach (const QString &path, importPaths()) {
url = path + QLatin1Char('/') + url;
QFileInfo dirInfo = QFileInfo(url);
if (dirInfo.exists() && dirInfo.isDir()) {
const QString canonicalDirPath = dirInfo.canonicalFilePath();
m_watcher.addPath(canonicalDirPath);
//m_dirToQualifier.insertMulti(canonicalDirPath, import.qualifier()); ### todo: proper support for import as
}
}
// TODO: QDeclarativeDomImport::Library
}
m_imports.insert(pos, import);
}
void SubComponentManager::removeImport(int pos)
{
const Import import = m_imports.takeAt(pos);
if (import.isFileImport()) {
const QFileInfo dirInfo = QFileInfo(m_filePath.resolved(import.file()).toLocalFile());
const QString canonicalDirPath = dirInfo.canonicalFilePath();
//m_dirToQualifier.remove(canonicalDirPath, import.qualifier()); ### todo: proper support for import as
if (!m_dirToQualifier.contains(canonicalDirPath))
m_watcher.removePath(canonicalDirPath);
// foreach (const QFileInfo &monitoredFile, watchedFiles(canonicalDirPath)) { ### todo: proper support for import as
// if (!m_dirToQualifier.contains(canonicalDirPath))
// unregisterQmlFile(monitoredFile, import.qualifier());
// }
} else {
// TODO: QDeclarativeDomImport::Library
}
}
void SubComponentManager::parseDirectories()
{
if (!m_filePath.isEmpty()) {
const QString file = m_filePath.toLocalFile();
QFileInfo dirInfo = QFileInfo(QFileInfo(file).path());
if (dirInfo.exists() && dirInfo.isDir())
parseDirectory(dirInfo.canonicalFilePath());
foreach (const QString &subDir, QDir(QFileInfo(file).path()).entryList(QDir::Dirs | QDir::NoDot | QDir::NoDotDot)) {
parseDirectory(dirInfo.canonicalFilePath() + "/" + subDir, true, subDir.toUtf8());
}
}
foreach (const Import &import, m_imports) {
if (import.isFileImport()) {
QFileInfo dirInfo = QFileInfo(m_filePath.resolved(import.file()).toLocalFile());
if (dirInfo.exists() && dirInfo.isDir())
parseDirectory(dirInfo.canonicalFilePath(), true, dirInfo.baseName().toUtf8());
} else {
QString url = import.url();
url.replace(QLatin1Char('.'), QLatin1Char('/'));
QFileInfo dirInfo = QFileInfo(url);
foreach (const QString &path, importPaths()) {
QString fullUrl = path + QLatin1Char('/') + url;
dirInfo = QFileInfo(fullUrl);
if (dirInfo.exists() && dirInfo.isDir()) {
//### todo full qualified names QString nameSpace = import.uri();
parseDirectory(dirInfo.canonicalFilePath(), false);
}
QString fullUrlVersion = path + QLatin1Char('/') + url + QLatin1Char('.') + import.version().split(".").first();
dirInfo = QFileInfo(fullUrlVersion);
if (dirInfo.exists() && dirInfo.isDir()) {
//### todo full qualified names QString nameSpace = import.uri();
parseDirectory(dirInfo.canonicalFilePath(), false);
}
}
}
}
}
void SubComponentManager::parseDirectory(const QString &canonicalDirPath, bool addToLibrary, const TypeName& qualification)
{
if (!model() || !model()->rewriterView())
return;
QDir designerDir(canonicalDirPath + Constants::QML_DESIGNER_SUBFOLDER);
if (designerDir.exists()) {
QStringList filter;
filter << "*.metainfo";
designerDir.setNameFilters(filter);
QStringList metaFiles = designerDir.entryList(QDir::Files);
foreach (const QFileInfo &metaInfoFile, designerDir.entryInfoList(QDir::Files)) {
if (model() && model()->metaInfo().itemLibraryInfo()) {
Internal::MetaInfoReader reader(model()->metaInfo());
reader.setQualifcation(qualification);
try {
reader.readMetaInfoFile(metaInfoFile.absoluteFilePath(), true);
} catch (const InvalidMetaInfoException &e) {
qWarning() << e.description();
const QString errorMessage = metaInfoFile.absoluteFilePath() + QLatin1Char('\n') + QLatin1Char('\n') + reader.errors().join(QLatin1Char('\n'));
Core::AsynchronousMessageBox::warning(QCoreApplication::translate("SubComponentManager::parseDirectory", "Invalid meta info"),
errorMessage);
}
}
}
if (!metaFiles.isEmpty())
return;
}
if (debug)
qDebug() << Q_FUNC_INFO << canonicalDirPath;
QDir dir(canonicalDirPath);
dir.setNameFilters(QStringList(s_qmlFilePattern));
dir.setFilter(QDir::Files | QDir::Readable | QDir::CaseSensitive);
QList<QFileInfo> monitoredList = watchedFiles(canonicalDirPath);
QList<QFileInfo> newList;
foreach (const QFileInfo &qmlFile, dir.entryInfoList()) {
if (QFileInfo(m_filePath.toLocalFile()) == qmlFile) {
// do not parse main file
continue;
}
if (!qmlFile.fileName().at(0).isUpper()) {
// QML sub components must be upper case
continue;
}
newList << qmlFile;
}
Utils::sort(monitoredList);
Utils::sort(newList);
if (debug)
qDebug() << "monitored list " << monitoredList.size() << "new list " << newList.size();
auto oldIter = monitoredList.constBegin();
auto newIter = newList.constBegin();
while (oldIter != monitoredList.constEnd() && newIter != newList.constEnd()) {
const QFileInfo oldFileInfo = *oldIter;
const QFileInfo newFileInfo = *newIter;
if (oldFileInfo == newFileInfo) {
++oldIter;
++newIter;
continue;
}
if (oldFileInfo < newFileInfo) {
foreach (const QString &qualifier, m_dirToQualifier.value(canonicalDirPath))
unregisterQmlFile(oldFileInfo, qualifier);
m_watcher.removePath(oldFileInfo.filePath());
++oldIter;
continue;
}
// oldFileInfo > newFileInfo
parseFile(newFileInfo.filePath(), addToLibrary, qualification);
++newIter;
}
while (oldIter != monitoredList.constEnd()) {
foreach (const QString &qualifier, m_dirToQualifier.value(canonicalDirPath))
unregisterQmlFile(*oldIter, qualifier);
++oldIter;
}
while (newIter != newList.constEnd()) {
parseFile(newIter->filePath(), addToLibrary, qualification);
if (debug)
qDebug() << "m_watcher.addPath(" << newIter->filePath() << ')';
++newIter;
}
}
void SubComponentManager::parseFile(const QString &canonicalFilePath, bool addToLibrary, const QString& qualification)
{
if (debug)
qDebug() << Q_FUNC_INFO << canonicalFilePath;
QFile file(canonicalFilePath);
if (!file.open(QIODevice::ReadOnly | QIODevice::Text))
return;
QString dir = QFileInfo(canonicalFilePath).path();
foreach (const QString &qualifier, m_dirToQualifier.values(dir)) {
registerQmlFile(canonicalFilePath, qualifier, addToLibrary);
}
registerQmlFile(canonicalFilePath, qualification, addToLibrary);
}
void SubComponentManager::parseFile(const QString &canonicalFilePath)
{
parseFile(canonicalFilePath, true, QString());
}
// dirInfo must already contain a canonical path
QList<QFileInfo> SubComponentManager::watchedFiles(const QString &canonicalDirPath)
{
QList<QFileInfo> files;
foreach (const QString &monitoredFile, m_watcher.files()) {
QFileInfo fileInfo(monitoredFile);
if (fileInfo.dir().absolutePath() == canonicalDirPath)
files.append(fileInfo);
}
return files;
}
void SubComponentManager::unregisterQmlFile(const QFileInfo &fileInfo, const QString &qualifier)
{
QString componentName = fileInfo.baseName();
if (!qualifier.isEmpty())
componentName = qualifier + '.' + componentName;
}
void SubComponentManager::registerQmlFile(const QFileInfo &fileInfo, const QString &qualifier,
bool addToLibrary)
{
if (!model())
return;
if (!checkIfDerivedFromItem(fileInfo.absoluteFilePath()))
return;
QString componentName = fileInfo.baseName();
const QString baseComponentName = componentName;
QString fixedQualifier = qualifier;
if (!qualifier.isEmpty()) {
fixedQualifier = qualifier;
if (qualifier.right(1) == QStringLiteral("."))
fixedQualifier.chop(1); //remove last char if it is a dot
componentName = fixedQualifier + '.' + componentName;
}
if (debug)
qDebug() << "SubComponentManager" << __FUNCTION__ << componentName;
if (addToLibrary) {
// Add file components to the library
ItemLibraryEntry itemLibraryEntry;
itemLibraryEntry.setType(componentName.toUtf8(), -1, -1);
itemLibraryEntry.setName(baseComponentName);
itemLibraryEntry.setCategory("QML Components");
if (!qualifier.isEmpty()) {
itemLibraryEntry.setRequiredImport(fixedQualifier);
}
if (!model()->metaInfo().itemLibraryInfo()->containsEntry(itemLibraryEntry)) {
model()->metaInfo().itemLibraryInfo()->addEntry(itemLibraryEntry);
}
}
}
Model *SubComponentManager::model() const
{
return m_model.data();
}
QStringList SubComponentManager::importPaths() const
{
if (model())
return model()->importPaths();
return QStringList();
}
/*!
\class SubComponentManager
Detects & monitors (potential) component files in a list of directories, and registers
these in the metatype system.
*/
QStringList SubComponentManager::directories() const
{
return m_watcher.directories();
}
QStringList SubComponentManager::qmlFiles() const
{
return m_watcher.files();
}
void SubComponentManager::update(const QUrl &filePath, const QList<Import> &imports)
{
if (debug)
qDebug() << Q_FUNC_INFO << filePath << imports.size();
QFileInfo oldDir, newDir;
if (!m_filePath.isEmpty()) {
const QString file = m_filePath.toLocalFile();
oldDir = QFileInfo(QFileInfo(file).path());
}
if (!filePath.isEmpty()) {
const QString file = filePath.toLocalFile();
newDir = QFileInfo(QFileInfo(file).path());
}
m_filePath = filePath;
//
// (implicit) import of local directory
//
if (oldDir != newDir) {
if (!oldDir.filePath().isEmpty()) {
m_dirToQualifier.remove(oldDir.canonicalFilePath(), QString());
if (!m_dirToQualifier.contains(oldDir.canonicalFilePath()))
m_watcher.removePath(oldDir.filePath());
}
if (!newDir.filePath().isEmpty())
m_dirToQualifier.insertMulti(newDir.canonicalFilePath(), QString());
}
//
// Imports
//
// skip first list items until the lists differ
int i = 0;
while (i < qMin(imports.size(), m_imports.size())) {
if (!(imports.at(i) == m_imports.at(i)))
break;
++i;
}
for (int ii = m_imports.size() - 1; ii >= i; --ii)
removeImport(ii);
for (int ii = i; ii < imports.size(); ++ii) {
addImport(ii, imports.at(ii));
}
parseDirectories();
}
} // namespace QmlDesigner
<|endoftext|> |
<commit_before>#include "SoftapHookup.h"
#include <ESP8266WiFi.h>
#include <EEPROM.h>
//couldnt connect message from eeprom
//connect led
//looper
//dont reset
//allow to specify ip range
//turn off softap
//allow ip range change
SoftapHookup::SoftapHookup(char *defaultssid, char *password, ESP8266WebServer *inServer) {
softapssid = defaultssid;
softappassword = password;
server = inServer;
init();
}
SoftapHookup::SoftapHookup(char *defaultssid, char *password, ESP8266WebServer *inServer,
int inClearNetworkFromEepromPin) {
softapssid = defaultssid;
softappassword = password;
server = inServer;
clearNetworkFromEepromPin = inClearNetworkFromEepromPin;
init();
}
void SoftapHookup::init() {
currentMode = SH_MODE_RESET_CHECK;
numberOfFoundNetworks = 0;
timeoutMillis = 10000;
lastConnectAttemptFailed = false; //load this from eeprom
clearNetworkFromEepromPin = -1;
eepromStartingByte = 0;
shouldWriteToEeprom = true;
}
void SoftapHookup::start() {
switch (currentMode) {
case SH_MODE_RESET_CHECK:
checkForReset();
break;
case SH_MODE_EEPROM_CONNECT:
readFromEeprom();
break;
case SH_MODE_SCAN:
scanForNetworks();
break;
case SH_MODE_SOFTAPSETUP:
setupWiFi();
break;
case SH_MODE_SOFTAPSERVER:
softapServer();
break;
case SH_MODE_CONNECTING:
connectToRemoteWifi();
break;
case SH_MODE_CONNECTED:
break;
default:
Serial.println("Idle");
}
}
void SoftapHookup::checkForReset() {
Serial.println("Checking eeprom reset pin");
currentMode = SH_MODE_EEPROM_CONNECT;
if (clearNetworkFromEepromPin == -1) {
Serial.println("No reset pin specified. Skipping eeprom reset");
return;
}
pinMode(clearNetworkFromEepromPin, INPUT);
if (digitalRead(clearNetworkFromEepromPin) == HIGH) {
Serial.println("Pin detected. Clearing eeprom");
clearEeprom();
} else {
Serial.println("Skipping eeprom clearing. Pin not detected.");
}
}
void SoftapHookup::connectToRemoteWifi() {
Serial.print("Connecting to network ");
Serial.print(String(remoteSsid));
Serial.print(" with password ");
Serial.print(String(remotePassword));
Serial.println(".");
if (strlen(remotePassword) > 0) {
WiFi.begin(remoteSsid, remotePassword);
} else {
WiFi.begin(remoteSsid);
}
unsigned long previousMillis = millis();
unsigned long currentMillis;
while (WiFi.status() != WL_CONNECTED) {
currentMillis = millis();
if ((currentMillis - previousMillis) >= timeoutMillis) {
Serial.println("Connection Timeout");
currentMode = SH_MODE_SCAN;
lastConnectAttemptFailed = true;
return;
}
delay(500);
Serial.print(".");
}
Serial.println("");
Serial.print("Connected! IP address: ");
Serial.println(WiFi.localIP());
saveToEeprom();
currentMode = SH_MODE_CONNECTED;
}
void SoftapHookup::readFromEeprom() {
Serial.println("Checking Eeprom");
if (shouldIgnoreEeprom) {
currentMode = SH_MODE_SCAN;
return;
}
EEPROM.begin(512);
for (int i = 0; i < sizeof(remoteSsid); ++i) {
remoteSsid[i] = char(EEPROM.read(eepromStartingByte + i));
}
Serial.print("SSID: ");
Serial.println(remoteSsid);
Serial.println("Reading EEPROM pass");
for (int i = 0; i < sizeof(remotePassword); ++i) {
remotePassword[i] = char(EEPROM.read(eepromStartingByte + sizeof(remoteSsid) + i));
}
Serial.print("Password: ");
Serial.println(remotePassword);
if (strlen(remoteSsid) > 0) {
shouldWriteToEeprom = false;
currentMode = SH_MODE_CONNECTING;
} else {
currentMode = SH_MODE_SCAN;
}
}
void SoftapHookup::saveToEeprom() {
if (!shouldWriteToEeprom || shouldIgnoreEeprom) {
Serial.println("Skipping write to Eeprom");
return;
}
Serial.println("Writing to Eeprom");
EEPROM.begin(512);
clearEeprom();
for (int i = 0; i < sizeof(remoteSsid); ++i) {
EEPROM.write(eepromStartingByte + i, remoteSsid[i]);
}
Serial.print("Wrote: ");
Serial.println(remoteSsid);
for (int i = 0; i < sizeof(remotePassword); ++i) {
EEPROM.write(eepromStartingByte + sizeof(remoteSsid) + i, remotePassword[i]);
}
EEPROM.commit();
Serial.print("Wrote: ");
Serial.println(remotePassword);
}
void SoftapHookup::clearEeprom() {
if (shouldIgnoreEeprom) {
Serial.println("Skipping clear Eeprom");
return;
}
Serial.println("Clearing Eeprom");
int length = getEepromSizeUsed();
EEPROM.begin(512);
for (int i = 0; i < length; ++i) {
EEPROM.write(eepromStartingByte + i, 0);
}
EEPROM.commit();
}
void SoftapHookup::softapServer() {
server->handleClient();
}
void SoftapHookup::setupWiFi() {
Serial.println("in setup WiFi");
uint8_t mac[WL_MAC_ADDR_LENGTH];
WiFi.softAPmacAddress(mac);
String macID = String(mac[WL_MAC_ADDR_LENGTH - 2], HEX) +
String(mac[WL_MAC_ADDR_LENGTH - 1], HEX);
macID.toUpperCase();
String AP_NameString = String(softapssid);
char AP_NameChar[AP_NameString.length() + 1];
memset(AP_NameChar, 0, AP_NameString.length() + 1);
for (int i = 0; i < AP_NameString.length(); i++) {
AP_NameChar[i] = AP_NameString.charAt(i);
}
WiFi.softAP(AP_NameChar, softappassword);
currentMode = SH_MODE_SOFTAPSERVER;
server->on("/", HTTP_GET, std::bind(&SoftapHookup::showNetworks, this));
server->on("/refresh", HTTP_GET, std::bind(&SoftapHookup::refresh, this));
server->on("/select", HTTP_POST, std::bind(&SoftapHookup::selectSsid, this));
server->begin();
}
void SoftapHookup::refresh() {
scanForNetworks();
showNetworks();
}
String SoftapHookup::getHTMLHeader() {
return "<!DOCTYPE HTML>\r\n<html>\r\n";
}
String SoftapHookup::getHTMLFooter() {
return "</html>\n";
}
void SoftapHookup::selectSsid() {
Serial.println("User selection detected");
String hiddenPassword = server->arg("hiddenpassword");
String hiddenSsid = server->arg("hiddenssid");
int ssidNum = server->arg("ssid").toInt();
String password = server->arg("password");
boolean useHiddenNetwork = false;
String s = "";
s += getHTMLHeader();
if (hiddenSsid.length() > 0) {
useHiddenNetwork = true;
}
s += "Connecting to network <br>";
s += (useHiddenNetwork ? hiddenSsid : WiFi.SSID(ssidNum));
s += "<br>";
s += getHTMLFooter();
server->send(200, "text/html", s);
if (useHiddenNetwork) {
hiddenSsid.toCharArray(remoteSsid, sizeof(remoteSsid));
hiddenPassword.toCharArray(remotePassword, sizeof(remotePassword));
} else {
WiFi.SSID(ssidNum).toCharArray(remoteSsid, sizeof(remoteSsid));
password.toCharArray(remotePassword, sizeof(remotePassword));
}
currentMode = SH_MODE_CONNECTING;
}
void SoftapHookup::showNetworks() {
String s = "";
s += getHTMLHeader();
if (numberOfFoundNetworks == 0) {
s += "no networks found";
} else {
if (lastConnectAttemptFailed == true) {
s += "<b>Last connection failed</b><br>";
}
s += "Select a network for <b>" +
String(softapssid) +
"</b> to connect. * denotes password protected network<br><br><form action=\"/select\" method=\"post\">";
s += "<select name=\"ssid\">";
for (int i = 0; i < numberOfFoundNetworks; ++i) {
s += "<option value=\"" + String(i) + "\">";
s += i + 1;
s += ": ";
s += WiFi.SSID(i);
s += " (";
s += WiFi.RSSI(i);
s += ")";
s += (WiFi.encryptionType(i) == ENC_TYPE_NONE) ? " " : " *";
s += "</option>";
}
s += "</select><br><br>";
s += "Network Password: <input type=\"text\" name=\"password\"><br>";
s += "<br>or<br><br>";
s += "Hidden network SSID: <input type=\"text\" name=\"hiddenssid\"><br>";
s += "Network Password: <input type=\"text\" name=\"hiddenpassword\"><br>";
s += "<br>";
s += "<input type=\"submit\" value=\"Select\">";
s += "</form>";
}
s += "<a href=\"/refresh\">Refresh</a>";
s += getHTMLFooter();
server->send(200, "text/html", s);
Serial.println("in index");
}
void SoftapHookup::scanForNetworks() {
Serial.println("scan start");
WiFi.disconnect();
delay(100);
numberOfFoundNetworks = WiFi.scanNetworks();
Serial.println("scan done");
if (numberOfFoundNetworks == 0) {
Serial.println("no networks found");
} else {
Serial.print(numberOfFoundNetworks);
Serial.println(" networks found");
for (int i = 0; i < numberOfFoundNetworks; ++i) {
Serial.print(i + 1);
Serial.print(": ");
Serial.print(WiFi.SSID(i));
Serial.print(" (");
Serial.print(WiFi.RSSI(i));
Serial.print(")");
Serial.println((WiFi.encryptionType(i) == ENC_TYPE_NONE) ? " " : "*");
delay(10);
}
}
Serial.println("");
currentMode = SH_MODE_SOFTAPSETUP;
}
int SoftapHookup::getEepromSizeUsed() {
return sizeof(remoteSsid) + sizeof(remotePassword);
}
void SoftapHookup::setEepromStartingByte(int startByte) {
eepromStartingByte = startByte;
}
void SoftapHookup::setShouldWriteEeprom(boolean shouldWrite) {
shouldWriteToEeprom = shouldWrite;
}
void SoftapHookup::ignoreEeprom(boolean shouldIgnore) {
shouldIgnoreEeprom = shouldIgnore;
}
<commit_msg>CP - fixed pin reset command<commit_after>#include "SoftapHookup.h"
#include <ESP8266WiFi.h>
#include <EEPROM.h>
//couldnt connect message from eeprom
//connect led
//looper
//dont reset
//allow to specify ip range
//turn off softap
//allow ip range change
SoftapHookup::SoftapHookup(char *defaultssid, char *password, ESP8266WebServer *inServer) {
softapssid = defaultssid;
softappassword = password;
server = inServer;
clearNetworkFromEepromPin = -1;
init();
}
SoftapHookup::SoftapHookup(char *defaultssid, char *password, ESP8266WebServer *inServer,
int inClearNetworkFromEepromPin) {
softapssid = defaultssid;
softappassword = password;
server = inServer;
clearNetworkFromEepromPin = inClearNetworkFromEepromPin;
init();
}
void SoftapHookup::init() {
currentMode = SH_MODE_RESET_CHECK;
numberOfFoundNetworks = 0;
timeoutMillis = 10000;
lastConnectAttemptFailed = false; //load this from eeprom
eepromStartingByte = 0;
shouldWriteToEeprom = true;
}
void SoftapHookup::start() {
switch (currentMode) {
case SH_MODE_RESET_CHECK:
checkForReset();
break;
case SH_MODE_EEPROM_CONNECT:
readFromEeprom();
break;
case SH_MODE_SCAN:
scanForNetworks();
break;
case SH_MODE_SOFTAPSETUP:
setupWiFi();
break;
case SH_MODE_SOFTAPSERVER:
softapServer();
break;
case SH_MODE_CONNECTING:
connectToRemoteWifi();
break;
case SH_MODE_CONNECTED:
break;
default:
Serial.println("Idle");
}
}
void SoftapHookup::checkForReset() {
Serial.println("Checking eeprom reset pin");
currentMode = SH_MODE_EEPROM_CONNECT;
if (clearNetworkFromEepromPin == -1) {
Serial.println("No reset pin specified. Skipping eeprom reset");
return;
}
pinMode(clearNetworkFromEepromPin, INPUT);
if (digitalRead(clearNetworkFromEepromPin) == HIGH) {
Serial.println("Pin detected. Clearing eeprom");
clearEeprom();
} else {
Serial.println("Skipping eeprom clearing. Pin not detected.");
}
}
void SoftapHookup::connectToRemoteWifi() {
Serial.print("Connecting to network ");
Serial.print(String(remoteSsid));
Serial.print(" with password ");
Serial.print(String(remotePassword));
Serial.println(".");
if (strlen(remotePassword) > 0) {
WiFi.begin(remoteSsid, remotePassword);
} else {
WiFi.begin(remoteSsid);
}
unsigned long previousMillis = millis();
unsigned long currentMillis;
while (WiFi.status() != WL_CONNECTED) {
currentMillis = millis();
if ((currentMillis - previousMillis) >= timeoutMillis) {
Serial.println("Connection Timeout");
currentMode = SH_MODE_SCAN;
lastConnectAttemptFailed = true;
return;
}
delay(500);
Serial.print(".");
}
Serial.println("");
Serial.print("Connected! IP address: ");
Serial.println(WiFi.localIP());
saveToEeprom();
currentMode = SH_MODE_CONNECTED;
}
void SoftapHookup::readFromEeprom() {
Serial.println("Checking Eeprom");
if (shouldIgnoreEeprom) {
currentMode = SH_MODE_SCAN;
return;
}
EEPROM.begin(512);
for (int i = 0; i < sizeof(remoteSsid); ++i) {
remoteSsid[i] = char(EEPROM.read(eepromStartingByte + i));
}
Serial.print("SSID: ");
Serial.println(remoteSsid);
Serial.println("Reading EEPROM pass");
for (int i = 0; i < sizeof(remotePassword); ++i) {
remotePassword[i] = char(EEPROM.read(eepromStartingByte + sizeof(remoteSsid) + i));
}
Serial.print("Password: ");
Serial.println(remotePassword);
if (strlen(remoteSsid) > 0) {
shouldWriteToEeprom = false;
currentMode = SH_MODE_CONNECTING;
} else {
currentMode = SH_MODE_SCAN;
}
}
void SoftapHookup::saveToEeprom() {
if (!shouldWriteToEeprom || shouldIgnoreEeprom) {
Serial.println("Skipping write to Eeprom");
return;
}
Serial.println("Writing to Eeprom");
EEPROM.begin(512);
clearEeprom();
for (int i = 0; i < sizeof(remoteSsid); ++i) {
EEPROM.write(eepromStartingByte + i, remoteSsid[i]);
}
Serial.print("Wrote: ");
Serial.println(remoteSsid);
for (int i = 0; i < sizeof(remotePassword); ++i) {
EEPROM.write(eepromStartingByte + sizeof(remoteSsid) + i, remotePassword[i]);
}
EEPROM.commit();
Serial.print("Wrote: ");
Serial.println(remotePassword);
}
void SoftapHookup::clearEeprom() {
if (shouldIgnoreEeprom) {
Serial.println("Skipping clear Eeprom");
return;
}
Serial.println("Clearing Eeprom");
int length = getEepromSizeUsed();
EEPROM.begin(512);
for (int i = 0; i < length; ++i) {
EEPROM.write(eepromStartingByte + i, 0);
}
EEPROM.commit();
}
void SoftapHookup::softapServer() {
server->handleClient();
}
void SoftapHookup::setupWiFi() {
Serial.println("in setup WiFi");
uint8_t mac[WL_MAC_ADDR_LENGTH];
WiFi.softAPmacAddress(mac);
String macID = String(mac[WL_MAC_ADDR_LENGTH - 2], HEX) +
String(mac[WL_MAC_ADDR_LENGTH - 1], HEX);
macID.toUpperCase();
String AP_NameString = String(softapssid);
char AP_NameChar[AP_NameString.length() + 1];
memset(AP_NameChar, 0, AP_NameString.length() + 1);
for (int i = 0; i < AP_NameString.length(); i++) {
AP_NameChar[i] = AP_NameString.charAt(i);
}
WiFi.softAP(AP_NameChar, softappassword);
currentMode = SH_MODE_SOFTAPSERVER;
server->on("/", HTTP_GET, std::bind(&SoftapHookup::showNetworks, this));
server->on("/refresh", HTTP_GET, std::bind(&SoftapHookup::refresh, this));
server->on("/select", HTTP_POST, std::bind(&SoftapHookup::selectSsid, this));
server->begin();
}
void SoftapHookup::refresh() {
scanForNetworks();
showNetworks();
}
String SoftapHookup::getHTMLHeader() {
return "<!DOCTYPE HTML>\r\n<html>\r\n";
}
String SoftapHookup::getHTMLFooter() {
return "</html>\n";
}
void SoftapHookup::selectSsid() {
Serial.println("User selection detected");
String hiddenPassword = server->arg("hiddenpassword");
String hiddenSsid = server->arg("hiddenssid");
int ssidNum = server->arg("ssid").toInt();
String password = server->arg("password");
boolean useHiddenNetwork = false;
String s = "";
s += getHTMLHeader();
if (hiddenSsid.length() > 0) {
useHiddenNetwork = true;
}
s += "Connecting to network <br>";
s += (useHiddenNetwork ? hiddenSsid : WiFi.SSID(ssidNum));
s += "<br>";
s += getHTMLFooter();
server->send(200, "text/html", s);
if (useHiddenNetwork) {
hiddenSsid.toCharArray(remoteSsid, sizeof(remoteSsid));
hiddenPassword.toCharArray(remotePassword, sizeof(remotePassword));
} else {
WiFi.SSID(ssidNum).toCharArray(remoteSsid, sizeof(remoteSsid));
password.toCharArray(remotePassword, sizeof(remotePassword));
}
currentMode = SH_MODE_CONNECTING;
}
void SoftapHookup::showNetworks() {
String s = "";
s += getHTMLHeader();
if (numberOfFoundNetworks == 0) {
s += "no networks found";
} else {
if (lastConnectAttemptFailed == true) {
s += "<font size=\"3\" color=\"red\">Last connection failed</font><br>";
}
s += "Select a network for <b>" +
String(softapssid) +
"</b> to connect. * denotes password protected network<br><br><form action=\"/select\" method=\"post\">";
s += "<select name=\"ssid\">";
for (int i = 0; i < numberOfFoundNetworks; ++i) {
s += "<option value=\"" + String(i) + "\">";
s += i + 1;
s += ": ";
s += WiFi.SSID(i);
s += " (";
s += WiFi.RSSI(i);
s += ")";
s += (WiFi.encryptionType(i) == ENC_TYPE_NONE) ? " " : " *";
s += "</option>";
}
s += "</select><br><br>";
s += "Network Password: <input type=\"text\" name=\"password\"><br>";
s += "<br>or<br><br>";
s += "Hidden network SSID: <input type=\"text\" name=\"hiddenssid\"><br>";
s += "Network Password: <input type=\"text\" name=\"hiddenpassword\"><br>";
s += "<br>";
s += "<input type=\"submit\" value=\"Select\">";
s += "</form>";
}
s += "<a href=\"/refresh\">Refresh</a>";
s += getHTMLFooter();
server->send(200, "text/html", s);
Serial.println("in index");
}
void SoftapHookup::scanForNetworks() {
Serial.println("scan start");
WiFi.disconnect();
delay(100);
numberOfFoundNetworks = WiFi.scanNetworks();
Serial.println("scan done");
if (numberOfFoundNetworks == 0) {
Serial.println("no networks found");
} else {
Serial.print(numberOfFoundNetworks);
Serial.println(" networks found");
for (int i = 0; i < numberOfFoundNetworks; ++i) {
Serial.print(i + 1);
Serial.print(": ");
Serial.print(WiFi.SSID(i));
Serial.print(" (");
Serial.print(WiFi.RSSI(i));
Serial.print(")");
Serial.println((WiFi.encryptionType(i) == ENC_TYPE_NONE) ? " " : "*");
delay(10);
}
}
Serial.println("");
currentMode = SH_MODE_SOFTAPSETUP;
}
int SoftapHookup::getEepromSizeUsed() {
return sizeof(remoteSsid) + sizeof(remotePassword);
}
void SoftapHookup::setEepromStartingByte(int startByte) {
eepromStartingByte = startByte;
}
void SoftapHookup::setShouldWriteEeprom(boolean shouldWrite) {
shouldWriteToEeprom = shouldWrite;
}
void SoftapHookup::ignoreEeprom(boolean shouldIgnore) {
shouldIgnoreEeprom = shouldIgnore;
}
<|endoftext|> |
<commit_before>/*
* Copyright(c) Records For Living, Inc. 2004-2011. All rights reserved
*/
#include "Stroika/Foundation/StroikaPreComp.h"
#include <iostream>
#include <sstream>
#include "Stroika/Foundation/Execution/CriticalSection.h"
#include "Stroika/Foundation/Execution/Event.h"
#include "Stroika/Foundation/Execution/Lockable.h"
#include "Stroika/Foundation/Execution/Sleep.h"
#include "Stroika/Foundation/Execution/SimpleRunnable.h"
#include "Stroika/Foundation/Execution/Thread.h"
#include "Stroika/Foundation/Execution/ThreadPool.h"
#include "Stroika/Foundation/Execution/WaitTimedOutException.h"
#include "../TestHarness/TestHarness.h"
using namespace Stroika::Foundation;
using Execution::CriticalSection;
using Execution::Lockable;
using Execution::AutoCriticalSection;
using Execution::SimpleRunnable;
using Execution::Thread;
using Execution::ThreadPool;
namespace {
void RegressionTest1_ ()
{
struct FRED {
static void DoIt (void* ignored)
{
for (int i = 1; i < 10; i++) {
Execution::Sleep (.1);
}
}
};
Thread thread (&FRED::DoIt, const_cast<char*> ("foo"));
thread.Start ();
thread.WaitForDone ();
}
}
namespace {
CriticalSection sharedCriticalSection_;
void RegressionTest2_ ()
{
// Make 2 concurrent threads, which share a critical section object to take turns updating a variable
struct FRED {
static void DoIt (void* ignored)
{
int* argP = reinterpret_cast<int*> (ignored);
for (int i = 0; i < 10; i++) {
AutoCriticalSection critSect (sharedCriticalSection_);
int tmp = *argP;
Execution::Sleep (.01);
//DbgTrace ("Updating value in thread id %d", ::GetCurrentThreadId ());
*argP = tmp + 1;
}
}
};
int updaterValue = 0;
Thread thread1 (&FRED::DoIt, &updaterValue);
Thread thread2 (&FRED::DoIt, &updaterValue);
thread1.Start ();
thread2.Start ();
thread1.WaitForDone ();
thread2.WaitForDone ();
VerifyTestResult (updaterValue == 2 * 10);
}
}
namespace {
Execution::Event sRegTest3Event_T1_;
Execution::Event sRegTest3Event_T2_;
void RegressionTest3_ ()
{
// Make 2 concurrent threads, which share a critical section object to take turns updating a variable
struct FRED1 {
static void DoIt (void* ignored)
{
int* argP = reinterpret_cast<int*> (ignored);
for (int i = 0; i < 10; i++) {
sRegTest3Event_T1_.Wait ();
int tmp = *argP;
Execution::Sleep (.01);
//DbgTrace ("FRED1: Updating value in of %d", tmp);
*argP = tmp + 1;
sRegTest3Event_T2_.Set ();
}
}
};
struct FRED2 {
static void DoIt (void* ignored)
{
int* argP = reinterpret_cast<int*> (ignored);
for (int i = 0; i < 10; i++) {
sRegTest3Event_T2_.Wait ();
int tmp = *argP;
Execution::Sleep (.01);
//DbgTrace ("FRED2: Updating value in of %d", tmp);
*argP = tmp + 1;
sRegTest3Event_T1_.Set ();
}
}
};
sRegTest3Event_T1_.Reset ();
sRegTest3Event_T2_.Reset ();
int updaterValue = 0;
Thread thread1 (&FRED1::DoIt, &updaterValue);
Thread thread2 (&FRED2::DoIt, &updaterValue);
thread1.Start ();
thread2.Start ();
sRegTest3Event_T1_.Set ();
thread1.WaitForDone ();
thread2.WaitForDone ();
//DbgTrace ("Test3 - updaterValue = %d", updaterValue);
VerifyTestResult (updaterValue == 2 * 10);
}
}
namespace {
struct data_ {};
void RegressionTest4_Lockable_ ()
{
{
Lockable<data_> x;
Lockable<data_> y = data_ ();
x = data_ ();
}
{
Lockable<int> x;
Lockable<int> y = 3;
x = 4;
}
{
// Make 2 concurrent threads, which update a lockable variable
struct FRED {
static void DoIt (void* ignored)
{
Lockable<int>* argP = reinterpret_cast<Lockable<int>*> (ignored);
for (int i = 0; i < 10; i++) {
AutoCriticalSection critSect (*argP);
int tmp = *argP;
Execution::Sleep (.01);
//DbgTrace ("Updating value in thread id %d", ::GetCurrentThreadId ());
*argP = tmp + 1;
}
}
};
Lockable<int> updaterValue = 0;
Thread thread1 (&FRED::DoIt, &updaterValue);
Thread thread2 (&FRED::DoIt, &updaterValue);
thread1.Start ();
thread2.Start ();
thread1.WaitForDone ();
thread2.WaitForDone ();
VerifyTestResult (updaterValue == 2 * 10);
}
}
}
namespace {
void RegressionTest5_Aborting_ ()
{
struct FRED {
static void DoIt ()
{
while (true) {
Execution::CheckForThreadAborting ();
}
}
};
Thread thread (&FRED::DoIt);
thread.Start ();
try {
thread.WaitForDone (1.0); // should timeout
VerifyTestResult (false);
}
catch (const Execution::WaitTimedOutException&) {
// GOOD
}
catch (...) {
VerifyTestResult (false);
}
// Now - abort it, and wait
thread.AbortAndWaitForDone ();
}
}
namespace {
void RegressionTest6_ThreadWaiting_ ()
{
struct FRED {
static void DoIt ()
{
Execution::Sleep (1.0);
}
};
// Normal usage
{
Thread thread (&FRED::DoIt);
thread.Start ();
thread.WaitForDone ();
}
// OK to never wait
{
Thread thread (&FRED::DoIt);
thread.Start ();
}
// OK to wait and wait
{
Thread thread (&FRED::DoIt);
thread.Start ();
thread.WaitForDone ();
thread.WaitForDone (1.0);
thread.WaitForDone ();
thread.WaitForDone ();
}
}
}
namespace {
void RegressionTest7_SimpleThreadPool_ ()
{
{
ThreadPool p;
p.SetPoolSize (1);
p.Abort ();
p.WaitForDone ();
}
{
ThreadPool p;
p.SetPoolSize (1);
struct FRED {
static void DoIt (void* arg)
{
int* p = reinterpret_cast<int*> (arg);
(*p)++;
}
};
int intVal = 3;
Memory::SharedPtr<Execution::IRunnable> task = SimpleRunnable::MAKE (FRED::DoIt, &intVal);
p.AddTask (task);
p.WaitForTask (task);
p.AbortAndWaitForDone ();
VerifyTestResult (intVal == 4);
}
}
}
namespace {
void RegressionTest8_ThreadPool_ ()
{
// Make 2 concurrent tasks, which share a critical section object to take turns updating a variable
struct FRED {
static void DoIt (void* ignored)
{
int* argP = reinterpret_cast<int*> (ignored);
for (int i = 0; i < 10; i++) {
AutoCriticalSection critSect (sharedCriticalSection_);
int tmp = *argP;
Execution::Sleep (.01);
//DbgTrace ("Updating value in thread id %d", ::GetCurrentThreadId ());
*argP = tmp + 1;
}
}
};
for (unsigned int threadPoolSize = 1; threadPoolSize < 10; ++threadPoolSize) {
ThreadPool p;
p.SetPoolSize (threadPoolSize);
int updaterValue = 0;
Memory::SharedPtr<Execution::IRunnable> task1 = SimpleRunnable::MAKE (&FRED::DoIt, &updaterValue);
Memory::SharedPtr<Execution::IRunnable> task2 = SimpleRunnable::MAKE (&FRED::DoIt, &updaterValue);
p.AddTask (task1);
p.AddTask (task2);
p.WaitForTask (task1);
p.WaitForTask (task2);
p.AbortAndWaitForDone ();
VerifyTestResult (updaterValue == 2 * 10);
}
}
}
namespace {
void RegressionTest9_ThreadsAbortingEarly_ ()
{
// I was seeing SOME rare thread bug - trying to abort a thread which was itself trying to create a new thread - and was
// between the create of thread and Abort
struct FRED {
static void DoItInnerThread ()
{
Execution::Sleep (1.0);
}
static void DoOuterThread ()
{
while (true) {
Thread t (DoItInnerThread);
Execution::Sleep (1);
t.Start ();
}
}
};
Thread thread (&FRED::DoOuterThread);
thread.Start ();
Execution::Sleep (5);
thread.AbortAndWaitForDone ();
}
}
namespace {
void DoRegressionTests_ ()
{
RegressionTest1_ ();
RegressionTest2_ ();
RegressionTest3_ ();
RegressionTest4_Lockable_ ();
RegressionTest5_Aborting_ ();
RegressionTest6_ThreadWaiting_ ();
RegressionTest7_SimpleThreadPool_ ();
RegressionTest8_ThreadPool_ ();
RegressionTest9_ThreadsAbortingEarly_ ();
}
}
#if qOnlyOneMain
extern int TestThreads ()
#else
int main (int argc, const char* argv[])
#endif
{
Stroika::TestHarness::Setup ();
Stroika::TestHarness::PrintPassOrFail (DoRegressionTests_);
return EXIT_SUCCESS;
}
<commit_msg>Embellished automated tests<commit_after>/*
* Copyright(c) Records For Living, Inc. 2004-2011. All rights reserved
*/
#include "Stroika/Foundation/StroikaPreComp.h"
#include <iostream>
#include <sstream>
#include "Stroika/Foundation/Execution/CriticalSection.h"
#include "Stroika/Foundation/Execution/Event.h"
#include "Stroika/Foundation/Execution/Lockable.h"
#include "Stroika/Foundation/Execution/Sleep.h"
#include "Stroika/Foundation/Execution/SimpleRunnable.h"
#include "Stroika/Foundation/Execution/Thread.h"
#include "Stroika/Foundation/Execution/ThreadPool.h"
#include "Stroika/Foundation/Execution/WaitTimedOutException.h"
#include "../TestHarness/TestHarness.h"
using namespace Stroika::Foundation;
using Execution::CriticalSection;
using Execution::Lockable;
using Execution::AutoCriticalSection;
using Execution::SimpleRunnable;
using Execution::Thread;
using Execution::ThreadPool;
namespace {
void RegressionTest1_ ()
{
struct FRED {
static void DoIt (void* ignored)
{
for (int i = 1; i < 10; i++) {
Execution::Sleep (.1);
}
}
};
Thread thread (&FRED::DoIt, const_cast<char*> ("foo"));
thread.Start ();
thread.WaitForDone ();
}
}
namespace {
CriticalSection sharedCriticalSection_;
void RegressionTest2_ ()
{
// Make 2 concurrent threads, which share a critical section object to take turns updating a variable
struct FRED {
static void DoIt (void* ignored)
{
int* argP = reinterpret_cast<int*> (ignored);
for (int i = 0; i < 10; i++) {
AutoCriticalSection critSect (sharedCriticalSection_);
int tmp = *argP;
Execution::Sleep (.01);
//DbgTrace ("Updating value in thread id %d", ::GetCurrentThreadId ());
*argP = tmp + 1;
}
}
};
int updaterValue = 0;
Thread thread1 (&FRED::DoIt, &updaterValue);
Thread thread2 (&FRED::DoIt, &updaterValue);
thread1.Start ();
thread2.Start ();
thread1.WaitForDone ();
thread2.WaitForDone ();
VerifyTestResult (updaterValue == 2 * 10);
}
}
namespace {
Execution::Event sRegTest3Event_T1_;
Execution::Event sRegTest3Event_T2_;
void RegressionTest3_ ()
{
// Make 2 concurrent threads, which share a critical section object to take turns updating a variable
struct FRED1 {
static void DoIt (void* ignored)
{
int* argP = reinterpret_cast<int*> (ignored);
for (int i = 0; i < 10; i++) {
sRegTest3Event_T1_.Wait ();
int tmp = *argP;
Execution::Sleep (.01);
//DbgTrace ("FRED1: Updating value in of %d", tmp);
*argP = tmp + 1;
sRegTest3Event_T2_.Set ();
}
}
};
struct FRED2 {
static void DoIt (void* ignored)
{
int* argP = reinterpret_cast<int*> (ignored);
for (int i = 0; i < 10; i++) {
sRegTest3Event_T2_.Wait ();
int tmp = *argP;
Execution::Sleep (.01);
//DbgTrace ("FRED2: Updating value in of %d", tmp);
*argP = tmp + 1;
sRegTest3Event_T1_.Set ();
}
}
};
sRegTest3Event_T1_.Reset ();
sRegTest3Event_T2_.Reset ();
int updaterValue = 0;
Thread thread1 (&FRED1::DoIt, &updaterValue);
Thread thread2 (&FRED2::DoIt, &updaterValue);
thread1.Start ();
thread2.Start ();
sRegTest3Event_T1_.Set ();
thread1.WaitForDone ();
thread2.WaitForDone ();
//DbgTrace ("Test3 - updaterValue = %d", updaterValue);
VerifyTestResult (updaterValue == 2 * 10);
}
}
namespace {
struct data_ {};
void RegressionTest4_Lockable_ ()
{
{
Lockable<data_> x;
Lockable<data_> y = data_ ();
x = data_ ();
}
{
Lockable<int> x;
Lockable<int> y = 3;
x = 4;
}
{
// Make 2 concurrent threads, which update a lockable variable
struct FRED {
static void DoIt (void* ignored)
{
Lockable<int>* argP = reinterpret_cast<Lockable<int>*> (ignored);
for (int i = 0; i < 10; i++) {
AutoCriticalSection critSect (*argP);
int tmp = *argP;
Execution::Sleep (.01);
//DbgTrace ("Updating value in thread id %d", ::GetCurrentThreadId ());
*argP = tmp + 1;
}
}
};
Lockable<int> updaterValue = 0;
Thread thread1 (&FRED::DoIt, &updaterValue);
Thread thread2 (&FRED::DoIt, &updaterValue);
thread1.Start ();
thread2.Start ();
thread1.WaitForDone ();
thread2.WaitForDone ();
VerifyTestResult (updaterValue == 2 * 10);
}
}
}
namespace {
void RegressionTest5_Aborting_ ()
{
struct FRED {
static void DoIt ()
{
while (true) {
Execution::CheckForThreadAborting ();
}
}
};
Thread thread (&FRED::DoIt);
thread.Start ();
try {
thread.WaitForDone (1.0); // should timeout
VerifyTestResult (false);
}
catch (const Execution::WaitTimedOutException&) {
// GOOD
}
catch (...) {
VerifyTestResult (false);
}
// Now - abort it, and wait
thread.AbortAndWaitForDone ();
}
}
namespace {
void RegressionTest6_ThreadWaiting_ ()
{
struct FRED {
static void DoIt ()
{
Execution::Sleep (1.0);
}
};
// Normal usage
{
Thread thread (&FRED::DoIt);
thread.Start ();
thread.WaitForDone ();
}
// OK to never wait
for (int i = 0; i < 100; ++i) {
Thread thread (&FRED::DoIt);
thread.Start ();
}
// OK to wait and wait
{
Thread thread (&FRED::DoIt);
thread.Start ();
thread.WaitForDone ();
thread.WaitForDone (1.0);
thread.WaitForDone ();
thread.WaitForDone ();
}
}
}
namespace {
void RegressionTest7_SimpleThreadPool_ ()
{
{
ThreadPool p;
p.SetPoolSize (1);
p.Abort ();
p.WaitForDone ();
}
{
ThreadPool p;
p.SetPoolSize (1);
struct FRED {
static void DoIt (void* arg)
{
int* p = reinterpret_cast<int*> (arg);
(*p)++;
}
};
int intVal = 3;
Memory::SharedPtr<Execution::IRunnable> task = SimpleRunnable::MAKE (FRED::DoIt, &intVal);
p.AddTask (task);
p.WaitForTask (task);
p.AbortAndWaitForDone ();
VerifyTestResult (intVal == 4);
}
}
}
namespace {
void RegressionTest8_ThreadPool_ ()
{
// Make 2 concurrent tasks, which share a critical section object to take turns updating a variable
struct FRED {
static void DoIt (void* ignored)
{
int* argP = reinterpret_cast<int*> (ignored);
for (int i = 0; i < 10; i++) {
AutoCriticalSection critSect (sharedCriticalSection_);
int tmp = *argP;
Execution::Sleep (.01);
//DbgTrace ("Updating value in thread id %d", ::GetCurrentThreadId ());
*argP = tmp + 1;
}
}
};
for (unsigned int threadPoolSize = 1; threadPoolSize < 10; ++threadPoolSize) {
ThreadPool p;
p.SetPoolSize (threadPoolSize);
int updaterValue = 0;
Memory::SharedPtr<Execution::IRunnable> task1 = SimpleRunnable::MAKE (&FRED::DoIt, &updaterValue);
Memory::SharedPtr<Execution::IRunnable> task2 = SimpleRunnable::MAKE (&FRED::DoIt, &updaterValue);
p.AddTask (task1);
p.AddTask (task2);
p.WaitForTask (task1);
p.WaitForTask (task2);
p.AbortAndWaitForDone ();
VerifyTestResult (updaterValue == 2 * 10);
}
}
}
namespace {
void RegressionTest9_ThreadsAbortingEarly_ ()
{
// I was seeing SOME rare thread bug - trying to abort a thread which was itself trying to create a new thread - and was
// between the create of thread and Abort
struct FRED {
static void DoItInnerThread ()
{
Execution::Sleep (.1);
}
static void DoOuterThread ()
{
while (true) {
Thread t (DoItInnerThread);
Execution::Sleep (.2);
t.Start ();
}
}
};
Thread thread (&FRED::DoOuterThread);
thread.Start ();
Execution::Sleep (5);
thread.AbortAndWaitForDone ();
}
}
namespace {
void DoRegressionTests_ ()
{
RegressionTest1_ ();
RegressionTest2_ ();
RegressionTest3_ ();
RegressionTest4_Lockable_ ();
RegressionTest5_Aborting_ ();
RegressionTest6_ThreadWaiting_ ();
RegressionTest7_SimpleThreadPool_ ();
RegressionTest8_ThreadPool_ ();
RegressionTest9_ThreadsAbortingEarly_ ();
}
}
#if qOnlyOneMain
extern int TestThreads ()
#else
int main (int argc, const char* argv[])
#endif
{
Stroika::TestHarness::Setup ();
Stroika::TestHarness::PrintPassOrFail (DoRegressionTests_);
return EXIT_SUCCESS;
}
<|endoftext|> |
<commit_before>/*
* Copyright(c) Records For Living, Inc. 2004-2011. All rights reserved
*/
#include "Stroika/Foundation/StroikaPreComp.h"
#include <iostream>
#include <sstream>
#include "Stroika/Foundation/Debug/Assertions.h"
#include "Stroika/Foundation/Debug/Trace.h"
#include "Stroika/Foundation/Execution/Sleep.h"
#include "Stroika/Foundation/Time/Date.h"
#include "Stroika/Foundation/Time/DateTime.h"
#include "Stroika/Foundation/Time/Duration.h"
#include "Stroika/Foundation/Time/Realtime.h"
#include "../TestHarness/TestHarness.h"
using namespace Stroika::Foundation;
using namespace Stroika::Foundation::Time;
using Stroika::Foundation::Debug::TraceContextBumper;
namespace {
void Test_1_TestTickCountGrowsMonotonically_ ()
{
DurationSecondsType start = Time::GetTickCount ();
Execution::Sleep (0.1);
VerifyTestResult (start <= Time::GetTickCount ());
}
}
namespace {
void Test_2_TestTimeOfDay_ ()
{
{
TimeOfDay t;
VerifyTestResult (t.empty ());
TimeOfDay t2 (2);
VerifyTestResult (t < t2);
VerifyTestResult (t.GetAsSecondsCount () == 0);
VerifyTestResult (not t2.empty ());
VerifyTestResult (t.Format ().empty ());
VerifyTestResult (not t2.Format ().empty ());
VerifyTestResult (t2.GetHours () == 0);
VerifyTestResult (t2.GetMinutes () == 0);
VerifyTestResult (t2.GetSeconds () == 2);
}
{
TimeOfDay t2 (5 * 60 * 60 + 3 * 60 + 49);
VerifyTestResult (t2.GetHours () == 5);
VerifyTestResult (t2.GetMinutes () == 3);
VerifyTestResult (t2.GetSeconds () == 49);
}
{
TimeOfDay t2 (25 * 60 * 60);
VerifyTestResult (t2.GetHours () == 23);
VerifyTestResult (t2.GetMinutes () == 59);
VerifyTestResult (t2.GetSeconds () == 59);
VerifyTestResult (t2 == TimeOfDay::kMax);
}
{
VerifyTestResult (TimeOfDay::Parse (L"3pm", locale::classic ()).GetAsSecondsCount () == 15 * 60 * 60);
VerifyTestResult (TimeOfDay::Parse (L"3am", locale::classic ()).GetAsSecondsCount () == 3 * 60 * 60);
VerifyTestResult (TimeOfDay::Parse (L"3:00", locale::classic ()).GetAsSecondsCount () == 3 * 60 * 60);
VerifyTestResult (TimeOfDay::Parse (L"16:00", locale::classic ()).GetAsSecondsCount () == 16 * 60 * 60);
}
{
// Not sure these should ALWAYS work in any locale. Probably not. But any locale I'd test in??? Maybe... Good for starters anyhow...
// -- LGP 2011-10-08
VerifyTestResult (TimeOfDay::Parse (L"3pm", TimeOfDay::eCurrentLocale_PF).GetAsSecondsCount () == 15 * 60 * 60);
VerifyTestResult (TimeOfDay::Parse (L"3am", TimeOfDay::eCurrentLocale_PF).GetAsSecondsCount () == 3 * 60 * 60);
VerifyTestResult (TimeOfDay::Parse (L"3:00", TimeOfDay::eCurrentLocale_PF).GetAsSecondsCount () == 3 * 60 * 60);
VerifyTestResult (TimeOfDay::Parse (L"16:00", TimeOfDay::eCurrentLocale_PF).GetAsSecondsCount () == 16 * 60 * 60);
}
{
#if qPlatform_Windows
const LCID kUS_ENGLISH_LOCALE = MAKELCID (MAKELANGID (LANG_ENGLISH, SUBLANG_ENGLISH_US), SORT_DEFAULT);
#endif
TimeOfDay threePM = TimeOfDay::Parse (L"3pm", locale::classic ());
#if qPlatform_Windows
VerifyTestResult (threePM.Format (kUS_ENGLISH_LOCALE) == L"3 PM");
#endif
//VerifyTestResult (threePM.Format (locale::classic ()) == L"3 PM");
VerifyTestResult (threePM.Format (locale::classic ()) == L"15:00:00"); // UGH!!!
}
}
}
namespace {
void VERIFY_ROUNDTRIP_XML_ (const Date& d)
{
VerifyTestResult (Date::Parse (d.Format (Date::eXML_PF), Date::eXML_PF) == d);
}
void Test_3_TestDate_ ()
{
{
Date d (Year (1903), eApril, DayOfMonth (4));
VerifyTestResult (d.Format (Date::eXML_PF) == L"1903-04-04");
VERIFY_ROUNDTRIP_XML_ (d);
d.AddDays (4);
VERIFY_ROUNDTRIP_XML_ (d);
VerifyTestResult (d.Format (Date::eXML_PF) == L"1903-04-08");
d.AddDays (-4);
VERIFY_ROUNDTRIP_XML_ (d);
VerifyTestResult (d.Format (Date::eXML_PF) == L"1903-04-04");
}
{
Date d = Date::Parse (L"09/14/1752", locale::classic ());
VerifyTestResult (not d.empty ());
VerifyTestResult (d == Date::kMin);
VerifyTestResult (d.Format (Date::eXML_PF) == L"1752-09-14"); // xml cuz otherwise we get confusion over locale - COULD use hardwired US locale at some point?
}
{
Date d;
VerifyTestResult (d.empty ());
VerifyTestResult (d < DateTime::GetToday ());
VerifyTestResult (DateTime::GetToday () > d);
}
{
Date d = Date::kMin;
VerifyTestResult (not d.empty ());
VerifyTestResult (d < DateTime::Now ().GetDate ());
VerifyTestResult (not (DateTime::Now ().GetDate () < d));
VerifyTestResult (d.Format (Date::eXML_PF) == L"1752-09-14"); // xml cuz otherwise we get confusion over locale - COULD use hardwired US locale at some point?
}
#if qPlatform_Windows
{
wstring testCase = L"6/1/2005";
VerifyTestResult (Date::Parse (testCase, LOCALE_USER_DEFAULT) == Date::Parse (testCase, locale::classic ()));
}
{
wstring testCase = L"4/20/1964";
VerifyTestResult (Date::Parse (testCase, LOCALE_USER_DEFAULT) == Date::Parse (testCase, locale::classic ()));
}
{
wstring testCase = L"7/4/1776";
VerifyTestResult (Date::Parse (testCase, LOCALE_USER_DEFAULT) == Date::Parse (testCase, locale::classic ()));
}
{
wstring testCase = L"7/4/2076";
// TODO:
// Fails - debug soon -- LGP 2011-10-08
//VerifyTestResult (Date::Parse (testCase, LOCALE_USER_DEFAULT) == Date::Parse (testCase, locale::classic ()));
}
#endif
}
}
namespace {
void Test_4_TestDateTime_ ()
{
{
DateTime d = Date (Year (1903), eApril, DayOfMonth (4));
VerifyTestResult (d.Format (DateTime::eXML_PF) == L"1903-04-04");
}
{
DateTime d;
VerifyTestResult (d.empty ());
VerifyTestResult (d < DateTime::Now ());
VerifyTestResult (DateTime::Now () > d);
}
{
DateTime d = DateTime::kMin;
VerifyTestResult (not d.empty ());
VerifyTestResult (d < DateTime::Now ());
VerifyTestResult (DateTime::Now () > d);
d = DateTime (d.GetDate (), d.GetTimeOfDay (), DateTime::eUTC_TZ); // so that compare works - cuz we dont know timezone we'll run test with...
VerifyTestResult (d.Format (DateTime::eXML_PF) == L"1752-09-14T00:00:00Z"); // xml cuz otherwise we get confusion over locale - COULD use hardwired US locale at some point?
}
#if qPlatform_Windows
{
const LCID kUS_ENGLISH_LOCALE = MAKELCID (MAKELANGID (LANG_ENGLISH, SUBLANG_ENGLISH_US), SORT_DEFAULT);
wstring testCase = L"2010-01-01";
//TODO: FIX SO THIS WORKS... (or come up with better test)
//VerifyTestResult (DateTime::Parse (testCase, kUS_ENGLISH_LOCALE) == DateTime::Parse (testCase, locale::classic ()));
}
#endif
}
}
namespace {
void Test_5_DateTimeTimeT_ ()
{
{
DateTime d = Date (Year (2000), eApril, DayOfMonth (20));
VerifyTestResult (d.As<time_t> () == 956188800); // source - http://www.onlineconversion.com/unix_time.htm
}
{
DateTime d = DateTime (Date (Year (1995), eJune, DayOfMonth (4)), TimeOfDay::Parse (L"3pm", locale ()));
VerifyTestResult (d.As<time_t> () == 802278000); // source - http://www.onlineconversion.com/unix_time.htm
}
{
DateTime d = DateTime (Date (Year (1995), eJune, DayOfMonth (4)), TimeOfDay::Parse (L"3pm", TimeOfDay::eCurrentLocale_PF));
VerifyTestResult (d.As<time_t> () == 802278000); // source - http://www.onlineconversion.com/unix_time.htm
}
{
DateTime d = DateTime (Date (Year (1995), eJune, DayOfMonth (4)), TimeOfDay::Parse (L"3am", TimeOfDay::eCurrentLocale_PF));
VerifyTestResult (d.As<time_t> () == 802234800); // source - http://www.onlineconversion.com/unix_time.htm
}
{
DateTime d = DateTime (Date (Year (1995), eJune, DayOfMonth (4)), TimeOfDay::Parse (L"3:00", TimeOfDay::eCurrentLocale_PF));
VerifyTestResult (d.As<time_t> () == 802234800); // source - http://www.onlineconversion.com/unix_time.htm
}
{
const time_t kTEST = 802234800;
DateTime d = DateTime (kTEST);
VerifyTestResult (d.As<time_t> () == kTEST); // source - http://www.onlineconversion.com/unix_time.htm
}
}
}
namespace {
void Test_6_Duration_ ()
{
const int kSecondsPerDay = TimeOfDay::kMaxSecondsPerDay;
{
const Duration k30Days = Duration (L"P30D");
VerifyTestResult (k30Days.As<time_t> () == 30 * kSecondsPerDay);
}
{
const Duration k6Months = Duration (L"P6M");
VerifyTestResult (k6Months.As<time_t> () == 6 * 30 * kSecondsPerDay);
}
{
const Duration kP1Y = Duration (L"P1Y");
VerifyTestResult (kP1Y.As<time_t> () == 365 * kSecondsPerDay);
}
{
const Duration kP2Y = Duration (L"P2Y");
VerifyTestResult (kP2Y.As<time_t> () == 2 * 365 * kSecondsPerDay);
VerifyTestResult (Duration (2 * 365 * kSecondsPerDay).As<wstring> () == L"P2Y");
}
{
const Duration kHalfMinute = Duration (L"PT0.5M");
VerifyTestResult (kHalfMinute.As<time_t> () == 30);
}
{
const Duration kD = Duration (L"PT0.1S");
VerifyTestResult (kD.As<time_t> () == 0);
VerifyTestResult (kD.As<double> () == 0.1);
}
{
const Duration kHalfMinute = Duration (L"PT0.5M");
VerifyTestResult (kHalfMinute.PrettyPrint () == L"30 seconds");
}
{
const Duration k3MS = Duration (L"PT0.003S");
VerifyTestResult (k3MS.PrettyPrint () == L"3 ms");
}
{
const Duration kD = Duration (L"PT1.003S");
VerifyTestResult (kD.PrettyPrint () == L"1 second, 3 ms");
}
{
const Duration kD = Duration (L"PT0.000045S");
VerifyTestResult (kD.PrettyPrint () == L"45 s");
}
VerifyTestResult (Duration (L"P30S").As<time_t> () == 30);
VerifyTestResult (Duration (L"PT30S").As<time_t> () == 30);
VerifyTestResult (Duration (60).As<wstring> () == L"PT1M");
VerifyTestResult (Duration (L"-PT1H1S").As<time_t> () == -3601);
for (time_t i = -45; i < 60 * 3 * 60 + 99; ++i) {
VerifyTestResult (Duration (Duration (i).As<wstring> ()).As<time_t> () == i);
}
for (time_t i = 60 * 60 * 24 * 365 - 40; i < 3 * 60 * 60 * 24 * 365; i += 263) {
VerifyTestResult (Duration (Duration (i).As<wstring> ()).As<time_t> () == i);
}
}
}
namespace {
void DoRegressionTests_ ()
{
Test_1_TestTickCountGrowsMonotonically_ ();
Test_2_TestTimeOfDay_ ();
Test_3_TestDate_ ();
Test_4_TestDateTime_ ();
Test_5_DateTimeTimeT_ ();
Test_6_Duration_ ();
}
}
#if qOnlyOneMain
extern int TestDateAndTime ()
#else
int main (int argc, const char* argv[])
#endif
{
Stroika::TestHarness::Setup ();
Stroika::TestHarness::PrintPassOrFail (DoRegressionTests_);
return EXIT_SUCCESS;
}
<commit_msg>reset codepage to UTF8 for Test.cpp test 7 source file (all SB utf8)<commit_after>/*
* Copyright(c) Records For Living, Inc. 2004-2011. All rights reserved
*/
#include "Stroika/Foundation/StroikaPreComp.h"
#include <iostream>
#include <sstream>
#include "Stroika/Foundation/Debug/Assertions.h"
#include "Stroika/Foundation/Debug/Trace.h"
#include "Stroika/Foundation/Execution/Sleep.h"
#include "Stroika/Foundation/Time/Date.h"
#include "Stroika/Foundation/Time/DateTime.h"
#include "Stroika/Foundation/Time/Duration.h"
#include "Stroika/Foundation/Time/Realtime.h"
#include "../TestHarness/TestHarness.h"
using namespace Stroika::Foundation;
using namespace Stroika::Foundation::Time;
using Stroika::Foundation::Debug::TraceContextBumper;
namespace {
void Test_1_TestTickCountGrowsMonotonically_ ()
{
DurationSecondsType start = Time::GetTickCount ();
Execution::Sleep (0.1);
VerifyTestResult (start <= Time::GetTickCount ());
}
}
namespace {
void Test_2_TestTimeOfDay_ ()
{
{
TimeOfDay t;
VerifyTestResult (t.empty ());
TimeOfDay t2 (2);
VerifyTestResult (t < t2);
VerifyTestResult (t.GetAsSecondsCount () == 0);
VerifyTestResult (not t2.empty ());
VerifyTestResult (t.Format ().empty ());
VerifyTestResult (not t2.Format ().empty ());
VerifyTestResult (t2.GetHours () == 0);
VerifyTestResult (t2.GetMinutes () == 0);
VerifyTestResult (t2.GetSeconds () == 2);
}
{
TimeOfDay t2 (5 * 60 * 60 + 3 * 60 + 49);
VerifyTestResult (t2.GetHours () == 5);
VerifyTestResult (t2.GetMinutes () == 3);
VerifyTestResult (t2.GetSeconds () == 49);
}
{
TimeOfDay t2 (25 * 60 * 60);
VerifyTestResult (t2.GetHours () == 23);
VerifyTestResult (t2.GetMinutes () == 59);
VerifyTestResult (t2.GetSeconds () == 59);
VerifyTestResult (t2 == TimeOfDay::kMax);
}
{
VerifyTestResult (TimeOfDay::Parse (L"3pm", locale::classic ()).GetAsSecondsCount () == 15 * 60 * 60);
VerifyTestResult (TimeOfDay::Parse (L"3am", locale::classic ()).GetAsSecondsCount () == 3 * 60 * 60);
VerifyTestResult (TimeOfDay::Parse (L"3:00", locale::classic ()).GetAsSecondsCount () == 3 * 60 * 60);
VerifyTestResult (TimeOfDay::Parse (L"16:00", locale::classic ()).GetAsSecondsCount () == 16 * 60 * 60);
}
{
// Not sure these should ALWAYS work in any locale. Probably not. But any locale I'd test in??? Maybe... Good for starters anyhow...
// -- LGP 2011-10-08
VerifyTestResult (TimeOfDay::Parse (L"3pm", TimeOfDay::eCurrentLocale_PF).GetAsSecondsCount () == 15 * 60 * 60);
VerifyTestResult (TimeOfDay::Parse (L"3am", TimeOfDay::eCurrentLocale_PF).GetAsSecondsCount () == 3 * 60 * 60);
VerifyTestResult (TimeOfDay::Parse (L"3:00", TimeOfDay::eCurrentLocale_PF).GetAsSecondsCount () == 3 * 60 * 60);
VerifyTestResult (TimeOfDay::Parse (L"16:00", TimeOfDay::eCurrentLocale_PF).GetAsSecondsCount () == 16 * 60 * 60);
}
{
#if qPlatform_Windows
const LCID kUS_ENGLISH_LOCALE = MAKELCID (MAKELANGID (LANG_ENGLISH, SUBLANG_ENGLISH_US), SORT_DEFAULT);
#endif
TimeOfDay threePM = TimeOfDay::Parse (L"3pm", locale::classic ());
#if qPlatform_Windows
VerifyTestResult (threePM.Format (kUS_ENGLISH_LOCALE) == L"3 PM");
#endif
//VerifyTestResult (threePM.Format (locale::classic ()) == L"3 PM");
VerifyTestResult (threePM.Format (locale::classic ()) == L"15:00:00"); // UGH!!!
}
}
}
namespace {
void VERIFY_ROUNDTRIP_XML_ (const Date& d)
{
VerifyTestResult (Date::Parse (d.Format (Date::eXML_PF), Date::eXML_PF) == d);
}
void Test_3_TestDate_ ()
{
{
Date d (Year (1903), eApril, DayOfMonth (4));
VerifyTestResult (d.Format (Date::eXML_PF) == L"1903-04-04");
VERIFY_ROUNDTRIP_XML_ (d);
d.AddDays (4);
VERIFY_ROUNDTRIP_XML_ (d);
VerifyTestResult (d.Format (Date::eXML_PF) == L"1903-04-08");
d.AddDays (-4);
VERIFY_ROUNDTRIP_XML_ (d);
VerifyTestResult (d.Format (Date::eXML_PF) == L"1903-04-04");
}
{
Date d = Date::Parse (L"09/14/1752", locale::classic ());
VerifyTestResult (not d.empty ());
VerifyTestResult (d == Date::kMin);
VerifyTestResult (d.Format (Date::eXML_PF) == L"1752-09-14"); // xml cuz otherwise we get confusion over locale - COULD use hardwired US locale at some point?
}
{
Date d;
VerifyTestResult (d.empty ());
VerifyTestResult (d < DateTime::GetToday ());
VerifyTestResult (DateTime::GetToday () > d);
}
{
Date d = Date::kMin;
VerifyTestResult (not d.empty ());
VerifyTestResult (d < DateTime::Now ().GetDate ());
VerifyTestResult (not (DateTime::Now ().GetDate () < d));
VerifyTestResult (d.Format (Date::eXML_PF) == L"1752-09-14"); // xml cuz otherwise we get confusion over locale - COULD use hardwired US locale at some point?
}
#if qPlatform_Windows
{
wstring testCase = L"6/1/2005";
VerifyTestResult (Date::Parse (testCase, LOCALE_USER_DEFAULT) == Date::Parse (testCase, locale::classic ()));
}
{
wstring testCase = L"4/20/1964";
VerifyTestResult (Date::Parse (testCase, LOCALE_USER_DEFAULT) == Date::Parse (testCase, locale::classic ()));
}
{
wstring testCase = L"7/4/1776";
VerifyTestResult (Date::Parse (testCase, LOCALE_USER_DEFAULT) == Date::Parse (testCase, locale::classic ()));
}
{
wstring testCase = L"7/4/2076";
// TODO:
// Fails - debug soon -- LGP 2011-10-08
//VerifyTestResult (Date::Parse (testCase, LOCALE_USER_DEFAULT) == Date::Parse (testCase, locale::classic ()));
}
#endif
}
}
namespace {
void Test_4_TestDateTime_ ()
{
{
DateTime d = Date (Year (1903), eApril, DayOfMonth (4));
VerifyTestResult (d.Format (DateTime::eXML_PF) == L"1903-04-04");
}
{
DateTime d;
VerifyTestResult (d.empty ());
VerifyTestResult (d < DateTime::Now ());
VerifyTestResult (DateTime::Now () > d);
}
{
DateTime d = DateTime::kMin;
VerifyTestResult (not d.empty ());
VerifyTestResult (d < DateTime::Now ());
VerifyTestResult (DateTime::Now () > d);
d = DateTime (d.GetDate (), d.GetTimeOfDay (), DateTime::eUTC_TZ); // so that compare works - cuz we dont know timezone we'll run test with...
VerifyTestResult (d.Format (DateTime::eXML_PF) == L"1752-09-14T00:00:00Z"); // xml cuz otherwise we get confusion over locale - COULD use hardwired US locale at some point?
}
#if qPlatform_Windows
{
const LCID kUS_ENGLISH_LOCALE = MAKELCID (MAKELANGID (LANG_ENGLISH, SUBLANG_ENGLISH_US), SORT_DEFAULT);
wstring testCase = L"2010-01-01";
//TODO: FIX SO THIS WORKS... (or come up with better test)
//VerifyTestResult (DateTime::Parse (testCase, kUS_ENGLISH_LOCALE) == DateTime::Parse (testCase, locale::classic ()));
}
#endif
}
}
namespace {
void Test_5_DateTimeTimeT_ ()
{
{
DateTime d = Date (Year (2000), eApril, DayOfMonth (20));
VerifyTestResult (d.As<time_t> () == 956188800); // source - http://www.onlineconversion.com/unix_time.htm
}
{
DateTime d = DateTime (Date (Year (1995), eJune, DayOfMonth (4)), TimeOfDay::Parse (L"3pm", locale ()));
VerifyTestResult (d.As<time_t> () == 802278000); // source - http://www.onlineconversion.com/unix_time.htm
}
{
DateTime d = DateTime (Date (Year (1995), eJune, DayOfMonth (4)), TimeOfDay::Parse (L"3pm", TimeOfDay::eCurrentLocale_PF));
VerifyTestResult (d.As<time_t> () == 802278000); // source - http://www.onlineconversion.com/unix_time.htm
}
{
DateTime d = DateTime (Date (Year (1995), eJune, DayOfMonth (4)), TimeOfDay::Parse (L"3am", TimeOfDay::eCurrentLocale_PF));
VerifyTestResult (d.As<time_t> () == 802234800); // source - http://www.onlineconversion.com/unix_time.htm
}
{
DateTime d = DateTime (Date (Year (1995), eJune, DayOfMonth (4)), TimeOfDay::Parse (L"3:00", TimeOfDay::eCurrentLocale_PF));
VerifyTestResult (d.As<time_t> () == 802234800); // source - http://www.onlineconversion.com/unix_time.htm
}
{
const time_t kTEST = 802234800;
DateTime d = DateTime (kTEST);
VerifyTestResult (d.As<time_t> () == kTEST); // source - http://www.onlineconversion.com/unix_time.htm
}
}
}
namespace {
void Test_6_Duration_ ()
{
const int kSecondsPerDay = TimeOfDay::kMaxSecondsPerDay;
{
const Duration k30Days = Duration (L"P30D");
VerifyTestResult (k30Days.As<time_t> () == 30 * kSecondsPerDay);
}
{
const Duration k6Months = Duration (L"P6M");
VerifyTestResult (k6Months.As<time_t> () == 6 * 30 * kSecondsPerDay);
}
{
const Duration kP1Y = Duration (L"P1Y");
VerifyTestResult (kP1Y.As<time_t> () == 365 * kSecondsPerDay);
}
{
const Duration kP2Y = Duration (L"P2Y");
VerifyTestResult (kP2Y.As<time_t> () == 2 * 365 * kSecondsPerDay);
VerifyTestResult (Duration (2 * 365 * kSecondsPerDay).As<wstring> () == L"P2Y");
}
{
const Duration kHalfMinute = Duration (L"PT0.5M");
VerifyTestResult (kHalfMinute.As<time_t> () == 30);
}
{
const Duration kD = Duration (L"PT0.1S");
VerifyTestResult (kD.As<time_t> () == 0);
VerifyTestResult (kD.As<double> () == 0.1);
}
{
const Duration kHalfMinute = Duration (L"PT0.5M");
VerifyTestResult (kHalfMinute.PrettyPrint () == L"30 seconds");
}
{
const Duration k3MS = Duration (L"PT0.003S");
VerifyTestResult (k3MS.PrettyPrint () == L"3 ms");
}
{
const Duration kD = Duration (L"PT1.003S");
VerifyTestResult (kD.PrettyPrint () == L"1 second, 3 ms");
}
{
const Duration kD = Duration (L"PT0.000045S");
VerifyTestResult (kD.PrettyPrint () == L"45 µs");
}
VerifyTestResult (Duration (L"P30S").As<time_t> () == 30);
VerifyTestResult (Duration (L"PT30S").As<time_t> () == 30);
VerifyTestResult (Duration (60).As<wstring> () == L"PT1M");
VerifyTestResult (Duration (L"-PT1H1S").As<time_t> () == -3601);
for (time_t i = -45; i < 60 * 3 * 60 + 99; ++i) {
VerifyTestResult (Duration (Duration (i).As<wstring> ()).As<time_t> () == i);
}
for (time_t i = 60 * 60 * 24 * 365 - 40; i < 3 * 60 * 60 * 24 * 365; i += 263) {
VerifyTestResult (Duration (Duration (i).As<wstring> ()).As<time_t> () == i);
}
}
}
namespace {
void DoRegressionTests_ ()
{
Test_1_TestTickCountGrowsMonotonically_ ();
Test_2_TestTimeOfDay_ ();
Test_3_TestDate_ ();
Test_4_TestDateTime_ ();
Test_5_DateTimeTimeT_ ();
Test_6_Duration_ ();
}
}
#if qOnlyOneMain
extern int TestDateAndTime ()
#else
int main (int argc, const char* argv[])
#endif
{
Stroika::TestHarness::Setup ();
Stroika::TestHarness::PrintPassOrFail (DoRegressionTests_);
return EXIT_SUCCESS;
}
<|endoftext|> |
<commit_before>StringID("easy");
StringID("easy 1");
StringID( "easy 2" );
StringID ("easy 3"); StringID ("easy 4");
StringID ("easy 3"); Toto; StringID ("easy 4");
Coucou; StringID ("easy 3"); Toto; StringID ("easy 4"); Lolilol;
StringID ("easy 4");
StringID( "easy XV3" );
hiphop StringID("easy A");
StringID( "easy B" );
WRONGStringID ("easy");
WRONG_StringID("easy");
WRONG,StringID("easy");
StringID( "easy", 0x21159d601e3fd4bb ); Hihiphip
StringID( "easy B" );StringID( "easy",0x1234 ); Hihiphip
StringID ("wrong" , 0x123 123);
StringID ("easy", 9876); Coucou; StringID ("easy 3");
StringID( "Wrong" , 123 123 123);
WRONGStringID ("easy" ,,, 123);
WRONG_StringID("easy" ,123);
WRONG,StringID("easy" , 0x1233221);
std::make_pair(std::make_pair(GL_FLOAT_VEC4, StringID("color", 0x77f5c18e246c6638)), LAMBDA_FUNCTION{ vertices.set_data<glm::vec4>(data.colors, StringID("color", 0x77f5c18e246c6638)); })
std::make_pair(std::make_pair(GL_FLOAT_VEC4, StringID("color")), LAMBDA_FUNCTION{ vertices.set_data<glm::vec4>(data.colors, StringID("color")); })
<commit_msg>Simple test update<commit_after>StringID("easy");
StringID("easy 1");
StringID( "easy 2" );
StringID ("easy 3"); StringID ("easy 4");
StringID ("easy 3"); Toto; StringID ("easy 4");
Coucou; StringID ("easy 3"); Toto; StringID ("easy 4"); Lolilol;
StringID ("easy 4");
StringID( "easy XV3" );
hiphop StringID("easy A");
StringID( "easy B" );
WRONGStringID ("easy");
WRONG_StringID("easy");
WRONG,StringID("easy");
StringID( "easy", 0x21159d601e3fd4bb ); Hihiphip
StringID( "easy B" );StringID( "easy",0x1234 ); Hihiphip
StringID ("wrong" , 0x123 123);
StringID ("easy", 9876); Coucou; StringID ("easy 3");
StringID( "Wrong" , 123 123 123);
WRONGStringID ("easy" ,,, 123);
WRONG_StringID("easy" ,123);
WRONG,StringID("easy" , 0x1233221);
std::make_pair(std::make_pair(GL_FLOAT_VEC4, StringID("colorA", 0x77f5c18e246c6638)), LAMBDA_FUNCTION{ vertices.set_data<glm::vec4>(data.colors, StringID("colorB", 0x77f5c18e246c6638)); })
std::make_pair(std::make_pair(GL_FLOAT_VEC4, StringID("colorA")), LAMBDA_FUNCTION{ vertices.set_data<glm::vec4>(data.colors, StringID("colorB")); })
<|endoftext|> |
<commit_before>/*
This file is part of the Util library.
Copyright (C) 2007-2012 Benjamin Eikel <benjamin@eikel.org>
Copyright (C) 2007-2012 Claudius Jähn <claudius@uni-paderborn.de>
Copyright (C) 2007-2012 Ralf Petring <ralf@petring.net>
This library is subject to the terms of the Mozilla Public License, v. 2.0.
You should have received a copy of the MPL along with this library; see the
file LICENSE. If not, you can obtain one at http://mozilla.org/MPL/2.0/.
*/
#if defined(UTIL_HAVE_LIB_X11) and defined(UTIL_HAVE_LIB_EGL)
#include "WindowEGL.h"
#include "WindowX11Data.h"
#include "../StringUtils.h"
#include <X11/Xlib.h>
#include <X11/Xutil.h>
#include <EGL/egl.h>
#include <memory>
#include <stdexcept>
namespace Util {
namespace UI {
extern Key keySymToKey(KeySym sym);
struct WindowEGL::WindowEGLData {
EGLDisplay display;
EGLContext context;
EGLSurface surface;
WindowEGLData() :
display(EGL_NO_DISPLAY), context(EGL_NO_CONTEXT), surface(EGL_NO_SURFACE) {
}
~WindowEGLData() {
if (display != EGL_NO_DISPLAY) {
eglMakeCurrent(display, EGL_NO_SURFACE, EGL_NO_SURFACE, EGL_NO_CONTEXT);
if (surface != EGL_NO_SURFACE) {
eglDestroySurface(display, surface);
}
if (context != EGL_NO_CONTEXT) {
eglDestroyContext(display, context);
}
eglTerminate(display);
}
}
};
static std::string eglErrorToString(const EGLint errorCode) {
const std::string strErrorCode = StringUtils::toString(errorCode);
switch(errorCode) {
case EGL_SUCCESS:
return "EGL_SUCCESS/" + strErrorCode + ": The last function succeeded without error.";
case EGL_NOT_INITIALIZED:
return "EGL_NOT_INITIALIZED/" + strErrorCode + ": EGL is not initialized, or could not be initialized, for the specified EGL display connection.";
case EGL_BAD_ACCESS:
return "EGL_BAD_ACCESS/" + strErrorCode + ": EGL cannot access a requested resource (for example a context is bound in another thread).";
case EGL_BAD_ALLOC:
return "EGL_BAD_ALLOC/" + strErrorCode + ": EGL failed to allocate resources for the requested operation.";
case EGL_BAD_ATTRIBUTE:
return "EGL_BAD_ATTRIBUTE/" + strErrorCode + ": An unrecognized attribute or attribute value was passed in the attribute list.";
case EGL_BAD_CONTEXT:
return "EGL_BAD_CONTEXT/" + strErrorCode + ": An EGLContext argument does not name a valid EGL rendering context.";
case EGL_BAD_CONFIG:
return "EGL_BAD_CONFIG/" + strErrorCode + ": An EGLConfig argument does not name a valid EGL frame buffer configuration.";
case EGL_BAD_CURRENT_SURFACE:
return "EGL_BAD_CURRENT_SURFACE/" + strErrorCode + ": The current surface of the calling thread is a window, pixel buffer or pixmap that is no longer valid.";
case EGL_BAD_DISPLAY:
return "EGL_BAD_DISPLAY/" + strErrorCode + ": An EGLDisplay argument does not name a valid EGL display connection.";
case EGL_BAD_SURFACE:
return "EGL_BAD_SURFACE/" + strErrorCode + ": An EGLSurface argument does not name a valid surface (window, pixel buffer or pixmap) configured for GL rendering.";
case EGL_BAD_MATCH:
return "EGL_BAD_MATCH/" + strErrorCode + ": Arguments are inconsistent (for example, a valid context requires buffers not supplied by a valid surface).";
case EGL_BAD_PARAMETER:
return "EGL_BAD_PARAMETER/" + strErrorCode + ": One or more argument values are invalid.";
case EGL_BAD_NATIVE_PIXMAP:
return "EGL_BAD_NATIVE_PIXMAP/" + strErrorCode + ": A NativePixmapType argument does not refer to a valid native pixmap.";
case EGL_BAD_NATIVE_WINDOW:
return "EGL_BAD_NATIVE_WINDOW/" + strErrorCode + ": A NativeWindowType argument does not refer to a valid native window.";
case EGL_CONTEXT_LOST:
return "EGL_CONTEXT_LOST/" + strErrorCode + ": A power management event has occurred. The application must destroy all contexts and reinitialise OpenGL ES state and objects to continue rendering.";
default:
return "";
}
}
WindowEGL::WindowEGL(const Window::Properties & properties) :
WindowX11(properties), eglData(new WindowEGLData) {
eglData->display = eglGetDisplay(x11Data->display);
if (eglData->display == EGL_NO_DISPLAY) {
throw std::runtime_error("Failed to open display.");
}
EGLint versionMajor;
EGLint versionMinor;
if (eglInitialize(eglData->display, &versionMajor, &versionMinor) == EGL_FALSE) {
throw std::runtime_error("Failed to initialize display.");
}
// EGL version 1.3 is needed for EGL_CONTEXT_CLIENT_VERSION
if ((versionMajor < 1) || ((versionMajor == 1) && (versionMinor < 3))) {
throw std::runtime_error("EGL version less than 1.3 detected.");
}
if (EGL_TRUE != eglBindAPI(EGL_OPENGL_ES_API)) {
throw std::runtime_error("Cannot bind API.");
}
// Define attributes of desired framebuffer configurations
EGLint fbAttribs[] = { EGL_COLOR_BUFFER_TYPE, EGL_RGB_BUFFER, EGL_BUFFER_SIZE, 24, EGL_RED_SIZE, 8, EGL_GREEN_SIZE, 8, EGL_BLUE_SIZE, 8, EGL_DEPTH_SIZE, 8,
EGL_NATIVE_RENDERABLE, EGL_TRUE, EGL_SURFACE_TYPE, EGL_WINDOW_BIT, EGL_NONE };
// Request a single framebuffer configuration
EGLConfig fbConfig;
EGLint fbCount;
if (eglChooseConfig(eglData->display, fbAttribs, &fbConfig, 1, &fbCount) == EGL_FALSE) {
throw std::runtime_error("Failed to retrieve a matching framebuffer configuration.");
}
if (fbCount == 0) {
// FIXME: Workaround: Use eglGetConfigs instead of eglChooseConfig, because sometimes eglChooseConfig does not find matching configurations.
EGLConfig fbConfigs[200];
eglGetConfigs(eglData->display, fbConfigs, 200, &fbCount);
for (EGLint i = 0; i < fbCount; ++i) {
EGLint value;
// We want to render into a window
eglGetConfigAttrib(eglData->display, fbConfigs[i], EGL_SURFACE_TYPE, &value);
if (!(value & EGL_WINDOW_BIT)) {
continue;
}
// We want a configuration with a depth buffer
eglGetConfigAttrib(eglData->display, fbConfigs[i], EGL_DEPTH_SIZE, &value);
if (value == 0) {
continue;
}
fbConfig = fbConfigs[i];
}
}
if (fbCount == 0) {
throw std::runtime_error("No matching framebuffer configurations found.");
}
EGLint visualID;
eglGetConfigAttrib(eglData->display, fbConfig, EGL_NATIVE_VISUAL_ID, &visualID);
const EGLint contextAttribs[] = { EGL_CONTEXT_CLIENT_VERSION, 2, EGL_NONE };
eglData->context = eglCreateContext(eglData->display, fbConfig, EGL_NO_CONTEXT, contextAttribs);
if (eglData->context == EGL_NO_CONTEXT) {
throw std::runtime_error("Failed to create OpenGL ES 2.x context. " +
eglErrorToString(eglGetError()));
}
// Create X11 window
XVisualInfo templateInfo;
templateInfo.visualid = visualID;
int visualCount;
XVisualInfo * visualsInfo = XGetVisualInfo(x11Data->display, VisualIDMask, &templateInfo, &visualCount);
if (visualsInfo == nullptr) {
throw std::runtime_error("Failed to find a matching visual.");
} else if (visualCount != 1) {
XFree(visualsInfo);
throw std::runtime_error("More than one visual found.");
}
x11Data->colorMap = XCreateColormap(x11Data->display, RootWindow(x11Data->display, visualsInfo[0].screen), visualsInfo[0].visual, AllocNone);
x11Data->freeColorMap = true;
XSetWindowAttributes windowAttribs;
windowAttribs.colormap = x11Data->colorMap;
windowAttribs.background_pixmap = None;
windowAttribs.border_pixel = 0;
windowAttribs.event_mask = StructureNotifyMask | KeyPressMask | KeyReleaseMask | ButtonPressMask | ButtonReleaseMask | PointerMotionMask;
x11Data->window = XCreateWindow(x11Data->display, RootWindow(x11Data->display, visualsInfo[0].screen),
0, 0, properties.clientAreaWidth, properties.clientAreaHeight,
0, visualsInfo[0].depth,
InputOutput, visualsInfo[0].visual, CWBorderPixel | CWColormap | CWEventMask, &windowAttribs);
XFree(visualsInfo);
if (!x11Data->window) {
throw std::runtime_error("Failed to create window.");
} else {
x11Data->freeWindow = true;
}
if (properties.borderless) {
x11Data->removeWindowBorder();
}
if (!properties.resizable) {
x11Data->fixWindowSize(static_cast<int>(properties.clientAreaWidth),
static_cast<int>(properties.clientAreaHeight));
}
x11Data->inputMethod = XOpenIM(x11Data->display, nullptr, nullptr, nullptr);
if (x11Data->inputMethod == nullptr) {
throw std::runtime_error("Failed to create input method.");
}
x11Data->inputContext = XCreateIC(x11Data->inputMethod,
XNInputStyle, XIMPreeditNone | XIMStatusNone,
XNClientWindow, x11Data->window,
XNFocusWindow, x11Data->window,
nullptr);
if (x11Data->inputContext == nullptr) {
throw std::runtime_error("Failed to create input context.");
}
XStoreName(x11Data->display, x11Data->window, properties.title.c_str());
XMapWindow(x11Data->display, x11Data->window);
if (properties.positioned) {
XMoveWindow(x11Data->display, x11Data->window, properties.posX, properties.posY);
}
eglData->surface = eglCreateWindowSurface(eglData->display, fbConfig, x11Data->window, nullptr);
if (eglData->surface == EGL_NO_SURFACE) {
throw std::runtime_error("Failed to create window surface.");
}
eglMakeCurrent(eglData->display, eglData->surface, eglData->surface, eglData->context);
}
WindowEGL::~WindowEGL() = default;
void WindowEGL::swapBuffers() {
eglSwapBuffers(eglData->display, eglData->surface);
}
}
}
#endif /* defined(UTIL_HAVE_LIB_X11) and defined(UTIL_HAVE_LIB_EGL) */
<commit_msg>Select rendering API based on parameter<commit_after>/*
This file is part of the Util library.
Copyright (C) 2007-2012 Benjamin Eikel <benjamin@eikel.org>
Copyright (C) 2007-2012 Claudius Jähn <claudius@uni-paderborn.de>
Copyright (C) 2007-2012 Ralf Petring <ralf@petring.net>
This library is subject to the terms of the Mozilla Public License, v. 2.0.
You should have received a copy of the MPL along with this library; see the
file LICENSE. If not, you can obtain one at http://mozilla.org/MPL/2.0/.
*/
#if defined(UTIL_HAVE_LIB_X11) and defined(UTIL_HAVE_LIB_EGL)
#include "WindowEGL.h"
#include "WindowX11Data.h"
#include "../StringUtils.h"
#include <X11/Xlib.h>
#include <X11/Xutil.h>
#include <EGL/egl.h>
#include <memory>
#include <stdexcept>
namespace Util {
namespace UI {
extern Key keySymToKey(KeySym sym);
struct WindowEGL::WindowEGLData {
EGLDisplay display;
EGLContext context;
EGLSurface surface;
WindowEGLData() :
display(EGL_NO_DISPLAY), context(EGL_NO_CONTEXT), surface(EGL_NO_SURFACE) {
}
~WindowEGLData() {
if (display != EGL_NO_DISPLAY) {
eglMakeCurrent(display, EGL_NO_SURFACE, EGL_NO_SURFACE, EGL_NO_CONTEXT);
if (surface != EGL_NO_SURFACE) {
eglDestroySurface(display, surface);
}
if (context != EGL_NO_CONTEXT) {
eglDestroyContext(display, context);
}
eglTerminate(display);
}
}
};
static std::string eglErrorToString(const EGLint errorCode) {
const std::string strErrorCode = StringUtils::toString(errorCode);
switch(errorCode) {
case EGL_SUCCESS:
return "EGL_SUCCESS/" + strErrorCode + ": The last function succeeded without error.";
case EGL_NOT_INITIALIZED:
return "EGL_NOT_INITIALIZED/" + strErrorCode + ": EGL is not initialized, or could not be initialized, for the specified EGL display connection.";
case EGL_BAD_ACCESS:
return "EGL_BAD_ACCESS/" + strErrorCode + ": EGL cannot access a requested resource (for example a context is bound in another thread).";
case EGL_BAD_ALLOC:
return "EGL_BAD_ALLOC/" + strErrorCode + ": EGL failed to allocate resources for the requested operation.";
case EGL_BAD_ATTRIBUTE:
return "EGL_BAD_ATTRIBUTE/" + strErrorCode + ": An unrecognized attribute or attribute value was passed in the attribute list.";
case EGL_BAD_CONTEXT:
return "EGL_BAD_CONTEXT/" + strErrorCode + ": An EGLContext argument does not name a valid EGL rendering context.";
case EGL_BAD_CONFIG:
return "EGL_BAD_CONFIG/" + strErrorCode + ": An EGLConfig argument does not name a valid EGL frame buffer configuration.";
case EGL_BAD_CURRENT_SURFACE:
return "EGL_BAD_CURRENT_SURFACE/" + strErrorCode + ": The current surface of the calling thread is a window, pixel buffer or pixmap that is no longer valid.";
case EGL_BAD_DISPLAY:
return "EGL_BAD_DISPLAY/" + strErrorCode + ": An EGLDisplay argument does not name a valid EGL display connection.";
case EGL_BAD_SURFACE:
return "EGL_BAD_SURFACE/" + strErrorCode + ": An EGLSurface argument does not name a valid surface (window, pixel buffer or pixmap) configured for GL rendering.";
case EGL_BAD_MATCH:
return "EGL_BAD_MATCH/" + strErrorCode + ": Arguments are inconsistent (for example, a valid context requires buffers not supplied by a valid surface).";
case EGL_BAD_PARAMETER:
return "EGL_BAD_PARAMETER/" + strErrorCode + ": One or more argument values are invalid.";
case EGL_BAD_NATIVE_PIXMAP:
return "EGL_BAD_NATIVE_PIXMAP/" + strErrorCode + ": A NativePixmapType argument does not refer to a valid native pixmap.";
case EGL_BAD_NATIVE_WINDOW:
return "EGL_BAD_NATIVE_WINDOW/" + strErrorCode + ": A NativeWindowType argument does not refer to a valid native window.";
case EGL_CONTEXT_LOST:
return "EGL_CONTEXT_LOST/" + strErrorCode + ": A power management event has occurred. The application must destroy all contexts and reinitialise OpenGL ES state and objects to continue rendering.";
default:
return "";
}
}
WindowEGL::WindowEGL(const Window::Properties & properties) :
WindowX11(properties), eglData(new WindowEGLData) {
eglData->display = eglGetDisplay(x11Data->display);
if (eglData->display == EGL_NO_DISPLAY) {
throw std::runtime_error("Failed to open display.");
}
EGLint versionMajor;
EGLint versionMinor;
if (eglInitialize(eglData->display, &versionMajor, &versionMinor) == EGL_FALSE) {
throw std::runtime_error("Failed to initialize display.");
}
// EGL version 1.3 is needed for EGL_CONTEXT_CLIENT_VERSION
if ((versionMajor < 1) || ((versionMajor == 1) && (versionMinor < 3))) {
throw std::runtime_error("EGL version less than 1.3 detected.");
}
EGLenum api;
EGLint glesVersion = 0;
switch(properties.renderingAPI) {
case Properties::RenderingAPI::GL_ES_1:
api = EGL_OPENGL_ES_API;
glesVersion = 1;
break;
case Properties::RenderingAPI::GL_ES_2:
api = EGL_OPENGL_ES_API;
glesVersion = 2;
break;
case Properties::RenderingAPI::GL_ES_3:
api = EGL_OPENGL_ES_API;
glesVersion = 3;
break;
case Properties::RenderingAPI::GL:
api = EGL_OPENGL_API;
break;
default:
throw std::runtime_error("Unsupported rendering API.");
}
if (EGL_TRUE != eglBindAPI(api)) {
throw std::runtime_error("Cannot bind API.");
}
// Define attributes of desired framebuffer configurations
EGLint fbAttribs[] = { EGL_COLOR_BUFFER_TYPE, EGL_RGB_BUFFER, EGL_BUFFER_SIZE, 24, EGL_RED_SIZE, 8, EGL_GREEN_SIZE, 8, EGL_BLUE_SIZE, 8, EGL_DEPTH_SIZE, 8,
EGL_NATIVE_RENDERABLE, EGL_TRUE, EGL_SURFACE_TYPE, EGL_WINDOW_BIT, EGL_NONE };
// Request a single framebuffer configuration
EGLConfig fbConfig;
EGLint fbCount;
if (eglChooseConfig(eglData->display, fbAttribs, &fbConfig, 1, &fbCount) == EGL_FALSE) {
throw std::runtime_error("Failed to retrieve a matching framebuffer configuration.");
}
if (fbCount == 0) {
// FIXME: Workaround: Use eglGetConfigs instead of eglChooseConfig, because sometimes eglChooseConfig does not find matching configurations.
EGLConfig fbConfigs[200];
eglGetConfigs(eglData->display, fbConfigs, 200, &fbCount);
for (EGLint i = 0; i < fbCount; ++i) {
EGLint value;
// We want to render into a window
eglGetConfigAttrib(eglData->display, fbConfigs[i], EGL_SURFACE_TYPE, &value);
if (!(value & EGL_WINDOW_BIT)) {
continue;
}
// We want a configuration with a depth buffer
eglGetConfigAttrib(eglData->display, fbConfigs[i], EGL_DEPTH_SIZE, &value);
if (value == 0) {
continue;
}
fbConfig = fbConfigs[i];
}
}
if (fbCount == 0) {
throw std::runtime_error("No matching framebuffer configurations found.");
}
EGLint visualID;
eglGetConfigAttrib(eglData->display, fbConfig, EGL_NATIVE_VISUAL_ID, &visualID);
EGLint contextAttribs[] = { EGL_CONTEXT_CLIENT_VERSION, glesVersion, EGL_NONE };
if (0 == glesVersion) {
contextAttribs[0] = EGL_NONE;
contextAttribs[1] = EGL_NONE;
}
eglData->context = eglCreateContext(eglData->display, fbConfig, EGL_NO_CONTEXT, contextAttribs);
if (eglData->context == EGL_NO_CONTEXT) {
throw std::runtime_error("Failed to create context: " +
eglErrorToString(eglGetError()));
}
// Create X11 window
XVisualInfo templateInfo;
templateInfo.visualid = visualID;
int visualCount;
XVisualInfo * visualsInfo = XGetVisualInfo(x11Data->display, VisualIDMask, &templateInfo, &visualCount);
if (visualsInfo == nullptr) {
throw std::runtime_error("Failed to find a matching visual.");
} else if (visualCount != 1) {
XFree(visualsInfo);
throw std::runtime_error("More than one visual found.");
}
x11Data->colorMap = XCreateColormap(x11Data->display, RootWindow(x11Data->display, visualsInfo[0].screen), visualsInfo[0].visual, AllocNone);
x11Data->freeColorMap = true;
XSetWindowAttributes windowAttribs;
windowAttribs.colormap = x11Data->colorMap;
windowAttribs.background_pixmap = None;
windowAttribs.border_pixel = 0;
windowAttribs.event_mask = StructureNotifyMask | KeyPressMask | KeyReleaseMask | ButtonPressMask | ButtonReleaseMask | PointerMotionMask;
x11Data->window = XCreateWindow(x11Data->display, RootWindow(x11Data->display, visualsInfo[0].screen),
0, 0, properties.clientAreaWidth, properties.clientAreaHeight,
0, visualsInfo[0].depth,
InputOutput, visualsInfo[0].visual, CWBorderPixel | CWColormap | CWEventMask, &windowAttribs);
XFree(visualsInfo);
if (!x11Data->window) {
throw std::runtime_error("Failed to create window.");
} else {
x11Data->freeWindow = true;
}
if (properties.borderless) {
x11Data->removeWindowBorder();
}
if (!properties.resizable) {
x11Data->fixWindowSize(static_cast<int>(properties.clientAreaWidth),
static_cast<int>(properties.clientAreaHeight));
}
x11Data->inputMethod = XOpenIM(x11Data->display, nullptr, nullptr, nullptr);
if (x11Data->inputMethod == nullptr) {
throw std::runtime_error("Failed to create input method.");
}
x11Data->inputContext = XCreateIC(x11Data->inputMethod,
XNInputStyle, XIMPreeditNone | XIMStatusNone,
XNClientWindow, x11Data->window,
XNFocusWindow, x11Data->window,
nullptr);
if (x11Data->inputContext == nullptr) {
throw std::runtime_error("Failed to create input context.");
}
XStoreName(x11Data->display, x11Data->window, properties.title.c_str());
XMapWindow(x11Data->display, x11Data->window);
if (properties.positioned) {
XMoveWindow(x11Data->display, x11Data->window, properties.posX, properties.posY);
}
eglData->surface = eglCreateWindowSurface(eglData->display, fbConfig, x11Data->window, nullptr);
if (eglData->surface == EGL_NO_SURFACE) {
throw std::runtime_error("Failed to create window surface.");
}
eglMakeCurrent(eglData->display, eglData->surface, eglData->surface, eglData->context);
}
WindowEGL::~WindowEGL() = default;
void WindowEGL::swapBuffers() {
eglSwapBuffers(eglData->display, eglData->surface);
}
}
}
#endif /* defined(UTIL_HAVE_LIB_X11) and defined(UTIL_HAVE_LIB_EGL) */
<|endoftext|> |
<commit_before>//VBA_NestFunc.hpp
//Copyright (c) 2015 mmYYmmdd
#include "OAIdl.h" //wtypes.h
#include <memory>
//VBA配列の次元取得
__int32 __stdcall Dimension(const VARIANT* pv);
//プレースホルダの生成
VARIANT __stdcall placeholder(__int32);
//プレースホルダの判定
__int32 __stdcall is_placeholder(const VARIANT* pv);
//bindされていないVBA関数を2引数で呼び出す
VARIANT __stdcall unbind_invoke(VARIANT* bfun, VARIANT* param1, VARIANT* param2);
//--------------------------------------------------------
class safearrayRef {
SAFEARRAY* psa;
VARTYPE pvt;
std::size_t dim;
std::size_t elemsize;
char* it;
std::size_t size[3];
VARIANT val_;
public:
safearrayRef(const VARIANT* pv);
~safearrayRef();
std::size_t getDim() const;
std::size_t getSize(std::size_t i) const;
std::size_t getOriginalLBound(std::size_t i) const;
VARIANT& operator()(std::size_t i, std::size_t j = 0, std::size_t k = 0);
};
//--------------------------------------------------------
//関数のインタフェース
class funcExpr_i {
public:
virtual ~funcExpr_i();
virtual bool isYielder() const;
virtual VARIANT* eval(VARIANT*, VARIANT*, int left_right = 0) = 0;
};
//--------------------------------------------------------
//使用する唯一のVBAコールバック関数型 vbCallbackFunc_t
//VBAにおけるシグネチャは
// Function fun(ByRef elem As Variant, ByRef dummy As Variant) As Variant
// もしくは
// Function fun(ByRef elem As Variant, Optional ByRef dummy As Variant) As Variant
using vbCallbackFunc_t = VARIANT (__stdcall * )(VARIANT*, VARIANT*);
namespace{
struct VBCallbackStruct;
}
//
class functionExpr : public funcExpr_i {
vbCallbackFunc_t fun;
VARIANT val;
std::unique_ptr<funcExpr_i> left;
std::unique_ptr<funcExpr_i> right;
public:
functionExpr(const VARIANT*);
functionExpr(const VBCallbackStruct&);
~functionExpr();
VARIANT* eval(VARIANT*, VARIANT*, int left_right = 0);
bool isValid() const;
};
<commit_msg>リファクタリング<commit_after>//VBA_NestFunc.hpp
//Copyright (c) 2015 mmYYmmdd
#include "OAIdl.h" //wtypes.h
#include <memory>
#include <array>
//VBA配列の次元取得
__int32 __stdcall Dimension(const VARIANT* pv);
//プレースホルダの生成
VARIANT __stdcall placeholder(__int32);
//プレースホルダの判定
__int32 __stdcall is_placeholder(const VARIANT* pv);
//bindされていないVBA関数を2引数で呼び出す
VARIANT __stdcall unbind_invoke(VARIANT* bfun, VARIANT* param1, VARIANT* param2);
//--------------------------------------------------------
class safearrayRef {
SAFEARRAY* psa;
VARTYPE pvt;
std::size_t dim;
std::size_t elemsize;
char* it;
VARIANT val_;
std::array<std::size_t, 3> size;
public:
safearrayRef(const VARIANT* pv);
~safearrayRef();
std::size_t getDim() const;
std::size_t getSize(std::size_t i) const;
std::size_t getOriginalLBound(std::size_t i) const;
VARIANT& operator()(std::size_t i, std::size_t j = 0, std::size_t k = 0);
};
//--------------------------------------------------------
//関数のインタフェース
class funcExpr_i {
public:
virtual ~funcExpr_i();
virtual bool isYielder() const;
virtual VARIANT* eval(VARIANT*, VARIANT*, int left_right = 0) = 0;
};
//--------------------------------------------------------
//使用する唯一のVBAコールバック関数型 vbCallbackFunc_t
//VBAにおけるシグネチャは
// Function fun(ByRef elem As Variant, ByRef dummy As Variant) As Variant
// もしくは
// Function fun(ByRef elem As Variant, Optional ByRef dummy As Variant) As Variant
using vbCallbackFunc_t = VARIANT (__stdcall * )(VARIANT*, VARIANT*);
namespace{
struct VBCallbackStruct;
}
//
class functionExpr : public funcExpr_i {
vbCallbackFunc_t fun;
VARIANT val;
std::unique_ptr<funcExpr_i> left;
std::unique_ptr<funcExpr_i> right;
public:
functionExpr(const VARIANT*);
functionExpr(const VBCallbackStruct&);
~functionExpr();
VARIANT* eval(VARIANT*, VARIANT*, int left_right = 0);
bool isValid() const;
};
<|endoftext|> |
<commit_before>/*
* Software License Agreement (BSD License)
*
* Copyright (c) 2010, Willow Garage, Inc.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above
* copyright notice, this list of conditions and the following
* disclaimer in the documentation and/or other materials provided
* with the distribution.
* * Neither the name of Willow Garage, Inc. nor the names of its
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
* ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*
*
*/
//////////////////////////////////////////////////////////////////////////////////////////////
template <typename PointT> void
pcl::transformPointCloud (const pcl::PointCloud<PointT> &cloud_in,
pcl::PointCloud<PointT> &cloud_out,
const Eigen::Affine3f &transform)
{
// In order to transform the data, we need to remove NaNs
cloud_out.is_dense = true;
if (&cloud_in != &cloud_out)
{
// Note: could be replaced by cloud_out = cloud_in
cloud_out.header = cloud_in.header;
cloud_out.width = cloud_in.width;
cloud_out.height = cloud_in.height;
cloud_out.points.reserve (cloud_out.points.size ());
cloud_out.points.assign (cloud_in.points.begin (), cloud_in.points.end ());
}
if (cloud_in.is_dense)
{
// If the dataset is dense, simply transform it!
for (size_t i = 0; i < cloud_out.points.size (); ++i)
cloud_out.points[i].getVector3fMap () = transform *
cloud_in.points[i].getVector3fMap ();
}
else
{
// Dataset might contain NaNs and Infs, so check for them first,
// otherwise we get errors during the multiplication (?)
for (size_t i = 0; i < cloud_out.points.size (); ++i)
{
if (!pcl_isfinite (cloud_in.points[i].x) ||
!pcl_isfinite (cloud_in.points[i].y) ||
!pcl_isfinite (cloud_in.points[i].z))
continue;
cloud_out.points[i].getVector3fMap () = transform *
cloud_in.points[i].getVector3fMap ();
}
}
}
//////////////////////////////////////////////////////////////////////////////////////////////
template <typename PointT> void
pcl::transformPointCloud (const pcl::PointCloud<PointT> &cloud_in,
const std::vector<int> &indices,
pcl::PointCloud<PointT> &cloud_out,
const Eigen::Affine3f &transform)
{
size_t npts = indices.size ();
// In order to transform the data, we need to remove NaNs
cloud_out.is_dense = true;
cloud_out.header = cloud_in.header;
cloud_out.width = npts;
cloud_out.height = 1;
cloud_out.points.resize (npts);
if (cloud_in.is_dense)
{
// If the dataset is dense, simply transform it!
for (size_t i = 0; i < npts; ++i)
cloud_out.points[i].getVector3fMap () = transform *
cloud_in.points[indices[i]].getVector3fMap ();
}
else
{
// Dataset might contain NaNs and Infs, so check for them first,
// otherwise we get errors during the multiplication (?)
for (size_t i = 0; i < npts; ++i)
{
if (!pcl_isfinite (cloud_in.points[indices[i]].x) ||
!pcl_isfinite (cloud_in.points[indices[i]].y) ||
!pcl_isfinite (cloud_in.points[indices[i]].z))
continue;
cloud_out.points[i].getVector3fMap () = transform *
cloud_in.points[indices[i]].getVector3fMap ();
}
}
}
//////////////////////////////////////////////////////////////////////////////////////////////
template <typename PointT> void
pcl::transformPointCloudWithNormals (const pcl::PointCloud<PointT> &cloud_in,
pcl::PointCloud<PointT> &cloud_out,
const Eigen::Affine3f &transform)
{
if (&cloud_in != &cloud_out)
{
// Note: could be replaced by cloud_out = cloud_in
cloud_out.header = cloud_in.header;
cloud_out.width = cloud_in.width;
cloud_out.height = cloud_in.height;
cloud_out.is_dense = cloud_in.is_dense;
cloud_out.points.reserve (cloud_out.points.size ());
cloud_out.points.assign (cloud_in.points.begin (), cloud_in.points.end ());
}
// If the data is dense, we don't need to check for NaN
if (cloud_in.is_dense)
{
for (size_t i = 0; i < cloud_out.points.size (); ++i)
{
cloud_out.points[i].getVector3fMap() = transform *
cloud_in.points[i].getVector3fMap ();
// Rotate normals
cloud_out.points[i].getNormalVector3fMap() = transform.rotation () *
cloud_in.points[i].getNormalVector3fMap ();
}
}
// Dataset might contain NaNs and Infs, so check for them first.
else
{
for (size_t i = 0; i < cloud_out.points.size (); ++i)
{
if (!pcl_isfinite (cloud_in.points[i].x) ||
!pcl_isfinite (cloud_in.points[i].y) ||
!pcl_isfinite (cloud_in.points[i].z))
continue;
cloud_out.points[i].getVector3fMap() = transform *
cloud_in.points[i].getVector3fMap ();
// Rotate normals
cloud_out.points[i].getNormalVector3fMap() = transform.rotation () *
cloud_in.points[i].getNormalVector3fMap ();
}
}
}
//////////////////////////////////////////////////////////////////////////////////////////////
template <typename PointT> void
pcl::transformPointCloud (const pcl::PointCloud<PointT> &cloud_in,
pcl::PointCloud<PointT> &cloud_out,
const Eigen::Matrix4f &transform)
{
if (&cloud_in != &cloud_out)
{
// Note: could be replaced by cloud_out = cloud_in
cloud_out.header = cloud_in.header;
cloud_out.width = cloud_in.width;
cloud_out.height = cloud_in.height;
cloud_out.is_dense = cloud_in.is_dense;
cloud_out.points.reserve (cloud_out.points.size ());
cloud_out.points.assign (cloud_in.points.begin (), cloud_in.points.end ());
}
Eigen::Matrix3f rot = transform.block<3, 3> (0, 0);
Eigen::Vector3f trans = transform.block<3, 1> (0, 3);
// If the data is dense, we don't need to check for NaN
if (cloud_in.is_dense)
{
for (size_t i = 0; i < cloud_out.points.size (); ++i)
cloud_out.points[i].getVector3fMap () = rot *
cloud_in.points[i].getVector3fMap () + trans;
}
// Dataset might contain NaNs and Infs, so check for them first.
else
{
for (size_t i = 0; i < cloud_out.points.size (); ++i)
{
if (!pcl_isfinite (cloud_in.points[i].x) ||
!pcl_isfinite (cloud_in.points[i].y) ||
!pcl_isfinite (cloud_in.points[i].z))
continue;
cloud_out.points[i].getVector3fMap () = rot *
cloud_in.points[i].getVector3fMap () + trans;
}
}
}
//////////////////////////////////////////////////////////////////////////////////////////////
template <typename PointT> void
pcl::transformPointCloudWithNormals (const pcl::PointCloud<PointT> &cloud_in,
pcl::PointCloud<PointT> &cloud_out,
const Eigen::Matrix4f &transform)
{
if (&cloud_in != &cloud_out)
{
// Note: could be replaced by cloud_out = cloud_in
cloud_out.header = cloud_in.header;
cloud_out.width = cloud_in.width;
cloud_out.height = cloud_in.height;
cloud_out.is_dense = cloud_in.is_dense;
cloud_out.points.reserve (cloud_out.points.size ());
cloud_out.points.assign (cloud_in.points.begin (), cloud_in.points.end ());
}
Eigen::Matrix3f rot = transform.block<3, 3> (0, 0);
Eigen::Vector3f trans = transform.block<3, 1> (0, 3);
// If the data is dense, we don't need to check for NaN
if (cloud_in.is_dense)
{
for (size_t i = 0; i < cloud_out.points.size (); ++i)
{
cloud_out.points[i].getVector3fMap () = rot *
cloud_in.points[i].getVector3fMap () + trans;
// Rotate normals
cloud_out.points[i].getNormalVector3fMap() = rot *
cloud_in.points[i].getNormalVector3fMap ();
}
}
// Dataset might contain NaNs and Infs, so check for them first.
else
{
for (size_t i = 0; i < cloud_out.points.size (); ++i)
{
if (!pcl_isfinite (cloud_in.points[i].x) ||
!pcl_isfinite (cloud_in.points[i].y) ||
!pcl_isfinite (cloud_in.points[i].z))
continue;
cloud_out.points[i].getVector3fMap () = rot *
cloud_in.points[i].getVector3fMap () + trans;
// Rotate normals
cloud_out.points[i].getNormalVector3fMap() = rot *
cloud_in.points[i].getNormalVector3fMap ();
}
}
}
//////////////////////////////////////////////////////////////////////////////////////////////
template <typename PointT> inline void
pcl::transformPointCloud (const pcl::PointCloud<PointT> &cloud_in,
pcl::PointCloud<PointT> &cloud_out,
const Eigen::Vector3f &offset,
const Eigen::Quaternionf &rotation)
{
Eigen::Translation3f translation (offset);
// Assemble an Eigen Transform
Eigen::Affine3f t;
t = translation * rotation;
transformPointCloud (cloud_in, cloud_out, t);
}
//////////////////////////////////////////////////////////////////////////////////////////////
template <typename PointT> inline void
pcl::transformPointCloudWithNormals (const pcl::PointCloud<PointT> &cloud_in,
pcl::PointCloud<PointT> &cloud_out,
const Eigen::Vector3f &offset,
const Eigen::Quaternionf &rotation)
{
Eigen::Translation3f translation (offset);
// Assemble an Eigen Transform
Eigen::Affine3f t;
t = translation * rotation;
transformPointCloudWithNormals (cloud_in, cloud_out, t);
}
<commit_msg>is_dense fix for transformPointCloud (thanks Aitor)<commit_after>/*
* Software License Agreement (BSD License)
*
* Copyright (c) 2010, Willow Garage, Inc.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above
* copyright notice, this list of conditions and the following
* disclaimer in the documentation and/or other materials provided
* with the distribution.
* * Neither the name of Willow Garage, Inc. nor the names of its
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
* ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*
*
*/
//////////////////////////////////////////////////////////////////////////////////////////////
template <typename PointT> void
pcl::transformPointCloud (const pcl::PointCloud<PointT> &cloud_in,
pcl::PointCloud<PointT> &cloud_out,
const Eigen::Affine3f &transform)
{
if (&cloud_in != &cloud_out)
{
// Note: could be replaced by cloud_out = cloud_in
cloud_out.header = cloud_in.header;
cloud_out.is_dense = cloud_in.is_dense;
cloud_out.width = cloud_in.width;
cloud_out.height = cloud_in.height;
cloud_out.points.reserve (cloud_out.points.size ());
cloud_out.points.assign (cloud_in.points.begin (), cloud_in.points.end ());
}
if (cloud_in.is_dense)
{
// If the dataset is dense, simply transform it!
for (size_t i = 0; i < cloud_out.points.size (); ++i)
cloud_out.points[i].getVector3fMap () = transform *
cloud_in.points[i].getVector3fMap ();
}
else
{
// Dataset might contain NaNs and Infs, so check for them first,
// otherwise we get errors during the multiplication (?)
for (size_t i = 0; i < cloud_out.points.size (); ++i)
{
if (!pcl_isfinite (cloud_in.points[i].x) ||
!pcl_isfinite (cloud_in.points[i].y) ||
!pcl_isfinite (cloud_in.points[i].z))
continue;
cloud_out.points[i].getVector3fMap () = transform *
cloud_in.points[i].getVector3fMap ();
}
}
}
//////////////////////////////////////////////////////////////////////////////////////////////
template <typename PointT> void
pcl::transformPointCloud (const pcl::PointCloud<PointT> &cloud_in,
const std::vector<int> &indices,
pcl::PointCloud<PointT> &cloud_out,
const Eigen::Affine3f &transform)
{
size_t npts = indices.size ();
// In order to transform the data, we need to remove NaNs
cloud_out.is_dense = cloud_in.is_dense;
cloud_out.header = cloud_in.header;
cloud_out.width = npts;
cloud_out.height = 1;
cloud_out.points.resize (npts);
if (cloud_in.is_dense)
{
// If the dataset is dense, simply transform it!
for (size_t i = 0; i < npts; ++i)
cloud_out.points[i].getVector3fMap () = transform *
cloud_in.points[indices[i]].getVector3fMap ();
}
else
{
// Dataset might contain NaNs and Infs, so check for them first,
// otherwise we get errors during the multiplication (?)
for (size_t i = 0; i < npts; ++i)
{
if (!pcl_isfinite (cloud_in.points[indices[i]].x) ||
!pcl_isfinite (cloud_in.points[indices[i]].y) ||
!pcl_isfinite (cloud_in.points[indices[i]].z))
continue;
cloud_out.points[i].getVector3fMap () = transform *
cloud_in.points[indices[i]].getVector3fMap ();
}
}
}
//////////////////////////////////////////////////////////////////////////////////////////////
template <typename PointT> void
pcl::transformPointCloudWithNormals (const pcl::PointCloud<PointT> &cloud_in,
pcl::PointCloud<PointT> &cloud_out,
const Eigen::Affine3f &transform)
{
if (&cloud_in != &cloud_out)
{
// Note: could be replaced by cloud_out = cloud_in
cloud_out.header = cloud_in.header;
cloud_out.width = cloud_in.width;
cloud_out.height = cloud_in.height;
cloud_out.is_dense = cloud_in.is_dense;
cloud_out.points.reserve (cloud_out.points.size ());
cloud_out.points.assign (cloud_in.points.begin (), cloud_in.points.end ());
}
// If the data is dense, we don't need to check for NaN
if (cloud_in.is_dense)
{
for (size_t i = 0; i < cloud_out.points.size (); ++i)
{
cloud_out.points[i].getVector3fMap() = transform *
cloud_in.points[i].getVector3fMap ();
// Rotate normals
cloud_out.points[i].getNormalVector3fMap() = transform.rotation () *
cloud_in.points[i].getNormalVector3fMap ();
}
}
// Dataset might contain NaNs and Infs, so check for them first.
else
{
for (size_t i = 0; i < cloud_out.points.size (); ++i)
{
if (!pcl_isfinite (cloud_in.points[i].x) ||
!pcl_isfinite (cloud_in.points[i].y) ||
!pcl_isfinite (cloud_in.points[i].z))
continue;
cloud_out.points[i].getVector3fMap() = transform *
cloud_in.points[i].getVector3fMap ();
// Rotate normals
cloud_out.points[i].getNormalVector3fMap() = transform.rotation () *
cloud_in.points[i].getNormalVector3fMap ();
}
}
}
//////////////////////////////////////////////////////////////////////////////////////////////
template <typename PointT> void
pcl::transformPointCloud (const pcl::PointCloud<PointT> &cloud_in,
pcl::PointCloud<PointT> &cloud_out,
const Eigen::Matrix4f &transform)
{
if (&cloud_in != &cloud_out)
{
// Note: could be replaced by cloud_out = cloud_in
cloud_out.header = cloud_in.header;
cloud_out.width = cloud_in.width;
cloud_out.height = cloud_in.height;
cloud_out.is_dense = cloud_in.is_dense;
cloud_out.points.reserve (cloud_out.points.size ());
cloud_out.points.assign (cloud_in.points.begin (), cloud_in.points.end ());
}
Eigen::Matrix3f rot = transform.block<3, 3> (0, 0);
Eigen::Vector3f trans = transform.block<3, 1> (0, 3);
// If the data is dense, we don't need to check for NaN
if (cloud_in.is_dense)
{
for (size_t i = 0; i < cloud_out.points.size (); ++i)
cloud_out.points[i].getVector3fMap () = rot *
cloud_in.points[i].getVector3fMap () + trans;
}
// Dataset might contain NaNs and Infs, so check for them first.
else
{
for (size_t i = 0; i < cloud_out.points.size (); ++i)
{
if (!pcl_isfinite (cloud_in.points[i].x) ||
!pcl_isfinite (cloud_in.points[i].y) ||
!pcl_isfinite (cloud_in.points[i].z))
continue;
cloud_out.points[i].getVector3fMap () = rot *
cloud_in.points[i].getVector3fMap () + trans;
}
}
}
//////////////////////////////////////////////////////////////////////////////////////////////
template <typename PointT> void
pcl::transformPointCloudWithNormals (const pcl::PointCloud<PointT> &cloud_in,
pcl::PointCloud<PointT> &cloud_out,
const Eigen::Matrix4f &transform)
{
if (&cloud_in != &cloud_out)
{
// Note: could be replaced by cloud_out = cloud_in
cloud_out.header = cloud_in.header;
cloud_out.width = cloud_in.width;
cloud_out.height = cloud_in.height;
cloud_out.is_dense = cloud_in.is_dense;
cloud_out.points.reserve (cloud_out.points.size ());
cloud_out.points.assign (cloud_in.points.begin (), cloud_in.points.end ());
}
Eigen::Matrix3f rot = transform.block<3, 3> (0, 0);
Eigen::Vector3f trans = transform.block<3, 1> (0, 3);
// If the data is dense, we don't need to check for NaN
if (cloud_in.is_dense)
{
for (size_t i = 0; i < cloud_out.points.size (); ++i)
{
cloud_out.points[i].getVector3fMap () = rot *
cloud_in.points[i].getVector3fMap () + trans;
// Rotate normals
cloud_out.points[i].getNormalVector3fMap() = rot *
cloud_in.points[i].getNormalVector3fMap ();
}
}
// Dataset might contain NaNs and Infs, so check for them first.
else
{
for (size_t i = 0; i < cloud_out.points.size (); ++i)
{
if (!pcl_isfinite (cloud_in.points[i].x) ||
!pcl_isfinite (cloud_in.points[i].y) ||
!pcl_isfinite (cloud_in.points[i].z))
continue;
cloud_out.points[i].getVector3fMap () = rot *
cloud_in.points[i].getVector3fMap () + trans;
// Rotate normals
cloud_out.points[i].getNormalVector3fMap() = rot *
cloud_in.points[i].getNormalVector3fMap ();
}
}
}
//////////////////////////////////////////////////////////////////////////////////////////////
template <typename PointT> inline void
pcl::transformPointCloud (const pcl::PointCloud<PointT> &cloud_in,
pcl::PointCloud<PointT> &cloud_out,
const Eigen::Vector3f &offset,
const Eigen::Quaternionf &rotation)
{
Eigen::Translation3f translation (offset);
// Assemble an Eigen Transform
Eigen::Affine3f t;
t = translation * rotation;
transformPointCloud (cloud_in, cloud_out, t);
}
//////////////////////////////////////////////////////////////////////////////////////////////
template <typename PointT> inline void
pcl::transformPointCloudWithNormals (const pcl::PointCloud<PointT> &cloud_in,
pcl::PointCloud<PointT> &cloud_out,
const Eigen::Vector3f &offset,
const Eigen::Quaternionf &rotation)
{
Eigen::Translation3f translation (offset);
// Assemble an Eigen Transform
Eigen::Affine3f t;
t = translation * rotation;
transformPointCloudWithNormals (cloud_in, cloud_out, t);
}
<|endoftext|> |
<commit_before>#include "gameloop.hpp"
#include "input.hpp"
#include "font.hpp"
#include "spinner/frac.hpp"
#include "camera.hpp"
#include "updator.hpp"
#include "scene.hpp"
#include "sound.hpp"
#include <sstream>
#include <boost/archive/binary_oarchive.hpp>
#include <boost/archive/binary_iarchive.hpp>
#include "serialization/smart_ptr.hpp"
#include "serialization/chrono.hpp"
#include "serialization/chars.hpp"
namespace rs {
// --------------------- DrawThread ---------------------
void DrawThread::runL(const SPLooper& mainLooper, SPGLContext ctx_b, const SPWindow& w, const UPMainProc& mp) {
Handler drawHandler(mainLooper);
drawHandler.postArgs(msg::DrawInit());
SPGLContext ctx(std::move(ctx_b));
ctx->makeCurrent(w);
LoadGLFunc();
mgr_gl.onDeviceReset();
UPDrawProc up(mp->initDraw());
bool bLoop = true;
do {
// メインスレッドから描画開始の指示が来るまで待機
while(auto m = getLooper()->wait()) {
if(msg::DrawReq* p = *m) {
_info.lock()->state = State::Drawing;
// 1フレーム分の描画処理
if(up->runU(p->id))
ctx->swapWindow();
glFinish();
{
auto lk = _info.lock();
lk->state = State::Idle;
lk->accum = p->id;
}
}
if(msg::QuitReq* q = *m)
bLoop = false;
// AndroidではContextSharingが出来ないのでメインスレッドからロードするタスクを受け取ってここで処理
}
} while(bLoop && !isInterrupted());
std::cout << "DrawThread End" << std::endl;
}
// --------------------- MainThread ---------------------
MainThread::MainThread(MPCreate mcr): _mcr(mcr) {
auto lk = _info.lock();
lk->accumUpd = lk->accumDraw = 0;
lk->tmBegin = Clock::now();
lk->fps = 0;
}
void MainThread::runL(const SPLooper& guiLooper, const SPWindow& w, const char* apppath) {
SPGLContext ctx = GLContext::CreateContext(w, false),
ctxD = GLContext::CreateContext(w, true);
ctxD->makeCurrent();
ctx->makeCurrent(w);
GLRes glrP;
RWMgr rwP;
AppPath appPath(apppath);
std::string pathlist("pathlist_");
pathlist += TOOL_PREFIX;
appPath.setFromText(mgr_rw.fromFile(pathlist.c_str(), RWops::Read, false));
FontFamily fontP;
fontP.loadFamilyWildCard(mgr_path.getPath(AppPath::Type::Font).plain_utf8());
FontGen fgenP(spn::PowSize(512,512));
CameraMgr camP;
InputMgr inpP;
ObjMgr objP;
UpdMgr updP;
SceneMgr scP;
std::unique_ptr<SoundMgr> sndP(new SoundMgr(44100));
sndP->makeCurrent();
UPMainProc mp(_mcr(w));
Handler guiHandler(guiLooper, [](){
SDL_Event e;
e.type = EVID_SIGNAL;
SDL_PushEvent(&e);
});
DrawThread dth;
dth.start(std::ref(getLooper()), std::move(ctxD), w, mp);
// 描画スレッドの初期化完了を待つ
while(auto m = getLooper()->wait()) {
if(msg::DrawInit* p = *m)
break;
}
Handler drawHandler(dth.getLooper());
guiHandler.postArgs(msg::MainInit());
const spn::FracI fracInterval(50000, 3);
spn::FracI frac(0,1);
Timepoint prevtime = Clock::now();
int skip = 0;
constexpr int MAX_SKIPFRAME = 3;
constexpr int DRAW_THRESHOLD_USEC = 2000;
using namespace std::chrono;
// ゲームの進行や更新タイミングを図って描画など
bool bLoop = true;
do {
if(!dth.isRunning()) {
// 何らかの原因で描画スレッドが終了していた時
try {
// 例外が投げられて終了したかをチェック
dth.getResult();
} catch (...) {
guiHandler.postArgs(msg::QuitReq());
Assert(Warn, false, "MainThread: draw thread was ended by throwing exception")
throw;
}
Assert(Warn, false, "MainThread: draw thread was ended unexpectedly")
break;
}
// 何かメッセージが来てたら処理する
while(OPMessage m = getLooper()->peek(std::chrono::seconds(0))) {
if(msg::PauseReq* pr = *m) {
mgr_sound.pauseAllSound();
// ユーザーに通知(Pause)
mp->onPause();
std::stringstream buffer; // サウンドデバイスデータ
for(;;) {
// DrawThreadがIdleになるまで待つ
while(dth.getInfo()->accum != getInfo()->accumDraw)
SDL_Delay(0);
// Resumeメッセージが来るまでwaitループ
OPMessage m = getLooper()->wait();
if(msg::ResumeReq* rr = *m) {
mgr_sound.resumeAllSound();
// ユーザーに通知(Resume)
mp->onResume();
break;
} else if(msg::StopReq* sr = *m) {
mp->onStop();
// OpenGLリソースの解放
mgr_gl.onDeviceLost();
glFlush();
// サウンドデバイスのバックアップ
boost::archive::binary_oarchive oa(buffer);
oa << mgr_rw;
mgr_rw.resetSerializeFlag();
SoundMgr* sp = sndP.get();
oa << sp;
sp->resetSerializeFlag();
// サウンドを一旦全部停止させておく -> 復元した時に以前再生していたものは処理が継続される
sndP.reset(nullptr);
}
else if(msg::ReStartReq* rr = *m) {
// サウンドデバイスの復元
boost::archive::binary_iarchive ia(buffer);
ia >> mgr_rw;
SoundMgr* sp = nullptr;
ia >> sp;
sndP.reset(sp);
sndP->makeCurrent();
std::cout << "------------";
sndP->update();
// OpenGLリソースの再確保
mgr_gl.onDeviceReset();
glFlush();
mp->onReStart();
}
}
}
}
// 次のフレーム開始を待つ
auto ntp = prevtime + microseconds(16666);
auto tp = Clock::now();
if(ntp <= tp)
ntp = tp;
else {
auto dur = ntp - tp;
if(dur >= microseconds(1000)) {
// 時間に余裕があるならスリープをかける
SDLEC_P(Warn, SDL_Delay, duration_cast<milliseconds>(dur).count() - 1);
}
// スピンウェイト
while(Clock::now() < ntp);
}
prevtime = ntp;
// ゲーム進行
++getInfo()->accumUpd;
mgr_input.update();
if(!mp->runU()) {
std::cout << "MainLoop END" << std::endl;
break;
}
// 時間が残っていれば描画
// 最大スキップフレームを超過してたら必ず描画
auto dur = Clock::now() - tp;
if(skip >= MAX_SKIPFRAME || dur > microseconds(DRAW_THRESHOLD_USEC)) {
skip = 0;
drawHandler.postArgs(msg::DrawReq(++getInfo()->accumDraw));
} else
++skip;
} while(bLoop && !isInterrupted());
while(mgr_scene.getTop().valid()) {
mgr_scene.setPopScene(1);
mgr_scene.onUpdate();
}
// 描画スレッドの終了を待つ
dth.interrupt();
drawHandler.postArgs(msg::QuitReq());
dth.join();
guiHandler.postArgs(msg::QuitReq());
}
void GameLoop::_procWindowEvent(SDL_Event& e) {
switch(e.window.event) {
case SDL_WINDOWEVENT_CLOSE:
// ウィンドウ閉じたら終了
e.type = SDL_QUIT;
e.quit.timestamp = 0;
SDL_PushEvent(&e);
break;
case SDL_WINDOWEVENT_MINIMIZED:
_setLevel(std::min(_level, Stop));
break;
case SDL_WINDOWEVENT_RESTORED:
_setLevel(std::max(_level, Pause));
break;
case SDL_WINDOWEVENT_FOCUS_GAINED:
_setLevel(std::max(_level, Active));
break;
case SDL_WINDOWEVENT_FOCUS_LOST:
_setLevel(std::min(_level, Pause));
break;
default: break;
}
}
// それぞれユーザースレッドに通知
void GameLoop::_onPause() {
_handler->postArgs(msg::PauseReq());
}
void GameLoop::_onResume() {
_handler->postArgs(msg::ResumeReq());
}
void GameLoop::_onStop() {
_handler->postArgs(msg::StopReq());
}
void GameLoop::_onReStart() {
_handler->postArgs(msg::ReStartReq());
}
void GameLoop::_setLevel(Level level) {
int ilevel = level,
curLevel = _level;
int idx = ilevel > curLevel ? 0 : 1,
inc = ilevel > curLevel ? 1 : -1;
while(ilevel != curLevel) {
if(LFunc f = cs_lfunc[curLevel][idx])
(this->*f)();
curLevel += inc;
}
_level = level;
}
const GameLoop::LFunc GameLoop::cs_lfunc[NumLevel][2] = {
{&GameLoop::_onReStart, nullptr},
{&GameLoop::_onResume, &GameLoop::_onStop},
{nullptr, &GameLoop::_onPause}
};
const uint32_t EVID_SIGNAL = SDL_RegisterEvents(1);
GameLoop::GameLoop(MPCreate mcr): _mcr(mcr), _level(Active) {}
int GameLoop::run(const char* apppath, spn::To8Str title, int w, int h, uint32_t flag, int major, int minor, int depth) {
SDLInitializer sdlI(SDL_INIT_VIDEO | SDL_INIT_EVENTS | SDL_INIT_JOYSTICK | SDL_INIT_TIMER);
Window::SetStdGLAttributes(major, minor, depth);
SPWindow _spWindow = Window::Create(title.moveTo(), w, h, flag);
rs::SDLMouse::SetWindow(_spWindow->getWindow());
// メインスレッドのメッセージキューを初期化
Looper::Prepare();
auto& loop = Looper::GetLooper();
// メインスレッドに渡す
MainThread mth(_mcr);
mth.start(std::ref(loop), std::ref(_spWindow), apppath);
// メインスレッドのキューが準備出来るのを待つ
while(auto msg = loop->wait()) {
if(msg::MainInit* p = *msg)
break;
}
_handler = Handler(mth.getLooper());
// GUIスレッドのメッセージループ
SDL_Event e;
bool bLoop = true;
while(bLoop && mth.isRunning() && SDL_WaitEvent(&e)) {
if(e.type == EVID_SIGNAL) {
// 自作スレッドのキューにメッセージがある
while(OPMessage m = loop->peek(std::chrono::seconds(0))) {
if(msg::QuitReq* p = *m) {
e.type = SDL_QUIT;
e.quit.timestamp = 0;
SDL_PushEvent(&e);
}
}
} else {
PrintEvent::All(e);
// 当分はGame_Sleep()でリソース解放、Game_Wakeup()でリソース復帰とする
// (onStop()やonStart()は関知しない)
switch(e.type) {
case SDL_WINDOWEVENT:
_procWindowEvent(e); break;
case SDL_QUIT:
// アプリケーション終了コールが来たらループを抜ける
bLoop = false;
break;
case SDL_APP_TERMINATING: // Android: onDestroy()
break;
case SDL_APP_LOWMEMORY: // Android: onLowMemory()
break;
case SDL_APP_WILLENTERBACKGROUND: // Android: onPause()
case SDL_APP_DIDENTERBACKGROUND: // Android: onPause()
_setLevel(std::min(_level, Stop));
break;
case SDL_APP_WILLENTERFOREGROUND: // Android: onResume()
case SDL_APP_DIDENTERFOREGROUND: // Android: onResume()
_setLevel(std::max(_level, Active));
break;
}
}
}
mth.interrupt();
try {
// 例外が投げられて終了したかをチェック
mth.getResult();
} catch (...) {
Assert(Warn, false, "GuiThread: main thread was ended by throwing exception")
}
return 0;
}
}
<commit_msg>VSyncをoffにして置かないと環境によっては30fpsになってしまう問題の修正<commit_after>#include "gameloop.hpp"
#include "input.hpp"
#include "font.hpp"
#include "spinner/frac.hpp"
#include "camera.hpp"
#include "updator.hpp"
#include "scene.hpp"
#include "sound.hpp"
#include <sstream>
#include <boost/archive/binary_oarchive.hpp>
#include <boost/archive/binary_iarchive.hpp>
#include "serialization/smart_ptr.hpp"
#include "serialization/chrono.hpp"
#include "serialization/chars.hpp"
namespace rs {
// --------------------- DrawThread ---------------------
void DrawThread::runL(const SPLooper& mainLooper, SPGLContext ctx_b, const SPWindow& w, const UPMainProc& mp) {
Handler drawHandler(mainLooper);
drawHandler.postArgs(msg::DrawInit());
SPGLContext ctx(std::move(ctx_b));
ctx->makeCurrent(w);
LoadGLFunc();
mgr_gl.onDeviceReset();
SetSwapInterval(0);
UPDrawProc up(mp->initDraw());
bool bLoop = true;
do {
// メインスレッドから描画開始の指示が来るまで待機
while(auto m = getLooper()->wait()) {
SetSwapInterval(0);
if(msg::DrawReq* p = *m) {
_info.lock()->state = State::Drawing;
// 1フレーム分の描画処理
if(up->runU(p->id))
ctx->swapWindow();
glFinish();
{
auto lk = _info.lock();
lk->state = State::Idle;
lk->accum = p->id;
}
}
if(msg::QuitReq* q = *m)
bLoop = false;
// AndroidではContextSharingが出来ないのでメインスレッドからロードするタスクを受け取ってここで処理
}
} while(bLoop && !isInterrupted());
std::cout << "DrawThread End" << std::endl;
}
// --------------------- MainThread ---------------------
MainThread::MainThread(MPCreate mcr): _mcr(mcr) {
auto lk = _info.lock();
lk->accumUpd = lk->accumDraw = 0;
lk->tmBegin = Clock::now();
lk->fps = 0;
}
void MainThread::runL(const SPLooper& guiLooper, const SPWindow& w, const char* apppath) {
SPGLContext ctx = GLContext::CreateContext(w, false),
ctxD = GLContext::CreateContext(w, true);
ctxD->makeCurrent();
ctx->makeCurrent(w);
GLRes glrP;
RWMgr rwP;
AppPath appPath(apppath);
std::string pathlist("pathlist_");
pathlist += TOOL_PREFIX;
appPath.setFromText(mgr_rw.fromFile(pathlist.c_str(), RWops::Read, false));
FontFamily fontP;
fontP.loadFamilyWildCard(mgr_path.getPath(AppPath::Type::Font).plain_utf8());
FontGen fgenP(spn::PowSize(512,512));
CameraMgr camP;
InputMgr inpP;
ObjMgr objP;
UpdMgr updP;
SceneMgr scP;
std::unique_ptr<SoundMgr> sndP(new SoundMgr(44100));
sndP->makeCurrent();
UPMainProc mp(_mcr(w));
Handler guiHandler(guiLooper, [](){
SDL_Event e;
e.type = EVID_SIGNAL;
SDL_PushEvent(&e);
});
DrawThread dth;
dth.start(std::ref(getLooper()), std::move(ctxD), w, mp);
// 描画スレッドの初期化完了を待つ
while(auto m = getLooper()->wait()) {
if(msg::DrawInit* p = *m)
break;
}
Handler drawHandler(dth.getLooper());
guiHandler.postArgs(msg::MainInit());
const spn::FracI fracInterval(50000, 3);
spn::FracI frac(0,1);
Timepoint prevtime = Clock::now();
int skip = 0;
constexpr int MAX_SKIPFRAME = 3;
constexpr int DRAW_THRESHOLD_USEC = 2000;
using namespace std::chrono;
// ゲームの進行や更新タイミングを図って描画など
bool bLoop = true;
do {
if(!dth.isRunning()) {
// 何らかの原因で描画スレッドが終了していた時
try {
// 例外が投げられて終了したかをチェック
dth.getResult();
} catch (...) {
guiHandler.postArgs(msg::QuitReq());
Assert(Warn, false, "MainThread: draw thread was ended by throwing exception")
throw;
}
Assert(Warn, false, "MainThread: draw thread was ended unexpectedly")
break;
}
// 何かメッセージが来てたら処理する
while(OPMessage m = getLooper()->peek(std::chrono::seconds(0))) {
if(msg::PauseReq* pr = *m) {
mgr_sound.pauseAllSound();
// ユーザーに通知(Pause)
mp->onPause();
std::stringstream buffer; // サウンドデバイスデータ
for(;;) {
// DrawThreadがIdleになるまで待つ
while(dth.getInfo()->accum != getInfo()->accumDraw)
SDL_Delay(0);
// Resumeメッセージが来るまでwaitループ
OPMessage m = getLooper()->wait();
if(msg::ResumeReq* rr = *m) {
mgr_sound.resumeAllSound();
// ユーザーに通知(Resume)
mp->onResume();
break;
} else if(msg::StopReq* sr = *m) {
mp->onStop();
// OpenGLリソースの解放
mgr_gl.onDeviceLost();
glFlush();
// サウンドデバイスのバックアップ
boost::archive::binary_oarchive oa(buffer);
oa << mgr_rw;
mgr_rw.resetSerializeFlag();
SoundMgr* sp = sndP.get();
oa << sp;
sp->resetSerializeFlag();
// サウンドを一旦全部停止させておく -> 復元した時に以前再生していたものは処理が継続される
sndP.reset(nullptr);
}
else if(msg::ReStartReq* rr = *m) {
// サウンドデバイスの復元
boost::archive::binary_iarchive ia(buffer);
ia >> mgr_rw;
SoundMgr* sp = nullptr;
ia >> sp;
sndP.reset(sp);
sndP->makeCurrent();
std::cout << "------------";
sndP->update();
// OpenGLリソースの再確保
mgr_gl.onDeviceReset();
glFlush();
mp->onReStart();
}
}
}
}
// 次のフレーム開始を待つ
auto ntp = prevtime + microseconds(16666);
auto tp = Clock::now();
if(ntp <= tp)
ntp = tp;
else {
auto dur = ntp - tp;
if(dur >= microseconds(1000)) {
// 時間に余裕があるならスリープをかける
SDLEC_P(Warn, SDL_Delay, duration_cast<milliseconds>(dur).count() - 1);
}
// スピンウェイト
while(Clock::now() < ntp);
}
prevtime = ntp;
// ゲーム進行
++getInfo()->accumUpd;
mgr_input.update();
if(!mp->runU()) {
std::cout << "MainLoop END" << std::endl;
break;
}
// TODO: ループ早すぎると描画キューにメッセージ溜まりすぎて死ぬ
// 時間が残っていれば描画
// 最大スキップフレームを超過してたら必ず描画
auto dur = Clock::now() - tp;
if(skip >= MAX_SKIPFRAME || dur > microseconds(DRAW_THRESHOLD_USEC)) {
skip = 0;
drawHandler.postArgs(msg::DrawReq(++getInfo()->accumDraw));
} else
++skip;
} while(bLoop && !isInterrupted());
while(mgr_scene.getTop().valid()) {
mgr_scene.setPopScene(1);
mgr_scene.onUpdate();
}
// 描画スレッドの終了を待つ
dth.interrupt();
drawHandler.postArgs(msg::QuitReq());
dth.join();
guiHandler.postArgs(msg::QuitReq());
}
void GameLoop::_procWindowEvent(SDL_Event& e) {
switch(e.window.event) {
case SDL_WINDOWEVENT_CLOSE:
// ウィンドウ閉じたら終了
e.type = SDL_QUIT;
e.quit.timestamp = 0;
SDL_PushEvent(&e);
break;
case SDL_WINDOWEVENT_MINIMIZED:
_setLevel(std::min(_level, Stop));
break;
case SDL_WINDOWEVENT_RESTORED:
_setLevel(std::max(_level, Pause));
break;
case SDL_WINDOWEVENT_FOCUS_GAINED:
_setLevel(std::max(_level, Active));
break;
case SDL_WINDOWEVENT_FOCUS_LOST:
_setLevel(std::min(_level, Pause));
break;
default: break;
}
}
// それぞれユーザースレッドに通知
void GameLoop::_onPause() {
_handler->postArgs(msg::PauseReq());
}
void GameLoop::_onResume() {
_handler->postArgs(msg::ResumeReq());
}
void GameLoop::_onStop() {
_handler->postArgs(msg::StopReq());
}
void GameLoop::_onReStart() {
_handler->postArgs(msg::ReStartReq());
}
void GameLoop::_setLevel(Level level) {
int ilevel = level,
curLevel = _level;
int idx = ilevel > curLevel ? 0 : 1,
inc = ilevel > curLevel ? 1 : -1;
while(ilevel != curLevel) {
if(LFunc f = cs_lfunc[curLevel][idx])
(this->*f)();
curLevel += inc;
}
_level = level;
}
const GameLoop::LFunc GameLoop::cs_lfunc[NumLevel][2] = {
{&GameLoop::_onReStart, nullptr},
{&GameLoop::_onResume, &GameLoop::_onStop},
{nullptr, &GameLoop::_onPause}
};
const uint32_t EVID_SIGNAL = SDL_RegisterEvents(1);
GameLoop::GameLoop(MPCreate mcr): _mcr(mcr), _level(Active) {}
int GameLoop::run(const char* apppath, spn::To8Str title, int w, int h, uint32_t flag, int major, int minor, int depth) {
SDLInitializer sdlI(SDL_INIT_VIDEO | SDL_INIT_EVENTS | SDL_INIT_JOYSTICK | SDL_INIT_TIMER);
Window::SetStdGLAttributes(major, minor, depth);
SPWindow _spWindow = Window::Create(title.moveTo(), w, h, flag);
rs::SDLMouse::SetWindow(_spWindow->getWindow());
// メインスレッドのメッセージキューを初期化
Looper::Prepare();
auto& loop = Looper::GetLooper();
// メインスレッドに渡す
MainThread mth(_mcr);
mth.start(std::ref(loop), std::ref(_spWindow), apppath);
// メインスレッドのキューが準備出来るのを待つ
while(auto msg = loop->wait()) {
if(msg::MainInit* p = *msg)
break;
}
_handler = Handler(mth.getLooper());
// GUIスレッドのメッセージループ
SDL_Event e;
bool bLoop = true;
while(bLoop && mth.isRunning() && SDL_WaitEvent(&e)) {
if(e.type == EVID_SIGNAL) {
// 自作スレッドのキューにメッセージがある
while(OPMessage m = loop->peek(std::chrono::seconds(0))) {
if(msg::QuitReq* p = *m) {
e.type = SDL_QUIT;
e.quit.timestamp = 0;
SDL_PushEvent(&e);
}
}
} else {
PrintEvent::All(e);
// 当分はGame_Sleep()でリソース解放、Game_Wakeup()でリソース復帰とする
// (onStop()やonStart()は関知しない)
switch(e.type) {
case SDL_WINDOWEVENT:
_procWindowEvent(e); break;
case SDL_QUIT:
// アプリケーション終了コールが来たらループを抜ける
bLoop = false;
break;
case SDL_APP_TERMINATING: // Android: onDestroy()
break;
case SDL_APP_LOWMEMORY: // Android: onLowMemory()
break;
case SDL_APP_WILLENTERBACKGROUND: // Android: onPause()
case SDL_APP_DIDENTERBACKGROUND: // Android: onPause()
_setLevel(std::min(_level, Stop));
break;
case SDL_APP_WILLENTERFOREGROUND: // Android: onResume()
case SDL_APP_DIDENTERFOREGROUND: // Android: onResume()
_setLevel(std::max(_level, Active));
break;
}
}
}
mth.interrupt();
try {
// 例外が投げられて終了したかをチェック
mth.getResult();
} catch (...) {
Assert(Warn, false, "GuiThread: main thread was ended by throwing exception")
}
return 0;
}
}
<|endoftext|> |
<commit_before>#include <bits/stdc++.h>
using namespace std;
const double EPS=1e-6;
int dcmp(double x)
{
if(fabs(x)<EPS) return 0;
else return x<0 ? -1:1;
}
struct Point
{
double x,y;
Point(){x=0,y=0;}
Point(int _x,int _y){x=_x;y=_y;}
Point operator +(const Point & b)
{
return Point(x+b.x,y+b.y);
}
Point operator - (const Point & b) const
{
return Point(x-b.x,y-b.y);
}
Point operator * (double p)
{
return Point(x*p,y*p);
}
Point operator / (double p)
{
return Point(x/p,y/p);
}
bool operator <(const Point & b)
{
return x<b.x || (x==b.x && y<b.y);
}
bool operator ==(const Point & b)
{
return dcmp(x-b.x)==0 && dcmp(y-b.y)==0;
}
};
typedef Point Vector;
double dot (Vector v1,Vector v2)
{
return v1.x*v2.x+v1.y*v2.y;
}
double cross(Point & o,Point & a, Point &b) //OA X OB
{
return (a.x-o.x)*(b.y-o.y)-(a.y-o.y)*(b.x-o.x);
}
double cross(Vector a,Vector b)
{
return a.x*b.y-a.y*b.x;
}
double length(Vector v)
{
return sqrt(v.x*v.x+v.y*v.y); //return sqrt(dot(v,v));
}
double angle (const Vector & a,const Vector & b)
{
return acos(dot(a,b)/length(a)/length(b));
}
double Triarea(const Point & p1,const Point & p2 ,const Point & p3)
{
return fabs(cross(p2-p1,p3-p1))/2;
}
Vector Rotate(const Vector & a,double rad) //radian 0~2pi //counterclockwise
{
return Vector(a.x*cos(rad)-a.y*sin(rad),a.x*sin(rad)+a.y*cos(rad)); //旋轉矩陣
}
Vector Normal(const Vector &a) //向量的單位法線
{
double L=length(a);
return Vector(-a.y/L,a.x/L);
}
struct Line
{
Point p1,p2;
};
typedef Line Segment;
Point GetLineIntersection (Point p,Vector v,Point q,Vector w) //點斜式交點 p+vt1 q+wt2
{
Vector u=p-q;
double t=cross(w,u)/cross(v,w); //t1
return p+v*t; //p+vt1
}
Point GetLineProjection (Point p,Point a,Point b)
{
Vector v=b-a;
return a+v*(dot(v,p-a)/dot(v,v));
}
typedef Line Segment;
bool Onsegment(Point p,Point a1,Point a2)//點在線上
{
//平行 //端點在兩側
return dcmp(cross(a1-p,a2-p))==0 && dcmp(dot(a1-p,a2-p))<0;
}
bool SegmentProperIntersection(Point a1,Point a2,Point b1,Point b2)
{
// 規範相交 :交點不能是線段的交點
double c1=cross(a2-a1,b1-a1) ,c2=cross(a2-a1,b2-a1);
double c3=cross(b2-b1,a1-b1),c4=cross(b2-b1,a2-b1);
return dcmp(c1)*dcmp(c2)<0 && dcmp(c3)* dcmp(c4)<0;
}
bool SegmentProperIntersection(Segment s1, Segment s2)
{
return SegmentProperIntersection(s1.p1,s1.p2,s2.p1,s2.p2);
}
bool SegmentInterSection(Point a1,Point a2,Point b1,Point b2) //非規範相交
{
//端點相交
if(Onsegment(a1,b1,b2)|| Onsegment (a2,b1,b2) || Onsegment (b1,a1,a2) || Onsegment (b2,a1,a2)) return true;
if(SegmentProperIntersection(a1,a2,b1,b2)) return true; //規範相交
return false;
}
bool SegmentInterSection(Line & l1 ,Line & l2)
{
return SegmentInterSection(l1.p1,l1.p2,l2.p1,l2.p2);
}
double distance (Point & a,Point & b)
{
return sqrt(length(b-a));
}
double distance (Point &p,Point & p1, Point & p2)//Line => p1,p2
{
Vector v1=p-p1,v2=p2-p1;
return fabs(cross(v1,v2))/length(v2); //面積/底=高(距離)
}
double distance (Point &p ,Segment & s) //Point to Segment
{
Vector v=s.p2-s.p1;
if(dcmp(length(v))==0) return length(p-s.p1); //線段退化成點
Vector v1=p-s.p1;
Vector v2=p-s.p2;
if(dcmp(dot(v1,v))<0)return length(v1); // 點投影不在線上
if(dcmp(dot(v2,v))>0) return length(v2);// 點投影不在線上
return fabs(cross(v,v1))/length(v);
}
double distance(Segment & s1 , Segment & s2) //線段到線段
{
if(SegmentInterSection(s1,s2)) return 0;
double d =1e9;
d=min(d,distance(s1.p1,s2)); //點到線段距離取最短
d=min(d,distance(s1.p2,s2));
d=min(d,distance(s2.p1,s1));
d=min(d,distance(s2.p2,s1));
return d;
}
double ldistance (Line & l1 ,Line & l2) //線段到線段距離
{
Vector v1=l1.p2-l1.p1;
Vector v2=l2.p2-l2.p1;
if(cross(v1,v2)!=0) return 0;
return distance(l1.p1,l2); //點到線段距離
}
int ConvexHull(Point* P, int cnt, Point* res) { //凸包
sort(P, P + cnt); //先x 後 y
cnt = unique(P, P + cnt) - P; //非重複的點數量
int m = 0;
for (int i = 0; i < cnt; i++) {
while (m > 1 && cross(res[m - 1] - res[m - 2], P[i] - res[m - 2]) <= 0)
m--;
res[m++] = P[i];
}
int k = m;
for (int i = cnt - 2; i >= 0; i--) {
while (m > k && cross(res[m - 1] - res[m - 2], P[i] - res[m - 2]) <= 0)
m--;
res[m++] = P[i];
}
if (cnt > 1) //頭尾
m--;
return m; //凸包點數
}
double PolygonArea(Point *p,int n)
{
double area;
for(int i=0;i<n;++i)
area+=cross(p[i],p[(i+1)%n]);
return fabs(area)/2;
}
//半平面交
typedef vector<Point> Polygon;
Polygon halfplane_intersection (Polygon & p,Line & line)
{
Polygon q;
Point p1=line.p1,p2=line.p2;
int n=p.size();
for(int i=0;i<n;i++)
{
double c=cross(p1,p2,p[i]);
double d=cross(p1,p2,p[(i+1)%n]);
if(dcmp(c)>=0)q.push_back(p[i]);
if(dcmp(c*d)<0) q.push_back(GetLineIntersection(p1,p2,p[i],p[(i+1)%n]));
}
return q;
}
<commit_msg>debug<commit_after>#include <bits/stdc++.h>
using namespace std;
const double EPS=1e-6;
int dcmp(double x)
{
if(fabs(x)<EPS) return 0;
else return x<0 ? -1:1;
}
struct Point
{
double x,y;
Point(){x=0,y=0;}
Point(double _x,double _y){x=_x;y=_y;}
Point operator +(const Point & b)
{
return Point(x+b.x,y+b.y);
}
Point operator - (const Point & b) const
{
return Point(x-b.x,y-b.y);
}
Point operator * (double p)
{
return Point(x*p,y*p);
}
Point operator / (double p)
{
return Point(x/p,y/p);
}
bool operator <(const Point & b)
{
return x<b.x || (x==b.x && y<b.y);
}
bool operator ==(const Point & b)
{
return dcmp(x-b.x)==0 && dcmp(y-b.y)==0;
}
};
typedef Point Vector;
double dot (Vector v1,Vector v2)
{
return v1.x*v2.x+v1.y*v2.y;
}
double cross(Point & o,Point & a, Point &b) //OA X OB
{
return (a.x-o.x)*(b.y-o.y)-(a.y-o.y)*(b.x-o.x);
}
double cross(Vector a,Vector b)
{
return a.x*b.y-a.y*b.x;
}
double length(Vector v)
{
return sqrt(v.x*v.x+v.y*v.y); //return sqrt(dot(v,v));
}
double angle (const Vector & a,const Vector & b)
{
return acos(dot(a,b)/length(a)/length(b));
}
double Triarea(const Point & p1,const Point & p2 ,const Point & p3)
{
return fabs(cross(p2-p1,p3-p1))/2;
}
Vector Rotate(const Vector & a,double rad) //radian 0~2pi //counterclockwise
{
return Vector(a.x*cos(rad)-a.y*sin(rad),a.x*sin(rad)+a.y*cos(rad)); //旋轉矩陣
}
Vector Normal(const Vector &a) //向量的單位法線
{
double L=length(a);
return Vector(-a.y/L,a.x/L);
}
struct Line
{
Point p1,p2;
};
typedef Line Segment;
Point GetLineIntersection (Point p,Vector v,Point q,Vector w) //點斜式交點 p+vt1 q+wt2
{
Vector u=p-q;
double t=cross(w,u)/cross(v,w); //t1
return p+v*t; //p+vt1
}
Point GetLineProjection (Point p,Point a,Point b)
{
Vector v=b-a;
return a+v*(dot(v,p-a)/dot(v,v));
}
typedef Line Segment;
bool Onsegment(Point p,Point a1,Point a2)//點在線上
{
//平行 //端點在兩側
return dcmp(cross(a1-p,a2-p))==0 && dcmp(dot(a1-p,a2-p))<0;
}
bool SegmentProperIntersection(Point a1,Point a2,Point b1,Point b2)
{
// 規範相交 :交點不能是線段的交點
double c1=cross(a2-a1,b1-a1) ,c2=cross(a2-a1,b2-a1);
double c3=cross(b2-b1,a1-b1),c4=cross(b2-b1,a2-b1);
return dcmp(c1)*dcmp(c2)<0 && dcmp(c3)* dcmp(c4)<0;
}
bool SegmentProperIntersection(Segment s1, Segment s2)
{
return SegmentProperIntersection(s1.p1,s1.p2,s2.p1,s2.p2);
}
bool SegmentInterSection(Point a1,Point a2,Point b1,Point b2) //非規範相交
{
//端點相交
if(Onsegment(a1,b1,b2)|| Onsegment (a2,b1,b2) || Onsegment (b1,a1,a2) || Onsegment (b2,a1,a2)) return true;
if(SegmentProperIntersection(a1,a2,b1,b2)) return true; //規範相交
return false;
}
bool SegmentInterSection(Line & l1 ,Line & l2)
{
return SegmentInterSection(l1.p1,l1.p2,l2.p1,l2.p2);
}
double distance (Point & a,Point & b)
{
return sqrt(length(b-a));
}
double distance (Point &p,Point & p1, Point & p2)//Line => p1,p2
{
Vector v1=p-p1,v2=p2-p1;
return fabs(cross(v1,v2))/length(v2); //面積/底=高(距離)
}
double distance (Point &p ,Segment & s) //Point to Segment
{
Vector v=s.p2-s.p1;
if(dcmp(length(v))==0) return length(p-s.p1); //線段退化成點
Vector v1=p-s.p1;
Vector v2=p-s.p2;
if(dcmp(dot(v1,v))<0)return length(v1); // 點投影不在線上
if(dcmp(dot(v2,v))>0) return length(v2);// 點投影不在線上
return fabs(cross(v,v1))/length(v);
}
double distance(Segment & s1 , Segment & s2) //線段到線段
{
if(SegmentInterSection(s1,s2)) return 0;
double d =1e9;
d=min(d,distance(s1.p1,s2)); //點到線段距離取最短
d=min(d,distance(s1.p2,s2));
d=min(d,distance(s2.p1,s1));
d=min(d,distance(s2.p2,s1));
return d;
}
double ldistance (Line & l1 ,Line & l2) //線段到線段距離
{
Vector v1=l1.p2-l1.p1;
Vector v2=l2.p2-l2.p1;
if(cross(v1,v2)!=0) return 0;
return distance(l1.p1,l2); //點到線段距離
}
int ConvexHull(Point* P, int cnt, Point* res) { //凸包
sort(P, P + cnt); //先x 後 y
cnt = unique(P, P + cnt) - P; //非重複的點數量
int m = 0;
for (int i = 0; i < cnt; i++) {
while (m > 1 && cross(res[m - 1] - res[m - 2], P[i] - res[m - 2]) <= 0)
m--;
res[m++] = P[i];
}
int k = m;
for (int i = cnt - 2; i >= 0; i--) {
while (m > k && cross(res[m - 1] - res[m - 2], P[i] - res[m - 2]) <= 0)
m--;
res[m++] = P[i];
}
if (cnt > 1) //頭尾
m--;
return m; //凸包點數
}
double PolygonArea(Point *p,int n)
{
double area=0;
for(int i=0;i<n;++i)
area+=cross(p[i],p[(i+1)%n]);
return fabs(area)/2;
}
//半平面交
typedef vector<Point> Polygon;
Polygon halfplane_intersection (Polygon & p,Line & line)
{
Polygon q;
Point p1=line.p1,p2=line.p2;
int n=p.size();
for(int i=0;i<n;i++)
{
double c=cross(p1,p2,p[i]);
double d=cross(p1,p2,p[(i+1)%n]);
if(dcmp(c)>=0)q.push_back(p[i]);
if(dcmp(c*d)<0) q.push_back(GetLineIntersection(p1,p2,p[i],p[(i+1)%n]));
}
return q;
}
<|endoftext|> |
<commit_before>/**************************************************************************
*
* Copyright 2011 Jose Fonseca
* All Rights Reserved.
*
* 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 "glproc.hpp"
#include "glws.hpp"
namespace glws {
static LRESULT CALLBACK
WndProc(HWND hWnd, UINT uMsg, WPARAM wParam, LPARAM lParam)
{
MINMAXINFO *pMMI;
switch (uMsg) {
case WM_GETMINMAXINFO:
// Allow to create a window bigger than the desktop
pMMI = (MINMAXINFO *)lParam;
pMMI->ptMaxSize.x = 60000;
pMMI->ptMaxSize.y = 60000;
pMMI->ptMaxTrackSize.x = 60000;
pMMI->ptMaxTrackSize.y = 60000;
break;
default:
break;
}
return DefWindowProc(hWnd, uMsg, wParam, lParam);
}
class WglDrawable : public Drawable
{
public:
DWORD dwExStyle;
DWORD dwStyle;
HWND hWnd;
HDC hDC;
PIXELFORMATDESCRIPTOR pfd;
int iPixelFormat;
WglDrawable(const Visual *vis, int width, int height) :
Drawable(vis, width, height)
{
static bool first = TRUE;
RECT rect;
if (first) {
WNDCLASS wc;
memset(&wc, 0, sizeof wc);
wc.hbrBackground = (HBRUSH) (COLOR_BTNFACE + 1);
wc.hCursor = LoadCursor(NULL, IDC_ARROW);
wc.hIcon = LoadIcon(NULL, IDI_APPLICATION);
wc.lpfnWndProc = WndProc;
wc.lpszClassName = "glretrace";
wc.style = CS_OWNDC | CS_HREDRAW | CS_VREDRAW;
RegisterClass(&wc);
first = FALSE;
}
dwExStyle = 0;
dwStyle = WS_CLIPSIBLINGS | WS_CLIPCHILDREN | WS_OVERLAPPEDWINDOW;
int x = 0, y = 0;
rect.left = x;
rect.top = y;
rect.right = rect.left + width;
rect.bottom = rect.top + height;
AdjustWindowRectEx(&rect, dwStyle, FALSE, dwExStyle);
hWnd = CreateWindowEx(dwExStyle,
"glretrace", /* wc.lpszClassName */
NULL,
dwStyle,
0, /* x */
0, /* y */
rect.right - rect.left, /* width */
rect.bottom - rect.top, /* height */
NULL,
NULL,
NULL,
NULL);
hDC = GetDC(hWnd);
memset(&pfd, 0, sizeof pfd);
pfd.cColorBits = 4;
pfd.cRedBits = 1;
pfd.cGreenBits = 1;
pfd.cBlueBits = 1;
pfd.cAlphaBits = 1;
pfd.cDepthBits = 1;
pfd.cStencilBits = 1;
pfd.dwFlags = PFD_DRAW_TO_WINDOW | PFD_SUPPORT_OPENGL;
pfd.iLayerType = PFD_MAIN_PLANE;
pfd.iPixelType = PFD_TYPE_RGBA;
pfd.nSize = sizeof(pfd);
pfd.nVersion = 1;
if (visual->doubleBuffer) {
pfd.dwFlags |= PFD_DOUBLEBUFFER;
}
iPixelFormat = ChoosePixelFormat(hDC, &pfd);
SetPixelFormat(hDC, iPixelFormat, &pfd);
}
~WglDrawable() {
ReleaseDC(hWnd, hDC);
DestroyWindow(hWnd);
}
void
resize(int w, int h) {
if (w == width && h == height) {
return;
}
RECT rClient, rWindow;
GetClientRect(hWnd, &rClient);
GetWindowRect(hWnd, &rWindow);
w += (rWindow.right - rWindow.left) - rClient.right;
h += (rWindow.bottom - rWindow.top) - rClient.bottom;
SetWindowPos(hWnd, NULL, rWindow.left, rWindow.top, w, h, SWP_NOMOVE);
Drawable::resize(w, h);
}
void show(void) {
if (visible) {
return;
}
ShowWindow(hWnd, SW_SHOW);
Drawable::show();
}
void swapBuffers(void) {
SwapBuffers(hDC);
// Drain message queue to prevent window from being considered
// non-responsive
MSG msg;
while (PeekMessage(&msg, NULL, 0, 0, PM_REMOVE)) {
TranslateMessage(&msg);
DispatchMessage(&msg);
}
}
};
class WglContext : public Context
{
public:
HGLRC hglrc;
WglContext *shareContext;
WglContext(const Visual *vis, Profile prof, WglContext *share) :
Context(vis, prof),
hglrc(0),
shareContext(share)
{}
~WglContext() {
if (hglrc) {
wglDeleteContext(hglrc);
}
}
};
void
init(void) {
/*
* OpenGL library must be loaded by the time we call GDI.
*/
__libGlHandle = LoadLibraryA("OPENGL32");
}
void
cleanup(void) {
}
Visual *
createVisual(bool doubleBuffer, Profile profile) {
if (profile != PROFILE_COMPAT) {
return NULL;
}
Visual *visual = new Visual();
visual->doubleBuffer = doubleBuffer;
return visual;
}
Drawable *
createDrawable(const Visual *visual, int width, int height)
{
return new WglDrawable(visual, width, height);
}
Context *
createContext(const Visual *visual, Context *shareContext, Profile profile)
{
if (profile != PROFILE_COMPAT) {
return NULL;
}
return new WglContext(visual, profile, static_cast<WglContext *>(shareContext));
}
bool
makeCurrent(Drawable *drawable, Context *context)
{
if (!drawable || !context) {
return wglMakeCurrent(NULL, NULL);
} else {
WglDrawable *wglDrawable = static_cast<WglDrawable *>(drawable);
WglContext *wglContext = static_cast<WglContext *>(context);
if (!wglContext->hglrc) {
wglContext->hglrc = wglCreateContext(wglDrawable->hDC);
if (!wglContext->hglrc) {
return false;
}
if (wglContext->shareContext) {
wglShareLists(wglContext->shareContext->hglrc,
wglContext->hglrc);
}
}
return wglMakeCurrent(wglDrawable->hDC, wglContext->hglrc);
}
}
bool
processEvents(void) {
// TODO
return true;
}
} /* namespace glws */
<commit_msg>Allow to specify an alternative opengl32.dll when retracing.<commit_after>/**************************************************************************
*
* Copyright 2011 Jose Fonseca
* All Rights Reserved.
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*
**************************************************************************/
#include <iostream>
#include "glproc.hpp"
#include "glws.hpp"
namespace glws {
static LRESULT CALLBACK
WndProc(HWND hWnd, UINT uMsg, WPARAM wParam, LPARAM lParam)
{
MINMAXINFO *pMMI;
switch (uMsg) {
case WM_GETMINMAXINFO:
// Allow to create a window bigger than the desktop
pMMI = (MINMAXINFO *)lParam;
pMMI->ptMaxSize.x = 60000;
pMMI->ptMaxSize.y = 60000;
pMMI->ptMaxTrackSize.x = 60000;
pMMI->ptMaxTrackSize.y = 60000;
break;
default:
break;
}
return DefWindowProc(hWnd, uMsg, wParam, lParam);
}
class WglDrawable : public Drawable
{
public:
DWORD dwExStyle;
DWORD dwStyle;
HWND hWnd;
HDC hDC;
PIXELFORMATDESCRIPTOR pfd;
int iPixelFormat;
WglDrawable(const Visual *vis, int width, int height) :
Drawable(vis, width, height)
{
static bool first = TRUE;
RECT rect;
if (first) {
WNDCLASS wc;
memset(&wc, 0, sizeof wc);
wc.hbrBackground = (HBRUSH) (COLOR_BTNFACE + 1);
wc.hCursor = LoadCursor(NULL, IDC_ARROW);
wc.hIcon = LoadIcon(NULL, IDI_APPLICATION);
wc.lpfnWndProc = WndProc;
wc.lpszClassName = "glretrace";
wc.style = CS_OWNDC | CS_HREDRAW | CS_VREDRAW;
RegisterClass(&wc);
first = FALSE;
}
dwExStyle = 0;
dwStyle = WS_CLIPSIBLINGS | WS_CLIPCHILDREN | WS_OVERLAPPEDWINDOW;
int x = 0, y = 0;
rect.left = x;
rect.top = y;
rect.right = rect.left + width;
rect.bottom = rect.top + height;
AdjustWindowRectEx(&rect, dwStyle, FALSE, dwExStyle);
hWnd = CreateWindowEx(dwExStyle,
"glretrace", /* wc.lpszClassName */
NULL,
dwStyle,
0, /* x */
0, /* y */
rect.right - rect.left, /* width */
rect.bottom - rect.top, /* height */
NULL,
NULL,
NULL,
NULL);
hDC = GetDC(hWnd);
memset(&pfd, 0, sizeof pfd);
pfd.cColorBits = 4;
pfd.cRedBits = 1;
pfd.cGreenBits = 1;
pfd.cBlueBits = 1;
pfd.cAlphaBits = 1;
pfd.cDepthBits = 1;
pfd.cStencilBits = 1;
pfd.dwFlags = PFD_DRAW_TO_WINDOW | PFD_SUPPORT_OPENGL;
pfd.iLayerType = PFD_MAIN_PLANE;
pfd.iPixelType = PFD_TYPE_RGBA;
pfd.nSize = sizeof(pfd);
pfd.nVersion = 1;
if (visual->doubleBuffer) {
pfd.dwFlags |= PFD_DOUBLEBUFFER;
}
iPixelFormat = ChoosePixelFormat(hDC, &pfd);
SetPixelFormat(hDC, iPixelFormat, &pfd);
}
~WglDrawable() {
ReleaseDC(hWnd, hDC);
DestroyWindow(hWnd);
}
void
resize(int w, int h) {
if (w == width && h == height) {
return;
}
RECT rClient, rWindow;
GetClientRect(hWnd, &rClient);
GetWindowRect(hWnd, &rWindow);
w += (rWindow.right - rWindow.left) - rClient.right;
h += (rWindow.bottom - rWindow.top) - rClient.bottom;
SetWindowPos(hWnd, NULL, rWindow.left, rWindow.top, w, h, SWP_NOMOVE);
Drawable::resize(w, h);
}
void show(void) {
if (visible) {
return;
}
ShowWindow(hWnd, SW_SHOW);
Drawable::show();
}
void swapBuffers(void) {
SwapBuffers(hDC);
// Drain message queue to prevent window from being considered
// non-responsive
MSG msg;
while (PeekMessage(&msg, NULL, 0, 0, PM_REMOVE)) {
TranslateMessage(&msg);
DispatchMessage(&msg);
}
}
};
class WglContext : public Context
{
public:
HGLRC hglrc;
WglContext *shareContext;
WglContext(const Visual *vis, Profile prof, WglContext *share) :
Context(vis, prof),
hglrc(0),
shareContext(share)
{}
~WglContext() {
if (hglrc) {
wglDeleteContext(hglrc);
}
}
};
void
init(void) {
/*
* OpenGL library must be loaded by the time we call GDI.
*/
const char * libgl_filename = getenv("TRACE_LIBGL");
if (!libgl_filename) {
libgl_filename = "OPENGL32";
}
__libGlHandle = LoadLibraryA(libgl_filename);
if (!__libGlHandle) {
std::cerr << "error: unable to open " << libgl_filename << "\n";
exit(1);
}
}
void
cleanup(void) {
}
Visual *
createVisual(bool doubleBuffer, Profile profile) {
if (profile != PROFILE_COMPAT) {
return NULL;
}
Visual *visual = new Visual();
visual->doubleBuffer = doubleBuffer;
return visual;
}
Drawable *
createDrawable(const Visual *visual, int width, int height)
{
return new WglDrawable(visual, width, height);
}
Context *
createContext(const Visual *visual, Context *shareContext, Profile profile)
{
if (profile != PROFILE_COMPAT) {
return NULL;
}
return new WglContext(visual, profile, static_cast<WglContext *>(shareContext));
}
bool
makeCurrent(Drawable *drawable, Context *context)
{
if (!drawable || !context) {
return wglMakeCurrent(NULL, NULL);
} else {
WglDrawable *wglDrawable = static_cast<WglDrawable *>(drawable);
WglContext *wglContext = static_cast<WglContext *>(context);
if (!wglContext->hglrc) {
wglContext->hglrc = wglCreateContext(wglDrawable->hDC);
if (!wglContext->hglrc) {
return false;
}
if (wglContext->shareContext) {
wglShareLists(wglContext->shareContext->hglrc,
wglContext->hglrc);
}
}
return wglMakeCurrent(wglDrawable->hDC, wglContext->hglrc);
}
}
bool
processEvents(void) {
// TODO
return true;
}
} /* namespace glws */
<|endoftext|> |
<commit_before>#include <QApplication>
#include <QCommandLineParser>
#include <QDebug>
#include <databasecontroller.h>
#include <qsingleinstance.h>
#include <QFileInfo>
#include <QFile>
#include "traycontrol.h"
#include "pluginloader.h"
#include "wizard/databasewizard.h"
#include "consoleoperator.h"
static void setupParser(QCommandLineParser &parser);
int main(int argc, char *argv[])
{
QApplication a(argc, argv);
QApplication::setApplicationName(QStringLiteral(TARGET));
QApplication::setApplicationVersion(QStringLiteral(VERSION));
QApplication::setOrganizationName(QStringLiteral(COMPANY));
QApplication::setOrganizationDomain(QStringLiteral(BUNDLE));
QApplication::setApplicationDisplayName(QStringLiteral(DISPLAY_NAME));
QApplication::setWindowIcon(QIcon(QStringLiteral(":/icons/main.svg")));
QApplication::setQuitOnLastWindowClosed(false);
//load translations
DatabaseController::loadTranslation(QStringLiteral("paxchange_gui"));
QCommandLineParser parser;
setupParser(parser);
parser.process(a);
QSingleInstance instance;
instance.setGlobal(true);
instance.setStartupFunction([&]() {
if(parser.isSet(QStringLiteral("f"))){
if(PluginLoader::cacheForwardedPluginArgs(parser.positionalArguments()))
QMetaObject::invokeMethod(qApp, "quit", Qt::QueuedConnection);
else
return EXIT_FAILURE;
return EXIT_SUCCESS;
}
try {
PluginLoader::loadPlugin(parser.value(QStringLiteral("p")));
} catch(PluginLoadException &e) {
qCritical() << e.what();
return EXIT_FAILURE;
}
auto tray = new TrayControl(&a);
new ConsoleOperator(&a);
if(!DatabaseController::instance()->isLoaded()) {
if(!DatabaseWizard::run()) {
QMetaObject::invokeMethod(qApp, "quit", Qt::QueuedConnection);
return EXIT_SUCCESS;
}
} else
PluginLoader::readCachedForwardedPluginArgs();
tray->show();
return EXIT_SUCCESS;
});
QObject::connect(&instance, &QSingleInstance::instanceMessage, [&](QStringList args){
if(!parser.parse(args) || !parser.isSet(QStringLiteral("f")))
return;
PluginLoader::plugin()->forwardedArguments(parser.positionalArguments());
});
return instance.singleExec();
}
static void setupParser(QCommandLineParser &parser)
{
parser.addVersionOption();
parser.addHelpOption();
parser.addOption({
{QStringLiteral("p"), QStringLiteral("pacin")},
QCoreApplication::translate("GLOBAL", "Explicitly select the plugin to be loaded"),
QStringLiteral("plugin")
});
parser.addOption({
{QStringLiteral("f"), QStringLiteral("forward")},
QCoreApplication::translate("GLOBAL", "Forwards the arguments to the plugin")
});
}
<commit_msg>made stdin args possible<commit_after>#include <QApplication>
#include <QCommandLineParser>
#include <QDebug>
#include <databasecontroller.h>
#include <qsingleinstance.h>
#include <QFileInfo>
#include <QFile>
#include "traycontrol.h"
#include "pluginloader.h"
#include "wizard/databasewizard.h"
#include "consoleoperator.h"
static void setupParser(QCommandLineParser &parser);
int main(int argc, char *argv[])
{
// ugly fix to enable stdin input
QByteArrayList xArgs;
int stdIdx = -1;
for(auto i = 0; i < argc; i++) {
if(qstrcmp(argv[i], "--stdin") == 0) {
stdIdx = i;
QFile in;
in.open(stdin, QIODevice::ReadOnly);
xArgs = in.readAll().simplified().split(' ');
break;
}
}
QVector<char*> nArgs{argc + xArgs.size()};
int nArgc = 0;
char **nArgv = nullptr;
if(xArgs.isEmpty()) {
nArgs.clear();
nArgc = argc;
nArgv = argv;
} else {
int idx;
for(idx = 0; idx < argc; idx++)
nArgs[idx] = argv[idx];
for(; (idx - argc) < xArgs.size(); idx++)
nArgs[idx] = xArgs[idx - argc].data();
nArgs.removeAt(stdIdx);
nArgc = nArgs.size();
nArgv = nArgs.data();
}
// begin actual main
QApplication a(nArgc, nArgv);
QApplication::setApplicationName(QStringLiteral(TARGET));
QApplication::setApplicationVersion(QStringLiteral(VERSION));
QApplication::setOrganizationName(QStringLiteral(COMPANY));
QApplication::setOrganizationDomain(QStringLiteral(BUNDLE));
QApplication::setApplicationDisplayName(QStringLiteral(DISPLAY_NAME));
QApplication::setWindowIcon(QIcon(QStringLiteral(":/icons/main.svg")));
QApplication::setQuitOnLastWindowClosed(false);
qDebug() << QCoreApplication::arguments();
//load translations
DatabaseController::loadTranslation(QStringLiteral("paxchange_gui"));
QCommandLineParser parser;
setupParser(parser);
parser.process(a);
QSingleInstance instance;
instance.setGlobal(true);
instance.setStartupFunction([&]() {
if(parser.isSet(QStringLiteral("f"))){
if(PluginLoader::cacheForwardedPluginArgs(parser.positionalArguments()))
QMetaObject::invokeMethod(qApp, "quit", Qt::QueuedConnection);
else
return EXIT_FAILURE;
return EXIT_SUCCESS;
}
try {
PluginLoader::loadPlugin(parser.value(QStringLiteral("p")));
} catch(PluginLoadException &e) {
qCritical() << e.what();
return EXIT_FAILURE;
}
auto tray = new TrayControl(&a);
new ConsoleOperator(&a);
if(!DatabaseController::instance()->isLoaded()) {
if(!DatabaseWizard::run()) {
QMetaObject::invokeMethod(qApp, "quit", Qt::QueuedConnection);
return EXIT_SUCCESS;
}
} else
PluginLoader::readCachedForwardedPluginArgs();
tray->show();
return EXIT_SUCCESS;
});
QObject::connect(&instance, &QSingleInstance::instanceMessage, [&](const QStringList &args){
if(!parser.parse(args) || !parser.isSet(QStringLiteral("f")))
return;
PluginLoader::plugin()->forwardedArguments(parser.positionalArguments());
});
return instance.singleExec();
}
static void setupParser(QCommandLineParser &parser)
{
parser.addVersionOption();
parser.addHelpOption();
parser.addOption({
{QStringLiteral("p"), QStringLiteral("pacin")},
QCoreApplication::translate("GLOBAL", "Explicitly select the plugin to be loaded"),
QStringLiteral("plugin")
});
parser.addOption({
{QStringLiteral("f"), QStringLiteral("forward")},
QCoreApplication::translate("GLOBAL", "Forwards the arguments to the plugin")
});
parser.addOption({
{QStringLiteral("stdin")},
QCoreApplication::translate("GLOBAL", "Arguments to be forwarded to the plugin should be read from stdin "
"and appended to the commandline")
});
}
<|endoftext|> |
<commit_before>// Petter Strandmark 2012--2013.
#include <functional>
#include <iostream>
#include <random>
#include <spii/auto_diff_term.h>
#include <spii/constraints.h>
#include <spii/interval_term.h>
#include <spii/solver.h>
using namespace spii;
// One term in the negative log-likelihood function for
// a one-dimensional Gaussian distribution.
struct NegLogLikelihood
{
double sample;
NegLogLikelihood(double sample)
{
this->sample = sample;
}
template<typename R>
R operator()(const R* const mu, const R* const sigma) const
{
R diff = (*mu - sample) / *sigma;
return 0.5 * diff*diff + log(*sigma);
}
};
int main_function()
{
std::mt19937 prng(1);
std::normal_distribution<double> normal;
auto randn = std::bind(normal, prng);
double mu = 5.0;
double sigma = 3.0;
std::cout << "mu = " << mu << ", sigma = " << sigma << std::endl;
Function f;
f.add_variable(&mu, 1);
f.add_variable_with_change<GreaterThanZero>(&sigma, 1, 1);
for (int i = 0; i < 10000; ++i) {
double sample = sigma*randn() + mu;
f.add_term(std::make_shared<IntervalTerm<NegLogLikelihood, 1, 1>>(sample), &mu, &sigma);
}
mu = 0.0;
sigma = 1.0;
Solver solver;
SolverResults results;
solver.solve_lbfgs(f, &results);
std::cout << "Estimated:" << std::endl;
std::cout << "mu = " << mu << ", sigma = " << sigma << std::endl << std::endl;
// Remove the constraint on sigma.
f.add_variable(&sigma, 1);
Interval<double> start_mu(4.0, 6.0);
Interval<double> start_sigma(1.0, 10.0);
IntervalVector start_box;
start_box.push_back(start_mu);
start_box.push_back(start_sigma);
solver.maximum_iterations = 5000;
solver.solve_global(f, start_box, &results);
std::cout << results << std::endl;
std::cout << "Global optimization:" << std::endl;
std::cout << "mu = " << mu << ", sigma = " << sigma << std::endl << std::endl;
return 0;
}
int main()
{
try {
return main_function();
}
catch (std::exception& e) {
std::cerr << "Error: " << e.what() << '\n';
return 1;
}
}<commit_msg>No global optimization in fit_gaussian.<commit_after>// Petter Strandmark 2012--2013.
#include <functional>
#include <iostream>
#include <random>
#include <spii/auto_diff_term.h>
#include <spii/constraints.h>
#include <spii/interval_term.h>
#include <spii/solver.h>
using namespace spii;
// One term in the negative log-likelihood function for
// a one-dimensional Gaussian distribution.
struct NegLogLikelihood
{
double sample;
NegLogLikelihood(double sample)
{
this->sample = sample;
}
template<typename R>
R operator()(const R* const mu, const R* const sigma) const
{
R diff = (*mu - sample) / *sigma;
return 0.5 * diff*diff + log(*sigma);
}
};
int main_function()
{
std::mt19937 prng(1u);
std::normal_distribution<double> normal;
auto randn = std::bind(normal, prng);
double mu = 5.0;
double sigma = 3.0;
std::cout << "mu = " << mu << ", sigma = " << sigma << std::endl;
Function f;
f.add_variable(&mu, 1);
f.add_variable_with_change<GreaterThanZero>(&sigma, 1, 1);
for (int i = 0; i < 10000; ++i) {
double sample = sigma*randn() + mu;
f.add_term(std::make_shared<IntervalTerm<NegLogLikelihood, 1, 1>>(sample), &mu, &sigma);
}
mu = 0.0;
sigma = 1.0;
LBFGSSolver solver;
SolverResults results;
solver.solve(f, &results);
std::cout << "Estimated:" << std::endl;
std::cout << "f = " << f.evaluate() << " mu = " << mu << ", sigma = " << sigma << std::endl << std::endl;
return 0;
}
int main()
{
try {
return main_function();
}
catch (std::exception& e) {
std::cerr << "Error: " << e.what() << '\n';
return 1;
}
}<|endoftext|> |
<commit_before>//------------------------------------------------------------------------
#include <stdio.h>
#include <math.h>
#include <sstream>
#include <string>
#include <fstream>
#include <random>
#include <particle_simulator.hpp>
//------------------------------------------------------------------------
const PS::F64 CUTOFF_LENGTH = 3.0;
//------------------------------------------------------------------------
class ForceLJ {
public:
PS::F64vec force;
PS::F64 potential;
void clear() {
force = 0.0;
potential = 0.0;
}
};
//------------------------------------------------------------------------
class FPLJ {
public:
PS::S32 id;
PS::F64vec p;
PS::F64vec q;
PS::F64vec force;
PS::F64 potential;
PS::F64vec getPos() const {
return q;
}
void setPos(PS::F64vec nq) {
q = nq;
}
void copyFromForce(const ForceLJ & f) {
force = f.force;
potential = f.potential;
}
};
//------------------------------------------------------------------------
class EPLJ {
public:
PS::S32 id;
PS::F64vec q;
PS::F64vec getPos() const {
return q;
}
void setPos(const PS::F64vec & nq) {
q = nq;
}
PS::F64 getRSearch() const {
return CUTOFF_LENGTH;
}
void copyFromFP(const FPLJ & fp) {
id = fp.id;
q = fp.q;
}
};
//------------------------------------------------------------------------
class CalcForceLJ {
public:
void operator() (const EPLJ * epi, const PS::S32 ni,
const EPLJ * epj, const PS::S32 nj,
ForceLJ *force) {
const PS::F64 CL2 = CUTOFF_LENGTH*CUTOFF_LENGTH;
const PS::F64 CL6 = CL2*CL2*CL2;
const PS::F64 CL12 = CL6*CL6;
const PS::F64 C0 = - 4.0 * (1.0/CL12 - 1.0/CL6);
for (PS::S32 i = 0; i < ni; i++) {
force[i].force = 0.0;
force[i].potential = 0.0;
for (PS::S32 j = 0; j < nj; j++) {
if(epi[i].id == epj[j].id) continue;
PS::F64vec dq = epj[j].q - epi[i].q;
PS::F64 r2 = dq * dq;
PS::F64 r6 = r2*r2*r2;
PS::F64 r12 = r6 * r6;
if (r2 > CL2) continue;
PS::F64 df = (24.0 * r6 - 48.0) / (r6 * r6 * r2);
force[i].force += dq * df;
force[i].potential += (4.0 * (1.0 / r12 - 1.0 / r6) + C0)*0.5;
}
}
}
};
//------------------------------------------------------------------------
PS::F64
reducesum(PS::F64 v){
PS::F64 r;
MPI::COMM_WORLD.Allreduce(&v, &r, 1, PS::GetDataType<PS::F64>(), MPI::SUM);
return r;
}
//------------------------------------------------------------------------
template<class Tpsys>
PS::F64
energy(const Tpsys &system){
PS::F64 e = 0.0;
const PS::S32 n = system.getNumberOfParticleLocal();
for(PS::S32 i = 0; i < n; i++) {
FPLJ a = system[i];
e += (a.p*a.p)*0.5;
e += a.potential;
}
return reducesum(e);
}
//------------------------------------------------------------------------
template<class Tpsys>
void
drift(Tpsys & system, const PS::F64 dt) {
const PS::S32 n = system.getNumberOfParticleLocal();
for (PS::S32 i = 0; i < n; i++) {
system[i].q += system[i].p * dt;
}
}
//------------------------------------------------------------------------
template<class Tpsys>
void
kick(Tpsys & system, const PS::F64 dt) {
const PS::S32 n = system.getNumberOfParticleLocal();
for (PS::S32 i = 0; i < n; i++) {
system[i].p += system[i].force * dt;
}
}
//------------------------------------------------------------------------
template<class Tpsys>
void
dump(std::ostream &os, const PS::F64 s_time, Tpsys &system){
const PS::S32 n = system.getNumberOfParticleLocal();
if (n == 0)return;
os << s_time << " ";
for (PS::S32 i = 0; i < n; i++) {
os << system[i].q.x << " ";
}
os << std::endl;
}
//------------------------------------------------------------------------
int
main(int argc, char **argv) {
PS::Initialize(argc, argv);
const int rank = PS::Comm::getRank();
const int procs = PS::Comm::getNumberOfProc();
PS::ParticleSystem<FPLJ> lj_system;
lj_system.initialize();
const PS::F64 L = 10;
PS::DomainInfo dinfo;
dinfo.initialize();
dinfo.setBoundaryCondition(PS::BOUNDARY_CONDITION_PERIODIC_XYZ);
dinfo.setPosRootDomain(PS::F64vec(0, 0, 0), PS::F64vec(L, L, L));
const int N = 2;
if (rank == 0){
lj_system.setNumberOfParticleLocal(N);
lj_system[0].id = 0;
lj_system[0].p = PS::F64vec(1.0, 0.0, 0.0);
lj_system[0].q = PS::F64vec(2.5, 5.0, 5.0);
lj_system[1].id = 1;
lj_system[1].p = PS::F64vec(-1.0, 0.0, 0.0);
lj_system[1].q = PS::F64vec(7.5, 5.0, 5.0);
}else{
lj_system.setNumberOfParticleLocal(0);
}
PS::TreeForForceShort<ForceLJ, EPLJ, EPLJ>::Gather tree_lj;
tree_lj.initialize(N);
const PS::F64 dt = 0.01;
PS::F64 s_time = 0.0;
const int LOOP = 1000;
dinfo.decomposeDomainAll(lj_system);
lj_system.exchangeParticle(dinfo);
char filename[256];
sprintf(filename,"trac%02d.dat",rank);
std::ofstream ofs(filename);
for(int i=0;i<LOOP;i++){
drift(lj_system, dt*0.5);
tree_lj.calcForceAllAndWriteBack(CalcForceLJ(), lj_system, dinfo);
kick(lj_system, dt);
drift(lj_system, dt*0.5);
dump(ofs, s_time, lj_system);
tree_lj.calcForceAllAndWriteBack(CalcForceLJ(), lj_system, dinfo);
PS::F64 e = energy(lj_system);
if (rank==0){
std::cout << s_time << " " << e << std::endl;
}
s_time += dt;
}
PS::Finalize();
}
//------------------------------------------------------------------------
<commit_msg>use PS::Comm::getSum<commit_after>//------------------------------------------------------------------------
#include <stdio.h>
#include <math.h>
#include <sstream>
#include <string>
#include <fstream>
#include <random>
#include <particle_simulator.hpp>
//------------------------------------------------------------------------
const PS::F64 CUTOFF_LENGTH = 3.0;
//------------------------------------------------------------------------
class ForceLJ {
public:
PS::F64vec force;
PS::F64 potential;
void clear() {
force = 0.0;
potential = 0.0;
}
};
//------------------------------------------------------------------------
class FPLJ {
public:
PS::S32 id;
PS::F64vec p;
PS::F64vec q;
PS::F64vec force;
PS::F64 potential;
PS::F64vec getPos() const {
return q;
}
void setPos(PS::F64vec nq) {
q = nq;
}
void copyFromForce(const ForceLJ & f) {
force = f.force;
potential = f.potential;
}
};
//------------------------------------------------------------------------
class EPLJ {
public:
PS::S32 id;
PS::F64vec q;
PS::F64vec getPos() const {
return q;
}
void setPos(const PS::F64vec & nq) {
q = nq;
}
PS::F64 getRSearch() const {
return CUTOFF_LENGTH;
}
void copyFromFP(const FPLJ & fp) {
id = fp.id;
q = fp.q;
}
};
//------------------------------------------------------------------------
class CalcForceLJ {
public:
void operator() (const EPLJ * epi, const PS::S32 ni,
const EPLJ * epj, const PS::S32 nj,
ForceLJ *force) {
const PS::F64 CL2 = CUTOFF_LENGTH*CUTOFF_LENGTH;
const PS::F64 CL6 = CL2*CL2*CL2;
const PS::F64 CL12 = CL6*CL6;
const PS::F64 C0 = - 4.0 * (1.0/CL12 - 1.0/CL6);
for (PS::S32 i = 0; i < ni; i++) {
force[i].force = 0.0;
force[i].potential = 0.0;
for (PS::S32 j = 0; j < nj; j++) {
if(epi[i].id == epj[j].id) continue;
PS::F64vec dq = epj[j].q - epi[i].q;
PS::F64 r2 = dq * dq;
PS::F64 r6 = r2*r2*r2;
PS::F64 r12 = r6 * r6;
if (r2 > CL2) continue;
PS::F64 df = (24.0 * r6 - 48.0) / (r6 * r6 * r2);
force[i].force += dq * df;
force[i].potential += (4.0 * (1.0 / r12 - 1.0 / r6) + C0)*0.5;
}
}
}
};
//------------------------------------------------------------------------
template<class Tpsys>
PS::F64
energy(const Tpsys &system){
PS::F64 e = 0.0;
const PS::S32 n = system.getNumberOfParticleLocal();
for(PS::S32 i = 0; i < n; i++) {
FPLJ a = system[i];
e += (a.p*a.p)*0.5;
e += a.potential;
}
return PS::Comm::getSum(e);
}
//------------------------------------------------------------------------
template<class Tpsys>
void
drift(Tpsys & system, const PS::F64 dt) {
const PS::S32 n = system.getNumberOfParticleLocal();
for (PS::S32 i = 0; i < n; i++) {
system[i].q += system[i].p * dt;
}
}
//------------------------------------------------------------------------
template<class Tpsys>
void
kick(Tpsys & system, const PS::F64 dt) {
const PS::S32 n = system.getNumberOfParticleLocal();
for (PS::S32 i = 0; i < n; i++) {
system[i].p += system[i].force * dt;
}
}
//------------------------------------------------------------------------
template<class Tpsys>
void
dump(std::ostream &os, const PS::F64 s_time, Tpsys &system){
const PS::S32 n = system.getNumberOfParticleLocal();
if (n == 0)return;
os << s_time << " ";
for (PS::S32 i = 0; i < n; i++) {
os << system[i].q.x << " ";
}
os << std::endl;
}
//------------------------------------------------------------------------
int
main(int argc, char **argv) {
PS::Initialize(argc, argv);
const int rank = PS::Comm::getRank();
const int procs = PS::Comm::getNumberOfProc();
PS::ParticleSystem<FPLJ> lj_system;
lj_system.initialize();
const PS::F64 L = 10;
PS::DomainInfo dinfo;
dinfo.initialize();
dinfo.setBoundaryCondition(PS::BOUNDARY_CONDITION_PERIODIC_XYZ);
dinfo.setPosRootDomain(PS::F64vec(0, 0, 0), PS::F64vec(L, L, L));
const int N = 2;
if (rank == 0){
lj_system.setNumberOfParticleLocal(N);
lj_system[0].id = 0;
lj_system[0].p = PS::F64vec(1.0, 0.0, 0.0);
lj_system[0].q = PS::F64vec(2.5, 5.0, 5.0);
lj_system[1].id = 1;
lj_system[1].p = PS::F64vec(-1.0, 0.0, 0.0);
lj_system[1].q = PS::F64vec(7.5, 5.0, 5.0);
}else{
lj_system.setNumberOfParticleLocal(0);
}
PS::TreeForForceShort<ForceLJ, EPLJ, EPLJ>::Gather tree_lj;
tree_lj.initialize(N);
const PS::F64 dt = 0.01;
PS::F64 s_time = 0.0;
const int LOOP = 1000;
dinfo.decomposeDomainAll(lj_system);
lj_system.exchangeParticle(dinfo);
char filename[256];
sprintf(filename,"trac%02d.dat",rank);
std::ofstream ofs(filename);
for(int i=0;i<LOOP;i++){
drift(lj_system, dt*0.5);
tree_lj.calcForceAllAndWriteBack(CalcForceLJ(), lj_system, dinfo);
kick(lj_system, dt);
drift(lj_system, dt*0.5);
dump(ofs, s_time, lj_system);
tree_lj.calcForceAllAndWriteBack(CalcForceLJ(), lj_system, dinfo);
PS::F64 e = energy(lj_system);
if (rank==0){
std::cout << s_time << " " << e << std::endl;
}
s_time += dt;
}
PS::Finalize();
}
//------------------------------------------------------------------------
<|endoftext|> |
<commit_before>// C++ source file - (C) 2003 Robert Osfield, released under the OSGPL.
// (C) 2005 Mike Weiblen http://mew.cx/ released under the OSGPL.
// Simple example using GLUT to create an OpenGL window and OSG for rendering.
// Derived from osgGLUTsimple.cpp and osgkeyboardmouse.cpp
#include <osgViewer/Viewer>
#include <osgViewer/StatsHandler>
#include <osgGA/TrackballManipulator>
#include <osgDB/ReadFile>
#include <FL/Fl.H>
#include <FL/Fl_Gl_Window.H>
#include <iostream>
class AdapterWidget : public Fl_Gl_Window
{
public:
AdapterWidget(int x, int y, int w, int h, const char *label=0);
virtual ~AdapterWidget() {}
osgViewer::GraphicsWindow* getGraphicsWindow() { return _gw.get(); }
const osgViewer::GraphicsWindow* getGraphicsWindow() const { return _gw.get(); }
virtual void resize(int x, int y, int w, int h);
protected:
virtual int handle(int event);
osg::ref_ptr<osgViewer::GraphicsWindowEmbedded> _gw;
};
AdapterWidget::AdapterWidget(int x, int y, int w, int h, const char *label):
Fl_Gl_Window(x, y, w, h, label)
{
_gw = new osgViewer::GraphicsWindowEmbedded(x,y,w,h);
}
void AdapterWidget::resize(int x, int y, int w, int h)
{
_gw->getEventQueue()->windowResize(x, y, w, h );
_gw->resized(x,y,w,h);
Fl_Gl_Window::resize(x,y,w,h);
}
int AdapterWidget::handle(int event)
{
switch(event){
case FL_PUSH:
_gw->getEventQueue()->mouseButtonPress(Fl::event_x(), Fl::event_y(), Fl::event_button());
return 1;
case FL_MOVE:
case FL_DRAG:
_gw->getEventQueue()->mouseMotion(Fl::event_x(), Fl::event_y());
return 1;
case FL_RELEASE:
_gw->getEventQueue()->mouseButtonRelease(Fl::event_x(), Fl::event_y(), Fl::event_button());
return 1;
case FL_KEYDOWN:
_gw->getEventQueue()->keyPress((osgGA::GUIEventAdapter::KeySymbol)Fl::event_key());
return 1;
case FL_KEYUP:
_gw->getEventQueue()->keyRelease((osgGA::GUIEventAdapter::KeySymbol)Fl::event_key());
return 1;
default:
// pass other events to the base class
return Fl_Gl_Window::handle(event);
}
}
void idle_cb()
{
Fl::redraw();
}
class ViewerFLTK : public osgViewer::Viewer, public AdapterWidget
{
public:
ViewerFLTK(int x, int y, int w, int h, const char *label=0):
AdapterWidget(x,y,w,h,label)
{
getCamera()->setViewport(new osg::Viewport(0,0,w,h));
getCamera()->setGraphicsContext(getGraphicsWindow());
setThreadingModel(osgViewer::Viewer::SingleThreaded);
}
protected:
virtual void draw() { frame(); }
};
int main( int argc, char **argv )
{
if (argc<2)
{
std::cout << argv[0] <<": requires filename argument." << std::endl;
return 1;
}
// load the scene.
osg::ref_ptr<osg::Node> loadedModel = osgDB::readNodeFile(argv[1]);
if (!loadedModel)
{
std::cout << argv[0] <<": No data loaded." << std::endl;
return 1;
}
ViewerFLTK viewerWindow(100,100,800,600);
viewerWindow.resizable(&viewerWindow);
viewerWindow.setSceneData(loadedModel.get());
viewerWindow.setCameraManipulator(new osgGA::TrackballManipulator);
viewerWindow.addEventHandler(new osgViewer::StatsHandler);
viewerWindow.show();
Fl::set_idle(idle_cb);
return Fl::run();
}
<commit_msg>Added CompositeViewer support into FLTK example<commit_after>// C++ source file - (C) 2003 Robert Osfield, released under the OSGPL.
// (C) 2005 Mike Weiblen http://mew.cx/ released under the OSGPL.
// Simple example using GLUT to create an OpenGL window and OSG for rendering.
// Derived from osgGLUTsimple.cpp and osgkeyboardmouse.cpp
#include <osgViewer/Viewer>
#include <osgViewer/CompositeViewer>
#include <osgViewer/StatsHandler>
#include <osgGA/TrackballManipulator>
#include <osgDB/ReadFile>
#include <FL/Fl.H>
#include <FL/Fl_Gl_Window.H>
#include <iostream>
class AdapterWidget : public Fl_Gl_Window
{
public:
AdapterWidget(int x, int y, int w, int h, const char *label=0);
virtual ~AdapterWidget() {}
osgViewer::GraphicsWindow* getGraphicsWindow() { return _gw.get(); }
const osgViewer::GraphicsWindow* getGraphicsWindow() const { return _gw.get(); }
virtual void resize(int x, int y, int w, int h);
protected:
virtual int handle(int event);
osg::ref_ptr<osgViewer::GraphicsWindowEmbedded> _gw;
};
AdapterWidget::AdapterWidget(int x, int y, int w, int h, const char *label):
Fl_Gl_Window(x, y, w, h, label)
{
_gw = new osgViewer::GraphicsWindowEmbedded(x,y,w,h);
}
void AdapterWidget::resize(int x, int y, int w, int h)
{
_gw->getEventQueue()->windowResize(x, y, w, h );
_gw->resized(x,y,w,h);
Fl_Gl_Window::resize(x,y,w,h);
}
int AdapterWidget::handle(int event)
{
switch(event){
case FL_PUSH:
_gw->getEventQueue()->mouseButtonPress(Fl::event_x(), Fl::event_y(), Fl::event_button());
return 1;
case FL_MOVE:
case FL_DRAG:
_gw->getEventQueue()->mouseMotion(Fl::event_x(), Fl::event_y());
return 1;
case FL_RELEASE:
_gw->getEventQueue()->mouseButtonRelease(Fl::event_x(), Fl::event_y(), Fl::event_button());
return 1;
case FL_KEYDOWN:
_gw->getEventQueue()->keyPress((osgGA::GUIEventAdapter::KeySymbol)Fl::event_key());
return 1;
case FL_KEYUP:
_gw->getEventQueue()->keyRelease((osgGA::GUIEventAdapter::KeySymbol)Fl::event_key());
return 1;
default:
// pass other events to the base class
return Fl_Gl_Window::handle(event);
}
}
void idle_cb()
{
Fl::redraw();
}
class ViewerFLTK : public osgViewer::Viewer, public AdapterWidget
{
public:
ViewerFLTK(int x, int y, int w, int h, const char *label=0):
AdapterWidget(x,y,w,h,label)
{
getCamera()->setViewport(new osg::Viewport(0,0,w,h));
getCamera()->setGraphicsContext(getGraphicsWindow());
setThreadingModel(osgViewer::Viewer::SingleThreaded);
}
protected:
virtual void draw() { frame(); }
};
class CompositeViewerFLTK : public osgViewer::CompositeViewer, public AdapterWidget
{
public:
CompositeViewerFLTK(int x, int y, int w, int h, const char *label=0):
AdapterWidget(x,y,w,h,label)
{
setThreadingModel(osgViewer::CompositeViewer::SingleThreaded);
}
protected:
virtual void draw() { frame(); }
};
int main( int argc, char **argv )
{
if (argc<2)
{
std::cout << argv[0] <<": requires filename argument." << std::endl;
return 1;
}
osg::ArgumentParser arguments(&argc, argv);
// load the scene.
osg::ref_ptr<osg::Node> loadedModel = osgDB::readNodeFiles(arguments);
if (!loadedModel)
{
std::cout << argv[0] <<": No data loaded." << std::endl;
return 1;
}
if (arguments.read("--CompositeViewer"))
{
unsigned int width = 1024;
unsigned int height = 800;
CompositeViewerFLTK viewerWindow(100,100,width,height);
viewerWindow.resizable(&viewerWindow);
{
osgViewer::View* view1 = new osgViewer::View;
view1->getCamera()->setGraphicsContext(viewerWindow.getGraphicsWindow());
view1->getCamera()->setProjectionMatrixAsPerspective(30.0f, static_cast<double>(width)/static_cast<double>(height/2), 1.0, 1000.0);
view1->getCamera()->setViewport(new osg::Viewport(0,0,width,height/2));
view1->setCameraManipulator(new osgGA::TrackballManipulator);
view1->setSceneData(loadedModel.get());
viewerWindow.addView(view1);
}
{
osgViewer::View* view2 = new osgViewer::View;
view2->getCamera()->setGraphicsContext(viewerWindow.getGraphicsWindow());
view2->getCamera()->setProjectionMatrixAsPerspective(30.0f, static_cast<double>(width)/static_cast<double>(height/2), 1.0, 1000.0);
view2->getCamera()->setViewport(new osg::Viewport(0,height/2,width,height/2));
view2->setCameraManipulator(new osgGA::TrackballManipulator);
view2->setSceneData(loadedModel.get());
viewerWindow.addView(view2);
}
viewerWindow.show();
Fl::set_idle(idle_cb);
return Fl::run();
}
else
{
ViewerFLTK viewerWindow(100,100,800,600);
viewerWindow.resizable(&viewerWindow);
viewerWindow.setSceneData(loadedModel.get());
viewerWindow.setCameraManipulator(new osgGA::TrackballManipulator);
viewerWindow.addEventHandler(new osgViewer::StatsHandler);
viewerWindow.show();
Fl::set_idle(idle_cb);
return Fl::run();
}
}
<|endoftext|> |
<commit_before>#include "Bullet.h"
#include "SceneHandler.h"
Bullet::Bullet()
{
m_position = Vector2(0, 0);
m_direction = Direction::UP;
m_2Drender = new aie::Renderer2D;
SceneHandler::bullets->push_back(*this);
}
// Vector2: Starting Position | Direction: Enum Bullet Movement Direction
Bullet::Bullet(Vector2 position, Direction direction)
{
m_direction = direction;
m_position = position;
m_2Drender = new aie::Renderer2D;
SceneHandler::bullets->push_back(*this);
}
Bullet::~Bullet()
{
//delete m_2Drender;
}
void Bullet::Update(const float deltaTime)
{
Vector2 velocity = BulletDirection();
velocity = (velocity * m_speed) * deltaTime;
m_position = m_position + velocity;
}
void Bullet::Draw()
{
m_2Drender->begin();
m_2Drender->drawBox(m_position.x, m_position.y, m_bulletWidth, m_bulletHeight);
m_2Drender->end();
}
Vector2 Bullet::GetPosition()
{
return m_position;
}
Direction Bullet::GetDirection()
{
return m_direction;
}
const Vector2 Bullet::BulletDirection()
{
// 1 = up | -1 = down
switch (m_direction)
{
case Direction::UP: return Vector2(0, 1);
case Direction::DOWN: return Vector2(0, -1);
}
}
<commit_msg>bullet update<commit_after>#include "Bullet.h"
#include "SceneHandler.h"
Bullet::Bullet()
{
m_position = Vector2(0, 0);
m_direction = Direction::UP;
m_2Drender = new aie::Renderer2D;
SceneHandler::bullets->push_back(*this);
}
// Vector2: Starting Position | Direction: Enum Bullet Movement Direction
Bullet::Bullet(Vector2 position, Direction direction)
{
m_direction = direction;
m_position = position;
m_2Drender = new aie::Renderer2D;
SceneHandler::bullets->push_back(*this);
}
Bullet::~Bullet()
{
//delete m_2Drender;
}
void Bullet::Update(const float deltaTime)
{
Vector2 velocity = BulletDirection();
velocity = (velocity * m_speed) * deltaTime;
m_position = m_position + velocity;
}
void Bullet::Draw()
{
m_2Drender->begin();
m_2Drender->drawBox(m_position.x, m_position.y, m_bulletWidth, m_bulletHeight);
m_2Drender->end();
}
Vector2 Bullet::GetPosition()
{
return m_position;
}
Direction Bullet::GetDirection()
{
return m_direction;
}
const Vector2 Bullet::BulletDirection()
{
// 1 = up | -1 = down
switch (m_direction)
{
case Direction::UP: return Vector2(0, 1);
case Direction::DOWN: return Vector2(0, -1);
default: return Vector2(0, 0);
}
}
<|endoftext|> |
<commit_before>#ifndef PROMETHEUS_VALUES_HH__
#define PROMETHEUS_VALUES_HH__
#include "output_formatter.hh"
#include <atomic>
#include <string>
#include <vector>
namespace prometheus {
extern const double kInf;
extern const std::vector<double> default_histogram_levels;
std::vector<double> histogram_levels(std::vector<double>&&);
std::vector<double> histogram_levels_powers_of(double base, double count);
namespace impl {
class BaseScalarValue {
// A base class used by the various scalar values (counter and gauges).
public:
BaseScalarValue() : value_(0) {}
~BaseScalarValue() {}
BaseScalarValue(BaseScalarValue const& rhs) : value_(rhs.value_.load()) {}
double value() const { return value_.load(std::memory_order_relaxed); }
template<typename... ContextParams>
void value_output(OutputFormatter& f, ContextParams const&... params) const {
f.addMetricValue(this->value_, params...);
}
protected:
std::atomic<double> value_;
};
class SetGaugeValue : public BaseScalarValue {
public:
void set(double value) { value_.store(value, std::memory_order_relaxed); }
const static std::string type_;
};
class IncDecGaugeValue : public BaseScalarValue {
public:
void inc(double value = 1.0);
void dec(double value = 1.0);
const static std::string type_;
};
class CounterValue : public BaseScalarValue {
public:
void inc(double value = 1.0);
const static std::string type_;
};
class HistogramValue {
public:
HistogramValue(std::vector<double> const& levels = default_histogram_levels);
~HistogramValue();
HistogramValue(HistogramValue const& rhs);
void record(double value);
static bool is_posinf(double d);
static std::vector<double> add_inf(std::vector<double> const&);
double value(double threshold = kInf) const;
template<typename... ContextParams>
void value_output(OutputFormatter& f, ContextParams const&... params) const {
auto it = values_.begin();
for (auto const& l : levels_) {
f.addMetricValue(*it, l, params...);
++it;
}
}
const static std::string type_;
private:
const std::vector<double> levels_;
std::vector<std::atomic<double>> values_;
};
} /* namespace impl */
} /* namespace prometheus */
#endif
<commit_msg>Add a safety check against improper usage of BaseScalarValue.<commit_after>#ifndef PROMETHEUS_VALUES_HH__
#define PROMETHEUS_VALUES_HH__
#include "output_formatter.hh"
#include <atomic>
#include <string>
#include <vector>
namespace prometheus {
extern const double kInf;
extern const std::vector<double> default_histogram_levels;
std::vector<double> histogram_levels(std::vector<double>&&);
std::vector<double> histogram_levels_powers_of(double base, double count);
namespace impl {
class BaseScalarValue {
// A base class used by the various scalar values (counter and gauges).
public:
BaseScalarValue() : value_(0) {
static_assert(sizeof(BaseScalarValue) == sizeof(std::atomic<double>),
"BaseScalarValue is not meant to have a vtable or to be used polymorphically.");
}
~BaseScalarValue() {}
BaseScalarValue(BaseScalarValue const& rhs) : value_(rhs.value_.load()) {}
double value() const { return value_.load(std::memory_order_relaxed); }
template<typename... ContextParams>
void value_output(OutputFormatter& f, ContextParams const&... params) const {
f.addMetricValue(this->value_, params...);
}
protected:
std::atomic<double> value_;
};
class SetGaugeValue : public BaseScalarValue {
public:
void set(double value) { value_.store(value, std::memory_order_relaxed); }
const static std::string type_;
};
class IncDecGaugeValue : public BaseScalarValue {
public:
void inc(double value = 1.0);
void dec(double value = 1.0);
const static std::string type_;
};
class CounterValue : public BaseScalarValue {
public:
void inc(double value = 1.0);
const static std::string type_;
};
class HistogramValue {
public:
HistogramValue(std::vector<double> const& levels = default_histogram_levels);
~HistogramValue();
HistogramValue(HistogramValue const& rhs);
void record(double value);
static bool is_posinf(double d);
static std::vector<double> add_inf(std::vector<double> const&);
double value(double threshold = kInf) const;
template<typename... ContextParams>
void value_output(OutputFormatter& f, ContextParams const&... params) const {
auto it = values_.begin();
for (auto const& l : levels_) {
f.addMetricValue(*it, l, params...);
++it;
}
}
const static std::string type_;
private:
const std::vector<double> levels_;
std::vector<std::atomic<double>> values_;
};
} /* namespace impl */
} /* namespace prometheus */
#endif
<|endoftext|> |
<commit_before>#include "error.hpp"
#include "Node.hpp"
#include <boost/algorithm/string/join.hpp>
#include <boost/exception/diagnostic_information.hpp>
namespace configure {
std::string error_string()
{ return error_string(std::current_exception()); }
static std::string what(std::exception_ptr const& e)
{
try { std::rethrow_exception(e); }
catch (std::exception const& err) { return err.what(); }
catch (...) { return "Error:"; }
std::abort();
}
std::string error_string(std::exception_ptr const& e, unsigned int indent)
{
using boost::get_error_info;
std::string padding(' ', indent);
std::string res = padding + what(e) + "\n";
try { std::rethrow_exception(e); }
catch (boost::exception const& e) {
if (auto ptr = get_error_info<error::path>(e))
res += padding + " Path: " + ptr->string() + "\n";
if (auto ptr = get_error_info<error::lua_function>(e))
res += padding + " Lua function: " + *ptr + "\n";
if (auto ptr = get_error_info<error::node>(e))
res += padding + " Node: " + (*ptr)->string() + "\n";
if (auto ptr = get_error_info<error::lua_traceback>(e))
{
res += padding + " Lua traceback:\n";
for (auto const& frame: *ptr)
{
if (frame.builtin &&frame.name.empty())
continue;
res += padding + " ";
if (frame.builtin)
res += "{builtin}: ";
else
res += frame.source.string() + ":" +
std::to_string(frame.current_line) + ": ";
res += "in ";
if (!frame.kind.empty())
res += frame.kind + " ";
if (frame.kind != "method")
res += "function ";
if (!frame.name.empty())
res += frame.name + "() ";
if (!frame.builtin)
res += "defined at " + frame.source.filename().string() + ":" +
std::to_string(frame.first_function_line);
res += "\n";
}
}
if (auto ptr = get_error_info<error::command>(e))
res += padding + " Command: " + boost::join(*ptr, " ");
if (auto ptr = get_error_info<error::nested>(e))
res += padding + " Initial error: " + error_string(*ptr, indent + 2);
}
catch (...) {}
return res;
}
}
<commit_msg>Remove extra whitespace at the end of the error string,.<commit_after>#include "error.hpp"
#include "Node.hpp"
#include <boost/algorithm/string/join.hpp>
#include <boost/algorithm/string/trim.hpp>
#include <boost/exception/diagnostic_information.hpp>
namespace configure {
std::string error_string()
{ return error_string(std::current_exception()); }
static std::string what(std::exception_ptr const& e)
{
try { std::rethrow_exception(e); }
catch (std::exception const& err) { return err.what(); }
catch (...) { return "Error:"; }
std::abort();
}
std::string error_string(std::exception_ptr const& e, unsigned int indent)
{
using boost::get_error_info;
std::string padding(' ', indent);
std::string res = padding + what(e) + "\n";
try { std::rethrow_exception(e); }
catch (boost::exception const& e) {
if (auto ptr = get_error_info<error::path>(e))
res += padding + " Path: " + ptr->string() + "\n";
if (auto ptr = get_error_info<error::lua_function>(e))
res += padding + " Lua function: " + *ptr + "\n";
if (auto ptr = get_error_info<error::node>(e))
res += padding + " Node: " + (*ptr)->string() + "\n";
if (auto ptr = get_error_info<error::lua_traceback>(e))
{
res += padding + " Lua traceback:\n";
for (auto const& frame: *ptr)
{
if (frame.builtin &&frame.name.empty())
continue;
res += padding + " ";
if (frame.builtin)
res += "{builtin}: ";
else
res += frame.source.string() + ":" +
std::to_string(frame.current_line) + ": ";
res += "in ";
if (!frame.kind.empty())
res += frame.kind + " ";
if (frame.kind != "method")
res += "function ";
if (!frame.name.empty())
res += frame.name + "() ";
if (!frame.builtin)
res += "defined at " + frame.source.filename().string() + ":" +
std::to_string(frame.first_function_line);
res += "\n";
}
}
if (auto ptr = get_error_info<error::command>(e))
res += padding + " Command: " + boost::join(*ptr, " ");
if (auto ptr = get_error_info<error::nested>(e))
res += padding + " Initial error: " + error_string(*ptr, indent + 2);
}
catch (...) {}
return boost::trim_right_copy(res);
}
}
<|endoftext|> |
<commit_before>// To regenerate this list of includes run the following command from skia/include:
//
// find core effects pathops -maxdepth 1 -name "*.h" | sed "s#^[^\/]*\/##g" | sed "s/\(.*\)/#include \"\1\"/" | sort
//
#include "Sk1DPathEffect.h"
#include "Sk2DPathEffect.h"
#include "SkAdvancedTypefaceMetrics.h"
#include "SkAlphaThresholdFilter.h"
#include "SkAnnotation.h"
#include "SkArithmeticMode.h"
#include "SkAvoidXfermode.h"
#include "SkBBHFactory.h"
#include "SkBitmapDevice.h"
#include "SkBitmap.h"
#include "SkBitmapSource.h"
#include "SkBlitRow.h"
#include "SkBlurDrawLooper.h"
#include "SkBlurImageFilter.h"
#include "SkBlurMaskFilter.h"
#include "SkBlurTypes.h"
#include "SkCanvas.h"
#include "SkChecksum.h"
#include "SkChunkAlloc.h"
#include "SkClipStack.h"
#include "SkColorFilter.h"
#include "SkColorFilterImageFilter.h"
#include "SkColor.h"
#include "SkColorMatrixFilter.h"
#include "SkColorMatrix.h"
#include "SkColorPriv.h"
#include "SkColorShader.h"
#include "SkColorTable.h"
#include "SkComposeImageFilter.h"
#include "SkComposeShader.h"
#include "SkCornerPathEffect.h"
#include "SkDashPathEffect.h"
#include "SkData.h"
#include "SkDataTable.h"
#include "SkDeque.h"
#include "SkDevice.h"
#include "SkDeviceProperties.h"
#include "SkDiscretePathEffect.h"
#include "SkDisplacementMapEffect.h"
#include "SkDither.h"
#include "SkDocument.h"
#include "SkDrawExtraPathEffect.h"
#include "SkDrawFilter.h"
#include "SkDraw.h"
#include "SkDrawLooper.h"
#include "SkDropShadowImageFilter.h"
#include "SkDynamicAnnotations.h"
#include "SkEmbossMaskFilter.h"
#include "SkEmptyShader.h"
#include "SkEndian.h"
#include "SkError.h"
#include "SkFixed.h"
#include "SkFlate.h"
#include "SkFlattenableBuffers.h"
#include "SkFlattenable.h"
#include "SkFlattenableSerialization.h"
#include "SkFloatBits.h"
#include "SkFloatingPoint.h"
#include "SkFont.h"
#include "SkFontHost.h"
#include "SkFontLCDConfig.h"
#include "SkGeometry.h"
#include "SkGradientShader.h"
#include "SkGraphics.h"
#include "SkImageDecoder.h"
#include "SkImageEncoder.h"
#include "SkImageFilter.h"
#include "SkImageGenerator.h"
#include "SkImage.h"
#include "SkImageInfo.h"
#include "SkInstCnt.h"
#include "SkLayerDrawLooper.h"
#include "SkLayerRasterizer.h"
#include "SkLerpXfermode.h"
#include "SkLightingImageFilter.h"
#include "SkLineClipper.h"
#include "SkLumaColorFilter.h"
#include "SkMagnifierImageFilter.h"
#include "SkMallocPixelRef.h"
#include "SkMaskFilter.h"
#include "SkMask.h"
#include "SkMath.h"
#include "SkMatrixConvolutionImageFilter.h"
#include "SkMatrix.h"
#include "SkMatrixImageFilter.h"
#include "SkMergeImageFilter.h"
#include "SkMetaData.h"
#include "SkMorphologyImageFilter.h"
#include "SkOffsetImageFilter.h"
#include "SkOnce.h"
#include "SkOSFile.h"
#include "SkPackBits.h"
#include "SkPaintFlagsDrawFilter.h"
#include "SkPaint.h"
#include "SkPaintOptionsAndroid.h"
#include "SkPathEffect.h"
#include "SkPath.h"
#include "SkPathMeasure.h"
#include "SkPathOps.h"
#include "SkPathRef.h"
#include "SkPerlinNoiseShader.h"
#include "SkPicture.h"
#include "SkPictureImageFilter.h"
#include "SkPictureRecorder.h"
#include "SkPixelRef.h"
#include "SkPixelXorXfermode.h"
#include "SkPoint.h"
#include "SkPorterDuff.h"
#include "SkPostConfig.h"
#include "SkPreConfig.h"
#include "SkRasterizer.h"
#include "SkReadBuffer.h"
#include "SkReader32.h"
#include "SkRect.h"
#include "SkRectShaderImageFilter.h"
#include "SkRefCnt.h"
#include "SkRegion.h"
#include "SkRRect.h"
#include "SkScalar.h"
#include "SkShader.h"
#include "SkSize.h"
#include "SkStippleMaskFilter.h"
#include "SkStream.h"
#include "SkString.h"
#include "SkStringUtils.h"
#include "SkStrokeRec.h"
#include "SkSurface.h"
#include "SkTableColorFilter.h"
#include "SkTableMaskFilter.h"
#include "SkTArray.h"
#include "SkTDArray.h"
#include "SkTDict.h"
#include "SkTDStack.h"
#include "SkTemplates.h"
#include "SkTestImageFilters.h"
#include "SkThread.h"
#include "SkTileImageFilter.h"
#include "SkTime.h"
#include "SkTInternalLList.h"
#include "SkTLazy.h"
#include "SkTransparentShader.h"
#include "SkTRegistry.h"
#include "SkTSearch.h"
#include "SkTypeface.h"
#include "SkTypes.h"
#include "SkUnPreMultiply.h"
#include "SkUtils.h"
#include "SkVertState.h"
#include "SkWeakRefCnt.h"
#include "SkWriteBuffer.h"
#include "SkWriter32.h"
#include "SkXfermode.h"
#include "SkXfermodeImageFilter.h"
SkBitmap source;
{{.Code}}
<commit_msg>remove SkStippleMaskFilter - no external clients<commit_after>// To regenerate this list of includes run the following command from skia/include:
//
// find core effects pathops -maxdepth 1 -name "*.h" | sed "s#^[^\/]*\/##g" | sed "s/\(.*\)/#include \"\1\"/" | sort
//
#include "Sk1DPathEffect.h"
#include "Sk2DPathEffect.h"
#include "SkAdvancedTypefaceMetrics.h"
#include "SkAlphaThresholdFilter.h"
#include "SkAnnotation.h"
#include "SkArithmeticMode.h"
#include "SkAvoidXfermode.h"
#include "SkBBHFactory.h"
#include "SkBitmapDevice.h"
#include "SkBitmap.h"
#include "SkBitmapSource.h"
#include "SkBlitRow.h"
#include "SkBlurDrawLooper.h"
#include "SkBlurImageFilter.h"
#include "SkBlurMaskFilter.h"
#include "SkBlurTypes.h"
#include "SkCanvas.h"
#include "SkChecksum.h"
#include "SkChunkAlloc.h"
#include "SkClipStack.h"
#include "SkColorFilter.h"
#include "SkColorFilterImageFilter.h"
#include "SkColor.h"
#include "SkColorMatrixFilter.h"
#include "SkColorMatrix.h"
#include "SkColorPriv.h"
#include "SkColorShader.h"
#include "SkColorTable.h"
#include "SkComposeImageFilter.h"
#include "SkComposeShader.h"
#include "SkCornerPathEffect.h"
#include "SkDashPathEffect.h"
#include "SkData.h"
#include "SkDataTable.h"
#include "SkDeque.h"
#include "SkDevice.h"
#include "SkDeviceProperties.h"
#include "SkDiscretePathEffect.h"
#include "SkDisplacementMapEffect.h"
#include "SkDither.h"
#include "SkDocument.h"
#include "SkDrawExtraPathEffect.h"
#include "SkDrawFilter.h"
#include "SkDraw.h"
#include "SkDrawLooper.h"
#include "SkDropShadowImageFilter.h"
#include "SkDynamicAnnotations.h"
#include "SkEmbossMaskFilter.h"
#include "SkEmptyShader.h"
#include "SkEndian.h"
#include "SkError.h"
#include "SkFixed.h"
#include "SkFlate.h"
#include "SkFlattenableBuffers.h"
#include "SkFlattenable.h"
#include "SkFlattenableSerialization.h"
#include "SkFloatBits.h"
#include "SkFloatingPoint.h"
#include "SkFont.h"
#include "SkFontHost.h"
#include "SkFontLCDConfig.h"
#include "SkGeometry.h"
#include "SkGradientShader.h"
#include "SkGraphics.h"
#include "SkImageDecoder.h"
#include "SkImageEncoder.h"
#include "SkImageFilter.h"
#include "SkImageGenerator.h"
#include "SkImage.h"
#include "SkImageInfo.h"
#include "SkInstCnt.h"
#include "SkLayerDrawLooper.h"
#include "SkLayerRasterizer.h"
#include "SkLerpXfermode.h"
#include "SkLightingImageFilter.h"
#include "SkLineClipper.h"
#include "SkLumaColorFilter.h"
#include "SkMagnifierImageFilter.h"
#include "SkMallocPixelRef.h"
#include "SkMaskFilter.h"
#include "SkMask.h"
#include "SkMath.h"
#include "SkMatrixConvolutionImageFilter.h"
#include "SkMatrix.h"
#include "SkMatrixImageFilter.h"
#include "SkMergeImageFilter.h"
#include "SkMetaData.h"
#include "SkMorphologyImageFilter.h"
#include "SkOffsetImageFilter.h"
#include "SkOnce.h"
#include "SkOSFile.h"
#include "SkPackBits.h"
#include "SkPaintFlagsDrawFilter.h"
#include "SkPaint.h"
#include "SkPaintOptionsAndroid.h"
#include "SkPathEffect.h"
#include "SkPath.h"
#include "SkPathMeasure.h"
#include "SkPathOps.h"
#include "SkPathRef.h"
#include "SkPerlinNoiseShader.h"
#include "SkPicture.h"
#include "SkPictureImageFilter.h"
#include "SkPictureRecorder.h"
#include "SkPixelRef.h"
#include "SkPixelXorXfermode.h"
#include "SkPoint.h"
#include "SkPorterDuff.h"
#include "SkPostConfig.h"
#include "SkPreConfig.h"
#include "SkRasterizer.h"
#include "SkReadBuffer.h"
#include "SkReader32.h"
#include "SkRect.h"
#include "SkRectShaderImageFilter.h"
#include "SkRefCnt.h"
#include "SkRegion.h"
#include "SkRRect.h"
#include "SkScalar.h"
#include "SkShader.h"
#include "SkSize.h"
#include "SkStream.h"
#include "SkString.h"
#include "SkStringUtils.h"
#include "SkStrokeRec.h"
#include "SkSurface.h"
#include "SkTableColorFilter.h"
#include "SkTableMaskFilter.h"
#include "SkTArray.h"
#include "SkTDArray.h"
#include "SkTDict.h"
#include "SkTDStack.h"
#include "SkTemplates.h"
#include "SkTestImageFilters.h"
#include "SkThread.h"
#include "SkTileImageFilter.h"
#include "SkTime.h"
#include "SkTInternalLList.h"
#include "SkTLazy.h"
#include "SkTransparentShader.h"
#include "SkTRegistry.h"
#include "SkTSearch.h"
#include "SkTypeface.h"
#include "SkTypes.h"
#include "SkUnPreMultiply.h"
#include "SkUtils.h"
#include "SkVertState.h"
#include "SkWeakRefCnt.h"
#include "SkWriteBuffer.h"
#include "SkWriter32.h"
#include "SkXfermode.h"
#include "SkXfermodeImageFilter.h"
SkBitmap source;
{{.Code}}
<|endoftext|> |
<commit_before>/*=========================================================================
*
* Copyright Insight Software Consortium
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0.txt
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*=========================================================================*/
#include "itkCudaDataManager.h"
#include <itksys/SystemTools.hxx>
namespace itk
{
// constructor
CudaDataManager::CudaDataManager()
{
m_ContextManager = CudaContextManager::GetInstance();
// Creating the context in the constructor allows avoiding a memory leak.
// However, the cuda data manager is created even if there is no use of CUDA
// software and sometimes one compiles RTK with CUDA but wants to use it
// without CUDA. So if the context pointer is NULL, which indicates that there
// is no CUDA device available, we just do not set the context (SR). This fixes
// the problem reported here:
// http://public.kitware.com/pipermail/rtk-users/2015-July/000570.html
CUcontext *ctx = m_ContextManager->GetCurrentContext();
if(ctx)
CUDA_CHECK(cuCtxSetCurrent(*ctx));
m_CPUBuffer = NULL;
m_GPUBuffer = GPUMemPointer::New();
this->Initialize();
m_ReleaseDirtyGPUBuffer = true;
std::string relString;
if( itksys::SystemTools::GetEnv("ITK_RELEASE_DIRTY_GPU_BUFFERS",relString) &&
( itksys::SystemTools::LowerCase(relString) == "false" ||
atoi(relString.c_str()) != 0 ) )
{
#ifdef VERBOSE
std::cout << "Releasing dirty GPU buffer" << std::endl;
#endif
m_ReleaseDirtyGPUBuffer = false;
}
}
CudaDataManager::~CudaDataManager()
{
m_GPUBuffer = NULL;
CudaContextManager::DestroyInstance();
}
void CudaDataManager::SetBufferSize(size_t num)
{
m_BufferSize = num;
}
void CudaDataManager::SetBufferFlag(int flags)
{
m_MemFlags = flags;
}
void CudaDataManager::Allocate()
{
if (m_BufferSize > 0 && m_GPUBuffer->GetBufferSize() != m_BufferSize)
{
m_GPUBuffer->Allocate(m_BufferSize);
m_IsGPUBufferDirty = true;
}
}
void CudaDataManager::Free()
{
m_Mutex.lock();
if (m_GPUBuffer->GetBufferSize() > 0)
{
m_GPUBuffer->Free();
m_IsGPUBufferDirty = true;
}
m_Mutex.unlock();
}
void CudaDataManager::SetCPUBufferPointer(void* ptr)
{
m_CPUBuffer = ptr;
}
void CudaDataManager::SetCPUDirtyFlag(bool isDirty)
{
m_IsCPUBufferDirty = isDirty;
}
void CudaDataManager::SetGPUDirtyFlag(bool isDirty)
{
m_IsGPUBufferDirty = isDirty;
if(isDirty && m_ReleaseDirtyGPUBuffer)
this->Free();
}
void CudaDataManager::SetGPUBufferDirty()
{
this->UpdateCPUBuffer();
m_IsGPUBufferDirty = true;
if(m_ReleaseDirtyGPUBuffer)
this->Free();
}
void CudaDataManager::SetCPUBufferDirty()
{
this->UpdateGPUBuffer();
m_IsCPUBufferDirty = true;
}
void CudaDataManager::UpdateCPUBuffer()
{
m_Mutex.lock();
if(m_IsGPUBufferDirty)
{
m_IsCPUBufferDirty = false;
}
else if(m_IsCPUBufferDirty && m_GPUBuffer && m_CPUBuffer)
{
#ifdef VERBOSE
std::cout << this << "::UpdateCPUBuffer GPU->CPU data copy " << m_GPUBuffer->GetPointer() << "->" << m_CPUBuffer << " : " << m_BufferSize << std::endl;
#endif
CUDA_CHECK(cuCtxSetCurrent(*(this->m_ContextManager->GetCurrentContext()))); // This is necessary when running multithread to bind the host CPU thread to the right context
CUDA_CHECK(cudaMemcpy(m_CPUBuffer, m_GPUBuffer->GetPointer(), m_BufferSize, cudaMemcpyDeviceToHost));
m_IsCPUBufferDirty = false;
}
m_Mutex.unlock();
}
void CudaDataManager::UpdateGPUBuffer()
{
m_Mutex.lock();
if (m_IsGPUBufferDirty && m_GPUBuffer)
{
this->Allocate(); // do the allocation
if(!m_IsCPUBufferDirty && m_CPUBuffer)
{
#ifdef VERBOSE
std::cout << this << "::UpdateGPUBuffer CPU->GPU data copy " << m_CPUBuffer << "->" << m_GPUBuffer->GetPointer() << " : " << m_BufferSize << std::endl;
#endif
CUDA_CHECK(cuCtxSetCurrent(*(this->m_ContextManager->GetCurrentContext()))); // This is necessary when running multithread to bind the host CPU thread to the right context
CUDA_CHECK(cudaMemcpy(m_GPUBuffer->GetPointer(), m_CPUBuffer, m_BufferSize, cudaMemcpyHostToDevice));
}
m_IsGPUBufferDirty = false;
}
m_Mutex.unlock();
}
void* CudaDataManager::GetGPUBufferPointer()
{
SetCPUBufferDirty();
return m_GPUBuffer->GetPointerPtr();
}
void* CudaDataManager::GetCPUBufferPointer()
{
SetGPUBufferDirty();
return m_CPUBuffer;
}
bool CudaDataManager::Update()
{
if (m_IsGPUBufferDirty && m_IsCPUBufferDirty)
{
itkExceptionMacro("Cannot make up-to-date buffer because both CPU and GPU buffers are dirty");
return false;
}
this->UpdateGPUBuffer();
this->UpdateCPUBuffer();
m_IsGPUBufferDirty = m_IsCPUBufferDirty = false;
return true;
}
void CudaDataManager::Graft(const CudaDataManager* data)
{
if (data)
{
m_BufferSize = data->m_BufferSize;
m_ContextManager = data->m_ContextManager;
m_GPUBuffer = data->m_GPUBuffer;
m_CPUBuffer = data->m_CPUBuffer;
m_IsCPUBufferDirty = data->m_IsCPUBufferDirty;
m_IsGPUBufferDirty = data->m_IsGPUBufferDirty;
}
}
void CudaDataManager::Initialize()
{
m_BufferSize = 0;
m_CPUBuffer = NULL;
m_MemFlags = 0; // default flag
m_IsGPUBufferDirty = false;
m_IsCPUBufferDirty = false;
}
void CudaDataManager::PrintSelf(std::ostream & os, Indent indent) const
{
os << indent << "CudaDataManager (" << this << ")" << std::endl;
os << indent << "m_BufferSize: " << m_BufferSize << std::endl;
os << indent << "m_IsGPUBufferDirty: " << m_IsGPUBufferDirty << std::endl;
os << indent << "m_GPUBuffer: " << m_GPUBuffer << std::endl;
os << indent << "m_IsCPUBufferDirty: " << m_IsCPUBufferDirty << std::endl;
os << indent << "m_CPUBuffer: " << m_CPUBuffer << std::endl;
}
} // namespace itk
<commit_msg>BUG: part of the CUDA data manager was not thread safe<commit_after>/*=========================================================================
*
* Copyright Insight Software Consortium
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0.txt
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*=========================================================================*/
#include "itkCudaDataManager.h"
#include <itksys/SystemTools.hxx>
namespace itk
{
// constructor
CudaDataManager::CudaDataManager()
{
m_ContextManager = CudaContextManager::GetInstance();
// Creating the context in the constructor allows avoiding a memory leak.
// However, the cuda data manager is created even if there is no use of CUDA
// software and sometimes one compiles RTK with CUDA but wants to use it
// without CUDA. So if the context pointer is NULL, which indicates that there
// is no CUDA device available, we just do not set the context (SR). This fixes
// the problem reported here:
// http://public.kitware.com/pipermail/rtk-users/2015-July/000570.html
CUcontext *ctx = m_ContextManager->GetCurrentContext();
if(ctx)
CUDA_CHECK(cuCtxSetCurrent(*ctx));
m_CPUBuffer = NULL;
m_GPUBuffer = GPUMemPointer::New();
this->Initialize();
m_ReleaseDirtyGPUBuffer = true;
std::string relString;
if( itksys::SystemTools::GetEnv("ITK_RELEASE_DIRTY_GPU_BUFFERS",relString) &&
( itksys::SystemTools::LowerCase(relString) == "false" ||
atoi(relString.c_str()) != 0 ) )
{
#ifdef VERBOSE
std::cout << "Releasing dirty GPU buffer" << std::endl;
#endif
m_ReleaseDirtyGPUBuffer = false;
}
}
CudaDataManager::~CudaDataManager()
{
m_GPUBuffer = NULL;
CudaContextManager::DestroyInstance();
}
void CudaDataManager::SetBufferSize(size_t num)
{
m_BufferSize = num;
}
void CudaDataManager::SetBufferFlag(int flags)
{
m_MemFlags = flags;
}
void CudaDataManager::Allocate()
{
if (m_BufferSize > 0 && m_GPUBuffer->GetBufferSize() != m_BufferSize)
{
m_GPUBuffer->Allocate(m_BufferSize);
m_IsGPUBufferDirty = true;
}
}
void CudaDataManager::Free()
{
std::string exceptionDetails;
bool exceptionOccured = false;
m_Mutex.lock();
if (m_GPUBuffer->GetBufferSize() > 0)
{
try
{
CUDA_CHECK(cuCtxSetCurrent(*(this->m_ContextManager->GetCurrentContext()))); // This is necessary when running multithread to bind the host CPU thread to the right context
m_GPUBuffer->Free();
}
catch(itk::ExceptionObject &e)
{
exceptionOccured = true;
exceptionDetails = e.what();
}
m_IsGPUBufferDirty = true;
}
m_Mutex.unlock();
if( exceptionOccured )
{
if( exceptionDetails.empty() )
{
itkExceptionMacro("Exception occurred during CudaDataManager::Free");
}
else
{
itkExceptionMacro(<< "Exception occurred during CudaDataManager::Free" << std::endl << exceptionDetails);
}
}
}
void CudaDataManager::SetCPUBufferPointer(void* ptr)
{
m_CPUBuffer = ptr;
}
void CudaDataManager::SetCPUDirtyFlag(bool isDirty)
{
m_IsCPUBufferDirty = isDirty;
}
void CudaDataManager::SetGPUDirtyFlag(bool isDirty)
{
m_IsGPUBufferDirty = isDirty;
if(isDirty && m_ReleaseDirtyGPUBuffer)
this->Free();
}
void CudaDataManager::SetGPUBufferDirty()
{
this->UpdateCPUBuffer();
m_IsGPUBufferDirty = true;
if(m_ReleaseDirtyGPUBuffer)
this->Free();
}
void CudaDataManager::SetCPUBufferDirty()
{
this->UpdateGPUBuffer();
m_IsCPUBufferDirty = true;
}
void CudaDataManager::UpdateCPUBuffer()
{
std::string exceptionDetails;
bool exceptionOccured = false;
m_Mutex.lock();
if(m_IsGPUBufferDirty)
{
m_IsCPUBufferDirty = false;
}
else if(m_IsCPUBufferDirty && m_GPUBuffer && m_CPUBuffer)
{
try
{
#ifdef VERBOSE
std::cout << this << "::UpdateCPUBuffer GPU->CPU data copy " << m_GPUBuffer->GetPointer() << "->" << m_CPUBuffer << " : " << m_BufferSize << std::endl;
#endif
CUDA_CHECK(cuCtxSetCurrent(*(this->m_ContextManager->GetCurrentContext()))); // This is necessary when running multithread to bind the host CPU thread to the right context
CUDA_CHECK(cudaMemcpy(m_CPUBuffer, m_GPUBuffer->GetPointer(), m_BufferSize, cudaMemcpyDeviceToHost));
m_IsCPUBufferDirty = false;
}
catch(itk::ExceptionObject &e)
{
exceptionOccured = true;
exceptionDetails = e.what();
}
}
m_Mutex.unlock();
if( exceptionOccured )
{
if( exceptionDetails.empty() )
{
itkExceptionMacro("Exception occurred during CudaDataManager::UpdateCPUBuffer");
}
else
{
itkExceptionMacro(<< "Exception occurred during CudaDataManager::UpdateCPUBuffer" << std::endl << exceptionDetails);
}
}
}
void CudaDataManager::UpdateGPUBuffer()
{
m_Mutex.lock();
if (m_IsGPUBufferDirty && m_GPUBuffer)
{
this->Allocate(); // do the allocation
if(!m_IsCPUBufferDirty && m_CPUBuffer)
{
#ifdef VERBOSE
std::cout << this << "::UpdateGPUBuffer CPU->GPU data copy " << m_CPUBuffer << "->" << m_GPUBuffer->GetPointer() << " : " << m_BufferSize << std::endl;
#endif
CUDA_CHECK(cuCtxSetCurrent(*(this->m_ContextManager->GetCurrentContext()))); // This is necessary when running multithread to bind the host CPU thread to the right context
CUDA_CHECK(cudaMemcpy(m_GPUBuffer->GetPointer(), m_CPUBuffer, m_BufferSize, cudaMemcpyHostToDevice));
}
m_IsGPUBufferDirty = false;
}
m_Mutex.unlock();
}
void* CudaDataManager::GetGPUBufferPointer()
{
SetCPUBufferDirty();
return m_GPUBuffer->GetPointerPtr();
}
void* CudaDataManager::GetCPUBufferPointer()
{
SetGPUBufferDirty();
return m_CPUBuffer;
}
bool CudaDataManager::Update()
{
if (m_IsGPUBufferDirty && m_IsCPUBufferDirty)
{
itkExceptionMacro("Cannot make up-to-date buffer because both CPU and GPU buffers are dirty");
return false;
}
this->UpdateGPUBuffer();
this->UpdateCPUBuffer();
m_IsGPUBufferDirty = m_IsCPUBufferDirty = false;
return true;
}
void CudaDataManager::Graft(const CudaDataManager* data)
{
if (data)
{
m_BufferSize = data->m_BufferSize;
m_ContextManager = data->m_ContextManager;
m_GPUBuffer = data->m_GPUBuffer;
m_CPUBuffer = data->m_CPUBuffer;
m_IsCPUBufferDirty = data->m_IsCPUBufferDirty;
m_IsGPUBufferDirty = data->m_IsGPUBufferDirty;
}
}
void CudaDataManager::Initialize()
{
m_BufferSize = 0;
m_CPUBuffer = NULL;
m_MemFlags = 0; // default flag
m_IsGPUBufferDirty = false;
m_IsCPUBufferDirty = false;
}
void CudaDataManager::PrintSelf(std::ostream & os, Indent indent) const
{
os << indent << "CudaDataManager (" << this << ")" << std::endl;
os << indent << "m_BufferSize: " << m_BufferSize << std::endl;
os << indent << "m_IsGPUBufferDirty: " << m_IsGPUBufferDirty << std::endl;
os << indent << "m_GPUBuffer: " << m_GPUBuffer << std::endl;
os << indent << "m_IsCPUBufferDirty: " << m_IsCPUBufferDirty << std::endl;
os << indent << "m_CPUBuffer: " << m_CPUBuffer << std::endl;
}
} // namespace itk
<|endoftext|> |
<commit_before>/*
Copyright (c) 2006, Arvid Norberg
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions
are met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in
the documentation and/or other materials provided with the distribution.
* Neither the name of the author nor the names of its
contributors may be used to endorse or promote products derived
from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
POSSIBILITY OF SUCH DAMAGE.
*/
#include "libtorrent/entry.hpp"
#include "libtorrent/bencode.hpp"
#include "libtorrent/torrent_info.hpp"
#include "libtorrent/file.hpp"
#include "libtorrent/storage.hpp"
#include "libtorrent/hasher.hpp"
#include "libtorrent/create_torrent.hpp"
#include "libtorrent/file.hpp"
#include <boost/bind.hpp>
using namespace libtorrent;
// do not include files and folders whose
// name starts with a .
bool file_filter(std::string const& f)
{
if (filename(f)[0] == '.') return false;
fprintf(stderr, "%s\n", f.c_str());
return true;
}
void print_progress(int i, int num)
{
fprintf(stderr, "\r%d/%d", i+1, num);
}
void print_usage()
{
fputs("usage: make_torrent FILE [OPTIONS]\n"
"\n"
"Generates a torrent file from the specified file\n"
"or directory and writes it to standard out\n\n"
"OPTIONS:\n"
"-m file generate a merkle hash tree torrent.\n"
" merkle torrents require client support\n"
" the resulting full merkle tree is written to\n"
" the specified file\n"
"-f include sha-1 file hashes in the torrent\n"
" this helps supporting mixing sources from\n"
" other networks\n"
"-w url adds a web seed to the torrent with\n"
" the specified url\n"
"-t url adds the specified tracker to the\n"
" torrent\n"
"-p bytes enables padding files. Files larger\n"
" than bytes will be piece-aligned\n"
"-s bytes specifies a piece size for the torrent\n"
" This has to be a multiple of 16 kiB\n"
"-l Don't follow symlinks, instead encode them as\n"
" links in the torrent file\n"
"-o file specifies the output filename of the torrent file\n"
" If this is not specified, the torrent file is\n"
" printed to the standard out, except on windows\n"
" where the filename defaults to a.torrent\n"
, stderr);
}
int main(int argc, char* argv[])
{
using namespace libtorrent;
char const* creator_str = "libtorrent";
if (argc < 2)
{
print_usage();
return 1;
}
#ifndef BOOST_NO_EXCEPTIONS
try
{
#endif
std::vector<std::string> web_seeds;
std::vector<std::string> trackers;
int pad_file_limit = -1;
int piece_size = 0;
int flags = 0;
std::string outfile;
std::string merklefile;
#ifdef TORRENT_WINDOWS
// don't ever write binary data to the console on windows
// it will just be interpreted as text and corrupted
outfile = "a.torrent";
#endif
for (int i = 2; i < argc; ++i)
{
if (argv[i][0] != '-')
{
print_usage();
return 1;
}
switch (argv[i][1])
{
case 'w':
++i;
web_seeds.push_back(argv[i]);
break;
case 't':
++i;
trackers.push_back(argv[i]);
break;
case 'p':
++i;
pad_file_limit = atoi(argv[i]);
flags |= create_torrent::optimize;
break;
case 's':
++i;
piece_size = atoi(argv[i]);
break;
case 'm':
++i;
merklefile = argv[i];
flags |= create_torrent::merkle;
break;
case 'o':
++i;
outfile = argv[i];
break;
case 'f':
flags |= create_torrent::calculate_file_hashes;
break;
case 'l':
flags |= create_torrent::symlinks;
break;
default:
print_usage();
return 1;
}
}
file_storage fs;
file_pool fp;
std::string full_path = libtorrent::complete(argv[1]);
add_files(fs, full_path, file_filter, flags);
if (fs.num_files() == 0)
{
fputs("no files specified.\n", stderr);
return 1;
}
create_torrent t(fs, piece_size, pad_file_limit, flags);
for (std::vector<std::string>::iterator i = trackers.begin()
, end(trackers.end()); i != end; ++i)
t.add_tracker(*i);
for (std::vector<std::string>::iterator i = web_seeds.begin()
, end(web_seeds.end()); i != end; ++i)
t.add_url_seed(*i);
error_code ec;
set_piece_hashes(t, parent_path(full_path)
, boost::bind(&print_progress, _1, t.num_pieces()), ec);
if (ec)
{
fprintf(stderr, "%s\n", ec.message().c_str());
return 1;
}
fprintf(stderr, "\n");
t.set_creator(creator_str);
// create the torrent and print it to stdout
std::vector<char> torrent;
bencode(back_inserter(torrent), t.generate());
FILE* output = stdout;
if (!outfile.empty())
output = fopen(outfile.c_str(), "wb+");
fwrite(&torrent[0], 1, torrent.size(), output);
if (output != stdout)
fclose(output);
if (!merklefile.empty())
{
output = fopen(merklefile.c_str(), "wb+");
int ret = fwrite(&t.merkle_tree()[0], 1, t.merkle_tree().size(), output);
if (ret != t.merkle_tree().size())
{
fprintf(stderr, "failed to write %s: (%d) %s\n"
, merklefile.c_str(), errno, strerror(errno));
}
fclose(output);
}
#ifndef BOOST_NO_EXCEPTIONS
}
catch (std::exception& e)
{
fprintf(stderr, "%s\n", e.what());
}
#endif
return 0;
}
<commit_msg>fixed bug in make torrents when saving merkle tree<commit_after>/*
Copyright (c) 2006, Arvid Norberg
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions
are met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in
the documentation and/or other materials provided with the distribution.
* Neither the name of the author nor the names of its
contributors may be used to endorse or promote products derived
from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
POSSIBILITY OF SUCH DAMAGE.
*/
#include "libtorrent/entry.hpp"
#include "libtorrent/bencode.hpp"
#include "libtorrent/torrent_info.hpp"
#include "libtorrent/file.hpp"
#include "libtorrent/storage.hpp"
#include "libtorrent/hasher.hpp"
#include "libtorrent/create_torrent.hpp"
#include "libtorrent/file.hpp"
#include <boost/bind.hpp>
using namespace libtorrent;
// do not include files and folders whose
// name starts with a .
bool file_filter(std::string const& f)
{
if (filename(f)[0] == '.') return false;
fprintf(stderr, "%s\n", f.c_str());
return true;
}
void print_progress(int i, int num)
{
fprintf(stderr, "\r%d/%d", i+1, num);
}
void print_usage()
{
fputs("usage: make_torrent FILE [OPTIONS]\n"
"\n"
"Generates a torrent file from the specified file\n"
"or directory and writes it to standard out\n\n"
"OPTIONS:\n"
"-m file generate a merkle hash tree torrent.\n"
" merkle torrents require client support\n"
" the resulting full merkle tree is written to\n"
" the specified file\n"
"-f include sha-1 file hashes in the torrent\n"
" this helps supporting mixing sources from\n"
" other networks\n"
"-w url adds a web seed to the torrent with\n"
" the specified url\n"
"-t url adds the specified tracker to the\n"
" torrent\n"
"-p bytes enables padding files. Files larger\n"
" than bytes will be piece-aligned\n"
"-s bytes specifies a piece size for the torrent\n"
" This has to be a multiple of 16 kiB\n"
"-l Don't follow symlinks, instead encode them as\n"
" links in the torrent file\n"
"-o file specifies the output filename of the torrent file\n"
" If this is not specified, the torrent file is\n"
" printed to the standard out, except on windows\n"
" where the filename defaults to a.torrent\n"
, stderr);
}
int main(int argc, char* argv[])
{
using namespace libtorrent;
char const* creator_str = "libtorrent";
if (argc < 2)
{
print_usage();
return 1;
}
#ifndef BOOST_NO_EXCEPTIONS
try
{
#endif
std::vector<std::string> web_seeds;
std::vector<std::string> trackers;
int pad_file_limit = -1;
int piece_size = 0;
int flags = 0;
std::string outfile;
std::string merklefile;
#ifdef TORRENT_WINDOWS
// don't ever write binary data to the console on windows
// it will just be interpreted as text and corrupted
outfile = "a.torrent";
#endif
for (int i = 2; i < argc; ++i)
{
if (argv[i][0] != '-')
{
print_usage();
return 1;
}
switch (argv[i][1])
{
case 'w':
++i;
web_seeds.push_back(argv[i]);
break;
case 't':
++i;
trackers.push_back(argv[i]);
break;
case 'p':
++i;
pad_file_limit = atoi(argv[i]);
flags |= create_torrent::optimize;
break;
case 's':
++i;
piece_size = atoi(argv[i]);
break;
case 'm':
++i;
merklefile = argv[i];
flags |= create_torrent::merkle;
break;
case 'o':
++i;
outfile = argv[i];
break;
case 'f':
flags |= create_torrent::calculate_file_hashes;
break;
case 'l':
flags |= create_torrent::symlinks;
break;
default:
print_usage();
return 1;
}
}
file_storage fs;
file_pool fp;
std::string full_path = libtorrent::complete(argv[1]);
add_files(fs, full_path, file_filter, flags);
if (fs.num_files() == 0)
{
fputs("no files specified.\n", stderr);
return 1;
}
create_torrent t(fs, piece_size, pad_file_limit, flags);
for (std::vector<std::string>::iterator i = trackers.begin()
, end(trackers.end()); i != end; ++i)
t.add_tracker(*i);
for (std::vector<std::string>::iterator i = web_seeds.begin()
, end(web_seeds.end()); i != end; ++i)
t.add_url_seed(*i);
error_code ec;
set_piece_hashes(t, parent_path(full_path)
, boost::bind(&print_progress, _1, t.num_pieces()), ec);
if (ec)
{
fprintf(stderr, "%s\n", ec.message().c_str());
return 1;
}
fprintf(stderr, "\n");
t.set_creator(creator_str);
// create the torrent and print it to stdout
std::vector<char> torrent;
bencode(back_inserter(torrent), t.generate());
FILE* output = stdout;
if (!outfile.empty())
output = fopen(outfile.c_str(), "wb+");
fwrite(&torrent[0], 1, torrent.size(), output);
if (output != stdout)
fclose(output);
if (!merklefile.empty())
{
output = fopen(merklefile.c_str(), "wb+");
int ret = fwrite(&t.merkle_tree()[0], 20, t.merkle_tree().size(), output);
if (ret != t.merkle_tree().size() * 20)
{
fprintf(stderr, "failed to write %s: (%d) %s\n"
, merklefile.c_str(), errno, strerror(errno));
}
fclose(output);
}
#ifndef BOOST_NO_EXCEPTIONS
}
catch (std::exception& e)
{
fprintf(stderr, "%s\n", e.what());
}
#endif
return 0;
}
<|endoftext|> |
<commit_before>/*
* CHeatmapData.hpp
*
* Copyright (C) 2015, Achim Lösch <achim.loesch@upb.de>, Christoph Knorr <cknorr@mail.uni-paderborn.de>
* All rights reserved.
*
* This software may be modified and distributed under the terms
* of the BSD license. See the LICENSE file for details.
*
* encoding: UTF-8
* tab size: 4
*
* author: Christoph Knorr (cknorr@mail.uni-paderborn.de)
* created: 01/27/16
* version: 0.7.3 - add heatmaps to msmonitor and the enum ipmi_timeout_setting in libmeasure
*/
#include "CHeatmapData.hpp"
namespace Ui {
HeatmapData::HeatmapData():
mpData(0),
mSize(0),
mMinX(0),
mMaxX(0),
mMinY(0),
mMaxY(100) {
QwtInterval interv(mMinY, mMaxY);
this->setInterval(Qt::ZAxis, interv);
}
HeatmapData::HeatmapData(double *data, uint32_t size, int32_t minX, int32_t maxX, double minY, double maxY):
QwtRasterData(),
mpData(data),
mSize(size),
mMinX(minX),
mMaxX(maxX),
mMinY(minY),
mMaxY(maxY) {
pixelHint(QwtDoubleRect(0, minX, minX+size, 1.0));
QwtInterval interv(minY, maxY);
this->setInterval(Qt::ZAxis, interv);
}
HeatmapData::~HeatmapData() {
//nothing todo
}
QwtRasterData * HeatmapData::copy() const {
return new HeatmapData(mpData, mSize, mMinX, mMaxX, mMinY, mMaxY);
}
QwtDoubleInterval HeatmapData::range() const {
return QwtDoubleInterval(mMinY, mMaxY);
}
double HeatmapData::value(double x, double y) const {
double interval = (mMaxX-mMinX);
if (0 == interval || 0 == mSize) {
return 0.0;
}
int index = ((x-mMinX)/(double)interval*mSize);
if (0 == mpData || index < 0 || index >= mSize) {
return 0.0;
}
return mpData[index];
}
QSize HeatmapData::rasterHint(const QwtDoubleRect& rect) const {
return QSize(mSize, 1);
}
void HeatmapData::setDataPtr(double* data, uint32_t size) {
mpData = data;
mSize = size;
}
void HeatmapData::setXInterval(int32_t minX, int32_t maxX) {
mMinX = minX;
mMaxX = maxX;
}
void HeatmapData::setYInterval(double minY, double maxY) {
mMinY = minY;
mMaxY = maxY;
QwtInterval interv(minY, maxY);
this->setInterval(Qt::ZAxis, interv);
}
}
<commit_msg>Fix small unsigned int bug<commit_after>/*
* CHeatmapData.hpp
*
* Copyright (C) 2015, Achim Lösch <achim.loesch@upb.de>, Christoph Knorr <cknorr@mail.uni-paderborn.de>
* All rights reserved.
*
* This software may be modified and distributed under the terms
* of the BSD license. See the LICENSE file for details.
*
* encoding: UTF-8
* tab size: 4
*
* author: Christoph Knorr (cknorr@mail.uni-paderborn.de)
* created: 01/27/16
* version: 0.7.3 - add heatmaps to msmonitor and the enum ipmi_timeout_setting in libmeasure
*/
#include "CHeatmapData.hpp"
namespace Ui {
HeatmapData::HeatmapData():
mpData(0),
mSize(0),
mMinX(0),
mMaxX(0),
mMinY(0),
mMaxY(100) {
QwtInterval interv(mMinY, mMaxY);
this->setInterval(Qt::ZAxis, interv);
}
HeatmapData::HeatmapData(double *data, uint32_t size, int32_t minX, int32_t maxX, double minY, double maxY):
QwtRasterData(),
mpData(data),
mSize(size),
mMinX(minX),
mMaxX(maxX),
mMinY(minY),
mMaxY(maxY) {
pixelHint(QwtDoubleRect(0, minX, minX+size, 1.0));
QwtInterval interv(minY, maxY);
this->setInterval(Qt::ZAxis, interv);
}
HeatmapData::~HeatmapData() {
//nothing todo
}
QwtRasterData * HeatmapData::copy() const {
return new HeatmapData(mpData, mSize, mMinX, mMaxX, mMinY, mMaxY);
}
QwtDoubleInterval HeatmapData::range() const {
return QwtDoubleInterval(mMinY, mMaxY);
}
double HeatmapData::value(double x, double y) const {
double interval = (mMaxX-mMinX);
if (0 == interval || 0 == mSize) {
return 0.0;
}
unsigned int index = ((x-mMinX)/(double)interval*mSize);
if (0 == mpData || index >= mSize) {
return 0.0;
}
return mpData[index];
}
QSize HeatmapData::rasterHint(const QwtDoubleRect& rect) const {
return QSize(mSize, 1);
}
void HeatmapData::setDataPtr(double* data, uint32_t size) {
mpData = data;
mSize = size;
}
void HeatmapData::setXInterval(int32_t minX, int32_t maxX) {
mMinX = minX;
mMaxX = maxX;
}
void HeatmapData::setYInterval(double minY, double maxY) {
mMinY = minY;
mMaxY = maxY;
QwtInterval interv(minY, maxY);
this->setInterval(Qt::ZAxis, interv);
}
}
<|endoftext|> |
<commit_before>// Copyright 2019 Google LLC
//
// 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 "google/cloud/storage/client.h"
#include "google/cloud/storage/examples/storage_examples_common.h"
#include "google/cloud/internal/getenv.h"
#include <iostream>
namespace {
void GetServiceAccount(google::cloud::storage::Client client,
std::vector<std::string> const&) {
//! [START storage_get_service_account] [get service account]
namespace gcs = google::cloud::storage;
using ::google::cloud::StatusOr;
[](gcs::Client client) {
StatusOr<gcs::ServiceAccount> account = client.GetServiceAccount();
if (!account) throw std::runtime_error(account.status().message());
std::cout << "The service account details are " << *account << "\n";
}
//! [END storage_get_service_account] [get service account]
(std::move(client));
}
void GetServiceAccountForProject(google::cloud::storage::Client client,
std::vector<std::string> const& argv) {
//! [get service account for project]
namespace gcs = google::cloud::storage;
using ::google::cloud::StatusOr;
[](gcs::Client client, std::string const& project_id) {
StatusOr<gcs::ServiceAccount> account =
client.GetServiceAccountForProject(project_id);
if (!account) throw std::runtime_error(account.status().message());
std::cout << "The service account details for project " << project_id
<< " are " << *account << "\n";
}
//! [get service account for project]
(std::move(client), argv.at(0));
}
void ListHmacKeys(google::cloud::storage::Client client,
std::vector<std::string> const&) {
//! [list hmac keys] [START storage_list_hmac_keys]
namespace gcs = google::cloud::storage;
using ::google::cloud::StatusOr;
[](gcs::Client client) {
int count = 0;
gcs::ListHmacKeysReader hmac_keys_list = client.ListHmacKeys();
for (auto const& key : hmac_keys_list) {
if (!key) throw std::runtime_error(key.status().message());
std::cout << "service_account_email = " << key->service_account_email()
<< "\naccess_id = " << key->access_id() << "\n";
++count;
}
if (count == 0) {
std::cout << "No HMAC keys in default project\n";
}
}
//! [list hmac keys] [END storage_list_hmac_keys]
(std::move(client));
}
void ListHmacKeysWithServiceAccount(google::cloud::storage::Client client,
std::vector<std::string> const& argv) {
//! [list hmac keys service account]
namespace gcs = google::cloud::storage;
using ::google::cloud::StatusOr;
[](gcs::Client client, std::string const& service_account) {
int count = 0;
gcs::ListHmacKeysReader hmac_keys_list =
client.ListHmacKeys(gcs::ServiceAccountFilter(service_account));
for (auto const& key : hmac_keys_list) {
if (!key) throw std::runtime_error(key.status().message());
std::cout << "service_account_email = " << key->service_account_email()
<< "\naccess_id = " << key->access_id() << "\n";
++count;
}
if (count == 0) {
std::cout << "No HMAC keys for service account " << service_account
<< " in default project\n";
}
}
//! [list hmac keys service account]
(std::move(client), argv.at(0));
}
void CreateHmacKey(google::cloud::storage::Client client,
std::vector<std::string> const& argv) {
//! [create hmac key] [START storage_create_hmac_key]
namespace gcs = google::cloud::storage;
using ::google::cloud::StatusOr;
[](gcs::Client client, std::string const& service_account_email) {
StatusOr<std::pair<gcs::HmacKeyMetadata, std::string>> key_info =
client.CreateHmacKey(service_account_email);
if (!key_info) throw std::runtime_error(key_info.status().message());
std::cout << "The base64 encoded secret is: " << key_info->second
<< "\nDo not miss that secret, there is no API to recover it."
<< "\nThe HMAC key metadata is: " << key_info->first << "\n";
}
//! [create hmac key] [END storage_create_hmac_key]
(std::move(client), argv.at(0));
}
void CreateHmacKeyForProject(google::cloud::storage::Client client,
std::vector<std::string> const& argv) {
//! [create hmac key project]
namespace gcs = google::cloud::storage;
using ::google::cloud::StatusOr;
[](gcs::Client client, std::string const& project_id,
std::string const& service_account_email) {
StatusOr<std::pair<gcs::HmacKeyMetadata, std::string>> hmac_key_details =
client.CreateHmacKey(service_account_email,
gcs::OverrideDefaultProject(project_id));
if (!hmac_key_details) {
throw std::runtime_error(hmac_key_details.status().message());
}
std::cout << "The base64 encoded secret is: " << hmac_key_details->second
<< "\nDo not miss that secret, there is no API to recover it."
<< "\nThe HMAC key metadata is: " << hmac_key_details->first
<< "\n";
}
//! [create hmac key project]
(std::move(client), argv.at(0), argv.at(1));
}
void DeleteHmacKey(google::cloud::storage::Client client,
std::vector<std::string> const& argv) {
//! [delete hmac key] [START storage_delete_hmac_key]
namespace gcs = google::cloud::storage;
[](gcs::Client client, std::string const& access_id) {
google::cloud::Status status = client.DeleteHmacKey(access_id);
if (!status.ok()) throw std::runtime_error(status.message());
std::cout << "The key is deleted, though it may still appear"
<< " in ListHmacKeys() results.\n";
}
//! [delete hmac key] [END storage_delete_hmac_key]
(std::move(client), argv.at(0));
}
void GetHmacKey(google::cloud::storage::Client client,
std::vector<std::string> const& argv) {
//! [get hmac key] [START storage_get_hmac_key]
namespace gcs = google::cloud::storage;
using ::google::cloud::StatusOr;
[](gcs::Client client, std::string const& access_id) {
StatusOr<gcs::HmacKeyMetadata> hmac_key = client.GetHmacKey(access_id);
if (!hmac_key) throw std::runtime_error(hmac_key.status().message());
std::cout << "The HMAC key metadata is: " << *hmac_key << "\n";
}
//! [get hmac key] [END storage_get_hmac_key]
(std::move(client), argv.at(0));
}
void UpdateHmacKey(google::cloud::storage::Client client,
std::vector<std::string> const& argv) {
//! [update hmac key]
namespace gcs = google::cloud::storage;
using ::google::cloud::StatusOr;
[](gcs::Client client, std::string const& access_id,
std::string const& state) {
StatusOr<gcs::HmacKeyMetadata> updated = client.UpdateHmacKey(
access_id, gcs::HmacKeyMetadata().set_state(std::move(state)));
if (!updated) throw std::runtime_error(updated.status().message());
std::cout << "The updated HMAC key metadata is: " << *updated << "\n";
}
//! [update hmac key]
(std::move(client), argv.at(0), argv.at(1));
}
void ActivateHmacKey(google::cloud::storage::Client client,
std::vector<std::string> const& argv) {
//! [START storage_activate_hmac_key]
namespace gcs = google::cloud::storage;
using ::google::cloud::StatusOr;
[](gcs::Client client, std::string const& access_id) {
StatusOr<gcs::HmacKeyMetadata> updated = client.UpdateHmacKey(
access_id,
gcs::HmacKeyMetadata().set_state(gcs::HmacKeyMetadata::state_active()));
if (!updated) throw std::runtime_error(updated.status().message());
if (updated->state() != gcs::HmacKeyMetadata::state_active()) {
throw std::runtime_error(
"The HMAC key is NOT active, this is unexpected");
}
std::cout << "The HMAC key is now active\nFull metadata: " << *updated
<< "\n";
}
//! [END storage_activate_hmac_key]
(std::move(client), argv.at(0));
}
void DeactivateHmacKey(google::cloud::storage::Client client,
std::vector<std::string> const& argv) {
//! [START storage_deactivate_hmac_key]
namespace gcs = google::cloud::storage;
using ::google::cloud::StatusOr;
[](gcs::Client client, std::string const& access_id) {
StatusOr<gcs::HmacKeyMetadata> updated = client.UpdateHmacKey(
access_id, gcs::HmacKeyMetadata().set_state(
gcs::HmacKeyMetadata::state_inactive()));
if (!updated) throw std::runtime_error(updated.status().message());
if (updated->state() != gcs::HmacKeyMetadata::state_inactive()) {
throw std::runtime_error("The HMAC key is active, this is unexpected");
}
std::cout << "The HMAC key is now inactive\nFull metadata: " << *updated
<< "\n";
}
//! [END storage_deactivate_hmac_key]
(std::move(client), argv.at(0));
}
void RunAll(std::vector<std::string> const& argv) {
namespace examples = ::google::cloud::storage::examples;
namespace gcs = ::google::cloud::storage;
if (!argv.empty()) throw examples::Usage{"auto"};
examples::CheckEnvironmentVariablesAreSet({
"GOOGLE_CLOUD_PROJECT",
"GOOGLE_CLOUD_CPP_STORAGE_TEST_HMAC_SERVICE_ACCOUNT",
});
auto const project_id =
google::cloud::internal::GetEnv("GOOGLE_CLOUD_PROJECT").value();
auto const service_account =
google::cloud::internal::GetEnv(
"GOOGLE_CLOUD_CPP_STORAGE_TEST_HMAC_SERVICE_ACCOUNT")
.value();
auto client = gcs::Client::CreateDefaultClient().value();
std::cout << "\nRunning GetServiceAccountForProject() example" << std::endl;
GetServiceAccountForProject(client, {project_id});
std::cout << "\nRunning GetServiceAccount() example" << std::endl;
GetServiceAccount(client, {});
std::cout << "\nRunning ListHmacKeys() example [1]" << std::endl;
ListHmacKeys(client, {});
std::cout << "\nRunning ListHmacKeysWithServiceAccount() example [1]"
<< std::endl;
ListHmacKeysWithServiceAccount(client, {service_account});
auto const key_info =
client
.CreateHmacKey(service_account,
gcs::OverrideDefaultProject(project_id))
.value();
std::cout << "\nRunning CreateHmacKey() example" << std::endl;
CreateHmacKey(client, {service_account});
std::cout << "\nRunning CreateHmacKeyForProject() example" << std::endl;
CreateHmacKeyForProject(client, {project_id, service_account});
std::cout << "\nRunning ListHmacKeys() example [2]" << std::endl;
ListHmacKeys(client, {});
std::cout << "\nRunning ListHmacKeysWithServiceAccount() example [2]"
<< std::endl;
ListHmacKeysWithServiceAccount(client, {service_account});
std::cout << "\nRunning GetHmacKey() example" << std::endl;
GetHmacKey(client, {key_info.first.access_id()});
std::cout << "\nRunning UpdateHmacKey() example" << std::endl;
UpdateHmacKey(client, {key_info.first.access_id(), "INACTIVE"});
std::cout << "\nRunning ActivateHmacKey() example" << std::endl;
ActivateHmacKey(client, {key_info.first.access_id()});
std::cout << "\nRunning DeactivateHmacKey() example" << std::endl;
DeactivateHmacKey(client, {key_info.first.access_id()});
std::cout << "\nRunning DeleteHmacKey() example" << std::endl;
DeleteHmacKey(client, {key_info.first.access_id()});
for (auto const& key :
client.ListHmacKeys(gcs::ServiceAccountFilter(service_account))) {
if (!key) break;
(void)client.UpdateHmacKey(key->access_id(),
gcs::HmacKeyMetadata().set_state(
gcs::HmacKeyMetadata::state_inactive()));
(void)client.DeleteHmacKey(key->access_id());
}
}
} // anonymous namespace
int main(int argc, char* argv[]) {
namespace examples = ::google::cloud::storage::examples;
examples::Example example({
examples::CreateCommandEntry("get-service-account", {},
GetServiceAccount),
examples::CreateCommandEntry("get-service-account-for-project",
{"<project-id>"},
GetServiceAccountForProject),
examples::CreateCommandEntry("list-hmac-keys", {}, ListHmacKeys),
examples::CreateCommandEntry("list-hmac-keys-with-service-account",
{"<service-account>"},
ListHmacKeysWithServiceAccount),
examples::CreateCommandEntry("create-hmac-key",
{"<service-account-email>"}, CreateHmacKey),
examples::CreateCommandEntry("create-hmac-key-for-project",
{"<project-id>", "<service-account-email>"},
CreateHmacKeyForProject),
examples::CreateCommandEntry("delete-hmac-key", {"<access-id>"},
DeleteHmacKey),
examples::CreateCommandEntry("get-hmac-key", {"<access-id>"}, GetHmacKey),
examples::CreateCommandEntry("update-hmac-key",
{"<access-id>", "<state>"}, UpdateHmacKey),
examples::CreateCommandEntry("activate-hmac-key", {"<access-id>"},
ActivateHmacKey),
examples::CreateCommandEntry("deactivate-hmac-key", {"<access-id>"},
DeactivateHmacKey),
{"auto", RunAll},
});
return example.Run(argc, argv);
}
<commit_msg>fix: eliminate data race between storage "service account" tests (#4403)<commit_after>// Copyright 2019 Google LLC
//
// 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 "google/cloud/storage/client.h"
#include "google/cloud/storage/examples/storage_examples_common.h"
#include "google/cloud/internal/getenv.h"
#include <iostream>
namespace {
void GetServiceAccount(google::cloud::storage::Client client,
std::vector<std::string> const&) {
//! [START storage_get_service_account] [get service account]
namespace gcs = google::cloud::storage;
using ::google::cloud::StatusOr;
[](gcs::Client client) {
StatusOr<gcs::ServiceAccount> account = client.GetServiceAccount();
if (!account) throw std::runtime_error(account.status().message());
std::cout << "The service account details are " << *account << "\n";
}
//! [END storage_get_service_account] [get service account]
(std::move(client));
}
void GetServiceAccountForProject(google::cloud::storage::Client client,
std::vector<std::string> const& argv) {
//! [get service account for project]
namespace gcs = google::cloud::storage;
using ::google::cloud::StatusOr;
[](gcs::Client client, std::string const& project_id) {
StatusOr<gcs::ServiceAccount> account =
client.GetServiceAccountForProject(project_id);
if (!account) throw std::runtime_error(account.status().message());
std::cout << "The service account details for project " << project_id
<< " are " << *account << "\n";
}
//! [get service account for project]
(std::move(client), argv.at(0));
}
void ListHmacKeys(google::cloud::storage::Client client,
std::vector<std::string> const&) {
//! [list hmac keys] [START storage_list_hmac_keys]
namespace gcs = google::cloud::storage;
using ::google::cloud::StatusOr;
[](gcs::Client client) {
int count = 0;
gcs::ListHmacKeysReader hmac_keys_list = client.ListHmacKeys();
for (auto const& key : hmac_keys_list) {
if (!key) throw std::runtime_error(key.status().message());
std::cout << "service_account_email = " << key->service_account_email()
<< "\naccess_id = " << key->access_id() << "\n";
++count;
}
if (count == 0) {
std::cout << "No HMAC keys in default project\n";
}
}
//! [list hmac keys] [END storage_list_hmac_keys]
(std::move(client));
}
void ListHmacKeysWithServiceAccount(google::cloud::storage::Client client,
std::vector<std::string> const& argv) {
//! [list hmac keys service account]
namespace gcs = google::cloud::storage;
using ::google::cloud::StatusOr;
[](gcs::Client client, std::string const& service_account) {
int count = 0;
gcs::ListHmacKeysReader hmac_keys_list =
client.ListHmacKeys(gcs::ServiceAccountFilter(service_account));
for (auto const& key : hmac_keys_list) {
if (!key) throw std::runtime_error(key.status().message());
std::cout << "service_account_email = " << key->service_account_email()
<< "\naccess_id = " << key->access_id() << "\n";
++count;
}
if (count == 0) {
std::cout << "No HMAC keys for service account " << service_account
<< " in default project\n";
}
}
//! [list hmac keys service account]
(std::move(client), argv.at(0));
}
std::string CreateHmacKey(google::cloud::storage::Client client,
std::vector<std::string> const& argv) {
//! [create hmac key] [START storage_create_hmac_key]
namespace gcs = google::cloud::storage;
using ::google::cloud::StatusOr;
return [](gcs::Client client, std::string const& service_account_email) {
StatusOr<std::pair<gcs::HmacKeyMetadata, std::string>> key_info =
client.CreateHmacKey(service_account_email);
if (!key_info) throw std::runtime_error(key_info.status().message());
std::cout << "The base64 encoded secret is: " << key_info->second
<< "\nDo not miss that secret, there is no API to recover it."
<< "\nThe HMAC key metadata is: " << key_info->first << "\n";
return key_info->first.access_id();
}
//! [create hmac key] [END storage_create_hmac_key]
(std::move(client), argv.at(0));
}
std::string CreateHmacKeyForProject(google::cloud::storage::Client client,
std::vector<std::string> const& argv) {
//! [create hmac key project]
namespace gcs = google::cloud::storage;
using ::google::cloud::StatusOr;
return [](gcs::Client client, std::string const& project_id,
std::string const& service_account_email) {
StatusOr<std::pair<gcs::HmacKeyMetadata, std::string>> hmac_key_details =
client.CreateHmacKey(service_account_email,
gcs::OverrideDefaultProject(project_id));
if (!hmac_key_details) {
throw std::runtime_error(hmac_key_details.status().message());
}
std::cout << "The base64 encoded secret is: " << hmac_key_details->second
<< "\nDo not miss that secret, there is no API to recover it."
<< "\nThe HMAC key metadata is: " << hmac_key_details->first
<< "\n";
return hmac_key_details->first.access_id();
}
//! [create hmac key project]
(std::move(client), argv.at(0), argv.at(1));
}
void DeleteHmacKey(google::cloud::storage::Client client,
std::vector<std::string> const& argv) {
//! [delete hmac key] [START storage_delete_hmac_key]
namespace gcs = google::cloud::storage;
[](gcs::Client client, std::string const& access_id) {
google::cloud::Status status = client.DeleteHmacKey(access_id);
if (!status.ok()) throw std::runtime_error(status.message());
std::cout << "The key is deleted, though it may still appear"
<< " in ListHmacKeys() results.\n";
}
//! [delete hmac key] [END storage_delete_hmac_key]
(std::move(client), argv.at(0));
}
void GetHmacKey(google::cloud::storage::Client client,
std::vector<std::string> const& argv) {
//! [get hmac key] [START storage_get_hmac_key]
namespace gcs = google::cloud::storage;
using ::google::cloud::StatusOr;
[](gcs::Client client, std::string const& access_id) {
StatusOr<gcs::HmacKeyMetadata> hmac_key = client.GetHmacKey(access_id);
if (!hmac_key) throw std::runtime_error(hmac_key.status().message());
std::cout << "The HMAC key metadata is: " << *hmac_key << "\n";
}
//! [get hmac key] [END storage_get_hmac_key]
(std::move(client), argv.at(0));
}
void UpdateHmacKey(google::cloud::storage::Client client,
std::vector<std::string> const& argv) {
//! [update hmac key]
namespace gcs = google::cloud::storage;
using ::google::cloud::StatusOr;
[](gcs::Client client, std::string const& access_id,
std::string const& state) {
StatusOr<gcs::HmacKeyMetadata> updated = client.UpdateHmacKey(
access_id, gcs::HmacKeyMetadata().set_state(std::move(state)));
if (!updated) throw std::runtime_error(updated.status().message());
std::cout << "The updated HMAC key metadata is: " << *updated << "\n";
}
//! [update hmac key]
(std::move(client), argv.at(0), argv.at(1));
}
void ActivateHmacKey(google::cloud::storage::Client client,
std::vector<std::string> const& argv) {
//! [START storage_activate_hmac_key]
namespace gcs = google::cloud::storage;
using ::google::cloud::StatusOr;
[](gcs::Client client, std::string const& access_id) {
StatusOr<gcs::HmacKeyMetadata> updated = client.UpdateHmacKey(
access_id,
gcs::HmacKeyMetadata().set_state(gcs::HmacKeyMetadata::state_active()));
if (!updated) throw std::runtime_error(updated.status().message());
if (updated->state() != gcs::HmacKeyMetadata::state_active()) {
throw std::runtime_error(
"The HMAC key is NOT active, this is unexpected");
}
std::cout << "The HMAC key is now active\nFull metadata: " << *updated
<< "\n";
}
//! [END storage_activate_hmac_key]
(std::move(client), argv.at(0));
}
void DeactivateHmacKey(google::cloud::storage::Client client,
std::vector<std::string> const& argv) {
//! [START storage_deactivate_hmac_key]
namespace gcs = google::cloud::storage;
using ::google::cloud::StatusOr;
[](gcs::Client client, std::string const& access_id) {
StatusOr<gcs::HmacKeyMetadata> updated = client.UpdateHmacKey(
access_id, gcs::HmacKeyMetadata().set_state(
gcs::HmacKeyMetadata::state_inactive()));
if (!updated) throw std::runtime_error(updated.status().message());
if (updated->state() != gcs::HmacKeyMetadata::state_inactive()) {
throw std::runtime_error("The HMAC key is active, this is unexpected");
}
std::cout << "The HMAC key is now inactive\nFull metadata: " << *updated
<< "\n";
}
//! [END storage_deactivate_hmac_key]
(std::move(client), argv.at(0));
}
void RunAll(std::vector<std::string> const& argv) {
namespace examples = ::google::cloud::storage::examples;
namespace gcs = ::google::cloud::storage;
if (!argv.empty()) throw examples::Usage{"auto"};
examples::CheckEnvironmentVariablesAreSet({
"GOOGLE_CLOUD_PROJECT",
"GOOGLE_CLOUD_CPP_STORAGE_TEST_HMAC_SERVICE_ACCOUNT",
});
auto const project_id =
google::cloud::internal::GetEnv("GOOGLE_CLOUD_PROJECT").value();
auto const service_account =
google::cloud::internal::GetEnv(
"GOOGLE_CLOUD_CPP_STORAGE_TEST_HMAC_SERVICE_ACCOUNT")
.value();
auto client = gcs::Client::CreateDefaultClient().value();
std::cout << "\nRunning GetServiceAccountForProject() example" << std::endl;
GetServiceAccountForProject(client, {project_id});
std::cout << "\nRunning GetServiceAccount() example" << std::endl;
GetServiceAccount(client, {});
std::cout << "\nRunning ListHmacKeys() example [1]" << std::endl;
ListHmacKeys(client, {});
std::cout << "\nRunning ListHmacKeysWithServiceAccount() example [1]"
<< std::endl;
ListHmacKeysWithServiceAccount(client, {service_account});
auto const key_info =
client
.CreateHmacKey(service_account,
gcs::OverrideDefaultProject(project_id))
.value();
std::cout << "\nRunning CreateHmacKey() example" << std::endl;
auto const hmac_access_id = CreateHmacKey(client, {service_account});
std::cout << "\nRunning CreateHmacKeyForProject() example" << std::endl;
auto const project_hmac_access_id =
CreateHmacKeyForProject(client, {project_id, service_account});
std::cout << "\nRunning ListHmacKeys() example [2]" << std::endl;
ListHmacKeys(client, {});
std::cout << "\nRunning ListHmacKeysWithServiceAccount() example [2]"
<< std::endl;
ListHmacKeysWithServiceAccount(client, {service_account});
std::cout << "\nRunning GetHmacKey() example" << std::endl;
GetHmacKey(client, {key_info.first.access_id()});
std::cout << "\nRunning UpdateHmacKey() example" << std::endl;
UpdateHmacKey(client, {key_info.first.access_id(), "INACTIVE"});
std::cout << "\nRunning ActivateHmacKey() example" << std::endl;
ActivateHmacKey(client, {key_info.first.access_id()});
std::cout << "\nRunning DeactivateHmacKey() example" << std::endl;
DeactivateHmacKey(client, {key_info.first.access_id()});
std::cout << "\nRunning DeleteHmacKey() example" << std::endl;
DeleteHmacKey(client, {key_info.first.access_id()});
for (auto const& access_id : {project_hmac_access_id, hmac_access_id}) {
(void)client.UpdateHmacKey(access_id,
gcs::HmacKeyMetadata().set_state(
gcs::HmacKeyMetadata::state_inactive()));
(void)client.DeleteHmacKey(access_id);
}
}
} // anonymous namespace
int main(int argc, char* argv[]) {
namespace examples = ::google::cloud::storage::examples;
examples::Example example({
examples::CreateCommandEntry("get-service-account", {},
GetServiceAccount),
examples::CreateCommandEntry("get-service-account-for-project",
{"<project-id>"},
GetServiceAccountForProject),
examples::CreateCommandEntry("list-hmac-keys", {}, ListHmacKeys),
examples::CreateCommandEntry("list-hmac-keys-with-service-account",
{"<service-account>"},
ListHmacKeysWithServiceAccount),
examples::CreateCommandEntry("create-hmac-key",
{"<service-account-email>"}, CreateHmacKey),
examples::CreateCommandEntry("create-hmac-key-for-project",
{"<project-id>", "<service-account-email>"},
CreateHmacKeyForProject),
examples::CreateCommandEntry("delete-hmac-key", {"<access-id>"},
DeleteHmacKey),
examples::CreateCommandEntry("get-hmac-key", {"<access-id>"}, GetHmacKey),
examples::CreateCommandEntry("update-hmac-key",
{"<access-id>", "<state>"}, UpdateHmacKey),
examples::CreateCommandEntry("activate-hmac-key", {"<access-id>"},
ActivateHmacKey),
examples::CreateCommandEntry("deactivate-hmac-key", {"<access-id>"},
DeactivateHmacKey),
{"auto", RunAll},
});
return example.Run(argc, argv);
}
<|endoftext|> |
<commit_before>/**
* Find the number which is repeated
* odd number of times in a given array
* which has even number of elements already
* and atleast on number is repeated odd
* number of times
*/
#include <iostream>
using namespace std;
void printArray(int A[], int size) {
for (int i = 0; i < size; i++)
cout<<A[i]<<" ";
cout<<endl;
}
/**
* XOR all the numbers and result
* should be the number of odd times
* repeated
*/
void findOddNumber(int A[], int size) {
int res = 0;
for (int i = 0; i < size; i++) {
res = res ^ A[i];
}
cout<<"Element repeated odd number of times : "<<res<<endl;
}
int main() {
int A[] = {1, 1, 2, 2, 3, 3, 3};
int size = sizeof(A)/sizeof(A[0]);
printArray(A, size);
findOddNumber(A, size);
return 0;
}
<commit_msg>Change input<commit_after>/**
* Find the number which is repeated
* odd number of times in a given array
* which has even number of elements already
* and only one number is repeated odd
* number of times
*/
#include <iostream>
using namespace std;
void printArray(int A[], int size) {
for (int i = 0; i < size; i++)
cout<<A[i]<<" ";
cout<<endl;
}
/**
* XOR all the numbers and result
* should be the number of odd times
* repeated
*/
void findOddNumber(int A[], int size) {
int res = 0;
for (int i = 0; i < size; i++) {
res = res ^ A[i];
}
cout<<"Element repeated odd number of times : "<<res<<endl;
}
int main() {
int A[] = {2, 3, 5, 4, 5, 2, 4, 3, 5, 2, 4, 4, 2};
int size = sizeof(A)/sizeof(A[0]);
printArray(A, size);
findOddNumber(A, size);
return 0;
}
<|endoftext|> |
<commit_before>/*
***********************************************************************************************************************
*
* Copyright (c) 2021 Google LLC. All Rights Reserved.
*
* 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 "cache_creator.h"
#include "llvm/BinaryFormat/MsgPackDocument.h"
#include "gmock/gmock.h"
#include <array>
TEST(CacheCreatorTest, PlaceholderTestPass) {
EXPECT_TRUE(true);
}
using UuidArray = std::array<uint8_t, 16>;
TEST(CacheCreatorTest, BasicUuidToString) {
UuidArray uuid;
uuid.fill(0);
EXPECT_EQ(cc::uuidToHexString(uuid), "00000000-0000-0000-0000-000000000000");
uuid[0] = 16;
EXPECT_EQ(cc::uuidToHexString(uuid), "10000000-0000-0000-0000-000000000000");
uuid[0] = 255;
EXPECT_EQ(cc::uuidToHexString(uuid), "ff000000-0000-0000-0000-000000000000");
uuid[0] = 0;
uuid.back() = 1;
EXPECT_EQ(cc::uuidToHexString(uuid), "00000000-0000-0000-0000-000000000001");
uuid.back() = 15;
EXPECT_EQ(cc::uuidToHexString(uuid), "00000000-0000-0000-0000-00000000000f");
uuid.back() = 255;
EXPECT_EQ(cc::uuidToHexString(uuid), "00000000-0000-0000-0000-0000000000ff");
uuid[0] = 255;
EXPECT_EQ(cc::uuidToHexString(uuid), "ff000000-0000-0000-0000-0000000000ff");
}
TEST(CacheCreatorTest, BasicHexStringToUuid) {
UuidArray allZeros = {};
UuidArray allOnes = {};
allOnes.fill(255);
UuidArray out = {};
EXPECT_TRUE(cc::hexStringToUuid("00000000-0000-0000-0000-000000000000", out));
EXPECT_EQ(out, allZeros);
EXPECT_TRUE(cc::hexStringToUuid("10000000-0000-0000-0000-000000000000", out));
EXPECT_EQ(out.front(), 16);
EXPECT_EQ(out.back(), 0);
EXPECT_TRUE(cc::hexStringToUuid("f0000000-0000-0000-0000-000000000000", out));
EXPECT_EQ(out.front(), 240);
EXPECT_EQ(out.back(), 0);
EXPECT_TRUE(cc::hexStringToUuid("ff000000-0000-0000-0000-000000000000", out));
EXPECT_EQ(out.front(), 255);
EXPECT_EQ(out.back(), 0);
EXPECT_TRUE(cc::hexStringToUuid("00000000-0000-0000-0000-000000000001", out));
EXPECT_EQ(out.front(), 0);
EXPECT_EQ(out.back(), 1);
EXPECT_TRUE(cc::hexStringToUuid("00000000-0000-0000-0000-00000000000f", out));
EXPECT_EQ(out.front(), 0);
EXPECT_EQ(out.back(), 15);
EXPECT_TRUE(cc::hexStringToUuid("00000000-0000-0000-0000-0000000000ff", out));
EXPECT_EQ(out.front(), 0);
EXPECT_EQ(out.back(), 255);
EXPECT_TRUE(cc::hexStringToUuid("ffffffff-ffff-ffff-ffff-ffffffffffff", out));
EXPECT_EQ(out, allOnes);
}
TEST(CacheCreatorTest, BadHexStringUuids) {
UuidArray out = {};
EXPECT_FALSE(cc::hexStringToUuid("", out));
EXPECT_FALSE(cc::hexStringToUuid("----", out));
EXPECT_FALSE(cc::hexStringToUuid("ffffffffffffffffffffffffffffffff", out));
EXPECT_FALSE(cc::hexStringToUuid("fffffff-ffff-ffff-ffff-ffffffffffff", out));
EXPECT_FALSE(cc::hexStringToUuid("0ffffffff-ffff-ffff-ffff-ffffffffffff", out));
EXPECT_FALSE(cc::hexStringToUuid("ffffffff-ffff-ffff-ffff-ffffffffffff0", out));
EXPECT_FALSE(cc::hexStringToUuid("ffffffff-ffff-ffff-ffff0ffffffffffff", out));
EXPECT_FALSE(cc::hexStringToUuid("ffffffff-ffff-ffff-ffff-ffffffffffff-", out));
EXPECT_FALSE(cc::hexStringToUuid("ffffffff\0-ffff-ffff-ffff-ffffffffffff", out));
EXPECT_FALSE(cc::hexStringToUuid("gfffffff-ffff-ffff-ffff-ffffffffffff", out));
EXPECT_FALSE(cc::hexStringToUuid("FFFFFFFF-FFFF-FFFF-FFFF-FFFFFFFFFFFF", out));
EXPECT_FALSE(cc::hexStringToUuid("Hey, what's up?", out));
UuidArray allZeros = {};
EXPECT_EQ(out, allZeros);
}
TEST(CacheCreatorTest, FullUuidRoundtrip) {
UuidArray uuid = {16, 2, 104, 108, 0, 3, 0, 0, 213, 232, 11, 199, 227, 23, 129, 116};
cc::UuidString hexStr = cc::uuidToHexString(uuid);
EXPECT_EQ(hexStr, "1002686c-0003-0000-d5e8-0bc7e3178174");
UuidArray dumped = {};
EXPECT_TRUE(cc::hexStringToUuid(hexStr, dumped));
EXPECT_EQ(dumped, uuid);
}
TEST(CacheCreatorTest, GetCacheInfoFromInvalidPalMetadataBlob) {
char badMetadata[10] = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9};
llvm::StringRef noteBlob(badMetadata, sizeof(badMetadata));
llvm::Expected<cc::ElfLlpcCacheInfo> cacheInfoOrErr = cc::getCacheInfoFromMetadataBlob(noteBlob);
llvm::Error err = cacheInfoOrErr.takeError();
EXPECT_TRUE(err.isA<llvm::StringError>());
llvm::consumeError(std::move(err));
}
TEST(CacheCreatorTest, GetCacheInfoFromValidPalMetadataBlob) {
const char *sampleMetadata = R"(---
amdpal.pipelines:
- .xgl_cache_info:
.128_bit_cache_hash:
- 17226562260713912943
- 15513868906143827149
.llpc_version: !str '46.1'
...
)";
llvm::msgpack::Document document;
document.fromYAML(sampleMetadata);
std::string noteBlob;
document.writeToBlob(noteBlob);
llvm::Expected<cc::ElfLlpcCacheInfo> cacheInfoOrErr = cc::getCacheInfoFromMetadataBlob(noteBlob);
EXPECT_TRUE((bool)cacheInfoOrErr);
cc::ElfLlpcCacheInfo elfLlpcInfo = cacheInfoOrErr.get();
EXPECT_EQ(elfLlpcInfo.cacheHash.qwords[0], 17226562260713912943u);
EXPECT_EQ(elfLlpcInfo.cacheHash.qwords[1], 15513868906143827149u);
EXPECT_EQ(elfLlpcInfo.llpcVersion.getMajor(), 46);
EXPECT_EQ(elfLlpcInfo.llpcVersion.getMinor().getValue(), 1);
}
<commit_msg>Fix warning (signed/unsigned comparison). NFC.<commit_after>/*
***********************************************************************************************************************
*
* Copyright (c) 2021 Google LLC. All Rights Reserved.
*
* 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 "cache_creator.h"
#include "llvm/BinaryFormat/MsgPackDocument.h"
#include "gmock/gmock.h"
#include <array>
TEST(CacheCreatorTest, PlaceholderTestPass) {
EXPECT_TRUE(true);
}
using UuidArray = std::array<uint8_t, 16>;
TEST(CacheCreatorTest, BasicUuidToString) {
UuidArray uuid;
uuid.fill(0);
EXPECT_EQ(cc::uuidToHexString(uuid), "00000000-0000-0000-0000-000000000000");
uuid[0] = 16;
EXPECT_EQ(cc::uuidToHexString(uuid), "10000000-0000-0000-0000-000000000000");
uuid[0] = 255;
EXPECT_EQ(cc::uuidToHexString(uuid), "ff000000-0000-0000-0000-000000000000");
uuid[0] = 0;
uuid.back() = 1;
EXPECT_EQ(cc::uuidToHexString(uuid), "00000000-0000-0000-0000-000000000001");
uuid.back() = 15;
EXPECT_EQ(cc::uuidToHexString(uuid), "00000000-0000-0000-0000-00000000000f");
uuid.back() = 255;
EXPECT_EQ(cc::uuidToHexString(uuid), "00000000-0000-0000-0000-0000000000ff");
uuid[0] = 255;
EXPECT_EQ(cc::uuidToHexString(uuid), "ff000000-0000-0000-0000-0000000000ff");
}
TEST(CacheCreatorTest, BasicHexStringToUuid) {
UuidArray allZeros = {};
UuidArray allOnes = {};
allOnes.fill(255);
UuidArray out = {};
EXPECT_TRUE(cc::hexStringToUuid("00000000-0000-0000-0000-000000000000", out));
EXPECT_EQ(out, allZeros);
EXPECT_TRUE(cc::hexStringToUuid("10000000-0000-0000-0000-000000000000", out));
EXPECT_EQ(out.front(), 16);
EXPECT_EQ(out.back(), 0);
EXPECT_TRUE(cc::hexStringToUuid("f0000000-0000-0000-0000-000000000000", out));
EXPECT_EQ(out.front(), 240);
EXPECT_EQ(out.back(), 0);
EXPECT_TRUE(cc::hexStringToUuid("ff000000-0000-0000-0000-000000000000", out));
EXPECT_EQ(out.front(), 255);
EXPECT_EQ(out.back(), 0);
EXPECT_TRUE(cc::hexStringToUuid("00000000-0000-0000-0000-000000000001", out));
EXPECT_EQ(out.front(), 0);
EXPECT_EQ(out.back(), 1);
EXPECT_TRUE(cc::hexStringToUuid("00000000-0000-0000-0000-00000000000f", out));
EXPECT_EQ(out.front(), 0);
EXPECT_EQ(out.back(), 15);
EXPECT_TRUE(cc::hexStringToUuid("00000000-0000-0000-0000-0000000000ff", out));
EXPECT_EQ(out.front(), 0);
EXPECT_EQ(out.back(), 255);
EXPECT_TRUE(cc::hexStringToUuid("ffffffff-ffff-ffff-ffff-ffffffffffff", out));
EXPECT_EQ(out, allOnes);
}
TEST(CacheCreatorTest, BadHexStringUuids) {
UuidArray out = {};
EXPECT_FALSE(cc::hexStringToUuid("", out));
EXPECT_FALSE(cc::hexStringToUuid("----", out));
EXPECT_FALSE(cc::hexStringToUuid("ffffffffffffffffffffffffffffffff", out));
EXPECT_FALSE(cc::hexStringToUuid("fffffff-ffff-ffff-ffff-ffffffffffff", out));
EXPECT_FALSE(cc::hexStringToUuid("0ffffffff-ffff-ffff-ffff-ffffffffffff", out));
EXPECT_FALSE(cc::hexStringToUuid("ffffffff-ffff-ffff-ffff-ffffffffffff0", out));
EXPECT_FALSE(cc::hexStringToUuid("ffffffff-ffff-ffff-ffff0ffffffffffff", out));
EXPECT_FALSE(cc::hexStringToUuid("ffffffff-ffff-ffff-ffff-ffffffffffff-", out));
EXPECT_FALSE(cc::hexStringToUuid("ffffffff\0-ffff-ffff-ffff-ffffffffffff", out));
EXPECT_FALSE(cc::hexStringToUuid("gfffffff-ffff-ffff-ffff-ffffffffffff", out));
EXPECT_FALSE(cc::hexStringToUuid("FFFFFFFF-FFFF-FFFF-FFFF-FFFFFFFFFFFF", out));
EXPECT_FALSE(cc::hexStringToUuid("Hey, what's up?", out));
UuidArray allZeros = {};
EXPECT_EQ(out, allZeros);
}
TEST(CacheCreatorTest, FullUuidRoundtrip) {
UuidArray uuid = {16, 2, 104, 108, 0, 3, 0, 0, 213, 232, 11, 199, 227, 23, 129, 116};
cc::UuidString hexStr = cc::uuidToHexString(uuid);
EXPECT_EQ(hexStr, "1002686c-0003-0000-d5e8-0bc7e3178174");
UuidArray dumped = {};
EXPECT_TRUE(cc::hexStringToUuid(hexStr, dumped));
EXPECT_EQ(dumped, uuid);
}
TEST(CacheCreatorTest, GetCacheInfoFromInvalidPalMetadataBlob) {
char badMetadata[10] = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9};
llvm::StringRef noteBlob(badMetadata, sizeof(badMetadata));
llvm::Expected<cc::ElfLlpcCacheInfo> cacheInfoOrErr = cc::getCacheInfoFromMetadataBlob(noteBlob);
llvm::Error err = cacheInfoOrErr.takeError();
EXPECT_TRUE(err.isA<llvm::StringError>());
llvm::consumeError(std::move(err));
}
TEST(CacheCreatorTest, GetCacheInfoFromValidPalMetadataBlob) {
const char *sampleMetadata = R"(---
amdpal.pipelines:
- .xgl_cache_info:
.128_bit_cache_hash:
- 17226562260713912943
- 15513868906143827149
.llpc_version: !str '46.1'
...
)";
llvm::msgpack::Document document;
document.fromYAML(sampleMetadata);
std::string noteBlob;
document.writeToBlob(noteBlob);
llvm::Expected<cc::ElfLlpcCacheInfo> cacheInfoOrErr = cc::getCacheInfoFromMetadataBlob(noteBlob);
EXPECT_TRUE((bool)cacheInfoOrErr);
cc::ElfLlpcCacheInfo elfLlpcInfo = cacheInfoOrErr.get();
EXPECT_EQ(elfLlpcInfo.cacheHash.qwords[0], 17226562260713912943u);
EXPECT_EQ(elfLlpcInfo.cacheHash.qwords[1], 15513868906143827149u);
EXPECT_EQ(elfLlpcInfo.llpcVersion.getMajor(), 46u);
EXPECT_EQ(elfLlpcInfo.llpcVersion.getMinor().getValue(), 1u);
}
<|endoftext|> |
<commit_before>// Copyright (c) 2013 GitHub, Inc.
// Use of this source code is governed by the MIT license that can be
// found in the LICENSE file.
#include "atom/common/api/atom_bindings.h"
#include <algorithm>
#include <iostream>
#include <string>
#include <utility>
#include <vector>
#include "atom/browser/browser.h"
#include "atom/common/api/locker.h"
#include "atom/common/application_info.h"
#include "atom/common/atom_version.h"
#include "atom/common/heap_snapshot.h"
#include "atom/common/native_mate_converters/file_path_converter.h"
#include "atom/common/native_mate_converters/string16_converter.h"
#include "atom/common/promise_util.h"
#include "base/logging.h"
#include "base/process/process_handle.h"
#include "base/process/process_info.h"
#include "base/process/process_metrics_iocounters.h"
#include "base/system/sys_info.h"
#include "base/threading/thread_restrictions.h"
#include "chrome/common/chrome_version.h"
#include "native_mate/dictionary.h"
#include "services/resource_coordinator/public/cpp/memory_instrumentation/global_memory_dump.h"
#include "services/resource_coordinator/public/cpp/memory_instrumentation/memory_instrumentation.h"
// Must be the last in the includes list, otherwise the definition of chromium
// macros conflicts with node macros.
#include "atom/common/node_includes.h"
namespace atom {
namespace {
// Dummy class type that used for crashing the program.
struct DummyClass {
bool crash;
};
// Called when there is a fatal error in V8, we just crash the process here so
// we can get the stack trace.
void FatalErrorCallback(const char* location, const char* message) {
LOG(ERROR) << "Fatal error in V8: " << location << " " << message;
AtomBindings::Crash();
}
} // namespace
AtomBindings::AtomBindings(uv_loop_t* loop) {
uv_async_init(loop, &call_next_tick_async_, OnCallNextTick);
call_next_tick_async_.data = this;
metrics_ = base::ProcessMetrics::CreateCurrentProcessMetrics();
}
AtomBindings::~AtomBindings() {
uv_close(reinterpret_cast<uv_handle_t*>(&call_next_tick_async_), nullptr);
}
// static
void AtomBindings::BindProcess(v8::Isolate* isolate,
mate::Dictionary* process,
base::ProcessMetrics* metrics) {
// These bindings are shared between sandboxed & unsandboxed renderers
process->SetMethod("crash", &Crash);
process->SetMethod("hang", &Hang);
process->SetMethod("log", &Log);
process->SetMethod("getCreationTime", &GetCreationTime);
process->SetMethod("getHeapStatistics", &GetHeapStatistics);
process->SetMethod("getProcessMemoryInfo", &GetProcessMemoryInfo);
process->SetMethod("getSystemMemoryInfo", &GetSystemMemoryInfo);
process->SetMethod("getIOCounters", &GetIOCounters);
process->SetMethod("getCPUUsage", base::Bind(&AtomBindings::GetCPUUsage,
base::Unretained(metrics)));
#if defined(MAS_BUILD)
process->SetReadOnly("mas", true);
#endif
#if defined(OS_WIN)
if (IsRunningInDesktopBridge())
process->SetReadOnly("windowsStore", true);
#endif
}
void AtomBindings::BindTo(v8::Isolate* isolate, v8::Local<v8::Object> process) {
isolate->SetFatalErrorHandler(FatalErrorCallback);
mate::Dictionary dict(isolate, process);
BindProcess(isolate, &dict, metrics_.get());
dict.SetMethod("takeHeapSnapshot", &TakeHeapSnapshot);
#if defined(OS_POSIX)
dict.SetMethod("setFdLimit", &base::IncreaseFdLimitTo);
#endif
dict.SetMethod("activateUvLoop", base::Bind(&AtomBindings::ActivateUVLoop,
base::Unretained(this)));
mate::Dictionary versions;
if (dict.Get("versions", &versions)) {
versions.SetReadOnly(ATOM_PROJECT_NAME, ATOM_VERSION_STRING);
versions.SetReadOnly("chrome", CHROME_VERSION_STRING);
}
}
void AtomBindings::EnvironmentDestroyed(node::Environment* env) {
auto it =
std::find(pending_next_ticks_.begin(), pending_next_ticks_.end(), env);
if (it != pending_next_ticks_.end())
pending_next_ticks_.erase(it);
}
void AtomBindings::ActivateUVLoop(v8::Isolate* isolate) {
node::Environment* env = node::Environment::GetCurrent(isolate);
if (std::find(pending_next_ticks_.begin(), pending_next_ticks_.end(), env) !=
pending_next_ticks_.end())
return;
pending_next_ticks_.push_back(env);
uv_async_send(&call_next_tick_async_);
}
// static
void AtomBindings::OnCallNextTick(uv_async_t* handle) {
AtomBindings* self = static_cast<AtomBindings*>(handle->data);
for (std::list<node::Environment*>::const_iterator it =
self->pending_next_ticks_.begin();
it != self->pending_next_ticks_.end(); ++it) {
node::Environment* env = *it;
mate::Locker locker(env->isolate());
v8::Context::Scope context_scope(env->context());
node::InternalCallbackScope scope(
env, v8::Local<v8::Object>(), {0, 0},
node::InternalCallbackScope::kAllowEmptyResource);
}
self->pending_next_ticks_.clear();
}
// static
void AtomBindings::Log(const base::string16& message) {
std::cout << message << std::flush;
}
// static
void AtomBindings::Crash() {
static_cast<DummyClass*>(nullptr)->crash = true;
}
// static
void AtomBindings::Hang() {
for (;;)
base::PlatformThread::Sleep(base::TimeDelta::FromSeconds(1));
}
// static
v8::Local<v8::Value> AtomBindings::GetHeapStatistics(v8::Isolate* isolate) {
v8::HeapStatistics v8_heap_stats;
isolate->GetHeapStatistics(&v8_heap_stats);
mate::Dictionary dict = mate::Dictionary::CreateEmpty(isolate);
dict.SetHidden("simple", true);
dict.Set("totalHeapSize",
static_cast<double>(v8_heap_stats.total_heap_size() >> 10));
dict.Set(
"totalHeapSizeExecutable",
static_cast<double>(v8_heap_stats.total_heap_size_executable() >> 10));
dict.Set("totalPhysicalSize",
static_cast<double>(v8_heap_stats.total_physical_size() >> 10));
dict.Set("totalAvailableSize",
static_cast<double>(v8_heap_stats.total_available_size() >> 10));
dict.Set("usedHeapSize",
static_cast<double>(v8_heap_stats.used_heap_size() >> 10));
dict.Set("heapSizeLimit",
static_cast<double>(v8_heap_stats.heap_size_limit() >> 10));
dict.Set("mallocedMemory",
static_cast<double>(v8_heap_stats.malloced_memory() >> 10));
dict.Set("peakMallocedMemory",
static_cast<double>(v8_heap_stats.peak_malloced_memory() >> 10));
dict.Set("doesZapGarbage",
static_cast<bool>(v8_heap_stats.does_zap_garbage()));
return dict.GetHandle();
}
// static
v8::Local<v8::Value> AtomBindings::GetCreationTime(v8::Isolate* isolate) {
auto timeValue = base::CurrentProcessInfo::CreationTime();
if (timeValue.is_null()) {
return v8::Null(isolate);
}
double jsTime = timeValue.ToJsTime();
return v8::Number::New(isolate, jsTime);
}
// static
v8::Local<v8::Value> AtomBindings::GetSystemMemoryInfo(v8::Isolate* isolate,
mate::Arguments* args) {
base::SystemMemoryInfoKB mem_info;
if (!base::GetSystemMemoryInfo(&mem_info)) {
args->ThrowError("Unable to retrieve system memory information");
return v8::Undefined(isolate);
}
mate::Dictionary dict = mate::Dictionary::CreateEmpty(isolate);
dict.SetHidden("simple", true);
dict.Set("total", mem_info.total);
// See Chromium's "base/process/process_metrics.h" for an explanation.
int free =
#if defined(OS_WIN)
mem_info.avail_phys;
#else
mem_info.free;
#endif
dict.Set("free", free);
// NB: These return bogus values on macOS
#if !defined(OS_MACOSX)
dict.Set("swapTotal", mem_info.swap_total);
dict.Set("swapFree", mem_info.swap_free);
#endif
return dict.GetHandle();
}
// static
v8::Local<v8::Promise> AtomBindings::GetProcessMemoryInfo(
v8::Isolate* isolate) {
scoped_refptr<util::Promise> promise = new util::Promise(isolate);
if (mate::Locker::IsBrowserProcess() && !Browser::Get()->is_ready()) {
promise->RejectWithErrorMessage(
"Memory Info is available only after app ready");
return promise->GetHandle();
}
v8::Global<v8::Context> context(isolate, isolate->GetCurrentContext());
memory_instrumentation::MemoryInstrumentation::GetInstance()
->RequestGlobalDumpForPid(base::GetCurrentProcId(),
std::vector<std::string>(),
base::Bind(&AtomBindings::DidReceiveMemoryDump,
std::move(context), promise));
return promise->GetHandle();
}
// static
void AtomBindings::DidReceiveMemoryDump(
const v8::Global<v8::Context>& context,
scoped_refptr<util::Promise> promise,
bool success,
std::unique_ptr<memory_instrumentation::GlobalMemoryDump> global_dump) {
v8::Isolate* isolate = promise->isolate();
mate::Locker locker(isolate);
v8::HandleScope handle_scope(isolate);
v8::MicrotasksScope script_scope(isolate,
v8::MicrotasksScope::kRunMicrotasks);
v8::Context::Scope context_scope(
v8::Local<v8::Context>::New(isolate, context));
if (!success) {
promise->RejectWithErrorMessage("Failed to create memory dump");
return;
}
bool resolved = false;
for (const memory_instrumentation::GlobalMemoryDump::ProcessDump& dump :
global_dump->process_dumps()) {
if (base::GetCurrentProcId() == dump.pid()) {
mate::Dictionary dict = mate::Dictionary::CreateEmpty(isolate);
const auto& osdump = dump.os_dump();
#if defined(OS_LINUX) || defined(OS_WIN)
dict.Set("residentSet", osdump.resident_set_kb);
#endif
dict.Set("private", osdump.private_footprint_kb);
dict.Set("shared", osdump.shared_footprint_kb);
promise->Resolve(dict.GetHandle());
resolved = true;
break;
}
}
if (!resolved) {
promise->RejectWithErrorMessage(
R"(Failed to find current process memory details in memory dump)");
}
}
// static
v8::Local<v8::Value> AtomBindings::GetCPUUsage(base::ProcessMetrics* metrics,
v8::Isolate* isolate) {
mate::Dictionary dict = mate::Dictionary::CreateEmpty(isolate);
dict.SetHidden("simple", true);
int processor_count = base::SysInfo::NumberOfProcessors();
dict.Set("percentCPUUsage",
metrics->GetPlatformIndependentCPUUsage() / processor_count);
// NB: This will throw NOTIMPLEMENTED() on Windows
// For backwards compatibility, we'll return 0
#if !defined(OS_WIN)
dict.Set("idleWakeupsPerSecond", metrics->GetIdleWakeupsPerSecond());
#else
dict.Set("idleWakeupsPerSecond", 0);
#endif
return dict.GetHandle();
}
// static
v8::Local<v8::Value> AtomBindings::GetIOCounters(v8::Isolate* isolate) {
auto metrics = base::ProcessMetrics::CreateCurrentProcessMetrics();
base::IoCounters io_counters;
mate::Dictionary dict = mate::Dictionary::CreateEmpty(isolate);
dict.SetHidden("simple", true);
if (metrics->GetIOCounters(&io_counters)) {
dict.Set("readOperationCount", io_counters.ReadOperationCount);
dict.Set("writeOperationCount", io_counters.WriteOperationCount);
dict.Set("otherOperationCount", io_counters.OtherOperationCount);
dict.Set("readTransferCount", io_counters.ReadTransferCount);
dict.Set("writeTransferCount", io_counters.WriteTransferCount);
dict.Set("otherTransferCount", io_counters.OtherTransferCount);
}
return dict.GetHandle();
}
// static
bool AtomBindings::TakeHeapSnapshot(v8::Isolate* isolate,
const base::FilePath& file_path) {
base::ThreadRestrictions::ScopedAllowIO allow_io;
base::File file(file_path,
base::File::FLAG_CREATE_ALWAYS | base::File::FLAG_WRITE);
return atom::TakeHeapSnapshot(isolate, &file);
}
} // namespace atom
<commit_msg>CurrentProcessInfo::CreationTime -> Process::Current().CreationTime()<commit_after>// Copyright (c) 2013 GitHub, Inc.
// Use of this source code is governed by the MIT license that can be
// found in the LICENSE file.
#include "atom/common/api/atom_bindings.h"
#include <algorithm>
#include <iostream>
#include <string>
#include <utility>
#include <vector>
#include "atom/browser/browser.h"
#include "atom/common/api/locker.h"
#include "atom/common/application_info.h"
#include "atom/common/atom_version.h"
#include "atom/common/heap_snapshot.h"
#include "atom/common/native_mate_converters/file_path_converter.h"
#include "atom/common/native_mate_converters/string16_converter.h"
#include "atom/common/promise_util.h"
#include "base/logging.h"
#include "base/process/process.h"
#include "base/process/process_handle.h"
#include "base/process/process_metrics_iocounters.h"
#include "base/system/sys_info.h"
#include "base/threading/thread_restrictions.h"
#include "chrome/common/chrome_version.h"
#include "native_mate/dictionary.h"
#include "services/resource_coordinator/public/cpp/memory_instrumentation/global_memory_dump.h"
#include "services/resource_coordinator/public/cpp/memory_instrumentation/memory_instrumentation.h"
// Must be the last in the includes list, otherwise the definition of chromium
// macros conflicts with node macros.
#include "atom/common/node_includes.h"
namespace atom {
namespace {
// Dummy class type that used for crashing the program.
struct DummyClass {
bool crash;
};
// Called when there is a fatal error in V8, we just crash the process here so
// we can get the stack trace.
void FatalErrorCallback(const char* location, const char* message) {
LOG(ERROR) << "Fatal error in V8: " << location << " " << message;
AtomBindings::Crash();
}
} // namespace
AtomBindings::AtomBindings(uv_loop_t* loop) {
uv_async_init(loop, &call_next_tick_async_, OnCallNextTick);
call_next_tick_async_.data = this;
metrics_ = base::ProcessMetrics::CreateCurrentProcessMetrics();
}
AtomBindings::~AtomBindings() {
uv_close(reinterpret_cast<uv_handle_t*>(&call_next_tick_async_), nullptr);
}
// static
void AtomBindings::BindProcess(v8::Isolate* isolate,
mate::Dictionary* process,
base::ProcessMetrics* metrics) {
// These bindings are shared between sandboxed & unsandboxed renderers
process->SetMethod("crash", &Crash);
process->SetMethod("hang", &Hang);
process->SetMethod("log", &Log);
process->SetMethod("getCreationTime", &GetCreationTime);
process->SetMethod("getHeapStatistics", &GetHeapStatistics);
process->SetMethod("getProcessMemoryInfo", &GetProcessMemoryInfo);
process->SetMethod("getSystemMemoryInfo", &GetSystemMemoryInfo);
process->SetMethod("getIOCounters", &GetIOCounters);
process->SetMethod("getCPUUsage", base::Bind(&AtomBindings::GetCPUUsage,
base::Unretained(metrics)));
#if defined(MAS_BUILD)
process->SetReadOnly("mas", true);
#endif
#if defined(OS_WIN)
if (IsRunningInDesktopBridge())
process->SetReadOnly("windowsStore", true);
#endif
}
void AtomBindings::BindTo(v8::Isolate* isolate, v8::Local<v8::Object> process) {
isolate->SetFatalErrorHandler(FatalErrorCallback);
mate::Dictionary dict(isolate, process);
BindProcess(isolate, &dict, metrics_.get());
dict.SetMethod("takeHeapSnapshot", &TakeHeapSnapshot);
#if defined(OS_POSIX)
dict.SetMethod("setFdLimit", &base::IncreaseFdLimitTo);
#endif
dict.SetMethod("activateUvLoop", base::Bind(&AtomBindings::ActivateUVLoop,
base::Unretained(this)));
mate::Dictionary versions;
if (dict.Get("versions", &versions)) {
versions.SetReadOnly(ATOM_PROJECT_NAME, ATOM_VERSION_STRING);
versions.SetReadOnly("chrome", CHROME_VERSION_STRING);
}
}
void AtomBindings::EnvironmentDestroyed(node::Environment* env) {
auto it =
std::find(pending_next_ticks_.begin(), pending_next_ticks_.end(), env);
if (it != pending_next_ticks_.end())
pending_next_ticks_.erase(it);
}
void AtomBindings::ActivateUVLoop(v8::Isolate* isolate) {
node::Environment* env = node::Environment::GetCurrent(isolate);
if (std::find(pending_next_ticks_.begin(), pending_next_ticks_.end(), env) !=
pending_next_ticks_.end())
return;
pending_next_ticks_.push_back(env);
uv_async_send(&call_next_tick_async_);
}
// static
void AtomBindings::OnCallNextTick(uv_async_t* handle) {
AtomBindings* self = static_cast<AtomBindings*>(handle->data);
for (std::list<node::Environment*>::const_iterator it =
self->pending_next_ticks_.begin();
it != self->pending_next_ticks_.end(); ++it) {
node::Environment* env = *it;
mate::Locker locker(env->isolate());
v8::Context::Scope context_scope(env->context());
node::InternalCallbackScope scope(
env, v8::Local<v8::Object>(), {0, 0},
node::InternalCallbackScope::kAllowEmptyResource);
}
self->pending_next_ticks_.clear();
}
// static
void AtomBindings::Log(const base::string16& message) {
std::cout << message << std::flush;
}
// static
void AtomBindings::Crash() {
static_cast<DummyClass*>(nullptr)->crash = true;
}
// static
void AtomBindings::Hang() {
for (;;)
base::PlatformThread::Sleep(base::TimeDelta::FromSeconds(1));
}
// static
v8::Local<v8::Value> AtomBindings::GetHeapStatistics(v8::Isolate* isolate) {
v8::HeapStatistics v8_heap_stats;
isolate->GetHeapStatistics(&v8_heap_stats);
mate::Dictionary dict = mate::Dictionary::CreateEmpty(isolate);
dict.SetHidden("simple", true);
dict.Set("totalHeapSize",
static_cast<double>(v8_heap_stats.total_heap_size() >> 10));
dict.Set(
"totalHeapSizeExecutable",
static_cast<double>(v8_heap_stats.total_heap_size_executable() >> 10));
dict.Set("totalPhysicalSize",
static_cast<double>(v8_heap_stats.total_physical_size() >> 10));
dict.Set("totalAvailableSize",
static_cast<double>(v8_heap_stats.total_available_size() >> 10));
dict.Set("usedHeapSize",
static_cast<double>(v8_heap_stats.used_heap_size() >> 10));
dict.Set("heapSizeLimit",
static_cast<double>(v8_heap_stats.heap_size_limit() >> 10));
dict.Set("mallocedMemory",
static_cast<double>(v8_heap_stats.malloced_memory() >> 10));
dict.Set("peakMallocedMemory",
static_cast<double>(v8_heap_stats.peak_malloced_memory() >> 10));
dict.Set("doesZapGarbage",
static_cast<bool>(v8_heap_stats.does_zap_garbage()));
return dict.GetHandle();
}
// static
v8::Local<v8::Value> AtomBindings::GetCreationTime(v8::Isolate* isolate) {
auto timeValue = base::Process::Current().CreationTime();
if (timeValue.is_null()) {
return v8::Null(isolate);
}
double jsTime = timeValue.ToJsTime();
return v8::Number::New(isolate, jsTime);
}
// static
v8::Local<v8::Value> AtomBindings::GetSystemMemoryInfo(v8::Isolate* isolate,
mate::Arguments* args) {
base::SystemMemoryInfoKB mem_info;
if (!base::GetSystemMemoryInfo(&mem_info)) {
args->ThrowError("Unable to retrieve system memory information");
return v8::Undefined(isolate);
}
mate::Dictionary dict = mate::Dictionary::CreateEmpty(isolate);
dict.SetHidden("simple", true);
dict.Set("total", mem_info.total);
// See Chromium's "base/process/process_metrics.h" for an explanation.
int free =
#if defined(OS_WIN)
mem_info.avail_phys;
#else
mem_info.free;
#endif
dict.Set("free", free);
// NB: These return bogus values on macOS
#if !defined(OS_MACOSX)
dict.Set("swapTotal", mem_info.swap_total);
dict.Set("swapFree", mem_info.swap_free);
#endif
return dict.GetHandle();
}
// static
v8::Local<v8::Promise> AtomBindings::GetProcessMemoryInfo(
v8::Isolate* isolate) {
scoped_refptr<util::Promise> promise = new util::Promise(isolate);
if (mate::Locker::IsBrowserProcess() && !Browser::Get()->is_ready()) {
promise->RejectWithErrorMessage(
"Memory Info is available only after app ready");
return promise->GetHandle();
}
v8::Global<v8::Context> context(isolate, isolate->GetCurrentContext());
memory_instrumentation::MemoryInstrumentation::GetInstance()
->RequestGlobalDumpForPid(base::GetCurrentProcId(),
std::vector<std::string>(),
base::Bind(&AtomBindings::DidReceiveMemoryDump,
std::move(context), promise));
return promise->GetHandle();
}
// static
void AtomBindings::DidReceiveMemoryDump(
const v8::Global<v8::Context>& context,
scoped_refptr<util::Promise> promise,
bool success,
std::unique_ptr<memory_instrumentation::GlobalMemoryDump> global_dump) {
v8::Isolate* isolate = promise->isolate();
mate::Locker locker(isolate);
v8::HandleScope handle_scope(isolate);
v8::MicrotasksScope script_scope(isolate,
v8::MicrotasksScope::kRunMicrotasks);
v8::Context::Scope context_scope(
v8::Local<v8::Context>::New(isolate, context));
if (!success) {
promise->RejectWithErrorMessage("Failed to create memory dump");
return;
}
bool resolved = false;
for (const memory_instrumentation::GlobalMemoryDump::ProcessDump& dump :
global_dump->process_dumps()) {
if (base::GetCurrentProcId() == dump.pid()) {
mate::Dictionary dict = mate::Dictionary::CreateEmpty(isolate);
const auto& osdump = dump.os_dump();
#if defined(OS_LINUX) || defined(OS_WIN)
dict.Set("residentSet", osdump.resident_set_kb);
#endif
dict.Set("private", osdump.private_footprint_kb);
dict.Set("shared", osdump.shared_footprint_kb);
promise->Resolve(dict.GetHandle());
resolved = true;
break;
}
}
if (!resolved) {
promise->RejectWithErrorMessage(
R"(Failed to find current process memory details in memory dump)");
}
}
// static
v8::Local<v8::Value> AtomBindings::GetCPUUsage(base::ProcessMetrics* metrics,
v8::Isolate* isolate) {
mate::Dictionary dict = mate::Dictionary::CreateEmpty(isolate);
dict.SetHidden("simple", true);
int processor_count = base::SysInfo::NumberOfProcessors();
dict.Set("percentCPUUsage",
metrics->GetPlatformIndependentCPUUsage() / processor_count);
// NB: This will throw NOTIMPLEMENTED() on Windows
// For backwards compatibility, we'll return 0
#if !defined(OS_WIN)
dict.Set("idleWakeupsPerSecond", metrics->GetIdleWakeupsPerSecond());
#else
dict.Set("idleWakeupsPerSecond", 0);
#endif
return dict.GetHandle();
}
// static
v8::Local<v8::Value> AtomBindings::GetIOCounters(v8::Isolate* isolate) {
auto metrics = base::ProcessMetrics::CreateCurrentProcessMetrics();
base::IoCounters io_counters;
mate::Dictionary dict = mate::Dictionary::CreateEmpty(isolate);
dict.SetHidden("simple", true);
if (metrics->GetIOCounters(&io_counters)) {
dict.Set("readOperationCount", io_counters.ReadOperationCount);
dict.Set("writeOperationCount", io_counters.WriteOperationCount);
dict.Set("otherOperationCount", io_counters.OtherOperationCount);
dict.Set("readTransferCount", io_counters.ReadTransferCount);
dict.Set("writeTransferCount", io_counters.WriteTransferCount);
dict.Set("otherTransferCount", io_counters.OtherTransferCount);
}
return dict.GetHandle();
}
// static
bool AtomBindings::TakeHeapSnapshot(v8::Isolate* isolate,
const base::FilePath& file_path) {
base::ThreadRestrictions::ScopedAllowIO allow_io;
base::File file(file_path,
base::File::FLAG_CREATE_ALWAYS | base::File::FLAG_WRITE);
return atom::TakeHeapSnapshot(isolate, &file);
}
} // namespace atom
<|endoftext|> |
<commit_before>// Copyright (c) 2010 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome/browser/chromeos/dom_ui/language_options_handler.h"
#include <map>
#include <set>
#include <string>
#include <utility>
#include "app/l10n_util.h"
#include "base/utf_string_conversions.h"
#include "base/values.h"
#include "chrome/app/chrome_dll_resource.h"
#include "chrome/browser/browser.h"
#include "chrome/browser/browser_process.h"
#include "chrome/browser/chromeos/cros/cros_library.h"
#include "chrome/browser/chromeos/cros/input_method_library.h"
#include "chrome/browser/chromeos/input_method/input_method_util.h"
#include "chrome/browser/pref_service.h"
#include "chrome/browser/tab_contents/tab_contents.h"
#include "chrome/common/pref_names.h"
#include "grit/chromium_strings.h"
#include "grit/generated_resources.h"
namespace chromeos {
LanguageOptionsHandler::LanguageOptionsHandler() {
}
LanguageOptionsHandler::~LanguageOptionsHandler() {
}
void LanguageOptionsHandler::GetLocalizedValues(
DictionaryValue* localized_strings) {
DCHECK(localized_strings);
localized_strings->SetString("languagePage",
l10n_util::GetStringUTF16(IDS_OPTIONS_SETTINGS_LANGUAGES_DIALOG_TITLE));
localized_strings->SetString("add_button",
l10n_util::GetStringUTF16(IDS_OPTIONS_SETTINGS_LANGUAGES_ADD_BUTTON));
localized_strings->SetString("configure",
l10n_util::GetStringUTF16(IDS_OPTIONS_SETTINGS_LANGUAGES_CONFIGURE));
localized_strings->SetString("input_method",
l10n_util::GetStringUTF16(IDS_OPTIONS_SETTINGS_LANGUAGES_INPUT_METHOD));
localized_strings->SetString("languages",
l10n_util::GetStringUTF16(IDS_OPTIONS_SETTINGS_LANGUAGES_LANGUAGES));
localized_strings->SetString("please_add_another_input_method",
l10n_util::GetStringUTF16(
IDS_OPTIONS_SETTINGS_LANGUAGES_PLEASE_ADD_ANOTHER_INPUT_METHOD));
localized_strings->SetString("please_add_another_language",
l10n_util::GetStringUTF16(
IDS_OPTIONS_SETTINGS_LANGUAGES_PLEASE_ADD_ANOTHER_LANGUAGE));
localized_strings->SetString(L"ok_button", l10n_util::GetStringUTF16(IDS_OK));
localized_strings->SetString("remove_button",
l10n_util::GetStringUTF16(IDS_OPTIONS_SETTINGS_LANGUAGES_REMOVE_BUTTON));
localized_strings->SetString("restart_button",
l10n_util::GetStringUTF16(IDS_OPTIONS_SETTINGS_LANGUAGES_RESTART_BUTTON));
localized_strings->SetString("add_language_instructions",
l10n_util::GetStringUTF16(
IDS_OPTIONS_SETTINGS_LANGUAGES_ADD_LANGUAGE_INSTRUCTIONS));
localized_strings->SetString("input_method_instructions",
l10n_util::GetStringUTF16(
IDS_OPTIONS_SETTINGS_LANGUAGES_INPUT_METHOD_INSTRUCTIONS));
localized_strings->SetString("switch_input_methods_hint",
l10n_util::GetStringFUTF16(
IDS_OPTIONS_SETTINGS_LANGUAGES_SWITCH_INPUT_METHODS_HINT,
ASCIIToUTF16("alt+shift")));
localized_strings->SetString("select_previous_input_method_hint",
l10n_util::GetStringFUTF16(
IDS_OPTIONS_SETTINGS_LANGUAGES_SELECT_PREVIOUS_INPUT_METHOD_HINT,
ASCIIToUTF16("ctrl+space")));
localized_strings->SetString("cannot_be_displayed_in_this_language",
l10n_util::GetStringFUTF16(
IDS_OPTIONS_SETTINGS_LANGUAGES_CANNOT_BE_DISPLAYED_IN_THIS_LANGUAGE,
l10n_util::GetStringUTF16(IDS_PRODUCT_OS_NAME)));
localized_strings->SetString("is_displayed_in_this_language",
l10n_util::GetStringFUTF16(
IDS_OPTIONS_SETTINGS_LANGUAGES_IS_DISPLAYED_IN_THIS_LANGUAGE,
l10n_util::GetStringUTF16(IDS_PRODUCT_OS_NAME)));
localized_strings->SetString("display_in_this_language",
l10n_util::GetStringFUTF16(
IDS_OPTIONS_SETTINGS_LANGUAGES_DISPLAY_IN_THIS_LANGUAGE,
l10n_util::GetStringUTF16(IDS_PRODUCT_OS_NAME)));
localized_strings->SetString("restart_required",
l10n_util::GetStringUTF16(IDS_OPTIONS_RESTART_REQUIRED));
localized_strings->SetString("this_language_is_currently_in_use",
l10n_util::GetStringFUTF16(
IDS_OPTIONS_SETTINGS_LANGUAGES_THIS_LANGUAGE_IS_CURRENTLY_IN_USE,
l10n_util::GetStringUTF16(IDS_PRODUCT_OS_NAME)));
// GetSupportedInputMethods() never return NULL.
scoped_ptr<InputMethodDescriptors> descriptors(
CrosLibrary::Get()->GetInputMethodLibrary()->GetSupportedInputMethods());
// The followigns are resources, rather than local strings.
localized_strings->SetString("currentUiLanguageCode",
g_browser_process->GetApplicationLocale());
localized_strings->Set("inputMethodList", GetInputMethodList(*descriptors));
localized_strings->Set("languageList", GetLanguageList(*descriptors));
localized_strings->Set("uiLanguageCodeSet", GetUiLanguageCodeSet());
}
void LanguageOptionsHandler::RegisterMessages() {
DCHECK(dom_ui_);
dom_ui_->RegisterMessageCallback("uiLanguageChange",
NewCallback(this, &LanguageOptionsHandler::UiLanguageChangeCallback));
dom_ui_->RegisterMessageCallback("uiLanguageRestart",
NewCallback(this, &LanguageOptionsHandler::RestartCallback));
}
ListValue* LanguageOptionsHandler::GetInputMethodList(
const InputMethodDescriptors& descriptors) {
ListValue* input_method_list = new ListValue();
for (size_t i = 0; i < descriptors.size(); ++i) {
const InputMethodDescriptor& descriptor = descriptors[i];
const std::string language_code =
input_method::GetLanguageCodeFromDescriptor(descriptor);
const std::string display_name =
input_method::GetInputMethodDisplayNameFromId(descriptor.id);
DictionaryValue* dictionary = new DictionaryValue();
dictionary->SetString("id", descriptor.id);
dictionary->SetString("displayName", display_name);
// One input method can be associated with multiple languages, hence
// we use a dictionary here.
DictionaryValue* language_codes = new DictionaryValue();
language_codes->SetBoolean(language_code, true);
// Check kExtraLanguages to see if there are languages associated with
// this input method. If these are present, add these.
for (size_t j = 0; j < arraysize(input_method::kExtraLanguages); ++j) {
const std::string extra_input_method_id =
input_method::kExtraLanguages[j].input_method_id;
const std::string extra_language_code =
input_method::kExtraLanguages[j].language_code;
if (extra_input_method_id == descriptor.id) {
language_codes->SetBoolean(extra_language_code, true);
}
}
dictionary->Set("languageCodeSet", language_codes);
input_method_list->Append(dictionary);
}
return input_method_list;
}
ListValue* LanguageOptionsHandler::GetLanguageList(
const InputMethodDescriptors& descriptors) {
std::set<std::string> language_codes;
// Collect the language codes from the supported input methods.
for (size_t i = 0; i < descriptors.size(); ++i) {
const InputMethodDescriptor& descriptor = descriptors[i];
const std::string language_code =
input_method::GetLanguageCodeFromDescriptor(descriptor);
language_codes.insert(language_code);
}
// Collect the language codes from kExtraLanguages.
for (size_t i = 0; i < arraysize(input_method::kExtraLanguages); ++i) {
const char* language_code =
input_method::kExtraLanguages[i].language_code;
language_codes.insert(language_code);
}
// Map of display name -> {language code, native_display_name}.
// In theory, we should be able to create a map that is sorted by
// display names using ICU comparator, but doing it is hard, thus we'll
// use an auxiliary vector to achieve the same result.
typedef std::pair<std::string, std::wstring> LanguagePair;
typedef std::map<std::wstring, LanguagePair> LanguageMap;
LanguageMap language_map;
// The auxiliary vector mentioned above.
std::vector<std::wstring> display_names;
// Build the list of display names, and build the language map.
for (std::set<std::string>::const_iterator iter = language_codes.begin();
iter != language_codes.end(); ++iter) {
const std::wstring display_name =
input_method::GetLanguageDisplayNameFromCode(*iter);
const std::wstring native_display_name =
input_method::GetLanguageNativeDisplayNameFromCode(*iter);
display_names.push_back(display_name);
language_map[display_name] =
std::make_pair(*iter, native_display_name);
}
DCHECK_EQ(display_names.size(), language_map.size());
// Sort display names using locale specific sorter.
l10n_util::SortStrings(g_browser_process->GetApplicationLocale(),
&display_names);
// Build the language list from the language map.
ListValue* language_list = new ListValue();
for (size_t i = 0; i < display_names.size(); ++i) {
const LanguagePair& pair = language_map[display_names[i]];
DictionaryValue* dictionary = new DictionaryValue();
dictionary->SetString("code", pair.first);
dictionary->SetString("displayName", WideToUTF16Hack(display_names[i]));
dictionary->SetString("nativeDisplayName", WideToUTF16Hack(pair.second));
language_list->Append(dictionary);
}
return language_list;
}
DictionaryValue* LanguageOptionsHandler::GetUiLanguageCodeSet() {
DictionaryValue* dictionary = new DictionaryValue();
const std::vector<std::string>& available_locales =
l10n_util::GetAvailableLocales();
for (size_t i = 0; i < available_locales.size(); ++i) {
dictionary->SetBoolean(available_locales[i], true);
}
return dictionary;
}
void LanguageOptionsHandler::UiLanguageChangeCallback(
const Value* value) {
if (!value || !value->IsType(Value::TYPE_LIST)) {
NOTREACHED();
LOG(INFO) << "NOTREACHED";
return;
}
const ListValue* list_value = static_cast<const ListValue*>(value);
std::string language_code;
if (list_value->GetSize() != 1 ||
!list_value->GetString(0, &language_code)) {
NOTREACHED();
LOG(INFO) << "NOTREACHED";
return;
}
PrefService* prefs = g_browser_process->local_state();
prefs->SetString(prefs::kApplicationLocale, language_code);
prefs->SavePersistentPrefs();
dom_ui_->CallJavascriptFunction(
L"options.LanguageOptions.uiLanguageSaved");
}
void LanguageOptionsHandler::RestartCallback(const Value* value) {
Browser* browser = Browser::GetBrowserForController(
&dom_ui_->tab_contents()->controller(), NULL);
// TODO(kochi): For ChromiumOS, just exiting means browser restart.
// Implement browser restart for Chromium Win/Linux/Mac.
if (browser)
browser->ExecuteCommand(IDC_EXIT);
}
} // namespace chromeos
<commit_msg>Fix build (wstring->string mismatch).<commit_after>// Copyright (c) 2010 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome/browser/chromeos/dom_ui/language_options_handler.h"
#include <map>
#include <set>
#include <string>
#include <utility>
#include "app/l10n_util.h"
#include "base/utf_string_conversions.h"
#include "base/values.h"
#include "chrome/app/chrome_dll_resource.h"
#include "chrome/browser/browser.h"
#include "chrome/browser/browser_process.h"
#include "chrome/browser/chromeos/cros/cros_library.h"
#include "chrome/browser/chromeos/cros/input_method_library.h"
#include "chrome/browser/chromeos/input_method/input_method_util.h"
#include "chrome/browser/pref_service.h"
#include "chrome/browser/tab_contents/tab_contents.h"
#include "chrome/common/pref_names.h"
#include "grit/chromium_strings.h"
#include "grit/generated_resources.h"
namespace chromeos {
LanguageOptionsHandler::LanguageOptionsHandler() {
}
LanguageOptionsHandler::~LanguageOptionsHandler() {
}
void LanguageOptionsHandler::GetLocalizedValues(
DictionaryValue* localized_strings) {
DCHECK(localized_strings);
localized_strings->SetString("languagePage",
l10n_util::GetStringUTF16(IDS_OPTIONS_SETTINGS_LANGUAGES_DIALOG_TITLE));
localized_strings->SetString("add_button",
l10n_util::GetStringUTF16(IDS_OPTIONS_SETTINGS_LANGUAGES_ADD_BUTTON));
localized_strings->SetString("configure",
l10n_util::GetStringUTF16(IDS_OPTIONS_SETTINGS_LANGUAGES_CONFIGURE));
localized_strings->SetString("input_method",
l10n_util::GetStringUTF16(IDS_OPTIONS_SETTINGS_LANGUAGES_INPUT_METHOD));
localized_strings->SetString("languages",
l10n_util::GetStringUTF16(IDS_OPTIONS_SETTINGS_LANGUAGES_LANGUAGES));
localized_strings->SetString("please_add_another_input_method",
l10n_util::GetStringUTF16(
IDS_OPTIONS_SETTINGS_LANGUAGES_PLEASE_ADD_ANOTHER_INPUT_METHOD));
localized_strings->SetString("please_add_another_language",
l10n_util::GetStringUTF16(
IDS_OPTIONS_SETTINGS_LANGUAGES_PLEASE_ADD_ANOTHER_LANGUAGE));
localized_strings->SetString("ok_button", l10n_util::GetStringUTF16(IDS_OK));
localized_strings->SetString("remove_button",
l10n_util::GetStringUTF16(IDS_OPTIONS_SETTINGS_LANGUAGES_REMOVE_BUTTON));
localized_strings->SetString("restart_button",
l10n_util::GetStringUTF16(IDS_OPTIONS_SETTINGS_LANGUAGES_RESTART_BUTTON));
localized_strings->SetString("add_language_instructions",
l10n_util::GetStringUTF16(
IDS_OPTIONS_SETTINGS_LANGUAGES_ADD_LANGUAGE_INSTRUCTIONS));
localized_strings->SetString("input_method_instructions",
l10n_util::GetStringUTF16(
IDS_OPTIONS_SETTINGS_LANGUAGES_INPUT_METHOD_INSTRUCTIONS));
localized_strings->SetString("switch_input_methods_hint",
l10n_util::GetStringFUTF16(
IDS_OPTIONS_SETTINGS_LANGUAGES_SWITCH_INPUT_METHODS_HINT,
ASCIIToUTF16("alt+shift")));
localized_strings->SetString("select_previous_input_method_hint",
l10n_util::GetStringFUTF16(
IDS_OPTIONS_SETTINGS_LANGUAGES_SELECT_PREVIOUS_INPUT_METHOD_HINT,
ASCIIToUTF16("ctrl+space")));
localized_strings->SetString("cannot_be_displayed_in_this_language",
l10n_util::GetStringFUTF16(
IDS_OPTIONS_SETTINGS_LANGUAGES_CANNOT_BE_DISPLAYED_IN_THIS_LANGUAGE,
l10n_util::GetStringUTF16(IDS_PRODUCT_OS_NAME)));
localized_strings->SetString("is_displayed_in_this_language",
l10n_util::GetStringFUTF16(
IDS_OPTIONS_SETTINGS_LANGUAGES_IS_DISPLAYED_IN_THIS_LANGUAGE,
l10n_util::GetStringUTF16(IDS_PRODUCT_OS_NAME)));
localized_strings->SetString("display_in_this_language",
l10n_util::GetStringFUTF16(
IDS_OPTIONS_SETTINGS_LANGUAGES_DISPLAY_IN_THIS_LANGUAGE,
l10n_util::GetStringUTF16(IDS_PRODUCT_OS_NAME)));
localized_strings->SetString("restart_required",
l10n_util::GetStringUTF16(IDS_OPTIONS_RESTART_REQUIRED));
localized_strings->SetString("this_language_is_currently_in_use",
l10n_util::GetStringFUTF16(
IDS_OPTIONS_SETTINGS_LANGUAGES_THIS_LANGUAGE_IS_CURRENTLY_IN_USE,
l10n_util::GetStringUTF16(IDS_PRODUCT_OS_NAME)));
// GetSupportedInputMethods() never return NULL.
scoped_ptr<InputMethodDescriptors> descriptors(
CrosLibrary::Get()->GetInputMethodLibrary()->GetSupportedInputMethods());
// The followigns are resources, rather than local strings.
localized_strings->SetString("currentUiLanguageCode",
g_browser_process->GetApplicationLocale());
localized_strings->Set("inputMethodList", GetInputMethodList(*descriptors));
localized_strings->Set("languageList", GetLanguageList(*descriptors));
localized_strings->Set("uiLanguageCodeSet", GetUiLanguageCodeSet());
}
void LanguageOptionsHandler::RegisterMessages() {
DCHECK(dom_ui_);
dom_ui_->RegisterMessageCallback("uiLanguageChange",
NewCallback(this, &LanguageOptionsHandler::UiLanguageChangeCallback));
dom_ui_->RegisterMessageCallback("uiLanguageRestart",
NewCallback(this, &LanguageOptionsHandler::RestartCallback));
}
ListValue* LanguageOptionsHandler::GetInputMethodList(
const InputMethodDescriptors& descriptors) {
ListValue* input_method_list = new ListValue();
for (size_t i = 0; i < descriptors.size(); ++i) {
const InputMethodDescriptor& descriptor = descriptors[i];
const std::string language_code =
input_method::GetLanguageCodeFromDescriptor(descriptor);
const std::string display_name =
input_method::GetInputMethodDisplayNameFromId(descriptor.id);
DictionaryValue* dictionary = new DictionaryValue();
dictionary->SetString("id", descriptor.id);
dictionary->SetString("displayName", display_name);
// One input method can be associated with multiple languages, hence
// we use a dictionary here.
DictionaryValue* language_codes = new DictionaryValue();
language_codes->SetBoolean(language_code, true);
// Check kExtraLanguages to see if there are languages associated with
// this input method. If these are present, add these.
for (size_t j = 0; j < arraysize(input_method::kExtraLanguages); ++j) {
const std::string extra_input_method_id =
input_method::kExtraLanguages[j].input_method_id;
const std::string extra_language_code =
input_method::kExtraLanguages[j].language_code;
if (extra_input_method_id == descriptor.id) {
language_codes->SetBoolean(extra_language_code, true);
}
}
dictionary->Set("languageCodeSet", language_codes);
input_method_list->Append(dictionary);
}
return input_method_list;
}
ListValue* LanguageOptionsHandler::GetLanguageList(
const InputMethodDescriptors& descriptors) {
std::set<std::string> language_codes;
// Collect the language codes from the supported input methods.
for (size_t i = 0; i < descriptors.size(); ++i) {
const InputMethodDescriptor& descriptor = descriptors[i];
const std::string language_code =
input_method::GetLanguageCodeFromDescriptor(descriptor);
language_codes.insert(language_code);
}
// Collect the language codes from kExtraLanguages.
for (size_t i = 0; i < arraysize(input_method::kExtraLanguages); ++i) {
const char* language_code =
input_method::kExtraLanguages[i].language_code;
language_codes.insert(language_code);
}
// Map of display name -> {language code, native_display_name}.
// In theory, we should be able to create a map that is sorted by
// display names using ICU comparator, but doing it is hard, thus we'll
// use an auxiliary vector to achieve the same result.
typedef std::pair<std::string, std::wstring> LanguagePair;
typedef std::map<std::wstring, LanguagePair> LanguageMap;
LanguageMap language_map;
// The auxiliary vector mentioned above.
std::vector<std::wstring> display_names;
// Build the list of display names, and build the language map.
for (std::set<std::string>::const_iterator iter = language_codes.begin();
iter != language_codes.end(); ++iter) {
const std::wstring display_name =
input_method::GetLanguageDisplayNameFromCode(*iter);
const std::wstring native_display_name =
input_method::GetLanguageNativeDisplayNameFromCode(*iter);
display_names.push_back(display_name);
language_map[display_name] =
std::make_pair(*iter, native_display_name);
}
DCHECK_EQ(display_names.size(), language_map.size());
// Sort display names using locale specific sorter.
l10n_util::SortStrings(g_browser_process->GetApplicationLocale(),
&display_names);
// Build the language list from the language map.
ListValue* language_list = new ListValue();
for (size_t i = 0; i < display_names.size(); ++i) {
const LanguagePair& pair = language_map[display_names[i]];
DictionaryValue* dictionary = new DictionaryValue();
dictionary->SetString("code", pair.first);
dictionary->SetString("displayName", WideToUTF16Hack(display_names[i]));
dictionary->SetString("nativeDisplayName", WideToUTF16Hack(pair.second));
language_list->Append(dictionary);
}
return language_list;
}
DictionaryValue* LanguageOptionsHandler::GetUiLanguageCodeSet() {
DictionaryValue* dictionary = new DictionaryValue();
const std::vector<std::string>& available_locales =
l10n_util::GetAvailableLocales();
for (size_t i = 0; i < available_locales.size(); ++i) {
dictionary->SetBoolean(available_locales[i], true);
}
return dictionary;
}
void LanguageOptionsHandler::UiLanguageChangeCallback(
const Value* value) {
if (!value || !value->IsType(Value::TYPE_LIST)) {
NOTREACHED();
LOG(INFO) << "NOTREACHED";
return;
}
const ListValue* list_value = static_cast<const ListValue*>(value);
std::string language_code;
if (list_value->GetSize() != 1 ||
!list_value->GetString(0, &language_code)) {
NOTREACHED();
LOG(INFO) << "NOTREACHED";
return;
}
PrefService* prefs = g_browser_process->local_state();
prefs->SetString(prefs::kApplicationLocale, language_code);
prefs->SavePersistentPrefs();
dom_ui_->CallJavascriptFunction(
L"options.LanguageOptions.uiLanguageSaved");
}
void LanguageOptionsHandler::RestartCallback(const Value* value) {
Browser* browser = Browser::GetBrowserForController(
&dom_ui_->tab_contents()->controller(), NULL);
// TODO(kochi): For ChromiumOS, just exiting means browser restart.
// Implement browser restart for Chromium Win/Linux/Mac.
if (browser)
browser->ExecuteCommand(IDC_EXIT);
}
} // namespace chromeos
<|endoftext|> |
<commit_before>/*************************************************************************
*
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* Copyright 2008 by Sun Microsystems, Inc.
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: optionsdrawinglayer.hxx,v $
* $Revision: 1.5 $
*
* This file is part of OpenOffice.org.
*
* OpenOffice.org is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License version 3
* only, as published by the Free Software Foundation.
*
* OpenOffice.org is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License version 3 for more details
* (a copy is included in the LICENSE file that accompanied this code).
*
* You should have received a copy of the GNU Lesser General Public License
* version 3 along with OpenOffice.org. If not, see
* <http://www.openoffice.org/license.html>
* for a copy of the LGPLv3 License.
*
************************************************************************/
#ifndef INCLUDED_SVTOOLS_OPTIONSDRAWINGLAYER_HXX
#define INCLUDED_SVTOOLS_OPTIONSDRAWINGLAYER_HXX
//_________________________________________________________________________________________________________________
// includes
//_________________________________________________________________________________________________________________
#include "svtools/svldllapi.h"
#include <sal/types.h>
#include <osl/mutex.hxx>
#include <rtl/ustring.hxx>
#include <tools/color.hxx>
//_________________________________________________________________________________________________________________
// forward declarations
//_________________________________________________________________________________________________________________
/*-************************************************************************************************************//**
@short forward declaration to our private date container implementation
@descr We use these class as internal member to support small memory requirements.
You can create the container if it is neccessary. The class which use these mechanism
is faster and smaller then a complete implementation!
*//*-*************************************************************************************************************/
class SvtOptionsDrawinglayer_Impl;
//_________________________________________________________________________________________________________________
// declarations
//_________________________________________________________________________________________________________________
/*-************************************************************************************************************//**
@short collect informations about startup features
@descr -
@implements -
@base -
@devstatus ready to use
*//*-*************************************************************************************************************/
class SVL_DLLPUBLIC SvtOptionsDrawinglayer
{
//-------------------------------------------------------------------------------------------------------------
// public methods
//-------------------------------------------------------------------------------------------------------------
public:
//---------------------------------------------------------------------------------------------------------
// constructor / destructor
//---------------------------------------------------------------------------------------------------------
/*-****************************************************************************************************//**
@short standard constructor and destructor
@descr This will initialize an instance with default values.
We implement these class with a refcount mechanism! Every instance of this class increase it
at create and decrease it at delete time - but all instances use the same data container!
He is implemented as a static member ...
@seealso member m_nRefCount
@seealso member m_pDataContainer
@param -
@return -
@onerror -
*//*-*****************************************************************************************************/
SvtOptionsDrawinglayer();
~SvtOptionsDrawinglayer();
//---------------------------------------------------------------------------------------------------------
// interface
//---------------------------------------------------------------------------------------------------------
/*-****************************************************************************************************//**
@short interface methods to get and set value of config key "org.openoffice.Office.Common/Drawinglayer/..."
@descr These options describe internal states to enable/disable features of installed office.
IsOverlayBuffer()
SetOverlayBuffer() => Activate this field for letting Overlay use a buffer
IsPaintBuffer()
SetPaintBuffer() => Activate this field for letting Paint use a prerender buffer
GetStripeColorA()
SetStripeColorA() => Set first of two colors which overlay uses to draw stripes
GetStripeColorB()
SetStripeColorB() => Set second of two colors which overlay uses to draw stripes
GetStripeLength()
SetStripeLength() => Set length of a single stripe in pixels
@seealso configuration package "org.openoffice.Office.Common/Drawinglayer"
*//*-*****************************************************************************************************/
sal_Bool IsOverlayBuffer() const;
sal_Bool IsPaintBuffer() const;
Color GetStripeColorA() const;
Color GetStripeColorB() const;
sal_uInt16 GetStripeLength() const;
void SetOverlayBuffer( sal_Bool bState );
void SetPaintBuffer( sal_Bool bState );
void SetStripeColorA( Color aColor );
void SetStripeColorB( Color aColor );
void SetStripeLength( sal_uInt16 nLength );
// #i73602#
sal_Bool IsOverlayBuffer_Calc() const;
sal_Bool IsOverlayBuffer_Writer() const;
sal_Bool IsOverlayBuffer_DrawImpress() const;
void SetOverlayBuffer_Calc( sal_Bool bState );
void SetOverlayBuffer_Writer( sal_Bool bState );
void SetOverlayBuffer_DrawImpress( sal_Bool bState );
// #i74769#, #i75172#
sal_Bool IsPaintBuffer_Calc() const;
sal_Bool IsPaintBuffer_Writer() const;
sal_Bool IsPaintBuffer_DrawImpress() const;
void SetPaintBuffer_Calc( sal_Bool bState );
void SetPaintBuffer_Writer( sal_Bool bState );
void SetPaintBuffer_DrawImpress( sal_Bool bState );
// #i4219#
sal_uInt32 GetMaximumPaperWidth() const;
sal_uInt32 GetMaximumPaperHeight() const;
sal_uInt32 GetMaximumPaperLeftMargin() const;
sal_uInt32 GetMaximumPaperRightMargin() const;
sal_uInt32 GetMaximumPaperTopMargin() const;
sal_uInt32 GetMaximumPaperBottomMargin() const;
void SetMaximumPaperWidth(sal_uInt32 nNew);
void SetMaximumPaperHeight(sal_uInt32 nNew);
void SetMaximumPaperLeftMargin(sal_uInt32 nNew);
void SetMaximumPaperRightMargin(sal_uInt32 nNew);
void SetMaximumPaperTopMargin(sal_uInt32 nNew);
void SetMaximumPaperBottomMargin(sal_uInt32 nNew);
//-------------------------------------------------------------------------------------------------------------
// private methods
//-------------------------------------------------------------------------------------------------------------
private:
/*-****************************************************************************************************//**
@short return a reference to a static mutex
@descr These class use his own static mutex to be threadsafe.
We create a static mutex only for one ime and use at different times.
@seealso -
@param -
@return A reference to a static mutex member.
@onerror -
*//*-*****************************************************************************************************/
SVL_DLLPRIVATE static ::osl::Mutex& GetOwnStaticMutex();
//-------------------------------------------------------------------------------------------------------------
// private member
//-------------------------------------------------------------------------------------------------------------
private:
/*Attention
Don't initialize these static member in these header!
a) Double dfined symbols will be detected ...
b) and unresolved externals exist at linking time.
Do it in your source only.
*/
static SvtOptionsDrawinglayer_Impl* m_pDataContainer ; /// impl. data container as dynamic pointer for smaller memory requirements!
static sal_Int32 m_nRefCount ; /// internal ref count mechanism
}; // class SvtOptionsDrawinglayer
#endif // #ifndef INCLUDED_SVTOOLS_OPTIONSDRAWINGLAYER_HXX
<commit_msg>INTEGRATION: CWS aw033 (1.4.32); FILE MERGED 2008/05/14 15:16:42 aw 1.4.32.2: RESYNC: (1.4-1.5); FILE MERGED 2007/10/16 15:44:49 aw 1.4.32.1: #i39532# Added AA and other values to DrawingLayer settings<commit_after>/*************************************************************************
*
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* Copyright 2008 by Sun Microsystems, Inc.
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: optionsdrawinglayer.hxx,v $
* $Revision: 1.6 $
*
* This file is part of OpenOffice.org.
*
* OpenOffice.org is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License version 3
* only, as published by the Free Software Foundation.
*
* OpenOffice.org is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License version 3 for more details
* (a copy is included in the LICENSE file that accompanied this code).
*
* You should have received a copy of the GNU Lesser General Public License
* version 3 along with OpenOffice.org. If not, see
* <http://www.openoffice.org/license.html>
* for a copy of the LGPLv3 License.
*
************************************************************************/
#ifndef INCLUDED_SVTOOLS_OPTIONSDRAWINGLAYER_HXX
#define INCLUDED_SVTOOLS_OPTIONSDRAWINGLAYER_HXX
//_________________________________________________________________________________________________________________
// includes
//_________________________________________________________________________________________________________________
#include "svtools/svldllapi.h"
#include <sal/types.h>
#include <osl/mutex.hxx>
#include <rtl/ustring.hxx>
#include <tools/color.hxx>
//_________________________________________________________________________________________________________________
// forward declarations
//_________________________________________________________________________________________________________________
/*-************************************************************************************************************//**
@short forward declaration to our private date container implementation
@descr We use these class as internal member to support small memory requirements.
You can create the container if it is neccessary. The class which use these mechanism
is faster and smaller then a complete implementation!
*//*-*************************************************************************************************************/
class SvtOptionsDrawinglayer_Impl;
//_________________________________________________________________________________________________________________
// declarations
//_________________________________________________________________________________________________________________
/*-************************************************************************************************************//**
@short collect informations about startup features
@descr -
@implements -
@base -
@devstatus ready to use
*//*-*************************************************************************************************************/
class SVL_DLLPUBLIC SvtOptionsDrawinglayer
{
//-------------------------------------------------------------------------------------------------------------
// public methods
//-------------------------------------------------------------------------------------------------------------
public:
//---------------------------------------------------------------------------------------------------------
// constructor / destructor
//---------------------------------------------------------------------------------------------------------
/*-****************************************************************************************************//**
@short standard constructor and destructor
@descr This will initialize an instance with default values.
We implement these class with a refcount mechanism! Every instance of this class increase it
at create and decrease it at delete time - but all instances use the same data container!
He is implemented as a static member ...
@seealso member m_nRefCount
@seealso member m_pDataContainer
@param -
@return -
@onerror -
*//*-*****************************************************************************************************/
SvtOptionsDrawinglayer();
~SvtOptionsDrawinglayer();
//---------------------------------------------------------------------------------------------------------
// interface
//---------------------------------------------------------------------------------------------------------
/*-****************************************************************************************************//**
@short interface methods to get and set value of config key "org.openoffice.Office.Common/Drawinglayer/..."
@descr These options describe internal states to enable/disable features of installed office.
IsOverlayBuffer()
SetOverlayBuffer() => Activate this field for letting Overlay use a buffer
IsPaintBuffer()
SetPaintBuffer() => Activate this field for letting Paint use a prerender buffer
GetStripeColorA()
SetStripeColorA() => Set first of two colors which overlay uses to draw stripes
GetStripeColorB()
SetStripeColorB() => Set second of two colors which overlay uses to draw stripes
GetStripeLength()
SetStripeLength() => Set length of a single stripe in pixels
@seealso configuration package "org.openoffice.Office.Common/Drawinglayer"
*//*-*****************************************************************************************************/
sal_Bool IsOverlayBuffer() const;
sal_Bool IsPaintBuffer() const;
Color GetStripeColorA() const;
Color GetStripeColorB() const;
sal_uInt16 GetStripeLength() const;
void SetOverlayBuffer( sal_Bool bState );
void SetPaintBuffer( sal_Bool bState );
void SetStripeColorA( Color aColor );
void SetStripeColorB( Color aColor );
void SetStripeLength( sal_uInt16 nLength );
// #i73602#
sal_Bool IsOverlayBuffer_Calc() const;
sal_Bool IsOverlayBuffer_Writer() const;
sal_Bool IsOverlayBuffer_DrawImpress() const;
void SetOverlayBuffer_Calc( sal_Bool bState );
void SetOverlayBuffer_Writer( sal_Bool bState );
void SetOverlayBuffer_DrawImpress( sal_Bool bState );
// #i74769#, #i75172#
sal_Bool IsPaintBuffer_Calc() const;
sal_Bool IsPaintBuffer_Writer() const;
sal_Bool IsPaintBuffer_DrawImpress() const;
void SetPaintBuffer_Calc( sal_Bool bState );
void SetPaintBuffer_Writer( sal_Bool bState );
void SetPaintBuffer_DrawImpress( sal_Bool bState );
// #i4219#
sal_uInt32 GetMaximumPaperWidth() const;
sal_uInt32 GetMaximumPaperHeight() const;
sal_uInt32 GetMaximumPaperLeftMargin() const;
sal_uInt32 GetMaximumPaperRightMargin() const;
sal_uInt32 GetMaximumPaperTopMargin() const;
sal_uInt32 GetMaximumPaperBottomMargin() const;
void SetMaximumPaperWidth(sal_uInt32 nNew);
void SetMaximumPaperHeight(sal_uInt32 nNew);
void SetMaximumPaperLeftMargin(sal_uInt32 nNew);
void SetMaximumPaperRightMargin(sal_uInt32 nNew);
void SetMaximumPaperTopMargin(sal_uInt32 nNew);
void SetMaximumPaperBottomMargin(sal_uInt32 nNew);
// primitives
sal_Bool IsAntiAliasing() const;
sal_uInt32 GetQuadratic3DRenderLimit() const;
sal_uInt32 GetQuadraticFormControlRenderLimit() const;
void SetAntiAliasing( sal_Bool bState );
void SetQuadratic3DRenderLimit(sal_uInt32 nNew);
void SetQuadraticFormControlRenderLimit(sal_uInt32 nNew);
//-------------------------------------------------------------------------------------------------------------
// private methods
//-------------------------------------------------------------------------------------------------------------
private:
/*-****************************************************************************************************//**
@short return a reference to a static mutex
@descr These class use his own static mutex to be threadsafe.
We create a static mutex only for one ime and use at different times.
@seealso -
@param -
@return A reference to a static mutex member.
@onerror -
*//*-*****************************************************************************************************/
SVL_DLLPRIVATE static ::osl::Mutex& GetOwnStaticMutex();
//-------------------------------------------------------------------------------------------------------------
// private member
//-------------------------------------------------------------------------------------------------------------
private:
/*Attention
Don't initialize these static member in these header!
a) Double dfined symbols will be detected ...
b) and unresolved externals exist at linking time.
Do it in your source only.
*/
static SvtOptionsDrawinglayer_Impl* m_pDataContainer ; /// impl. data container as dynamic pointer for smaller memory requirements!
static sal_Int32 m_nRefCount ; /// internal ref count mechanism
}; // class SvtOptionsDrawinglayer
#endif // #ifndef INCLUDED_SVTOOLS_OPTIONSDRAWINGLAYER_HXX
<|endoftext|> |
<commit_before>/*************************************************************************
*
* $RCSfile: animationstate.cxx,v $
*
* $Revision: 1.2 $
*
* last change: $Author: rt $ $Date: 2003-11-24 16:42:53 $
*
* The Contents of this file are made available subject to the terms of
* either of the following licenses
*
* - GNU Lesser General Public License Version 2.1
* - Sun Industry Standards Source License Version 1.1
*
* Sun Microsystems Inc., October, 2000
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2000 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
*
* Sun Industry Standards Source License Version 1.1
* =================================================
* The contents of this file are subject to the Sun Industry Standards
* Source License Version 1.1 (the "License"); You may not use this file
* except in compliance with the License. You may obtain a copy of the
* License at http://www.openoffice.org/license.html.
*
* Software provided under this License is provided on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
* WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
* MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
* See the License for the specific provisions governing your rights and
* obligations concerning the Software.
*
* The Initial Developer of the Original Code is: Sun Microsystems, Inc.
*
* Copyright: 2000 by Sun Microsystems, Inc.
*
* All Rights Reserved.
*
* Contributor(s): _______________________________________
*
*
************************************************************************/
#ifndef _SDR_ANIMATION_ANIMATIONSTATE_HXX
#include <svx/sdr/animation/animationstate.hxx>
#endif
#ifndef _TOOLS_DEBUG_HXX
#include <tools/debug.hxx>
#endif
#ifndef _SDR_CONTACT_VIEWOBJECTCONTACT_HXX
#include <svx/sdr/contact/viewobjectcontact.hxx>
#endif
#ifndef _SDR_ANIMATION_OBJECTANIMATOR_HXX
#include <svx/sdr/animation/objectanimator.hxx>
#endif
#ifndef _SDR_ANIMATION_ANIMATIONINFO_HXX
#include <svx/sdr/animation/animationinfo.hxx>
#endif
#ifndef _SDR_CONTACT_OBJECTCONTACT_HXX
#include <svx/sdr/contact/objectcontact.hxx>
#endif
#ifndef _SDR_CONTACT_VIEWCONTACT_HXX
#include <svx/sdr/contact/viewcontact.hxx>
#endif
//////////////////////////////////////////////////////////////////////////////
namespace sdr
{
namespace animation
{
// get associated AnimationInfo
AnimationInfo& AnimationState::GetAnimationInfo() const
{
return *(mrVOContact.GetViewContact().GetAnimationInfo());
}
// get associated ObectAnimator
ObjectAnimator& AnimationState::GetObjectAnimator() const
{
return mrVOContact.GetObjectContact().GetObjectAnimator();
}
AnimationState::AnimationState(
sdr::contact::ViewObjectContact& rVOContact)
: Event(0L),
mrVOContact(rVOContact)
{
const sal_uInt32 nStartTime(GetAnimationInfo().GetStartTime());
if(0L != nStartTime)
{
SetTime(nStartTime);
}
}
AnimationState::~AnimationState()
{
// ensure that Event member is removed from ObjectAnimator
GetObjectAnimator().RemoveEvent(this);
}
// execute event, from base class Event
void AnimationState::Trigger(sal_uInt32 nTime)
{
// schedule a repaint of associated object
mrVOContact.ActionChanged();
// need to produce event after nTime?
sal_uInt32 nNewTime(nTime);
if(GetAnimationInfo().DoRegisterAgain(nTime, nNewTime, *this))
{
SetTime(nNewTime);
GetObjectAnimator().InsertEvent(this);
}
}
} // end of namespace animation
} // end of namespace sdr
//////////////////////////////////////////////////////////////////////////////
// eof
<commit_msg>INTEGRATION: CWS aw023 (1.2.610); FILE MERGED 2004/12/16 11:40:31 aw 1.2.610.1: #i38135#<commit_after>/*************************************************************************
*
* $RCSfile: animationstate.cxx,v $
*
* $Revision: 1.3 $
*
* last change: $Author: rt $ $Date: 2005-01-28 16:31:00 $
*
* The Contents of this file are made available subject to the terms of
* either of the following licenses
*
* - GNU Lesser General Public License Version 2.1
* - Sun Industry Standards Source License Version 1.1
*
* Sun Microsystems Inc., October, 2000
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2000 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
*
* Sun Industry Standards Source License Version 1.1
* =================================================
* The contents of this file are subject to the Sun Industry Standards
* Source License Version 1.1 (the "License"); You may not use this file
* except in compliance with the License. You may obtain a copy of the
* License at http://www.openoffice.org/license.html.
*
* Software provided under this License is provided on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
* WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
* MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
* See the License for the specific provisions governing your rights and
* obligations concerning the Software.
*
* The Initial Developer of the Original Code is: Sun Microsystems, Inc.
*
* Copyright: 2000 by Sun Microsystems, Inc.
*
* All Rights Reserved.
*
* Contributor(s): _______________________________________
*
*
************************************************************************/
#ifndef _SDR_ANIMATION_ANIMATIONSTATE_HXX
#include <svx/sdr/animation/animationstate.hxx>
#endif
#ifndef _TOOLS_DEBUG_HXX
#include <tools/debug.hxx>
#endif
#ifndef _SDR_CONTACT_VIEWOBJECTCONTACT_HXX
#include <svx/sdr/contact/viewobjectcontact.hxx>
#endif
#ifndef _SDR_ANIMATION_OBJECTANIMATOR_HXX
#include <svx/sdr/animation/objectanimator.hxx>
#endif
#ifndef _SDR_ANIMATION_ANIMATIONINFO_HXX
#include <svx/sdr/animation/animationinfo.hxx>
#endif
#ifndef _SDR_CONTACT_OBJECTCONTACT_HXX
#include <svx/sdr/contact/objectcontact.hxx>
#endif
#ifndef _SDR_CONTACT_VIEWCONTACT_HXX
#include <svx/sdr/contact/viewcontact.hxx>
#endif
//////////////////////////////////////////////////////////////////////////////
namespace sdr
{
namespace animation
{
// get associated AnimationInfo
AnimationInfo& AnimationState::GetAnimationInfo() const
{
return *(mrVOContact.GetViewContact().GetAnimationInfo());
}
// get associated ObectAnimator
ObjectAnimator& AnimationState::GetObjectAnimator() const
{
return mrVOContact.GetObjectContact().GetObjectAnimator();
}
AnimationState::AnimationState(
sdr::contact::ViewObjectContact& rVOContact)
: Event(0L),
mrVOContact(rVOContact)
{
const sal_uInt32 nStartTime(GetAnimationInfo().GetStartTime());
if(0L != nStartTime)
{
SetTime(nStartTime);
}
}
AnimationState::~AnimationState()
{
// ensure that Event member is removed from ObjectAnimator
GetObjectAnimator().RemoveEvent(this);
}
// execute event, from base class Event
void AnimationState::Trigger(sal_uInt32 nTime)
{
// schedule a repaint of associated object
mrVOContact.ActionChanged();
// need to produce event after nTime?
sal_uInt32 nNewTime(nTime);
if(GetAnimationInfo().DoRegisterAgain(nTime, nNewTime, *this))
{
SetTime(nNewTime);
}
else
{
// #i38135# Advance 10 minutes
nNewTime = nTime + (10L * 60000L);
SetTime(nNewTime);
}
// insert event again
GetObjectAnimator().InsertEvent(this);
}
} // end of namespace animation
} // end of namespace sdr
//////////////////////////////////////////////////////////////////////////////
// eof
<|endoftext|> |
<commit_before>/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
/*
* Version: MPL 1.1 / GPLv3+ / LGPLv3+
*
* The contents of this file are subject to the Mozilla Public License Version
* 1.1 (the "License"); you may not use this file except in compliance with
* the License or as specified alternatively below. You may obtain a copy of
* the License at http://www.mozilla.org/MPL/
*
* Software distributed under the License is distributed on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
* for the specific language governing rights and limitations under the
* License.
*
* Major Contributor(s):
* [ Copyright (C) 2011 SUSE <cbosdonnat@suse.com> (initial developer) ]
*
* All Rights Reserved.
*
* For minor contributions see the git repository.
*
* Alternatively, the contents of this file may be used under the terms of
* either the GNU General Public License Version 3 or later (the "GPLv3+"), or
* the GNU Lesser General Public License Version 3 or later (the "LGPLv3+"),
* in which case the provisions of the GPLv3+ or the LGPLv3+ are applicable
* instead of those above.
*/
#include <edtwin.hxx>
#include <FrameControlsManager.hxx>
#include <HeaderFooterWin.hxx>
#include <PageBreakWin.hxx>
#include <pagefrm.hxx>
#include <viewopt.hxx>
#include <view.hxx>
#include <wrtsh.hxx>
using namespace std;
SwFrameControlsManager::SwFrameControlsManager( SwEditWin* pEditWin ) :
m_pEditWin( pEditWin ),
m_aControls( )
{
}
SwFrameControlsManager::~SwFrameControlsManager()
{
}
SwFrameControlsManager::SwFrameControlsManager( const SwFrameControlsManager& rCopy ) :
m_pEditWin( rCopy.m_pEditWin ),
m_aControls( rCopy.m_aControls )
{
}
const SwFrameControlsManager& SwFrameControlsManager::operator=( const SwFrameControlsManager& rCopy )
{
m_pEditWin = rCopy.m_pEditWin;
m_aControls = rCopy.m_aControls;
return *this;
}
SwFrameControlPtr SwFrameControlsManager::GetControl( FrameControlType eType, const SwFrm* pFrm )
{
SwFrameControlPtrMap& rControls = m_aControls[eType];
SwFrameControlPtrMap::iterator aIt = rControls.find(pFrm);
if (aIt != rControls.end())
return aIt->second;
return SwFrameControlPtr();
}
void SwFrameControlsManager::AddControl( FrameControlType eType, SwFrameControlPtr pControl )
{
m_aControls[eType].insert(make_pair(pControl->GetFrame(), pControl));
}
void SwFrameControlsManager::RemoveControls( const SwFrm* pFrm )
{
map< FrameControlType, SwFrameControlPtrMap >::iterator pIt = m_aControls.begin();
while ( pIt != m_aControls.end() )
{
SwFrameControlPtrMap& rMap = pIt->second;
rMap.erase(pFrm);
++pIt;
}
}
void SwFrameControlsManager::RemoveControlsByType( FrameControlType eType, const SwFrm* pFrm )
{
SwFrameControlPtrMap& rMap = m_aControls[eType];
rMap.erase(pFrm);
}
void SwFrameControlsManager::HideControls( FrameControlType eType )
{
SwFrameControlPtrMap::iterator pIt = m_aControls[eType].begin();
while ( pIt != m_aControls[eType].end() )
{
pIt->second->ShowAll( false );
++pIt;
}
}
void SwFrameControlsManager::SetReadonlyControls( bool bReadonly )
{
map< FrameControlType, SwFrameControlPtrMap >::iterator pIt = m_aControls.begin();
while ( pIt != m_aControls.end() )
{
SwFrameControlPtrMap::iterator aCtrlIt = pIt->second.begin();
while ( aCtrlIt != pIt->second.end() )
{
aCtrlIt->second->SetReadonly( bReadonly );
++aCtrlIt;
}
++pIt;
}
}
void SwFrameControlsManager::SetHeaderFooterControl( const SwPageFrm* pPageFrm, FrameControlType eType, Point aOffset )
{
OSL_ASSERT( eType == Header || eType == Footer );
// Check if we already have the control
SwFrameControlPtr pControl;
const bool bHeader = ( eType == Header );
SwFrameControlPtrMap& rControls = m_aControls[eType];
SwFrameControlPtrMap::iterator lb = rControls.lower_bound(pPageFrm);
if (lb != rControls.end() && !(rControls.key_comp()(pPageFrm, lb->first)))
pControl = lb->second;
else
{
SwFrameControlPtr pNewControl( new SwHeaderFooterWin( m_pEditWin, pPageFrm, bHeader ) );
const SwViewOption* pViewOpt = m_pEditWin->GetView().GetWrtShell().GetViewOptions();
pNewControl->SetReadonly( pViewOpt->IsReadonly() );
rControls.insert(lb, make_pair(pPageFrm, pNewControl));
pControl.swap( pNewControl );
}
assert(pControl->IsHeader() == bHeader);
Rectangle aPageRect = m_pEditWin->LogicToPixel( pPageFrm->Frm().SVRect() );
SwHeaderFooterWin* pHFWin = dynamic_cast< SwHeaderFooterWin* >( pControl.get() );
pHFWin->SetOffset( aOffset, aPageRect.Left(), aPageRect.Right() );
if ( !pHFWin->IsVisible() )
pControl->ShowAll( true );
}
void SwFrameControlsManager::SetPageBreakControl( const SwPageFrm* pPageFrm )
{
// Check if we already have the control
SwFrameControlPtr pControl;
SwFrameControlPtrMap& rControls = m_aControls[PageBreak];
SwFrameControlPtrMap::iterator lb = rControls.lower_bound(pPageFrm);
if (lb != rControls.end() && !(rControls.key_comp()(pPageFrm, lb->first)))
pControl = lb->second;
else
{
SwFrameControlPtr pNewControl( new SwPageBreakWin( m_pEditWin, pPageFrm ) );
const SwViewOption* pViewOpt = m_pEditWin->GetView().GetWrtShell().GetViewOptions();
pNewControl->SetReadonly( pViewOpt->IsReadonly() );
rControls.insert(lb, make_pair(pPageFrm, pNewControl));
pControl.swap( pNewControl );
}
SwPageBreakWin* pWin = dynamic_cast< SwPageBreakWin* >( pControl.get() );
pWin->UpdatePosition();
if ( !pWin->IsVisible() )
pControl->ShowAll( true );
}
/* vim:set shiftwidth=4 softtabstop=4 expandtab: */
<commit_msg>fix build, wrong type inside assert<commit_after>/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
/*
* Version: MPL 1.1 / GPLv3+ / LGPLv3+
*
* The contents of this file are subject to the Mozilla Public License Version
* 1.1 (the "License"); you may not use this file except in compliance with
* the License or as specified alternatively below. You may obtain a copy of
* the License at http://www.mozilla.org/MPL/
*
* Software distributed under the License is distributed on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
* for the specific language governing rights and limitations under the
* License.
*
* Major Contributor(s):
* [ Copyright (C) 2011 SUSE <cbosdonnat@suse.com> (initial developer) ]
*
* All Rights Reserved.
*
* For minor contributions see the git repository.
*
* Alternatively, the contents of this file may be used under the terms of
* either the GNU General Public License Version 3 or later (the "GPLv3+"), or
* the GNU Lesser General Public License Version 3 or later (the "LGPLv3+"),
* in which case the provisions of the GPLv3+ or the LGPLv3+ are applicable
* instead of those above.
*/
#include <edtwin.hxx>
#include <FrameControlsManager.hxx>
#include <HeaderFooterWin.hxx>
#include <PageBreakWin.hxx>
#include <pagefrm.hxx>
#include <viewopt.hxx>
#include <view.hxx>
#include <wrtsh.hxx>
using namespace std;
SwFrameControlsManager::SwFrameControlsManager( SwEditWin* pEditWin ) :
m_pEditWin( pEditWin ),
m_aControls( )
{
}
SwFrameControlsManager::~SwFrameControlsManager()
{
}
SwFrameControlsManager::SwFrameControlsManager( const SwFrameControlsManager& rCopy ) :
m_pEditWin( rCopy.m_pEditWin ),
m_aControls( rCopy.m_aControls )
{
}
const SwFrameControlsManager& SwFrameControlsManager::operator=( const SwFrameControlsManager& rCopy )
{
m_pEditWin = rCopy.m_pEditWin;
m_aControls = rCopy.m_aControls;
return *this;
}
SwFrameControlPtr SwFrameControlsManager::GetControl( FrameControlType eType, const SwFrm* pFrm )
{
SwFrameControlPtrMap& rControls = m_aControls[eType];
SwFrameControlPtrMap::iterator aIt = rControls.find(pFrm);
if (aIt != rControls.end())
return aIt->second;
return SwFrameControlPtr();
}
void SwFrameControlsManager::AddControl( FrameControlType eType, SwFrameControlPtr pControl )
{
m_aControls[eType].insert(make_pair(pControl->GetFrame(), pControl));
}
void SwFrameControlsManager::RemoveControls( const SwFrm* pFrm )
{
map< FrameControlType, SwFrameControlPtrMap >::iterator pIt = m_aControls.begin();
while ( pIt != m_aControls.end() )
{
SwFrameControlPtrMap& rMap = pIt->second;
rMap.erase(pFrm);
++pIt;
}
}
void SwFrameControlsManager::RemoveControlsByType( FrameControlType eType, const SwFrm* pFrm )
{
SwFrameControlPtrMap& rMap = m_aControls[eType];
rMap.erase(pFrm);
}
void SwFrameControlsManager::HideControls( FrameControlType eType )
{
SwFrameControlPtrMap::iterator pIt = m_aControls[eType].begin();
while ( pIt != m_aControls[eType].end() )
{
pIt->second->ShowAll( false );
++pIt;
}
}
void SwFrameControlsManager::SetReadonlyControls( bool bReadonly )
{
map< FrameControlType, SwFrameControlPtrMap >::iterator pIt = m_aControls.begin();
while ( pIt != m_aControls.end() )
{
SwFrameControlPtrMap::iterator aCtrlIt = pIt->second.begin();
while ( aCtrlIt != pIt->second.end() )
{
aCtrlIt->second->SetReadonly( bReadonly );
++aCtrlIt;
}
++pIt;
}
}
void SwFrameControlsManager::SetHeaderFooterControl( const SwPageFrm* pPageFrm, FrameControlType eType, Point aOffset )
{
OSL_ASSERT( eType == Header || eType == Footer );
// Check if we already have the control
SwFrameControlPtr pControl;
const bool bHeader = ( eType == Header );
SwFrameControlPtrMap& rControls = m_aControls[eType];
SwFrameControlPtrMap::iterator lb = rControls.lower_bound(pPageFrm);
if (lb != rControls.end() && !(rControls.key_comp()(pPageFrm, lb->first)))
pControl = lb->second;
else
{
SwFrameControlPtr pNewControl( new SwHeaderFooterWin( m_pEditWin, pPageFrm, bHeader ) );
const SwViewOption* pViewOpt = m_pEditWin->GetView().GetWrtShell().GetViewOptions();
pNewControl->SetReadonly( pViewOpt->IsReadonly() );
rControls.insert(lb, make_pair(pPageFrm, pNewControl));
pControl.swap( pNewControl );
}
Rectangle aPageRect = m_pEditWin->LogicToPixel( pPageFrm->Frm().SVRect() );
SwHeaderFooterWin* pHFWin = dynamic_cast< SwHeaderFooterWin* >( pControl.get() );
assert(pHFWin->IsHeader() == bHeader);
pHFWin->SetOffset( aOffset, aPageRect.Left(), aPageRect.Right() );
if ( !pHFWin->IsVisible() )
pControl->ShowAll( true );
}
void SwFrameControlsManager::SetPageBreakControl( const SwPageFrm* pPageFrm )
{
// Check if we already have the control
SwFrameControlPtr pControl;
SwFrameControlPtrMap& rControls = m_aControls[PageBreak];
SwFrameControlPtrMap::iterator lb = rControls.lower_bound(pPageFrm);
if (lb != rControls.end() && !(rControls.key_comp()(pPageFrm, lb->first)))
pControl = lb->second;
else
{
SwFrameControlPtr pNewControl( new SwPageBreakWin( m_pEditWin, pPageFrm ) );
const SwViewOption* pViewOpt = m_pEditWin->GetView().GetWrtShell().GetViewOptions();
pNewControl->SetReadonly( pViewOpt->IsReadonly() );
rControls.insert(lb, make_pair(pPageFrm, pNewControl));
pControl.swap( pNewControl );
}
SwPageBreakWin* pWin = dynamic_cast< SwPageBreakWin* >( pControl.get() );
pWin->UpdatePosition();
if ( !pWin->IsVisible() )
pControl->ShowAll( true );
}
/* vim:set shiftwidth=4 softtabstop=4 expandtab: */
<|endoftext|> |
<commit_before>// Copyright (c) 2016 - present Advanced Micro Devices, Inc. All rights reserved.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
/// @file
/// @brief googletest based unit tester for rocfft
///
#include <fstream>
#include <gtest/gtest.h>
#include <iostream>
#include <streambuf>
#include <string>
#include "accuracy_test.h"
#include "fftw_transform.h"
#include "rocfft.h"
#include "rocfft_against_fftw.h"
#include "test_constants.h"
#include <boost/program_options.hpp>
namespace po = boost::program_options;
// Control output verbosity:
int verbose = 0;
// Parameters for single manual test:
// Transform type parameters:
rocfft_transform_type transformType;
rocfft_array_type itype;
rocfft_array_type otype;
size_t nbatch = 1;
rocfft_result_placement place;
rocfft_precision precision;
std::vector<size_t> length;
size_t istride0;
size_t ostride0;
// Control whether we use FFTW's wisdom (which we use to imply FFTW_MEASURE).
bool use_fftw_wisdom = false;
int main(int argc, char* argv[])
{
// NB: If we initialize gtest first, then it removes all of its own command-line
// arguments and sets argc and argv correctly; no need to jump through hoops for
// boost::program_options.
::testing::InitGoogleTest(&argc, argv);
// Filename for fftw and fftwf wisdom.
std::string fftw_wisdom_filename;
// Declare the supported options.
// clang-format doesn't handle boost program options very well:
// clang-format off
po::options_description opdesc("rocFFT Runtime Test command line options");
opdesc.add_options()
("help,h", "produces this help message")
("verbose,v", po::value<int>()->default_value(0),
"print out detailed information for the tests.")
("transformType,t", po::value<rocfft_transform_type>(&transformType)
->default_value(rocfft_transform_type_complex_forward),
"Type of transform:\n0) complex forward\n1) complex inverse\n2) real "
"forward\n3) real inverse")
("notInPlace,o", "Not in-place FFT transform (default: in-place)")
("double", "Double precision transform (default: single)")
( "itype", po::value<rocfft_array_type>(&itype)
->default_value(rocfft_array_type_unset),
"Array type of input data:\n0) interleaved\n1) planar\n2) real\n3) "
"hermitian interleaved\n4) hermitian planar")
( "otype", po::value<rocfft_array_type>(&otype)
->default_value(rocfft_array_type_unset),
"Array type of output data:\n0) interleaved\n1) planar\n2) real\n3) "
"hermitian interleaved\n4) hermitian planar")
("length", po::value<std::vector<size_t>>(&length)->multitoken(), "Lengths.")
( "batchSize,b", po::value<size_t>(&nbatch)->default_value(1),
"If this value is greater than one, arrays will be used ")
( "istride0", po::value<size_t>(&istride0)->default_value(1),
"Input stride ")
( "ostride0", po::value<size_t>(&ostride0)->default_value(1),
"Output stride ")
("wise,w", "use FFTW wisdom")
("wisdomfile,W",
po::value<std::string>(&fftw_wisdom_filename)->default_value("wisdom3.txt"),
"FFTW3 wisdom filename");
// clang-format on
po::variables_map vm;
po::store(po::parse_command_line(argc, argv, opdesc), vm);
po::notify(vm);
if(vm.count("help"))
{
std::cout << opdesc << std::endl;
return 0;
}
place = vm.count("notInPlace") ? rocfft_placement_notinplace : rocfft_placement_inplace;
precision = vm.count("double") ? rocfft_precision_double : rocfft_precision_single;
verbose = vm["verbose"].as<int>();
if(vm.count("wise"))
{
use_fftw_wisdom = true;
}
if(length.size() == 0)
{
length.push_back(8);
// TODO: add random size?
}
rocfft_setup();
char v[256];
rocfft_get_version_string(v, 256);
std::cout << "rocFFT version: " << v << std::endl;
if(use_fftw_wisdom)
{
if(verbose)
{
std::cout << "Using " << fftw_wisdom_filename << " wisdom file\n";
}
std::ifstream fftw_wisdom_file(fftw_wisdom_filename);
std::string allwisdom = std::string(std::istreambuf_iterator<char>(fftw_wisdom_file),
std::istreambuf_iterator<char>());
std::string fftw_wisdom;
std::string fftwf_wisdom;
bool load_wisdom = false;
bool load_fwisdom = false;
std::istringstream input;
input.str(allwisdom);
// Separate the single-precision and double-precision wisdom:
for(std::string line; std::getline(input, line);)
{
if(line.rfind("(fftw", 0) == 0 && line.find("fftw_wisdom") != std::string::npos)
{
load_wisdom = true;
}
if(line.rfind("(fftw", 0) == 0 && line.find("fftwf_wisdom") != std::string::npos)
{
load_fwisdom = true;
}
if(load_wisdom)
{
fftw_wisdom.append(line + "\n");
}
if(load_fwisdom)
{
fftwf_wisdom.append(line + "\n");
}
if(line.rfind(")", 0) == 0)
{
load_wisdom = false;
load_fwisdom = false;
}
}
fftw_import_wisdom_from_string(fftw_wisdom.c_str());
fftwf_import_wisdom_from_string(fftwf_wisdom.c_str());
}
auto retval = RUN_ALL_TESTS();
if(use_fftw_wisdom)
{
std::string fftw_wisdom = std::string(fftw_export_wisdom_to_string());
std::string fftwf_wisdom = std::string(fftwf_export_wisdom_to_string());
fftw_wisdom.append(std::string(fftwf_export_wisdom_to_string()));
std::ofstream fftw_wisdom_file(fftw_wisdom_filename);
fftw_wisdom_file << fftw_wisdom;
fftw_wisdom_file << fftwf_wisdom;
fftw_wisdom_file.close();
}
rocfft_cleanup();
return retval;
}
TEST(manual, vs_fftw)
{
// Run an individual test using the provided command-line parameters.
std::cout << "Manual test:" << std::endl;
check_set_iotypes(place, transformType, itype, otype);
print_params(length, istride0, istride0, nbatch, place, precision, transformType, itype, otype);
const size_t dim = length.size();
// Input cpu parameters:
auto ilength = length;
if(transformType == rocfft_transform_type_real_inverse)
ilength[dim - 1] = ilength[dim - 1] / 2 + 1;
const auto cpu_istride = compute_stride(ilength, 1);
const auto cpu_itype = contiguous_itype(transformType);
const auto cpu_idist
= set_idist(rocfft_placement_notinplace, transformType, length, cpu_istride);
// Output cpu parameters:
auto olength = length;
if(transformType == rocfft_transform_type_real_forward)
olength[dim - 1] = olength[dim - 1] / 2 + 1;
const auto cpu_ostride = compute_stride(olength, 1);
const auto cpu_odist
= set_odist(rocfft_placement_notinplace, transformType, length, cpu_ostride);
auto cpu_otype = contiguous_otype(transformType);
// Generate the data:
auto cpu_input = compute_input<fftwAllocator<char>>(
precision, cpu_itype, length, cpu_istride, cpu_idist, nbatch);
auto cpu_input_copy = cpu_input; // copy of input (might get overwritten by FFTW).
// Compute the Linfinity and L2 norm of the CPU output:
auto cpu_input_L2Linfnorm
= norm(cpu_input, ilength, nbatch, precision, cpu_itype, cpu_istride, cpu_idist);
if(verbose > 2)
{
std::cout << "CPU Input Linf norm: " << cpu_input_L2Linfnorm.l_inf << "\n";
std::cout << "CPU Input L2 norm: " << cpu_input_L2Linfnorm.l_2 << "\n";
}
ASSERT_TRUE(std::isfinite(cpu_input_L2Linfnorm.l_inf));
ASSERT_TRUE(std::isfinite(cpu_input_L2Linfnorm.l_2));
if(verbose > 3)
{
std::cout << "CPU input:\n";
printbuffer(precision, cpu_itype, cpu_input, ilength, cpu_istride, nbatch, cpu_idist);
}
// FFTW computation
// NB: FFTW may overwrite input, even for out-of-place transforms.
auto cpu_output = fftw_via_rocfft(length,
cpu_istride,
cpu_ostride,
nbatch,
cpu_idist,
cpu_odist,
precision,
transformType,
cpu_input);
// Compute the Linfinity and L2 norm of the CPU output:
auto cpu_output_L2Linfnorm
= norm(cpu_output, olength, nbatch, precision, cpu_otype, cpu_ostride, cpu_odist);
if(verbose > 2)
{
std::cout << "CPU Output Linf norm: " << cpu_output_L2Linfnorm.l_inf << "\n";
std::cout << "CPU Output L2 norm: " << cpu_output_L2Linfnorm.l_2 << "\n";
}
if(verbose > 3)
{
std::cout << "CPU output:\n";
printbuffer(precision, cpu_otype, cpu_output, olength, cpu_ostride, nbatch, cpu_odist);
}
ASSERT_TRUE(std::isfinite(cpu_output_L2Linfnorm.l_inf));
ASSERT_TRUE(std::isfinite(cpu_output_L2Linfnorm.l_2));
rocfft_transform(length,
istride0,
ostride0,
nbatch,
precision,
transformType,
itype,
otype,
place,
cpu_istride,
cpu_ostride,
cpu_idist,
cpu_odist,
cpu_itype,
cpu_otype,
cpu_input_copy,
cpu_output,
cpu_output_L2Linfnorm);
}
<commit_msg>Tweak names.<commit_after>// Copyright (c) 2016 - present Advanced Micro Devices, Inc. All rights reserved.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
/// @file
/// @brief googletest based unit tester for rocfft
///
#include <fstream>
#include <gtest/gtest.h>
#include <iostream>
#include <streambuf>
#include <string>
#include "accuracy_test.h"
#include "fftw_transform.h"
#include "rocfft.h"
#include "rocfft_against_fftw.h"
#include "test_constants.h"
#include <boost/program_options.hpp>
namespace po = boost::program_options;
// Control output verbosity:
int verbose = 0;
// Parameters for single manual test:
// Transform type parameters:
rocfft_transform_type transformType;
rocfft_array_type itype;
rocfft_array_type otype;
size_t nbatch = 1;
rocfft_result_placement place;
rocfft_precision precision;
std::vector<size_t> length;
size_t istride0;
size_t ostride0;
// Control whether we use FFTW's wisdom (which we use to imply FFTW_MEASURE).
bool use_fftw_wisdom = false;
int main(int argc, char* argv[])
{
// NB: If we initialize gtest first, then it removes all of its own command-line
// arguments and sets argc and argv correctly; no need to jump through hoops for
// boost::program_options.
::testing::InitGoogleTest(&argc, argv);
// Filename for fftw and fftwf wisdom.
std::string fftw_wisdom_filename;
// Declare the supported options.
// clang-format doesn't handle boost program options very well:
// clang-format off
po::options_description opdesc("rocFFT Runtime Test command line options");
opdesc.add_options()
("help,h", "produces this help message")
("verbose,v", po::value<int>()->default_value(0),
"print out detailed information for the tests.")
("transformType,t", po::value<rocfft_transform_type>(&transformType)
->default_value(rocfft_transform_type_complex_forward),
"Type of transform:\n0) complex forward\n1) complex inverse\n2) real "
"forward\n3) real inverse")
("notInPlace,o", "Not in-place FFT transform (default: in-place)")
("double", "Double precision transform (default: single)")
( "itype", po::value<rocfft_array_type>(&itype)
->default_value(rocfft_array_type_unset),
"Array type of input data:\n0) interleaved\n1) planar\n2) real\n3) "
"hermitian interleaved\n4) hermitian planar")
( "otype", po::value<rocfft_array_type>(&otype)
->default_value(rocfft_array_type_unset),
"Array type of output data:\n0) interleaved\n1) planar\n2) real\n3) "
"hermitian interleaved\n4) hermitian planar")
("length", po::value<std::vector<size_t>>(&length)->multitoken(), "Lengths.")
( "batchSize,b", po::value<size_t>(&nbatch)->default_value(1),
"If this value is greater than one, arrays will be used ")
( "istride0", po::value<size_t>(&istride0)->default_value(1),
"Input stride ")
( "ostride0", po::value<size_t>(&ostride0)->default_value(1),
"Output stride ")
("wise,w", "use FFTW wisdom")
("wisdomfile,W",
po::value<std::string>(&fftw_wisdom_filename)->default_value("wisdom3.txt"),
"FFTW3 wisdom filename");
// clang-format on
po::variables_map vm;
po::store(po::parse_command_line(argc, argv, opdesc), vm);
po::notify(vm);
if(vm.count("help"))
{
std::cout << opdesc << std::endl;
return 0;
}
place = vm.count("notInPlace") ? rocfft_placement_notinplace : rocfft_placement_inplace;
precision = vm.count("double") ? rocfft_precision_double : rocfft_precision_single;
verbose = vm["verbose"].as<int>();
if(vm.count("wise"))
{
use_fftw_wisdom = true;
}
if(length.size() == 0)
{
length.push_back(8);
// TODO: add random size?
}
rocfft_setup();
char v[256];
rocfft_get_version_string(v, 256);
std::cout << "rocFFT version: " << v << std::endl;
if(use_fftw_wisdom)
{
if(verbose)
{
std::cout << "Using " << fftw_wisdom_filename << " wisdom file\n";
}
std::ifstream fftw_wisdom_file(fftw_wisdom_filename);
std::string allwisdom = std::string(std::istreambuf_iterator<char>(fftw_wisdom_file),
std::istreambuf_iterator<char>());
std::string fftw_wisdom;
std::string fftwf_wisdom;
bool load_wisdom = false;
bool load_fwisdom = false;
std::istringstream input;
input.str(allwisdom);
// Separate the single-precision and double-precision wisdom:
for(std::string line; std::getline(input, line);)
{
if(line.rfind("(fftw", 0) == 0 && line.find("fftw_wisdom") != std::string::npos)
{
load_wisdom = true;
}
if(line.rfind("(fftw", 0) == 0 && line.find("fftwf_wisdom") != std::string::npos)
{
load_fwisdom = true;
}
if(load_wisdom)
{
fftw_wisdom.append(line + "\n");
}
if(load_fwisdom)
{
fftwf_wisdom.append(line + "\n");
}
if(line.rfind(")", 0) == 0)
{
load_wisdom = false;
load_fwisdom = false;
}
}
fftw_import_wisdom_from_string(fftw_wisdom.c_str());
fftwf_import_wisdom_from_string(fftwf_wisdom.c_str());
}
auto retval = RUN_ALL_TESTS();
if(use_fftw_wisdom)
{
std::string fftw_wisdom = std::string(fftw_export_wisdom_to_string());
std::string fftwf_wisdom = std::string(fftwf_export_wisdom_to_string());
fftw_wisdom.append(std::string(fftwf_export_wisdom_to_string()));
std::ofstream fftw_wisdom_file(fftw_wisdom_filename);
fftw_wisdom_file << fftw_wisdom;
fftw_wisdom_file << fftwf_wisdom;
fftw_wisdom_file.close();
}
rocfft_cleanup();
return retval;
}
TEST(manual, vs_fftw)
{
// Run an individual test using the provided command-line parameters.
std::cout << "Manual test:" << std::endl;
check_set_iotypes(place, transformType, itype, otype);
print_params(length, istride0, istride0, nbatch, place, precision, transformType, itype, otype);
const size_t dim = length.size();
// Input cpu parameters:
auto ilength = length;
if(transformType == rocfft_transform_type_real_inverse)
ilength[dim - 1] = ilength[dim - 1] / 2 + 1;
const auto cpu_istride = compute_stride(ilength, 1);
const auto cpu_itype = contiguous_itype(transformType);
const auto cpu_idist
= set_idist(rocfft_placement_notinplace, transformType, length, cpu_istride);
// Output cpu parameters:
auto olength = length;
if(transformType == rocfft_transform_type_real_forward)
olength[dim - 1] = olength[dim - 1] / 2 + 1;
const auto cpu_ostride = compute_stride(olength, 1);
const auto cpu_odist
= set_odist(rocfft_placement_notinplace, transformType, length, cpu_ostride);
auto cpu_otype = contiguous_otype(transformType);
// Generate the data:
auto cpu_input = compute_input<fftwAllocator<char>>(
precision, cpu_itype, length, cpu_istride, cpu_idist, nbatch);
auto cpu_input_copy = cpu_input; // copy of input (might get overwritten by FFTW).
// Compute the Linfinity and L2 norm of the CPU output:
auto cpu_input_norm
= norm(cpu_input, ilength, nbatch, precision, cpu_itype, cpu_istride, cpu_idist);
if(verbose > 2)
{
std::cout << "CPU Input Linf norm: " << cpu_input_norm.l_inf << "\n";
std::cout << "CPU Input L2 norm: " << cpu_input_norm.l_2 << "\n";
}
ASSERT_TRUE(std::isfinite(cpu_input_norm.l_inf));
ASSERT_TRUE(std::isfinite(cpu_input_norm.l_2));
if(verbose > 3)
{
std::cout << "CPU input:\n";
printbuffer(precision, cpu_itype, cpu_input, ilength, cpu_istride, nbatch, cpu_idist);
}
// FFTW computation
// NB: FFTW may overwrite input, even for out-of-place transforms.
auto cpu_output = fftw_via_rocfft(length,
cpu_istride,
cpu_ostride,
nbatch,
cpu_idist,
cpu_odist,
precision,
transformType,
cpu_input);
// Compute the Linfinity and L2 norm of the CPU output:
auto cpu_output_norm
= norm(cpu_output, olength, nbatch, precision, cpu_otype, cpu_ostride, cpu_odist);
if(verbose > 2)
{
std::cout << "CPU Output Linf norm: " << cpu_output_norm.l_inf << "\n";
std::cout << "CPU Output L2 norm: " << cpu_output_norm.l_2 << "\n";
}
if(verbose > 3)
{
std::cout << "CPU output:\n";
printbuffer(precision, cpu_otype, cpu_output, olength, cpu_ostride, nbatch, cpu_odist);
}
ASSERT_TRUE(std::isfinite(cpu_output_norm.l_inf));
ASSERT_TRUE(std::isfinite(cpu_output_norm.l_2));
rocfft_transform(length,
istride0,
ostride0,
nbatch,
precision,
transformType,
itype,
otype,
place,
cpu_istride,
cpu_ostride,
cpu_idist,
cpu_odist,
cpu_itype,
cpu_otype,
cpu_input_copy,
cpu_output,
cpu_output_norm);
}
<|endoftext|> |
<commit_before>MARKDOWNISH_TEST("simple [re2]", RE2, "**test**\n## test", "<p><strong>test</strong></p><h2>test</h2>");
MARKDOWNISH_TEST("simple [jit]", re2jit::it, "**test**\n## test", "<p><strong>test</strong></p><h2>test</h2>");
MARKDOWNISH_PERF_TEST(200000, "simple", "**test**\n## test");
MARKDOWNISH_FILE_PERF_TEST(500, "dg-tutorial.md", "test/32-markdownish-dg-tutorial.md");
<commit_msg>Parse the project's README as a test.<commit_after>MARKDOWNISH_TEST("simple [re2]", RE2, "**test**\n## test", "<p><strong>test</strong></p><h2>test</h2>");
MARKDOWNISH_TEST("simple [jit]", re2jit::it, "**test**\n## test", "<p><strong>test</strong></p><h2>test</h2>");
MARKDOWNISH_PERF_TEST(200000, "simple", "**test**\n## test");
MARKDOWNISH_FILE_PERF_TEST(500, "dg-tutorial.md", "test/32-markdownish-dg-tutorial.md");
MARKDOWNISH_FILE_PERF_TEST(1000, "README.md", "README.md");
<|endoftext|> |
<commit_before>// Loosely based on https://repo.anl-external.org/repos/BlueTBB/tbb30_104oss/src/rml/perfor/tbb_simple.cpp
// #include "stdafx.h"
// int _tmain(int argc, _TCHAR* argv[])
// {
// return 0;
// }
#include "tbb/task_group.h"
#include <iostream>
#include <stdio.h> //// MOVE TO iostreams TODO
#include <stdlib.h>
//#include <chrono> // for 2s to mean 2 seconds
//using namespace std::literals::chrono_literals; // as above
//#include <thread> // for std::this_thread::sleep_for(1);
#include <tbb/mutex.h>
#include <tbb/tbb_thread.h>
// tbb::mutex my_mutex;
#if _WIN32||_WIN64
//#include <Windows.h> /* Sleep */
#else
//// #error Only tested on Windows! TODO
// #include <unistd.h> /* usleep */
#endif
using namespace tbb;
#if 0 // totally inappropriate and broken use of subclassing of tbb::task, just for giggles
// see https://www.threadingbuildingblocks.org/docs/help/reference/task_scheduler/task_cls.htm
#include "tbb/task.h"
class TrivialTask : public tbb::task {
public:
TrivialTask() { }
task* parent() const { // the "parent" member-function is confusingly referred to as "the successor attribute"
return NULL;
}
task* execute() override {
puts("Hello from my task!");
return NULL;
}
~TrivialTask() {
puts("Destroying my task");
}
};
// allocate_continuation
// #include <stdio.h>
// #include <stdlib.h>
int main(int argc, char *argv[]) {
// use TBB's custom allocator, along the lines shown in
// https://www.threadingbuildingblocks.org/docs/help/tbb_userguide/Simple_Example_Fibonacci_Numbers.htm#tutorial_Simple_Example_Fibonacci_Numbers
// see also https://www.threadingbuildingblocks.org/docs/help/reference/task_scheduler/task_allocation.htm
{
// looking at task_allocation.htm this should use:
// "cancellation group is the current innermost cancellation group. "
////// WHICH WE DON'T HAVE!?!?! shouldn't this cause an assert failure?
task& t = *new(task::allocate_root()) TrivialTask; // following http://fulla.fnal.gov/intel/tbb/html/a00249.html
auto count1 = t.ref_count();
t.execute(); // No concurrency! Hence 'totally inappropriate'
// t.decrement_ref_count(); causes underflow!
//if ( NULL != t.parent ) {
//}
// "Because there is no placement delete expression[...]" https://en.wikipedia.org/w/index.php?title=Placement_syntax&oldid=674756226#Custom_allocators
// not using standard 'new' so can't use standard 'delete'
//delete (task::allocate_root()) &t; // kaboom! VS2010 picks up a double-free problem. Looks like we're missing something important....????
auto count2 = t.ref_count();
t.decrement_ref_count(); // same as t.set_ref_count(0);
}
return EXIT_SUCCESS;
}
#endif
#if 0
int main(int argc, char *argv[]) {
puts("Starting...");
task_group g;
g.run([&] {Sleep(2000); puts("Task 1 is away"); });
g.run([&] {Sleep(2000); puts("Task 2 is away"); });
g.run([&] {Sleep(2000); puts("Task 3 is away"); });
g.run_and_wait([&] {Sleep(2000); puts("A message from the main thread"); });
//////g.wait();
// getchar();
return EXIT_SUCCESS;
}
#endif
#if 1 // fun with the idea of futures
// #include "tbb/atomic.h"
// Faking/implementing futures with TBB tasks
// Note that mutable state is held in its own struct,
// as TBB's run(1) function accepts its arg by const reference,
// forcing us to handle mutation via a pointer to a mutable value
// and not within the MyFuture class itself.
// we use TBB's sleep functionality, to avoid C++14 dependency
const tbb::tick_count::interval_t oneSecond(1.0); // double holds the number of seconds
const tbb::tick_count::interval_t threeSeconds(3.0);
const tbb::tick_count::interval_t tenSeconds(10.0);
int main(int argc, char *argv[]) {
puts("Starting...");
class MyFuture {
struct MutableState {
MutableState() : result(0) { }
int result;
};
class Executor {
/*not const*/ MutableState * const msPtr;
public:
Executor(MutableState *m) : msPtr(m) { };
void operator()() const {
puts("[from task] Task is running. Now for the pause...");
// this_tbb_thread::sleep( threeSeconds );
this_tbb_thread::sleep( tenSeconds );
puts("[from task] Task pause complete, assigning output...");
msPtr->result = 3;
return;
}
};
task_group tg;
MutableState ms;
const Executor e; // must be const in order to call run(1)
public:
MyFuture() : e(&ms) // just invoke default constructor of tg and ms
{ }
void begin() {
tg.run( this->e );
}
int force() /*const*/ {
tg.wait();
return ms.result;
}
};
MyFuture f; // not const: we mutate internally
puts("Now to run");
f.begin();
puts("Running. Now to do a couple of prints with a pause between each.");
this_tbb_thread::sleep( oneSecond );
puts("And here we are after a second");
this_tbb_thread::sleep( oneSecond );
puts("And here we are after another second");
this_tbb_thread::sleep( oneSecond );
puts("And here we are after yet another second");
this_tbb_thread::sleep( oneSecond );
puts("And here we are after yet another second");
puts("And now to wait...");
printf( "%d\n", f.force() );
return EXIT_SUCCESS;
}
#endif
#if 0 // the fib example from the web
int fib(int n) {
int ret;
if (n < 2) {
ret = n;
}
else {
int x, y;
task_group g;
x = y = 9;
// g.run( [&]{my_mutex.lock();/* x=fib(n-1); */ puts("Now:\n"); getchar(); my_mutex.unlock();} ); // spawn a task
g.run([&] {
tbb::mutex::scoped_lock lock(my_mutex);
/* x=fib(n-1); */ puts("Now:\n"); getchar();
}); // spawn a task
// g.run( [&]{my_mutex.lock();/* y=fib(n-2); */ puts("Now:\n"); getchar(); my_mutex.unlock();} ); // spawn another task
g.run([&] {
tbb::mutex::scoped_lock lock(my_mutex);/* y=fib(n-2); */ puts("Now:\n"); getchar();
}); // spawn another task
g.wait(); // wait for both tasks to complete
ret = x + y;
}
return ret;
} // - See more at: https://www.threadingbuildingblocks.org/tutorial-intel-tbb-task-based-programming#sthash.EzgRXzaB.dpuf
int main(int argc, char *argv[]) {
std::cout << fib(33);
// getchar();
return EXIT_SUCCESS;
}
#endif
<commit_msg>Fix up an older toy example<commit_after>// Loosely based on https://repo.anl-external.org/repos/BlueTBB/tbb30_104oss/src/rml/perfor/tbb_simple.cpp
// #include "stdafx.h"
// int _tmain(int argc, _TCHAR* argv[])
// {
// return 0;
// }
#include "tbb/task_group.h"
#include <iostream>
#include <stdio.h> //// MOVE TO iostreams TODO
#include <stdlib.h>
//#include <chrono> // for 2s to mean 2 seconds
//using namespace std::literals::chrono_literals; // as above
//#include <thread> // for std::this_thread::sleep_for(1);
#include <tbb/mutex.h>
#include <tbb/tbb_thread.h>
// tbb::mutex my_mutex;
#if _WIN32||_WIN64
//#include <Windows.h> /* Sleep */
#else
//// #error Only tested on Windows! TODO
// #include <unistd.h> /* usleep */
#endif
using namespace tbb;
#if 0 // totally inappropriate and broken use of subclassing of tbb::task, just for giggles
// see https://www.threadingbuildingblocks.org/docs/help/reference/task_scheduler/task_cls.htm
#include "tbb/task.h"
class TrivialTask : public tbb::task {
public:
TrivialTask() { }
task* parent() const { // the "parent" member-function is confusingly referred to as "the successor attribute"
return NULL;
}
task* execute() override {
puts("Hello from my task!");
return NULL;
}
~TrivialTask() {
puts("Destroying my task");
}
};
// allocate_continuation
// #include <stdio.h>
// #include <stdlib.h>
int main(int argc, char *argv[]) {
// use TBB's custom allocator, along the lines shown in
// https://www.threadingbuildingblocks.org/docs/help/tbb_userguide/Simple_Example_Fibonacci_Numbers.htm#tutorial_Simple_Example_Fibonacci_Numbers
// see also https://www.threadingbuildingblocks.org/docs/help/reference/task_scheduler/task_allocation.htm
{
// looking at task_allocation.htm this should use:
// "cancellation group is the current innermost cancellation group. "
////// WHICH WE DON'T HAVE!?!?! shouldn't this cause an assert failure?
task& t = *new(task::allocate_root()) TrivialTask; // following http://fulla.fnal.gov/intel/tbb/html/a00249.html
auto count1 = t.ref_count();
t.execute(); // No concurrency! Hence 'totally inappropriate'
// t.decrement_ref_count(); causes underflow!
//if ( NULL != t.parent ) {
//}
// "Because there is no placement delete expression[...]" https://en.wikipedia.org/w/index.php?title=Placement_syntax&oldid=674756226#Custom_allocators
// not using standard 'new' so can't use standard 'delete'
//delete (task::allocate_root()) &t; // kaboom! VS2010 picks up a double-free problem. Looks like we're missing something important....????
auto count2 = t.ref_count();
t.decrement_ref_count(); // same as t.set_ref_count(0);
}
return EXIT_SUCCESS;
}
#endif
#if 0 // just spin up and run four simple tasks, using lambdas
const tbb::tick_count::interval_t oneSecond(1.0); // double holds the number of seconds
int main(int argc, char *argv[]) {
puts("Starting...");
task_group g;
g.run( [&]{ this_tbb_thread::sleep(oneSecond); puts("[Task 1] started"); } );
g.run( [&]{ this_tbb_thread::sleep(oneSecond); puts("[Task 2] started"); } );
g.run( [&]{ this_tbb_thread::sleep(oneSecond); puts("[Task 3] started"); } );
g.run_and_wait( [&]{ this_tbb_thread::sleep(oneSecond); puts("A message from the main thread"); } );
return EXIT_SUCCESS;
}
#endif
#if 1 // fun with the idea of futures
// #include "tbb/atomic.h"
// Faking/implementing futures with TBB tasks
// Note that mutable state is held in its own struct,
// as TBB's run(1) function accepts its arg by const reference,
// forcing us to handle mutation via a pointer to a mutable value
// and not within the MyFuture class itself.
// we use TBB's sleep functionality, to avoid C++14 dependency
const tbb::tick_count::interval_t oneSecond(1.0); // double holds the number of seconds
const tbb::tick_count::interval_t threeSeconds(3.0);
const tbb::tick_count::interval_t tenSeconds(10.0);
int main(int argc, char *argv[]) {
puts("Starting...");
class MyFuture {
struct MutableState {
MutableState() : result(0) { }
int result;
};
class Executor {
/*not const*/ MutableState * const msPtr;
public:
Executor(MutableState *m) : msPtr(m) { };
void operator()() const {
puts("[from task] Task is running. Now for the pause...");
// this_tbb_thread::sleep( threeSeconds );
this_tbb_thread::sleep( tenSeconds );
puts("[from task] Task pause complete, assigning output...");
msPtr->result = 3;
return;
}
};
task_group tg;
MutableState ms;
const Executor e; // must be const in order to call run(1)
public:
MyFuture() : e(&ms) // just invoke default constructor of tg and ms
{ }
void begin() {
tg.run( this->e );
}
int force() /*const*/ {
tg.wait();
return ms.result;
}
};
MyFuture f; // not const: we mutate internally
puts("Now to run");
f.begin();
puts("Running. Now to do a couple of prints with a pause between each.");
this_tbb_thread::sleep( oneSecond );
puts("And here we are after a second");
this_tbb_thread::sleep( oneSecond );
puts("And here we are after another second");
this_tbb_thread::sleep( oneSecond );
puts("And here we are after yet another second");
this_tbb_thread::sleep( oneSecond );
puts("And here we are after yet another second");
puts("And now to wait...");
printf( "%d\n", f.force() );
return EXIT_SUCCESS;
}
#endif
#if 0 // the fib example from the web
int fib(int n) {
int ret;
if (n < 2) {
ret = n;
}
else {
int x, y;
task_group g;
x = y = 9;
// g.run( [&]{my_mutex.lock();/* x=fib(n-1); */ puts("Now:\n"); getchar(); my_mutex.unlock();} ); // spawn a task
g.run([&] {
tbb::mutex::scoped_lock lock(my_mutex);
/* x=fib(n-1); */ puts("Now:\n"); getchar();
}); // spawn a task
// g.run( [&]{my_mutex.lock();/* y=fib(n-2); */ puts("Now:\n"); getchar(); my_mutex.unlock();} ); // spawn another task
g.run([&] {
tbb::mutex::scoped_lock lock(my_mutex);/* y=fib(n-2); */ puts("Now:\n"); getchar();
}); // spawn another task
g.wait(); // wait for both tasks to complete
ret = x + y;
}
return ret;
} // - See more at: https://www.threadingbuildingblocks.org/tutorial-intel-tbb-task-based-programming#sthash.EzgRXzaB.dpuf
int main(int argc, char *argv[]) {
std::cout << fib(33);
// getchar();
return EXIT_SUCCESS;
}
#endif
<|endoftext|> |
<commit_before>/*
* Author: Vladimir Ivan
*
* Copyright (c) 2017, University Of Edinburgh
* 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 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 <exotica/Problems/SamplingProblem.h>
#include <exotica/Setup.h>
REGISTER_PROBLEM_TYPE("SamplingProblem", exotica::SamplingProblem)
namespace exotica
{
SamplingProblem::SamplingProblem()
{
Flags = KIN_FK;
}
SamplingProblem::~SamplingProblem()
{
// TODO Auto-generated destructor stub
}
std::vector<double> SamplingProblem::getBounds()
{
std::vector<double> bounds;
auto jointLimits = scene_->getSolver().getJointLimits();
bounds.resize(2 * N);
for (unsigned int i = 0; i < N; i++)
{
bounds[i] = jointLimits(i, 0);
bounds[i + N] = jointLimits(i, 1);
}
return bounds;
}
void SamplingProblem::Instantiate(SamplingProblemInitializer& init)
{
Parameters = init;
if (init.LocalPlannerConfig != "")
{
local_planner_config_ = init.LocalPlannerConfig;
}
goal_ = init.Goal;
if (scene_->getBaseType() != exotica::BASE_TYPE::FIXED)
compound_ = true;
else
compound_ = false;
NumTasks = Tasks.size();
PhiN = 0;
JN = 0;
for (int i = 0; i < NumTasks; i++)
{
appendVector(Phi.map, Tasks[i]->getLieGroupIndices());
PhiN += Tasks[i]->Length;
JN += Tasks[i]->LengthJ;
}
Phi.setZero(PhiN);
TaskSpaceVector dummy;
Constraint.initialize(init.Constraint, shared_from_this(), dummy);
Constraint.Tolerance = init.ConstraintTolerance;
applyStartState(false);
preupdate();
}
void SamplingProblem::preupdate()
{
PlanningProblem::preupdate();
for (int i = 0; i < Tasks.size(); i++) Tasks[i]->isUsed = false;
Constraint.updateS();
}
void SamplingProblem::setGoalState(Eigen::VectorXdRefConst qT)
{
if (qT.rows() != N)
throw_pretty("Dimensionality of goal state wrong: Got " << qT.rows() << ", expected " << N);
goal_ = qT;
}
bool SamplingProblem::isValid(Eigen::VectorXdRefConst x)
{
scene_->Update(x);
for (int i = 0; i < NumTasks; i++)
{
if (Tasks[i]->isUsed)
Tasks[i]->update(x, Phi.data.segment(Tasks[i]->Start, Tasks[i]->Length));
}
Constraint.update(Phi);
numberOfProblemUpdates++;
return ((Constraint.S * Constraint.ydiff).array() < 0.0).all();
}
void SamplingProblem::Update(Eigen::VectorXdRefConst x)
{
isValid(x);
}
int SamplingProblem::getSpaceDim()
{
return N;
}
bool SamplingProblem::isCompoundStateSpace()
{
return compound_;
}
} /* namespace exotica */
<commit_msg>SamplingProblem: Fix constraint validity check. - Relates to #368<commit_after>/*
* Author: Vladimir Ivan
*
* Copyright (c) 2017, University Of Edinburgh
* 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 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 <exotica/Problems/SamplingProblem.h>
#include <exotica/Setup.h>
REGISTER_PROBLEM_TYPE("SamplingProblem", exotica::SamplingProblem)
namespace exotica
{
SamplingProblem::SamplingProblem()
{
Flags = KIN_FK;
}
SamplingProblem::~SamplingProblem()
{
// TODO Auto-generated destructor stub
}
std::vector<double> SamplingProblem::getBounds()
{
std::vector<double> bounds;
auto jointLimits = scene_->getSolver().getJointLimits();
bounds.resize(2 * N);
for (unsigned int i = 0; i < N; i++)
{
bounds[i] = jointLimits(i, 0);
bounds[i + N] = jointLimits(i, 1);
}
return bounds;
}
void SamplingProblem::Instantiate(SamplingProblemInitializer& init)
{
Parameters = init;
if (init.LocalPlannerConfig != "")
{
local_planner_config_ = init.LocalPlannerConfig;
}
goal_ = init.Goal;
if (scene_->getBaseType() != exotica::BASE_TYPE::FIXED)
compound_ = true;
else
compound_ = false;
NumTasks = Tasks.size();
PhiN = 0;
JN = 0;
for (int i = 0; i < NumTasks; i++)
{
appendVector(Phi.map, Tasks[i]->getLieGroupIndices());
PhiN += Tasks[i]->Length;
JN += Tasks[i]->LengthJ;
}
Phi.setZero(PhiN);
TaskSpaceVector dummy;
Constraint.initialize(init.Constraint, shared_from_this(), dummy);
Constraint.Tolerance = init.ConstraintTolerance;
applyStartState(false);
preupdate();
}
void SamplingProblem::preupdate()
{
PlanningProblem::preupdate();
for (int i = 0; i < Tasks.size(); i++) Tasks[i]->isUsed = false;
Constraint.updateS();
}
void SamplingProblem::setGoalState(Eigen::VectorXdRefConst qT)
{
if (qT.rows() != N)
throw_pretty("Dimensionality of goal state wrong: Got " << qT.rows() << ", expected " << N);
goal_ = qT;
}
bool SamplingProblem::isValid(Eigen::VectorXdRefConst x)
{
scene_->Update(x);
for (int i = 0; i < NumTasks; i++)
{
if (Tasks[i]->isUsed)
Tasks[i]->update(x, Phi.data.segment(Tasks[i]->Start, Tasks[i]->Length));
}
Constraint.update(Phi);
numberOfProblemUpdates++;
return ((Constraint.S * Constraint.ydiff).array().abs() <= 0.0).all();
}
void SamplingProblem::Update(Eigen::VectorXdRefConst x)
{
isValid(x);
}
int SamplingProblem::getSpaceDim()
{
return N;
}
bool SamplingProblem::isCompoundStateSpace()
{
return compound_;
}
} /* namespace exotica */
<|endoftext|> |
<commit_before>// Copyright 2016 Yahoo Inc. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
#include <vespa/fastos/fastos.h>
#include <vespa/searchcore/proton/matchengine/matchengine.h>
#include <vespa/vespalib/data/slime/slime.h>
#include <vespa/vespalib/testkit/test_kit.h>
#include <vespa/searchlib/engine/docsumreply.h>
#include <vespa/log/log.h>
LOG_SETUP("matchengine_test");
using namespace proton;
using namespace search::engine;
using namespace vespalib::slime;
using vespalib::Slime;
class MySearchHandler : public ISearchHandler {
size_t _numHits;
std::string _name;
std::string _reply;
public:
MySearchHandler(size_t numHits = 0,
const std::string & name = "my",
const std::string & reply = "myreply") :
_numHits(numHits), _name(name), _reply(reply) {}
virtual DocsumReply::UP getDocsums(const DocsumRequest &) {
return DocsumReply::UP(new DocsumReply);
}
virtual search::engine::SearchReply::UP match(
const ISearchHandler::SP &,
const search::engine::SearchRequest &,
vespalib::ThreadBundle &) const {
SearchReply::UP retval(new SearchReply);
for (size_t i = 0; i < _numHits; ++i) {
retval->hits.push_back(SearchReply::Hit());
}
return retval;
}
};
class LocalSearchClient : public SearchClient {
private:
vespalib::Monitor _monitor;
SearchReply::UP _reply;
public:
void searchDone(SearchReply::UP reply) {
vespalib::MonitorGuard guard(_monitor);
_reply = std::move(reply);
guard.broadcast();
}
SearchReply::UP getReply(uint32_t millis) {
vespalib::MonitorGuard guard(_monitor);
vespalib::TimedWaiter waiter(guard, millis);
while (_reply.get() == NULL && waiter.hasTime()) {
waiter.wait();
}
return std::move(_reply);
}
};
TEST("requireThatSearchesExecute")
{
int numMatcherThreads = 16;
MatchEngine engine(numMatcherThreads, 1, 7);
engine.setOnline();
engine.setNodeUp(true);
MySearchHandler::SP handler(new MySearchHandler);
DocTypeName dtnvfoo("foo");
engine.putSearchHandler(dtnvfoo, handler);
LocalSearchClient client;
SearchRequest::Source request(new SearchRequest());
SearchReply::UP reply = engine.search(std::move(request), client);
EXPECT_TRUE(reply.get() == NULL);
reply = client.getReply(10000);
EXPECT_TRUE(reply.get() != NULL);
}
bool
assertSearchReply(MatchEngine & engine, const std::string & searchDocType, size_t expHits)
{
SearchRequest *request = new SearchRequest();
request->propertiesMap.lookupCreate(search::MapNames::MATCH).add("documentdb.searchdoctype", searchDocType);
LocalSearchClient client;
engine.search(SearchRequest::Source(request), client);
SearchReply::UP reply = client.getReply(10000);
return EXPECT_EQUAL(expHits, reply->hits.size());
}
TEST("requireThatCorrectHandlerIsUsed")
{
MatchEngine engine(1, 1, 7);
engine.setOnline();
engine.setNodeUp(true);
ISearchHandler::SP h1(new MySearchHandler(2));
ISearchHandler::SP h2(new MySearchHandler(4));
ISearchHandler::SP h3(new MySearchHandler(6));
DocTypeName dtnvfoo("foo");
DocTypeName dtnvbar("bar");
DocTypeName dtnvbaz("baz");
engine.putSearchHandler(dtnvfoo, h1);
engine.putSearchHandler(dtnvbar, h2);
engine.putSearchHandler(dtnvbaz, h3);
EXPECT_TRUE(assertSearchReply(engine, "foo", 2));
EXPECT_TRUE(assertSearchReply(engine, "bar", 4));
EXPECT_TRUE(assertSearchReply(engine, "baz", 6));
EXPECT_TRUE(assertSearchReply(engine, "not", 4)); // uses the first (sorted on name)
}
struct ObserveBundleMatchHandler : MySearchHandler {
typedef std::shared_ptr<ObserveBundleMatchHandler> SP;
mutable size_t bundleSize;
ObserveBundleMatchHandler() : bundleSize(0) {}
virtual search::engine::SearchReply::UP match(
const ISearchHandler::SP &,
const search::engine::SearchRequest &,
vespalib::ThreadBundle &threadBundle) const
{
bundleSize = threadBundle.size();
return SearchReply::UP(new SearchReply);
}
};
TEST("requireThatBundlesAreUsed")
{
MatchEngine engine(15, 5, 7);
engine.setOnline();
engine.setNodeUp(true);
ObserveBundleMatchHandler::SP handler(new ObserveBundleMatchHandler());
DocTypeName dtnvfoo("foo");
engine.putSearchHandler(dtnvfoo, handler);
LocalSearchClient client;
SearchRequest::Source request(new SearchRequest());
engine.search(std::move(request), client);
SearchReply::UP reply = client.getReply(10000);
EXPECT_EQUAL(7u, reply->getDistributionKey());
EXPECT_EQUAL(5u, handler->bundleSize);
}
TEST("requireThatHandlersCanBeRemoved")
{
MatchEngine engine(1, 1, 7);
engine.setOnline();
engine.setNodeUp(true);
ISearchHandler::SP h(new MySearchHandler(1));
DocTypeName docType("foo");
engine.putSearchHandler(docType, h);
ISearchHandler::SP r = engine.getSearchHandler(docType);
EXPECT_TRUE(r.get() != NULL);
EXPECT_TRUE(h.get() == r.get());
r = engine.removeSearchHandler(docType);
EXPECT_TRUE(r.get() != NULL);
EXPECT_TRUE(h.get() == r.get());
r = engine.getSearchHandler(docType);
EXPECT_TRUE(r.get() == NULL);
}
TEST("requireThatEngineCanBeSetOffline")
{
MatchEngine engine(1, 1, 7);
engine.setNodeUp(true);
engine.setOnline();
engine.setInService();
ASSERT_TRUE(engine.isOnline());
engine.setOffline();
ASSERT_FALSE(engine.isOnline());
engine.setOnline();
ASSERT_TRUE(engine.isOnline());
engine.setOutOfService();
ASSERT_FALSE(engine.isOnline());
}
TEST("requireThatEmptySearchReplyIsReturnedWhenEngineIsClosed")
{
MatchEngine engine(1, 1, 7);
engine.setOnline();
engine.setNodeUp(true);
engine.close();
LocalSearchClient client;
SearchRequest::Source request(new SearchRequest());
SearchReply::UP reply = engine.search(std::move(request), client);
EXPECT_TRUE(reply.get() != NULL);
EXPECT_EQUAL(0u, reply->hits.size());
EXPECT_EQUAL(7u, reply->getDistributionKey());
}
TEST("requireThatStateIsReported")
{
MatchEngine engine(1, 1, 7);
Slime slime;
SlimeInserter inserter(slime);
engine.get_state(inserter, false);
EXPECT_EQUAL(
"{\n"
" \"status\": {\n"
" \"state\": \"OFFLINE\",\n"
" \"message\": \"Search interface is offline\"\n"
" }\n"
"}\n",
slime.toString());
}
TEST_MAIN() { TEST_RUN_ALL(); }
<commit_msg>No need for logging<commit_after>// Copyright 2016 Yahoo Inc. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
#include <vespa/fastos/fastos.h>
#include <vespa/searchcore/proton/matchengine/matchengine.h>
#include <vespa/vespalib/data/slime/slime.h>
#include <vespa/searchlib/engine/docsumreply.h>
#include <vespa/vespalib/testkit/test_kit.h>
using namespace proton;
using namespace search::engine;
using namespace vespalib::slime;
using vespalib::Slime;
class MySearchHandler : public ISearchHandler {
size_t _numHits;
std::string _name;
std::string _reply;
public:
MySearchHandler(size_t numHits = 0,
const std::string & name = "my",
const std::string & reply = "myreply") :
_numHits(numHits), _name(name), _reply(reply) {}
virtual DocsumReply::UP getDocsums(const DocsumRequest &) {
return DocsumReply::UP(new DocsumReply);
}
virtual search::engine::SearchReply::UP match(
const ISearchHandler::SP &,
const search::engine::SearchRequest &,
vespalib::ThreadBundle &) const {
SearchReply::UP retval(new SearchReply);
for (size_t i = 0; i < _numHits; ++i) {
retval->hits.push_back(SearchReply::Hit());
}
return retval;
}
};
class LocalSearchClient : public SearchClient {
private:
vespalib::Monitor _monitor;
SearchReply::UP _reply;
public:
void searchDone(SearchReply::UP reply) {
vespalib::MonitorGuard guard(_monitor);
_reply = std::move(reply);
guard.broadcast();
}
SearchReply::UP getReply(uint32_t millis) {
vespalib::MonitorGuard guard(_monitor);
vespalib::TimedWaiter waiter(guard, millis);
while (_reply.get() == NULL && waiter.hasTime()) {
waiter.wait();
}
return std::move(_reply);
}
};
TEST("requireThatSearchesExecute")
{
int numMatcherThreads = 16;
MatchEngine engine(numMatcherThreads, 1, 7);
engine.setOnline();
engine.setNodeUp(true);
MySearchHandler::SP handler(new MySearchHandler);
DocTypeName dtnvfoo("foo");
engine.putSearchHandler(dtnvfoo, handler);
LocalSearchClient client;
SearchRequest::Source request(new SearchRequest());
SearchReply::UP reply = engine.search(std::move(request), client);
EXPECT_TRUE(reply.get() == NULL);
reply = client.getReply(10000);
EXPECT_TRUE(reply.get() != NULL);
}
bool
assertSearchReply(MatchEngine & engine, const std::string & searchDocType, size_t expHits)
{
SearchRequest *request = new SearchRequest();
request->propertiesMap.lookupCreate(search::MapNames::MATCH).add("documentdb.searchdoctype", searchDocType);
LocalSearchClient client;
engine.search(SearchRequest::Source(request), client);
SearchReply::UP reply = client.getReply(10000);
return EXPECT_EQUAL(expHits, reply->hits.size());
}
TEST("requireThatCorrectHandlerIsUsed")
{
MatchEngine engine(1, 1, 7);
engine.setOnline();
engine.setNodeUp(true);
ISearchHandler::SP h1(new MySearchHandler(2));
ISearchHandler::SP h2(new MySearchHandler(4));
ISearchHandler::SP h3(new MySearchHandler(6));
DocTypeName dtnvfoo("foo");
DocTypeName dtnvbar("bar");
DocTypeName dtnvbaz("baz");
engine.putSearchHandler(dtnvfoo, h1);
engine.putSearchHandler(dtnvbar, h2);
engine.putSearchHandler(dtnvbaz, h3);
EXPECT_TRUE(assertSearchReply(engine, "foo", 2));
EXPECT_TRUE(assertSearchReply(engine, "bar", 4));
EXPECT_TRUE(assertSearchReply(engine, "baz", 6));
EXPECT_TRUE(assertSearchReply(engine, "not", 4)); // uses the first (sorted on name)
}
struct ObserveBundleMatchHandler : MySearchHandler {
typedef std::shared_ptr<ObserveBundleMatchHandler> SP;
mutable size_t bundleSize;
ObserveBundleMatchHandler() : bundleSize(0) {}
virtual search::engine::SearchReply::UP match(
const ISearchHandler::SP &,
const search::engine::SearchRequest &,
vespalib::ThreadBundle &threadBundle) const
{
bundleSize = threadBundle.size();
return SearchReply::UP(new SearchReply);
}
};
TEST("requireThatBundlesAreUsed")
{
MatchEngine engine(15, 5, 7);
engine.setOnline();
engine.setNodeUp(true);
ObserveBundleMatchHandler::SP handler(new ObserveBundleMatchHandler());
DocTypeName dtnvfoo("foo");
engine.putSearchHandler(dtnvfoo, handler);
LocalSearchClient client;
SearchRequest::Source request(new SearchRequest());
engine.search(std::move(request), client);
SearchReply::UP reply = client.getReply(10000);
EXPECT_EQUAL(7u, reply->getDistributionKey());
EXPECT_EQUAL(5u, handler->bundleSize);
}
TEST("requireThatHandlersCanBeRemoved")
{
MatchEngine engine(1, 1, 7);
engine.setOnline();
engine.setNodeUp(true);
ISearchHandler::SP h(new MySearchHandler(1));
DocTypeName docType("foo");
engine.putSearchHandler(docType, h);
ISearchHandler::SP r = engine.getSearchHandler(docType);
EXPECT_TRUE(r.get() != NULL);
EXPECT_TRUE(h.get() == r.get());
r = engine.removeSearchHandler(docType);
EXPECT_TRUE(r.get() != NULL);
EXPECT_TRUE(h.get() == r.get());
r = engine.getSearchHandler(docType);
EXPECT_TRUE(r.get() == NULL);
}
TEST("requireThatEngineCanBeSetOffline")
{
MatchEngine engine(1, 1, 7);
engine.setNodeUp(true);
engine.setOnline();
engine.setInService();
ASSERT_TRUE(engine.isOnline());
engine.setOffline();
ASSERT_FALSE(engine.isOnline());
engine.setOnline();
ASSERT_TRUE(engine.isOnline());
engine.setOutOfService();
ASSERT_FALSE(engine.isOnline());
}
TEST("requireThatEmptySearchReplyIsReturnedWhenEngineIsClosed")
{
MatchEngine engine(1, 1, 7);
engine.setOnline();
engine.setNodeUp(true);
engine.close();
LocalSearchClient client;
SearchRequest::Source request(new SearchRequest());
SearchReply::UP reply = engine.search(std::move(request), client);
EXPECT_TRUE(reply.get() != NULL);
EXPECT_EQUAL(0u, reply->hits.size());
EXPECT_EQUAL(7u, reply->getDistributionKey());
}
TEST("requireThatStateIsReported")
{
MatchEngine engine(1, 1, 7);
Slime slime;
SlimeInserter inserter(slime);
engine.get_state(inserter, false);
EXPECT_EQUAL(
"{\n"
" \"status\": {\n"
" \"state\": \"OFFLINE\",\n"
" \"message\": \"Search interface is offline\"\n"
" }\n"
"}\n",
slime.toString());
}
TEST_MAIN() { TEST_RUN_ALL(); }
<|endoftext|> |
<commit_before>/*
* Copyright 2017 Google Inc.
*
* Use of this source code is governed by a BSD-style license that can be
* found in the LICENSE file.
*/
#include "SkottieAnimator.h"
#include "SkCubicMap.h"
#include "SkJSONCPP.h"
#include "SkottieProperties.h"
#include "SkottieParser.h"
#include "SkTArray.h"
#include <memory>
namespace skottie {
namespace {
#define LOG SkDebugf
bool LogFail(const Json::Value& json, const char* msg) {
const auto dump = json.toStyledString();
LOG("!! %s: %s", msg, dump.c_str());
return false;
}
template <typename T>
static inline T lerp(const T&, const T&, float);
template <>
ScalarValue lerp(const ScalarValue& v0, const ScalarValue& v1, float t) {
SkASSERT(t >= 0 && t <= 1);
return v0 * (1 - t) + v1 * t;
}
template <>
VectorValue lerp(const VectorValue& v0, const VectorValue& v1, float t) {
SkASSERT(v0.size() == v1.size());
VectorValue v;
v.reserve(v0.size());
for (size_t i = 0; i < v0.size(); ++i) {
v.push_back(lerp(v0[i], v1[i], t));
}
return v;
}
template <>
ShapeValue lerp(const ShapeValue& v0, const ShapeValue& v1, float t) {
SkASSERT(t >= 0 && t <= 1);
SkASSERT(v1.isInterpolatable(v0));
ShapeValue v;
SkAssertResult(v1.interpolate(v0, t, &v));
v.setIsVolatile(true);
return v;
}
class KeyframeAnimatorBase : public sksg::Animator {
public:
int count() const { return fRecs.count(); }
protected:
KeyframeAnimatorBase() = default;
struct KeyframeRec {
float t0, t1;
int vidx0, vidx1, // v0/v1 indices
cmidx; // cubic map index
bool contains(float t) const { return t0 <= t && t <= t1; }
bool isConstant() const { return vidx0 == vidx1; }
bool isValid() const {
SkASSERT(t0 <= t1);
// Constant frames don't need/use t1 and vidx1.
return t0 < t1 || this->isConstant();
}
};
const KeyframeRec& frame(float t) {
if (!fCachedRec || !fCachedRec->contains(t)) {
fCachedRec = findFrame(t);
}
return *fCachedRec;
}
float localT(const KeyframeRec& rec, float t) const {
SkASSERT(rec.isValid());
SkASSERT(!rec.isConstant());
SkASSERT(t > rec.t0 && t < rec.t1);
auto lt = (t - rec.t0) / (rec.t1 - rec.t0);
return rec.cmidx < 0
? lt
: SkTPin(fCubicMaps[rec.cmidx].computeYFromX(lt), 0.0f, 1.0f);
}
virtual int parseValue(const Json::Value&) = 0;
void parseKeyFrames(const Json::Value& jframes) {
if (!jframes.isArray())
return;
for (const auto& jframe : jframes) {
if (!jframe.isObject())
continue;
float t0;
if (!Parse(jframe["t"], &t0)) {
continue;
}
if (!fRecs.empty()) {
if (fRecs.back().t1 >= t0) {
LOG("!! Ignoring out-of-order key frame (t:%f < t:%f)\n", t0, fRecs.back().t1);
continue;
}
// Back-fill t1 in prev interval. Note: we do this even if we end up discarding
// the current interval (to support "t"-only final frames).
fRecs.back().t1 = t0;
}
const auto vidx0 = this->parseValue(jframe["s"]);
if (vidx0 < 0) {
continue;
}
// Defaults for constant frames.
int vidx1 = vidx0, cmidx = -1;
if (!ParseDefault(jframe["h"], false)) {
// Regular frame, requires an end value.
vidx1 = this->parseValue(jframe["e"]);
if (vidx1 < 0) {
continue;
}
// default is linear lerp
static constexpr SkPoint kDefaultC0 = { 0, 0 },
kDefaultC1 = { 1, 1 };
const auto c0 = ParseDefault(jframe["i"], kDefaultC0),
c1 = ParseDefault(jframe["o"], kDefaultC1);
if (c0 != kDefaultC0 || c1 != kDefaultC1) {
// TODO: is it worth de-duping these?
cmidx = fCubicMaps.count();
fCubicMaps.emplace_back();
// TODO: why do we have to plug these inverted?
fCubicMaps.back().setPts(c1, c0);
}
}
fRecs.push_back({t0, t0, vidx0, vidx1, cmidx });
}
// If we couldn't determine a valid t1 for the last frame, discard it.
if (!fRecs.empty() && !fRecs.back().isValid()) {
fRecs.pop_back();
}
SkASSERT(fRecs.empty() || fRecs.back().isValid());
}
private:
const KeyframeRec* findFrame(float t) const {
SkASSERT(!fRecs.empty());
auto f0 = &fRecs.front(),
f1 = &fRecs.back();
SkASSERT(f0->isValid());
SkASSERT(f1->isValid());
if (t < f0->t0) {
return f0;
}
if (t > f1->t1) {
return f1;
}
while (f0 != f1) {
SkASSERT(f0 < f1);
SkASSERT(t >= f0->t0 && t <= f1->t1);
const auto f = f0 + (f1 - f0) / 2;
SkASSERT(f->isValid());
if (t > f->t1) {
f0 = f + 1;
} else {
f1 = f;
}
}
SkASSERT(f0 == f1);
SkASSERT(f0->contains(t));
return f0;
}
SkTArray<KeyframeRec> fRecs;
SkTArray<SkCubicMap> fCubicMaps;
const KeyframeRec* fCachedRec = nullptr;
using INHERITED = sksg::Animator;
};
template <typename T>
class KeyframeAnimator final : public KeyframeAnimatorBase {
public:
static std::unique_ptr<KeyframeAnimator> Make(const Json::Value& jframes,
std::function<void(const T&)>&& apply) {
std::unique_ptr<KeyframeAnimator> animator(new KeyframeAnimator(jframes, std::move(apply)));
if (!animator->count())
return nullptr;
return animator;
}
protected:
void onTick(float t) override {
T val;
this->eval(this->frame(t), t, &val);
fApplyFunc(val);
}
private:
KeyframeAnimator(const Json::Value& jframes,
std::function<void(const T&)>&& apply)
: fApplyFunc(std::move(apply)) {
this->parseKeyFrames(jframes);
}
int parseValue(const Json::Value& jv) override {
T val;
if (!Parse(jv, &val) || (!fVs.empty() &&
ValueTraits<T>::Cardinality(val) != ValueTraits<T>::Cardinality(fVs.back()))) {
return -1;
}
// TODO: full deduping?
if (fVs.empty() || val != fVs.back()) {
fVs.push_back(std::move(val));
}
return fVs.count() - 1;
}
void eval(const KeyframeRec& rec, float t, T* v) const {
SkASSERT(rec.isValid());
if (rec.isConstant() || t <= rec.t0) {
*v = fVs[rec.vidx0];
} else if (t >= rec.t1) {
*v = fVs[rec.vidx1];
} else {
const auto lt = this->localT(rec, t);
const auto& v0 = fVs[rec.vidx0];
const auto& v1 = fVs[rec.vidx1];
*v = lerp(v0, v1, lt);
}
}
const std::function<void(const T&)> fApplyFunc;
SkTArray<T> fVs;
using INHERITED = KeyframeAnimatorBase;
};
template <typename T>
static inline bool BindPropertyImpl(const Json::Value& jprop,
sksg::AnimatorList* animators,
std::function<void(const T&)>&& apply,
const T* noop) {
if (!jprop.isObject())
return false;
const auto& jpropA = jprop["a"];
const auto& jpropK = jprop["k"];
// Older Json versions don't have an "a" animation marker.
// For those, we attempt to parse both ways.
if (!ParseDefault(jpropA, false)) {
T val;
if (Parse<T>(jpropK, &val)) {
// Static property.
if (noop && val == *noop)
return false;
apply(val);
return true;
}
if (!jpropA.isNull()) {
return LogFail(jprop, "Could not parse (explicit) static property");
}
}
// Keyframe property.
auto animator = KeyframeAnimator<T>::Make(jpropK, std::move(apply));
if (!animator) {
return LogFail(jprop, "Could not parse keyframed property");
}
animators->push_back(std::move(animator));
return true;
}
} // namespace
template <>
bool BindProperty(const Json::Value& jprop,
sksg::AnimatorList* animators,
std::function<void(const ScalarValue&)>&& apply,
const ScalarValue* noop) {
return BindPropertyImpl(jprop, animators, std::move(apply), noop);
}
template <>
bool BindProperty(const Json::Value& jprop,
sksg::AnimatorList* animators,
std::function<void(const VectorValue&)>&& apply,
const VectorValue* noop) {
return BindPropertyImpl(jprop, animators, std::move(apply), noop);
}
template <>
bool BindProperty(const Json::Value& jprop,
sksg::AnimatorList* animators,
std::function<void(const ShapeValue&)>&& apply,
const ShapeValue* noop) {
return BindPropertyImpl(jprop, animators, std::move(apply), noop);
}
} // namespace skottie
<commit_msg>[skottie] Split-position support<commit_after>/*
* Copyright 2017 Google Inc.
*
* Use of this source code is governed by a BSD-style license that can be
* found in the LICENSE file.
*/
#include "SkottieAnimator.h"
#include "SkCubicMap.h"
#include "SkJSONCPP.h"
#include "SkottieProperties.h"
#include "SkottieParser.h"
#include "SkTArray.h"
#include <memory>
namespace skottie {
namespace {
#define LOG SkDebugf
bool LogFail(const Json::Value& json, const char* msg) {
const auto dump = json.toStyledString();
LOG("!! %s: %s", msg, dump.c_str());
return false;
}
template <typename T>
static inline T lerp(const T&, const T&, float);
template <>
ScalarValue lerp(const ScalarValue& v0, const ScalarValue& v1, float t) {
SkASSERT(t >= 0 && t <= 1);
return v0 * (1 - t) + v1 * t;
}
template <>
VectorValue lerp(const VectorValue& v0, const VectorValue& v1, float t) {
SkASSERT(v0.size() == v1.size());
VectorValue v;
v.reserve(v0.size());
for (size_t i = 0; i < v0.size(); ++i) {
v.push_back(lerp(v0[i], v1[i], t));
}
return v;
}
template <>
ShapeValue lerp(const ShapeValue& v0, const ShapeValue& v1, float t) {
SkASSERT(t >= 0 && t <= 1);
SkASSERT(v1.isInterpolatable(v0));
ShapeValue v;
SkAssertResult(v1.interpolate(v0, t, &v));
v.setIsVolatile(true);
return v;
}
class KeyframeAnimatorBase : public sksg::Animator {
public:
int count() const { return fRecs.count(); }
protected:
KeyframeAnimatorBase() = default;
struct KeyframeRec {
float t0, t1;
int vidx0, vidx1, // v0/v1 indices
cmidx; // cubic map index
bool contains(float t) const { return t0 <= t && t <= t1; }
bool isConstant() const { return vidx0 == vidx1; }
bool isValid() const {
SkASSERT(t0 <= t1);
// Constant frames don't need/use t1 and vidx1.
return t0 < t1 || this->isConstant();
}
};
const KeyframeRec& frame(float t) {
if (!fCachedRec || !fCachedRec->contains(t)) {
fCachedRec = findFrame(t);
}
return *fCachedRec;
}
float localT(const KeyframeRec& rec, float t) const {
SkASSERT(rec.isValid());
SkASSERT(!rec.isConstant());
SkASSERT(t > rec.t0 && t < rec.t1);
auto lt = (t - rec.t0) / (rec.t1 - rec.t0);
return rec.cmidx < 0
? lt
: SkTPin(fCubicMaps[rec.cmidx].computeYFromX(lt), 0.0f, 1.0f);
}
virtual int parseValue(const Json::Value&) = 0;
void parseKeyFrames(const Json::Value& jframes) {
if (!jframes.isArray())
return;
for (const auto& jframe : jframes) {
if (!jframe.isObject())
continue;
float t0;
if (!Parse(jframe["t"], &t0)) {
continue;
}
if (!fRecs.empty()) {
if (fRecs.back().t1 >= t0) {
LOG("!! Ignoring out-of-order key frame (t:%f < t:%f)\n", t0, fRecs.back().t1);
continue;
}
// Back-fill t1 in prev interval. Note: we do this even if we end up discarding
// the current interval (to support "t"-only final frames).
fRecs.back().t1 = t0;
}
const auto vidx0 = this->parseValue(jframe["s"]);
if (vidx0 < 0) {
continue;
}
// Defaults for constant frames.
int vidx1 = vidx0, cmidx = -1;
if (!ParseDefault(jframe["h"], false)) {
// Regular frame, requires an end value.
vidx1 = this->parseValue(jframe["e"]);
if (vidx1 < 0) {
continue;
}
// default is linear lerp
static constexpr SkPoint kDefaultC0 = { 0, 0 },
kDefaultC1 = { 1, 1 };
const auto c0 = ParseDefault(jframe["i"], kDefaultC0),
c1 = ParseDefault(jframe["o"], kDefaultC1);
if (c0 != kDefaultC0 || c1 != kDefaultC1) {
// TODO: is it worth de-duping these?
cmidx = fCubicMaps.count();
fCubicMaps.emplace_back();
// TODO: why do we have to plug these inverted?
fCubicMaps.back().setPts(c1, c0);
}
}
fRecs.push_back({t0, t0, vidx0, vidx1, cmidx });
}
// If we couldn't determine a valid t1 for the last frame, discard it.
if (!fRecs.empty() && !fRecs.back().isValid()) {
fRecs.pop_back();
}
SkASSERT(fRecs.empty() || fRecs.back().isValid());
}
private:
const KeyframeRec* findFrame(float t) const {
SkASSERT(!fRecs.empty());
auto f0 = &fRecs.front(),
f1 = &fRecs.back();
SkASSERT(f0->isValid());
SkASSERT(f1->isValid());
if (t < f0->t0) {
return f0;
}
if (t > f1->t1) {
return f1;
}
while (f0 != f1) {
SkASSERT(f0 < f1);
SkASSERT(t >= f0->t0 && t <= f1->t1);
const auto f = f0 + (f1 - f0) / 2;
SkASSERT(f->isValid());
if (t > f->t1) {
f0 = f + 1;
} else {
f1 = f;
}
}
SkASSERT(f0 == f1);
SkASSERT(f0->contains(t));
return f0;
}
SkTArray<KeyframeRec> fRecs;
SkTArray<SkCubicMap> fCubicMaps;
const KeyframeRec* fCachedRec = nullptr;
using INHERITED = sksg::Animator;
};
template <typename T>
class KeyframeAnimator final : public KeyframeAnimatorBase {
public:
static std::unique_ptr<KeyframeAnimator> Make(const Json::Value& jframes,
std::function<void(const T&)>&& apply) {
std::unique_ptr<KeyframeAnimator> animator(new KeyframeAnimator(jframes, std::move(apply)));
if (!animator->count())
return nullptr;
return animator;
}
protected:
void onTick(float t) override {
T val;
this->eval(this->frame(t), t, &val);
fApplyFunc(val);
}
private:
KeyframeAnimator(const Json::Value& jframes,
std::function<void(const T&)>&& apply)
: fApplyFunc(std::move(apply)) {
this->parseKeyFrames(jframes);
}
int parseValue(const Json::Value& jv) override {
T val;
if (!Parse(jv, &val) || (!fVs.empty() &&
ValueTraits<T>::Cardinality(val) != ValueTraits<T>::Cardinality(fVs.back()))) {
return -1;
}
// TODO: full deduping?
if (fVs.empty() || val != fVs.back()) {
fVs.push_back(std::move(val));
}
return fVs.count() - 1;
}
void eval(const KeyframeRec& rec, float t, T* v) const {
SkASSERT(rec.isValid());
if (rec.isConstant() || t <= rec.t0) {
*v = fVs[rec.vidx0];
} else if (t >= rec.t1) {
*v = fVs[rec.vidx1];
} else {
const auto lt = this->localT(rec, t);
const auto& v0 = fVs[rec.vidx0];
const auto& v1 = fVs[rec.vidx1];
*v = lerp(v0, v1, lt);
}
}
const std::function<void(const T&)> fApplyFunc;
SkTArray<T> fVs;
using INHERITED = KeyframeAnimatorBase;
};
template <typename T>
static inline bool BindPropertyImpl(const Json::Value& jprop,
sksg::AnimatorList* animators,
std::function<void(const T&)>&& apply,
const T* noop = nullptr) {
if (!jprop.isObject())
return false;
const auto& jpropA = jprop["a"];
const auto& jpropK = jprop["k"];
// Older Json versions don't have an "a" animation marker.
// For those, we attempt to parse both ways.
if (!ParseDefault(jpropA, false)) {
T val;
if (Parse<T>(jpropK, &val)) {
// Static property.
if (noop && val == *noop)
return false;
apply(val);
return true;
}
if (!jpropA.isNull()) {
return LogFail(jprop, "Could not parse (explicit) static property");
}
}
// Keyframe property.
auto animator = KeyframeAnimator<T>::Make(jpropK, std::move(apply));
if (!animator) {
return LogFail(jprop, "Could not parse keyframed property");
}
animators->push_back(std::move(animator));
return true;
}
class SplitPointAnimator final : public sksg::Animator {
public:
static std::unique_ptr<SplitPointAnimator> Make(const Json::Value& jprop,
std::function<void(const VectorValue&)>&& apply,
const VectorValue*) {
if (!jprop.isObject())
return nullptr;
std::unique_ptr<SplitPointAnimator> split_animator(
new SplitPointAnimator(std::move(apply)));
// This raw pointer is captured in lambdas below. But the lambdas are owned by
// the object itself, so the scope is bound to the life time of the object.
auto* split_animator_ptr = split_animator.get();
if (!BindPropertyImpl<ScalarValue>(jprop["x"], &split_animator->fAnimators,
[split_animator_ptr](const ScalarValue& x) { split_animator_ptr->setX(x); }) ||
!BindPropertyImpl<ScalarValue>(jprop["y"], &split_animator->fAnimators,
[split_animator_ptr](const ScalarValue& y) { split_animator_ptr->setY(y); })) {
LogFail(jprop, "Could not parse split property");
return nullptr;
}
if (split_animator->fAnimators.empty()) {
// Static split property, no need to hold on to the split animator.
return nullptr;
}
return split_animator;
}
void onTick(float t) override {
for (const auto& animator : fAnimators) {
animator->tick(t);
}
const VectorValue vec = { fX, fY };
fApplyFunc(vec);
}
void setX(const ScalarValue& x) { fX = x; }
void setY(const ScalarValue& y) { fY = y; }
private:
explicit SplitPointAnimator(std::function<void(const VectorValue&)>&& apply)
: fApplyFunc(std::move(apply)) {}
const std::function<void(const VectorValue&)> fApplyFunc;
sksg::AnimatorList fAnimators;
ScalarValue fX = 0,
fY = 0;
using INHERITED = sksg::Animator;
};
bool BindSplitPositionProperty(const Json::Value& jprop,
sksg::AnimatorList* animators,
std::function<void(const VectorValue&)>&& apply,
const VectorValue* noop) {
if (auto split_animator = SplitPointAnimator::Make(jprop, std::move(apply), noop)) {
animators->push_back(std::unique_ptr<sksg::Animator>(split_animator.release()));
return true;
}
return false;
}
} // namespace
template <>
bool BindProperty(const Json::Value& jprop,
sksg::AnimatorList* animators,
std::function<void(const ScalarValue&)>&& apply,
const ScalarValue* noop) {
return BindPropertyImpl(jprop, animators, std::move(apply), noop);
}
template <>
bool BindProperty(const Json::Value& jprop,
sksg::AnimatorList* animators,
std::function<void(const VectorValue&)>&& apply,
const VectorValue* noop) {
return ParseDefault(jprop["s"], false)
? BindSplitPositionProperty(jprop, animators, std::move(apply), noop)
: BindPropertyImpl(jprop, animators, std::move(apply), noop);
}
template <>
bool BindProperty(const Json::Value& jprop,
sksg::AnimatorList* animators,
std::function<void(const ShapeValue&)>&& apply,
const ShapeValue* noop) {
return BindPropertyImpl(jprop, animators, std::move(apply), noop);
}
} // namespace skottie
<|endoftext|> |
<commit_before>// Copyright (c) 2011 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome/browser/safe_browsing/client_side_detection_host.h"
#include <vector>
#include "base/command_line.h"
#include "base/logging.h"
#include "base/metrics/histogram.h"
#include "base/ref_counted.h"
#include "base/task.h"
#include "chrome/browser/browser_process.h"
#include "chrome/browser/profiles/profile.h"
#include "chrome/browser/safe_browsing/client_side_detection_service.h"
#include "chrome/browser/safe_browsing/safe_browsing_service.h"
#include "chrome/common/chrome_switches.h"
#include "chrome/common/render_messages.h"
#include "chrome/common/safebrowsing_messages.h"
#include "content/browser/browser_thread.h"
#include "content/browser/renderer_host/render_process_host.h"
#include "content/browser/renderer_host/render_view_host.h"
#include "content/browser/renderer_host/resource_dispatcher_host.h"
#include "content/browser/tab_contents/navigation_controller.h"
#include "content/browser/tab_contents/tab_contents.h"
#include "content/common/notification_service.h"
#include "content/common/notification_type.h"
#include "content/common/view_messages.h"
#include "googleurl/src/gurl.h"
namespace safe_browsing {
// This class is instantiated each time a new toplevel URL loads, and
// asynchronously checks whether the phishing classifier should run for this
// URL. If so, it notifies the renderer with a StartPhishingDetection IPC.
// Objects of this class are ref-counted and will be destroyed once nobody
// uses it anymore. If |tab_contents|, |csd_service| or |host| go away you need
// to call Cancel(). We keep the |sb_service| alive in a ref pointer for as
// long as it takes.
class ClientSideDetectionHost::ShouldClassifyUrlRequest
: public base::RefCountedThreadSafe<
ClientSideDetectionHost::ShouldClassifyUrlRequest> {
public:
ShouldClassifyUrlRequest(const ViewHostMsg_FrameNavigate_Params& params,
TabContents* tab_contents,
ClientSideDetectionService* csd_service,
SafeBrowsingService* sb_service,
ClientSideDetectionHost* host)
: canceled_(false),
params_(params),
tab_contents_(tab_contents),
csd_service_(csd_service),
sb_service_(sb_service),
host_(host) {
DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
DCHECK(tab_contents_);
DCHECK(csd_service_);
DCHECK(sb_service_);
DCHECK(host_);
}
void Start() {
DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
// We first start by doing the proxy, local IP and off-the-record checks
// synchronously because they are fast and they run on the UI thread.
// Don't run the phishing classifier if the URL came from a private
// network, since we don't want to ping back in this case. We also need
// to check whether the connection was proxied -- if so, we won't have the
// correct remote IP address, and will skip phishing classification.
if (params_.was_fetched_via_proxy) {
VLOG(1) << "Skipping phishing classification for URL: " << params_.url
<< " because it was fetched via a proxy.";
UMA_HISTOGRAM_COUNTS("SBClientPhishing.NoClassifyProxyFetch", 1);
return;
}
if (csd_service_->IsPrivateIPAddress(params_.socket_address.host())) {
VLOG(1) << "Skipping phishing classification for URL: " << params_.url
<< " because of hosting on private IP: "
<< params_.socket_address.host();
UMA_HISTOGRAM_COUNTS("SBClientPhishing.NoClassifyPrivateIP", 1);
return;
}
// Don't run the phishing classifier if the tab is off-the-record.
if (tab_contents_->profile()->IsOffTheRecord()) {
VLOG(1) << "Skipping phishing classification for URL: " << params_.url
<< " because we're browsing off-the-record.";
UMA_HISTOGRAM_COUNTS("SBClientPhishing.NoClassifyOffTheRecord", 1);
return;
}
// We lookup the csd-whitelist before we lookup the cache because
// a URL may have recently been whitelisted. If the URL matches
// the csd-whitelist we won't start classification. The
// csd-whitelist check has to be done on the IO thread because it
// uses the SafeBrowsing service class.
BrowserThread::PostTask(
BrowserThread::IO,
FROM_HERE,
NewRunnableMethod(this,
&ShouldClassifyUrlRequest::CheckCsdWhitelist,
params_.url));
}
void Cancel() {
canceled_ = true;
// Just to make sure we don't do anything stupid we reset all these
// pointers except for the safebrowsing service class which may be
// accessed by CheckCsdWhitelist().
tab_contents_ = NULL;
csd_service_ = NULL;
host_ = NULL;
}
private:
friend class base::RefCountedThreadSafe<
ClientSideDetectionHost::ShouldClassifyUrlRequest>;
// The destructor can be called either from the UI or the IO thread.
virtual ~ShouldClassifyUrlRequest() { }
void CheckCsdWhitelist(GURL url) {
DCHECK(BrowserThread::CurrentlyOn(BrowserThread::IO));
if (!sb_service_ || sb_service_->MatchCsdWhitelistUrl(url)) {
// We're done. There is no point in going back to the UI thread.
UMA_HISTOGRAM_COUNTS("SBClientPhishing.NoClassifyMatchCsdWhitelist", 1);
return;
}
BrowserThread::PostTask(
BrowserThread::UI,
FROM_HERE,
NewRunnableMethod(this,
&ShouldClassifyUrlRequest::CheckCache));
}
void CheckCache() {
DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
if (canceled_) {
return;
}
// If result is cached, we don't want to run classification again
bool is_phishing;
if (csd_service_->GetValidCachedResult(params_.url, &is_phishing)) {
VLOG(1) << "Satisfying request for " << params_.url << " from cache";
UMA_HISTOGRAM_COUNTS("SBClientPhishing.RequestSatisfiedFromCache", 1);
// Since we are already on the UI thread, this is safe.
host_->MaybeShowPhishingWarning(params_.url, is_phishing);
return;
}
// We want to limit the number of requests, though we will ignore the
// limit for urls in the cache. We don't want to start classifying
// too many pages as phishing, but for those that we already think are
// phishing we want to give ourselves a chance to fix false positives.
if (csd_service_->IsInCache(params_.url)) {
VLOG(1) << "Reporting limit skipped for " << params_.url
<< " as it was in the cache.";
UMA_HISTOGRAM_COUNTS("SBClientPhishing.ReportLimitSkipped", 1);
} else if (csd_service_->OverReportLimit()) {
VLOG(1) << "Too many report phishing requests sent recently, "
<< "not running classification for " << params_.url;
UMA_HISTOGRAM_COUNTS("SBClientPhishing.NoClassifyTooManyReports", 1);
return;
}
// Everything checks out, so start classification.
// |tab_contents_| is safe to call as we will be destructed
// before it is.
RenderViewHost* rvh = tab_contents_->render_view_host();
rvh->Send(new ViewMsg_StartPhishingDetection(
rvh->routing_id(), params_.url));
}
// No need to protect |canceled_| with a lock because it is only read and
// written by the UI thread.
bool canceled_;
ViewHostMsg_FrameNavigate_Params params_;
TabContents* tab_contents_;
ClientSideDetectionService* csd_service_;
// We keep a ref pointer here just to make sure the service class stays alive
// long enough.
scoped_refptr<SafeBrowsingService> sb_service_;
ClientSideDetectionHost* host_;
DISALLOW_COPY_AND_ASSIGN(ShouldClassifyUrlRequest);
};
// This class is used to display the phishing interstitial.
class CsdClient : public SafeBrowsingService::Client {
public:
CsdClient() {}
// Method from SafeBrowsingService::Client. This method is called on the
// IO thread once the interstitial is going away. This method simply deletes
// the CsdClient object.
virtual void OnBlockingPageComplete(bool proceed) {
DCHECK(BrowserThread::CurrentlyOn(BrowserThread::IO));
// Delete this on the UI thread since it was created there.
BrowserThread::PostTask(BrowserThread::UI,
FROM_HERE,
new DeleteTask<CsdClient>(this));
}
private:
friend class DeleteTask<CsdClient>; // Calls the private destructor.
// We're taking care of deleting this object. No-one else should delete
// this object.
virtual ~CsdClient() {}
DISALLOW_COPY_AND_ASSIGN(CsdClient);
};
ClientSideDetectionHost::ClientSideDetectionHost(TabContents* tab)
: TabContentsObserver(tab),
csd_service_(g_browser_process->safe_browsing_detection_service()),
cb_factory_(ALLOW_THIS_IN_INITIALIZER_LIST(this)) {
DCHECK(tab);
// Note: csd_service_ and sb_service_ might be NULL.
ResourceDispatcherHost* resource =
g_browser_process->resource_dispatcher_host();
if (resource) {
sb_service_ = resource->safe_browsing_service();
}
}
ClientSideDetectionHost::~ClientSideDetectionHost() {
// Tell any pending classification request that it is being canceled.
if (classification_request_.get()) {
classification_request_->Cancel();
}
}
bool ClientSideDetectionHost::OnMessageReceived(const IPC::Message& message) {
bool handled = true;
IPC_BEGIN_MESSAGE_MAP(ClientSideDetectionHost, message)
IPC_MESSAGE_HANDLER(SafeBrowsingDetectionHostMsg_DetectedPhishingSite,
OnDetectedPhishingSite)
IPC_MESSAGE_UNHANDLED(handled = false)
IPC_END_MESSAGE_MAP()
return handled;
}
void ClientSideDetectionHost::DidNavigateMainFramePostCommit(
const NavigationController::LoadCommittedDetails& details,
const ViewHostMsg_FrameNavigate_Params& params) {
// TODO(noelutz): move this DCHECK to TabContents and fix all the unit tests
// that don't call this method on the UI thread.
// DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
if (details.is_in_page) {
// If the navigation is within the same page, the user isn't really
// navigating away. We don't need to cancel a pending callback or
// begin a new classification.
return;
}
// If we navigate away and there currently is a pending phishing
// report request we have to cancel it to make sure we don't display
// an interstitial for the wrong page. Note that this won't cancel
// the server ping back but only cancel the showing of the
// interstial.
cb_factory_.RevokeAll();
if (csd_service_) {
// Cancel any pending classification request.
if (classification_request_.get()) {
classification_request_->Cancel();
}
// Notify the renderer if it should classify this URL.
classification_request_ = new ShouldClassifyUrlRequest(params,
tab_contents(),
csd_service_,
sb_service_,
this);
classification_request_->Start();
}
}
void ClientSideDetectionHost::OnDetectedPhishingSite(const GURL& phishing_url,
double phishing_score) {
DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
// There is something seriously wrong if there is no service class but
// this method is called. The renderer should not start phishing detection
// if there isn't any service class in the browser.
DCHECK(csd_service_);
if (csd_service_) {
// There shouldn't be any pending requests because we revoke them everytime
// we navigate away.
DCHECK(!cb_factory_.HasPendingCallbacks());
csd_service_->SendClientReportPhishingRequest(
phishing_url,
phishing_score,
cb_factory_.NewCallback(
&ClientSideDetectionHost::MaybeShowPhishingWarning));
}
}
void ClientSideDetectionHost::MaybeShowPhishingWarning(GURL phishing_url,
bool is_phishing) {
DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
if (is_phishing &&
CommandLine::ForCurrentProcess()->HasSwitch(
switches::kEnableClientSidePhishingInterstitial)) {
DCHECK(tab_contents());
// TODO(noelutz): this is not perfect. It's still possible that the
// user browses away before the interstitial is shown. Maybe we should
// stop all pending navigations?
if (sb_service_) {
// TODO(noelutz): refactor the SafeBrowsing service class and the
// SafeBrowsing blocking page class so that we don't need to depend
// on the SafeBrowsingService here and so that we don't need to go
// through the IO message loop.
std::vector<GURL> redirect_urls;
BrowserThread::PostTask(
BrowserThread::IO,
FROM_HERE,
NewRunnableMethod(sb_service_.get(),
&SafeBrowsingService::DisplayBlockingPage,
phishing_url, phishing_url,
redirect_urls,
// We only classify the main frame URL.
ResourceType::MAIN_FRAME,
// TODO(noelutz): create a separate threat type
// for client-side phishing detection.
SafeBrowsingService::URL_PHISHING,
new CsdClient() /* will delete itself */,
tab_contents()->GetRenderProcessHost()->id(),
tab_contents()->render_view_host()->routing_id()));
}
}
}
void ClientSideDetectionHost::set_client_side_detection_service(
ClientSideDetectionService* service) {
csd_service_ = service;
}
void ClientSideDetectionHost::set_safe_browsing_service(
SafeBrowsingService* service) {
sb_service_ = service;
}
} // namespace safe_browsing
<commit_msg>Group all histograms related to pre-classification check failures into a single enum histogram.<commit_after>// Copyright (c) 2011 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome/browser/safe_browsing/client_side_detection_host.h"
#include <vector>
#include "base/command_line.h"
#include "base/logging.h"
#include "base/metrics/histogram.h"
#include "base/ref_counted.h"
#include "base/task.h"
#include "chrome/browser/browser_process.h"
#include "chrome/browser/profiles/profile.h"
#include "chrome/browser/safe_browsing/client_side_detection_service.h"
#include "chrome/browser/safe_browsing/safe_browsing_service.h"
#include "chrome/common/chrome_switches.h"
#include "chrome/common/render_messages.h"
#include "chrome/common/safebrowsing_messages.h"
#include "content/browser/browser_thread.h"
#include "content/browser/renderer_host/render_process_host.h"
#include "content/browser/renderer_host/render_view_host.h"
#include "content/browser/renderer_host/resource_dispatcher_host.h"
#include "content/browser/tab_contents/navigation_controller.h"
#include "content/browser/tab_contents/tab_contents.h"
#include "content/common/notification_service.h"
#include "content/common/notification_type.h"
#include "content/common/view_messages.h"
#include "googleurl/src/gurl.h"
namespace safe_browsing {
// This class is instantiated each time a new toplevel URL loads, and
// asynchronously checks whether the phishing classifier should run for this
// URL. If so, it notifies the renderer with a StartPhishingDetection IPC.
// Objects of this class are ref-counted and will be destroyed once nobody
// uses it anymore. If |tab_contents|, |csd_service| or |host| go away you need
// to call Cancel(). We keep the |sb_service| alive in a ref pointer for as
// long as it takes.
class ClientSideDetectionHost::ShouldClassifyUrlRequest
: public base::RefCountedThreadSafe<
ClientSideDetectionHost::ShouldClassifyUrlRequest> {
public:
ShouldClassifyUrlRequest(const ViewHostMsg_FrameNavigate_Params& params,
TabContents* tab_contents,
ClientSideDetectionService* csd_service,
SafeBrowsingService* sb_service,
ClientSideDetectionHost* host)
: canceled_(false),
params_(params),
tab_contents_(tab_contents),
csd_service_(csd_service),
sb_service_(sb_service),
host_(host) {
DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
DCHECK(tab_contents_);
DCHECK(csd_service_);
DCHECK(sb_service_);
DCHECK(host_);
}
void Start() {
DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
// We first start by doing the proxy, local IP and off-the-record checks
// synchronously because they are fast and they run on the UI thread.
// Don't run the phishing classifier if the URL came from a private
// network, since we don't want to ping back in this case. We also need
// to check whether the connection was proxied -- if so, we won't have the
// correct remote IP address, and will skip phishing classification.
if (params_.was_fetched_via_proxy) {
VLOG(1) << "Skipping phishing classification for URL: " << params_.url
<< " because it was fetched via a proxy.";
UMA_HISTOGRAM_ENUMERATION("SBClientPhishing.PreClassificationCheckFail",
NO_CLASSIFY_PROXY_FETCH,
NO_CLASSIFY_MAX);
return;
}
if (csd_service_->IsPrivateIPAddress(params_.socket_address.host())) {
VLOG(1) << "Skipping phishing classification for URL: " << params_.url
<< " because of hosting on private IP: "
<< params_.socket_address.host();
UMA_HISTOGRAM_ENUMERATION("SBClientPhishing.PreClassificationCheckFail",
NO_CLASSIFY_PRIVATE_IP,
NO_CLASSIFY_MAX);
return;
}
// Don't run the phishing classifier if the tab is off-the-record.
if (tab_contents_->profile()->IsOffTheRecord()) {
VLOG(1) << "Skipping phishing classification for URL: " << params_.url
<< " because we're browsing off-the-record.";
UMA_HISTOGRAM_ENUMERATION("SBClientPhishing.PreClassificationCheckFail",
NO_CLASSIFY_OFF_THE_RECORD,
NO_CLASSIFY_MAX);
return;
}
// We lookup the csd-whitelist before we lookup the cache because
// a URL may have recently been whitelisted. If the URL matches
// the csd-whitelist we won't start classification. The
// csd-whitelist check has to be done on the IO thread because it
// uses the SafeBrowsing service class.
BrowserThread::PostTask(
BrowserThread::IO,
FROM_HERE,
NewRunnableMethod(this,
&ShouldClassifyUrlRequest::CheckCsdWhitelist,
params_.url));
}
void Cancel() {
canceled_ = true;
// Just to make sure we don't do anything stupid we reset all these
// pointers except for the safebrowsing service class which may be
// accessed by CheckCsdWhitelist().
tab_contents_ = NULL;
csd_service_ = NULL;
host_ = NULL;
}
private:
friend class base::RefCountedThreadSafe<
ClientSideDetectionHost::ShouldClassifyUrlRequest>;
// Enum used to keep stats about why the pre-classification check failed.
enum PreClassificationCheckFailures {
NO_CLASSIFY_PROXY_FETCH,
NO_CLASSIFY_PRIVATE_IP,
NO_CLASSIFY_OFF_THE_RECORD,
NO_CLASSIFY_MATCH_CSD_WHITELIST,
NO_CLASSIFY_TOO_MANY_REPORTS,
NO_CLASSIFY_MAX // Always add new values before this one.
};
// The destructor can be called either from the UI or the IO thread.
virtual ~ShouldClassifyUrlRequest() { }
void CheckCsdWhitelist(GURL url) {
DCHECK(BrowserThread::CurrentlyOn(BrowserThread::IO));
if (!sb_service_ || sb_service_->MatchCsdWhitelistUrl(url)) {
// We're done. There is no point in going back to the UI thread.
UMA_HISTOGRAM_ENUMERATION("SBClientPhishing.PreClassificationCheckFail",
NO_CLASSIFY_MATCH_CSD_WHITELIST,
NO_CLASSIFY_MAX);
return;
}
BrowserThread::PostTask(
BrowserThread::UI,
FROM_HERE,
NewRunnableMethod(this,
&ShouldClassifyUrlRequest::CheckCache));
}
void CheckCache() {
DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
if (canceled_) {
return;
}
// If result is cached, we don't want to run classification again
bool is_phishing;
if (csd_service_->GetValidCachedResult(params_.url, &is_phishing)) {
VLOG(1) << "Satisfying request for " << params_.url << " from cache";
UMA_HISTOGRAM_COUNTS("SBClientPhishing.RequestSatisfiedFromCache", 1);
// Since we are already on the UI thread, this is safe.
host_->MaybeShowPhishingWarning(params_.url, is_phishing);
return;
}
// We want to limit the number of requests, though we will ignore the
// limit for urls in the cache. We don't want to start classifying
// too many pages as phishing, but for those that we already think are
// phishing we want to give ourselves a chance to fix false positives.
if (csd_service_->IsInCache(params_.url)) {
VLOG(1) << "Reporting limit skipped for " << params_.url
<< " as it was in the cache.";
UMA_HISTOGRAM_COUNTS("SBClientPhishing.ReportLimitSkipped", 1);
} else if (csd_service_->OverReportLimit()) {
VLOG(1) << "Too many report phishing requests sent recently, "
<< "not running classification for " << params_.url;
UMA_HISTOGRAM_ENUMERATION("SBClientPhishing.PreClassificationCheckFail",
NO_CLASSIFY_TOO_MANY_REPORTS,
NO_CLASSIFY_MAX);
return;
}
// Everything checks out, so start classification.
// |tab_contents_| is safe to call as we will be destructed
// before it is.
RenderViewHost* rvh = tab_contents_->render_view_host();
rvh->Send(new ViewMsg_StartPhishingDetection(
rvh->routing_id(), params_.url));
}
// No need to protect |canceled_| with a lock because it is only read and
// written by the UI thread.
bool canceled_;
ViewHostMsg_FrameNavigate_Params params_;
TabContents* tab_contents_;
ClientSideDetectionService* csd_service_;
// We keep a ref pointer here just to make sure the service class stays alive
// long enough.
scoped_refptr<SafeBrowsingService> sb_service_;
ClientSideDetectionHost* host_;
DISALLOW_COPY_AND_ASSIGN(ShouldClassifyUrlRequest);
};
// This class is used to display the phishing interstitial.
class CsdClient : public SafeBrowsingService::Client {
public:
CsdClient() {}
// Method from SafeBrowsingService::Client. This method is called on the
// IO thread once the interstitial is going away. This method simply deletes
// the CsdClient object.
virtual void OnBlockingPageComplete(bool proceed) {
DCHECK(BrowserThread::CurrentlyOn(BrowserThread::IO));
// Delete this on the UI thread since it was created there.
BrowserThread::PostTask(BrowserThread::UI,
FROM_HERE,
new DeleteTask<CsdClient>(this));
}
private:
friend class DeleteTask<CsdClient>; // Calls the private destructor.
// We're taking care of deleting this object. No-one else should delete
// this object.
virtual ~CsdClient() {}
DISALLOW_COPY_AND_ASSIGN(CsdClient);
};
ClientSideDetectionHost::ClientSideDetectionHost(TabContents* tab)
: TabContentsObserver(tab),
csd_service_(g_browser_process->safe_browsing_detection_service()),
cb_factory_(ALLOW_THIS_IN_INITIALIZER_LIST(this)) {
DCHECK(tab);
// Note: csd_service_ and sb_service_ might be NULL.
ResourceDispatcherHost* resource =
g_browser_process->resource_dispatcher_host();
if (resource) {
sb_service_ = resource->safe_browsing_service();
}
}
ClientSideDetectionHost::~ClientSideDetectionHost() {
// Tell any pending classification request that it is being canceled.
if (classification_request_.get()) {
classification_request_->Cancel();
}
}
bool ClientSideDetectionHost::OnMessageReceived(const IPC::Message& message) {
bool handled = true;
IPC_BEGIN_MESSAGE_MAP(ClientSideDetectionHost, message)
IPC_MESSAGE_HANDLER(SafeBrowsingDetectionHostMsg_DetectedPhishingSite,
OnDetectedPhishingSite)
IPC_MESSAGE_UNHANDLED(handled = false)
IPC_END_MESSAGE_MAP()
return handled;
}
void ClientSideDetectionHost::DidNavigateMainFramePostCommit(
const NavigationController::LoadCommittedDetails& details,
const ViewHostMsg_FrameNavigate_Params& params) {
// TODO(noelutz): move this DCHECK to TabContents and fix all the unit tests
// that don't call this method on the UI thread.
// DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
if (details.is_in_page) {
// If the navigation is within the same page, the user isn't really
// navigating away. We don't need to cancel a pending callback or
// begin a new classification.
return;
}
// If we navigate away and there currently is a pending phishing
// report request we have to cancel it to make sure we don't display
// an interstitial for the wrong page. Note that this won't cancel
// the server ping back but only cancel the showing of the
// interstial.
cb_factory_.RevokeAll();
if (csd_service_) {
// Cancel any pending classification request.
if (classification_request_.get()) {
classification_request_->Cancel();
}
// Notify the renderer if it should classify this URL.
classification_request_ = new ShouldClassifyUrlRequest(params,
tab_contents(),
csd_service_,
sb_service_,
this);
classification_request_->Start();
}
}
void ClientSideDetectionHost::OnDetectedPhishingSite(const GURL& phishing_url,
double phishing_score) {
DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
// There is something seriously wrong if there is no service class but
// this method is called. The renderer should not start phishing detection
// if there isn't any service class in the browser.
DCHECK(csd_service_);
if (csd_service_) {
// There shouldn't be any pending requests because we revoke them everytime
// we navigate away.
DCHECK(!cb_factory_.HasPendingCallbacks());
csd_service_->SendClientReportPhishingRequest(
phishing_url,
phishing_score,
cb_factory_.NewCallback(
&ClientSideDetectionHost::MaybeShowPhishingWarning));
}
}
void ClientSideDetectionHost::MaybeShowPhishingWarning(GURL phishing_url,
bool is_phishing) {
DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
if (is_phishing &&
CommandLine::ForCurrentProcess()->HasSwitch(
switches::kEnableClientSidePhishingInterstitial)) {
DCHECK(tab_contents());
// TODO(noelutz): this is not perfect. It's still possible that the
// user browses away before the interstitial is shown. Maybe we should
// stop all pending navigations?
if (sb_service_) {
// TODO(noelutz): refactor the SafeBrowsing service class and the
// SafeBrowsing blocking page class so that we don't need to depend
// on the SafeBrowsingService here and so that we don't need to go
// through the IO message loop.
std::vector<GURL> redirect_urls;
BrowserThread::PostTask(
BrowserThread::IO,
FROM_HERE,
NewRunnableMethod(sb_service_.get(),
&SafeBrowsingService::DisplayBlockingPage,
phishing_url, phishing_url,
redirect_urls,
// We only classify the main frame URL.
ResourceType::MAIN_FRAME,
// TODO(noelutz): create a separate threat type
// for client-side phishing detection.
SafeBrowsingService::URL_PHISHING,
new CsdClient() /* will delete itself */,
tab_contents()->GetRenderProcessHost()->id(),
tab_contents()->render_view_host()->routing_id()));
}
}
}
void ClientSideDetectionHost::set_client_side_detection_service(
ClientSideDetectionService* service) {
csd_service_ = service;
}
void ClientSideDetectionHost::set_safe_browsing_service(
SafeBrowsingService* service) {
sb_service_ = service;
}
} // namespace safe_browsing
<|endoftext|> |
<commit_before>// Copyright (c) 2011 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome/browser/ui/views/file_manager_dialog.h"
#include "base/file_util.h"
#include "base/logging.h"
#include "base/memory/scoped_ptr.h"
#include "base/path_service.h"
#include "base/scoped_temp_dir.h"
#include "base/threading/platform_thread.h"
#include "base/utf_string_conversions.h" // ASCIIToUTF16
#include "build/build_config.h"
#include "chrome/browser/extensions/extension_browsertest.h"
#include "chrome/browser/extensions/extension_test_message_listener.h"
#include "chrome/browser/profiles/profile.h"
#include "chrome/browser/ui/browser.h"
#include "chrome/browser/ui/browser_window.h"
#include "chrome/browser/ui/shell_dialogs.h" // SelectFileDialog
#include "chrome/common/chrome_paths.h"
#include "chrome/test/ui_test_utils.h"
#include "content/browser/renderer_host/render_view_host.h"
#include "content/common/content_notification_types.h"
#include "webkit/fileapi/file_system_context.h"
#include "webkit/fileapi/file_system_mount_point_provider.h"
#include "webkit/fileapi/file_system_path_manager.h"
// Mock listener used by test below.
class MockSelectFileDialogListener : public SelectFileDialog::Listener {
public:
MockSelectFileDialogListener()
: file_selected_(false),
canceled_(false),
params_(NULL) {
}
bool file_selected() const { return file_selected_; }
bool canceled() const { return canceled_; }
FilePath path() const { return path_; }
void* params() const { return params_; }
// SelectFileDialog::Listener implementation.
virtual void FileSelected(const FilePath& path, int index, void* params) {
file_selected_ = true;
path_ = path;
params_ = params;
}
virtual void MultiFilesSelected(
const std::vector<FilePath>& files, void* params) {}
virtual void FileSelectionCanceled(void* params) {
canceled_ = true;
params_ = params;
}
private:
bool file_selected_;
bool canceled_;
FilePath path_;
void* params_;
DISALLOW_COPY_AND_ASSIGN(MockSelectFileDialogListener);
};
class FileManagerDialogTest : public ExtensionBrowserTest {
public:
void SetUp() {
// Create the dialog wrapper object, but don't show it yet.
listener_.reset(new MockSelectFileDialogListener());
dialog_ = new FileManagerDialog(listener_.get());
// Must run after our setup because it actually runs the test.
ExtensionBrowserTest::SetUp();
}
void TearDown() {
ExtensionBrowserTest::TearDown();
// Release the dialog first, as it holds a pointer to the listener.
dialog_.release();
listener_.reset();
}
// Creates a file system mount point for a directory.
void AddMountPoint(const FilePath& path) {
fileapi::FileSystemPathManager* path_manager =
browser()->profile()->GetFileSystemContext()->path_manager();
fileapi::ExternalFileSystemMountPointProvider* provider =
path_manager->external_provider();
provider->AddMountPoint(path);
}
scoped_ptr<MockSelectFileDialogListener> listener_;
scoped_refptr<FileManagerDialog> dialog_;
};
IN_PROC_BROWSER_TEST_F(FileManagerDialogTest, FileManagerCreateAndDestroy) {
// Browser window must be up for us to test dialog window parent.
gfx::NativeWindow native_window = browser()->window()->GetNativeHandle();
ASSERT_TRUE(native_window != NULL);
// Before we call SelectFile, dialog is not running/visible.
ASSERT_FALSE(dialog_->IsRunning(native_window));
}
IN_PROC_BROWSER_TEST_F(FileManagerDialogTest, FileManagerDestroyListener) {
// Some users of SelectFileDialog destroy their listener before cleaning
// up the dialog. Make sure we don't crash.
dialog_->ListenerDestroyed();
listener_.reset();
}
// Flaky: http://crbug.com/89733
IN_PROC_BROWSER_TEST_F(FileManagerDialogTest, FLAKY_SelectFileAndCancel) {
// Add tmp mount point even though this test won't use it directly.
// We need this to make sure that at least one top-level directory exists
// in the file browser.
FilePath tmp_dir("/tmp");
AddMountPoint(tmp_dir);
// Spawn a dialog to open a file. The dialog will signal that it is done
// loading via chrome.test.sendMessage('ready') in the extension JavaScript.
ExtensionTestMessageListener msg_listener("ready", false /* will_reply */);
gfx::NativeWindow owning_window = browser()->window()->GetNativeHandle();
dialog_->SelectFile(SelectFileDialog::SELECT_OPEN_FILE,
string16() /* title */,
FilePath() /* default_path */,
NULL /* file_types */,
0 /* file_type_index */,
FILE_PATH_LITERAL("") /* default_extension */,
NULL /* source_contents */,
owning_window,
this /* params */);
LOG(INFO) << "Waiting for JavaScript ready message.";
ASSERT_TRUE(msg_listener.WaitUntilSatisfied());
// Dialog should be running now.
ASSERT_TRUE(dialog_->IsRunning(owning_window));
// Inject JavaScript to click the cancel button and wait for notification
// that the window has closed.
ui_test_utils::WindowedNotificationObserver host_destroyed(
content::NOTIFICATION_RENDER_WIDGET_HOST_DESTROYED,
NotificationService::AllSources());
RenderViewHost* host = dialog_->GetRenderViewHost();
string16 main_frame;
string16 script = ASCIIToUTF16(
"console.log(\'Test JavaScript injected.\');"
"document.querySelector(\'.cancel\').click();");
// The file selection handler closes the dialog and does not return control
// to JavaScript, so do not wait for return values.
host->ExecuteJavascriptInWebFrame(main_frame, script);
LOG(INFO) << "Waiting for window close notification.";
host_destroyed.Wait();
// Dialog no longer believes it is running.
ASSERT_FALSE(dialog_->IsRunning(owning_window));
// Listener should have been informed of the cancellation.
ASSERT_FALSE(listener_->file_selected());
ASSERT_TRUE(listener_->canceled());
ASSERT_EQ(this, listener_->params());
}
IN_PROC_BROWSER_TEST_F(FileManagerDialogTest, SelectFileAndOpen) {
// Allow the tmp directory to be mounted. We explicitly use /tmp because
// it it whitelisted for file system access on Chrome OS.
FilePath tmp_dir("/tmp");
AddMountPoint(tmp_dir);
// Create a directory with a single file in it. ScopedTempDir will delete
// itself and our temp file when it goes out of scope.
ScopedTempDir scoped_temp_dir;
ASSERT_TRUE(scoped_temp_dir.CreateUniqueTempDirUnderPath(tmp_dir));
FilePath temp_dir = scoped_temp_dir.path();
FilePath test_file = temp_dir.AppendASCII("file_manager_test.html");
// Create an empty file to give us something to select.
FILE* fp = file_util::OpenFile(test_file, "w");
ASSERT_TRUE(fp != NULL);
ASSERT_TRUE(file_util::CloseFile(fp));
// Spawn a dialog to open a file. Provide the path to the file so the dialog
// will automatically select it. Ensure that the OK button is enabled by
// waiting for chrome.test.sendMessage('selection-change-complete').
ExtensionTestMessageListener msg_listener("selection-change-complete",
false /* will_reply */);
gfx::NativeWindow owning_window = browser()->window()->GetNativeHandle();
dialog_->SelectFile(SelectFileDialog::SELECT_OPEN_FILE,
string16() /* title */,
test_file,
NULL /* file_types */,
0 /* file_type_index */,
FILE_PATH_LITERAL("") /* default_extension */,
NULL /* source_contents */,
owning_window,
this /* params */);
LOG(INFO) << "Waiting for JavaScript selection-change-complete message.";
ASSERT_TRUE(msg_listener.WaitUntilSatisfied());
// Dialog should be running now.
ASSERT_TRUE(dialog_->IsRunning(owning_window));
// Inject JavaScript to click the open button and wait for notification
// that the window has closed.
ui_test_utils::WindowedNotificationObserver host_destroyed(
content::NOTIFICATION_RENDER_WIDGET_HOST_DESTROYED,
NotificationService::AllSources());
RenderViewHost* host = dialog_->GetRenderViewHost();
string16 main_frame;
string16 script = ASCIIToUTF16(
"console.log(\'Test JavaScript injected.\');"
"document.querySelector('.ok').click();");
// The file selection handler closes the dialog and does not return control
// to JavaScript, so do not wait for return values.
host->ExecuteJavascriptInWebFrame(main_frame, script);
LOG(INFO) << "Waiting for window close notification.";
host_destroyed.Wait();
// Dialog no longer believes it is running.
ASSERT_FALSE(dialog_->IsRunning(owning_window));
// Listener should have been informed that the file was opened.
ASSERT_TRUE(listener_->file_selected());
ASSERT_FALSE(listener_->canceled());
ASSERT_EQ(test_file, listener_->path());
ASSERT_EQ(this, listener_->params());
}
IN_PROC_BROWSER_TEST_F(FileManagerDialogTest, SelectFileAndSave) {
// Allow the tmp directory to be mounted. We explicitly use /tmp because
// it it whitelisted for file system access on Chrome OS.
FilePath tmp_dir("/tmp");
AddMountPoint(tmp_dir);
// Create a directory with a single file in it. ScopedTempDir will delete
// itself and our temp file when it goes out of scope.
ScopedTempDir scoped_temp_dir;
ASSERT_TRUE(scoped_temp_dir.CreateUniqueTempDirUnderPath(tmp_dir));
FilePath temp_dir = scoped_temp_dir.path();
FilePath test_file = temp_dir.AppendASCII("file_manager_test.html");
// Spawn a dialog to save a file, providing a suggested path.
// Ensure "Save" button is enabled by waiting for notification from
// chrome.test.sendMessage().
ExtensionTestMessageListener msg_listener("directory-change-complete",
false /* will_reply */);
gfx::NativeWindow owning_window = browser()->window()->GetNativeHandle();
dialog_->SelectFile(SelectFileDialog::SELECT_SAVEAS_FILE,
string16() /* title */,
test_file,
NULL /* file_types */,
0 /* file_type_index */,
FILE_PATH_LITERAL("") /* default_extension */,
NULL /* source_contents */,
owning_window,
this /* params */);
LOG(INFO) << "Waiting for JavaScript message.";
ASSERT_TRUE(msg_listener.WaitUntilSatisfied());
// Dialog should be running now.
ASSERT_TRUE(dialog_->IsRunning(owning_window));
// Inject JavaScript to click the save button and wait for notification
// that the window has closed.
ui_test_utils::WindowedNotificationObserver host_destroyed(
content::NOTIFICATION_RENDER_WIDGET_HOST_DESTROYED,
NotificationService::AllSources());
RenderViewHost* host = dialog_->GetRenderViewHost();
string16 main_frame;
string16 script = ASCIIToUTF16(
"console.log(\'Test JavaScript injected.\');"
"document.querySelector('.ok').click();");
// The file selection handler closes the dialog and does not return control
// to JavaScript, so do not wait for return values.
host->ExecuteJavascriptInWebFrame(main_frame, script);
LOG(INFO) << "Waiting for window close notification.";
host_destroyed.Wait();
// Dialog no longer believes it is running.
ASSERT_FALSE(dialog_->IsRunning(owning_window));
// Listener should have been informed that the file was selected.
ASSERT_TRUE(listener_->file_selected());
ASSERT_FALSE(listener_->canceled());
ASSERT_EQ(test_file, listener_->path());
ASSERT_EQ(this, listener_->params());
}
<commit_msg>Mark SelectFileAndSave test as FLAKY.<commit_after>// Copyright (c) 2011 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome/browser/ui/views/file_manager_dialog.h"
#include "base/file_util.h"
#include "base/logging.h"
#include "base/memory/scoped_ptr.h"
#include "base/path_service.h"
#include "base/scoped_temp_dir.h"
#include "base/threading/platform_thread.h"
#include "base/utf_string_conversions.h" // ASCIIToUTF16
#include "build/build_config.h"
#include "chrome/browser/extensions/extension_browsertest.h"
#include "chrome/browser/extensions/extension_test_message_listener.h"
#include "chrome/browser/profiles/profile.h"
#include "chrome/browser/ui/browser.h"
#include "chrome/browser/ui/browser_window.h"
#include "chrome/browser/ui/shell_dialogs.h" // SelectFileDialog
#include "chrome/common/chrome_paths.h"
#include "chrome/test/ui_test_utils.h"
#include "content/browser/renderer_host/render_view_host.h"
#include "content/common/content_notification_types.h"
#include "webkit/fileapi/file_system_context.h"
#include "webkit/fileapi/file_system_mount_point_provider.h"
#include "webkit/fileapi/file_system_path_manager.h"
// Mock listener used by test below.
class MockSelectFileDialogListener : public SelectFileDialog::Listener {
public:
MockSelectFileDialogListener()
: file_selected_(false),
canceled_(false),
params_(NULL) {
}
bool file_selected() const { return file_selected_; }
bool canceled() const { return canceled_; }
FilePath path() const { return path_; }
void* params() const { return params_; }
// SelectFileDialog::Listener implementation.
virtual void FileSelected(const FilePath& path, int index, void* params) {
file_selected_ = true;
path_ = path;
params_ = params;
}
virtual void MultiFilesSelected(
const std::vector<FilePath>& files, void* params) {}
virtual void FileSelectionCanceled(void* params) {
canceled_ = true;
params_ = params;
}
private:
bool file_selected_;
bool canceled_;
FilePath path_;
void* params_;
DISALLOW_COPY_AND_ASSIGN(MockSelectFileDialogListener);
};
class FileManagerDialogTest : public ExtensionBrowserTest {
public:
void SetUp() {
// Create the dialog wrapper object, but don't show it yet.
listener_.reset(new MockSelectFileDialogListener());
dialog_ = new FileManagerDialog(listener_.get());
// Must run after our setup because it actually runs the test.
ExtensionBrowserTest::SetUp();
}
void TearDown() {
ExtensionBrowserTest::TearDown();
// Release the dialog first, as it holds a pointer to the listener.
dialog_.release();
listener_.reset();
}
// Creates a file system mount point for a directory.
void AddMountPoint(const FilePath& path) {
fileapi::FileSystemPathManager* path_manager =
browser()->profile()->GetFileSystemContext()->path_manager();
fileapi::ExternalFileSystemMountPointProvider* provider =
path_manager->external_provider();
provider->AddMountPoint(path);
}
scoped_ptr<MockSelectFileDialogListener> listener_;
scoped_refptr<FileManagerDialog> dialog_;
};
IN_PROC_BROWSER_TEST_F(FileManagerDialogTest, FileManagerCreateAndDestroy) {
// Browser window must be up for us to test dialog window parent.
gfx::NativeWindow native_window = browser()->window()->GetNativeHandle();
ASSERT_TRUE(native_window != NULL);
// Before we call SelectFile, dialog is not running/visible.
ASSERT_FALSE(dialog_->IsRunning(native_window));
}
IN_PROC_BROWSER_TEST_F(FileManagerDialogTest, FileManagerDestroyListener) {
// Some users of SelectFileDialog destroy their listener before cleaning
// up the dialog. Make sure we don't crash.
dialog_->ListenerDestroyed();
listener_.reset();
}
// Flaky: http://crbug.com/89733
IN_PROC_BROWSER_TEST_F(FileManagerDialogTest, FLAKY_SelectFileAndCancel) {
// Add tmp mount point even though this test won't use it directly.
// We need this to make sure that at least one top-level directory exists
// in the file browser.
FilePath tmp_dir("/tmp");
AddMountPoint(tmp_dir);
// Spawn a dialog to open a file. The dialog will signal that it is done
// loading via chrome.test.sendMessage('ready') in the extension JavaScript.
ExtensionTestMessageListener msg_listener("ready", false /* will_reply */);
gfx::NativeWindow owning_window = browser()->window()->GetNativeHandle();
dialog_->SelectFile(SelectFileDialog::SELECT_OPEN_FILE,
string16() /* title */,
FilePath() /* default_path */,
NULL /* file_types */,
0 /* file_type_index */,
FILE_PATH_LITERAL("") /* default_extension */,
NULL /* source_contents */,
owning_window,
this /* params */);
LOG(INFO) << "Waiting for JavaScript ready message.";
ASSERT_TRUE(msg_listener.WaitUntilSatisfied());
// Dialog should be running now.
ASSERT_TRUE(dialog_->IsRunning(owning_window));
// Inject JavaScript to click the cancel button and wait for notification
// that the window has closed.
ui_test_utils::WindowedNotificationObserver host_destroyed(
content::NOTIFICATION_RENDER_WIDGET_HOST_DESTROYED,
NotificationService::AllSources());
RenderViewHost* host = dialog_->GetRenderViewHost();
string16 main_frame;
string16 script = ASCIIToUTF16(
"console.log(\'Test JavaScript injected.\');"
"document.querySelector(\'.cancel\').click();");
// The file selection handler closes the dialog and does not return control
// to JavaScript, so do not wait for return values.
host->ExecuteJavascriptInWebFrame(main_frame, script);
LOG(INFO) << "Waiting for window close notification.";
host_destroyed.Wait();
// Dialog no longer believes it is running.
ASSERT_FALSE(dialog_->IsRunning(owning_window));
// Listener should have been informed of the cancellation.
ASSERT_FALSE(listener_->file_selected());
ASSERT_TRUE(listener_->canceled());
ASSERT_EQ(this, listener_->params());
}
IN_PROC_BROWSER_TEST_F(FileManagerDialogTest, SelectFileAndOpen) {
// Allow the tmp directory to be mounted. We explicitly use /tmp because
// it it whitelisted for file system access on Chrome OS.
FilePath tmp_dir("/tmp");
AddMountPoint(tmp_dir);
// Create a directory with a single file in it. ScopedTempDir will delete
// itself and our temp file when it goes out of scope.
ScopedTempDir scoped_temp_dir;
ASSERT_TRUE(scoped_temp_dir.CreateUniqueTempDirUnderPath(tmp_dir));
FilePath temp_dir = scoped_temp_dir.path();
FilePath test_file = temp_dir.AppendASCII("file_manager_test.html");
// Create an empty file to give us something to select.
FILE* fp = file_util::OpenFile(test_file, "w");
ASSERT_TRUE(fp != NULL);
ASSERT_TRUE(file_util::CloseFile(fp));
// Spawn a dialog to open a file. Provide the path to the file so the dialog
// will automatically select it. Ensure that the OK button is enabled by
// waiting for chrome.test.sendMessage('selection-change-complete').
ExtensionTestMessageListener msg_listener("selection-change-complete",
false /* will_reply */);
gfx::NativeWindow owning_window = browser()->window()->GetNativeHandle();
dialog_->SelectFile(SelectFileDialog::SELECT_OPEN_FILE,
string16() /* title */,
test_file,
NULL /* file_types */,
0 /* file_type_index */,
FILE_PATH_LITERAL("") /* default_extension */,
NULL /* source_contents */,
owning_window,
this /* params */);
LOG(INFO) << "Waiting for JavaScript selection-change-complete message.";
ASSERT_TRUE(msg_listener.WaitUntilSatisfied());
// Dialog should be running now.
ASSERT_TRUE(dialog_->IsRunning(owning_window));
// Inject JavaScript to click the open button and wait for notification
// that the window has closed.
ui_test_utils::WindowedNotificationObserver host_destroyed(
content::NOTIFICATION_RENDER_WIDGET_HOST_DESTROYED,
NotificationService::AllSources());
RenderViewHost* host = dialog_->GetRenderViewHost();
string16 main_frame;
string16 script = ASCIIToUTF16(
"console.log(\'Test JavaScript injected.\');"
"document.querySelector('.ok').click();");
// The file selection handler closes the dialog and does not return control
// to JavaScript, so do not wait for return values.
host->ExecuteJavascriptInWebFrame(main_frame, script);
LOG(INFO) << "Waiting for window close notification.";
host_destroyed.Wait();
// Dialog no longer believes it is running.
ASSERT_FALSE(dialog_->IsRunning(owning_window));
// Listener should have been informed that the file was opened.
ASSERT_TRUE(listener_->file_selected());
ASSERT_FALSE(listener_->canceled());
ASSERT_EQ(test_file, listener_->path());
ASSERT_EQ(this, listener_->params());
}
// Flaky: http://crbug.com/89733
IN_PROC_BROWSER_TEST_F(FileManagerDialogTest, FLAKY_SelectFileAndSave) {
// Allow the tmp directory to be mounted. We explicitly use /tmp because
// it it whitelisted for file system access on Chrome OS.
FilePath tmp_dir("/tmp");
AddMountPoint(tmp_dir);
// Create a directory with a single file in it. ScopedTempDir will delete
// itself and our temp file when it goes out of scope.
ScopedTempDir scoped_temp_dir;
ASSERT_TRUE(scoped_temp_dir.CreateUniqueTempDirUnderPath(tmp_dir));
FilePath temp_dir = scoped_temp_dir.path();
FilePath test_file = temp_dir.AppendASCII("file_manager_test.html");
// Spawn a dialog to save a file, providing a suggested path.
// Ensure "Save" button is enabled by waiting for notification from
// chrome.test.sendMessage().
ExtensionTestMessageListener msg_listener("directory-change-complete",
false /* will_reply */);
gfx::NativeWindow owning_window = browser()->window()->GetNativeHandle();
dialog_->SelectFile(SelectFileDialog::SELECT_SAVEAS_FILE,
string16() /* title */,
test_file,
NULL /* file_types */,
0 /* file_type_index */,
FILE_PATH_LITERAL("") /* default_extension */,
NULL /* source_contents */,
owning_window,
this /* params */);
LOG(INFO) << "Waiting for JavaScript message.";
ASSERT_TRUE(msg_listener.WaitUntilSatisfied());
// Dialog should be running now.
ASSERT_TRUE(dialog_->IsRunning(owning_window));
// Inject JavaScript to click the save button and wait for notification
// that the window has closed.
ui_test_utils::WindowedNotificationObserver host_destroyed(
content::NOTIFICATION_RENDER_WIDGET_HOST_DESTROYED,
NotificationService::AllSources());
RenderViewHost* host = dialog_->GetRenderViewHost();
string16 main_frame;
string16 script = ASCIIToUTF16(
"console.log(\'Test JavaScript injected.\');"
"document.querySelector('.ok').click();");
// The file selection handler closes the dialog and does not return control
// to JavaScript, so do not wait for return values.
host->ExecuteJavascriptInWebFrame(main_frame, script);
LOG(INFO) << "Waiting for window close notification.";
host_destroyed.Wait();
// Dialog no longer believes it is running.
ASSERT_FALSE(dialog_->IsRunning(owning_window));
// Listener should have been informed that the file was selected.
ASSERT_TRUE(listener_->file_selected());
ASSERT_FALSE(listener_->canceled());
ASSERT_EQ(test_file, listener_->path());
ASSERT_EQ(this, listener_->params());
}
<|endoftext|> |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.