commit
stringlengths
40
40
old_file
stringlengths
2
205
new_file
stringlengths
2
205
old_contents
stringlengths
0
32.9k
new_contents
stringlengths
1
38.9k
subject
stringlengths
3
9.4k
message
stringlengths
6
9.84k
lang
stringlengths
3
13
license
stringclasses
13 values
repos
stringlengths
6
115k
f82d95f413de86871cb7a6dc7f1321df49814a71
tests/auto/qml/qmleditor/lookup/tst_lookup.cpp
tests/auto/qml/qmleditor/lookup/tst_lookup.cpp
#include <QDebug> #include <QtTest> #include <QObject> #include <QFile> #include <qml/qmldocument.h> #include <qml/parser/qmljsast_p.h> #include <qmllookupcontext.h> using namespace Qml; using namespace QmlEditor; using namespace QmlEditor::Internal; using namespace QmlJS; using namespace QmlJS::AST; class tst_Lookup: public QObject { Q_OBJECT public: tst_Lookup(): _typeSystem(0) {} ~tst_Lookup() { if (_typeSystem) resetTypeSystem(); } void resetTypeSystem() { if (_typeSystem) { delete _typeSystem; _typeSystem = 0; }} private Q_SLOTS: void basicSymbolTest(); void basicLookupTest(); void localIdLookup(); void localScriptMethodLookup(); void localScopeLookup(); void localRootLookup(); protected: QmlDocument::Ptr basicSymbolTest(const QString &input) const { const QLatin1String filename("<lookup test>"); QmlDocument::Ptr doc = QmlDocument::create(filename); doc->setSource(input); doc->parse(); QList<DiagnosticMessage> msgs = doc->diagnosticMessages(); foreach (const DiagnosticMessage &msg, msgs) { if (msg.isError()) { qDebug() << "Error:" << filename << ":" << msg.loc.startLine << ":" << msg.loc.startColumn << ":" << msg.message; } else if (msg.isWarning()) { qDebug() << "Warning:" << filename << ":" << msg.loc.startLine << ":" << msg.loc.startColumn << ":" << msg.message; } else { qDebug() << "Diagnostic:" << filename << ":" << msg.loc.startLine << ":" << msg.loc.startColumn << ":" << msg.message; } } return doc; } Snapshot snapshot(const QmlDocument::Ptr &doc) const { Snapshot snapshot; snapshot.insert(doc); return snapshot; } QmlTypeSystem *typeSystem() { if (!_typeSystem) _typeSystem = new QmlTypeSystem; return _typeSystem; } private: QmlTypeSystem *_typeSystem; }; void tst_Lookup::basicSymbolTest() { const QLatin1String input( "import Qt 4.6\n" "\n" "Rectangle {\n" " x: 10\n" " y: 10\n" " width: 10\n" " height: 10\n" "}\n" ); QmlDocument::Ptr doc = basicSymbolTest(input); QVERIFY(doc->isParsedCorrectly()); UiProgram *program = doc->program(); QVERIFY(program); QVERIFY(program->members); QVERIFY(program->members->member); UiObjectDefinition *rectDef = cast<UiObjectDefinition*>(program->members->member); QVERIFY(rectDef); QVERIFY(rectDef->qualifiedTypeNameId->name); QCOMPARE(rectDef->qualifiedTypeNameId->name->asString(), QLatin1String("Rectangle")); QVERIFY(rectDef->initializer); UiObjectMemberList *rectMembers = rectDef->initializer->members; QVERIFY(rectMembers); QVERIFY(rectMembers->member); UiScriptBinding *xBinding = cast<UiScriptBinding*>(rectMembers->member); QVERIFY(xBinding); QVERIFY(xBinding->qualifiedId); QVERIFY(xBinding->qualifiedId->name); QCOMPARE(xBinding->qualifiedId->name->asString(), QLatin1String("x")); QmlSymbol::List docSymbols = doc->symbols(); QCOMPARE(docSymbols.size(), 1); QmlSymbol *rectSymbol = docSymbols.at(0); QCOMPARE(rectSymbol->name(), QLatin1String("Rectangle")); QCOMPARE(rectSymbol->members().size(), 4); QmlSymbolFromFile *rectFromFile = rectSymbol->asSymbolFromFile(); QVERIFY(rectFromFile); QmlSymbolFromFile *xSymbol = rectFromFile->findMember(xBinding); QVERIFY(xSymbol); QCOMPARE(xSymbol->name(), QLatin1String("x")); } void tst_Lookup::basicLookupTest() { const QLatin1String input( "import Qt 4.6\n" "Item{}\n" ); QmlDocument::Ptr doc = basicSymbolTest(input); QVERIFY(doc->isParsedCorrectly()); UiProgram *program = doc->program(); QVERIFY(program); QStack<QmlSymbol *> emptyScope; QmlLookupContext context(emptyScope, doc, snapshot(doc), typeSystem()); QmlSymbol *rectSymbol = context.resolveType(QLatin1String("Text")); QVERIFY(rectSymbol); QmlBuildInSymbol *buildInRect = rectSymbol->asBuildInSymbol(); QVERIFY(buildInRect); QCOMPARE(buildInRect->name(), QLatin1String("Text")); QmlSymbol::List allBuildInRectMembers = buildInRect->members(true); QVERIFY(!allBuildInRectMembers.isEmpty()); bool xPropFound = false; bool fontPropFound = false; foreach (QmlSymbol *symbol, allBuildInRectMembers) { if (symbol->name() == QLatin1String("x")) xPropFound = true; else if (symbol->name() == QLatin1String("font")) fontPropFound = true; } QVERIFY(xPropFound); QVERIFY(fontPropFound); QmlSymbol::List buildInRectMembers = buildInRect->members(false); QVERIFY(!buildInRectMembers.isEmpty()); QSKIP("Getting properties _without_ the inerited properties doesn't work.", SkipSingle); fontPropFound = false; foreach (QmlSymbol *symbol, buildInRectMembers) { if (symbol->name() == QLatin1String("x")) QFAIL("Text has x property"); else if (symbol->name() == QLatin1String("font")) fontPropFound = true; } QVERIFY(fontPropFound); } void tst_Lookup::localIdLookup() { QFile input(":/data/localIdLookup.qml"); QVERIFY(input.open(QIODevice::ReadOnly)); QmlDocument::Ptr doc = basicSymbolTest(input.readAll()); QVERIFY(doc->isParsedCorrectly()); QStringList symbolNames; symbolNames.append("x"); symbolNames.append("y"); symbolNames.append("z"); symbolNames.append("opacity"); symbolNames.append("visible"); // check symbol existence foreach (const QString &symbolName, symbolNames) { QVERIFY(doc->ids()[symbolName]); } // try lookup QStack<QmlSymbol *> scopes; foreach (const QString &contextSymbolName, symbolNames) { scopes.push_back(doc->ids()[contextSymbolName]); QmlLookupContext context(scopes, doc, snapshot(doc), typeSystem()); foreach (const QString &lookupSymbolName, symbolNames) { QCOMPARE(context.resolve(lookupSymbolName), doc->ids()[lookupSymbolName]); } } } void tst_Lookup::localScriptMethodLookup() { QFile input(":/data/localScriptMethodLookup.qml"); QVERIFY(input.open(QIODevice::ReadOnly)); QmlDocument::Ptr doc = basicSymbolTest(input.readAll()); QVERIFY(doc->isParsedCorrectly()); QStringList symbolNames; symbolNames.append("theRoot"); symbolNames.append("theParent"); symbolNames.append("theChild"); QStringList functionNames; functionNames.append("x"); functionNames.append("y"); functionNames.append("z"); // check symbol existence foreach (const QString &symbolName, symbolNames) { QVERIFY(doc->ids()[symbolName]); } // try lookup QStack<QmlSymbol *> scopes; foreach (const QString &contextSymbolName, symbolNames) { scopes.push_back(doc->ids()[contextSymbolName]); QmlLookupContext context(scopes, doc, snapshot(doc), typeSystem()); foreach (const QString &functionName, functionNames) { QmlSymbol *symbol = context.resolve(functionName); QVERIFY(symbol); QVERIFY(!symbol->isProperty()); // verify that it's a function } } } void tst_Lookup::localScopeLookup() { QFile input(":/data/localScopeLookup.qml"); QVERIFY(input.open(QIODevice::ReadOnly)); QmlDocument::Ptr doc = basicSymbolTest(input.readAll()); QVERIFY(doc->isParsedCorrectly()); QStringList symbolNames; symbolNames.append("theRoot"); symbolNames.append("theParent"); symbolNames.append("theChild"); // check symbol existence foreach (const QString &symbolName, symbolNames) { QVERIFY(doc->ids()[symbolName]); } // try lookup QStack<QmlSymbol *> scopes; foreach (const QString &contextSymbolName, symbolNames) { scopes.push_back(doc->ids()[contextSymbolName]); QmlLookupContext context(scopes, doc, snapshot(doc), typeSystem()); QmlSymbol *symbol; symbol = context.resolve("prop"); QVERIFY(symbol); QVERIFY(symbol->isPropertyDefinitionSymbol()); QVERIFY(doc->ids()[contextSymbolName]->members().contains(symbol)); symbol = context.resolve("x"); QVERIFY(symbol); QVERIFY(symbol->isProperty()); QVERIFY(doc->ids()[contextSymbolName]->members().contains(symbol)); } } void tst_Lookup::localRootLookup() { QFile input(":/data/localRootLookup.qml"); QVERIFY(input.open(QIODevice::ReadOnly)); QmlDocument::Ptr doc = basicSymbolTest(input.readAll()); QVERIFY(doc->isParsedCorrectly()); QStringList symbolNames; symbolNames.append("theRoot"); symbolNames.append("theParent"); symbolNames.append("theChild"); // check symbol existence and build scopes QStack<QmlSymbol *> scopes; foreach (const QString &symbolName, symbolNames) { QmlSymbol *symbol = doc->ids()[symbolName]; QVERIFY(symbol); scopes.push_back(symbol); } // try lookup QmlLookupContext context(scopes, doc, snapshot(doc), typeSystem()); QmlSymbol *symbol; symbol = context.resolve("prop"); QVERIFY(symbol); QVERIFY(symbol->isPropertyDefinitionSymbol()); QVERIFY(doc->ids()[symbolNames[0]]->members().contains(symbol)); symbol = context.resolve("color"); QVERIFY(symbol); QVERIFY(symbol->isProperty()); QVERIFY(doc->ids()[symbolNames[0]]->members().contains(symbol)); } QTEST_APPLESS_MAIN(tst_Lookup) #include "tst_lookup.moc"
#include <QDebug> #include <QtTest> #include <QObject> #include <QFile> #include <qml/qmldocument.h> #include <qml/parser/qmljsast_p.h> #include <qmllookupcontext.h> #include <typeinfo> using namespace Qml; using namespace QmlEditor; using namespace QmlEditor::Internal; using namespace QmlJS; using namespace QmlJS::AST; class tst_Lookup: public QObject { Q_OBJECT public: tst_Lookup(): _typeSystem(0) {} ~tst_Lookup() { if (_typeSystem) resetTypeSystem(); } void resetTypeSystem() { if (_typeSystem) { delete _typeSystem; _typeSystem = 0; }} private Q_SLOTS: void basicSymbolTest(); void basicLookupTest(); void localIdLookup(); void localScriptMethodLookup(); void localScopeLookup(); void localRootLookup(); protected: QmlDocument::Ptr basicSymbolTest(const QString &input) const { const QLatin1String filename("<lookup test>"); QmlDocument::Ptr doc = QmlDocument::create(filename); doc->setSource(input); doc->parse(); QList<DiagnosticMessage> msgs = doc->diagnosticMessages(); foreach (const DiagnosticMessage &msg, msgs) { if (msg.isError()) { qDebug() << "Error:" << filename << ":" << msg.loc.startLine << ":" << msg.loc.startColumn << ":" << msg.message; } else if (msg.isWarning()) { qDebug() << "Warning:" << filename << ":" << msg.loc.startLine << ":" << msg.loc.startColumn << ":" << msg.message; } else { qDebug() << "Diagnostic:" << filename << ":" << msg.loc.startLine << ":" << msg.loc.startColumn << ":" << msg.message; } } return doc; } Snapshot snapshot(const QmlDocument::Ptr &doc) const { Snapshot snapshot; snapshot.insert(doc); return snapshot; } QmlTypeSystem *typeSystem() { if (!_typeSystem) _typeSystem = new QmlTypeSystem; return _typeSystem; } private: QmlTypeSystem *_typeSystem; }; void tst_Lookup::basicSymbolTest() { const QLatin1String input( "import Qt 4.6\n" "\n" "Rectangle {\n" " x: 10\n" " y: 10\n" " width: 10\n" " height: 10\n" "}\n" ); QmlDocument::Ptr doc = basicSymbolTest(input); QVERIFY(doc->isParsedCorrectly()); UiProgram *program = doc->program(); QVERIFY(program); QVERIFY(program->members); QVERIFY(program->members->member); UiObjectDefinition *rectDef = cast<UiObjectDefinition*>(program->members->member); QVERIFY(rectDef); QVERIFY(rectDef->qualifiedTypeNameId->name); QCOMPARE(rectDef->qualifiedTypeNameId->name->asString(), QLatin1String("Rectangle")); QVERIFY(rectDef->initializer); UiObjectMemberList *rectMembers = rectDef->initializer->members; QVERIFY(rectMembers); QVERIFY(rectMembers->member); UiScriptBinding *xBinding = cast<UiScriptBinding*>(rectMembers->member); QVERIFY(xBinding); QVERIFY(xBinding->qualifiedId); QVERIFY(xBinding->qualifiedId->name); QCOMPARE(xBinding->qualifiedId->name->asString(), QLatin1String("x")); QmlSymbol::List docSymbols = doc->symbols(); QCOMPARE(docSymbols.size(), 1); QmlSymbol *rectSymbol = docSymbols.at(0); QCOMPARE(rectSymbol->name(), QLatin1String("Rectangle")); QCOMPARE(rectSymbol->members().size(), 4); QmlSymbolFromFile *rectFromFile = rectSymbol->asSymbolFromFile(); QVERIFY(rectFromFile); QmlSymbolFromFile *xSymbol = rectFromFile->findMember(xBinding); QVERIFY(xSymbol); QCOMPARE(xSymbol->name(), QLatin1String("x")); } void tst_Lookup::basicLookupTest() { const QLatin1String input( "import Qt 4.6\n" "Item{}\n" ); QmlDocument::Ptr doc = basicSymbolTest(input); QVERIFY(doc->isParsedCorrectly()); UiProgram *program = doc->program(); QVERIFY(program); QStack<QmlSymbol *> emptyScope; QmlLookupContext context(emptyScope, doc, snapshot(doc), typeSystem()); QmlSymbol *rectSymbol = context.resolveType(QLatin1String("Text")); QVERIFY(rectSymbol); QmlBuildInSymbol *buildInRect = rectSymbol->asBuildInSymbol(); QVERIFY(buildInRect); QCOMPARE(buildInRect->name(), QLatin1String("Text")); QmlSymbol::List allBuildInRectMembers = buildInRect->members(true); QVERIFY(!allBuildInRectMembers.isEmpty()); bool xPropFound = false; bool fontPropFound = false; foreach (QmlSymbol *symbol, allBuildInRectMembers) { if (symbol->name() == QLatin1String("x")) xPropFound = true; else if (symbol->name() == QLatin1String("font")) fontPropFound = true; } QVERIFY(xPropFound); QVERIFY(fontPropFound); QmlSymbol::List buildInRectMembers = buildInRect->members(false); QVERIFY(!buildInRectMembers.isEmpty()); QSKIP("Getting properties _without_ the inerited properties doesn't work.", SkipSingle); fontPropFound = false; foreach (QmlSymbol *symbol, buildInRectMembers) { if (symbol->name() == QLatin1String("x")) QFAIL("Text has x property"); else if (symbol->name() == QLatin1String("font")) fontPropFound = true; } QVERIFY(fontPropFound); } void tst_Lookup::localIdLookup() { QFile input(":/data/localIdLookup.qml"); QVERIFY(input.open(QIODevice::ReadOnly)); QmlDocument::Ptr doc = basicSymbolTest(input.readAll()); QVERIFY(doc->isParsedCorrectly()); QStringList symbolNames; symbolNames.append("x"); symbolNames.append("y"); symbolNames.append("z"); symbolNames.append("opacity"); symbolNames.append("visible"); // check symbol existence foreach (const QString &symbolName, symbolNames) { QVERIFY(doc->ids()[symbolName]); } // try lookup QStack<QmlSymbol *> scopes; foreach (const QString &contextSymbolName, symbolNames) { scopes.push_back(doc->ids()[contextSymbolName]->parentNode()); QmlLookupContext context(scopes, doc, snapshot(doc), typeSystem()); foreach (const QString &lookupSymbolName, symbolNames) { QmlSymbol *resolvedSymbol = context.resolve(lookupSymbolName); QmlIdSymbol *targetSymbol = doc->ids()[lookupSymbolName]; QCOMPARE(resolvedSymbol, targetSymbol); QmlIdSymbol *resolvedId = resolvedSymbol->asIdSymbol(); QVERIFY(resolvedId); QCOMPARE(resolvedId->parentNode(), targetSymbol->parentNode()); } } } void tst_Lookup::localScriptMethodLookup() { QFile input(":/data/localScriptMethodLookup.qml"); QVERIFY(input.open(QIODevice::ReadOnly)); QmlDocument::Ptr doc = basicSymbolTest(input.readAll()); QVERIFY(doc->isParsedCorrectly()); QStringList symbolNames; symbolNames.append("theRoot"); symbolNames.append("theParent"); symbolNames.append("theChild"); QStringList functionNames; functionNames.append("x"); functionNames.append("y"); functionNames.append("z"); // check symbol existence foreach (const QString &symbolName, symbolNames) { QVERIFY(doc->ids()[symbolName]); } // try lookup QStack<QmlSymbol *> scopes; foreach (const QString &contextSymbolName, symbolNames) { scopes.push_back(doc->ids()[contextSymbolName]->parentNode()); QmlLookupContext context(scopes, doc, snapshot(doc), typeSystem()); foreach (const QString &functionName, functionNames) { QmlSymbol *symbol = context.resolve(functionName); QVERIFY(symbol); QVERIFY(!symbol->isProperty()); // verify that it's a function } } } void tst_Lookup::localScopeLookup() { QFile input(":/data/localScopeLookup.qml"); QVERIFY(input.open(QIODevice::ReadOnly)); QmlDocument::Ptr doc = basicSymbolTest(input.readAll()); QVERIFY(doc->isParsedCorrectly()); QStringList symbolNames; symbolNames.append("theRoot"); symbolNames.append("theParent"); symbolNames.append("theChild"); // check symbol existence foreach (const QString &symbolName, symbolNames) { QVERIFY(doc->ids()[symbolName]); } // try lookup QStack<QmlSymbol *> scopes; foreach (const QString &contextSymbolName, symbolNames) { QmlSymbol *parent = doc->ids()[contextSymbolName]->parentNode(); scopes.push_back(parent); QmlLookupContext context(scopes, doc, snapshot(doc), typeSystem()); QmlSymbol *symbol; symbol = context.resolve("prop"); QVERIFY(symbol); QVERIFY(symbol->isPropertyDefinitionSymbol()); QVERIFY(parent->members().contains(symbol)); symbol = context.resolve("x"); QVERIFY(symbol); QVERIFY(symbol->isProperty()); QVERIFY(parent->members().contains(symbol)); } } void tst_Lookup::localRootLookup() { QFile input(":/data/localRootLookup.qml"); QVERIFY(input.open(QIODevice::ReadOnly)); QmlDocument::Ptr doc = basicSymbolTest(input.readAll()); QVERIFY(doc->isParsedCorrectly()); QStringList symbolNames; symbolNames.append("theRoot"); symbolNames.append("theParent"); symbolNames.append("theChild"); // check symbol existence and build scopes QStack<QmlSymbol *> scopes; foreach (const QString &symbolName, symbolNames) { QmlIdSymbol *id = doc->ids()[symbolName]; QVERIFY(id); scopes.push_back(id->parentNode()); } // try lookup QmlSymbol *parent = scopes.top(); QmlLookupContext context(scopes, doc, snapshot(doc), typeSystem()); QmlSymbol *symbol; symbol = context.resolve("prop"); QVERIFY(symbol); QVERIFY(symbol->isPropertyDefinitionSymbol()); QVERIFY(parent->members().contains(symbol)); symbol = context.resolve("color"); QVERIFY(symbol); QVERIFY(symbol->isProperty()); QVERIFY(parent->members().contains(symbol)); } QTEST_APPLESS_MAIN(tst_Lookup) #include "tst_lookup.moc"
Build correct scopes for the lookup test.
Build correct scopes for the lookup test.
C++
lgpl-2.1
syntheticpp/qt-creator,pcacjr/qt-creator,renatofilho/QtCreator,martyone/sailfish-qtcreator,enricoros/k-qt-creator-inspector,AltarBeastiful/qt-creator,dmik/qt-creator-os2,sandsmark/qtcreator-minimap,yinyunqiao/qtcreator,AltarBeastiful/qt-creator,yinyunqiao/qtcreator,amyvmiwei/qt-creator,danimo/qt-creator,dmik/qt-creator-os2,maui-packages/qt-creator,dmik/qt-creator-os2,yinyunqiao/qtcreator,pcacjr/qt-creator,hdweiss/qt-creator-visualizer,duythanhphan/qt-creator,richardmg/qtcreator,kuba1/qtcreator,bakaiadam/collaborative_qt_creator,xianian/qt-creator,danimo/qt-creator,bakaiadam/collaborative_qt_creator,yinyunqiao/qtcreator,richardmg/qtcreator,darksylinc/qt-creator,sandsmark/qtcreator-minimap,KDAB/KDAB-Creator,duythanhphan/qt-creator,maui-packages/qt-creator,dmik/qt-creator-os2,xianian/qt-creator,kuba1/qtcreator,richardmg/qtcreator,kuba1/qtcreator,pcacjr/qt-creator,omniacreator/qtcreator,Distrotech/qtcreator,farseerri/git_code,farseerri/git_code,azat/qtcreator,Distrotech/qtcreator,kuba1/qtcreator,richardmg/qtcreator,pcacjr/qt-creator,xianian/qt-creator,kuba1/qtcreator,jonnor/qt-creator,KDE/android-qt-creator,dmik/qt-creator-os2,enricoros/k-qt-creator-inspector,AltarBeastiful/qt-creator,xianian/qt-creator,renatofilho/QtCreator,azat/qtcreator,omniacreator/qtcreator,jonnor/qt-creator,renatofilho/QtCreator,azat/qtcreator,AltarBeastiful/qt-creator,syntheticpp/qt-creator,yinyunqiao/qtcreator,martyone/sailfish-qtcreator,colede/qtcreator,bakaiadam/collaborative_qt_creator,amyvmiwei/qt-creator,danimo/qt-creator,danimo/qt-creator,syntheticpp/qt-creator,darksylinc/qt-creator,Distrotech/qtcreator,farseerri/git_code,malikcjm/qtcreator,danimo/qt-creator,darksylinc/qt-creator,pcacjr/qt-creator,maui-packages/qt-creator,xianian/qt-creator,omniacreator/qtcreator,sandsmark/qtcreator-minimap,sandsmark/qtcreator-minimap,farseerri/git_code,malikcjm/qtcreator,richardmg/qtcreator,ostash/qt-creator-i18n-uk,AltarBeastiful/qt-creator,maui-packages/qt-creator,martyone/sailfish-qtcreator,yinyunqiao/qtcreator,AltarBeastiful/qt-creator,darksylinc/qt-creator,malikcjm/qtcreator,azat/qtcreator,KDE/android-qt-creator,omniacreator/qtcreator,syntheticpp/qt-creator,AltarBeastiful/qt-creator,pcacjr/qt-creator,omniacreator/qtcreator,richardmg/qtcreator,amyvmiwei/qt-creator,Distrotech/qtcreator,martyone/sailfish-qtcreator,azat/qtcreator,duythanhphan/qt-creator,darksylinc/qt-creator,pcacjr/qt-creator,omniacreator/qtcreator,kuba1/qtcreator,syntheticpp/qt-creator,duythanhphan/qt-creator,bakaiadam/collaborative_qt_creator,ostash/qt-creator-i18n-uk,jonnor/qt-creator,martyone/sailfish-qtcreator,hdweiss/qt-creator-visualizer,amyvmiwei/qt-creator,Distrotech/qtcreator,xianian/qt-creator,hdweiss/qt-creator-visualizer,renatofilho/QtCreator,colede/qtcreator,KDAB/KDAB-Creator,duythanhphan/qt-creator,enricoros/k-qt-creator-inspector,dmik/qt-creator-os2,colede/qtcreator,colede/qtcreator,hdweiss/qt-creator-visualizer,KDAB/KDAB-Creator,bakaiadam/collaborative_qt_creator,duythanhphan/qt-creator,kuba1/qtcreator,amyvmiwei/qt-creator,KDAB/KDAB-Creator,martyone/sailfish-qtcreator,malikcjm/qtcreator,danimo/qt-creator,KDAB/KDAB-Creator,darksylinc/qt-creator,hdweiss/qt-creator-visualizer,hdweiss/qt-creator-visualizer,xianian/qt-creator,ostash/qt-creator-i18n-uk,xianian/qt-creator,darksylinc/qt-creator,danimo/qt-creator,jonnor/qt-creator,KDE/android-qt-creator,richardmg/qtcreator,farseerri/git_code,syntheticpp/qt-creator,malikcjm/qtcreator,renatofilho/QtCreator,enricoros/k-qt-creator-inspector,farseerri/git_code,enricoros/k-qt-creator-inspector,malikcjm/qtcreator,syntheticpp/qt-creator,maui-packages/qt-creator,kuba1/qtcreator,renatofilho/QtCreator,danimo/qt-creator,ostash/qt-creator-i18n-uk,farseerri/git_code,maui-packages/qt-creator,jonnor/qt-creator,martyone/sailfish-qtcreator,KDAB/KDAB-Creator,danimo/qt-creator,sandsmark/qtcreator-minimap,sandsmark/qtcreator-minimap,bakaiadam/collaborative_qt_creator,KDE/android-qt-creator,KDE/android-qt-creator,KDE/android-qt-creator,colede/qtcreator,bakaiadam/collaborative_qt_creator,ostash/qt-creator-i18n-uk,colede/qtcreator,maui-packages/qt-creator,azat/qtcreator,farseerri/git_code,KDE/android-qt-creator,martyone/sailfish-qtcreator,ostash/qt-creator-i18n-uk,yinyunqiao/qtcreator,colede/qtcreator,darksylinc/qt-creator,duythanhphan/qt-creator,ostash/qt-creator-i18n-uk,amyvmiwei/qt-creator,Distrotech/qtcreator,xianian/qt-creator,enricoros/k-qt-creator-inspector,enricoros/k-qt-creator-inspector,AltarBeastiful/qt-creator,KDE/android-qt-creator,dmik/qt-creator-os2,kuba1/qtcreator,Distrotech/qtcreator,omniacreator/qtcreator,jonnor/qt-creator,malikcjm/qtcreator,martyone/sailfish-qtcreator,amyvmiwei/qt-creator,amyvmiwei/qt-creator
f5230e57d46ee3793e157979e8e36633ec96a833
tests/unit/algorithm/LocatePointInRingTest.cpp
tests/unit/algorithm/LocatePointInRingTest.cpp
// // Test Suite for geos::algorithm::PointLocator // Ported from JTS junit/algorithm/PointLocator.java #include <tut/tut.hpp> // geos #include <geos/io/WKTReader.h> #include <geos/algorithm/PointLocator.h> #include <geos/algorithm/CGAlgorithms.h> #include <geos/algorithm/RayCrossingCounterDD.h> #include <geos/geom/PrecisionModel.h> #include <geos/geom/GeometryFactory.h> #include <geos/geom/Geometry.h> // required for use in unique_ptr #include <geos/geom/Polygon.h> #include <geos/geom/LineString.h> #include <geos/geom/Coordinate.h> // std #include <sstream> #include <string> #include <memory> namespace geos { namespace geom { class Geometry; } } using namespace geos::geom; // for Location using namespace geos::algorithm; // for Location namespace tut { // // Test Group // // dummy data, not used struct test_locatepointinring_data {}; typedef test_group<test_locatepointinring_data> group; typedef group::object object; group test_locatepointinring_group("geos::algorithm::LocatePointInRing"); // These are static to avoid namespace pollution // The struct test_*_data above is probably there // for the same reason... // static PrecisionModel pm; static GeometryFactory::Ptr gf = GeometryFactory::create(&pm); static geos::io::WKTReader reader(gf.get()); typedef std::unique_ptr<Geometry> GeomPtr; static void runPtLocator(int expected, const Coordinate& pt, const std::string& wkt) { std::unique_ptr<Geometry> geom(reader.read(wkt)); const Polygon *poly = dynamic_cast<Polygon*>(geom.get()); const CoordinateSequence* cs = poly->getExteriorRing()->getCoordinatesRO(); int loc = CGAlgorithms::locatePointInRing(pt, *cs); ensure_equals(loc, expected); } static void runPtLocatorDD(int expected, const Coordinate& pt, const std::string& wkt) { std::unique_ptr<Geometry> geom(reader.read(wkt)); const Polygon *poly = dynamic_cast<Polygon*>(geom.get()); const CoordinateSequence* cs = poly->getExteriorRing()->getCoordinatesRO(); int loc = RayCrossingCounterDD::locatePointInRing(pt, *cs); ensure_equals(loc, expected); } const std::string wkt_comb("POLYGON ((0 0, 0 10, 4 5, 6 10, 7 5, 9 10, 10 5, 13 5, 15 10, 16 3, 17 10, 18 3, 25 10, 30 10, 30 0, 15 0, 14 5, 13 0, 9 0, 8 5, 6 0, 0 0))"); const std::string wkt_rpts("POLYGON ((0 0, 0 10, 2 5, 2 5, 2 5, 2 5, 2 5, 3 10, 6 10, 8 5, 8 5, 8 5, 8 5, 10 10, 10 5, 10 5, 10 5, 10 5, 10 0, 0 0))"); // // Test Cases // // 1 - Test box template<> template<> void object::test<1>() { runPtLocator( Location::INTERIOR, Coordinate(10, 10), "POLYGON ((0 0, 0 20, 20 20, 20 0, 0 0))"); } // 2 - Test complex ring template<> template<> void object::test<2>() { runPtLocator( Location::INTERIOR, Coordinate(0, 0), "POLYGON ((-40 80, -40 -80, 20 0, 20 -100, 40 40, 80 -80, 100 80, 140 -20, 120 140, 40 180, 60 40, 0 120, -20 -20, -40 80))"); } // 3 - Comb tests template<> template<> void object::test<3>() { runPtLocator(Location::BOUNDARY, Coordinate(0, 0), wkt_comb); runPtLocator(Location::BOUNDARY, Coordinate(0, 1), wkt_comb); // at vertex runPtLocator(Location::BOUNDARY, Coordinate(4, 5), wkt_comb); runPtLocator(Location::BOUNDARY, Coordinate(8, 5), wkt_comb); // on horizontal segment runPtLocator(Location::BOUNDARY, Coordinate(11, 5), wkt_comb); // on vertical segment runPtLocator(Location::BOUNDARY, Coordinate(30, 5), wkt_comb); // on angled segment runPtLocator(Location::BOUNDARY, Coordinate(22, 7), wkt_comb); runPtLocator(Location::INTERIOR, Coordinate(1, 5), wkt_comb); runPtLocator(Location::INTERIOR, Coordinate(5, 5), wkt_comb); runPtLocator(Location::INTERIOR, Coordinate(1, 7), wkt_comb); runPtLocator(Location::EXTERIOR, Coordinate(12, 10), wkt_comb); runPtLocator(Location::EXTERIOR, Coordinate(16, 5), wkt_comb); runPtLocator(Location::EXTERIOR, Coordinate(35, 5), wkt_comb); } // 4 - repeated points template<> template<> void object::test<4>() { runPtLocator(Location::BOUNDARY, Coordinate(0, 0), wkt_rpts); runPtLocator(Location::BOUNDARY, Coordinate(0, 1), wkt_rpts); // at vertex runPtLocator(Location::BOUNDARY, Coordinate(2, 5), wkt_rpts); runPtLocator(Location::BOUNDARY, Coordinate(8, 5), wkt_rpts); runPtLocator(Location::BOUNDARY, Coordinate(10, 5), wkt_rpts); runPtLocator(Location::INTERIOR, Coordinate(1, 5), wkt_rpts); runPtLocator(Location::INTERIOR, Coordinate(3, 5), wkt_rpts); } // 5 - robustness template<> template<> void object::test<5>() { runPtLocatorDD(Location::EXTERIOR, Coordinate(25.374625374625374, 128.35564435564436), "POLYGON ((0.0 0.0, 0.0 172.0, 100.0 0.0, 0.0 0.0))"); } // 6 - robustness template<> template<> void object::test<6>() { runPtLocatorDD(Location::INTERIOR, Coordinate(97.96039603960396, 782.0), "POLYGON ((642.0 815.0, 69.0 764.0, 394.0 966.0, 642.0 815.0))"); } // 7 - robustness template<> template<> void object::test<7>() { runPtLocatorDD(Location::EXTERIOR, Coordinate(3.166572116932842, 48.5390194687463), "POLYGON ((2.152214146946829 50.470470727186765, 18.381941666723034 19.567250592139274, 2.390837642830135 49.228045261718165, 2.152214146946829 50.470470727186765))"); } } // namespace tut
// // Test Suite for geos::algorithm::PointLocator // Ported from JTS junit/algorithm/PointLocator.java #include <tut/tut.hpp> // geos #include <geos/io/WKTReader.h> #include <geos/algorithm/PointLocator.h> #include <geos/algorithm/CGAlgorithms.h> #include <geos/algorithm/RayCrossingCounterDD.h> #include <geos/geom/PrecisionModel.h> #include <geos/geom/GeometryFactory.h> #include <geos/geom/Geometry.h> // required for use in unique_ptr #include <geos/geom/Polygon.h> #include <geos/geom/LineString.h> #include <geos/geom/Coordinate.h> // std #include <sstream> #include <string> #include <memory> namespace geos { namespace geom { class Geometry; } } using namespace geos::geom; // for Location using namespace geos::algorithm; // for Location namespace tut { // // Test Group // // dummy data, not used struct test_locatepointinring_data {}; typedef test_group<test_locatepointinring_data> group; typedef group::object object; group test_locatepointinring_group("geos::algorithm::LocatePointInRing"); // These are static to avoid namespace pollution // The struct test_*_data above is probably there // for the same reason... // static PrecisionModel pm; static GeometryFactory::Ptr gf = GeometryFactory::create(&pm); static geos::io::WKTReader reader(gf.get()); static void runPtLocator(int expected, const Coordinate& pt, const std::string& wkt) { std::unique_ptr<Geometry> geom(reader.read(wkt)); const Polygon *poly = dynamic_cast<Polygon*>(geom.get()); const CoordinateSequence* cs = poly->getExteriorRing()->getCoordinatesRO(); int loc = CGAlgorithms::locatePointInRing(pt, *cs); ensure_equals(loc, expected); } static void runPtLocatorDD(int expected, const Coordinate& pt, const std::string& wkt) { std::unique_ptr<Geometry> geom(reader.read(wkt)); const Polygon *poly = dynamic_cast<Polygon*>(geom.get()); const CoordinateSequence* cs = poly->getExteriorRing()->getCoordinatesRO(); int loc = RayCrossingCounterDD::locatePointInRing(pt, *cs); ensure_equals(loc, expected); } const std::string wkt_comb("POLYGON ((0 0, 0 10, 4 5, 6 10, 7 5, 9 10, 10 5, 13 5, 15 10, 16 3, 17 10, 18 3, 25 10, 30 10, 30 0, 15 0, 14 5, 13 0, 9 0, 8 5, 6 0, 0 0))"); const std::string wkt_rpts("POLYGON ((0 0, 0 10, 2 5, 2 5, 2 5, 2 5, 2 5, 3 10, 6 10, 8 5, 8 5, 8 5, 8 5, 10 10, 10 5, 10 5, 10 5, 10 5, 10 0, 0 0))"); // // Test Cases // // 1 - Test box template<> template<> void object::test<1>() { runPtLocator( Location::INTERIOR, Coordinate(10, 10), "POLYGON ((0 0, 0 20, 20 20, 20 0, 0 0))"); } // 2 - Test complex ring template<> template<> void object::test<2>() { runPtLocator( Location::INTERIOR, Coordinate(0, 0), "POLYGON ((-40 80, -40 -80, 20 0, 20 -100, 40 40, 80 -80, 100 80, 140 -20, 120 140, 40 180, 60 40, 0 120, -20 -20, -40 80))"); } // 3 - Comb tests template<> template<> void object::test<3>() { runPtLocator(Location::BOUNDARY, Coordinate(0, 0), wkt_comb); runPtLocator(Location::BOUNDARY, Coordinate(0, 1), wkt_comb); // at vertex runPtLocator(Location::BOUNDARY, Coordinate(4, 5), wkt_comb); runPtLocator(Location::BOUNDARY, Coordinate(8, 5), wkt_comb); // on horizontal segment runPtLocator(Location::BOUNDARY, Coordinate(11, 5), wkt_comb); // on vertical segment runPtLocator(Location::BOUNDARY, Coordinate(30, 5), wkt_comb); // on angled segment runPtLocator(Location::BOUNDARY, Coordinate(22, 7), wkt_comb); runPtLocator(Location::INTERIOR, Coordinate(1, 5), wkt_comb); runPtLocator(Location::INTERIOR, Coordinate(5, 5), wkt_comb); runPtLocator(Location::INTERIOR, Coordinate(1, 7), wkt_comb); runPtLocator(Location::EXTERIOR, Coordinate(12, 10), wkt_comb); runPtLocator(Location::EXTERIOR, Coordinate(16, 5), wkt_comb); runPtLocator(Location::EXTERIOR, Coordinate(35, 5), wkt_comb); } // 4 - repeated points template<> template<> void object::test<4>() { runPtLocator(Location::BOUNDARY, Coordinate(0, 0), wkt_rpts); runPtLocator(Location::BOUNDARY, Coordinate(0, 1), wkt_rpts); // at vertex runPtLocator(Location::BOUNDARY, Coordinate(2, 5), wkt_rpts); runPtLocator(Location::BOUNDARY, Coordinate(8, 5), wkt_rpts); runPtLocator(Location::BOUNDARY, Coordinate(10, 5), wkt_rpts); runPtLocator(Location::INTERIOR, Coordinate(1, 5), wkt_rpts); runPtLocator(Location::INTERIOR, Coordinate(3, 5), wkt_rpts); } // 5 - robustness template<> template<> void object::test<5>() { runPtLocatorDD(Location::EXTERIOR, Coordinate(25.374625374625374, 128.35564435564436), "POLYGON ((0.0 0.0, 0.0 172.0, 100.0 0.0, 0.0 0.0))"); } // 6 - robustness template<> template<> void object::test<6>() { runPtLocatorDD(Location::INTERIOR, Coordinate(97.96039603960396, 782.0), "POLYGON ((642.0 815.0, 69.0 764.0, 394.0 966.0, 642.0 815.0))"); } // 7 - robustness template<> template<> void object::test<7>() { runPtLocatorDD(Location::EXTERIOR, Coordinate(3.166572116932842, 48.5390194687463), "POLYGON ((2.152214146946829 50.470470727186765, 18.381941666723034 19.567250592139274, 2.390837642830135 49.228045261718165, 2.152214146946829 50.470470727186765))"); } } // namespace tut
Remove unused typedef
Remove unused typedef
C++
lgpl-2.1
mwtoews/libgeos,libgeos/libgeos,mwtoews/libgeos,mwtoews/libgeos,libgeos/libgeos,mwtoews/libgeos,mwtoews/libgeos,libgeos/libgeos,libgeos/libgeos,mwtoews/libgeos,mwtoews/libgeos,libgeos/libgeos
b84557e736e46724178a61e54893835029263a4c
lib/cpp/src/gui/JobTree.cpp
lib/cpp/src/gui/JobTree.cpp
#include "JobTree.h" #include "plow.h" #include <QStringList> namespace Plow { namespace Gui { JobTree::JobTree(QWidget *parent) : QWidget(parent) { layout = new QVBoxLayout(this); QStringList header; header << "Job" << "Cores" << "Max" << "Waiting"; treeWidget = new QTreeWidget; treeWidget->setHeaderLabels(header); treeWidget->setColumnCount(4); layout->addWidget(treeWidget); } void JobTree::updateJobs() { PlowClient* client = getClient(); std::vector<JobT> jobs; JobFilterT filter; std::vector<JobState::type> states; states.push_back(JobState::RUNNING); filter.__set_states(states); client->getJobs(jobs, filter); for (std::vector<JobT>::iterator i = jobs.begin(); i != jobs.end(); ++i) { QTreeWidgetItem *item = new QTreeWidgetItem((QTreeWidget*)0, QStringList(QString(i->name.c_str()))); treeWidget->insertTopLevelItem(0, item); } } } }
#include "JobTree.h" #include "plow.h" #include <QStringList> #include <QString> namespace Plow { namespace Gui { JobTree::JobTree(QWidget *parent) : QWidget(parent) { layout = new QVBoxLayout(this); QStringList header; header << "Job" << "Cores" << "Max" << "Waiting"; treeWidget = new QTreeWidget; treeWidget->setHeaderLabels(header); treeWidget->setColumnCount(4); layout->addWidget(treeWidget); } void JobTree::updateJobs() { PlowClient* client = getClient(); std::vector<JobT> jobs; JobFilterT filter; std::vector<JobState::type> states; states.push_back(JobState::RUNNING); filter.__set_states(states); client->getJobs(jobs, filter); for (std::vector<JobT>::iterator i = jobs.begin(); i != jobs.end(); ++i) { QStringList data; data << QString::fromStdString(i->name) << QString::number(i->runningCoreCount) << QString::number(i->maxCores) << QString::number(i->waitingTaskCount); QTreeWidgetItem *item = new QTreeWidgetItem((QTreeWidget*)0, data); treeWidget->insertTopLevelItem(0, item); } } } }
Add more data to the JobTree
Add more data to the JobTree
C++
apache-2.0
chadmv/plow,Br3nda/plow,chadmv/plow,chadmv/plow,chadmv/plow,Br3nda/plow,chadmv/plow,chadmv/plow,Br3nda/plow,chadmv/plow,Br3nda/plow,Br3nda/plow
c0d817d6001afaba7c75c136a96a20fe7153f31a
tests/PythonQtTestMain.cpp
tests/PythonQtTestMain.cpp
/* * * Copyright (C) 2010 MeVis Medical Solutions AG All Rights Reserved. * * 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. * * Further, this software is distributed without any warranty that it is * free of the rightful claim of any third person regarding infringement * or the like. Any license provided herein, whether implied or * otherwise, applies only to this software file. Patent licenses, if * any, provided herein do not apply to combinations of this program with * other software, or any other product whatsoever. * * 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 * * Contact information: MeVis Medical Solutions AG, Universitaetsallee 29, * 28359 Bremen, Germany or: * * http://www.mevis.de * */ //---------------------------------------------------------------------------------- /*! // \file PythonQtTests.cpp // \author Florian Link // \author Last changed by $Author: florian $ // \date 2006-05 */ //---------------------------------------------------------------------------------- #include "PythonQt.h" #include "PythonQtTests.h" #include <QApplication> int main( int argc, char **argv ) { QApplication qapp(argc, argv); PythonQt::init(PythonQt::IgnoreSiteModule | PythonQt::RedirectStdOut); int failCount = 0; PythonQtTestApi api; failCount += QTest::qExec(&api, argc, argv); PythonQtTestSignalHandler signalHandler; failCount += QTest::qExec(&signalHandler, argc, argv); PythonQtTestSlotCalling slotCalling; failCount += QTest::qExec(&slotCalling, argc, argv); PythonQt::cleanup(); if (failCount>0) { std::cerr << "Tests failed: " << failCount << std::endl; } else { std::cout << "All tests passed successfully." << std::endl; } return failCount; }
/* * * Copyright (C) 2010 MeVis Medical Solutions AG All Rights Reserved. * * 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. * * Further, this software is distributed without any warranty that it is * free of the rightful claim of any third person regarding infringement * or the like. Any license provided herein, whether implied or * otherwise, applies only to this software file. Patent licenses, if * any, provided herein do not apply to combinations of this program with * other software, or any other product whatsoever. * * 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 * * Contact information: MeVis Medical Solutions AG, Universitaetsallee 29, * 28359 Bremen, Germany or: * * http://www.mevis.de * */ //---------------------------------------------------------------------------------- /*! // \file PythonQtTests.cpp // \author Florian Link // \author Last changed by $Author: florian $ // \date 2006-05 */ //---------------------------------------------------------------------------------- #include "PythonQt.h" #include "PythonQtTests.h" #include <QApplication> int main(int argc, char *argv[]) { QApplication qapp(argc, argv); PythonQt::init(PythonQt::IgnoreSiteModule | PythonQt::RedirectStdOut); int failCount = 0; PythonQtTestApi api; failCount += QTest::qExec(&api, argc, argv); PythonQtTestSignalHandler signalHandler; failCount += QTest::qExec(&signalHandler, argc, argv); PythonQtTestSlotCalling slotCalling; failCount += QTest::qExec(&slotCalling, argc, argv); PythonQt::cleanup(); if (failCount>0) { std::cerr << "Tests failed: " << failCount << std::endl; } else { std::cout << "All tests passed successfully." << std::endl; } return failCount; }
Fix tests link error on Windows
Fix tests link error on Windows This commit fixes a link error building PythonQtCppTests on Windows: 1>PythonQtCppTests.obj : error LNK2001: unresolved external symbol "int __cdecl tests_PythonQtTestMain(int,char * * const)" (?tests_PythonQtTestMain@@YAHHQEAPEAD@Z) 1>C:\temp\PythonQt-build\Debug\PythonQtCppTests.exe : fatal error LNK1120: 1 unresolved externals
C++
lgpl-2.1
rkhlebnikov/PythonQt,msmolens/PythonQt,msmolens/PythonQt,rkhlebnikov/PythonQt,rkhlebnikov/PythonQt,msmolens/PythonQt,msmolens/PythonQt,rkhlebnikov/PythonQt
91531a14826207c8a5cf110a4663644a761d4d21
py_module.cpp
py_module.cpp
#include <Python.h> #include "numpy/arrayobject.h" #include "part_int.h" #include <set> /*Wraps the flux_extractor into a python module called spectra_priv. Don't call this directly, call the python wrapper.*/ /*Check whether the passed array has type typename. Returns 1 if it doesn't, 0 if it does.*/ int check_type(PyArrayObject * arr, int npy_typename) { return !PyArray_EquivTypes(PyArray_DESCR(arr), PyArray_DescrFromType(npy_typename)); } int check_float(PyArrayObject * arr) { return check_type(arr, NPY_FLOAT); } /* When handed a list of particles, * return a list of bools with True for those nearby to a sightline*/ extern "C" PyObject * Py_near_lines(PyObject *self, PyObject *args) { int NumLos; long long Npart; double box100; PyArrayObject *cofm, *axis, *pos, *hh, *is_a_line; PyObject *out; if(!PyArg_ParseTuple(args, "dO!O!O!O!",&box100, &PyArray_Type, &pos, &PyArray_Type, &hh, &PyArray_Type, &axis, &PyArray_Type, &cofm) ) return NULL; NumLos = PyArray_DIM(cofm,0); Npart = PyArray_DIM(pos,0); if(NumLos != PyArray_DIM(axis,0) || 3 != PyArray_DIM(cofm,1)){ PyErr_SetString(PyExc_ValueError, "cofm must have dimensions (np.size(axis),3) \n"); return NULL; } if(check_type(cofm, NPY_DOUBLE) || check_type(axis,NPY_INT)){ PyErr_SetString(PyExc_ValueError, "cofm must have 64-bit float type and axis must be a 32-bit integer\n"); return NULL; } if(check_float(pos) || check_float(hh)){ PyErr_SetString(PyExc_TypeError, "pos and h must have 32-bit float type\n"); return NULL; } //Setup los_tables double * Cofm =(double *) PyArray_DATA(PyArray_GETCONTIGUOUS(cofm)); int32_t * Axis =(int32_t *) PyArray_DATA(PyArray_GETCONTIGUOUS(axis)); IndexTable sort_los_table(Cofm, Axis, NumLos, box100); //Set of particles near a line std::set<int> near_lines; //find lists //DANGER: potentially huge allocation const float * Pos =(float *) PyArray_DATA(PyArray_GETCONTIGUOUS(pos)); const float * h = (float *) PyArray_DATA(PyArray_GETCONTIGUOUS(hh)); #pragma omp parallel for for(long long i=0; i < Npart; i++){ std::map<int, double> nearby=sort_los_table.get_near_lines(&(Pos[3*i]),h[i]); if(nearby.size()>0){ #pragma omp critical { near_lines.insert(i); } } } //Copy data into python npy_intp size = near_lines.size(); is_a_line = (PyArrayObject *) PyArray_SimpleNew(1, &size, NPY_INT); int i=0; for (std::set<int>::const_iterator it = near_lines.begin(); it != near_lines.end() && i < size; ++it, ++i){ *(npy_int *)PyArray_GETPTR1(is_a_line,i) = (*it); } out = Py_BuildValue("O", is_a_line); Py_DECREF(is_a_line); return out; } /*****************************************************************************/ /*Interface for SPH interpolation*/ extern "C" PyObject * Py_Particle_Interpolation(PyObject *self, PyObject *args) { //Things which should be from input int nbins, NumLos, compute_tau; long long Npart; double box100, velfac, lambda, gamma, fosc, amumass; npy_intp size[2]; //Input variables in np format PyArrayObject *pos, *vel, *mass, *temp, *h; PyArrayObject *cofm, *axis; //Get our input if(!PyArg_ParseTuple(args, "iiddddddO!O!O!O!O!O!O!", &compute_tau, &nbins, &box100, &velfac, &lambda, &gamma, &fosc, &amumass, &PyArray_Type, &pos, &PyArray_Type, &vel, &PyArray_Type, &mass, &PyArray_Type, &temp, &PyArray_Type, &h, &PyArray_Type, &axis, &PyArray_Type, &cofm) ) { PyErr_SetString(PyExc_AttributeError, "Incorrect arguments: use compute_tau, nbins, boxsize, velfac, lambda, gamma, fosc, species mass (amu), pos, vel, mass, temp, h, axis, cofm\n"); return NULL; } //Check that our input has the right types if(check_float(pos) || check_float(vel) || check_float(mass) || check_float(temp) || check_float(h)){ PyErr_SetString(PyExc_TypeError, "One of the data arrays does not have 32-bit float type\n"); return NULL; } if(check_type(cofm,NPY_DOUBLE)){ PyErr_SetString(PyExc_TypeError, "Sightline positions must have 64-bit float type\n"); return NULL; } if(check_type(axis, NPY_INT32)){ PyErr_SetString(PyExc_TypeError, "Axis must be a 32-bit integer\n"); return NULL; } NumLos = PyArray_DIM(cofm,0); Npart = PyArray_DIM(pos,0); //Malloc stuff size[0] = NumLos; size[1] = nbins; if(NumLos != PyArray_DIM(axis,0) || 3 != PyArray_DIM(cofm,1)) { PyErr_SetString(PyExc_ValueError, "cofm must have dimensions (np.size(axis),3) \n"); return NULL; } /* Allocate array space. This is (I hope) contiguous. * Note: for an array of shape (a,b), element (i,j) can be accessed as * [i*b+j] */ PyArrayObject * colden_out = (PyArrayObject *) PyArray_SimpleNew(2, size, NPY_DOUBLE); PyArrayObject * tau_out; double * tau; if (compute_tau){ tau_out = (PyArrayObject *) PyArray_SimpleNew(2, size, NPY_DOUBLE); tau = (double *) PyArray_DATA(tau_out); } else{ tau_out = (PyArrayObject *) PyArray_SimpleNew(0, size, NPY_DOUBLE); tau = NULL; } if ( !colden_out || !tau_out ){ PyErr_SetString(PyExc_MemoryError, "Could not allocate memory for output arrays\n"); return NULL; } //Initialise output arrays to 0. PyArray_FILLWBYTE(colden_out, 0); PyArray_FILLWBYTE(tau_out, 0); //Here comes the cheat double * colden = (double *) PyArray_DATA(colden_out); //Initialise P from the data in the input numpy arrays. //Note: better be sure they are float32 in the calling function. float * Pos =(float *) PyArray_DATA(PyArray_GETCONTIGUOUS(pos)); float * Vel =(float *) PyArray_DATA(PyArray_GETCONTIGUOUS(vel)); float * Mass =(float *) PyArray_DATA(PyArray_GETCONTIGUOUS(mass)); float * Temp =(float *) PyArray_DATA(PyArray_GETCONTIGUOUS(temp)); float * Hh =(float *) PyArray_DATA(PyArray_GETCONTIGUOUS(h)); double * Cofm =(double *) PyArray_DATA(PyArray_GETCONTIGUOUS(cofm)); int * Axis =(int *) PyArray_DATA(PyArray_GETCONTIGUOUS(axis)); ParticleInterp pint(tau, colden, nbins, lambda, gamma, fosc, amumass, box100, velfac, Cofm, Axis ,NumLos); //Do the work pint.do_work(Pos, Vel, Mass, Temp, Hh, Npart); //Build a tuple from the interp struct PyObject * for_return; for_return = Py_BuildValue("OO", tau_out, colden_out); //Decrement the refcount Py_DECREF(tau_out); Py_DECREF(colden_out); return for_return; } static PyMethodDef spectrae[] = { {"_Particle_Interpolate", Py_Particle_Interpolation, METH_VARARGS, "Find absorption and column density by interpolating particles. " " Arguments: compute_tau nbins, boxsize, velfac, lambda, gamma, fosc, species mass (amu), pos, vel, mass, temp, h, axis, cofm" " "}, {"_near_lines", Py_near_lines,METH_VARARGS, "Give a list of particles and sightlines, " "return a list of booleans for those particles near " "a sightline." " Arguments: box, pos, h, axis, cofm"}, {NULL, NULL, 0, NULL}, }; PyMODINIT_FUNC init_spectra_priv(void) { Py_InitModule("_spectra_priv", spectrae); import_array(); }
#include <Python.h> #include "numpy/arrayobject.h" #include "part_int.h" #include <set> /*Wraps the flux_extractor into a python module called spectra_priv. Don't call this directly, call the python wrapper.*/ /*Check whether the passed array has type typename. Returns 1 if it doesn't, 0 if it does.*/ int check_type(PyArrayObject * arr, int npy_typename) { return !PyArray_EquivTypes(PyArray_DESCR(arr), PyArray_DescrFromType(npy_typename)); } int check_float(PyArrayObject * arr) { return check_type(arr, NPY_FLOAT); } /* When handed a list of particles, * return a list of bools with True for those nearby to a sightline*/ extern "C" PyObject * Py_near_lines(PyObject *self, PyObject *args) { int NumLos; long long Npart; double box100; PyArrayObject *cofm, *axis, *pos, *hh, *is_a_line; PyObject *out; if(!PyArg_ParseTuple(args, "dO!O!O!O!",&box100, &PyArray_Type, &pos, &PyArray_Type, &hh, &PyArray_Type, &axis, &PyArray_Type, &cofm) ) return NULL; NumLos = PyArray_DIM(cofm,0); Npart = PyArray_DIM(pos,0); if(NumLos != PyArray_DIM(axis,0) || 3 != PyArray_DIM(cofm,1)){ PyErr_SetString(PyExc_ValueError, "cofm must have dimensions (np.size(axis),3) \n"); return NULL; } if(check_type(cofm, NPY_DOUBLE) || check_type(axis,NPY_INT)){ PyErr_SetString(PyExc_ValueError, "cofm must have 64-bit float type and axis must be a 32-bit integer\n"); return NULL; } if(check_float(pos) || check_float(hh)){ PyErr_SetString(PyExc_TypeError, "pos and h must have 32-bit float type\n"); return NULL; } //Setup los_tables //PyArray_GETCONTIGUOUS increments the reference count of the object, //so to avoid leaking we need to save the PyArrayObject pointer. cofm = PyArray_GETCONTIGUOUS(cofm); axis = PyArray_GETCONTIGUOUS(axis); double * Cofm =(double *) PyArray_DATA(cofm); int32_t * Axis =(int32_t *) PyArray_DATA(axis); IndexTable sort_los_table(Cofm, Axis, NumLos, box100); //Set of particles near a line std::set<int> near_lines; //find lists //DANGER: potentially huge allocation pos = PyArray_GETCONTIGUOUS(pos); hh = PyArray_GETCONTIGUOUS(hh); const float * Pos =(float *) PyArray_DATA(pos); const float * h = (float *) PyArray_DATA(hh); #pragma omp parallel for for(long long i=0; i < Npart; i++){ std::map<int, double> nearby=sort_los_table.get_near_lines(&(Pos[3*i]),h[i]); if(nearby.size()>0){ #pragma omp critical { near_lines.insert(i); } } } //Copy data into python npy_intp size = near_lines.size(); is_a_line = (PyArrayObject *) PyArray_SimpleNew(1, &size, NPY_INT); int i=0; for (std::set<int>::const_iterator it = near_lines.begin(); it != near_lines.end() && i < size; ++it, ++i){ *(npy_int *)PyArray_GETPTR1(is_a_line,i) = (*it); } out = Py_BuildValue("O", is_a_line); Py_DECREF(is_a_line); //Because PyArray_GETCONTIGUOUS incremented the reference count, //and may have made an allocation, in which case this does not point to what it used to. Py_DECREF(pos); Py_DECREF(hh); Py_DECREF(cofm); Py_DECREF(axis); return out; } /*****************************************************************************/ /*Interface for SPH interpolation*/ extern "C" PyObject * Py_Particle_Interpolation(PyObject *self, PyObject *args) { //Things which should be from input int nbins, NumLos, compute_tau; long long Npart; double box100, velfac, lambda, gamma, fosc, amumass; npy_intp size[2]; //Input variables in np format PyArrayObject *pos, *vel, *mass, *temp, *h; PyArrayObject *cofm, *axis; //Get our input if(!PyArg_ParseTuple(args, "iiddddddO!O!O!O!O!O!O!", &compute_tau, &nbins, &box100, &velfac, &lambda, &gamma, &fosc, &amumass, &PyArray_Type, &pos, &PyArray_Type, &vel, &PyArray_Type, &mass, &PyArray_Type, &temp, &PyArray_Type, &h, &PyArray_Type, &axis, &PyArray_Type, &cofm) ) { PyErr_SetString(PyExc_AttributeError, "Incorrect arguments: use compute_tau, nbins, boxsize, velfac, lambda, gamma, fosc, species mass (amu), pos, vel, mass, temp, h, axis, cofm\n"); return NULL; } //Check that our input has the right types if(check_float(pos) || check_float(vel) || check_float(mass) || check_float(temp) || check_float(h)){ PyErr_SetString(PyExc_TypeError, "One of the data arrays does not have 32-bit float type\n"); return NULL; } if(check_type(cofm,NPY_DOUBLE)){ PyErr_SetString(PyExc_TypeError, "Sightline positions must have 64-bit float type\n"); return NULL; } if(check_type(axis, NPY_INT32)){ PyErr_SetString(PyExc_TypeError, "Axis must be a 32-bit integer\n"); return NULL; } NumLos = PyArray_DIM(cofm,0); Npart = PyArray_DIM(pos,0); //Malloc stuff size[0] = NumLos; size[1] = nbins; if(NumLos != PyArray_DIM(axis,0) || 3 != PyArray_DIM(cofm,1)) { PyErr_SetString(PyExc_ValueError, "cofm must have dimensions (np.size(axis),3) \n"); return NULL; } /* Allocate array space. This is (I hope) contiguous. * Note: for an array of shape (a,b), element (i,j) can be accessed as * [i*b+j] */ PyArrayObject * colden_out = (PyArrayObject *) PyArray_SimpleNew(2, size, NPY_DOUBLE); PyArrayObject * tau_out; double * tau; if (compute_tau){ tau_out = (PyArrayObject *) PyArray_SimpleNew(2, size, NPY_DOUBLE); tau = (double *) PyArray_DATA(tau_out); } else{ tau_out = (PyArrayObject *) PyArray_SimpleNew(0, size, NPY_DOUBLE); tau = NULL; } if ( !colden_out || !tau_out ){ PyErr_SetString(PyExc_MemoryError, "Could not allocate memory for output arrays\n"); return NULL; } //Initialise output arrays to 0. PyArray_FILLWBYTE(colden_out, 0); PyArray_FILLWBYTE(tau_out, 0); //Here comes the cheat double * colden = (double *) PyArray_DATA(colden_out); //Initialise P from the data in the input numpy arrays. //Note: better be sure they are float32 in the calling function. //PyArray_GETCONTIGUOUS increments the reference count of the object, //so to avoid leaking we need to save the PyArrayObject pointer. pos = PyArray_GETCONTIGUOUS(pos); vel = PyArray_GETCONTIGUOUS(vel); mass = PyArray_GETCONTIGUOUS(mass); temp = PyArray_GETCONTIGUOUS(temp); h = PyArray_GETCONTIGUOUS(h); float * Pos =(float *) PyArray_DATA(pos); float * Hh= (float *) PyArray_DATA(h); float * Vel =(float *) PyArray_DATA(vel); float * Mass =(float *) PyArray_DATA(mass); float * Temp =(float *) PyArray_DATA(temp); cofm = PyArray_GETCONTIGUOUS(cofm); axis = PyArray_GETCONTIGUOUS(axis); double * Cofm =(double *) PyArray_DATA(cofm); int32_t * Axis =(int32_t *) PyArray_DATA(axis); if( !Pos || !Vel || !Mass || !Temp || !Hh || !Cofm || !Axis ){ PyErr_SetString(PyExc_MemoryError, "Getting contiguous copies of input arrays failed\n"); return NULL; } ParticleInterp pint(tau, colden, nbins, lambda, gamma, fosc, amumass, box100, velfac, Cofm, Axis ,NumLos); //Do the work pint.do_work(Pos, Vel, Mass, Temp, Hh, Npart); //Build a tuple from the interp struct PyObject * for_return; for_return = Py_BuildValue("OO", tau_out, colden_out); //Decrement the refcount if(tau_out){ Py_DECREF(tau_out); } Py_DECREF(colden_out); //Because PyArray_GETCONTIGUOUS incremented the reference count, //and may have made an allocation, in which case this does not point to what it used to. Py_DECREF(pos); Py_DECREF(vel); Py_DECREF(mass); Py_DECREF(temp); Py_DECREF(h); Py_DECREF(cofm); Py_DECREF(axis); return for_return; } static PyMethodDef spectrae[] = { {"_Particle_Interpolate", Py_Particle_Interpolation, METH_VARARGS, "Find absorption and column density by interpolating particles. " " Arguments: compute_tau nbins, boxsize, velfac, lambda, gamma, fosc, species mass (amu), pos, vel, mass, temp, h, axis, cofm" " "}, {"_near_lines", Py_near_lines,METH_VARARGS, "Give a list of particles and sightlines, " "return a list of booleans for those particles near " "a sightline." " Arguments: box, pos, h, axis, cofm"}, {NULL, NULL, 0, NULL}, }; PyMODINIT_FUNC init_spectra_priv(void) { Py_InitModule("_spectra_priv", spectrae); import_array(); }
Rework array access from python to avoid memory leaks.
Rework array access from python to avoid memory leaks. PyArray_GETCONTIGUOUS always increments the refcount, and may allocate memory. This memory needs to be freed, so save the pointer it returns and call Py_DECREF on it when we're done.
C++
mit
sbird/fake_spectra,sbird/fake_spectra,sbird/fake_spectra
cb1066a2517ce9a71913f9bcf138e8e466c17f7b
viewer/interaction/ui2d.cc
viewer/interaction/ui2d.cc
#include "viewer/interaction/ui2d.hh" #include "logging/assert.hh" #include "viewer/projection.hh" #include <GL/glew.h> #include "viewer/gl_aliases.hh" namespace viewer { namespace { constexpr double Z_DIST = -0.1; void draw_pointer_targets(const std::vector<PointerTarget> &pointer_targets, const Projection &proj, const CharacterLibrary &char_lib) { glPushMatrix(); glPointSize(6.0); glColor3d(1.0, 1.0, 1.0); for (const auto &target : pointer_targets) { const auto screen_pt = proj.project(target.world_pos); glBegin(GL_POINTS); { glVertex3d(screen_pt.point.x(), screen_pt.point.y(), Z_DIST); } glEnd(); glLineWidth(0.3); glBegin(GL_LINE_STRIP); { glVertex3d(screen_pt.point.x(), screen_pt.point.y(), Z_DIST); glVertex3d(target.location.point.x(), target.location.point.y(), Z_DIST); } glEnd(); glTranslated(target.location.point.x(), target.location.point.y(), Z_DIST); write_string(target.text, char_lib); } glPopMatrix(); } PlotRange compute_plot_range(const LinePlot2d &line_plot) { PlotRange range; for (const auto &subplot_pair : line_plot.subplots) { const auto &subplot = subplot_pair.second; for (const auto &pt : subplot.points) { range.y_max = std::max(range.y_max, pt.y()); range.y_min = std::min(range.y_min, pt.y()); range.x_max = std::max(range.x_max, pt.x()); range.x_min = std::min(range.x_min, pt.x()); } } if (line_plot.plot_range.x_max != line_plot.plot_range.x_min) { range.x_max = line_plot.plot_range.x_max; range.x_min = line_plot.plot_range.x_min; } if (line_plot.plot_range.y_max != line_plot.plot_range.y_min) { range.y_max = line_plot.plot_range.y_max; range.y_min = line_plot.plot_range.y_min; } return range; } void draw_lineplot(const LinePlot2d &line_plot, const Projection &proj, const CharacterLibrary &char_lib) { glPushMatrix(); glPushAttrib(GL_CURRENT_BIT | GL_LINE_BIT); constexpr double X_OFFSET = 0.2; glTranslated(X_OFFSET, 0.2, 0.0); const double aspect = static_cast<double>(proj.viewport_size().width) / proj.viewport_size().height; glColor4d(0.6, 0.6, 0.6, 0.6); glBegin(GL_QUADS); const double field_y_max = 0.5; const double field_y_min = -0.5; const double field_x_min = 0.0; const double field_x_max = (aspect - X_OFFSET); glVertex3d(field_x_min, field_y_min, -0.9); glVertex3d(field_x_max, field_y_min, -0.9); glVertex3d(field_x_max, field_y_max, -0.9); glVertex3d(field_x_min, field_y_max, -0.9); glEnd(); const PlotRange range = compute_plot_range(line_plot); const double x_range = range.x_max - range.x_min; const double abs_y_max = std::max(std::abs(range.y_min), std::abs(range.y_max)); glEnable(GL_LINE_STIPPLE); for (const auto &subplot_pair : line_plot.subplots) { const auto &subplot = subplot_pair.second; glColor(subplot.color); if (subplot.dotted) { glLineStipple(1.0, 0x00FF); } else { glLineStipple(1.0, 0xFFFF); } glLineWidth(subplot.line_width); glBegin(GL_LINE_STRIP); for (const auto &pt : subplot.points) { const double x_val = field_x_max * (pt.x() - range.x_min) / x_range; const double y_val = field_y_max * pt.y() / abs_y_max; glVertex(jcc::Vec2(x_val, y_val)); } glEnd(); } glLineStipple(1, 0x00FF); glLineWidth(1.0); glBegin(GL_LINES); { glColor4d(1.0, 0.0, 0.0, 0.8); glVertex3d(field_x_min, 0.0, 0.5); glVertex3d(field_x_max, 0.0, 0.5); glColor4d(0.0, 1.0, 0.0, 0.8); const double x_origin = (0.0 - range.x_min) / x_range; glVertex3d(x_origin, field_y_min, 0.5); glVertex3d(x_origin, field_y_max, 0.5); } glEnd(); glTranslated(0.0, field_y_max + 0.05, 0.0); const std::string max_txt = line_plot.plot_title + "\nMax: " + std::to_string(abs_y_max); write_string(max_txt, char_lib, 0.5); glPopAttrib(); glPopMatrix(); } void draw_image(const Image &image, const Projection &proj, const CharacterLibrary &char_lib) { glPushMatrix(); glEnable(GL_TEXTURE_2D); if (!image.texture.ready()) { // // We want the *height* of the texture to be 1.0 // const double width_per_height = image.image.cols / static_cast<double>(image.image.rows); const jcc::Vec2 size(width_per_height, 1.0); image.texture = SmartTexture(size); image.texture.tex_image_2d(GL_TEXTURE_2D, 0, GL_RGB, image.image.cols, image.image.rows, 0, GL_BGR, GL_UNSIGNED_BYTE, image.image.data); } glTranslated(0.0, 0.0, -0.8); image.texture.draw(); glDisable(GL_TEXTURE_2D); glPopMatrix(); } void draw_points(const std::vector<Point2d> points, const Projection &proj, const CharacterLibrary &char_lib) { for (const auto &pt : points) { glPointSize(pt.size); glBegin(GL_POINTS); glColor(pt.color); glVertex3d(pt.point.x(), 1.0 - pt.point.y(), -0.1); glEnd(); } } void draw_lines(const std::vector<Line2d> &lines, const Projection &proj, const CharacterLibrary &char_lib) { for (const auto &line : lines) { glLineWidth(line.line_width); glColor(line.color); glBegin(GL_LINES); glVertex3d(line.start.x(), 1.0 - line.start.y(), -0.2); glVertex3d(line.end.x(), 1.0 - line.end.y(), -0.2); glEnd(); } } void draw_grid_mesh(const GridMesh &mesh) { const auto &pts = mesh.vertices; const int width = mesh.width; constexpr double Z_DIST = -0.1; constexpr double Z_DIST_OUTLINE = 0.1; const int cols_per_row = mesh.vertices.size() / width; const int rows = width; glColor(mesh.color); glBegin(GL_QUADS); { for (int r = 0; r < rows - 1; ++r) { for (int c = 0; c < cols_per_row - 1; ++c) { const int tl = c + (r * cols_per_row); const int tr = c + 1 + (r * cols_per_row); const int br = c + 1 + ((r + 1) * cols_per_row); const int bl = c + ((r + 1) * cols_per_row); glVertex3d(pts[tl].x(), pts[tl].y(), Z_DIST); glVertex3d(pts[tr].x(), pts[tr].y(), Z_DIST); glVertex3d(pts[br].x(), pts[br].y(), Z_DIST); glVertex3d(pts[bl].x(), pts[bl].y(), Z_DIST); } } glEnd(); } { glColor4d(0.1, 0.8, 0.1, 0.8); glLineWidth(1.0); for (int r = 0; r < rows - 1; ++r) { for (int c = 0; c < cols_per_row - 1; ++c) { const int tl = c + (r * cols_per_row); const int tr = c + 1 + (r * cols_per_row); const int br = c + 1 + ((r + 1) * cols_per_row); const int bl = c + ((r + 1) * cols_per_row); glBegin(GL_LINE_LOOP); glVertex3d(pts[tl].x(), pts[tl].y(), Z_DIST_OUTLINE); glVertex3d(pts[tr].x(), pts[tr].y(), Z_DIST_OUTLINE); glVertex3d(pts[br].x(), pts[br].y(), Z_DIST_OUTLINE); glVertex3d(pts[bl].x(), pts[bl].y(), Z_DIST_OUTLINE); glEnd(); } } } } } // namespace void Ui2d::add_pointer_target(const PointerTarget &pointer_target) { const std::lock_guard<std::mutex> lk(draw_mutex_); back_buffer_.pointer_targets.push_back(pointer_target); } void Ui2d::add_lineplot(const LinePlot2d &line_plot) { const std::lock_guard<std::mutex> lk(draw_mutex_); back_buffer_.line_plots.push_back(line_plot); } void Ui2d::add_grid_mesh(const GridMesh &grid_mesh) { const std::lock_guard<std::mutex> lk(draw_mutex_); JASSERT_GT(grid_mesh.width, 1, "Grid width must be greater 1"); JASSERT_FALSE(grid_mesh.vertices.empty(), "Grid cannot be empty."); JASSERT_EQ(grid_mesh.vertices.size() % grid_mesh.width, 0u, "Grid size must be divisible by width"); back_buffer_.grid_meshes.push_back(grid_mesh); } void Ui2d::clear() { const std::lock_guard<std::mutex> lk(draw_mutex_); back_buffer_.clear(); front_buffer_.clear(); } void Ui2d::flip() { const std::lock_guard<std::mutex> lk(draw_mutex_); front_buffer_ = std::move(back_buffer_); } void Ui2d::flush() { const std::lock_guard<std::mutex> lk(draw_mutex_); const auto insert = [](auto &into, const auto &from) { into.insert(into.begin(), from.begin(), from.end()); }; insert(front_buffer_.pointer_targets, back_buffer_.pointer_targets); insert(front_buffer_.line_plots, back_buffer_.line_plots); insert(front_buffer_.images, back_buffer_.images); insert(front_buffer_.points, back_buffer_.points); insert(front_buffer_.grid_meshes, back_buffer_.grid_meshes); insert(front_buffer_.lines, back_buffer_.lines); } void Ui2d::draw() const { const std::lock_guard<std::mutex> lk(draw_mutex_); // Create the character library when it's renderin' time if (char_lib_.size() == 0u) { char_lib_ = create_text_library(); } const auto proj = Projection::get_from_current(); glMatrixMode(GL_PROJECTION); glPushMatrix(); glLoadIdentity(); const double width = static_cast<double>(proj.viewport_size().width); const double height = static_cast<double>(proj.viewport_size().height); const double aspect_ratio = width / height; glOrtho(-aspect_ratio, aspect_ratio, -1.0, 1.0, -1.0, 1.0); glMatrixMode(GL_MODELVIEW); glPushMatrix(); glLoadIdentity(); draw_pointer_targets(front_buffer_.pointer_targets, proj, char_lib_); for (const auto &line_plot : front_buffer_.line_plots) { draw_lineplot(line_plot, proj, char_lib_); } draw_points(front_buffer_.points, proj, char_lib_); draw_lines(front_buffer_.lines, proj, char_lib_); for (const auto &image : front_buffer_.images) { draw_image(image, proj, char_lib_); } for (const auto &mesh : front_buffer_.grid_meshes) { draw_grid_mesh(mesh); } glPopMatrix(); glMatrixMode(GL_PROJECTION); glPopMatrix(); } } // namespace viewer
#include "viewer/interaction/ui2d.hh" #include "logging/assert.hh" #include "viewer/projection.hh" #include <GL/glew.h> #include "viewer/gl_aliases.hh" namespace viewer { namespace { constexpr double Z_DIST = -0.1; void draw_pointer_targets(const std::vector<PointerTarget> &pointer_targets, const Projection &proj, const CharacterLibrary &char_lib) { glPushMatrix(); glPointSize(6.0); glColor3d(1.0, 1.0, 1.0); for (const auto &target : pointer_targets) { const auto screen_pt = proj.project(target.world_pos); glBegin(GL_POINTS); { glVertex3d(screen_pt.point.x(), screen_pt.point.y(), Z_DIST); } glEnd(); glLineWidth(0.3); glBegin(GL_LINE_STRIP); { glVertex3d(screen_pt.point.x(), screen_pt.point.y(), Z_DIST); glVertex3d(target.location.point.x(), target.location.point.y(), Z_DIST); } glEnd(); glTranslated(target.location.point.x(), target.location.point.y(), Z_DIST); write_string(target.text, char_lib); } glPopMatrix(); } PlotRange compute_plot_range(const LinePlot2d &line_plot) { PlotRange range; for (const auto &subplot_pair : line_plot.subplots) { const auto &subplot = subplot_pair.second; for (const auto &pt : subplot.points) { range.y_max = std::max(range.y_max, pt.y()); range.y_min = std::min(range.y_min, pt.y()); range.x_max = std::max(range.x_max, pt.x()); range.x_min = std::min(range.x_min, pt.x()); } } if (line_plot.plot_range.x_max != line_plot.plot_range.x_min) { range.x_max = line_plot.plot_range.x_max; range.x_min = line_plot.plot_range.x_min; } if (line_plot.plot_range.y_max != line_plot.plot_range.y_min) { range.y_max = line_plot.plot_range.y_max; range.y_min = line_plot.plot_range.y_min; } return range; } void draw_lineplot(const LinePlot2d &line_plot, const Projection &proj, const CharacterLibrary &char_lib) { glPushMatrix(); glPushAttrib(GL_CURRENT_BIT | GL_LINE_BIT); constexpr double X_OFFSET = 0.2; glTranslated(X_OFFSET, 0.2, 0.0); const double aspect = static_cast<double>(proj.viewport_size().width) / proj.viewport_size().height; glColor4d(0.6, 0.6, 0.6, 0.6); glBegin(GL_QUADS); const double field_y_max = 0.5; const double field_y_min = -0.5; const double field_x_min = 0.0; const double field_x_max = (aspect - X_OFFSET); glVertex3d(field_x_min, field_y_min, -0.9); glVertex3d(field_x_max, field_y_min, -0.9); glVertex3d(field_x_max, field_y_max, -0.9); glVertex3d(field_x_min, field_y_max, -0.9); glEnd(); const PlotRange range = compute_plot_range(line_plot); const double x_range = range.x_max - range.x_min; const double abs_y_max = std::max(std::abs(range.y_min), std::abs(range.y_max)); glEnable(GL_LINE_STIPPLE); for (const auto &subplot_pair : line_plot.subplots) { const auto &subplot = subplot_pair.second; glColor(subplot.color); if (subplot.dotted) { glLineStipple(1.0, 0x00FF); } else { glLineStipple(1.0, 0xFFFF); } glLineWidth(subplot.line_width); glBegin(GL_LINE_STRIP); for (const auto &pt : subplot.points) { const double x_val = field_x_max * (pt.x() - range.x_min) / x_range; const double y_val = field_y_max * pt.y() / abs_y_max; glVertex(jcc::Vec2(x_val, y_val)); } glEnd(); } glLineStipple(1, 0x00FF); glLineWidth(1.0); glBegin(GL_LINES); { glColor4d(1.0, 0.0, 0.0, 0.8); glVertex3d(field_x_min, 0.0, 0.5); glVertex3d(field_x_max, 0.0, 0.5); glColor4d(0.0, 1.0, 0.0, 0.8); const double x_origin = (0.0 - range.x_min) / x_range; glVertex3d(x_origin, field_y_min, 0.5); glVertex3d(x_origin, field_y_max, 0.5); } glEnd(); glTranslated(0.0, field_y_max + 0.05, 0.0); const std::string max_txt = line_plot.plot_title + "\nMax: " + std::to_string(abs_y_max); write_string(max_txt, char_lib, 0.5); glPopAttrib(); glPopMatrix(); } void draw_image(const Image &image, const Projection &proj, const CharacterLibrary &char_lib) { glPushMatrix(); glEnable(GL_TEXTURE_2D); if (!image.texture.ready()) { // // We want the *height* of the texture to be 1.0 // const double width_per_height = image.image.cols / static_cast<double>(image.image.rows); const jcc::Vec2 size(width_per_height, 1.0); image.texture = SmartTexture(size); image.texture.tex_image_2d(GL_TEXTURE_2D, 0, GL_RGB, image.image.cols, image.image.rows, 0, GL_BGR, GL_UNSIGNED_BYTE, image.image.data); } glTranslated(0.0, 0.0, -0.8); image.texture.draw(); glDisable(GL_TEXTURE_2D); glPopMatrix(); } void draw_points(const std::vector<Point2d> points, const Projection &proj, const CharacterLibrary &char_lib) { for (const auto &pt : points) { glPointSize(pt.size); glBegin(GL_POINTS); glColor(pt.color); glVertex3d(pt.point.x(), 1.0 - pt.point.y(), 0.1); glEnd(); } } void draw_lines(const std::vector<Line2d> &lines, const Projection &proj, const CharacterLibrary &char_lib) { for (const auto &line : lines) { glLineWidth(line.line_width); glColor(line.color); glBegin(GL_LINES); glVertex3d(line.start.x(), 1.0 - line.start.y(), -0.2); glVertex3d(line.end.x(), 1.0 - line.end.y(), -0.2); glEnd(); } } void draw_grid_mesh(const GridMesh &mesh) { const auto &pts = mesh.vertices; const int width = mesh.width; constexpr double Z_DIST = -0.1; constexpr double Z_DIST_OUTLINE = 0.1; const int cols_per_row = mesh.vertices.size() / width; const int rows = width; glColor(mesh.color); glBegin(GL_QUADS); { for (int r = 0; r < rows - 1; ++r) { for (int c = 0; c < cols_per_row - 1; ++c) { const int tl = c + (r * cols_per_row); const int tr = c + 1 + (r * cols_per_row); const int br = c + 1 + ((r + 1) * cols_per_row); const int bl = c + ((r + 1) * cols_per_row); glVertex3d(pts[tl].x(), 1.0 - pts[tl].y(), Z_DIST); glVertex3d(pts[tr].x(), 1.0 - pts[tr].y(), Z_DIST); glVertex3d(pts[br].x(), 1.0 - pts[br].y(), Z_DIST); glVertex3d(pts[bl].x(), 1.0 - pts[bl].y(), Z_DIST); } } glEnd(); } { glColor4d(0.1, 0.8, 0.1, 0.8); glLineWidth(1.0); for (int r = 0; r < rows - 1; ++r) { for (int c = 0; c < cols_per_row - 1; ++c) { const int tl = c + (r * cols_per_row); const int tr = c + 1 + (r * cols_per_row); const int br = c + 1 + ((r + 1) * cols_per_row); const int bl = c + ((r + 1) * cols_per_row); glBegin(GL_LINE_LOOP); glVertex3d(pts[tl].x(), 1.0 - pts[tl].y(), Z_DIST_OUTLINE); glVertex3d(pts[tr].x(), 1.0 - pts[tr].y(), Z_DIST_OUTLINE); glVertex3d(pts[br].x(), 1.0 - pts[br].y(), Z_DIST_OUTLINE); glVertex3d(pts[bl].x(), 1.0 - pts[bl].y(), Z_DIST_OUTLINE); glEnd(); } } } } } // namespace void Ui2d::add_pointer_target(const PointerTarget &pointer_target) { const std::lock_guard<std::mutex> lk(draw_mutex_); back_buffer_.pointer_targets.push_back(pointer_target); } void Ui2d::add_lineplot(const LinePlot2d &line_plot) { const std::lock_guard<std::mutex> lk(draw_mutex_); back_buffer_.line_plots.push_back(line_plot); } void Ui2d::add_grid_mesh(const GridMesh &grid_mesh) { const std::lock_guard<std::mutex> lk(draw_mutex_); JASSERT_GT(grid_mesh.width, 1, "Grid width must be greater 1"); JASSERT_FALSE(grid_mesh.vertices.empty(), "Grid cannot be empty."); JASSERT_EQ(grid_mesh.vertices.size() % grid_mesh.width, 0u, "Grid size must be divisible by width"); back_buffer_.grid_meshes.push_back(grid_mesh); } void Ui2d::clear() { const std::lock_guard<std::mutex> lk(draw_mutex_); back_buffer_.clear(); front_buffer_.clear(); } void Ui2d::flip() { const std::lock_guard<std::mutex> lk(draw_mutex_); front_buffer_ = std::move(back_buffer_); } void Ui2d::flush() { const std::lock_guard<std::mutex> lk(draw_mutex_); const auto insert = [](auto &into, const auto &from) { into.insert(into.begin(), from.begin(), from.end()); }; insert(front_buffer_.pointer_targets, back_buffer_.pointer_targets); insert(front_buffer_.line_plots, back_buffer_.line_plots); insert(front_buffer_.images, back_buffer_.images); insert(front_buffer_.points, back_buffer_.points); insert(front_buffer_.grid_meshes, back_buffer_.grid_meshes); insert(front_buffer_.lines, back_buffer_.lines); } void Ui2d::draw() const { const std::lock_guard<std::mutex> lk(draw_mutex_); // Create the character library when it's renderin' time if (char_lib_.size() == 0u) { char_lib_ = create_text_library(); } const auto proj = Projection::get_from_current(); glMatrixMode(GL_PROJECTION); glPushMatrix(); glLoadIdentity(); const double width = static_cast<double>(proj.viewport_size().width); const double height = static_cast<double>(proj.viewport_size().height); const double aspect_ratio = width / height; glOrtho(-aspect_ratio, aspect_ratio, -1.0, 1.0, -1.0, 1.0); glMatrixMode(GL_MODELVIEW); glPushMatrix(); glLoadIdentity(); draw_pointer_targets(front_buffer_.pointer_targets, proj, char_lib_); for (const auto &line_plot : front_buffer_.line_plots) { draw_lineplot(line_plot, proj, char_lib_); } draw_points(front_buffer_.points, proj, char_lib_); draw_lines(front_buffer_.lines, proj, char_lib_); for (const auto &mesh : front_buffer_.grid_meshes) { draw_grid_mesh(mesh); } for (const auto &image : front_buffer_.images) { draw_image(image, proj, char_lib_); } glPopMatrix(); glMatrixMode(GL_PROJECTION); glPopMatrix(); } } // namespace viewer
Fix location of mesh2d y axis
Fix location of mesh2d y axis
C++
mit
jpanikulam/experiments,jpanikulam/experiments,jpanikulam/experiments,jpanikulam/experiments
23ec737536249f5822b1a6c5e4ab8a805e8dbfbb
src/apps/calibrate_radiometric_response/calibrate_radiometric_response.cpp
src/apps/calibrate_radiometric_response/calibrate_radiometric_response.cpp
/****************************************************************************** * Copyright (c) 2016-2017 Sergey Alexandrov * * 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 <cmath> #include <fstream> #include <iostream> #include <string> #include <vector> #include <boost/filesystem.hpp> #include <opencv2/core/core.hpp> #include <opencv2/highgui/highgui.hpp> #include <opencv2/imgproc/imgproc.hpp> #include <radical/radiometric_response.h> #include "grabbers/grabber.h" #include "utils/arrange_images_in_grid.h" #include "utils/plot_histogram.h" #include "utils/plot_radiometric_response.h" #include "utils/program_options.h" #include "calibration.h" #include "dataset.h" #include "dataset_collection.h" #include "engel_calibration.h" #if HAVE_CERES #include "debevec_calibration.h" #define DEFAULT_METHOD "debevec" #else #define DEFAULT_METHOD "engel" #endif class Options : public OptionsBase { public: std::string data_source = ""; std::string output; double convergence_threshold = 1e-5; std::string calibration_method = DEFAULT_METHOD; bool no_visualization = false; std::string save_dataset = ""; DatasetCollection::Parameters dc; unsigned int verbosity = 1; unsigned int min_samples = 5; bool interactive = false; double smoothing = 50; bool print = false; protected: virtual void addOptions(boost::program_options::options_description& desc) override { namespace po = boost::program_options; desc.add_options()("output,o", po::value<std::string>(&output), "Output filename with calibrated response function (default: camera model name + \".\" + camera " "serial number + \".crf\" suffix)"); desc.add_options()("threshold,t", po::value<double>(&convergence_threshold), "Threshold for energy update after which convergence is declared (default: 1e-5)"); desc.add_options()("method,m", po::value<std::string>(&calibration_method)->default_value(calibration_method), "Calibration method to use"); desc.add_options()("min-samples", po::value<unsigned int>(&min_samples)->default_value(min_samples), "Min number of samples per intensity level (only for debevec method)"); desc.add_options()("smoothing", po::value<double>(&smoothing)->default_value(smoothing), "Smoothing lambda (only for debevec method)"); desc.add_options()("no-visualization", po::bool_switch(&no_visualization), "Do not visualize the calibration process and results"); desc.add_options()("verbosity,v", po::value<unsigned int>(&verbosity)->default_value(verbosity), "Verbosity level (0 - silent, 1 - normal, 2 - verbose)"); desc.add_options()("interactive", po::bool_switch(&interactive), "Wait for a keypress after each optimization iteration"); desc.add_options()("print", po::bool_switch(&print), "Print calibrated response function to stdout"); boost::program_options::options_description dcopt("Data collection"); dcopt.add_options()("exposure-min", po::value<int>(&dc.exposure_min), "Minimum exposure (default: depends on the camera)"); dcopt.add_options()("exposure-max", po::value<int>(&dc.exposure_max), "Maximum exposure (default: depends on the camera)"); dcopt.add_options()("factor,f", po::value<float>(&dc.exposure_factor), "Multiplication factor for exposure (default: to cover desired exposure range in 30 steps)"); dcopt.add_options()("average,a", po::value<unsigned int>(&dc.num_average_frames)->default_value(dc.num_average_frames), "Number of consecutive frames to average into each image"); dcopt.add_options()("images,i", po::value<unsigned int>(&dc.num_images)->default_value(dc.num_images), "Number of images to take at each exposure setting"); dcopt.add_options()("lag,l", po::value<unsigned int>(&dc.exposure_control_lag)->default_value(dc.exposure_control_lag), "Number of frames to skip after changing exposure setting"); dcopt.add_options()("valid-min", po::value<unsigned int>(&dc.valid_intensity_min)->default_value(dc.valid_intensity_min), "Minimum valid intensity value of the sensor"); dcopt.add_options()("valid-max", po::value<unsigned int>(&dc.valid_intensity_max)->default_value(dc.valid_intensity_max), "Maximum valid intensity value of the sensor"); dcopt.add_options()("bloom-radius", po::value<unsigned int>(&dc.bloom_radius)->default_value(dc.bloom_radius), "Radius of the blooming effect"); dcopt.add_options()("save-dataset,s", po::value<std::string>(&save_dataset), "Save collected dataset in the given directory"); desc.add(dcopt); } virtual void addPositional(boost::program_options::options_description& desc, boost::program_options::positional_options_description& positional) override { namespace po = boost::program_options; desc.add_options()("data-source", po::value<std::string>(&data_source), "Data source, either a camera (\"asus\", \"intel\"), or a path to dataset"); positional.add("data-source", -1); } virtual void printHelp() override { std::cout << "Usage: calibrate_radiometric_response [options] <data-source>" << std::endl; std::cout << "" << std::endl; std::cout << "Calibrate radiometric response of a camera. Two algorithms are available:" << std::endl; std::cout << " * Engel et al. (A Photometrically Calibrated Benchmark For Monocular Visual Odometry)" << std::endl; std::cout << " * Debevec and Malik (Recovering High Dynamic Range Radiance Maps from Photographs)" << std::endl; std::cout << "" << std::endl; std::cout << "Working range of the sensor can be specified with --valid-min/--valid-max options." << std::endl; std::cout << "Pixels with intensity values outside this range do not contribute to the energy and" << std::endl; std::cout << "irradiance computation, however radiometric response is estimated for them as well." << std::endl; std::cout << "" << std::endl; } virtual void validate() override { if (dc.valid_intensity_max > 255) { throw boost::program_options::error("maximum valid intensity can not exceed 255"); } if (dc.valid_intensity_min > 255) { throw boost::program_options::error("minimum valid intensity can not exceed 255"); } } }; int main(int argc, const char** argv) { Options options; if (!options.parse(argc, argv)) return 1; auto imshow = [&options](const cv::Mat& image, int w = -1) { if (!options.no_visualization) { cv::imshow("Calibration", image); cv::waitKey(w); } }; auto data = Dataset::load(options.data_source); if (data) { if (!options("output")) { auto dir = boost::filesystem::canonical(options.data_source); options.output = (dir / dir.filename()).string() + ".crf"; } if (options.verbosity) std::cout << "Loaded dataset from: " << options.data_source << std::endl; auto hist = data->computeIntensityHistogram(); imshow(utils::plotHistogram(hist.rowRange(options.dc.valid_intensity_min, options.dc.valid_intensity_max), 2, 256)); } else { grabbers::Grabber::Ptr grabber; try { grabber = grabbers::createGrabber(options.data_source); } catch (grabbers::GrabberException&) { std::cerr << "Failed to create a grabber" << (options.data_source != "" ? " for camera " + options.data_source : "") << std::endl; return 1; } grabber->setAutoExposureEnabled(false); grabber->setAutoWhiteBalanceEnabled(false); if (!options("output")) options.output = grabber->getCameraUID() + ".crf"; if (!options("exposure-min")) options.dc.exposure_min = grabber->getExposureRange().first; if (!options("exposure-max")) options.dc.exposure_max = grabber->getExposureRange().second; if (!options("factor")) options.dc.exposure_factor = std::pow(1.0f * options.dc.exposure_max / options.dc.exposure_min, 1.0f / 30); // Change exposure to requested min value, wait some time until it works cv::Mat frame; for (size_t i = 0; i < 100; ++i) { grabber->grabFrame(frame); imshow(frame, 30); grabber->setExposure(options.dc.exposure_min); } DatasetCollection data_collection(grabber, options.dc); cv::Mat histogram(480, 640, CV_8UC3); while (grabber->hasMoreFrames()) { grabber->grabFrame(frame); if (data_collection.addFrame(frame)) break; auto hist = data_collection.getDataset()->computeIntensityHistogram(); histogram.setTo(0); utils::plotHistogram(hist.rowRange(options.dc.valid_intensity_min, options.dc.valid_intensity_max), histogram); imshow(arrangeImagesInGrid({frame, histogram}, {1, 2}), 30); } data = data_collection.getDataset(); if (options.save_dataset != "") { if (options.verbosity) std::cout << "Saving dataset to: " << options.save_dataset << std::endl; data->save(options.save_dataset); std::ofstream file(options.save_dataset + "/DESCRIPTION.txt"); if (file.is_open()) { file << "Camera: " << grabber->getCameraUID() << std::endl; file << "Resolution: " << data->getImageSize() << std::endl; file << "Exposure range: " << options.dc.exposure_min << " " << options.dc.exposure_max << std::endl; file << "Exposure factor: " << options.dc.exposure_factor << std::endl; file << "Images per exposure time: " << options.dc.num_images << std::endl; file << "Frames averaged into an image: " << options.dc.num_average_frames << std::endl; file.close(); } } } Calibration::Ptr calibration; if (options.calibration_method == "engel") { auto cal = std::make_shared<EngelCalibration>(); cal->setConvergenceThreshold(options.convergence_threshold); calibration = cal; } else if (options.calibration_method == "debevec") { #if HAVE_CERES auto cal = std::make_shared<DebevecCalibration>(); cal->setMinSamplesPerIntensityLevel(options.min_samples); cal->setSmoothingLambda(options.smoothing); calibration = cal; #else std::cerr << "Debevec calibration is not supported because the project was compiled without Ceres.\n"; return 2; #endif } else { std::cerr << "Unknown calibration method: " << options.calibration_method << ". Please specify \"engel\" or \"debevec\".\n"; return 1; } auto limshow = [=](const cv::Mat& image) { cv::imshow("Calibration", image); cv::waitKey(options.interactive ? -1 : 1); }; calibration->setValidPixelRange(static_cast<unsigned char>(options.dc.valid_intensity_min), static_cast<unsigned char>(options.dc.valid_intensity_max)); calibration->setVerbosity(options.verbosity); if (!options.no_visualization) calibration->setVisualizeProgress(limshow); cv::Mat response = calibration->calibrate(*data); if (options.verbosity) std::cout << "Done, writing response to: " << options.output << std::endl; radical::RadiometricResponse rr(response); rr.save(options.output); imshow(utils::plotRadiometricResponse(rr)); if (options.print) { std::vector<cv::Mat> response_channels; cv::split(response, response_channels); for (const auto& ch : response_channels) { for (int i = 0; i < static_cast<int>(ch.total()); ++i) std::cout << ch.at<float>(i) << " "; std::cout << std::endl; } } return 0; }
/****************************************************************************** * Copyright (c) 2016-2017 Sergey Alexandrov * * 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 <cmath> #include <fstream> #include <iostream> #include <string> #include <vector> #include <boost/filesystem.hpp> #include <opencv2/core/core.hpp> #include <opencv2/highgui/highgui.hpp> #include <opencv2/imgproc/imgproc.hpp> #include <radical/radiometric_response.h> #include "grabbers/grabber.h" #include "utils/arrange_images_in_grid.h" #include "utils/plot_histogram.h" #include "utils/plot_radiometric_response.h" #include "utils/program_options.h" #include "calibration.h" #include "dataset.h" #include "dataset_collection.h" #include "engel_calibration.h" #if HAVE_CERES #include "debevec_calibration.h" #define DEFAULT_METHOD "debevec" #else #define DEFAULT_METHOD "engel" #endif class Options : public OptionsBase { public: std::string data_source = ""; std::string output; double convergence_threshold = 1e-5; std::string calibration_method = DEFAULT_METHOD; bool no_visualization = false; std::string save_dataset = ""; DatasetCollection::Parameters dc; unsigned int verbosity = 1; unsigned int min_samples = 5; bool interactive = false; double smoothing = 50; bool print = false; protected: virtual void addOptions(boost::program_options::options_description& desc) override { namespace po = boost::program_options; desc.add_options()("output,o", po::value<std::string>(&output), "Output filename with calibrated response function (default: camera model name + \".\" + camera " "serial number + \".crf\" suffix)"); desc.add_options()("threshold,t", po::value<double>(&convergence_threshold), "Threshold for energy update after which convergence is declared (default: 1e-5)"); desc.add_options()("method,m", po::value<std::string>(&calibration_method)->default_value(calibration_method), "Calibration method to use"); desc.add_options()("min-samples", po::value<unsigned int>(&min_samples)->default_value(min_samples), "Min number of samples per intensity level (only for debevec method)"); desc.add_options()("smoothing", po::value<double>(&smoothing)->default_value(smoothing), "Smoothing lambda (only for debevec method)"); desc.add_options()("no-visualization", po::bool_switch(&no_visualization), "Do not visualize the calibration process and results"); desc.add_options()("verbosity,v", po::value<unsigned int>(&verbosity)->default_value(verbosity), "Verbosity level (0 - silent, 1 - normal, 2 - verbose)"); desc.add_options()("interactive", po::bool_switch(&interactive), "Wait for a keypress after each optimization iteration"); desc.add_options()("print", po::bool_switch(&print), "Print calibrated response function to stdout"); boost::program_options::options_description dcopt("Data collection"); dcopt.add_options()("exposure-min", po::value<int>(&dc.exposure_min), "Minimum exposure (default: depends on the camera)"); dcopt.add_options()("exposure-max", po::value<int>(&dc.exposure_max), "Maximum exposure (default: depends on the camera)"); dcopt.add_options()("factor,f", po::value<float>(&dc.exposure_factor), "Multiplication factor for exposure (default: to cover desired exposure range in 30 steps)"); dcopt.add_options()("average,a", po::value<unsigned int>(&dc.num_average_frames)->default_value(dc.num_average_frames), "Number of consecutive frames to average into each image"); dcopt.add_options()("images,i", po::value<unsigned int>(&dc.num_images)->default_value(dc.num_images), "Number of images to take at each exposure setting"); dcopt.add_options()("lag,l", po::value<unsigned int>(&dc.exposure_control_lag)->default_value(dc.exposure_control_lag), "Number of frames to skip after changing exposure setting"); dcopt.add_options()("valid-min", po::value<unsigned int>(&dc.valid_intensity_min)->default_value(dc.valid_intensity_min), "Minimum valid intensity value of the sensor"); dcopt.add_options()("valid-max", po::value<unsigned int>(&dc.valid_intensity_max)->default_value(dc.valid_intensity_max), "Maximum valid intensity value of the sensor"); dcopt.add_options()("bloom-radius", po::value<unsigned int>(&dc.bloom_radius)->default_value(dc.bloom_radius), "Radius of the blooming effect"); dcopt.add_options()("save-dataset,s", po::value<std::string>(&save_dataset), "Save collected dataset in the given directory"); desc.add(dcopt); } virtual void addPositional(boost::program_options::options_description& desc, boost::program_options::positional_options_description& positional) override { namespace po = boost::program_options; desc.add_options()("data-source", po::value<std::string>(&data_source), "Data source, either a camera (\"asus\", \"intel\"), or a path to dataset"); positional.add("data-source", -1); } virtual void printHelp() override { std::cout << "Usage: calibrate_radiometric_response [options] <data-source>" << std::endl; std::cout << "" << std::endl; std::cout << "Calibrate radiometric response of a camera. Two algorithms are available:" << std::endl; std::cout << " * Engel et al. (A Photometrically Calibrated Benchmark For Monocular Visual Odometry)" << std::endl; std::cout << " * Debevec and Malik (Recovering High Dynamic Range Radiance Maps from Photographs)" << std::endl; std::cout << "" << std::endl; std::cout << "Working range of the sensor can be specified with --valid-min/--valid-max options." << std::endl; std::cout << "Pixels with intensity values outside this range do not contribute to the energy and" << std::endl; std::cout << "irradiance computation, however radiometric response is estimated for them as well." << std::endl; std::cout << "" << std::endl; } virtual void validate() override { if (dc.valid_intensity_max > 255) { throw boost::program_options::error("maximum valid intensity can not exceed 255"); } if (dc.valid_intensity_min > 255) { throw boost::program_options::error("minimum valid intensity can not exceed 255"); } } }; int main(int argc, const char** argv) { Options options; if (!options.parse(argc, argv)) return 1; auto imshow = [&options](const cv::Mat& image, int w = -1) { if (!options.no_visualization) { cv::imshow("Calibration", image); cv::waitKey(w); } }; auto data = Dataset::load(options.data_source); if (data) { if (!options("output")) { auto dir = boost::filesystem::canonical(options.data_source); options.output = (dir / dir.filename()).string() + ".crf"; } if (options.verbosity) std::cout << "Loaded dataset from: " << options.data_source << std::endl; auto hist = data->computeIntensityHistogram(); imshow(utils::plotHistogram(hist.rowRange(options.dc.valid_intensity_min, options.dc.valid_intensity_max), 2, 256)); } else { grabbers::Grabber::Ptr grabber; try { grabber = grabbers::createGrabber(options.data_source); } catch (grabbers::GrabberException&) { std::cerr << "Failed to create a grabber" << (options.data_source != "" ? " for camera " + options.data_source : "") << std::endl; return 1; } if (!options("output")) options.output = grabber->getCameraUID() + ".crf"; if (!options("exposure-min")) options.dc.exposure_min = grabber->getExposureRange().first; if (!options("exposure-max")) options.dc.exposure_max = grabber->getExposureRange().second; if (!options("factor")) options.dc.exposure_factor = std::pow(1.0f * options.dc.exposure_max / options.dc.exposure_min, 1.0f / 30); cv::Mat frame; // Disable AEC but enable AWB so that colors are balanced grabber->setAutoExposureEnabled(false); grabber->setAutoWhiteBalanceEnabled(true); // Wait grabber->grabFrame(frame); imshow(frame, 400); // Disable AWB grabber->setAutoWhiteBalanceEnabled(false); // Change exposure to requested min value, wait some time until it works for (size_t i = 0; i < 12; ++i) { grabber->grabFrame(frame); imshow(frame, 400); grabber->setExposure(options.dc.exposure_min); } DatasetCollection data_collection(grabber, options.dc); cv::Mat histogram(480, 640, CV_8UC3); while (grabber->hasMoreFrames()) { grabber->grabFrame(frame); if (data_collection.addFrame(frame)) break; auto hist = data_collection.getDataset()->computeIntensityHistogram(); histogram.setTo(0); utils::plotHistogram(hist.rowRange(options.dc.valid_intensity_min, options.dc.valid_intensity_max), histogram); imshow(arrangeImagesInGrid({frame, histogram}, {1, 2}), 30); } data = data_collection.getDataset(); if (options.save_dataset != "") { if (options.verbosity) std::cout << "Saving dataset to: " << options.save_dataset << std::endl; data->save(options.save_dataset); std::ofstream file(options.save_dataset + "/DESCRIPTION.txt"); if (file.is_open()) { file << "Camera: " << grabber->getCameraUID() << std::endl; file << "Resolution: " << data->getImageSize() << std::endl; file << "Exposure range: " << options.dc.exposure_min << " " << options.dc.exposure_max << std::endl; file << "Exposure factor: " << options.dc.exposure_factor << std::endl; file << "Images per exposure time: " << options.dc.num_images << std::endl; file << "Frames averaged into an image: " << options.dc.num_average_frames << std::endl; file.close(); } } } Calibration::Ptr calibration; if (options.calibration_method == "engel") { auto cal = std::make_shared<EngelCalibration>(); cal->setConvergenceThreshold(options.convergence_threshold); calibration = cal; } else if (options.calibration_method == "debevec") { #if HAVE_CERES auto cal = std::make_shared<DebevecCalibration>(); cal->setMinSamplesPerIntensityLevel(options.min_samples); cal->setSmoothingLambda(options.smoothing); calibration = cal; #else std::cerr << "Debevec calibration is not supported because the project was compiled without Ceres.\n"; return 2; #endif } else { std::cerr << "Unknown calibration method: " << options.calibration_method << ". Please specify \"engel\" or \"debevec\".\n"; return 1; } auto limshow = [=](const cv::Mat& image) { cv::imshow("Calibration", image); cv::waitKey(options.interactive ? -1 : 1); }; calibration->setValidPixelRange(static_cast<unsigned char>(options.dc.valid_intensity_min), static_cast<unsigned char>(options.dc.valid_intensity_max)); calibration->setVerbosity(options.verbosity); if (!options.no_visualization) calibration->setVisualizeProgress(limshow); cv::Mat response = calibration->calibrate(*data); if (options.verbosity) std::cout << "Done, writing response to: " << options.output << std::endl; radical::RadiometricResponse rr(response); rr.save(options.output); imshow(utils::plotRadiometricResponse(rr)); if (options.print) { std::vector<cv::Mat> response_channels; cv::split(response, response_channels); for (const auto& ch : response_channels) { for (int i = 0; i < static_cast<int>(ch.total()); ++i) std::cout << ch.at<float>(i) << " "; std::cout << std::endl; } } return 0; }
Enable AWB for a short time in the beginning of data collection
Enable AWB for a short time in the beginning of data collection Additionally change the way shortest exposure time is enabled. Make less requests with longer pauses in between, otherwise some RealSense cameras might fail.
C++
mit
taketwo/radical,taketwo/radical,taketwo/radical
879c773972632c59185a9dc8318fb2f78160c457
Code/GraphMol/FragCatalog/FragCatalogUtils.cpp
Code/GraphMol/FragCatalog/FragCatalogUtils.cpp
// $Id$ // // Copyright (C) 2003-2006 Rational Discovery LLC // // @@ All Rights Reserved @@ // // REVIEW: move this to a GraphMol/FuncGroups directory #include <RDGeneral/BadFileException.h> #include "FragCatalogUtils.h" #include <GraphMol/Subgraphs/Subgraphs.h> #include <GraphMol/Subgraphs/SubgraphUtils.h> #include <fstream> #include <string> #include <GraphMol/SmilesParse/SmilesParse.h> #include <boost/tokenizer.hpp> typedef boost::tokenizer<boost::char_separator<char> > tokenizer; #include <boost/algorithm/string.hpp> namespace RDKit { // local utility namespace namespace { ROMol * getSmarts(const std::string &tmpStr) { ROMol *mol = 0; if (tmpStr.length() == 0) { // empty line return mol; } if (tmpStr.substr(0,2) == "//") { // comment line return mol; } boost::char_separator<char> tabSep("\t"); tokenizer tokens(tmpStr,tabSep); tokenizer::iterator token=tokens.begin(); // name of the functional groups std::string name = *token; boost::erase_all(name," "); ++token; // grab the smarts: std::string smarts = *token; boost::erase_all(smarts," "); ++token; mol = SmartsToMol(smarts); CHECK_INVARIANT(mol,smarts); mol->setProp("_Name", name); mol->setProp("_fragSMARTS",smarts); return mol; } } // end of local utility namespace MOL_SPTR_VECT readFuncGroups(std::istream &inStream,int nToRead) { MOL_SPTR_VECT funcGroups; funcGroups.clear(); if (inStream.bad()) { throw BadFileException("Bad stream contents."); } const int MAX_LINE_LEN = 512; char inLine[MAX_LINE_LEN]; std::string tmpstr; int nRead=0; while (!inStream.eof() && (nToRead<0 || nRead<nToRead)) { inStream.getline(inLine, MAX_LINE_LEN,'\n'); tmpstr = inLine; // parse the molecule on this line (if there is one) ROMol *mol = getSmarts(tmpstr); if (mol) { funcGroups.push_back(ROMOL_SPTR(mol)); nRead++; } } return funcGroups; } MOL_SPTR_VECT readFuncGroups(std::string fileName) { std::ifstream inStream(fileName.c_str()); if ((!inStream) || (inStream.bad()) ) { std::ostringstream errout; errout << "Bad input file " << fileName; throw BadFileException(errout.str()); } MOL_SPTR_VECT funcGroups; funcGroups=readFuncGroups(inStream); return funcGroups; } MatchVectType findFuncGroupsOnMol(const ROMol &mol, const FragCatParams *params, INT_VECT &fgBonds) { PRECONDITION(params,"bad params"); fgBonds.clear(); // also assume int fid, nfgs = params->getNumFuncGroups(); std::pair<int, int> amat; MatchVectType aidFgrps; std::vector<MatchVectType> fgpMatches; std::vector<MatchVectType>::const_iterator mati; MatchVectType::const_iterator mi; int aid; //const ROMol *fgrp; INT_VECT_CI bi; aidFgrps.clear(); fid = 0; const MOL_SPTR_VECT &fgrps = params->getFuncGroups(); MOL_SPTR_VECT::const_iterator fgci; for (fgci = fgrps.begin(); fgci != fgrps.end(); fgci++) { const ROMol *fgrp = fgci->get(); std::string fname; (*fgci)->getProp("_Name", fname); //std::cout << "Groups number: " << fname << "\n"; //(*fgci)->debugMol(std::cout); //mol->debugMol(std::cout); // match this functional group onto the molecule SubstructMatch(mol, *fgrp, fgpMatches); // loop over all the matches we get for this fgroup for (mati = fgpMatches.begin(); mati != fgpMatches.end(); mati++) { //FIX: we will assume that the first atom in fgrp is always the connection // atom amat = mati->front(); aid = amat.second; //FIX: is this correct - the second entry in the pair is the atom ID from mol // grab the list of atom Ids from mol that match the functional group INT_VECT bondIds, maids; for (mi = mati->begin(); mi != mati->end(); mi++) { maids.push_back(mi->second); } // create a list of bond IDs from these atom ID // these are the bond in mol that are part of portion that matches the // functional group bondIds = Subgraphs::bondListFromAtomList(mol, maids); // now check if all these bonds have been covered as part of larger // functional group that was dealt with earlier // FIX: obviously we assume here that the function groups in params // come in decreasing order of size. bool allDone = true; for (bi = bondIds.begin(); bi != bondIds.end(); bi++) { if (std::find(fgBonds.begin(), fgBonds.end(), (*bi)) == fgBonds.end()) { allDone = false; fgBonds.push_back(*bi); } } if (!allDone) { // this functional group mapping onto mol is not part of a larger func // group mapping so record it aidFgrps.push_back(std::pair<int, int>(aid, fid)); } } fid++; } return aidFgrps; } ROMol *prepareMol(const ROMol &mol, const FragCatParams *fparams, MatchVectType &aToFmap) { PRECONDITION(fparams,""); // get a mapping of the functional groups onto the molecule INT_VECT fgBonds; MatchVectType aidToFid = findFuncGroupsOnMol(mol, fparams, fgBonds); // get the core piece of molecule (i.e. the part of the molecule // without the functional groups). This basically the part of the molecule // that does not contain the function group bonds given by "fgBonds" INT_VECT cBonds; int bid, nbds = mol.getNumBonds(); for (bid = 0; bid < nbds; bid++) { if (std::find(fgBonds.begin(), fgBonds.end(), bid) == fgBonds.end()) { cBonds.push_back(bid); } } INT_MAP_INT aIdxMap; // a map from atom id in mol to the new atoms id in coreMol ROMol *coreMol = Subgraphs::PathToSubmol(mol, cBonds, false, aIdxMap); // now map the functional groups on mol to coreMol using aIdxMap MatchVectType::iterator mati; int newID; for (mati = aidToFid.begin(); mati != aidToFid.end(); mati++) { newID = aIdxMap[mati->first]; aToFmap.push_back(std::pair<int, int>(newID, mati->second)); } return coreMol; } }
// $Id$ // // Copyright (C) 2003-2006 Rational Discovery LLC // // @@ All Rights Reserved @@ // // REVIEW: move this to a GraphMol/FuncGroups directory #include <RDGeneral/BadFileException.h> #include "FragCatalogUtils.h" #include <GraphMol/Subgraphs/Subgraphs.h> #include <GraphMol/Subgraphs/SubgraphUtils.h> #include <fstream> #include <string> #include <GraphMol/SmilesParse/SmilesParse.h> #include <boost/tokenizer.hpp> typedef boost::tokenizer<boost::char_separator<char> > tokenizer; #include <boost/algorithm/string.hpp> namespace RDKit { // local utility namespace namespace { ROMol * getSmarts(const std::string &tmpStr) { ROMol *mol = 0; if (tmpStr.length() == 0) { // empty line return mol; } if (tmpStr.substr(0,2) == "//") { // comment line return mol; } boost::char_separator<char> tabSep("\t"); tokenizer tokens(tmpStr,tabSep); tokenizer::iterator token=tokens.begin(); // name of the functional groups std::string name = *token; boost::erase_all(name," "); ++token; // grab the smarts: std::string smarts = *token; boost::erase_all(smarts," "); ++token; mol = SmartsToMol(smarts); CHECK_INVARIANT(mol,smarts); mol->setProp("_Name", name); mol->setProp("_fragSMARTS",smarts); return mol; } } // end of local utility namespace MOL_SPTR_VECT readFuncGroups(std::istream &inStream,int nToRead) { MOL_SPTR_VECT funcGroups; funcGroups.clear(); if (inStream.bad()) { throw BadFileException("Bad stream contents."); } const int MAX_LINE_LEN = 512; char inLine[MAX_LINE_LEN]; std::string tmpstr; int nRead=0; while (!inStream.eof() && (nToRead<0 || nRead<nToRead)) { inStream.getline(inLine, MAX_LINE_LEN,'\n'); tmpstr = inLine; // parse the molecule on this line (if there is one) ROMol *mol = getSmarts(tmpstr); if (mol) { funcGroups.push_back(ROMOL_SPTR(mol)); nRead++; } } return funcGroups; } MOL_SPTR_VECT readFuncGroups(std::string fileName) { std::ifstream inStream(fileName.c_str()); if ((!inStream) || (inStream.bad()) ) { std::ostringstream errout; errout << "Bad input file " << fileName; throw BadFileException(errout.str()); } MOL_SPTR_VECT funcGroups; funcGroups=readFuncGroups(inStream); return funcGroups; } MatchVectType findFuncGroupsOnMol(const ROMol &mol, const FragCatParams *params, INT_VECT &fgBonds) { PRECONDITION(params,"bad params"); fgBonds.clear(); std::pair<int, int> amat; MatchVectType aidFgrps; std::vector<MatchVectType> fgpMatches; std::vector<MatchVectType>::const_iterator mati; MatchVectType::const_iterator mi; int aid; //const ROMol *fgrp; INT_VECT_CI bi; aidFgrps.clear(); int fid = 0; const MOL_SPTR_VECT &fgrps = params->getFuncGroups(); MOL_SPTR_VECT::const_iterator fgci; for (fgci = fgrps.begin(); fgci != fgrps.end(); fgci++) { const ROMol *fgrp = fgci->get(); std::string fname; (*fgci)->getProp("_Name", fname); //std::cout << "Groups number: " << fname << "\n"; //(*fgci)->debugMol(std::cout); //mol->debugMol(std::cout); // match this functional group onto the molecule SubstructMatch(mol, *fgrp, fgpMatches); // loop over all the matches we get for this fgroup for (mati = fgpMatches.begin(); mati != fgpMatches.end(); mati++) { //FIX: we will assume that the first atom in fgrp is always the connection // atom amat = mati->front(); aid = amat.second; //FIX: is this correct - the second entry in the pair is the atom ID from mol // grab the list of atom Ids from mol that match the functional group INT_VECT bondIds, maids; for (mi = mati->begin(); mi != mati->end(); mi++) { maids.push_back(mi->second); } // create a list of bond IDs from these atom ID // these are the bond in mol that are part of portion that matches the // functional group bondIds = Subgraphs::bondListFromAtomList(mol, maids); // now check if all these bonds have been covered as part of larger // functional group that was dealt with earlier // FIX: obviously we assume here that the function groups in params // come in decreasing order of size. bool allDone = true; for (bi = bondIds.begin(); bi != bondIds.end(); bi++) { if (std::find(fgBonds.begin(), fgBonds.end(), (*bi)) == fgBonds.end()) { allDone = false; fgBonds.push_back(*bi); } } if (!allDone) { // this functional group mapping onto mol is not part of a larger func // group mapping so record it aidFgrps.push_back(std::pair<int, int>(aid, fid)); } } fid++; } return aidFgrps; } ROMol *prepareMol(const ROMol &mol, const FragCatParams *fparams, MatchVectType &aToFmap) { PRECONDITION(fparams,""); // get a mapping of the functional groups onto the molecule INT_VECT fgBonds; MatchVectType aidToFid = findFuncGroupsOnMol(mol, fparams, fgBonds); // get the core piece of molecule (i.e. the part of the molecule // without the functional groups). This basically the part of the molecule // that does not contain the function group bonds given by "fgBonds" INT_VECT cBonds; int bid, nbds = mol.getNumBonds(); for (bid = 0; bid < nbds; bid++) { if (std::find(fgBonds.begin(), fgBonds.end(), bid) == fgBonds.end()) { cBonds.push_back(bid); } } INT_MAP_INT aIdxMap; // a map from atom id in mol to the new atoms id in coreMol ROMol *coreMol = Subgraphs::PathToSubmol(mol, cBonds, false, aIdxMap); // now map the functional groups on mol to coreMol using aIdxMap MatchVectType::iterator mati; int newID; for (mati = aidToFid.begin(); mati != aidToFid.end(); mati++) { newID = aIdxMap[mati->first]; aToFmap.push_back(std::pair<int, int>(newID, mati->second)); } return coreMol; } }
fix a compiler warning
fix a compiler warning
C++
bsd-3-clause
bp-kelley/rdkit,strets123/rdkit,bp-kelley/rdkit,AlexanderSavelyev/rdkit,rvianello/rdkit,adalke/rdkit,ptosco/rdkit,jandom/rdkit,greglandrum/rdkit,bp-kelley/rdkit,ptosco/rdkit,adalke/rdkit,AlexanderSavelyev/rdkit,strets123/rdkit,adalke/rdkit,rvianello/rdkit,adalke/rdkit,greglandrum/rdkit,bp-kelley/rdkit,rdkit/rdkit,AlexanderSavelyev/rdkit,jandom/rdkit,rvianello/rdkit,jandom/rdkit,rvianello/rdkit,soerendip42/rdkit,ptosco/rdkit,greglandrum/rdkit,jandom/rdkit,rdkit/rdkit,soerendip42/rdkit,bp-kelley/rdkit,rdkit/rdkit,strets123/rdkit,adalke/rdkit,adalke/rdkit,greglandrum/rdkit,soerendip42/rdkit,rdkit/rdkit,jandom/rdkit,rdkit/rdkit,AlexanderSavelyev/rdkit,AlexanderSavelyev/rdkit,rvianello/rdkit,adalke/rdkit,bp-kelley/rdkit,rvianello/rdkit,rdkit/rdkit,greglandrum/rdkit,strets123/rdkit,rvianello/rdkit,adalke/rdkit,ptosco/rdkit,strets123/rdkit,AlexanderSavelyev/rdkit,jandom/rdkit,AlexanderSavelyev/rdkit,AlexanderSavelyev/rdkit,greglandrum/rdkit,ptosco/rdkit,bp-kelley/rdkit,soerendip42/rdkit,strets123/rdkit,strets123/rdkit,ptosco/rdkit,soerendip42/rdkit,jandom/rdkit,rdkit/rdkit,ptosco/rdkit,AlexanderSavelyev/rdkit,greglandrum/rdkit,jandom/rdkit,rdkit/rdkit,greglandrum/rdkit,bp-kelley/rdkit,ptosco/rdkit,strets123/rdkit,soerendip42/rdkit,soerendip42/rdkit,rvianello/rdkit,soerendip42/rdkit
26b91a725d04ddeb7eb939271069634e5e1929ed
raytracer.cpp
raytracer.cpp
#include "lib/output.h" #include "lib/image.h" #include "lib/intersection.h" #include "lib/lambertian.h" #include "lib/range.h" #include "lib/types.h" #include <assimp/Importer.hpp> // C++ importer interface #include <assimp/scene.h> // Output data structure #include <assimp/postprocess.h> // Post processing flags #include <math.h> #include <vector> #include <iostream> // // Convert 2d raster coodinates into 3d cameras coordinates. // // We assume that the camera is trivial: // assert(cam.mPosition == aiVector3D(0, 0, 0)); // assert(cam.mUp == aiVector3D(0, 1, 0)); // assert(cam.mLookAt == aiVector3D(0, 0, -1)); // assert(cam.mAspect != 0) { // // The positioning of the camera is done in its parent's node transformation // matrix. // aiVector3D raster2cam( const aiCamera& cam, const aiVector2D& p, const int w, const int h) { float delta_x = tan(cam.mHorizontalFOV / 2.); float delta_y = delta_x / cam.mAspect; return aiVector3D( -delta_x * (1 - 2 * p.x / static_cast<float>(w)), delta_y * (1 - 2 * p.y / static_cast<float>(h)), -1); } ssize_t ray_intersection(const aiRay& ray, const Triangles& triangles, float& min_r, float& min_s, float& min_t) { ssize_t triangle_index = -1; min_r = -1; float r, s, t; for (size_t i = 0; i < triangles.size(); i++) { auto intersect = ray_triangle_intersection( ray, triangles[i], r, s, t); if (intersect) { if (triangle_index < 0 || r < min_r) { min_r = r; min_s = s; min_t = t; triangle_index = i; } } } return triangle_index; } Triangles triangles_from_scene(const aiScene* scene) { Triangles triangles; for (auto node : make_range( scene->mRootNode->mChildren, scene->mRootNode->mNumChildren)) { const auto& T = node->mTransformation; if (node->mNumMeshes == 0) { continue; } for (auto mesh_index : make_range(node->mMeshes, node->mNumMeshes)) { const auto& mesh = *scene->mMeshes[mesh_index]; aiColor4D diffuse; scene->mMaterials[mesh.mMaterialIndex]->Get( AI_MATKEY_COLOR_DIFFUSE, diffuse); for (aiFace face : make_range(mesh.mFaces, mesh.mNumFaces)) { assert(face.mNumIndices == 3); triangles.push_back({ // vertices { T * mesh.mVertices[face.mIndices[0]], T * mesh.mVertices[face.mIndices[1]], T * mesh.mVertices[face.mIndices[2]] }, // normals { T * mesh.mNormals[face.mIndices[0]], T * mesh.mNormals[face.mIndices[1]], T * mesh.mNormals[face.mIndices[2]] }, diffuse }); } } } return triangles; } int main(int argc, char const *argv[]) { if (argc != 3) { std::cerr << "Usage: " << argv[0] << " <filename> <width>\n"; return 0; } std::string filename(argv[1]); int width = std::atoi(argv[2]); assert(width > 0); Assimp::Importer importer; const aiScene* scene = importer.ReadFile(filename, aiProcess_CalcTangentSpace | aiProcess_Triangulate | aiProcess_JoinIdenticalVertices | aiProcess_GenNormals | aiProcess_SortByPType); if (!scene) { std::cout << importer.GetErrorString() << std::endl; return 1; } std::cerr << *scene->mRootNode << std::endl; assert(scene->mNumCameras == 1); auto& cam = *scene->mCameras[0]; assert(cam.mPosition == aiVector3D(0, 0, 0)); assert(cam.mUp == aiVector3D(0, 1, 0)); assert(cam.mLookAt == aiVector3D(0, 0, -1)); if (cam.mAspect == 0) { // cam.mAspect = 16.f/9.f; cam.mAspect = 1.f; } std::cerr << cam << std::endl; int height = width / cam.mAspect; // raytracing auto* camNode = scene->mRootNode->FindNode("Camera"); assert(camNode != nullptr); const auto& CT = camNode->mTransformation; std::cerr << "Cam Trafo: " << CT << std::endl; auto cam_pos = CT * aiVector3D(0, 0, 0); // Get light node auto* lightNode = scene->mRootNode->FindNode("Light"); assert(lightNode != nullptr); const auto& LT = lightNode->mTransformation; std::cerr << "Light Trafo: " << LT << std::endl; auto light_pos = LT * aiVector3D(); auto triangles = triangles_from_scene(scene); // FIXME: Our scene does not have any lights yet. // std::cerr << scene->mNumLights << std::endl; // assert(scene->mNumLights == 1); // auto* light = scene->mLights[0]; // TODO: ... auto light_color = aiColor4D(0xFF / 255., 0xF8 / 255., 0xDD / 255., 1); // TODO: // 1. Add ambient light. // 2. Find a nice scene (cornell box). Image image(width, height); for (int y = 0; y < height; ++y) { for (int x = 0; x < width; ++x) { auto cam_dir = raster2cam(cam, aiVector2D(x, y), width, height); cam_dir = (CT * cam_dir - cam_pos).Normalize(); float r, s, t; auto triangle_index = ray_intersection( aiRay(cam_pos, std::move(cam_dir)), triangles, r, s, t); //image_data.emplace_back(); // black if (triangle_index < 0) { continue; } // intersection point auto p = cam_pos + r * cam_dir; const auto& triangle = triangles[triangle_index]; // compute normal // barycentric coordinates float u = s; float v = t; float w = 1.f - u - v; auto aN = triangle.normals[0]; auto bN = triangle.normals[1]; auto cN = triangle.normals[2]; auto normal = (w*aN + u*bN + v*cN).Normalize(); // compute vector towards light auto light_dir = (light_pos - p).Normalize(); image(x, y) = lambertian(light_dir, normal, triangle.diffuse, light_color); // TODO: get material's (ambient) color } } // output image std::cout << image << std::endl; return 0; }
#include "lib/output.h" #include "lib/image.h" #include "lib/intersection.h" #include "lib/lambertian.h" #include "lib/range.h" #include "lib/types.h" #include <assimp/Importer.hpp> // C++ importer interface #include <assimp/scene.h> // Output data structure #include <assimp/postprocess.h> // Post processing flags #include <math.h> #include <vector> #include <iostream> #include <chrono> // // Convert 2d raster coodinates into 3d cameras coordinates. // // We assume that the camera is trivial: // assert(cam.mPosition == aiVector3D(0, 0, 0)); // assert(cam.mUp == aiVector3D(0, 1, 0)); // assert(cam.mLookAt == aiVector3D(0, 0, -1)); // assert(cam.mAspect != 0) { // // The positioning of the camera is done in its parent's node transformation // matrix. // aiVector3D raster2cam( const aiCamera& cam, const aiVector2D& p, const int w, const int h) { float delta_x = tan(cam.mHorizontalFOV / 2.); float delta_y = delta_x / cam.mAspect; return aiVector3D( -delta_x * (1 - 2 * p.x / static_cast<float>(w)), delta_y * (1 - 2 * p.y / static_cast<float>(h)), -1); } ssize_t ray_intersection(const aiRay& ray, const Triangles& triangles, float& min_r, float& min_s, float& min_t) { ssize_t triangle_index = -1; min_r = -1; float r, s, t; for (size_t i = 0; i < triangles.size(); i++) { auto intersect = ray_triangle_intersection( ray, triangles[i], r, s, t); if (intersect) { if (triangle_index < 0 || r < min_r) { min_r = r; min_s = s; min_t = t; triangle_index = i; } } } return triangle_index; } Triangles triangles_from_scene(const aiScene* scene) { Triangles triangles; for (auto node : make_range( scene->mRootNode->mChildren, scene->mRootNode->mNumChildren)) { const auto& T = node->mTransformation; if (node->mNumMeshes == 0) { continue; } for (auto mesh_index : make_range(node->mMeshes, node->mNumMeshes)) { const auto& mesh = *scene->mMeshes[mesh_index]; aiColor4D diffuse; scene->mMaterials[mesh.mMaterialIndex]->Get( AI_MATKEY_COLOR_DIFFUSE, diffuse); for (aiFace face : make_range(mesh.mFaces, mesh.mNumFaces)) { assert(face.mNumIndices == 3); triangles.push_back({ // vertices { T * mesh.mVertices[face.mIndices[0]], T * mesh.mVertices[face.mIndices[1]], T * mesh.mVertices[face.mIndices[2]] }, // normals { T * mesh.mNormals[face.mIndices[0]], T * mesh.mNormals[face.mIndices[1]], T * mesh.mNormals[face.mIndices[2]] }, diffuse }); } } } return triangles; } int main(int argc, char const *argv[]) { if (argc != 3) { std::cerr << "Usage: " << argv[0] << " <filename> <width>\n"; return 0; } std::string filename(argv[1]); int width = std::atoi(argv[2]); assert(width > 0); Assimp::Importer importer; const aiScene* scene = importer.ReadFile(filename, aiProcess_CalcTangentSpace | aiProcess_Triangulate | aiProcess_JoinIdenticalVertices | aiProcess_GenNormals | aiProcess_SortByPType); if (!scene) { std::cout << importer.GetErrorString() << std::endl; return 1; } std::cerr << *scene->mRootNode << std::endl; assert(scene->mNumCameras == 1); auto& cam = *scene->mCameras[0]; assert(cam.mPosition == aiVector3D(0, 0, 0)); assert(cam.mUp == aiVector3D(0, 1, 0)); assert(cam.mLookAt == aiVector3D(0, 0, -1)); if (cam.mAspect == 0) { // cam.mAspect = 16.f/9.f; cam.mAspect = 1.f; } std::cerr << cam << std::endl; int height = width / cam.mAspect; // raytracing auto* camNode = scene->mRootNode->FindNode("Camera"); assert(camNode != nullptr); const auto& CT = camNode->mTransformation; std::cerr << "Cam Trafo: " << CT << std::endl; auto cam_pos = CT * aiVector3D(0, 0, 0); // Get light node auto* lightNode = scene->mRootNode->FindNode("Light"); assert(lightNode != nullptr); const auto& LT = lightNode->mTransformation; std::cerr << "Light Trafo: " << LT << std::endl; auto light_pos = LT * aiVector3D(); auto triangles = triangles_from_scene(scene); // FIXME: Our scene does not have any lights yet. // std::cerr << scene->mNumLights << std::endl; // assert(scene->mNumLights == 1); // auto* light = scene->mLights[0]; // TODO: ... auto light_color = aiColor4D(0xFF / 255., 0xF8 / 255., 0xDD / 255., 1); // TODO: // 1. Add ambient light. // 2. Find a nice scene (cornell box). auto start = std::chrono::steady_clock::now(); Image image(width, height); for (int y = 0; y < height; ++y) { for (int x = 0; x < width; ++x) { auto cam_dir = raster2cam(cam, aiVector2D(x, y), width, height); cam_dir = (CT * cam_dir - cam_pos).Normalize(); float r, s, t; auto triangle_index = ray_intersection( aiRay(cam_pos, std::move(cam_dir)), triangles, r, s, t); //image_data.emplace_back(); // black if (triangle_index < 0) { continue; } // intersection point auto p = cam_pos + r * cam_dir; const auto& triangle = triangles[triangle_index]; // compute normal auto n0 = triangle.normals[0]; auto n1 = triangle.normals[1]; auto n2 = triangle.normals[2]; auto normal = ((1.f - s - t)*n0 + s*n1 + t*n2).Normalize(); // compute vector towards light auto light_dir = light_pos - p; light_dir.Normalize(); image(x, y) = lambertian( light_dir, normal, triangle.diffuse, light_color); image(x, y) += 0.1f * triangle.diffuse; // TODO: get material's (ambient) color } } auto end = std::chrono::steady_clock::now(); auto ms = std::chrono::duration_cast<std::chrono::milliseconds>(end - start).count(); std::cerr << "Rendering time: " << ms << std::endl; // output image std::cout << image << std::endl; return 0; }
Add rendering time
Add rendering time
C++
apache-2.0
turner-renderer/turner,turner-renderer/turner,turner-renderer/turner,turner-renderer/turner,jeschkies/renderer,jeschkies/renderer,blacklab/renderer
7b806fd0bb2a0f5806f01ebe1f6b33bc4c13ce3b
samples/ModelView/Model.cpp
samples/ModelView/Model.cpp
/*********************************************************************** filename: Model.cpp created: Tue May 27 2014 author: Timotei Dolean <[email protected]> *************************************************************************/ /*************************************************************************** * Copyright (C) 2004 - 2014 Paul D Turner & The CEGUI Development Team * * 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 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 "Model.h" #include "CEGUI/PropertyHelper.h" #include <iterator> using namespace CEGUI; template<typename T> static ModelIndex makeValidIndex(size_t id, std::vector<T>& vector) { if (id >= 0 && id < vector.size()) return ModelIndex(&vector.at(id)); return ModelIndex(); } //----------------------------------------------------------------------------// InventoryItem InventoryItem::make(const CEGUI::String& name, float weight) { InventoryItem item; item.d_name = name; item.d_weight = weight; return item; } //----------------------------------------------------------------------------// bool InventoryItem::operator==(const InventoryItem& other) { if (d_weight != other.d_weight) return false; if (d_name != other.d_name) return false; if (d_items.size() != other.d_items.size()) return false; for (size_t i = 0; i < d_items.size(); ++i) { if (d_items.at(i) != other.d_items.at(i)) return false; } return true; } //----------------------------------------------------------------------------// bool InventoryItem::operator!=(const InventoryItem& other) { return !(*this == other); } //----------------------------------------------------------------------------// void InventoryModel::load() { d_inventoryRoot = InventoryItem::make("Inventory", 0.0f); InventoryItem prev_matryoshka; // matryoshka D to A bool has_child = false; for (char chr = 'D'; chr >= 'A'; --chr) { InventoryItem matryoshka = InventoryItem::make("Matryoshka " + String(1, chr), 1.0f); if (has_child) matryoshka.d_items.push_back(prev_matryoshka); prev_matryoshka = matryoshka; has_child = true; } InventoryItem beans = InventoryItem::make("Beans!", 0.1f); InventoryItem beans_can = InventoryItem::make("Beans can", 1.0f); beans_can.d_items.push_back(beans); InventoryItem backpack = InventoryItem::make("Trip backpack", 2.0f); backpack.d_items.push_back(prev_matryoshka); backpack.d_items.push_back(beans_can); d_inventoryRoot.d_items.push_back(backpack); InventoryItem bow = InventoryItem::make("Bow", 23.451f); for (int i = 0; i < 25; ++i) { InventoryItem arrow = InventoryItem::make( "arrow " + PropertyHelper<int>::toString(i), 0.2f); bow.d_items.push_back(arrow); } d_inventoryRoot.d_items.push_back(bow); // generate *many* items :D for (int i = 1960; i < 2000; i += 2) { InventoryItem almanach = InventoryItem::make( "Almanach " + PropertyHelper<int>::toString(i), 0.34f); d_inventoryRoot.d_items.push_back(almanach); } } //----------------------------------------------------------------------------// bool InventoryModel::isValidIndex(const ModelIndex& model_index) const { //TODO: check if we still have a reference to model_index.userdata? return model_index.d_modelData != 0; } //----------------------------------------------------------------------------// CEGUI::ModelIndex InventoryModel::makeIndex(size_t child, const ModelIndex& parent_index) { if (parent_index.d_modelData == 0) return ModelIndex(); InventoryItem* item = static_cast<InventoryItem*>(parent_index.d_modelData); return makeValidIndex(child, item->d_items); } //----------------------------------------------------------------------------// CEGUI::ModelIndex InventoryModel::getParentIndex(const ModelIndex& model_index) { if (model_index.d_modelData == &d_inventoryRoot) return ModelIndex(); return getRootIndex(); } //----------------------------------------------------------------------------// CEGUI::ModelIndex InventoryModel::getRootIndex() { return ModelIndex(&d_inventoryRoot); } //----------------------------------------------------------------------------// size_t InventoryModel::getChildCount(const ModelIndex& model_index) { if (model_index.d_modelData == 0) return d_inventoryRoot.d_items.size(); return static_cast<InventoryItem*>(model_index.d_modelData)->d_items.size(); } //----------------------------------------------------------------------------// CEGUI::String InventoryModel::getData(const ModelIndex& model_index, ItemDataRole role /*= IDR_Text*/) { if (model_index.d_modelData == 0) return ""; InventoryItem* item = static_cast<InventoryItem*>(model_index.d_modelData); if (role == CEGUI::IDR_Text) return item->d_name; return ""; } //----------------------------------------------------------------------------// void InventoryModel::clear() { size_t items_count = d_inventoryRoot.d_items.size(); d_inventoryRoot.d_items.clear(); notifyChildrenRemoved(getRootIndex(), 0, items_count); } //----------------------------------------------------------------------------// void InventoryModel::addItem(InventoryItem& new_item) { d_inventoryRoot.d_items.insert(d_inventoryRoot.d_items.begin(), new_item); //TODO: see how we specify that we added items starting *before* or *after* that start index notifyChildrenAdded(getRootIndex(), 0, 1); } //----------------------------------------------------------------------------// bool InventoryModel::areIndicesEqual(const ModelIndex& index1, const ModelIndex& index2) { return index1.d_modelData == index2.d_modelData; } //----------------------------------------------------------------------------// int InventoryModel::getChildId(const ModelIndex& model_index) { ModelIndex parent_index = getParentIndex(model_index); InventoryItem* parent_item = static_cast<InventoryItem*>(parent_index.d_modelData); InventoryItem* child_item = static_cast<InventoryItem*>(model_index.d_modelData); std::vector<InventoryItem>::iterator itor = std::find( parent_item->d_items.begin(), parent_item->d_items.end(), *child_item); if (itor == parent_item->d_items.end()) return -1; return std::distance(parent_item->d_items.begin(), itor); } //----------------------------------------------------------------------------// void InventoryModel::removeItem(const ModelIndex& index) { ModelIndex parent_index = getParentIndex(index); InventoryItem* parent_item = static_cast<InventoryItem*>(parent_index.d_modelData); InventoryItem* child_item = static_cast<InventoryItem*>(index.d_modelData); std::vector<InventoryItem>::iterator itor = std::find( parent_item->d_items.begin(), parent_item->d_items.end(), *child_item); if (itor != parent_item->d_items.end()) { size_t child_id = std::distance(parent_item->d_items.begin(), itor); parent_item->d_items.erase(itor); notifyChildrenRemoved(parent_index, child_id, 1); } }
/*********************************************************************** filename: Model.cpp created: Tue May 27 2014 author: Timotei Dolean <[email protected]> *************************************************************************/ /*************************************************************************** * Copyright (C) 2004 - 2014 Paul D Turner & The CEGUI Development Team * * 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 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 "Model.h" #include "CEGUI/PropertyHelper.h" #include <iterator> #include <algorithm> using namespace CEGUI; template<typename T> static ModelIndex makeValidIndex(size_t id, std::vector<T>& vector) { if (id >= 0 && id < vector.size()) return ModelIndex(&vector.at(id)); return ModelIndex(); } //----------------------------------------------------------------------------// InventoryItem InventoryItem::make(const CEGUI::String& name, float weight) { InventoryItem item; item.d_name = name; item.d_weight = weight; return item; } //----------------------------------------------------------------------------// bool InventoryItem::operator==(const InventoryItem& other) { if (d_weight != other.d_weight) return false; if (d_name != other.d_name) return false; if (d_items.size() != other.d_items.size()) return false; for (size_t i = 0; i < d_items.size(); ++i) { if (d_items.at(i) != other.d_items.at(i)) return false; } return true; } //----------------------------------------------------------------------------// bool InventoryItem::operator!=(const InventoryItem& other) { return !(*this == other); } //----------------------------------------------------------------------------// void InventoryModel::load() { d_inventoryRoot = InventoryItem::make("Inventory", 0.0f); InventoryItem prev_matryoshka; // matryoshka D to A bool has_child = false; for (char chr = 'D'; chr >= 'A'; --chr) { InventoryItem matryoshka = InventoryItem::make("Matryoshka " + String(1, chr), 1.0f); if (has_child) matryoshka.d_items.push_back(prev_matryoshka); prev_matryoshka = matryoshka; has_child = true; } InventoryItem beans = InventoryItem::make("Beans!", 0.1f); InventoryItem beans_can = InventoryItem::make("Beans can", 1.0f); beans_can.d_items.push_back(beans); InventoryItem backpack = InventoryItem::make("Trip backpack", 2.0f); backpack.d_items.push_back(prev_matryoshka); backpack.d_items.push_back(beans_can); d_inventoryRoot.d_items.push_back(backpack); InventoryItem bow = InventoryItem::make("Bow", 23.451f); for (int i = 0; i < 25; ++i) { InventoryItem arrow = InventoryItem::make( "arrow " + PropertyHelper<int>::toString(i), 0.2f); bow.d_items.push_back(arrow); } d_inventoryRoot.d_items.push_back(bow); // generate *many* items :D for (int i = 1960; i < 2000; i += 2) { InventoryItem almanach = InventoryItem::make( "Almanach " + PropertyHelper<int>::toString(i), 0.34f); d_inventoryRoot.d_items.push_back(almanach); } } //----------------------------------------------------------------------------// bool InventoryModel::isValidIndex(const ModelIndex& model_index) const { //TODO: check if we still have a reference to model_index.userdata? return model_index.d_modelData != 0; } //----------------------------------------------------------------------------// CEGUI::ModelIndex InventoryModel::makeIndex(size_t child, const ModelIndex& parent_index) { if (parent_index.d_modelData == 0) return ModelIndex(); InventoryItem* item = static_cast<InventoryItem*>(parent_index.d_modelData); return makeValidIndex(child, item->d_items); } //----------------------------------------------------------------------------// CEGUI::ModelIndex InventoryModel::getParentIndex(const ModelIndex& model_index) { if (model_index.d_modelData == &d_inventoryRoot) return ModelIndex(); return getRootIndex(); } //----------------------------------------------------------------------------// CEGUI::ModelIndex InventoryModel::getRootIndex() { return ModelIndex(&d_inventoryRoot); } //----------------------------------------------------------------------------// size_t InventoryModel::getChildCount(const ModelIndex& model_index) { if (model_index.d_modelData == 0) return d_inventoryRoot.d_items.size(); return static_cast<InventoryItem*>(model_index.d_modelData)->d_items.size(); } //----------------------------------------------------------------------------// CEGUI::String InventoryModel::getData(const ModelIndex& model_index, ItemDataRole role /*= IDR_Text*/) { if (model_index.d_modelData == 0) return ""; InventoryItem* item = static_cast<InventoryItem*>(model_index.d_modelData); if (role == CEGUI::IDR_Text) return item->d_name; return ""; } //----------------------------------------------------------------------------// void InventoryModel::clear() { size_t items_count = d_inventoryRoot.d_items.size(); d_inventoryRoot.d_items.clear(); notifyChildrenRemoved(getRootIndex(), 0, items_count); } //----------------------------------------------------------------------------// void InventoryModel::addItem(InventoryItem& new_item) { d_inventoryRoot.d_items.insert(d_inventoryRoot.d_items.begin(), new_item); //TODO: see how we specify that we added items starting *before* or *after* that start index notifyChildrenAdded(getRootIndex(), 0, 1); } //----------------------------------------------------------------------------// bool InventoryModel::areIndicesEqual(const ModelIndex& index1, const ModelIndex& index2) { return index1.d_modelData == index2.d_modelData; } //----------------------------------------------------------------------------// int InventoryModel::getChildId(const ModelIndex& model_index) { ModelIndex parent_index = getParentIndex(model_index); InventoryItem* parent_item = static_cast<InventoryItem*>(parent_index.d_modelData); InventoryItem* child_item = static_cast<InventoryItem*>(model_index.d_modelData); std::vector<InventoryItem>::iterator itor = std::find( parent_item->d_items.begin(), parent_item->d_items.end(), *child_item); if (itor == parent_item->d_items.end()) return -1; return std::distance(parent_item->d_items.begin(), itor); } //----------------------------------------------------------------------------// void InventoryModel::removeItem(const ModelIndex& index) { ModelIndex parent_index = getParentIndex(index); InventoryItem* parent_item = static_cast<InventoryItem*>(parent_index.d_modelData); InventoryItem* child_item = static_cast<InventoryItem*>(index.d_modelData); std::vector<InventoryItem>::iterator itor = std::find( parent_item->d_items.begin(), parent_item->d_items.end(), *child_item); if (itor != parent_item->d_items.end()) { size_t child_id = std::distance(parent_item->d_items.begin(), itor); parent_item->d_items.erase(itor); notifyChildrenRemoved(parent_index, child_id, 1); } }
Include the algorithm header
Include the algorithm header Fix compilation on GCC. --HG-- branch : model-view-devel
C++
mit
cbeck88/cegui-mirror-two,cbeck88/cegui-mirror-two,cbeck88/cegui-mirror-two,cbeck88/cegui-mirror-two,cbeck88/cegui-mirror-two
c1258d74227e035590217acfbfb6a9ef56aa895e
cxxtools/src/systemerror.cpp
cxxtools/src/systemerror.cpp
/*************************************************************************** * Copyright (C) 2004-2007 Marc Boris Duerner * * Copyright (C) 2005-2007 Aloysius Indrayanto * * * * This program is free software; you can redistribute it and/or modify * * it under the terms of the GNU Library General Public License as * * published by the Free Software Foundation; either version 2 of the * * License, or (at your option) any later version. * * * * As a special exception, you may use this file as part of a free * * software library without restriction. Specifically, if other files * * instantiate templates or use macros or inline functions from this * * file, or you compile this file and link it with other files to * * produce an executable, this file does not by itself cause the * * resulting executable to be covered by the GNU General Public * * License. This exception does not however invalidate any other * * reasons why the executable file might be covered by the GNU Library * * General Public License. * * * * This 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 Library General Public * * License along with this program; if not, write to the * * Free Software Foundation, Inc., * * 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. * ***************************************************************************/ #include "cxxtools/systemerror.h" #include <errno.h> #include <string.h> #include <sstream> namespace { std::string getErrnoString(int err, const char* fn) { if (err != 0) { std::ostringstream msg; msg << fn << ": errno " << err << ": " << strerror(err); return msg.str(); } else return fn; } } namespace cxxtools { void throwSysErrorIf(bool flag, const char* fn) { if(flag) throw SystemError(fn); } void throwSysErrorIf(bool flag, int err, const char* fn) { if(flag) throw SystemError(err, fn); } SystemError::SystemError(int err, const char* fn) : std::runtime_error( getErrnoString(err, fn) ) , m_errno(err) { } SystemError::SystemError(const char* fn) : std::runtime_error( getErrnoString(errno, fn) ) , m_errno(errno) {} SystemError::SystemError(const std::string& what, const SourceInfo& si) : std::runtime_error(what + si) , m_errno(0) { } SystemError::~SystemError() throw() { } OpenLibraryFailed::OpenLibraryFailed(const std::string& msg, const cxxtools::SourceInfo& si) : SystemError(msg, si) { } SymbolNotFound::SymbolNotFound(const std::string& sym, const cxxtools::SourceInfo& si) : SystemError("symbol not found: " + sym, si) , _symbol(sym) { } } // namespace cxxtools
/*************************************************************************** * Copyright (C) 2004-2007 Marc Boris Duerner * * Copyright (C) 2005-2007 Aloysius Indrayanto * * * * This program is free software; you can redistribute it and/or modify * * it under the terms of the GNU Library General Public License as * * published by the Free Software Foundation; either version 2 of the * * License, or (at your option) any later version. * * * * As a special exception, you may use this file as part of a free * * software library without restriction. Specifically, if other files * * instantiate templates or use macros or inline functions from this * * file, or you compile this file and link it with other files to * * produce an executable, this file does not by itself cause the * * resulting executable to be covered by the GNU General Public * * License. This exception does not however invalidate any other * * reasons why the executable file might be covered by the GNU Library * * General Public License. * * * * This 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 Library General Public * * License along with this program; if not, write to the * * Free Software Foundation, Inc., * * 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. * ***************************************************************************/ #include "cxxtools/systemerror.h" #include "cxxtools/log.h" #include <errno.h> #include <string.h> #include <sstream> log_define("cxxtools.systemerror") namespace { std::string getErrnoString(int err, const char* fn) { if (err != 0) { std::ostringstream msg; msg << fn << ": errno " << err << ": " << strerror(err); return msg.str(); } else return fn; } } namespace cxxtools { void throwSysErrorIf(bool flag, const char* fn) { if(flag) throw SystemError(fn); } void throwSysErrorIf(bool flag, int err, const char* fn) { if(flag) throw SystemError(err, fn); } SystemError::SystemError(int err, const char* fn) : std::runtime_error( getErrnoString(err, fn) ) , m_errno(err) { log_debug("system error; " << what()); } SystemError::SystemError(const char* fn) : std::runtime_error( getErrnoString(errno, fn) ) , m_errno(errno) { log_debug("system error; " << what()); } SystemError::SystemError(const std::string& what, const SourceInfo& si) : std::runtime_error(what + si) , m_errno(0) { log_debug("system error; " << std::exception::what()); } SystemError::~SystemError() throw() { } OpenLibraryFailed::OpenLibraryFailed(const std::string& msg, const cxxtools::SourceInfo& si) : SystemError(msg, si) { log_debug("open library failed; " << what()); } SymbolNotFound::SymbolNotFound(const std::string& sym, const cxxtools::SourceInfo& si) : SystemError("symbol not found: " + sym, si) , _symbol(sym) { log_debug("symbol " << sym << " not found; " << what()); } } // namespace cxxtools
add debug logging
add debug logging git-svn-id: 40192aece4a9e6664bc9a93aa558322db432a344@649 15ae5fad-cc11-0410-8fac-bce609e504b0
C++
lgpl-2.1
maekitalo/cxxtools,maekitalo/cxxtools,maekitalo/cxxtools,OlafRadicke/cxxtools,OlafRadicke/cxxtools,maekitalo/cxxtools,OlafRadicke/cxxtools,OlafRadicke/cxxtools
fbf75410448e70098395663fc6274d2b400cd45c
webkit/glue/webclipboard_impl.cc
webkit/glue/webclipboard_impl.cc
// 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 "webkit/glue/webclipboard_impl.h" #include "base/logging.h" #include "base/pickle.h" #include "base/string_util.h" #include "base/utf_string_conversions.h" #include "googleurl/src/gurl.h" #include "net/base/escape.h" #include "third_party/skia/include/core/SkBitmap.h" #include "third_party/WebKit/Source/WebKit/chromium/public/platform/WebData.h" #include "third_party/WebKit/Source/WebKit/chromium/public/platform/WebDragData.h" #include "third_party/WebKit/Source/WebKit/chromium/public/platform/WebImage.h" #include "third_party/WebKit/Source/WebKit/chromium/public/platform/WebSize.h" #include "third_party/WebKit/Source/WebKit/chromium/public/platform/WebString.h" #include "third_party/WebKit/Source/WebKit/chromium/public/platform/WebURL.h" #include "third_party/WebKit/Source/WebKit/chromium/public/platform/WebVector.h" #include "ui/base/clipboard/clipboard.h" #include "ui/base/clipboard/custom_data_helper.h" #include "webkit/glue/scoped_clipboard_writer_glue.h" #include "webkit/glue/webdropdata.h" #include "webkit/glue/webkit_glue.h" #if WEBKIT_USING_CG #include "skia/ext/skia_utils_mac.h" #endif using WebKit::WebClipboard; using WebKit::WebData; using WebKit::WebDragData; using WebKit::WebImage; using WebKit::WebString; using WebKit::WebURL; using WebKit::WebVector; namespace webkit_glue { // Static std::string WebClipboardImpl::URLToMarkup(const WebURL& url, const WebString& title) { std::string markup("<a href=\""); markup.append(url.spec()); markup.append("\">"); // TODO(darin): HTML escape this markup.append(net::EscapeForHTML(UTF16ToUTF8(title))); markup.append("</a>"); return markup; } // Static std::string WebClipboardImpl::URLToImageMarkup(const WebURL& url, const WebString& title) { std::string markup("<img src=\""); markup.append(url.spec()); markup.append("\""); if (!title.isEmpty()) { markup.append(" alt=\""); markup.append(net::EscapeForHTML(UTF16ToUTF8(title))); markup.append("\""); } markup.append("/>"); return markup; } WebClipboardImpl::WebClipboardImpl(ClipboardClient* client) : client_(client) { } WebClipboardImpl::~WebClipboardImpl() { } uint64 WebClipboardImpl::getSequenceNumber() { return sequenceNumber(BufferStandard); } uint64 WebClipboardImpl::sequenceNumber(Buffer buffer) { ui::Clipboard::Buffer buffer_type; if (!ConvertBufferType(buffer, &buffer_type)) return 0; return client_->GetSequenceNumber(buffer_type); } bool WebClipboardImpl::isFormatAvailable(Format format, Buffer buffer) { ui::Clipboard::Buffer buffer_type; if (!ConvertBufferType(buffer, &buffer_type)) return false; switch (format) { case FormatPlainText: return client_->IsFormatAvailable(ui::Clipboard::GetPlainTextFormatType(), buffer_type) || client_->IsFormatAvailable(ui::Clipboard::GetPlainTextWFormatType(), buffer_type); case FormatHTML: return client_->IsFormatAvailable(ui::Clipboard::GetHtmlFormatType(), buffer_type); case FormatSmartPaste: return client_->IsFormatAvailable( ui::Clipboard::GetWebKitSmartPasteFormatType(), buffer_type); case FormatBookmark: #if defined(OS_WIN) || defined(OS_MACOSX) return client_->IsFormatAvailable(ui::Clipboard::GetUrlWFormatType(), buffer_type); #endif default: NOTREACHED(); } return false; } WebVector<WebString> WebClipboardImpl::readAvailableTypes( Buffer buffer, bool* contains_filenames) { ui::Clipboard::Buffer buffer_type; std::vector<string16> types; if (ConvertBufferType(buffer, &buffer_type)) { client_->ReadAvailableTypes(buffer_type, &types, contains_filenames); } return types; } WebString WebClipboardImpl::readPlainText(Buffer buffer) { ui::Clipboard::Buffer buffer_type; if (!ConvertBufferType(buffer, &buffer_type)) return WebString(); if (client_->IsFormatAvailable(ui::Clipboard::GetPlainTextWFormatType(), buffer_type)) { string16 text; client_->ReadText(buffer_type, &text); if (!text.empty()) return text; } if (client_->IsFormatAvailable(ui::Clipboard::GetPlainTextFormatType(), buffer_type)) { std::string text; client_->ReadAsciiText(buffer_type, &text); if (!text.empty()) return ASCIIToUTF16(text); } return WebString(); } WebString WebClipboardImpl::readHTML(Buffer buffer, WebURL* source_url, unsigned* fragment_start, unsigned* fragment_end) { ui::Clipboard::Buffer buffer_type; if (!ConvertBufferType(buffer, &buffer_type)) return WebString(); string16 html_stdstr; GURL gurl; client_->ReadHTML(buffer_type, &html_stdstr, &gurl, static_cast<uint32*>(fragment_start), static_cast<uint32*>(fragment_end)); *source_url = gurl; return html_stdstr; } WebData WebClipboardImpl::readImage(Buffer buffer) { ui::Clipboard::Buffer buffer_type; if (!ConvertBufferType(buffer, &buffer_type)) return WebData(); std::string png_data; client_->ReadImage(buffer_type, &png_data); return WebData(png_data); } WebString WebClipboardImpl::readCustomData(Buffer buffer, const WebString& type) { ui::Clipboard::Buffer buffer_type; if (!ConvertBufferType(buffer, &buffer_type)) return WebString(); string16 data; client_->ReadCustomData(buffer_type, type, &data); return data; } void WebClipboardImpl::writeHTML( const WebString& html_text, const WebURL& source_url, const WebString& plain_text, bool write_smart_paste) { ScopedClipboardWriterGlue scw(client_); scw.WriteHTML(html_text, source_url.spec()); scw.WriteText(plain_text); if (write_smart_paste) scw.WriteWebSmartPaste(); } void WebClipboardImpl::writePlainText(const WebString& plain_text) { ScopedClipboardWriterGlue scw(client_); scw.WriteText(plain_text); } void WebClipboardImpl::writeURL(const WebURL& url, const WebString& title) { ScopedClipboardWriterGlue scw(client_); scw.WriteBookmark(title, url.spec()); scw.WriteHTML(UTF8ToUTF16(URLToMarkup(url, title)), ""); scw.WriteText(UTF8ToUTF16(std::string(url.spec()))); } void WebClipboardImpl::writeImage( const WebImage& image, const WebURL& url, const WebString& title) { ScopedClipboardWriterGlue scw(client_); if (!image.isNull()) { #if WEBKIT_USING_SKIA const SkBitmap& bitmap = image.getSkBitmap(); #elif WEBKIT_USING_CG const SkBitmap& bitmap = gfx::CGImageToSkBitmap(image.getCGImageRef()); #endif SkAutoLockPixels locked(bitmap); scw.WriteBitmapFromPixels(bitmap.getPixels(), image.size()); } if (!url.isEmpty()) { scw.WriteBookmark(title, url.spec()); #if !defined(OS_MACOSX) // When writing the image, we also write the image markup so that pasting // into rich text editors, such as Gmail, reveals the image. We also don't // want to call writeText(), since some applications (WordPad) don't pick // the image if there is also a text format on the clipboard. // We also don't want to write HTML on a Mac, since Mail.app prefers to use // the image markup over attaching the actual image. See // http://crbug.com/33016 for details. scw.WriteHTML(UTF8ToUTF16(URLToImageMarkup(url, title)), ""); #endif } } void WebClipboardImpl::writeDataObject(const WebDragData& data) { // TODO(dcheng): This actually results in a double clear of the clipboard. // Once in WebKit, and once here when the clipboard writer goes out of scope. // The same is true of the other WebClipboard::write* methods. ScopedClipboardWriterGlue scw(client_); WebDropData data_object(data); // TODO(dcheng): Properly support text/uri-list here. scw.WriteText(data_object.plain_text); scw.WriteHTML(data_object.text_html, ""); Pickle pickle; ui::WriteCustomDataToPickle(data_object.custom_data, &pickle); scw.WritePickledData(pickle, ui::Clipboard::GetWebCustomDataFormatType()); } bool WebClipboardImpl::ConvertBufferType(Buffer buffer, ui::Clipboard::Buffer* result) { switch (buffer) { case BufferStandard: *result = ui::Clipboard::BUFFER_STANDARD; break; case BufferSelection: #if defined(USE_X11) && !defined(USE_AURA) *result = ui::Clipboard::BUFFER_SELECTION; break; #endif default: NOTREACHED(); return false; } return true; } } // namespace webkit_glue
// 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 "webkit/glue/webclipboard_impl.h" #include "base/logging.h" #include "base/pickle.h" #include "base/string_util.h" #include "base/utf_string_conversions.h" #include "googleurl/src/gurl.h" #include "net/base/escape.h" #include "third_party/skia/include/core/SkBitmap.h" #include "third_party/WebKit/Source/WebKit/chromium/public/platform/WebData.h" #include "third_party/WebKit/Source/WebKit/chromium/public/platform/WebDragData.h" #include "third_party/WebKit/Source/WebKit/chromium/public/platform/WebImage.h" #include "third_party/WebKit/Source/WebKit/chromium/public/platform/WebSize.h" #include "third_party/WebKit/Source/WebKit/chromium/public/platform/WebString.h" #include "third_party/WebKit/Source/WebKit/chromium/public/platform/WebURL.h" #include "third_party/WebKit/Source/WebKit/chromium/public/platform/WebVector.h" #include "ui/base/clipboard/clipboard.h" #include "ui/base/clipboard/custom_data_helper.h" #include "webkit/glue/scoped_clipboard_writer_glue.h" #include "webkit/glue/webdropdata.h" #include "webkit/glue/webkit_glue.h" #if WEBKIT_USING_CG #include "skia/ext/skia_utils_mac.h" #endif using WebKit::WebClipboard; using WebKit::WebData; using WebKit::WebDragData; using WebKit::WebImage; using WebKit::WebString; using WebKit::WebURL; using WebKit::WebVector; namespace webkit_glue { // Static std::string WebClipboardImpl::URLToMarkup(const WebURL& url, const WebString& title) { std::string markup("<a href=\""); markup.append(url.spec()); markup.append("\">"); // TODO(darin): HTML escape this markup.append(net::EscapeForHTML(UTF16ToUTF8(title))); markup.append("</a>"); return markup; } // Static std::string WebClipboardImpl::URLToImageMarkup(const WebURL& url, const WebString& title) { std::string markup("<img src=\""); markup.append(url.spec()); markup.append("\""); if (!title.isEmpty()) { markup.append(" alt=\""); markup.append(net::EscapeForHTML(UTF16ToUTF8(title))); markup.append("\""); } markup.append("/>"); return markup; } WebClipboardImpl::WebClipboardImpl(ClipboardClient* client) : client_(client) { } WebClipboardImpl::~WebClipboardImpl() { } uint64 WebClipboardImpl::getSequenceNumber() { return sequenceNumber(BufferStandard); } uint64 WebClipboardImpl::sequenceNumber(Buffer buffer) { ui::Clipboard::Buffer buffer_type; if (!ConvertBufferType(buffer, &buffer_type)) return 0; return client_->GetSequenceNumber(buffer_type); } bool WebClipboardImpl::isFormatAvailable(Format format, Buffer buffer) { ui::Clipboard::Buffer buffer_type; if (!ConvertBufferType(buffer, &buffer_type)) return false; switch (format) { case FormatPlainText: return client_->IsFormatAvailable(ui::Clipboard::GetPlainTextFormatType(), buffer_type) || client_->IsFormatAvailable(ui::Clipboard::GetPlainTextWFormatType(), buffer_type); case FormatHTML: return client_->IsFormatAvailable(ui::Clipboard::GetHtmlFormatType(), buffer_type); case FormatSmartPaste: return client_->IsFormatAvailable( ui::Clipboard::GetWebKitSmartPasteFormatType(), buffer_type); case FormatBookmark: #if defined(OS_WIN) || defined(OS_MACOSX) return client_->IsFormatAvailable(ui::Clipboard::GetUrlWFormatType(), buffer_type); #endif default: NOTREACHED(); } return false; } WebVector<WebString> WebClipboardImpl::readAvailableTypes( Buffer buffer, bool* contains_filenames) { ui::Clipboard::Buffer buffer_type; std::vector<string16> types; if (ConvertBufferType(buffer, &buffer_type)) { client_->ReadAvailableTypes(buffer_type, &types, contains_filenames); } return types; } WebString WebClipboardImpl::readPlainText(Buffer buffer) { ui::Clipboard::Buffer buffer_type; if (!ConvertBufferType(buffer, &buffer_type)) return WebString(); if (client_->IsFormatAvailable(ui::Clipboard::GetPlainTextWFormatType(), buffer_type)) { string16 text; client_->ReadText(buffer_type, &text); if (!text.empty()) return text; } if (client_->IsFormatAvailable(ui::Clipboard::GetPlainTextFormatType(), buffer_type)) { std::string text; client_->ReadAsciiText(buffer_type, &text); if (!text.empty()) return ASCIIToUTF16(text); } return WebString(); } WebString WebClipboardImpl::readHTML(Buffer buffer, WebURL* source_url, unsigned* fragment_start, unsigned* fragment_end) { ui::Clipboard::Buffer buffer_type; if (!ConvertBufferType(buffer, &buffer_type)) return WebString(); string16 html_stdstr; GURL gurl; client_->ReadHTML(buffer_type, &html_stdstr, &gurl, static_cast<uint32*>(fragment_start), static_cast<uint32*>(fragment_end)); *source_url = gurl; return html_stdstr; } WebData WebClipboardImpl::readImage(Buffer buffer) { ui::Clipboard::Buffer buffer_type; if (!ConvertBufferType(buffer, &buffer_type)) return WebData(); std::string png_data; client_->ReadImage(buffer_type, &png_data); return WebData(png_data); } WebString WebClipboardImpl::readCustomData(Buffer buffer, const WebString& type) { ui::Clipboard::Buffer buffer_type; if (!ConvertBufferType(buffer, &buffer_type)) return WebString(); string16 data; client_->ReadCustomData(buffer_type, type, &data); return data; } void WebClipboardImpl::writeHTML( const WebString& html_text, const WebURL& source_url, const WebString& plain_text, bool write_smart_paste) { ScopedClipboardWriterGlue scw(client_); scw.WriteHTML(html_text, source_url.spec()); scw.WriteText(plain_text); if (write_smart_paste) scw.WriteWebSmartPaste(); } void WebClipboardImpl::writePlainText(const WebString& plain_text) { ScopedClipboardWriterGlue scw(client_); scw.WriteText(plain_text); } void WebClipboardImpl::writeURL(const WebURL& url, const WebString& title) { ScopedClipboardWriterGlue scw(client_); scw.WriteBookmark(title, url.spec()); scw.WriteHTML(UTF8ToUTF16(URLToMarkup(url, title)), ""); scw.WriteText(UTF8ToUTF16(std::string(url.spec()))); } void WebClipboardImpl::writeImage( const WebImage& image, const WebURL& url, const WebString& title) { ScopedClipboardWriterGlue scw(client_); if (!image.isNull()) { #if WEBKIT_USING_SKIA const SkBitmap& bitmap = image.getSkBitmap(); #elif WEBKIT_USING_CG const SkBitmap& bitmap = gfx::CGImageToSkBitmap(image.getCGImageRef()); #endif SkAutoLockPixels locked(bitmap); scw.WriteBitmapFromPixels(bitmap.getPixels(), image.size()); } if (!url.isEmpty()) { scw.WriteBookmark(title, url.spec()); #if !defined(OS_MACOSX) // When writing the image, we also write the image markup so that pasting // into rich text editors, such as Gmail, reveals the image. We also don't // want to call writeText(), since some applications (WordPad) don't pick // the image if there is also a text format on the clipboard. // We also don't want to write HTML on a Mac, since Mail.app prefers to use // the image markup over attaching the actual image. See // http://crbug.com/33016 for details. scw.WriteHTML(UTF8ToUTF16(URLToImageMarkup(url, title)), ""); #endif } } void WebClipboardImpl::writeDataObject(const WebDragData& data) { ScopedClipboardWriterGlue scw(client_); WebDropData data_object(data); // TODO(dcheng): Properly support text/uri-list here. scw.WriteText(data_object.plain_text); scw.WriteHTML(data_object.text_html, ""); // If there is no custom data, avoid calling WritePickledData. This ensures // that ScopedClipboardWriterGlue's dtor remains a no-op if the page didn't // modify the DataTransfer object, which is important to avoid stomping on // any clipboard contents written by extension functions such as // chrome.experimental.bookmarkManager.copy. if (!data_object.custom_data.empty()) { Pickle pickle; ui::WriteCustomDataToPickle(data_object.custom_data, &pickle); scw.WritePickledData(pickle, ui::Clipboard::GetWebCustomDataFormatType()); } } bool WebClipboardImpl::ConvertBufferType(Buffer buffer, ui::Clipboard::Buffer* result) { switch (buffer) { case BufferStandard: *result = ui::Clipboard::BUFFER_STANDARD; break; case BufferSelection: #if defined(USE_X11) && !defined(USE_AURA) *result = ui::Clipboard::BUFFER_SELECTION; break; #endif default: NOTREACHED(); return false; } return true; } } // namespace webkit_glue
Fix ^C/^X in Bookmark Manager.
Fix ^C/^X in Bookmark Manager. This fixes WebClipboardImpl so that writing an empty DataTransfer object is a no-op again. This is required because calling the bookmark manager extension functions to copy/cut a bookmark cause ScopedClipboardWriters to be nested. BUG=108293 TEST=manual Review URL: http://codereview.chromium.org/9122016 git-svn-id: de016e52bd170d2d4f2344f9bf92d50478b649e0@116794 0039d316-1c4b-4281-b951-d872f2087c98
C++
bsd-3-clause
ltilve/chromium,fujunwei/chromium-crosswalk,rogerwang/chromium,markYoungH/chromium.src,pozdnyakov/chromium-crosswalk,Chilledheart/chromium,jaruba/chromium.src,hgl888/chromium-crosswalk,Jonekee/chromium.src,mogoweb/chromium-crosswalk,rogerwang/chromium,dushu1203/chromium.src,Fireblend/chromium-crosswalk,anirudhSK/chromium,robclark/chromium,robclark/chromium,patrickm/chromium.src,pozdnyakov/chromium-crosswalk,ChromiumWebApps/chromium,PeterWangIntel/chromium-crosswalk,ondra-novak/chromium.src,nacl-webkit/chrome_deps,pozdnyakov/chromium-crosswalk,mohamed--abdel-maksoud/chromium.src,Just-D/chromium-1,crosswalk-project/chromium-crosswalk-efl,junmin-zhu/chromium-rivertrail,Jonekee/chromium.src,dushu1203/chromium.src,hgl888/chromium-crosswalk,TheTypoMaster/chromium-crosswalk,M4sse/chromium.src,bright-sparks/chromium-spacewalk,Jonekee/chromium.src,jaruba/chromium.src,robclark/chromium,M4sse/chromium.src,PeterWangIntel/chromium-crosswalk,krieger-od/nwjs_chromium.src,hgl888/chromium-crosswalk-efl,hujiajie/pa-chromium,axinging/chromium-crosswalk,bright-sparks/chromium-spacewalk,chuan9/chromium-crosswalk,ltilve/chromium,hujiajie/pa-chromium,rogerwang/chromium,M4sse/chromium.src,zcbenz/cefode-chromium,zcbenz/cefode-chromium,bright-sparks/chromium-spacewalk,junmin-zhu/chromium-rivertrail,TheTypoMaster/chromium-crosswalk,ChromiumWebApps/chromium,littlstar/chromium.src,zcbenz/cefode-chromium,hgl888/chromium-crosswalk-efl,pozdnyakov/chromium-crosswalk,junmin-zhu/chromium-rivertrail,crosswalk-project/chromium-crosswalk-efl,Fireblend/chromium-crosswalk,crosswalk-project/chromium-crosswalk-efl,zcbenz/cefode-chromium,patrickm/chromium.src,TheTypoMaster/chromium-crosswalk,hgl888/chromium-crosswalk,mohamed--abdel-maksoud/chromium.src,Just-D/chromium-1,bright-sparks/chromium-spacewalk,krieger-od/nwjs_chromium.src,ondra-novak/chromium.src,markYoungH/chromium.src,anirudhSK/chromium,timopulkkinen/BubbleFish,dednal/chromium.src,markYoungH/chromium.src,patrickm/chromium.src,chuan9/chromium-crosswalk,mohamed--abdel-maksoud/chromium.src,dushu1203/chromium.src,keishi/chromium,Jonekee/chromium.src,hgl888/chromium-crosswalk,ChromiumWebApps/chromium,zcbenz/cefode-chromium,Pluto-tv/chromium-crosswalk,ChromiumWebApps/chromium,Pluto-tv/chromium-crosswalk,bright-sparks/chromium-spacewalk,pozdnyakov/chromium-crosswalk,Pluto-tv/chromium-crosswalk,Fireblend/chromium-crosswalk,junmin-zhu/chromium-rivertrail,Just-D/chromium-1,timopulkkinen/BubbleFish,Jonekee/chromium.src,markYoungH/chromium.src,dushu1203/chromium.src,fujunwei/chromium-crosswalk,Just-D/chromium-1,Fireblend/chromium-crosswalk,markYoungH/chromium.src,anirudhSK/chromium,M4sse/chromium.src,ltilve/chromium,dushu1203/chromium.src,timopulkkinen/BubbleFish,keishi/chromium,nacl-webkit/chrome_deps,nacl-webkit/chrome_deps,M4sse/chromium.src,TheTypoMaster/chromium-crosswalk,nacl-webkit/chrome_deps,dednal/chromium.src,timopulkkinen/BubbleFish,crosswalk-project/chromium-crosswalk-efl,keishi/chromium,nacl-webkit/chrome_deps,krieger-od/nwjs_chromium.src,nacl-webkit/chrome_deps,mohamed--abdel-maksoud/chromium.src,hujiajie/pa-chromium,chuan9/chromium-crosswalk,mogoweb/chromium-crosswalk,anirudhSK/chromium,mohamed--abdel-maksoud/chromium.src,jaruba/chromium.src,M4sse/chromium.src,anirudhSK/chromium,keishi/chromium,rogerwang/chromium,rogerwang/chromium,axinging/chromium-crosswalk,hgl888/chromium-crosswalk,chuan9/chromium-crosswalk,robclark/chromium,anirudhSK/chromium,ltilve/chromium,crosswalk-project/chromium-crosswalk-efl,dushu1203/chromium.src,axinging/chromium-crosswalk,anirudhSK/chromium,junmin-zhu/chromium-rivertrail,Pluto-tv/chromium-crosswalk,littlstar/chromium.src,Chilledheart/chromium,bright-sparks/chromium-spacewalk,markYoungH/chromium.src,hgl888/chromium-crosswalk,littlstar/chromium.src,PeterWangIntel/chromium-crosswalk,dednal/chromium.src,zcbenz/cefode-chromium,Jonekee/chromium.src,PeterWangIntel/chromium-crosswalk,patrickm/chromium.src,jaruba/chromium.src,littlstar/chromium.src,mohamed--abdel-maksoud/chromium.src,chuan9/chromium-crosswalk,mohamed--abdel-maksoud/chromium.src,Chilledheart/chromium,littlstar/chromium.src,hgl888/chromium-crosswalk,krieger-od/nwjs_chromium.src,Just-D/chromium-1,krieger-od/nwjs_chromium.src,mohamed--abdel-maksoud/chromium.src,hgl888/chromium-crosswalk-efl,ondra-novak/chromium.src,ltilve/chromium,ChromiumWebApps/chromium,jaruba/chromium.src,axinging/chromium-crosswalk,dednal/chromium.src,TheTypoMaster/chromium-crosswalk,zcbenz/cefode-chromium,crosswalk-project/chromium-crosswalk-efl,robclark/chromium,hgl888/chromium-crosswalk-efl,krieger-od/nwjs_chromium.src,dushu1203/chromium.src,nacl-webkit/chrome_deps,fujunwei/chromium-crosswalk,anirudhSK/chromium,chuan9/chromium-crosswalk,ChromiumWebApps/chromium,robclark/chromium,PeterWangIntel/chromium-crosswalk,Jonekee/chromium.src,Just-D/chromium-1,hgl888/chromium-crosswalk,rogerwang/chromium,Pluto-tv/chromium-crosswalk,hujiajie/pa-chromium,ltilve/chromium,ondra-novak/chromium.src,hujiajie/pa-chromium,timopulkkinen/BubbleFish,ondra-novak/chromium.src,ChromiumWebApps/chromium,pozdnyakov/chromium-crosswalk,mogoweb/chromium-crosswalk,TheTypoMaster/chromium-crosswalk,pozdnyakov/chromium-crosswalk,TheTypoMaster/chromium-crosswalk,anirudhSK/chromium,keishi/chromium,mogoweb/chromium-crosswalk,krieger-od/nwjs_chromium.src,pozdnyakov/chromium-crosswalk,jaruba/chromium.src,bright-sparks/chromium-spacewalk,Chilledheart/chromium,junmin-zhu/chromium-rivertrail,mogoweb/chromium-crosswalk,crosswalk-project/chromium-crosswalk-efl,keishi/chromium,timopulkkinen/BubbleFish,robclark/chromium,krieger-od/nwjs_chromium.src,hgl888/chromium-crosswalk-efl,patrickm/chromium.src,Jonekee/chromium.src,ondra-novak/chromium.src,krieger-od/nwjs_chromium.src,Chilledheart/chromium,ltilve/chromium,Just-D/chromium-1,chuan9/chromium-crosswalk,axinging/chromium-crosswalk,keishi/chromium,hgl888/chromium-crosswalk-efl,mogoweb/chromium-crosswalk,Pluto-tv/chromium-crosswalk,chuan9/chromium-crosswalk,Jonekee/chromium.src,patrickm/chromium.src,fujunwei/chromium-crosswalk,Just-D/chromium-1,mogoweb/chromium-crosswalk,bright-sparks/chromium-spacewalk,nacl-webkit/chrome_deps,Fireblend/chromium-crosswalk,nacl-webkit/chrome_deps,zcbenz/cefode-chromium,pozdnyakov/chromium-crosswalk,ChromiumWebApps/chromium,hujiajie/pa-chromium,dednal/chromium.src,patrickm/chromium.src,keishi/chromium,keishi/chromium,ChromiumWebApps/chromium,jaruba/chromium.src,jaruba/chromium.src,timopulkkinen/BubbleFish,littlstar/chromium.src,littlstar/chromium.src,anirudhSK/chromium,dushu1203/chromium.src,markYoungH/chromium.src,patrickm/chromium.src,nacl-webkit/chrome_deps,M4sse/chromium.src,keishi/chromium,PeterWangIntel/chromium-crosswalk,dednal/chromium.src,fujunwei/chromium-crosswalk,Jonekee/chromium.src,PeterWangIntel/chromium-crosswalk,Pluto-tv/chromium-crosswalk,Fireblend/chromium-crosswalk,fujunwei/chromium-crosswalk,dednal/chromium.src,Pluto-tv/chromium-crosswalk,timopulkkinen/BubbleFish,junmin-zhu/chromium-rivertrail,axinging/chromium-crosswalk,fujunwei/chromium-crosswalk,rogerwang/chromium,fujunwei/chromium-crosswalk,zcbenz/cefode-chromium,rogerwang/chromium,markYoungH/chromium.src,ondra-novak/chromium.src,PeterWangIntel/chromium-crosswalk,anirudhSK/chromium,krieger-od/nwjs_chromium.src,ondra-novak/chromium.src,robclark/chromium,hgl888/chromium-crosswalk,ChromiumWebApps/chromium,junmin-zhu/chromium-rivertrail,Chilledheart/chromium,dushu1203/chromium.src,dednal/chromium.src,dushu1203/chromium.src,hgl888/chromium-crosswalk-efl,mogoweb/chromium-crosswalk,markYoungH/chromium.src,axinging/chromium-crosswalk,mohamed--abdel-maksoud/chromium.src,hujiajie/pa-chromium,ChromiumWebApps/chromium,mogoweb/chromium-crosswalk,timopulkkinen/BubbleFish,Chilledheart/chromium,TheTypoMaster/chromium-crosswalk,ltilve/chromium,bright-sparks/chromium-spacewalk,dushu1203/chromium.src,axinging/chromium-crosswalk,markYoungH/chromium.src,robclark/chromium,anirudhSK/chromium,hgl888/chromium-crosswalk-efl,robclark/chromium,Fireblend/chromium-crosswalk,Fireblend/chromium-crosswalk,M4sse/chromium.src,Pluto-tv/chromium-crosswalk,junmin-zhu/chromium-rivertrail,crosswalk-project/chromium-crosswalk-efl,keishi/chromium,junmin-zhu/chromium-rivertrail,rogerwang/chromium,zcbenz/cefode-chromium,Fireblend/chromium-crosswalk,timopulkkinen/BubbleFish,M4sse/chromium.src,krieger-od/nwjs_chromium.src,ChromiumWebApps/chromium,ltilve/chromium,PeterWangIntel/chromium-crosswalk,mogoweb/chromium-crosswalk,patrickm/chromium.src,M4sse/chromium.src,hgl888/chromium-crosswalk-efl,pozdnyakov/chromium-crosswalk,hujiajie/pa-chromium,jaruba/chromium.src,Just-D/chromium-1,crosswalk-project/chromium-crosswalk-efl,Chilledheart/chromium,Chilledheart/chromium,mohamed--abdel-maksoud/chromium.src,zcbenz/cefode-chromium,axinging/chromium-crosswalk,dednal/chromium.src,timopulkkinen/BubbleFish,mohamed--abdel-maksoud/chromium.src,jaruba/chromium.src,hgl888/chromium-crosswalk-efl,hujiajie/pa-chromium,axinging/chromium-crosswalk,rogerwang/chromium,jaruba/chromium.src,littlstar/chromium.src,Jonekee/chromium.src,nacl-webkit/chrome_deps,ondra-novak/chromium.src,axinging/chromium-crosswalk,chuan9/chromium-crosswalk,hujiajie/pa-chromium,hujiajie/pa-chromium,TheTypoMaster/chromium-crosswalk,M4sse/chromium.src,junmin-zhu/chromium-rivertrail,dednal/chromium.src,pozdnyakov/chromium-crosswalk,fujunwei/chromium-crosswalk,markYoungH/chromium.src,dednal/chromium.src
fd39870050d87e90f4b3221939e66bfc9ab2b75c
tests/src/circuit_test.cpp
tests/src/circuit_test.cpp
#include "circuit.h" #include "gmock/gmock.h" #include "gtest/gtest.h" namespace qflex { namespace { // Passing in an invalid filename to circuit.load(). TEST(CircuitExceptionTest, InvalidFilenameInput) { QflexCircuit circuit; std::string invalid_filename = "invalid.txt"; try { circuit.load(invalid_filename); } catch (std::string msg) { EXPECT_THAT(msg, testing::HasSubstr("Cannot open circuit file invalid.txt.")); } } TEST(CircuitExceptionTest, PrintGate) { QflexGate gate; gate.name = "cx"; gate.cycle = 1; gate.qubits = {2, 4}; gate.params = {3, 5}; // std::cout << gate << std::endl; } constexpr char kBadCircuit1[] = R"(0 h 0 0 h 1 9 h 0 9 h 1)"; constexpr char kBadCircuit2[] = R"(6 0 h 0 0 h 9 h 0 9 h 1)"; constexpr char kBadCircuit3[] = R"(2 0 h 0 0 h 1 cz 0 2 9 h 1)"; constexpr char kBadCircuit4[] = R"(2 0 h 0 0 h 1 9 cz 0 2 7 cz 1 3 9 h 1)"; constexpr char kBadCircuit5[] = R"(4 0 h 0 0 h 1 1 t 0 1 t 2 2 fsim(0.1, a) 0 1 4 h 0 4 h 1 )"; constexpr char kBadCircuit6[] = R"(2 0 h 0 0 h 1 1 t 0 1 t a 4 h 0 4 h 1)"; constexpr char kBadCircuit7[] = R"(4 0 h 0 0 h 1 4 t 2 4 t 4 4 cz 2 4 9 cz 0 2 9 cz 1 3 9 h 1)"; TEST(CircuitExceptionTest, BadCircuits) { QflexCircuit circuit; // First line isn't the number of active qubits try { circuit.load(std::stringstream(kBadCircuit1)); } catch (std::string msg) { EXPECT_THAT(msg, testing::HasSubstr("[1: 0 h 0] First line in circuit must be the number of active qubits.")); } // Gate is missing parameters. try { circuit.load(std::stringstream(kBadCircuit2)); } catch (std::string msg) { EXPECT_THAT(msg, testing::HasSubstr("[3: 0 h] Gate must be specified as: cycle gate_name[(p1[,p2,...])] q1 [q2, ...]")); } // First number isn't cycle. try { circuit.load(std::stringstream(kBadCircuit3)); } catch (std::string msg) { EXPECT_THAT(msg, testing::HasSubstr("[4: cz 0 2] First token must be a valid cycle number.")); } // Cycle isn't increasing. try { circuit.load(std::stringstream(kBadCircuit4)); } catch (std::string msg) { EXPECT_THAT(msg, testing::HasSubstr("[5: 7 cz 1 3] Cycle number can only increase.")); } // Params aren't numbers. try { circuit.load(std::stringstream(kBadCircuit5)); } catch (std::string msg) { EXPECT_THAT(msg, testing::HasSubstr("Params must be valid numbers.")); } // Qubits aren't valid numbers. try { circuit.load(std::stringstream(kBadCircuit6)); } catch (std::string msg) { EXPECT_THAT(msg, testing::HasSubstr("[5: 1 t a] Qubit must be a valid number.")); } // Qubits are being reused. try { circuit.load(std::stringstream(kBadCircuit7)); } catch (std::string msg) { EXPECT_THAT(msg, testing::HasSubstr("[6: 4 cz 2 4] Qubits can only used once per cycle.")); } } constexpr char kSimpleCircuit[] = R"(5 0 h 0 0 h 1 0 h 2 0 h 3 0 h 5 1 t 0 1 t 1 1 t 2 1 t 3 1 t 5 2 cz 0 1 3 cx 0 2 4 cx 1 3 5 cz 2 3 6 cz 3 5 11 cz 0 1 12 cx 0 2 14 h 0 14 h 1 14 h 2 14 h 3 14 h 5)"; // Testing loading a simple circuit. TEST(CircuitTest, SimpleLoadTest) { QflexCircuit circuit; circuit.load(std::stringstream(kSimpleCircuit)); EXPECT_EQ(circuit.num_active_qubits, 5); EXPECT_EQ(circuit.gates.size(), 22); } // Testing circuit.clear() constexpr char kClearCircuit[] = R"(2 0 h 0 0 h 1 9 h 0 9 h 1)"; TEST(CircuitTest, ClearCircuitTest) { QflexCircuit circuit; circuit.load(std::stringstream(kClearCircuit)); circuit.clear(); EXPECT_EQ(circuit.gates.size(), 0); EXPECT_EQ(circuit.num_active_qubits, 0); } } // namespace } // namespace qflex int main(int argc, char** argv) { ::testing::InitGoogleTest(&argc, argv); return RUN_ALL_TESTS(); }
#include "circuit.h" #include "gmock/gmock.h" #include "gtest/gtest.h" namespace qflex { namespace { // Passing in an invalid filename to circuit.load(). TEST(CircuitExceptionTest, InvalidFilenameInput) { QflexCircuit circuit; std::string invalid_filename = "invalid.txt"; try { circuit.load(invalid_filename); } catch (std::string msg) { EXPECT_THAT(msg, testing::HasSubstr("Cannot open circuit file invalid.txt.")); } } TEST(CircuitExceptionTest, PrintGate) { QflexGate gate; std::stringstream gate_as_string; gate.name = "cx"; gate.cycle = 1; gate.qubits = {2, 4}; gate.params = {3, 5}; gate_as_string << gate << std::endl; EXPECT_EQ(gate_as_string.str(), "gate_name: cx\nqubits: 2 4 \nparams: 3 5 \n\n"); } constexpr char kBadCircuit1[] = R"(0 h 0 0 h 1 9 h 0 9 h 1)"; constexpr char kBadCircuit2[] = R"(6 0 h 0 0 h 9 h 0 9 h 1)"; constexpr char kBadCircuit3[] = R"(2 0 h 0 0 h 1 cz 0 2 9 h 1)"; constexpr char kBadCircuit4[] = R"(2 0 h 0 0 h 1 9 cz 0 2 7 cz 1 3 9 h 1)"; constexpr char kBadCircuit5[] = R"(4 0 h 0 0 h 1 1 t 0 1 t 2 2 fsim(0.1, a) 0 1 4 h 0 4 h 1 )"; constexpr char kBadCircuit6[] = R"(2 0 h 0 0 h 1 1 t 0 1 t a 4 h 0 4 h 1)"; constexpr char kBadCircuit7[] = R"(4 0 h 0 0 h 1 4 t 2 4 t 4 4 cz 2 4 9 cz 0 2 9 cz 1 3 9 h 1)"; // Testing bad circuits TEST(CircuitExceptionTest, BadCircuits) { QflexCircuit circuit; // First line isn't the number of active qubits try { circuit.load(std::stringstream(kBadCircuit1)); } catch (std::string msg) { EXPECT_THAT(msg, testing::HasSubstr("[1: 0 h 0] First line in circuit must be the number of active qubits.")); } // Gate is missing parameters. try { circuit.load(std::stringstream(kBadCircuit2)); } catch (std::string msg) { EXPECT_THAT(msg, testing::HasSubstr("[3: 0 h] Gate must be specified as: cycle gate_name[(p1[,p2,...])] q1 [q2, ...]")); } // First number isn't cycle. try { circuit.load(std::stringstream(kBadCircuit3)); } catch (std::string msg) { EXPECT_THAT(msg, testing::HasSubstr("[4: cz 0 2] First token must be a valid cycle number.")); } // Cycle isn't increasing. try { circuit.load(std::stringstream(kBadCircuit4)); } catch (std::string msg) { EXPECT_THAT(msg, testing::HasSubstr("[5: 7 cz 1 3] Cycle number can only increase.")); } // Params aren't numbers. try { circuit.load(std::stringstream(kBadCircuit5)); } catch (std::string msg) { EXPECT_THAT(msg, testing::HasSubstr("Params must be valid numbers.")); } // Qubits aren't valid numbers. try { circuit.load(std::stringstream(kBadCircuit6)); } catch (std::string msg) { EXPECT_THAT(msg, testing::HasSubstr("[5: 1 t a] Qubit must be a valid number.")); } // Qubits are being reused. try { circuit.load(std::stringstream(kBadCircuit7)); } catch (std::string msg) { EXPECT_THAT(msg, testing::HasSubstr("[6: 4 cz 2 4] Qubits can only used once per cycle.")); } } constexpr char kSimpleCircuit[] = R"(5 0 h 0 0 h 1 0 h 2 0 h 3 0 h 5 1 t 0 1 t 1 1 t 2 1 t 3 1 t 5 2 cz 0 1 3 cx 0 2 4 cx 1 3 5 cz 2 3 6 cz 3 5 11 cz 0 1 12 cx 0 2 14 h 0 14 h 1 14 h 2 14 h 3 14 h 5)"; // Testing loading a simple circuit. TEST(CircuitTest, SimpleLoadTest) { QflexCircuit circuit; circuit.load(std::stringstream(kSimpleCircuit)); EXPECT_EQ(circuit.num_active_qubits, 5); EXPECT_EQ(circuit.gates.size(), 22); } constexpr char kClearCircuit[] = R"(2 0 h 0 0 h 1 9 h 0 9 h 1)"; // Testing circuit.clear() TEST(CircuitTest, ClearCircuitTest) { QflexCircuit circuit; circuit.load(std::stringstream(kClearCircuit)); circuit.clear(); EXPECT_EQ(circuit.gates.size(), 0); EXPECT_EQ(circuit.num_active_qubits, 0); } } // namespace } // namespace qflex int main(int argc, char** argv) { ::testing::InitGoogleTest(&argc, argv); return RUN_ALL_TESTS(); }
clean up
clean up
C++
apache-2.0
ngnrsaa/qflex,ngnrsaa/qflex,ngnrsaa/qflex,ngnrsaa/qflex
635edadc6b99cc34ac9e0c850fb363073b4a04db
model/tests/CPU_keyboard_test.cpp
model/tests/CPU_keyboard_test.cpp
#include <catch.hpp> #include "CPU.hpp" #include "aux/Aux.hpp" namespace { struct CpuFixture { Aux::TestKit testKit; model::CPU& cpu = testKit.cpu; Aux::IoDeviceMock& ioDevice = testKit.ioDevice; }; SCENARIO_METHOD( CpuFixture, "CPU skips next instruction with EX9E opcode " "when the key pressed is equal to register VX", "[keyboard]" ) { GIVEN( "A CPU with V0 set to 0 and an i/o connector with the key 0 pressed" ) { cpu.writeRegister( model::chip8::reg::v0, 0u ); ioDevice.setPressedKey( model::chip8::key::k0 ); const auto originalPc = cpu.getPc(); WHEN( "the CPU executes an EX9E operation with X equal to 0" ) { cpu.execute( 0xE09E ); THEN( "the program counter is updated to skip the next instruction" ) { REQUIRE( cpu.getPc() == originalPc + model::chip8::instruction_size_in_bytes ); } } } } SCENARIO_METHOD( CpuFixture, "CPU does not skip next instruction with EX9E opcode " "when the key pressed is not equal to register VX", "[keyboard]" ) { GIVEN( "A CPU with V0 set to 0 and an i/o connector with the key 1 pressed" ) { cpu.writeRegister( model::chip8::reg::v0, 0u ); ioDevice.setPressedKey( model::chip8::key::k1 ); const auto originalPc = cpu.getPc(); WHEN( "the CPU executes an EX9E operation with X equal to 0" ) { cpu.execute( 0xE09E ); THEN( "the program counter remains unchanged" ) { REQUIRE( cpu.getPc() == originalPc ); } } } } SCENARIO_METHOD( CpuFixture, "CPU skips next instruction with EXA1 opcode " "when the key pressed is not equal to register VX", "[keyboard]" ) { GIVEN( "A CPU with V0 set to 1 and an i/o connector with the key 0 pressed" ) { cpu.writeRegister( model::chip8::reg::v0, 1u ); ioDevice.setPressedKey( model::chip8::key::k0 ); const auto originalPc = cpu.getPc(); WHEN( "the CPU executes an EXA1 operation with X equal to 0" ) { cpu.execute( 0xE0A1 ); THEN( "the program counter is updated to skip the next instruction" ) { REQUIRE( cpu.getPc() == originalPc + model::chip8::instruction_size_in_bytes ); } } } } SCENARIO_METHOD( CpuFixture, "CPU does not skip next instruction with EXA1 opcode " "when the key pressed is equal to register VX", "[keyboard]" ) { GIVEN( "A CPU with V0 set to 0 and an i/o connector with the key 0 pressed" ) { cpu.writeRegister( model::chip8::reg::v0, 0u ); ioDevice.setPressedKey( model::chip8::key::k0 ); const auto originalPc = cpu.getPc(); WHEN( "the CPU executes an EXA1 operation with X equal to 0" ) { cpu.execute( 0xE0A1 ); THEN( "the program counter is updated to skip the next instruction" ) { REQUIRE( cpu.getPc() == originalPc ); } } } } SCENARIO_METHOD( CpuFixture, "CPU does not update the program counter with FX0A opcode " "when there is no key pressed", "[keyboard]" ) { GIVEN( "A CPU and an i/o connector with no key pressed" ) { ioDevice.setPressedKey( model::chip8::key::none ); const auto originalPc = cpu.getPc(); const auto originalV0 = cpu.readRegister( model::chip8::reg::v0 ); WHEN( "the CPU executes an FX0A" ) { cpu.execute( 0xF00A ); THEN( "the program counter remains unchanged (the CPU is halted)" ) { REQUIRE( cpu.getPc() == originalPc ); } AND_THEN( "register V0 remains unchanged" ) { REQUIRE( cpu.readRegister( model::chip8::reg::v0 ) == originalV0 ); } } } } SCENARIO_METHOD( CpuFixture, "A halted CPU (after a FX0A opcode) does not update the program counter " "when the CPU executes another instruction", "[keyboard]" ) { GIVEN( "A halted CPU and an i/o connector with no key pressed" ) { ioDevice.setPressedKey( model::chip8::key::none ); cpu.execute( 0xF00A ); const auto originalPc = cpu.getPc(); const auto originalV0 = cpu.readRegister( model::chip8::reg::v0 ); WHEN( "the CPU cycles" ) { cpu.execute( 0xF00A ); THEN( "the program counter remains unchanged (the CPU is halted)" ) { REQUIRE( cpu.getPc() == originalPc ); } AND_THEN( "register V0 remains unchanged" ) { REQUIRE( cpu.readRegister( model::chip8::reg::v0 ) == originalV0 ); } } } } SCENARIO_METHOD( CpuFixture, "CPU sets register X to the value of the pressed key " "after any key is pressed during a FX0A operation", "[keyboard]" ) { GIVEN( "A CPU and an i/o connector with the key F pressed" ) { ioDevice.setPressedKey( model::chip8::key::kf ); const auto originalPc = cpu.getPc(); WHEN( "the CPU executes an FX0A opcode" ) { cpu.execute( 0xF00A ); THEN( "the pressed key is stored in V0" ) { REQUIRE( cpu.readRegister( model::chip8::reg::v0 ) == 0xF ); } } } } } // unnamed namespace
#include <catch.hpp> #include "CPU.hpp" #include "aux/Aux.hpp" namespace { struct CpuFixture { Aux::TestKit testKit; model::CPU& cpu = testKit.cpu; Aux::IoDeviceMock& ioDevice = testKit.ioDevice; }; SCENARIO_METHOD( CpuFixture, "CPU skips next instruction with EX9E opcode " "when the key pressed is equal to register VX", "[keyboard]" ) { GIVEN( "A CPU with V0 set to 0 and an i/o connector with the key 0 pressed" ) { cpu.writeRegister( model::chip8::reg::v0, 0u ); ioDevice.setPressedKey( model::chip8::key::k0 ); const auto originalPc = cpu.getPc(); WHEN( "the CPU executes an EX9E operation with X equal to 0" ) { cpu.execute( 0xE09E ); THEN( "the program counter is updated to skip the next instruction" ) { REQUIRE( cpu.getPc() == originalPc + model::chip8::instruction_size_in_bytes ); } } } } SCENARIO_METHOD( CpuFixture, "CPU does not skip next instruction with EX9E opcode " "when the key pressed is not equal to register VX", "[keyboard]" ) { GIVEN( "A CPU with V0 set to 0 and an i/o connector with the key 1 pressed" ) { cpu.writeRegister( model::chip8::reg::v0, 0u ); ioDevice.setPressedKey( model::chip8::key::k1 ); const auto originalPc = cpu.getPc(); WHEN( "the CPU executes an EX9E operation with X equal to 0" ) { cpu.execute( 0xE09E ); THEN( "the program counter remains unchanged" ) { REQUIRE( cpu.getPc() == originalPc ); } } } } SCENARIO_METHOD( CpuFixture, "CPU skips next instruction with EXA1 opcode " "when the key pressed is not equal to register VX", "[keyboard]" ) { GIVEN( "A CPU with V0 set to 1 and an i/o connector with the key 0 pressed" ) { cpu.writeRegister( model::chip8::reg::v0, 1u ); ioDevice.setPressedKey( model::chip8::key::k0 ); const auto originalPc = cpu.getPc(); WHEN( "the CPU executes an EXA1 operation with X equal to 0" ) { cpu.execute( 0xE0A1 ); THEN( "the program counter is updated to skip the next instruction" ) { REQUIRE( cpu.getPc() == originalPc + model::chip8::instruction_size_in_bytes ); } } } } SCENARIO_METHOD( CpuFixture, "CPU does not skip next instruction with EXA1 opcode " "when the key pressed is equal to register VX", "[keyboard]" ) { GIVEN( "A CPU with V0 set to 0 and an i/o connector with the key 0 pressed" ) { cpu.writeRegister( model::chip8::reg::v0, 0u ); ioDevice.setPressedKey( model::chip8::key::k0 ); const auto originalPc = cpu.getPc(); WHEN( "the CPU executes an EXA1 operation with X equal to 0" ) { cpu.execute( 0xE0A1 ); THEN( "the program counter is updated to skip the next instruction" ) { REQUIRE( cpu.getPc() == originalPc ); } } } } SCENARIO_METHOD( CpuFixture, "CPU does not update the program counter with FX0A opcode " "when there is no key pressed", "[keyboard]" ) { GIVEN( "A CPU and an i/o connector with no key pressed" ) { ioDevice.setPressedKey( model::chip8::key::none ); const auto originalPc = cpu.getPc(); const auto originalV0 = cpu.readRegister( model::chip8::reg::v0 ); WHEN( "the CPU executes an FX0A" ) { cpu.execute( 0xF00A ); THEN( "the program counter remains unchanged (the CPU is halted)" ) { REQUIRE( cpu.getPc() == originalPc ); } AND_THEN( "register V0 remains unchanged" ) { REQUIRE( cpu.readRegister( model::chip8::reg::v0 ) == originalV0 ); } } } } SCENARIO_METHOD( CpuFixture, "A halted CPU (after a FX0A opcode) does not update the program counter " "when the CPU executes another instruction", "[keyboard]" ) { GIVEN( "A halted CPU and an i/o connector with no key pressed" ) { ioDevice.setPressedKey( model::chip8::key::none ); cpu.execute( 0xF00A ); const auto originalPc = cpu.getPc(); const auto originalV0 = cpu.readRegister( model::chip8::reg::v0 ); WHEN( "the CPU cycles" ) { cpu.execute( 0xF00A ); THEN( "the program counter remains unchanged (the CPU is halted)" ) { REQUIRE( cpu.getPc() == originalPc ); } AND_THEN( "register V0 remains unchanged" ) { REQUIRE( cpu.readRegister( model::chip8::reg::v0 ) == originalV0 ); } } } } SCENARIO_METHOD( CpuFixture, "CPU sets register X to the value of the pressed key " "after any key is pressed during a FX0A operation", "[keyboard]" ) { GIVEN( "A CPU and an i/o connector with the key F pressed" ) { ioDevice.setPressedKey( model::chip8::key::kf ); WHEN( "the CPU executes an FX0A opcode" ) { cpu.execute( 0xF00A ); THEN( "the pressed key is stored in V0" ) { REQUIRE( cpu.readRegister( model::chip8::reg::v0 ) == 0xF ); } } } } } // unnamed namespace
Remove warning from test
Remove warning from test
C++
mit
benvenutti/core8,benvenutti/core8
031e67c0f39154179091048dc5a1418c77e58219
src/tstock.cxx
src/tstock.cxx
/* * Connection pooling for the translation server. * * author: Max Kellermann <[email protected]> */ #include "tstock.hxx" #include "translate_client.hxx" #include "stock.hxx" #include "tcp_stock.hxx" #include "lease.hxx" #include "pool.hxx" #include "net/AllocatedSocketAddress.hxx" #include <daemon/log.h> #include <assert.h> #include <sys/un.h> #include <sys/socket.h> struct tstock { StockMap &tcp_stock; AllocatedSocketAddress address; const char *const address_string; tstock(StockMap &_tcp_stock, const char *path) :tcp_stock(_tcp_stock), address_string(path) { address.SetLocal(path); } }; struct tstock_request { struct pool &pool; struct tstock &stock; StockItem *item; const TranslateRequest &request; const TranslateHandler &handler; void *handler_ctx; struct async_operation_ref &async_ref; tstock_request(struct tstock &_stock, struct pool &_pool, const TranslateRequest &_request, const TranslateHandler &_handler, void *_ctx, struct async_operation_ref &_async_ref) :pool(_pool), stock(_stock), request(_request), handler(_handler), handler_ctx(_ctx), async_ref(_async_ref) {} }; /* * socket lease * */ static void tstock_socket_release(bool reuse, void *ctx) { tstock_request *r = (tstock_request *)ctx; tcp_stock_put(&r->stock.tcp_stock, *r->item, !reuse); } static const struct lease tstock_socket_lease = { .release = tstock_socket_release, }; /* * stock callback * */ static void tstock_stock_ready(StockItem &item, void *ctx) { tstock_request *r = (tstock_request *)ctx; r->item = &item; translate(r->pool, tcp_stock_item_get(item), tstock_socket_lease, r, r->request, r->handler, r->handler_ctx, r->async_ref); } static void tstock_stock_error(GError *error, void *ctx) { tstock_request *r = (tstock_request *)ctx; r->handler.error(error, r->handler_ctx); } static constexpr StockGetHandler tstock_stock_handler = { .ready = tstock_stock_ready, .error = tstock_stock_error, }; /* * constructor * */ struct tstock * tstock_new(struct pool &pool, StockMap &tcp_stock, const char *socket_path) { return NewFromPool<tstock>(pool, tcp_stock, socket_path); } void tstock_free(struct pool &pool, struct tstock *stock) { DeleteFromPool(pool, stock); } void tstock_translate(struct tstock &stock, struct pool &pool, const TranslateRequest &request, const TranslateHandler &handler, void *ctx, struct async_operation_ref &async_ref) { auto r = NewFromPool<tstock_request>(pool, stock, pool, request, handler, ctx, async_ref); tcp_stock_get(&stock.tcp_stock, &pool, stock.address_string, false, SocketAddress::Null(), stock.address, 10, &tstock_stock_handler, r, &async_ref); }
/* * Connection pooling for the translation server. * * author: Max Kellermann <[email protected]> */ #include "tstock.hxx" #include "translate_client.hxx" #include "stock.hxx" #include "tcp_stock.hxx" #include "lease.hxx" #include "pool.hxx" #include "net/AllocatedSocketAddress.hxx" #include <daemon/log.h> #include <assert.h> #include <sys/un.h> #include <sys/socket.h> struct tstock { StockMap &tcp_stock; AllocatedSocketAddress address; const char *const address_string; tstock(StockMap &_tcp_stock, const char *path) :tcp_stock(_tcp_stock), address_string(path) { address.SetLocal(path); } }; struct TranslateStockRequest { struct pool &pool; struct tstock &stock; StockItem *item; const TranslateRequest &request; const TranslateHandler &handler; void *handler_ctx; struct async_operation_ref &async_ref; TranslateStockRequest(struct tstock &_stock, struct pool &_pool, const TranslateRequest &_request, const TranslateHandler &_handler, void *_ctx, struct async_operation_ref &_async_ref) :pool(_pool), stock(_stock), request(_request), handler(_handler), handler_ctx(_ctx), async_ref(_async_ref) {} }; /* * socket lease * */ static void tstock_socket_release(bool reuse, void *ctx) { TranslateStockRequest *r = (TranslateStockRequest *)ctx; tcp_stock_put(&r->stock.tcp_stock, *r->item, !reuse); } static const struct lease tstock_socket_lease = { .release = tstock_socket_release, }; /* * stock callback * */ static void tstock_stock_ready(StockItem &item, void *ctx) { TranslateStockRequest *r = (TranslateStockRequest *)ctx; r->item = &item; translate(r->pool, tcp_stock_item_get(item), tstock_socket_lease, r, r->request, r->handler, r->handler_ctx, r->async_ref); } static void tstock_stock_error(GError *error, void *ctx) { TranslateStockRequest *r = (TranslateStockRequest *)ctx; r->handler.error(error, r->handler_ctx); } static constexpr StockGetHandler tstock_stock_handler = { .ready = tstock_stock_ready, .error = tstock_stock_error, }; /* * constructor * */ struct tstock * tstock_new(struct pool &pool, StockMap &tcp_stock, const char *socket_path) { return NewFromPool<tstock>(pool, tcp_stock, socket_path); } void tstock_free(struct pool &pool, struct tstock *stock) { DeleteFromPool(pool, stock); } void tstock_translate(struct tstock &stock, struct pool &pool, const TranslateRequest &request, const TranslateHandler &handler, void *ctx, struct async_operation_ref &async_ref) { auto r = NewFromPool<TranslateStockRequest>(pool, stock, pool, request, handler, ctx, async_ref); tcp_stock_get(&stock.tcp_stock, &pool, stock.address_string, false, SocketAddress::Null(), stock.address, 10, &tstock_stock_handler, r, &async_ref); }
rename with CamelCase
tstock: rename with CamelCase
C++
bsd-2-clause
CM4all/beng-proxy,CM4all/beng-proxy,CM4all/beng-proxy,CM4all/beng-proxy,CM4all/beng-proxy,CM4all/beng-proxy
eccc62cf1def9a9db019738bfa438fecc302a6df
tests/utils/StringTest.cpp
tests/utils/StringTest.cpp
//Copyright (c) 2015 Ultimaker B.V. //CuraEngine is released under the terms of the AGPLv3 or higher. #include "StringTest.h" #include <iomanip> #include <sstream> // ostringstream #include <../src/utils/intpoint.h> #include <../src/utils/string.h> namespace cura { CPPUNIT_TEST_SUITE_REGISTRATION(StringTest); void StringTest::setUp() { //Do nothing. } void StringTest::tearDown() { //Do nothing. } void StringTest::writeInt2mmTest10000Negative() { writeInt2mmAssert(-10000); } void StringTest::writeInt2mmTest1000Negative() { writeInt2mmAssert(-1000); } void StringTest::writeInt2mmTest100Negative() { writeInt2mmAssert(-100); } void StringTest::writeInt2mmTest10Negative() { writeInt2mmAssert(-10); } void StringTest::writeInt2mmTest1Negative() { writeInt2mmAssert(-1); } void StringTest::writeInt2mmTest0() { writeInt2mmAssert(0); } void StringTest::writeInt2mmTest1() { writeInt2mmAssert(1); } void StringTest::writeInt2mmTest10() { writeInt2mmAssert(10); } void StringTest::writeInt2mmTest100() { writeInt2mmAssert(100); } void StringTest::writeInt2mmTest1000() { writeInt2mmAssert(1000); } void StringTest::writeInt2mmTest10000() { writeInt2mmAssert(10000); } void StringTest::writeInt2mmTest123456789() { writeInt2mmAssert(123456789); } void StringTest::writeInt2mmTestMax() { writeInt2mmAssert(std::numeric_limits<int64_t>::max()/1001); // divide by 1001, because MM2INT first converts to int and then multiplies by 1000, which causes overflow for the highest integer. } void StringTest::writeInt2mmAssert(int64_t in) { std::ostringstream ss; writeInt2mm(in, ss); ss.flush(); std::string str = ss.str(); if (!ss.good()) { char buffer[200]; sprintf(buffer, "The integer %ld was printed as '%s' which was a bad string!", in, str.c_str()); CPPUNIT_ASSERT_MESSAGE(std::string(buffer), false); } int64_t out = MM2INT(strtod(str.c_str(), nullptr)); char buffer[200]; sprintf(buffer, "The integer %ld was printed as '%s' which was interpreted as %ld rather than %ld!", in, str.c_str(), out, in); CPPUNIT_ASSERT_MESSAGE(std::string(buffer), in == out); } void StringTest::writeDoubleToStreamTest10000Negative() { writeDoubleToStreamAssert(-10.000); } void StringTest::writeDoubleToStreamTest1000Negative() { writeDoubleToStreamAssert(-1.000); } void StringTest::writeDoubleToStreamTest100Negative() { writeDoubleToStreamAssert(-.100); } void StringTest::writeDoubleToStreamTest10Negative() { writeDoubleToStreamAssert(-.010); } void StringTest::writeDoubleToStreamTest1Negative() { writeDoubleToStreamAssert(-.001); } void StringTest::writeDoubleToStreamTest0() { writeDoubleToStreamAssert(0.000); } void StringTest::writeDoubleToStreamTest1() { writeDoubleToStreamAssert(.001); } void StringTest::writeDoubleToStreamTest10() { writeDoubleToStreamAssert(.010); } void StringTest::writeDoubleToStreamTest100() { writeDoubleToStreamAssert(.100); } void StringTest::writeDoubleToStreamTest1000() { writeDoubleToStreamAssert(1.000); } void StringTest::writeDoubleToStreamTest10000() { writeDoubleToStreamAssert(10.000); } void StringTest::writeDoubleToStreamTest123456789() { writeDoubleToStreamAssert(123456.789); } void StringTest::writeDoubleToStreamTestMin() { writeDoubleToStreamAssert(std::numeric_limits<double>::min()); } void StringTest::writeDoubleToStreamTestMax() { writeDoubleToStreamAssert(std::numeric_limits<double>::max()); } void StringTest::writeDoubleToStreamTestLowest() { writeDoubleToStreamAssert(std::numeric_limits<double>::lowest()); } void StringTest::writeDoubleToStreamTestLowestNeg() { writeDoubleToStreamAssert(-std::numeric_limits<double>::lowest()); } void StringTest::writeDoubleToStreamTestLow() { writeDoubleToStreamAssert(0.00000001d); } void StringTest::writeDoubleToStreamAssert(double in, unsigned int precision) { std::ostringstream ss; writeDoubleToStream(precision, in, ss); ss.flush(); std::string str = ss.str(); if (!ss.good()) { char buffer[8000]; sprintf(buffer, "The double %f was printed as '%s' which was a bad string!", in, str.c_str()); CPPUNIT_ASSERT_MESSAGE(std::string(buffer), false); } double out = strtod(str.c_str(), nullptr); std::ostringstream in_ss; in_ss << std::fixed << std::setprecision(precision) << in; std::string in_str = in_ss.str(); double in_reinterpreted = strtod(in_str.c_str(), nullptr); char buffer[8000]; sprintf(buffer, "The double %f was printed as '%s' which was interpreted as %f rather than %f!", in, str.c_str(), out, in_reinterpreted); if (in_reinterpreted != out) std::cerr << buffer << "\n"; CPPUNIT_ASSERT_MESSAGE(std::string(buffer), in_reinterpreted == out); } }
//Copyright (c) 2015 Ultimaker B.V. //CuraEngine is released under the terms of the AGPLv3 or higher. #include "StringTest.h" #include <iomanip> #include <sstream> // ostringstream #include <../src/utils/intpoint.h> #include <../src/utils/string.h> namespace cura { CPPUNIT_TEST_SUITE_REGISTRATION(StringTest); void StringTest::setUp() { //Do nothing. } void StringTest::tearDown() { //Do nothing. } void StringTest::writeInt2mmTest10000Negative() { writeInt2mmAssert(-10000); } void StringTest::writeInt2mmTest1000Negative() { writeInt2mmAssert(-1000); } void StringTest::writeInt2mmTest100Negative() { writeInt2mmAssert(-100); } void StringTest::writeInt2mmTest10Negative() { writeInt2mmAssert(-10); } void StringTest::writeInt2mmTest1Negative() { writeInt2mmAssert(-1); } void StringTest::writeInt2mmTest0() { writeInt2mmAssert(0); } void StringTest::writeInt2mmTest1() { writeInt2mmAssert(1); } void StringTest::writeInt2mmTest10() { writeInt2mmAssert(10); } void StringTest::writeInt2mmTest100() { writeInt2mmAssert(100); } void StringTest::writeInt2mmTest1000() { writeInt2mmAssert(1000); } void StringTest::writeInt2mmTest10000() { writeInt2mmAssert(10000); } void StringTest::writeInt2mmTest123456789() { writeInt2mmAssert(123456789); } void StringTest::writeInt2mmTestMax() { writeInt2mmAssert(std::numeric_limits<int64_t>::max() / 1001); // divide by 1001, because MM2INT first converts to int and then multiplies by 1000, which causes overflow for the highest integer. } void StringTest::writeInt2mmAssert(int64_t in) { std::ostringstream ss; writeInt2mm(in, ss); ss.flush(); std::string str = ss.str(); if (!ss.good()) { char buffer[200]; sprintf(buffer, "The integer %ld was printed as '%s' which was a bad string!", in, str.c_str()); CPPUNIT_ASSERT_MESSAGE(std::string(buffer), false); } int64_t out = MM2INT(strtod(str.c_str(), nullptr)); char buffer[200]; sprintf(buffer, "The integer %ld was printed as '%s' which was interpreted as %ld rather than %ld!", in, str.c_str(), out, in); CPPUNIT_ASSERT_MESSAGE(std::string(buffer), in == out); } void StringTest::writeDoubleToStreamTest10000Negative() { writeDoubleToStreamAssert(-10.000); } void StringTest::writeDoubleToStreamTest1000Negative() { writeDoubleToStreamAssert(-1.000); } void StringTest::writeDoubleToStreamTest100Negative() { writeDoubleToStreamAssert(-.100); } void StringTest::writeDoubleToStreamTest10Negative() { writeDoubleToStreamAssert(-.010); } void StringTest::writeDoubleToStreamTest1Negative() { writeDoubleToStreamAssert(-.001); } void StringTest::writeDoubleToStreamTest0() { writeDoubleToStreamAssert(0.000); } void StringTest::writeDoubleToStreamTest1() { writeDoubleToStreamAssert(.001); } void StringTest::writeDoubleToStreamTest10() { writeDoubleToStreamAssert(.010); } void StringTest::writeDoubleToStreamTest100() { writeDoubleToStreamAssert(.100); } void StringTest::writeDoubleToStreamTest1000() { writeDoubleToStreamAssert(1.000); } void StringTest::writeDoubleToStreamTest10000() { writeDoubleToStreamAssert(10.000); } void StringTest::writeDoubleToStreamTest123456789() { writeDoubleToStreamAssert(123456.789); } void StringTest::writeDoubleToStreamTestMin() { writeDoubleToStreamAssert(std::numeric_limits<double>::min()); } void StringTest::writeDoubleToStreamTestMax() { writeDoubleToStreamAssert(std::numeric_limits<double>::max()); } void StringTest::writeDoubleToStreamTestLowest() { writeDoubleToStreamAssert(std::numeric_limits<double>::lowest()); } void StringTest::writeDoubleToStreamTestLowestNeg() { writeDoubleToStreamAssert(-std::numeric_limits<double>::lowest()); } void StringTest::writeDoubleToStreamTestLow() { writeDoubleToStreamAssert(0.00000001d); } void StringTest::writeDoubleToStreamAssert(double in, unsigned int precision) { std::ostringstream ss; writeDoubleToStream(precision, in, ss); ss.flush(); std::string str = ss.str(); if (!ss.good()) { char buffer[8000]; sprintf(buffer, "The double %f was printed as '%s' which was a bad string!", in, str.c_str()); CPPUNIT_ASSERT_MESSAGE(std::string(buffer), false); } double out = strtod(str.c_str(), nullptr); std::ostringstream in_ss; in_ss << std::fixed << std::setprecision(precision) << in; std::string in_str = in_ss.str(); double in_reinterpreted = strtod(in_str.c_str(), nullptr); char buffer[8000]; sprintf(buffer, "The double %f was printed as '%s' which was interpreted as %f rather than %f!", in, str.c_str(), out, in_reinterpreted); if (in_reinterpreted != out) std::cerr << buffer << "\n"; CPPUNIT_ASSERT_MESSAGE(std::string(buffer), in_reinterpreted == out); } }
Add whitespace around binary operators
Add whitespace around binary operators As per our code style. Contributes to issue CURA-2627.
C++
agpl-3.0
alephobjects/CuraEngine,ROBO3D/CuraEngine,Ultimaker/CuraEngine,alephobjects/CuraEngine,ROBO3D/CuraEngine,ROBO3D/CuraEngine,alephobjects/CuraEngine,Ultimaker/CuraEngine
bbcea7341d9ae09775a37f03fbc4ccac6f1b5912
src/media/mediamodel.cpp
src/media/mediamodel.cpp
#include "mediamodel.h" #include "mediascanner.h" #include "dbreader.h" #include "backend.h" #define DEBUG if (1) qDebug() << __PRETTY_FUNCTION__ MediaModel::MediaModel(QObject *parent) : QAbstractItemModel(parent), m_loading(false), m_loaded(false), m_reader(0), m_readerThread(0) { } MediaModel::~MediaModel() { } QString MediaModel::part() const { return m_structure.split("|").value(m_cursor.length()); } QString MediaModel::mediaType() const { return m_mediaType; } void MediaModel::setMediaType(const QString &type) { m_mediaType = type; emit mediaTypeChanged(); beginResetModel(); initialize(); endResetModel(); QSqlDriver *driver = Backend::instance()->mediaDatabase().driver(); QSqlRecord record = driver->record(m_mediaType); if (record.isEmpty()) qWarning() << "Table " << type << " is not valid it seems"; QHash<int, QByteArray> hash = roleNames(); hash.insert(Qt::UserRole, "dotdot"); hash.insert(Qt::UserRole+1, "isLeaf"); for (int i = 0; i < record.count(); i++) { hash.insert(Qt::UserRole + i + 2, record.fieldName(i).toUtf8()); } setRoleNames(hash); } void MediaModel::addSearchPath(const QString &path, const QString &name) { QMetaObject::invokeMethod(MediaScanner::instance(), "addSearchPath", Qt::QueuedConnection, Q_ARG(QString, "picture"), Q_ARG(QString, path), Q_ARG(QString, name)); } void MediaModel::removeSearchPath(int index) { Q_UNUSED(index); } QString MediaModel::structure() const { return m_structure; } void MediaModel::setStructure(const QString &str) { m_structure = str; emit structureChanged(); beginResetModel(); initialize(); endResetModel(); } void MediaModel::enter(int index) { Q_UNUSED(index); if (m_cursor.count() + 1 == m_structure.split("|").count() && index != 0 /* up on leaf node is OK */) { DEBUG << "Refusing to enter leaf node"; return; } if (index == 0 && !m_cursor.isEmpty()) { back(); return; } DEBUG << "Entering " << index; m_cursor.append(m_data[index]); beginResetModel(); initialize(); endResetModel(); emit partChanged(); } void MediaModel::back() { beginResetModel(); m_cursor.removeLast(); initialize(); endResetModel(); emit partChanged(); } QVariant MediaModel::data(const QModelIndex &index, int role) const { if (!index.isValid()) return QVariant(); const QHash<QString, QVariant> &data = m_data[index.row()]; const QHash<int, QByteArray> hash = roleNames(); return data.value(hash.value(role)); } QModelIndex MediaModel::index(int row, int col, const QModelIndex &parent) const { if (parent.isValid()) return QModelIndex(); return createIndex(row, col); } QModelIndex MediaModel::parent(const QModelIndex &idx) const { Q_UNUSED(idx); return QModelIndex(); } int MediaModel::rowCount(const QModelIndex &parent) const { if (parent.isValid()) return 0; return m_data.count(); } int MediaModel::columnCount(const QModelIndex &idx) const { Q_UNUSED(idx); return 1; } bool MediaModel::hasChildren(const QModelIndex &parent) const { return !parent.isValid(); } bool MediaModel::canFetchMore(const QModelIndex &parent) const { if (parent.isValid() || m_mediaType.isEmpty() || m_structure.isEmpty()) return false; return !m_loading && !m_loaded; } void MediaModel::fetchMore(const QModelIndex &parent) { if (!canFetchMore(parent)) return; initialize(); QSqlQuery q = query(); DEBUG << q.lastQuery(); QMetaObject::invokeMethod(m_reader, "execute", Qt::QueuedConnection, Q_ARG(QSqlQuery, q)); } void MediaModel::initialize() { m_data.clear(); DbReader *newReader = new DbReader; if (m_reader) { disconnect(m_reader, 0, this, 0); m_reader->stop(); m_reader->deleteLater(); } m_reader = newReader; if (!m_readerThread) { m_readerThread = new QThread(this); m_readerThread->start(); } m_reader->moveToThread(m_readerThread); QMetaObject::invokeMethod(m_reader, "initialize", Q_ARG(QSqlDatabase, Backend::instance()->mediaDatabase())); connect(m_reader, SIGNAL(dataReady(DbReader *, QList<QSqlRecord>, void *)), this, SLOT(handleDataReady(DbReader *, QList<QSqlRecord>, void *))); m_loading = m_loaded = false; } void MediaModel::handleDataReady(DbReader *reader, const QList<QSqlRecord> &records, void *node) { Q_ASSERT(reader == m_reader); Q_UNUSED(reader); Q_UNUSED(node); DEBUG << "Received response from db of size " << records.size(); if (records.isEmpty()) return; if (!m_cursor.isEmpty()) { beginInsertRows(QModelIndex(), 0, records.count()); QHash<QString, QVariant> data; data.insert("display", tr("..")); data.insert("dotdot", true); data.insert("isLeaf", false); m_data.append(data); } else { beginInsertRows(QModelIndex(), 0, records.count() - 1); } bool isLeaf = false; if (m_cursor.count() + 1 == m_structure.split("|").count()) isLeaf = true; for (int i = 0; i < records.count(); i++) { QHash<QString, QVariant> data; for (int j = 0; j < records[i].count(); j++) { data.insert(records[i].fieldName(j), records[i].value(j)); } QStringList cols = m_structure.split("|").value(m_cursor.count()).split(","); QStringList displayString; for (int j = 0; j < cols.count(); j++) { displayString << records[i].value(cols[j]).toString(); } data.insert("display", displayString.join(", ")); data.insert("dotdot", false); data.insert("isLeaf", isLeaf); m_data.append(data); } m_loading = false; m_loaded = true; endInsertRows(); } void MediaModel::handleDatabaseUpdated(const QList<QSqlRecord> &records) { Q_UNUSED(records); // not implemented yet } // ## BIG FAT FIXME: Fix the string escaping to prevent sql injection! QSqlQuery MediaModel::query() { QString q; QStringList parts = m_structure.split("|"); QString curPart = parts[m_cursor.count()]; QSqlQuery query(Backend::instance()->mediaDatabase()); query.setForwardOnly(true); if (parts.count() == 1) { query.prepare(QString("SELECT * FROM %1").arg(m_mediaType)); return query; } QStringList where; for (int i = 0; i < m_cursor.count(); i++) { QString part = parts[i]; QStringList subParts = part.split(","); for (int j = 0; j < subParts.count(); j++) where.append(subParts[j] + " = \"" + m_cursor[i].value(subParts[j]).toString() + "\""); } QString conditions = where.join(" AND "); if (conditions.isEmpty()) { query.prepare(QString("SELECT * FROM %1 GROUP BY %2").arg(m_mediaType).arg(curPart)); } else { query.prepare(QString("SELECT DISTINCT %1 FROM %2 WHERE %3").arg(curPart).arg(m_mediaType).arg(conditions)); } return query; }
#include "mediamodel.h" #include "mediascanner.h" #include "dbreader.h" #include "backend.h" #define DEBUG if (1) qDebug() << __PRETTY_FUNCTION__ MediaModel::MediaModel(QObject *parent) : QAbstractItemModel(parent), m_loading(false), m_loaded(false), m_reader(0), m_readerThread(0) { } MediaModel::~MediaModel() { } QString MediaModel::part() const { return m_structure.split("|").value(m_cursor.length()); } QString MediaModel::mediaType() const { return m_mediaType; } void MediaModel::setMediaType(const QString &type) { m_mediaType = type; emit mediaTypeChanged(); beginResetModel(); initialize(); endResetModel(); QSqlDriver *driver = Backend::instance()->mediaDatabase().driver(); QSqlRecord record = driver->record(m_mediaType); if (record.isEmpty()) qWarning() << "Table " << type << " is not valid it seems"; QHash<int, QByteArray> hash = roleNames(); hash.insert(Qt::UserRole, "dotdot"); hash.insert(Qt::UserRole+1, "isLeaf"); for (int i = 0; i < record.count(); i++) { hash.insert(Qt::UserRole + i + 2, record.fieldName(i).toUtf8()); } setRoleNames(hash); } void MediaModel::addSearchPath(const QString &path, const QString &name) { QMetaObject::invokeMethod(MediaScanner::instance(), "addSearchPath", Qt::QueuedConnection, Q_ARG(QString, "picture"), Q_ARG(QString, path), Q_ARG(QString, name)); } void MediaModel::removeSearchPath(int index) { Q_UNUSED(index); } QString MediaModel::structure() const { return m_structure; } void MediaModel::setStructure(const QString &str) { m_structure = str; emit structureChanged(); beginResetModel(); initialize(); endResetModel(); } void MediaModel::enter(int index) { Q_UNUSED(index); if (m_cursor.count() + 1 == m_structure.split("|").count() && index != 0 /* up on leaf node is OK */) { DEBUG << "Refusing to enter leaf node"; return; } if (index == 0 && !m_cursor.isEmpty()) { back(); return; } DEBUG << "Entering " << index; m_cursor.append(m_data[index]); beginResetModel(); initialize(); endResetModel(); emit partChanged(); } void MediaModel::back() { beginResetModel(); m_cursor.removeLast(); initialize(); endResetModel(); emit partChanged(); } QVariant MediaModel::data(const QModelIndex &index, int role) const { if (!index.isValid()) return QVariant(); const QHash<QString, QVariant> &data = m_data[index.row()]; const QHash<int, QByteArray> hash = roleNames(); return data.value(hash.value(role)); } QModelIndex MediaModel::index(int row, int col, const QModelIndex &parent) const { if (parent.isValid()) return QModelIndex(); return createIndex(row, col); } QModelIndex MediaModel::parent(const QModelIndex &idx) const { Q_UNUSED(idx); return QModelIndex(); } int MediaModel::rowCount(const QModelIndex &parent) const { if (parent.isValid()) return 0; return m_data.count(); } int MediaModel::columnCount(const QModelIndex &idx) const { Q_UNUSED(idx); return 1; } bool MediaModel::hasChildren(const QModelIndex &parent) const { return !parent.isValid(); } bool MediaModel::canFetchMore(const QModelIndex &parent) const { if (parent.isValid() || m_mediaType.isEmpty() || m_structure.isEmpty()) return false; return !m_loading && !m_loaded; } void MediaModel::fetchMore(const QModelIndex &parent) { if (!canFetchMore(parent)) return; initialize(); QSqlQuery q = query(); DEBUG << q.lastQuery(); QMetaObject::invokeMethod(m_reader, "execute", Qt::QueuedConnection, Q_ARG(QSqlQuery, q)); } void MediaModel::initialize() { m_data.clear(); DbReader *newReader = new DbReader; if (m_reader) { disconnect(m_reader, 0, this, 0); m_reader->stop(); m_reader->deleteLater(); } m_reader = newReader; if (!m_readerThread) { m_readerThread = new QThread(this); m_readerThread->start(); } m_reader->moveToThread(m_readerThread); QMetaObject::invokeMethod(m_reader, "initialize", Q_ARG(QSqlDatabase, Backend::instance()->mediaDatabase())); connect(m_reader, SIGNAL(dataReady(DbReader *, QList<QSqlRecord>, void *)), this, SLOT(handleDataReady(DbReader *, QList<QSqlRecord>, void *))); m_loading = m_loaded = false; } void MediaModel::handleDataReady(DbReader *reader, const QList<QSqlRecord> &records, void *node) { Q_ASSERT(reader == m_reader); Q_UNUSED(reader); Q_UNUSED(node); DEBUG << "Received response from db of size " << records.size(); if (records.isEmpty()) return; if (!m_cursor.isEmpty()) { beginInsertRows(QModelIndex(), 0, records.count()); QHash<QString, QVariant> data; data.insert("display", tr("..")); data.insert("dotdot", true); data.insert("isLeaf", false); m_data.append(data); } else { beginInsertRows(QModelIndex(), 0, records.count() - 1); } bool isLeaf = false; if (m_cursor.count() + 1 == m_structure.split("|").count()) isLeaf = true; for (int i = 0; i < records.count(); i++) { QHash<QString, QVariant> data; for (int j = 0; j < records[i].count(); j++) { data.insert(records[i].fieldName(j), records[i].value(j)); } QStringList cols = m_structure.split("|").value(m_cursor.count()).split(","); QStringList displayString; for (int j = 0; j < cols.count(); j++) { displayString << records[i].value(cols[j]).toString(); } data.insert("display", displayString.join(", ")); data.insert("dotdot", false); data.insert("isLeaf", isLeaf); m_data.append(data); } m_loading = false; m_loaded = true; endInsertRows(); } void MediaModel::handleDatabaseUpdated(const QList<QSqlRecord> &records) { Q_UNUSED(records); // not implemented yet } // ## BIG FAT FIXME: Fix the string escaping to prevent sql injection! QSqlQuery MediaModel::query() { QString q; QStringList parts = m_structure.split("|"); QString curPart = parts[m_cursor.count()]; QSqlQuery query(Backend::instance()->mediaDatabase()); query.setForwardOnly(true); QStringList where; for (int i = 0; i < m_cursor.count(); i++) { QString part = parts[i]; QStringList subParts = part.split(","); for (int j = 0; j < subParts.count(); j++) where.append(subParts[j] + " = \"" + m_cursor[i].value(subParts[j]).toString() + "\""); } const bool lastPart = m_cursor.count() == parts.count()-1; QString queryString = QString("SELECT %1 FROM %2 ").arg(lastPart ? "*" : curPart).arg(m_mediaType); if (!where.isEmpty()) { QString conditions = where.join(" AND "); queryString.append(QString("WHERE %1 ").arg(conditions)); } if (!lastPart) queryString.append(QString("GROUP BY %1 ").arg(curPart)); queryString.append(QString("ORDER BY %1").arg(curPart)); query.prepare(queryString); return query; }
Optimize the query builder
Optimize the query builder
C++
bsd-3-clause
qtmediahub/sasquatch,qtmediahub/sasquatch,qtmediahub/sasquatch
602854e8135bafa2568e8097d343f09f2d51f57b
redis/reply.cc
redis/reply.cc
#include "reply.hh" #include "log.hh" namespace redis { static logging::logger logging("reply"); future<redis_message> redis_message::make_list_bytes(map_return_type r, size_t begin, size_t end) { auto m = make_lw_shared<scattered_message<char>> (); m->append(sstring(sprint("*%d\r\n", end - begin + 1))); auto& data = r->data(); for (size_t i = 0; i < data.size(); ++i) { if (i >= begin && i <= end) { write_bytes(m, *(data[i].first)); } } m->on_delete([ r = std::move(foreign_ptr { r }) ] {}); return make_ready_future<redis_message>(m); } future<redis_message> redis_message::make_list_bytes(map_return_type r, size_t index) { assert(r->has_data()); assert(r->data().size() > 0); assert(index >= 0 && index < r->data().size()); auto m = make_lw_shared<scattered_message<char>> (); auto& data = *(r->data()[index].second); write_bytes(m, data); m->on_delete([ r = std::move(foreign_ptr { r }) ] {}); return make_ready_future<redis_message>(m); } future<redis_message> redis_message::make_map_key_bytes(map_return_type r) { auto m = make_lw_shared<scattered_message<char>> (); auto& data = r->data(); m->append(sstring(sprint("*%d\r\n", data.size()))); for (size_t i = 0; i < data.size(); ++i) { write_bytes(m, *(data[i].first)); } m->on_delete([ r = std::move(foreign_ptr { r }) ] {}); return make_ready_future<redis_message>(m); } future<redis_message> redis_message::make_map_val_bytes(map_return_type r) { auto m = make_lw_shared<scattered_message<char>> (); auto& data = r->data(); m->append(sstring(sprint("*%d\r\n", data.size()))); for (size_t i = 0; i < data.size(); ++i) { write_bytes(m, *(data[i].second)); } m->on_delete([ r = std::move(foreign_ptr { r }) ] {}); return make_ready_future<redis_message>(m); } future<redis_message> redis_message::make_map_bytes(map_return_type r) { auto m = make_lw_shared<scattered_message<char>> (); auto& data = r->data(); m->append(sstring(sprint("*%d\r\n", 2 * data.size()))); for (size_t i = 0; i < data.size(); ++i) { write_bytes(m, *(data[i].first)); write_bytes(m, *(data[i].second)); } m->on_delete([ r = std::move(foreign_ptr { r }) ] {}); return make_ready_future<redis_message>(m); } future<redis_message> redis_message::make_set_bytes(map_return_type r, size_t index) { return make_set_bytes(r, std::vector<size_t> { index }); } future<redis_message> redis_message::make_set_bytes(map_return_type r, std::vector<size_t> indexes) { auto m = make_lw_shared<scattered_message<char>> (); auto& data = r->data(); m->append(sstring(sprint("*%d\r\n", indexes.size()))); for (auto index : indexes) { assert(index >= 0 && index < data.size()); write_bytes(m, *(data[index].first)); } m->on_delete([ r = std::move(foreign_ptr { r }) ] {}); return make_ready_future<redis_message>(m); } future<redis_message> redis_message::make_zset_bytes(lw_shared_ptr<std::vector<std::optional<bytes>>> r) { auto m = make_lw_shared<scattered_message<char>> (); m->append(sstring(sprint("*%d\r\n", r->size()))); for (auto& e : *r) { auto& b = *e; logging.info("zset e = {}", sstring(reinterpret_cast<const char*>(b.data()), b.size())); write_bytes(m, *e); } m->on_delete([ r = std::move(foreign_ptr { r }) ] {}); return make_ready_future<redis_message>(m); } future<redis_message> redis_message::make_mbytes(mbytes_return_type r) { auto m = make_lw_shared<scattered_message<char>> (); auto& data = r->data(); m->append(sstring(sprint("*%d\r\n", data.size()))); for (auto e : data) { write_bytes(m, e.second); } m->on_delete([ r = std::move(foreign_ptr { r }) ] {}); return make_ready_future<redis_message>(m); } }
#include "reply.hh" namespace redis { future<redis_message> redis_message::make_list_bytes(map_return_type r, size_t begin, size_t end) { auto m = make_lw_shared<scattered_message<char>> (); m->append(sstring(sprint("*%d\r\n", end - begin + 1))); auto& data = r->data(); for (size_t i = 0; i < data.size(); ++i) { if (i >= begin && i <= end) { write_bytes(m, *(data[i].first)); } } m->on_delete([ r = std::move(foreign_ptr { r }) ] {}); return make_ready_future<redis_message>(m); } future<redis_message> redis_message::make_list_bytes(map_return_type r, size_t index) { assert(r->has_data()); assert(r->data().size() > 0); assert(index >= 0 && index < r->data().size()); auto m = make_lw_shared<scattered_message<char>> (); auto& data = *(r->data()[index].second); write_bytes(m, data); m->on_delete([ r = std::move(foreign_ptr { r }) ] {}); return make_ready_future<redis_message>(m); } future<redis_message> redis_message::make_map_key_bytes(map_return_type r) { auto m = make_lw_shared<scattered_message<char>> (); auto& data = r->data(); m->append(sstring(sprint("*%d\r\n", data.size()))); for (size_t i = 0; i < data.size(); ++i) { write_bytes(m, *(data[i].first)); } m->on_delete([ r = std::move(foreign_ptr { r }) ] {}); return make_ready_future<redis_message>(m); } future<redis_message> redis_message::make_map_val_bytes(map_return_type r) { auto m = make_lw_shared<scattered_message<char>> (); auto& data = r->data(); m->append(sstring(sprint("*%d\r\n", data.size()))); for (size_t i = 0; i < data.size(); ++i) { write_bytes(m, *(data[i].second)); } m->on_delete([ r = std::move(foreign_ptr { r }) ] {}); return make_ready_future<redis_message>(m); } future<redis_message> redis_message::make_map_bytes(map_return_type r) { auto m = make_lw_shared<scattered_message<char>> (); auto& data = r->data(); m->append(sstring(sprint("*%d\r\n", 2 * data.size()))); for (size_t i = 0; i < data.size(); ++i) { write_bytes(m, *(data[i].first)); write_bytes(m, *(data[i].second)); } m->on_delete([ r = std::move(foreign_ptr { r }) ] {}); return make_ready_future<redis_message>(m); } future<redis_message> redis_message::make_set_bytes(map_return_type r, size_t index) { return make_set_bytes(r, std::vector<size_t> { index }); } future<redis_message> redis_message::make_set_bytes(map_return_type r, std::vector<size_t> indexes) { auto m = make_lw_shared<scattered_message<char>> (); auto& data = r->data(); m->append(sstring(sprint("*%d\r\n", indexes.size()))); for (auto index : indexes) { assert(index >= 0 && index < data.size()); write_bytes(m, *(data[index].first)); } m->on_delete([ r = std::move(foreign_ptr { r }) ] {}); return make_ready_future<redis_message>(m); } future<redis_message> redis_message::make_zset_bytes(lw_shared_ptr<std::vector<std::optional<bytes>>> r) { auto m = make_lw_shared<scattered_message<char>> (); m->append(sstring(sprint("*%d\r\n", r->size()))); for (auto& e : *r) { write_bytes(m, *e); } m->on_delete([ r = std::move(foreign_ptr { r }) ] {}); return make_ready_future<redis_message>(m); } future<redis_message> redis_message::make_mbytes(mbytes_return_type r) { auto m = make_lw_shared<scattered_message<char>> (); auto& data = r->data(); m->append(sstring(sprint("*%d\r\n", data.size()))); for (auto e : data) { write_bytes(m, e.second); } m->on_delete([ r = std::move(foreign_ptr { r }) ] {}); return make_ready_future<redis_message>(m); } }
remove unnecessary logs
remove unnecessary logs
C++
agpl-3.0
fastio/pedis,fastio/pedis,fastio/pedis
456b5e592fee5de02fab84a8d152b5de0b20e175
src/weakref.cc
src/weakref.cc
/* * Copyright (c) 2011, Ben Noordhuis <[email protected]> * * Permission to use, copy, modify, and/or distribute this software for any * purpose with or without fee is hereby granted, provided that the above * copyright notice and this permission notice appear in all copies. * * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. */ #include "v8.h" #include "node.h" using namespace v8; namespace { Persistent<ObjectTemplate> proxyClass; bool IsDead(Handle<Object> proxy) { assert(proxy->InternalFieldCount() == 1); Persistent<Object>* target = reinterpret_cast<Persistent<Object>*>( proxy->GetPointerFromInternalField(0)); assert(target != NULL); return target->IsEmpty(); } Handle<Object> Unwrap(Handle<Object> proxy) { assert(!IsDead(proxy)); Persistent<Object>* target = reinterpret_cast<Persistent<Object>*>( proxy->GetPointerFromInternalField(0)); assert(target != NULL); return *target; } #define UNWRAP \ HandleScope scope; \ Handle<Object> obj; \ const bool dead = IsDead(info.This()); \ if (!dead) obj = Unwrap(info.This()); \ Handle<Value> WeakNamedPropertyGetter(Local<String> property, const AccessorInfo& info) { UNWRAP return dead ? Local<Value>() : obj->Get(property); } Handle<Value> WeakNamedPropertySetter(Local<String> property, Local<Value> value, const AccessorInfo& info) { UNWRAP if (!dead) obj->Set(property, value); return value; } Handle<Integer> WeakNamedPropertyQuery(Local<String> property, const AccessorInfo& info) { return HandleScope().Close(Integer::New(None)); } Handle<Boolean> WeakNamedPropertyDeleter(Local<String> property, const AccessorInfo& info) { UNWRAP return Boolean::New(!dead && obj->Delete(property)); } Handle<Value> WeakIndexedPropertyGetter(uint32_t index, const AccessorInfo& info) { UNWRAP return dead ? Local<Value>() : obj->Get(index); } Handle<Value> WeakIndexedPropertySetter(uint32_t index, Local<Value> value, const AccessorInfo& info) { UNWRAP if (!dead) obj->Set(index, value); return value; } Handle<Integer> WeakIndexedPropertyQuery(uint32_t index, const AccessorInfo& info) { return HandleScope().Close(Integer::New(None)); } Handle<Boolean> WeakIndexedPropertyDeleter(uint32_t index, const AccessorInfo& info) { UNWRAP return Boolean::New(!dead && obj->Delete(index)); } Handle<Array> WeakPropertyEnumerator(const AccessorInfo& info) { UNWRAP return HandleScope().Close(dead ? Array::New(0) : obj->GetPropertyNames()); } template <bool delete_target> void WeakCallback(Persistent<Value> obj, void* arg) { assert(obj.IsNearDeath()); obj.Dispose(); obj.Clear(); Persistent<Object>* target = reinterpret_cast<Persistent<Object>*>(arg); (*target).Dispose(); (*target).Clear(); if (delete_target) delete target; } Handle<Value> Weaken(const Arguments& args) { HandleScope scope; if (!args[0]->IsObject()) { Local<String> message = String::New("Object expected"); return ThrowException(Exception::TypeError(message)); } Persistent<Object>* target = new Persistent<Object>(); *target = Persistent<Object>::New(args[0]->ToObject()); (*target).MakeWeak(target, WeakCallback<false>); Persistent<Object> proxy = Persistent<Object>::New(proxyClass->NewInstance()); proxy->SetPointerInInternalField(0, target); proxy.MakeWeak(target, WeakCallback<true>); return proxy; } void Initialize(Handle<Object> target) { HandleScope scope; proxyClass = Persistent<ObjectTemplate>::New(ObjectTemplate::New()); proxyClass->SetNamedPropertyHandler(WeakNamedPropertyGetter, WeakNamedPropertySetter, WeakNamedPropertyQuery, WeakNamedPropertyDeleter, WeakPropertyEnumerator); proxyClass->SetIndexedPropertyHandler(WeakIndexedPropertyGetter, WeakIndexedPropertySetter, WeakIndexedPropertyQuery, WeakIndexedPropertyDeleter, WeakPropertyEnumerator); proxyClass->SetInternalFieldCount(1); target->Set(String::NewSymbol("weaken"), FunctionTemplate::New(Weaken)->GetFunction()); } } // anonymous namespace NODE_MODULE(weakref, Initialize);
/* * Copyright (c) 2011, Ben Noordhuis <[email protected]> * * Permission to use, copy, modify, and/or distribute this software for any * purpose with or without fee is hereby granted, provided that the above * copyright notice and this permission notice appear in all copies. * * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. */ #include "v8.h" #include "node.h" using namespace v8; namespace { Persistent<ObjectTemplate> proxyClass; bool IsDead(Handle<Object> proxy) { assert(proxy->InternalFieldCount() == 1); Persistent<Object>* target = reinterpret_cast<Persistent<Object>*>( proxy->GetPointerFromInternalField(0)); assert(target != NULL); return target->IsEmpty(); } Handle<Object> Unwrap(Handle<Object> proxy) { assert(!IsDead(proxy)); Persistent<Object>* target = reinterpret_cast<Persistent<Object>*>( proxy->GetPointerFromInternalField(0)); assert(target != NULL); return *target; } #define UNWRAP \ HandleScope scope; \ Handle<Object> obj; \ const bool dead = IsDead(info.This()); \ if (!dead) obj = Unwrap(info.This()); \ Handle<Value> WeakNamedPropertyGetter(Local<String> property, const AccessorInfo& info) { UNWRAP return dead ? Local<Value>() : obj->Get(property); } Handle<Value> WeakNamedPropertySetter(Local<String> property, Local<Value> value, const AccessorInfo& info) { UNWRAP if (!dead) obj->Set(property, value); return value; } Handle<Integer> WeakNamedPropertyQuery(Local<String> property, const AccessorInfo& info) { return HandleScope().Close(Integer::New(None)); } Handle<Boolean> WeakNamedPropertyDeleter(Local<String> property, const AccessorInfo& info) { UNWRAP return Boolean::New(!dead && obj->Delete(property)); } Handle<Value> WeakIndexedPropertyGetter(uint32_t index, const AccessorInfo& info) { UNWRAP return dead ? Local<Value>() : obj->Get(index); } Handle<Value> WeakIndexedPropertySetter(uint32_t index, Local<Value> value, const AccessorInfo& info) { UNWRAP if (!dead) obj->Set(index, value); return value; } Handle<Integer> WeakIndexedPropertyQuery(uint32_t index, const AccessorInfo& info) { return HandleScope().Close(Integer::New(None)); } Handle<Boolean> WeakIndexedPropertyDeleter(uint32_t index, const AccessorInfo& info) { UNWRAP return Boolean::New(!dead && obj->Delete(index)); } Handle<Array> WeakPropertyEnumerator(const AccessorInfo& info) { UNWRAP return HandleScope().Close(dead ? Array::New(0) : obj->GetPropertyNames()); } template <bool delete_target> void WeakCallback(Persistent<Value> obj, void* arg) { assert(obj.IsNearDeath()); obj.Dispose(); obj.Clear(); Persistent<Object>* target = reinterpret_cast<Persistent<Object>*>(arg); (*target).Dispose(); (*target).Clear(); if (delete_target) delete target; } Handle<Value> Create(const Arguments& args) { HandleScope scope; if (!args[0]->IsObject()) { Local<String> message = String::New("Object expected"); return ThrowException(Exception::TypeError(message)); } Persistent<Object>* target = new Persistent<Object>(); *target = Persistent<Object>::New(args[0]->ToObject()); (*target).MakeWeak(target, WeakCallback<false>); Persistent<Object> proxy = Persistent<Object>::New(proxyClass->NewInstance()); proxy->SetPointerInInternalField(0, target); proxy.MakeWeak(target, WeakCallback<true>); return proxy; } void Initialize(Handle<Object> target) { HandleScope scope; proxyClass = Persistent<ObjectTemplate>::New(ObjectTemplate::New()); proxyClass->SetNamedPropertyHandler(WeakNamedPropertyGetter, WeakNamedPropertySetter, WeakNamedPropertyQuery, WeakNamedPropertyDeleter, WeakPropertyEnumerator); proxyClass->SetIndexedPropertyHandler(WeakIndexedPropertyGetter, WeakIndexedPropertySetter, WeakIndexedPropertyQuery, WeakIndexedPropertyDeleter, WeakPropertyEnumerator); proxyClass->SetInternalFieldCount(1); NODE_SET_METHOD(target, "create", Create); } } // anonymous namespace NODE_MODULE(weakref, Initialize);
Rename 'weaken' to 'create'.
Rename 'weaken' to 'create'.
C++
isc
kkoopa/node-weak,robcolburn/node-weak,fastest963/node-weak,kkoopa/node-weak,KenanSulayman/node-weak,kkoopa/node-weak,EvolveLabs/electron-weak,TooTallNate/node-weak,robcolburn/node-weak,TooTallNate/node-weak,TooTallNate/node-weak,unbornchikken/node-weak,unbornchikken/node-weak,robcolburn/node-weak,EvolveLabs/electron-weak,EvolveLabs/electron-weak,fastest963/node-weak,fastest963/node-weak,unbornchikken/node-weak,KenanSulayman/node-weak,KenanSulayman/node-weak
0f8805d56674fff8ef79abd0981a3ede8b79190d
chrome/browser/views/external_protocol_dialog.cc
chrome/browser/views/external_protocol_dialog.cc
// Copyright (c) 2010 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chrome/browser/views/external_protocol_dialog.h" #include "app/l10n_util.h" #include "app/message_box_flags.h" #include "base/metrics/histogram.h" #include "base/string_util.h" #include "base/thread.h" #include "base/utf_string_conversions.h" #include "base/win/registry.h" #include "chrome/browser/browser_process.h" #include "chrome/browser/external_protocol_handler.h" #include "chrome/browser/tab_contents/tab_contents.h" #include "chrome/browser/tab_contents/tab_util.h" #include "grit/chromium_strings.h" #include "grit/generated_resources.h" #include "views/controls/message_box_view.h" #include "views/window/window.h" namespace { const int kMessageWidth = 400; } // namespace /////////////////////////////////////////////////////////////////////////////// // ExternalProtocolHandler // static void ExternalProtocolHandler::RunExternalProtocolDialog( const GURL& url, int render_process_host_id, int routing_id) { std::wstring command = ExternalProtocolDialog::GetApplicationForProtocol(url); if (command.empty()) { // ShellExecute won't do anything. Don't bother warning the user. return; } TabContents* tab_contents = tab_util::GetTabContentsByID( render_process_host_id, routing_id); DCHECK(tab_contents); ExternalProtocolDialog* handler = new ExternalProtocolDialog(tab_contents, url, command); } /////////////////////////////////////////////////////////////////////////////// // ExternalProtocolDialog ExternalProtocolDialog::~ExternalProtocolDialog() { } ////////////////////////////////////////////////////////////////////////////// // ExternalProtocolDialog, views::DialogDelegate implementation: int ExternalProtocolDialog::GetDefaultDialogButton() const { return MessageBoxFlags::DIALOGBUTTON_CANCEL; } std::wstring ExternalProtocolDialog::GetDialogButtonLabel( MessageBoxFlags::DialogButton button) const { if (button == MessageBoxFlags::DIALOGBUTTON_OK) return l10n_util::GetString(IDS_EXTERNAL_PROTOCOL_OK_BUTTON_TEXT); else return l10n_util::GetString(IDS_EXTERNAL_PROTOCOL_CANCEL_BUTTON_TEXT); } std::wstring ExternalProtocolDialog::GetWindowTitle() const { return l10n_util::GetString(IDS_EXTERNAL_PROTOCOL_TITLE); } void ExternalProtocolDialog::DeleteDelegate() { delete this; } bool ExternalProtocolDialog::Cancel() { // We also get called back here if the user closes the dialog or presses // escape. In these cases it would be preferable to ignore the state of the // check box but MessageBox doesn't distinguish this from pressing the cancel // button. if (message_box_view_->IsCheckBoxSelected()) { ExternalProtocolHandler::SetBlockState( url_.scheme(), ExternalProtocolHandler::BLOCK); } // Returning true closes the dialog. return true; } bool ExternalProtocolDialog::Accept() { // We record how long it takes the user to accept an external protocol. If // users start accepting these dialogs too quickly, we should worry about // clickjacking. UMA_HISTOGRAM_LONG_TIMES("clickjacking.launch_url", base::TimeTicks::Now() - creation_time_); if (message_box_view_->IsCheckBoxSelected()) { ExternalProtocolHandler::SetBlockState( url_.scheme(), ExternalProtocolHandler::DONT_BLOCK); } ExternalProtocolHandler::LaunchUrlWithoutSecurityCheck(url_); // Returning true closes the dialog. return true; } views::View* ExternalProtocolDialog::GetContentsView() { return message_box_view_; } /////////////////////////////////////////////////////////////////////////////// // ExternalProtocolDialog, private: ExternalProtocolDialog::ExternalProtocolDialog(TabContents* tab_contents, const GURL& url, const std::wstring& command) : tab_contents_(tab_contents), url_(url), creation_time_(base::TimeTicks::Now()) { const int kMaxUrlWithoutSchemeSize = 256; const int kMaxCommandSize = 256; std::wstring elided_url_without_scheme; std::wstring elided_command; ElideString(ASCIIToWide(url.possibly_invalid_spec()), kMaxUrlWithoutSchemeSize, &elided_url_without_scheme); ElideString(command, kMaxCommandSize, &elided_command); std::wstring message_text = l10n_util::GetStringF( IDS_EXTERNAL_PROTOCOL_INFORMATION, ASCIIToWide(url.scheme() + ":"), elided_url_without_scheme) + L"\n\n"; message_text += l10n_util::GetStringF( IDS_EXTERNAL_PROTOCOL_APPLICATION_TO_LAUNCH, elided_command) + L"\n\n"; message_text += l10n_util::GetString(IDS_EXTERNAL_PROTOCOL_WARNING); message_box_view_ = new MessageBoxView(MessageBoxFlags::kIsConfirmMessageBox, message_text, std::wstring(), kMessageWidth); message_box_view_->SetCheckBoxLabel( l10n_util::GetString(IDS_EXTERNAL_PROTOCOL_CHECKBOX_TEXT)); HWND root_hwnd; if (tab_contents_) { root_hwnd = GetAncestor(tab_contents_->GetContentNativeView(), GA_ROOT); } else { // Dialog is top level if we don't have a tab_contents associated with us. root_hwnd = NULL; } views::Window::CreateChromeWindow(root_hwnd, gfx::Rect(), this)->Show(); } // static std::wstring ExternalProtocolDialog::GetApplicationForProtocol( const GURL& url) { std::wstring url_spec = ASCIIToWide(url.possibly_invalid_spec()); std::wstring cmd_key_path = ASCIIToWide(url.scheme() + "\\shell\\open\\command"); base::win::RegKey cmd_key(HKEY_CLASSES_ROOT, cmd_key_path.c_str(), KEY_READ); size_t split_offset = url_spec.find(L':'); if (split_offset == std::wstring::npos) return std::wstring(); std::wstring parameters = url_spec.substr(split_offset + 1, url_spec.length() - 1); std::wstring application_to_launch; if (cmd_key.ReadValue(NULL, &application_to_launch)) { ReplaceSubstringsAfterOffset(&application_to_launch, 0, L"%1", parameters); return application_to_launch; } else { return std::wstring(); } }
// 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/views/external_protocol_dialog.h" #include "app/l10n_util.h" #include "app/message_box_flags.h" #include "base/metrics/histogram.h" #include "base/string_util.h" #include "base/thread.h" #include "base/thread_restrictions.h" #include "base/utf_string_conversions.h" #include "base/win/registry.h" #include "chrome/browser/browser_process.h" #include "chrome/browser/external_protocol_handler.h" #include "chrome/browser/tab_contents/tab_contents.h" #include "chrome/browser/tab_contents/tab_util.h" #include "grit/chromium_strings.h" #include "grit/generated_resources.h" #include "views/controls/message_box_view.h" #include "views/window/window.h" namespace { const int kMessageWidth = 400; } // namespace /////////////////////////////////////////////////////////////////////////////// // ExternalProtocolHandler // static void ExternalProtocolHandler::RunExternalProtocolDialog( const GURL& url, int render_process_host_id, int routing_id) { std::wstring command = ExternalProtocolDialog::GetApplicationForProtocol(url); if (command.empty()) { // ShellExecute won't do anything. Don't bother warning the user. return; } TabContents* tab_contents = tab_util::GetTabContentsByID( render_process_host_id, routing_id); DCHECK(tab_contents); ExternalProtocolDialog* handler = new ExternalProtocolDialog(tab_contents, url, command); } /////////////////////////////////////////////////////////////////////////////// // ExternalProtocolDialog ExternalProtocolDialog::~ExternalProtocolDialog() { } ////////////////////////////////////////////////////////////////////////////// // ExternalProtocolDialog, views::DialogDelegate implementation: int ExternalProtocolDialog::GetDefaultDialogButton() const { return MessageBoxFlags::DIALOGBUTTON_CANCEL; } std::wstring ExternalProtocolDialog::GetDialogButtonLabel( MessageBoxFlags::DialogButton button) const { if (button == MessageBoxFlags::DIALOGBUTTON_OK) return l10n_util::GetString(IDS_EXTERNAL_PROTOCOL_OK_BUTTON_TEXT); else return l10n_util::GetString(IDS_EXTERNAL_PROTOCOL_CANCEL_BUTTON_TEXT); } std::wstring ExternalProtocolDialog::GetWindowTitle() const { return l10n_util::GetString(IDS_EXTERNAL_PROTOCOL_TITLE); } void ExternalProtocolDialog::DeleteDelegate() { delete this; } bool ExternalProtocolDialog::Cancel() { // We also get called back here if the user closes the dialog or presses // escape. In these cases it would be preferable to ignore the state of the // check box but MessageBox doesn't distinguish this from pressing the cancel // button. if (message_box_view_->IsCheckBoxSelected()) { ExternalProtocolHandler::SetBlockState( url_.scheme(), ExternalProtocolHandler::BLOCK); } // Returning true closes the dialog. return true; } bool ExternalProtocolDialog::Accept() { // We record how long it takes the user to accept an external protocol. If // users start accepting these dialogs too quickly, we should worry about // clickjacking. UMA_HISTOGRAM_LONG_TIMES("clickjacking.launch_url", base::TimeTicks::Now() - creation_time_); if (message_box_view_->IsCheckBoxSelected()) { ExternalProtocolHandler::SetBlockState( url_.scheme(), ExternalProtocolHandler::DONT_BLOCK); } ExternalProtocolHandler::LaunchUrlWithoutSecurityCheck(url_); // Returning true closes the dialog. return true; } views::View* ExternalProtocolDialog::GetContentsView() { return message_box_view_; } /////////////////////////////////////////////////////////////////////////////// // ExternalProtocolDialog, private: ExternalProtocolDialog::ExternalProtocolDialog(TabContents* tab_contents, const GURL& url, const std::wstring& command) : tab_contents_(tab_contents), url_(url), creation_time_(base::TimeTicks::Now()) { const int kMaxUrlWithoutSchemeSize = 256; const int kMaxCommandSize = 256; std::wstring elided_url_without_scheme; std::wstring elided_command; ElideString(ASCIIToWide(url.possibly_invalid_spec()), kMaxUrlWithoutSchemeSize, &elided_url_without_scheme); ElideString(command, kMaxCommandSize, &elided_command); std::wstring message_text = l10n_util::GetStringF( IDS_EXTERNAL_PROTOCOL_INFORMATION, ASCIIToWide(url.scheme() + ":"), elided_url_without_scheme) + L"\n\n"; message_text += l10n_util::GetStringF( IDS_EXTERNAL_PROTOCOL_APPLICATION_TO_LAUNCH, elided_command) + L"\n\n"; message_text += l10n_util::GetString(IDS_EXTERNAL_PROTOCOL_WARNING); message_box_view_ = new MessageBoxView(MessageBoxFlags::kIsConfirmMessageBox, message_text, std::wstring(), kMessageWidth); message_box_view_->SetCheckBoxLabel( l10n_util::GetString(IDS_EXTERNAL_PROTOCOL_CHECKBOX_TEXT)); HWND root_hwnd; if (tab_contents_) { root_hwnd = GetAncestor(tab_contents_->GetContentNativeView(), GA_ROOT); } else { // Dialog is top level if we don't have a tab_contents associated with us. root_hwnd = NULL; } views::Window::CreateChromeWindow(root_hwnd, gfx::Rect(), this)->Show(); } // static std::wstring ExternalProtocolDialog::GetApplicationForProtocol( const GURL& url) { // We shouldn't be accessing the registry from the UI thread, since it can go // to disk. http://crbug.com/61996 base::ThreadRestrictions::ScopedAllowIO allow_io; std::wstring url_spec = ASCIIToWide(url.possibly_invalid_spec()); std::wstring cmd_key_path = ASCIIToWide(url.scheme() + "\\shell\\open\\command"); base::win::RegKey cmd_key(HKEY_CLASSES_ROOT, cmd_key_path.c_str(), KEY_READ); size_t split_offset = url_spec.find(L':'); if (split_offset == std::wstring::npos) return std::wstring(); std::wstring parameters = url_spec.substr(split_offset + 1, url_spec.length() - 1); std::wstring application_to_launch; if (cmd_key.ReadValue(NULL, &application_to_launch)) { ReplaceSubstringsAfterOffset(&application_to_launch, 0, L"%1", parameters); return application_to_launch; } else { return std::wstring(); } }
Fix assert in PageCycler tests. Review URL: http://codereview.chromium.org/4559001
Fix assert in PageCycler tests. Review URL: http://codereview.chromium.org/4559001 git-svn-id: de016e52bd170d2d4f2344f9bf92d50478b649e0@65166 0039d316-1c4b-4281-b951-d872f2087c98
C++
bsd-3-clause
axinging/chromium-crosswalk,PeterWangIntel/chromium-crosswalk,dednal/chromium.src,bright-sparks/chromium-spacewalk,mogoweb/chromium-crosswalk,pozdnyakov/chromium-crosswalk,patrickm/chromium.src,mogoweb/chromium-crosswalk,anirudhSK/chromium,markYoungH/chromium.src,Pluto-tv/chromium-crosswalk,hgl888/chromium-crosswalk,Just-D/chromium-1,dednal/chromium.src,robclark/chromium,hujiajie/pa-chromium,crosswalk-project/chromium-crosswalk-efl,Pluto-tv/chromium-crosswalk,PeterWangIntel/chromium-crosswalk,ltilve/chromium,dednal/chromium.src,zcbenz/cefode-chromium,mohamed--abdel-maksoud/chromium.src,TheTypoMaster/chromium-crosswalk,jaruba/chromium.src,chuan9/chromium-crosswalk,nacl-webkit/chrome_deps,littlstar/chromium.src,hgl888/chromium-crosswalk,Chilledheart/chromium,Just-D/chromium-1,zcbenz/cefode-chromium,M4sse/chromium.src,crosswalk-project/chromium-crosswalk-efl,bright-sparks/chromium-spacewalk,dushu1203/chromium.src,Pluto-tv/chromium-crosswalk,hgl888/chromium-crosswalk-efl,nacl-webkit/chrome_deps,ondra-novak/chromium.src,Just-D/chromium-1,pozdnyakov/chromium-crosswalk,hgl888/chromium-crosswalk-efl,Chilledheart/chromium,hgl888/chromium-crosswalk-efl,Chilledheart/chromium,bright-sparks/chromium-spacewalk,ChromiumWebApps/chromium,littlstar/chromium.src,mogoweb/chromium-crosswalk,nacl-webkit/chrome_deps,jaruba/chromium.src,dushu1203/chromium.src,ChromiumWebApps/chromium,Jonekee/chromium.src,PeterWangIntel/chromium-crosswalk,Pluto-tv/chromium-crosswalk,krieger-od/nwjs_chromium.src,patrickm/chromium.src,Pluto-tv/chromium-crosswalk,littlstar/chromium.src,M4sse/chromium.src,dednal/chromium.src,timopulkkinen/BubbleFish,Chilledheart/chromium,hgl888/chromium-crosswalk,patrickm/chromium.src,dushu1203/chromium.src,chuan9/chromium-crosswalk,rogerwang/chromium,zcbenz/cefode-chromium,axinging/chromium-crosswalk,timopulkkinen/BubbleFish,hgl888/chromium-crosswalk-efl,hujiajie/pa-chromium,M4sse/chromium.src,dednal/chromium.src,krieger-od/nwjs_chromium.src,keishi/chromium,M4sse/chromium.src,markYoungH/chromium.src,Just-D/chromium-1,fujunwei/chromium-crosswalk,M4sse/chromium.src,hujiajie/pa-chromium,keishi/chromium,rogerwang/chromium,nacl-webkit/chrome_deps,hgl888/chromium-crosswalk-efl,robclark/chromium,anirudhSK/chromium,anirudhSK/chromium,krieger-od/nwjs_chromium.src,jaruba/chromium.src,anirudhSK/chromium,pozdnyakov/chromium-crosswalk,rogerwang/chromium,ondra-novak/chromium.src,timopulkkinen/BubbleFish,junmin-zhu/chromium-rivertrail,ChromiumWebApps/chromium,rogerwang/chromium,nacl-webkit/chrome_deps,rogerwang/chromium,chuan9/chromium-crosswalk,dushu1203/chromium.src,rogerwang/chromium,ondra-novak/chromium.src,keishi/chromium,ondra-novak/chromium.src,fujunwei/chromium-crosswalk,jaruba/chromium.src,Pluto-tv/chromium-crosswalk,hgl888/chromium-crosswalk,crosswalk-project/chromium-crosswalk-efl,zcbenz/cefode-chromium,anirudhSK/chromium,axinging/chromium-crosswalk,ChromiumWebApps/chromium,crosswalk-project/chromium-crosswalk-efl,rogerwang/chromium,jaruba/chromium.src,fujunwei/chromium-crosswalk,mogoweb/chromium-crosswalk,mohamed--abdel-maksoud/chromium.src,robclark/chromium,krieger-od/nwjs_chromium.src,anirudhSK/chromium,pozdnyakov/chromium-crosswalk,junmin-zhu/chromium-rivertrail,fujunwei/chromium-crosswalk,zcbenz/cefode-chromium,junmin-zhu/chromium-rivertrail,M4sse/chromium.src,TheTypoMaster/chromium-crosswalk,markYoungH/chromium.src,junmin-zhu/chromium-rivertrail,pozdnyakov/chromium-crosswalk,zcbenz/cefode-chromium,zcbenz/cefode-chromium,Jonekee/chromium.src,keishi/chromium,Chilledheart/chromium,timopulkkinen/BubbleFish,Jonekee/chromium.src,axinging/chromium-crosswalk,TheTypoMaster/chromium-crosswalk,fujunwei/chromium-crosswalk,hgl888/chromium-crosswalk,chuan9/chromium-crosswalk,rogerwang/chromium,jaruba/chromium.src,ChromiumWebApps/chromium,Pluto-tv/chromium-crosswalk,robclark/chromium,bright-sparks/chromium-spacewalk,keishi/chromium,ondra-novak/chromium.src,mogoweb/chromium-crosswalk,PeterWangIntel/chromium-crosswalk,Fireblend/chromium-crosswalk,hgl888/chromium-crosswalk,axinging/chromium-crosswalk,Jonekee/chromium.src,ChromiumWebApps/chromium,Jonekee/chromium.src,mogoweb/chromium-crosswalk,jaruba/chromium.src,markYoungH/chromium.src,axinging/chromium-crosswalk,krieger-od/nwjs_chromium.src,keishi/chromium,hgl888/chromium-crosswalk-efl,keishi/chromium,ChromiumWebApps/chromium,mogoweb/chromium-crosswalk,nacl-webkit/chrome_deps,pozdnyakov/chromium-crosswalk,Just-D/chromium-1,anirudhSK/chromium,ltilve/chromium,hujiajie/pa-chromium,ltilve/chromium,keishi/chromium,hgl888/chromium-crosswalk-efl,ondra-novak/chromium.src,Chilledheart/chromium,Pluto-tv/chromium-crosswalk,nacl-webkit/chrome_deps,anirudhSK/chromium,axinging/chromium-crosswalk,TheTypoMaster/chromium-crosswalk,timopulkkinen/BubbleFish,Jonekee/chromium.src,patrickm/chromium.src,dednal/chromium.src,jaruba/chromium.src,markYoungH/chromium.src,TheTypoMaster/chromium-crosswalk,timopulkkinen/BubbleFish,Jonekee/chromium.src,timopulkkinen/BubbleFish,hujiajie/pa-chromium,littlstar/chromium.src,junmin-zhu/chromium-rivertrail,hujiajie/pa-chromium,Fireblend/chromium-crosswalk,markYoungH/chromium.src,dushu1203/chromium.src,krieger-od/nwjs_chromium.src,Chilledheart/chromium,krieger-od/nwjs_chromium.src,patrickm/chromium.src,littlstar/chromium.src,ltilve/chromium,junmin-zhu/chromium-rivertrail,pozdnyakov/chromium-crosswalk,bright-sparks/chromium-spacewalk,hgl888/chromium-crosswalk-efl,jaruba/chromium.src,TheTypoMaster/chromium-crosswalk,TheTypoMaster/chromium-crosswalk,markYoungH/chromium.src,bright-sparks/chromium-spacewalk,TheTypoMaster/chromium-crosswalk,dushu1203/chromium.src,chuan9/chromium-crosswalk,rogerwang/chromium,Just-D/chromium-1,ChromiumWebApps/chromium,hujiajie/pa-chromium,krieger-od/nwjs_chromium.src,axinging/chromium-crosswalk,robclark/chromium,axinging/chromium-crosswalk,ltilve/chromium,junmin-zhu/chromium-rivertrail,PeterWangIntel/chromium-crosswalk,timopulkkinen/BubbleFish,chuan9/chromium-crosswalk,keishi/chromium,ltilve/chromium,rogerwang/chromium,dushu1203/chromium.src,anirudhSK/chromium,anirudhSK/chromium,Chilledheart/chromium,anirudhSK/chromium,markYoungH/chromium.src,junmin-zhu/chromium-rivertrail,pozdnyakov/chromium-crosswalk,PeterWangIntel/chromium-crosswalk,timopulkkinen/BubbleFish,Jonekee/chromium.src,nacl-webkit/chrome_deps,junmin-zhu/chromium-rivertrail,littlstar/chromium.src,mohamed--abdel-maksoud/chromium.src,robclark/chromium,ChromiumWebApps/chromium,Fireblend/chromium-crosswalk,krieger-od/nwjs_chromium.src,Just-D/chromium-1,fujunwei/chromium-crosswalk,bright-sparks/chromium-spacewalk,littlstar/chromium.src,patrickm/chromium.src,robclark/chromium,axinging/chromium-crosswalk,crosswalk-project/chromium-crosswalk-efl,chuan9/chromium-crosswalk,mohamed--abdel-maksoud/chromium.src,keishi/chromium,zcbenz/cefode-chromium,timopulkkinen/BubbleFish,hujiajie/pa-chromium,Fireblend/chromium-crosswalk,dushu1203/chromium.src,dushu1203/chromium.src,mogoweb/chromium-crosswalk,Jonekee/chromium.src,chuan9/chromium-crosswalk,Just-D/chromium-1,hgl888/chromium-crosswalk,mohamed--abdel-maksoud/chromium.src,robclark/chromium,bright-sparks/chromium-spacewalk,mohamed--abdel-maksoud/chromium.src,jaruba/chromium.src,dednal/chromium.src,fujunwei/chromium-crosswalk,PeterWangIntel/chromium-crosswalk,Fireblend/chromium-crosswalk,ChromiumWebApps/chromium,mogoweb/chromium-crosswalk,PeterWangIntel/chromium-crosswalk,mohamed--abdel-maksoud/chromium.src,ondra-novak/chromium.src,mohamed--abdel-maksoud/chromium.src,robclark/chromium,dushu1203/chromium.src,dednal/chromium.src,chuan9/chromium-crosswalk,M4sse/chromium.src,hgl888/chromium-crosswalk,Jonekee/chromium.src,zcbenz/cefode-chromium,littlstar/chromium.src,timopulkkinen/BubbleFish,hgl888/chromium-crosswalk-efl,Pluto-tv/chromium-crosswalk,zcbenz/cefode-chromium,junmin-zhu/chromium-rivertrail,Fireblend/chromium-crosswalk,junmin-zhu/chromium-rivertrail,markYoungH/chromium.src,hgl888/chromium-crosswalk,dushu1203/chromium.src,hujiajie/pa-chromium,hujiajie/pa-chromium,dednal/chromium.src,krieger-od/nwjs_chromium.src,PeterWangIntel/chromium-crosswalk,mohamed--abdel-maksoud/chromium.src,pozdnyakov/chromium-crosswalk,M4sse/chromium.src,pozdnyakov/chromium-crosswalk,ondra-novak/chromium.src,dednal/chromium.src,mohamed--abdel-maksoud/chromium.src,crosswalk-project/chromium-crosswalk-efl,robclark/chromium,hgl888/chromium-crosswalk-efl,ltilve/chromium,Jonekee/chromium.src,dednal/chromium.src,patrickm/chromium.src,patrickm/chromium.src,fujunwei/chromium-crosswalk,axinging/chromium-crosswalk,TheTypoMaster/chromium-crosswalk,M4sse/chromium.src,Chilledheart/chromium,fujunwei/chromium-crosswalk,M4sse/chromium.src,markYoungH/chromium.src,Just-D/chromium-1,mohamed--abdel-maksoud/chromium.src,hujiajie/pa-chromium,anirudhSK/chromium,M4sse/chromium.src,keishi/chromium,Fireblend/chromium-crosswalk,patrickm/chromium.src,jaruba/chromium.src,krieger-od/nwjs_chromium.src,ltilve/chromium,Fireblend/chromium-crosswalk,Fireblend/chromium-crosswalk,zcbenz/cefode-chromium,nacl-webkit/chrome_deps,crosswalk-project/chromium-crosswalk-efl,markYoungH/chromium.src,ChromiumWebApps/chromium,ltilve/chromium,crosswalk-project/chromium-crosswalk-efl,mogoweb/chromium-crosswalk,nacl-webkit/chrome_deps,ChromiumWebApps/chromium,nacl-webkit/chrome_deps,crosswalk-project/chromium-crosswalk-efl,pozdnyakov/chromium-crosswalk,bright-sparks/chromium-spacewalk,ondra-novak/chromium.src
ff3ae49360bd70eab8934b714987a90691ba7272
src/window.cpp
src/window.cpp
#include <QtGui> #include "window.h" #include <QVBoxLayout> #include <QTextEdit> #include <QSystemTrayIcon> #include <QIcon> #include <QAction> #include <QMenu> #include <QTabWidget> #include <QLabel> #include <QLineEdit> #include <QFormLayout> #include <QCheckBox> #include <QDialogButtonBox> #include <QVBoxLayout> #include <QPushButton> TabLogHandler::TabLogHandler(LogTab *logTab) :tab(logTab) { } void TabLogHandler::HandleLogEntry(const string& entry) { tab->addLogEntry(entry); } SettingsTab::SettingsTab(QWidget *parent) : QWidget(parent) { QVBoxLayout *layout = new QVBoxLayout; layout->addWidget(new QLabel(tr("Username:"))); username = new QLineEdit; layout->addWidget(username); layout->addWidget(new QLabel(tr("Password:"))); password = new QLineEdit; QHBoxLayout *row = new QHBoxLayout; QPushButton *revealButton = new QPushButton(tr("Reveal")); connect(revealButton, SIGNAL(clicked()), this, SLOT(reveal())); row->addWidget(password); row->addWidget(revealButton); layout->addItem(row); startAtLogin = new QCheckBox(tr("Start at Login")); layout->addWidget(startAtLogin); setLayout(layout); } void SettingsTab::reveal() { password->setEchoMode(QLineEdit::Normal); } void SettingsTab::conceal() { password->setEchoMode(QLineEdit::Password); } void SettingsTab::updateSettings() { Autostart autostart; QSettings settings; username->setText(settings.value("username").toString()); password->setText(settings.value("password").toString()); conceal(); startAtLogin->setChecked(autostart.IsActive()); } void SettingsTab::applySettings() { QSettings settings; Autostart autostart; settings.setValue("username", username->text()); settings.setValue("password", password->text()); autostart.SetActive(startAtLogin->isChecked()); } LogTab::LogTab(QWidget *parent) : QWidget(parent), logHandler(this) { QVBoxLayout *layout = new QVBoxLayout; logText = new QTextEdit; logText->setReadOnly(true); layout->addWidget(logText); setLayout(layout); gLogger.RegisterObserver(&logHandler); } LogTab::~LogTab() { gLogger.UnregisterObserver(&logHandler); } void LogTab::addLogEntry(const string& entry) { logText->moveCursor(QTextCursor::End); logText->insertPlainText(entry.c_str()); logText->moveCursor(QTextCursor::End); } Window::Window() { setWindowTitle(APP_NAME); Qt::WindowFlags flags = windowFlags(); flags |= Qt::CustomizeWindowHint; flags &= ~Qt::WindowMaximizeButtonHint; setWindowFlags(flags); createActions(); createTrayIcon(); tabWidget = new QTabWidget; settingsTab = new SettingsTab; logTab = new LogTab; tabWidget->addTab(settingsTab, tr("Settings")); tabWidget->addTab(logTab, tr("Log")); buttonBox = new QDialogButtonBox(QDialogButtonBox::Ok | QDialogButtonBox::Cancel); connect(buttonBox, SIGNAL(accepted()), this, SLOT(ok())); connect(buttonBox, SIGNAL(rejected()), this, SLOT(cancel())); QVBoxLayout *mainLayout = new QVBoxLayout; mainLayout->setSizeConstraint(QLayout::SetNoConstraint); mainLayout->addWidget(tabWidget); mainLayout->addWidget(buttonBox); setLayout(mainLayout); setFixedSize(400, 300); } Window::~Window() { } void Window::showEvent(QShowEvent *event) { QDialog::showEvent(event); settingsTab->updateSettings(); } void Window::ok() { hide(); settingsTab->applySettings(); } void Window::cancel() { hide(); } void Window::closeEvent(QCloseEvent *event) { if(trayIcon->isVisible()) { hide(); event->ignore(); } } // prevent esc from closing the app void Window::reject() { if(trayIcon->isVisible()) { hide(); } else { QDialog::reject(); } } void Window::createActions() { openProfileAction = new QAction(tr("Open Profile..."), this); connect(openProfileAction, SIGNAL(triggered()), this, SLOT(openProfile())); showAction = new QAction(tr("Settings..."), this); connect(showAction, SIGNAL(triggered()), this, SLOT(riseAndShine())); quitAction = new QAction(tr("Quit"), this); connect(quitAction, SIGNAL(triggered()), qApp, SLOT(quit())); } void Window::createTrayIcon() { trayIconMenu = new QMenu(this); trayIconMenu->addAction(openProfileAction); trayIconMenu->addSeparator(); trayIconMenu->addAction(showAction); trayIconMenu->addSeparator(); trayIconMenu->addAction(quitAction); trayIcon = new QSystemTrayIcon(this); trayIcon->setContextMenu(trayIconMenu); QIcon icon = QIcon(":/icons/paw.svg"); #ifdef Q_WS_MAC icon.addFile(":/icons/paw_inverted.svg", QSize(), QIcon::Selected); #endif trayIcon->setIcon(icon); trayIcon->show(); } void Window::riseAndShine() { show(); raise(); } void Window::openProfile() { core.Tracker().OpenProfile(); }
#include <QtGui> #include "window.h" TabLogHandler::TabLogHandler(LogTab *logTab) :tab(logTab) { } void TabLogHandler::HandleLogEntry(const string& entry) { tab->addLogEntry(entry); } SettingsTab::SettingsTab(QWidget *parent) : QWidget(parent) { QVBoxLayout *layout = new QVBoxLayout; layout->addWidget(new QLabel(tr("Username:"))); username = new QLineEdit; layout->addWidget(username); layout->addWidget(new QLabel(tr("Password:"))); password = new QLineEdit; QHBoxLayout *row = new QHBoxLayout; QPushButton *revealButton = new QPushButton(tr("Reveal")); connect(revealButton, SIGNAL(clicked()), this, SLOT(reveal())); row->addWidget(password); row->addWidget(revealButton); layout->addItem(row); startAtLogin = new QCheckBox(tr("Start at Login")); layout->addWidget(startAtLogin); setLayout(layout); } void SettingsTab::reveal() { password->setEchoMode(QLineEdit::Normal); } void SettingsTab::conceal() { password->setEchoMode(QLineEdit::Password); } void SettingsTab::updateSettings() { Autostart autostart; QSettings settings; username->setText(settings.value("username").toString()); password->setText(settings.value("password").toString()); conceal(); startAtLogin->setChecked(autostart.IsActive()); } void SettingsTab::applySettings() { QSettings settings; Autostart autostart; settings.setValue("username", username->text()); settings.setValue("password", password->text()); autostart.SetActive(startAtLogin->isChecked()); } LogTab::LogTab(QWidget *parent) : QWidget(parent), logHandler(this) { QVBoxLayout *layout = new QVBoxLayout; logText = new QTextEdit; logText->setReadOnly(true); layout->addWidget(logText); setLayout(layout); gLogger.RegisterObserver(&logHandler); } LogTab::~LogTab() { gLogger.UnregisterObserver(&logHandler); } void LogTab::addLogEntry(const string& entry) { logText->moveCursor(QTextCursor::End); logText->insertPlainText(entry.c_str()); logText->moveCursor(QTextCursor::End); } Window::Window() { setWindowTitle(APP_NAME); Qt::WindowFlags flags = windowFlags(); flags |= Qt::CustomizeWindowHint; flags &= ~Qt::WindowMaximizeButtonHint; setWindowFlags(flags); createActions(); createTrayIcon(); tabWidget = new QTabWidget; settingsTab = new SettingsTab; logTab = new LogTab; tabWidget->addTab(settingsTab, tr("Settings")); tabWidget->addTab(logTab, tr("Log")); buttonBox = new QDialogButtonBox(QDialogButtonBox::Ok | QDialogButtonBox::Cancel); connect(buttonBox, SIGNAL(accepted()), this, SLOT(ok())); connect(buttonBox, SIGNAL(rejected()), this, SLOT(cancel())); QVBoxLayout *mainLayout = new QVBoxLayout; mainLayout->setSizeConstraint(QLayout::SetNoConstraint); mainLayout->addWidget(tabWidget); mainLayout->addWidget(buttonBox); setLayout(mainLayout); setFixedSize(400, 300); } Window::~Window() { } void Window::showEvent(QShowEvent *event) { QDialog::showEvent(event); settingsTab->updateSettings(); } void Window::ok() { hide(); settingsTab->applySettings(); } void Window::cancel() { hide(); } void Window::closeEvent(QCloseEvent *event) { if(trayIcon->isVisible()) { hide(); event->ignore(); } } // prevent esc from closing the app void Window::reject() { if(trayIcon->isVisible()) { hide(); } else { QDialog::reject(); } } void Window::createActions() { openProfileAction = new QAction(tr("Open Profile..."), this); connect(openProfileAction, SIGNAL(triggered()), this, SLOT(openProfile())); showAction = new QAction(tr("Settings..."), this); connect(showAction, SIGNAL(triggered()), this, SLOT(riseAndShine())); quitAction = new QAction(tr("Quit"), this); connect(quitAction, SIGNAL(triggered()), qApp, SLOT(quit())); } void Window::createTrayIcon() { trayIconMenu = new QMenu(this); trayIconMenu->addAction(openProfileAction); trayIconMenu->addSeparator(); trayIconMenu->addAction(showAction); trayIconMenu->addSeparator(); trayIconMenu->addAction(quitAction); trayIcon = new QSystemTrayIcon(this); trayIcon->setContextMenu(trayIconMenu); QIcon icon = QIcon(":/icons/paw.svg"); #ifdef Q_WS_MAC icon.addFile(":/icons/paw_inverted.svg", QSize(), QIcon::Selected); #endif trayIcon->setIcon(icon); trayIcon->show(); } void Window::riseAndShine() { show(); raise(); } void Window::openProfile() { core.Tracker().OpenProfile(); }
remove unnecessary stuff
remove unnecessary stuff
C++
lgpl-2.1
stevschmid/track-o-bot,elzoido/track-o-bot,BOSSoNe0013/track-o-bot,bencart/track-o-bot,bencart/track-o-bot,BOSSoNe0013/track-o-bot,stevschmid/track-o-bot,elzoido/track-o-bot,elzoido/track-o-bot,bencart/track-o-bot
5129df17a59debc566df03f486a4f4e7a63ea6ce
src/worker.cpp
src/worker.cpp
#include <cfloat> #include <cstdio> #include <cassert> #include <map> #include <string> #include <vector> #include <utility> #include <unistd.h> #include <cstdlib> #include <iostream> #include <Python.h> #include "mpi.h" #include "structure.h" #include "msg_passing.h" #include "autotuner.h" #include "space_partition.h" using namespace std; int main(int argc, char** argv) { if(argc < 6) { printf("./worker <--design DESIGN-NAME> <--path WORKSPACE-PATH> <--pycode PYTHON-CODE> \n"); return 0; } /*************MPI initialization*******************/ int myrank; int pnum; int len; char hostname[MPI_MAX_PROCESSOR_NAME]; MPI_Status status; MPI_Init(&argc, &argv); MPI_Comm_rank(MPI_COMM_WORLD,&myrank); MPI_Comm_size(MPI_COMM_WORLD,&pnum); MPI_Get_processor_name(hostname,&len); int tune_type = 0; //1: vtr 2: vivado 3: quartus 4: other MPI_Recv(&tune_type,1,MPI_INT,0,0,MPI_COMM_WORLD,&status); int share_best = 1; //0:false 1:true MPI_Recv(&share_best,1,MPI_INT,0,0,MPI_COMM_WORLD,&status); /**************parse parameters*********************/ string spacepath = ""; string pycode = ""; string design = ""; int tune_cst = 0; int fake_argc = 0; char** fake_argv = NULL; vector<string> tmp_fake_argv; for(int i = 0; i < argc; i++) { if(strcmp(argv[i],"-path") == 0) { assert(i < argc-1); spacepath = string(argv[i+1]); i++; continue; } if(strcmp(argv[i],"-design") == 0) { assert(i < argc-1); design = string(argv[i+1]); i++; continue; } if(strcmp(argv[i],"-pycode") == 0) { assert(i < argc-1); pycode=string(argv[i+1]); i++; continue; } if(strcmp(argv[i],"-tune_cst") == 0) { assert(i < argc-1); tune_cst = atoi(argv[i+1]); i++; continue; } tmp_fake_argv.push_back(string(argv[i])); //set static parameters like --parallism=1 } char rankname[50]; sprintf(rankname,"--myrank=%d",myrank); tmp_fake_argv.push_back(string(rankname)); sprintf(rankname,"r%d.db",myrank); string db_path = "--database="+spacepath+"/"+rankname; tmp_fake_argv.push_back(db_path) if(share_best) { tmp_fake_argv.push_back("--seed-configuration"); char name[500]; sprintf(name,"StartPointSpace%d.json",myrank); tmp_fake_argv.push_back(string(name)); } /***********invoke autotuner****************/ Py_Initialize(); if(!Py_IsInitialized()) return -1; int result_id = 0; int cond = 0;//0:stop, 1:autotuning while(1) { MPI_Recv(&cond,1,MPI_INT,0,0,MPI_COMM_WORLD,&status); if(cond == 0) break; int limit; MPI_Recv(&limit,1,MPI_INT,0,0,MPI_COMM_WORLD,&status); {//generate arguments for OpenTuner char str_limit[10]; sprintf(str_limit,"%d",limit); bool flag_limit = false; for(int i = 0; i < tmp_fake_argv.size(); i++) { if(tmp_fake_argv[i].find("test-limit") != string::npos) { assert(i < tmp_fake_argv.size()-1); tmp_fake_argv[i+1] = string(str_limit); flag_limit = true; break; } } if(!flag_limit) { tmp_fake_argv.push_back("--test-limit"); tmp_fake_argv.push_back(string(str_limit)); } fake_argc = tmp_fake_argv.size(); assert(!fake_argv); fake_argv = new char*[fake_argc]; for(int i = 0; i < fake_argc; i++) { fake_argv[i] = new char[100]; strcpy(fake_argv[i],tmp_fake_argv[i].c_str()); } } PySys_SetArgv(fake_argc,fake_argv); Task* task = NULL; Recv_Task(task, 0); assert(task != NULL); vector<Result*> results; AutoTuner* tuner = new AutoTuner(task->subspace->id, design, tune_type, tune_cst); //start from 1 assert(tuner != NULL); tuner->callOpenTuner(task,results,myrank,spacepath,pycode); #ifdef DEBUG_MSG printf("rank %d sending results, result size %d\n",myrank, results.size()); printf("debug worker results: \n"); for(int i = 0; i < results.size(); i++) { printf("%d\n",i) for(int j = 0; j < results[i]->name2choice.size(); j++) { printf("%s : %s ",results[i]->name2choice[j].first.c_str(), results[i]->name2choice[j].second.c_str()); } printf("\n"); } printf("finish\n"); #endif Send_MultiResult(results,0); if(fake_argv) { for(int i = 0; i < fake_argc; i++) {delete []fake_argv[i]; fake_argv[i] = NULL;} delete []fake_argv; fake_argv=NULL; } } Py_Finalize(); MPI_Finalize(); return 0; }
#include <cfloat> #include <cstdio> #include <cassert> #include <map> #include <string> #include <vector> #include <utility> #include <unistd.h> #include <cstdlib> #include <iostream> #include <Python.h> #include "mpi.h" #include "structure.h" #include "msg_passing.h" #include "autotuner.h" #include "space_partition.h" using namespace std; int main(int argc, char** argv) { if(argc < 6) { printf("./worker <--design DESIGN-NAME> <--path WORKSPACE-PATH> <--pycode PYTHON-CODE> \n"); return 0; } /*************MPI initialization*******************/ int myrank; int pnum; int len; char hostname[MPI_MAX_PROCESSOR_NAME]; MPI_Status status; MPI_Init(&argc, &argv); MPI_Comm_rank(MPI_COMM_WORLD,&myrank); MPI_Comm_size(MPI_COMM_WORLD,&pnum); MPI_Get_processor_name(hostname,&len); int tune_type = 0; //1: vtr 2: vivado 3: quartus 4: other MPI_Recv(&tune_type,1,MPI_INT,0,0,MPI_COMM_WORLD,&status); int share_best = 1; //0:false 1:true MPI_Recv(&share_best,1,MPI_INT,0,0,MPI_COMM_WORLD,&status); /**************parse parameters*********************/ string spacepath = ""; string pycode = ""; string design = ""; int tune_cst = 0; int fake_argc = 0; char** fake_argv = NULL; vector<string> tmp_fake_argv; for(int i = 0; i < argc; i++) { if(strcmp(argv[i],"-path") == 0) { assert(i < argc-1); spacepath = string(argv[i+1]); i++; continue; } if(strcmp(argv[i],"-design") == 0) { assert(i < argc-1); design = string(argv[i+1]); i++; continue; } if(strcmp(argv[i],"-pycode") == 0) { assert(i < argc-1); pycode=string(argv[i+1]); i++; continue; } if(strcmp(argv[i],"-tune_cst") == 0) { assert(i < argc-1); tune_cst = atoi(argv[i+1]); i++; continue; } tmp_fake_argv.push_back(string(argv[i])); //set static parameters like --parallism=1 } char rankname[50]; sprintf(rankname,"--myrank=%d",myrank); tmp_fake_argv.push_back(string(rankname)); sprintf(rankname,"r%d.db",myrank); string db_path = "--database="+spacepath+"/"+rankname; tmp_fake_argv.push_back(db_path); if(share_best) { tmp_fake_argv.push_back("--seed-configuration"); char name[500]; sprintf(name,"StartPointSpace%d.json",myrank); tmp_fake_argv.push_back(string(name)); } /***********invoke autotuner****************/ Py_Initialize(); if(!Py_IsInitialized()) return -1; int result_id = 0; int cond = 0;//0:stop, 1:autotuning while(1) { MPI_Recv(&cond,1,MPI_INT,0,0,MPI_COMM_WORLD,&status); if(cond == 0) break; int limit; MPI_Recv(&limit,1,MPI_INT,0,0,MPI_COMM_WORLD,&status); {//generate arguments for OpenTuner char str_limit[10]; sprintf(str_limit,"%d",limit); bool flag_limit = false; for(int i = 0; i < tmp_fake_argv.size(); i++) { if(tmp_fake_argv[i].find("test-limit") != string::npos) { assert(i < tmp_fake_argv.size()-1); tmp_fake_argv[i+1] = string(str_limit); flag_limit = true; break; } } if(!flag_limit) { tmp_fake_argv.push_back("--test-limit"); tmp_fake_argv.push_back(string(str_limit)); } fake_argc = tmp_fake_argv.size(); assert(!fake_argv); fake_argv = new char*[fake_argc]; for(int i = 0; i < fake_argc; i++) { fake_argv[i] = new char[100]; strcpy(fake_argv[i],tmp_fake_argv[i].c_str()); } } PySys_SetArgv(fake_argc,fake_argv); Task* task = NULL; Recv_Task(task, 0); assert(task != NULL); vector<Result*> results; AutoTuner* tuner = new AutoTuner(task->subspace->id, design, tune_type, tune_cst); //start from 1 assert(tuner != NULL); tuner->callOpenTuner(task,results,myrank,spacepath,pycode); #ifdef DEBUG_MSG printf("rank %d sending results, result size %d\n",myrank, results.size()); printf("debug worker results: \n"); for(int i = 0; i < results.size(); i++) { printf("%d\n",i) for(int j = 0; j < results[i]->name2choice.size(); j++) { printf("%s : %s ",results[i]->name2choice[j].first.c_str(), results[i]->name2choice[j].second.c_str()); } printf("\n"); } printf("finish\n"); #endif Send_MultiResult(results,0); if(fake_argv) { for(int i = 0; i < fake_argc; i++) {delete []fake_argv[i]; fake_argv[i] = NULL;} delete []fake_argv; fake_argv=NULL; } } Py_Finalize(); MPI_Finalize(); return 0; }
fix bug
fix bug
C++
bsd-3-clause
cornell-zhang/datuner,cornell-zhang/datuner,cornell-zhang/datuner,cornell-zhang/datuner,cornell-zhang/datuner,cornell-zhang/datuner
685dba405865a2dd0dab7460bee07b41765390da
checks/ocb.cpp
checks/ocb.cpp
#include "validate.h" #include <botan/ocb.h> #include <botan/hex.h> #include <botan/sha2_32.h> #include <botan/aes.h> #include <iostream> //#include <botan/selftest.h> using namespace Botan; // something like this should be in the library std::vector<byte> ocb_decrypt(const SymmetricKey& key, const std::vector<byte>& nonce, const byte ct[], size_t ct_len, const byte ad[], size_t ad_len) { OCB_Decryption ocb(new AES_128); ocb.set_key(key); ocb.set_associated_data(ad, ad_len); ocb.start(&nonce[0], nonce.size()); secure_vector<byte> buf(ct, ct+ct_len); ocb.finish(buf, 0); return unlock(buf); } std::vector<byte> ocb_encrypt(const SymmetricKey& key, const std::vector<byte>& nonce, const byte pt[], size_t pt_len, const byte ad[], size_t ad_len) { OCB_Encryption ocb(new AES_128); ocb.set_key(key); ocb.set_associated_data(ad, ad_len); ocb.start(&nonce[0], nonce.size()); secure_vector<byte> buf(pt, pt+pt_len); ocb.finish(buf, 0); try { std::vector<byte> pt2 = ocb_decrypt(key, nonce, &buf[0], buf.size(), ad, ad_len); if(pt_len != pt2.size() || !same_mem(pt, &pt2[0], pt_len)) std::cout << "OCB failed to decrypt correctly\n"; } catch(std::exception& e) { std::cout << "OCB round trip error - " << e.what() << "\n"; } return unlock(buf); } template<typename Alloc, typename Alloc2> std::vector<byte> ocb_encrypt(const SymmetricKey& key, const std::vector<byte>& nonce, const std::vector<byte, Alloc>& pt, const std::vector<byte, Alloc2>& ad) { return ocb_encrypt(key, nonce, &pt[0], pt.size(), &ad[0], ad.size()); } template<typename Alloc, typename Alloc2> std::vector<byte> ocb_decrypt(const SymmetricKey& key, const std::vector<byte>& nonce, const std::vector<byte, Alloc>& pt, const std::vector<byte, Alloc2>& ad) { return ocb_decrypt(key, nonce, &pt[0], pt.size(), &ad[0], ad.size()); } std::vector<byte> ocb_encrypt(OCB_Encryption& ocb, const std::vector<byte>& nonce, const std::vector<byte>& pt, const std::vector<byte>& ad) { ocb.set_associated_data(&ad[0], ad.size()); ocb.start(&nonce[0], nonce.size()); secure_vector<byte> buf(pt.begin(), pt.end()); ocb.finish(buf, 0); return unlock(buf); } void test_ocb_long(size_t taglen, const std::string &expected) { OCB_Encryption ocb(new AES_128, taglen/8); ocb.set_key(SymmetricKey("00000000000000000000000000000000")); const std::vector<byte> empty; std::vector<byte> N(12); std::vector<byte> C; for(size_t i = 0; i != 128; ++i) { const std::vector<byte> S(i); N[11] = i; C += ocb_encrypt(ocb, N, S, S); C += ocb_encrypt(ocb, N, S, empty); C += ocb_encrypt(ocb, N, empty, S); } N[11] = 0; const std::vector<byte> cipher = ocb_encrypt(ocb, N, empty, C); const std::string cipher_hex = hex_encode(cipher); if(cipher_hex != expected) std::cout << "OCB AES-128 long test mistmatch " << cipher_hex << " != " << expected << "\n"; else std::cout << "OCB AES-128 long test OK\n"; } void test_ocb() { SymmetricKey key("000102030405060708090A0B0C0D0E0F"); std::vector<byte> nonce = hex_decode("000102030405060708090A0B"); std::vector<byte> pt = hex_decode("000102030405060708090A0B0C0D0E0F101112131415161718191A1B1C1D1E1F2021222324252627"); std::vector<byte> ad = hex_decode("000102030405060708090A0B0C0D0E0F101112131415161718191A1B1C1D1E1F2021222324252627"); const std::string expected = "BEA5E8798DBE7110031C144DA0B26122CEAAB9B05DF771A657149D53773463CB68C65778B058A635659C623211DEEA0DE30D2C381879F4C8"; std::vector<byte> ctext = ocb_encrypt(key, nonce, pt, ad); const std::string ctext_hex = hex_encode(ctext); if(ctext_hex != expected) std::cout << "OCB/AES-128 encrypt test failure\n" << ctext_hex << " !=\n" << expected << "\n"; else std::cout << "OCB/AES-128 encrypt OK\n"; try { std::vector<byte> dec = ocb_decrypt(key, nonce, ctext, ad); if(dec == pt) { std::cout << "OCB decrypts OK\n"; } else { std::cout << "OCB fails to decrypt\n"; } } catch(std::exception& e) { std::cout << "Correct OCB message rejected - " << e.what() << "\n"; } test_ocb_long(128, "B2B41CBF9B05037DA7F16C24A35C1C94"); test_ocb_long(96, "1A4F0654277709A5BDA0D380"); test_ocb_long(64, "B7ECE9D381FE437F"); }
#include "validate.h" #include <botan/ocb.h> #include <botan/hex.h> #include <botan/sha2_32.h> #include <botan/aes.h> #include <iostream> //#include <botan/selftest.h> using namespace Botan; // something like this should be in the library std::vector<byte> ocb_decrypt(const SymmetricKey& key, const std::vector<byte>& nonce, const byte ct[], size_t ct_len, const byte ad[], size_t ad_len) { OCB_Decryption ocb(new AES_128); ocb.set_key(key); ocb.set_associated_data(ad, ad_len); ocb.start(&nonce[0], nonce.size()); secure_vector<byte> buf(ct, ct+ct_len); ocb.finish(buf, 0); return unlock(buf); } std::vector<byte> ocb_encrypt(const SymmetricKey& key, const std::vector<byte>& nonce, const byte pt[], size_t pt_len, const byte ad[], size_t ad_len) { OCB_Encryption ocb(new AES_128); ocb.set_key(key); ocb.set_associated_data(ad, ad_len); ocb.start(&nonce[0], nonce.size()); secure_vector<byte> buf(pt, pt+pt_len); ocb.finish(buf, 0); try { std::vector<byte> pt2 = ocb_decrypt(key, nonce, &buf[0], buf.size(), ad, ad_len); if(pt_len != pt2.size() || !same_mem(pt, &pt2[0], pt_len)) std::cout << "OCB failed to decrypt correctly\n"; } catch(std::exception& e) { std::cout << "OCB round trip error - " << e.what() << "\n"; } return unlock(buf); } template<typename Alloc, typename Alloc2> std::vector<byte> ocb_encrypt(const SymmetricKey& key, const std::vector<byte>& nonce, const std::vector<byte, Alloc>& pt, const std::vector<byte, Alloc2>& ad) { return ocb_encrypt(key, nonce, &pt[0], pt.size(), &ad[0], ad.size()); } template<typename Alloc, typename Alloc2> std::vector<byte> ocb_decrypt(const SymmetricKey& key, const std::vector<byte>& nonce, const std::vector<byte, Alloc>& pt, const std::vector<byte, Alloc2>& ad) { return ocb_decrypt(key, nonce, &pt[0], pt.size(), &ad[0], ad.size()); } std::vector<byte> ocb_encrypt(OCB_Encryption& ocb, const std::vector<byte>& nonce, const std::vector<byte>& pt, const std::vector<byte>& ad) { ocb.set_associated_data(&ad[0], ad.size()); ocb.start(&nonce[0], nonce.size()); secure_vector<byte> buf(pt.begin(), pt.end()); ocb.finish(buf, 0); return unlock(buf); } void test_ocb_long(size_t taglen, const std::string &expected) { OCB_Encryption ocb(new AES_128, taglen/8); ocb.set_key(SymmetricKey("00000000000000000000000000000000")); const std::vector<byte> empty; std::vector<byte> N(12); std::vector<byte> C; for(size_t i = 0; i != 128; ++i) { const std::vector<byte> S(i); N[11] = i; C += ocb_encrypt(ocb, N, S, S); C += ocb_encrypt(ocb, N, S, empty); C += ocb_encrypt(ocb, N, empty, S); } N[11] = 0; const std::vector<byte> cipher = ocb_encrypt(ocb, N, empty, C); const std::string cipher_hex = hex_encode(cipher); if(cipher_hex != expected) std::cout << "OCB AES-128 long test mistmatch " << cipher_hex << " != " << expected << "\n"; } void test_ocb() { SymmetricKey key("000102030405060708090A0B0C0D0E0F"); std::vector<byte> nonce = hex_decode("000102030405060708090A0B"); std::vector<byte> pt = hex_decode("000102030405060708090A0B0C0D0E0F101112131415161718191A1B1C1D1E1F2021222324252627"); std::vector<byte> ad = hex_decode("000102030405060708090A0B0C0D0E0F101112131415161718191A1B1C1D1E1F2021222324252627"); const std::string expected = "BEA5E8798DBE7110031C144DA0B26122CEAAB9B05DF771A657149D53773463CB68C65778B058A635659C623211DEEA0DE30D2C381879F4C8"; std::vector<byte> ctext = ocb_encrypt(key, nonce, pt, ad); const std::string ctext_hex = hex_encode(ctext); if(ctext_hex != expected) std::cout << "OCB/AES-128 encrypt test failure\n" << ctext_hex << " !=\n" << expected << "\n"; try { std::vector<byte> dec = ocb_decrypt(key, nonce, ctext, ad); if(dec != pt) std::cout << "OCB fails to decrypt\n"; } catch(std::exception& e) { std::cout << "Correct OCB message rejected - " << e.what() << "\n"; } test_ocb_long(128, "B2B41CBF9B05037DA7F16C24A35C1C94"); test_ocb_long(96, "1A4F0654277709A5BDA0D380"); test_ocb_long(64, "B7ECE9D381FE437F"); }
Make OCB tests quiet
Make OCB tests quiet
C++
bsd-2-clause
Rohde-Schwarz-Cybersecurity/botan,Rohde-Schwarz-Cybersecurity/botan,randombit/botan,randombit/botan,webmaster128/botan,Rohde-Schwarz-Cybersecurity/botan,webmaster128/botan,webmaster128/botan,randombit/botan,randombit/botan,Rohde-Schwarz-Cybersecurity/botan,webmaster128/botan,Rohde-Schwarz-Cybersecurity/botan,Rohde-Schwarz-Cybersecurity/botan,webmaster128/botan,randombit/botan
d10a4ef7eb8e9411a7cd298cda1638165ca434a2
src/object/dictionary.cc
src/object/dictionary.cc
/* * Copyright (C) 2008-2011, Gostai S.A.S. * * This software is provided "as is" without warranty of any kind, * either expressed or implied, including but not limited to the * implied warranties of fitness for a particular purpose. * * See the LICENSE file for more information. */ /** ** \file object/dictionary.cc ** \brief Creation of the Urbi object dictionary. */ #include <libport/containers.hh> #include <kernel/userver.hh> #include <object/symbols.hh> #include <runner/runner.hh> #include <urbi/object/dictionary.hh> #include <urbi/object/event.hh> #include <urbi/object/list.hh> #include <urbi/object/string.hh> namespace urbi { namespace object { std::size_t unordered_map_hash::operator()(rObject val) const { return hash_value(*val); } bool unordered_map_equal_to::operator()(rObject lhs, rObject rhs) const { bool res = from_urbi<bool>(lhs->call("==", rhs)); // std::cerr << "equal_to() => " << res << std::endl; return res; } Dictionary::Dictionary() : content_() , elementAdded_(0) , elementChanged_(0) , elementRemoved_(0) { proto_add(proto ? rObject(proto) : Object::proto); } Dictionary::Dictionary(const value_type& value) : content_(value) , elementAdded_(0) , elementChanged_(0) , elementRemoved_(0) { proto_add(proto); } Dictionary::Dictionary(rDictionary model) : content_(model->content_) , elementAdded_(0) , elementChanged_(0) , elementRemoved_(0) { proto_add(proto); } URBI_CXX_OBJECT_INIT(Dictionary) : content_() , elementAdded_(0) , elementChanged_(0) , elementRemoved_(0) { bind(SYMBOL(asBool), &Dictionary::as_bool); bind(SYMBOL(elementAdded), &Dictionary::elementAdded_get); bind(SYMBOL(elementChanged), &Dictionary::elementChanged_get); bind(SYMBOL(elementRemoved), &Dictionary::elementRemoved_get); #define DECLARE(Name) \ bind(SYMBOL_(Name), &Dictionary::Name) DECLARE(clear); DECLARE(empty); DECLARE(erase); DECLARE(get); DECLARE(has); DECLARE(keys); DECLARE(set); DECLARE(size); #undef DECLARE } const Dictionary::value_type& Dictionary::value_get() const { return content_; } Dictionary::value_type& Dictionary::value_get() { return content_; } void Dictionary::key_check(rObject key) const { if (!libport::mhas(content_, key)) { static rObject exn = slot_get(SYMBOL(KeyError)); ::kernel::runner().raise(exn->call("new", key)); } } rDictionary Dictionary::set(rObject key, rObject val) { value_type::iterator it = content_.find(key); if (it == content_.end()) { content_[key] = val; elementAdded(); } else { it->second = val; elementChanged(); } return this; } rObject Dictionary::get(rObject key) { URBI_AT_HOOK(elementChanged); key_check(key); return content_[key]; unreachable(); // wtf? } rDictionary Dictionary::clear() { if (!empty()) { content_.clear(); elementRemoved(); } return this; } bool Dictionary::empty() const { bool res = content_.empty(); if (res) URBI_AT_HOOK(elementAdded); else URBI_AT_HOOK(elementRemoved); return res; } size_t Dictionary::size() const { URBI_AT_HOOK(elementAdded); URBI_AT_HOOK(elementRemoved); return content_.size(); } bool Dictionary::as_bool() const { return !empty(); } rDictionary Dictionary::erase(rObject key) { key_check(key); content_.erase(key); elementRemoved(); return this; } rList Dictionary::keys() { URBI_AT_HOOK(elementRemoved); URBI_AT_HOOK(elementAdded); List::value_type res; typedef const std::pair<rObject, rObject> elt_type; foreach (elt_type& elt, content_) res.push_back(elt.first); return new List(res); } bool Dictionary::has(rObject key) const { bool res = libport::mhas(content_, key); if (res) URBI_AT_HOOK(elementRemoved); else URBI_AT_HOOK(elementAdded); return res; } /* SYMBOL(elementAdded) SYMBOL(elementChanged) SYMBOL(elementRemoved) */ URBI_ATTRIBUTE_ON_DEMAND_IMPL(Dictionary, Event, elementAdded); URBI_ATTRIBUTE_ON_DEMAND_IMPL(Dictionary, Event, elementChanged); URBI_ATTRIBUTE_ON_DEMAND_IMPL(Dictionary, Event, elementRemoved); } }
/* * Copyright (C) 2008-2011, Gostai S.A.S. * * This software is provided "as is" without warranty of any kind, * either expressed or implied, including but not limited to the * implied warranties of fitness for a particular purpose. * * See the LICENSE file for more information. */ /** ** \file object/dictionary.cc ** \brief Creation of the Urbi object dictionary. */ #include <libport/containers.hh> #include <kernel/userver.hh> #include <object/symbols.hh> #include <runner/runner.hh> #include <urbi/object/dictionary.hh> #include <urbi/object/event.hh> #include <urbi/object/list.hh> #include <urbi/object/string.hh> namespace urbi { namespace object { std::size_t unordered_map_hash::operator()(rObject val) const { return hash_value(*val); } bool unordered_map_equal_to::operator()(rObject lhs, rObject rhs) const { bool res = from_urbi<bool>(lhs->call("==", rhs)); return res; } Dictionary::Dictionary() : content_() , elementAdded_(0) , elementChanged_(0) , elementRemoved_(0) { proto_add(proto ? rObject(proto) : Object::proto); } Dictionary::Dictionary(const value_type& value) : content_(value) , elementAdded_(0) , elementChanged_(0) , elementRemoved_(0) { proto_add(proto); } Dictionary::Dictionary(rDictionary model) : content_(model->content_) , elementAdded_(0) , elementChanged_(0) , elementRemoved_(0) { proto_add(proto); } URBI_CXX_OBJECT_INIT(Dictionary) : content_() , elementAdded_(0) , elementChanged_(0) , elementRemoved_(0) { bind(SYMBOL(asBool), &Dictionary::as_bool); bind(SYMBOL(elementAdded), &Dictionary::elementAdded_get); bind(SYMBOL(elementChanged), &Dictionary::elementChanged_get); bind(SYMBOL(elementRemoved), &Dictionary::elementRemoved_get); #define DECLARE(Name) \ bind(SYMBOL_(Name), &Dictionary::Name) DECLARE(clear); DECLARE(empty); DECLARE(erase); DECLARE(get); DECLARE(has); DECLARE(keys); DECLARE(set); DECLARE(size); #undef DECLARE } const Dictionary::value_type& Dictionary::value_get() const { return content_; } Dictionary::value_type& Dictionary::value_get() { return content_; } void Dictionary::key_check(rObject key) const { if (!libport::mhas(content_, key)) { static rObject exn = slot_get(SYMBOL(KeyError)); ::kernel::runner().raise(exn->call("new", key)); } } rDictionary Dictionary::set(rObject key, rObject val) { value_type::iterator it = content_.find(key); if (it == content_.end()) { content_[key] = val; elementAdded(); } else { it->second = val; elementChanged(); } return this; } rObject Dictionary::get(rObject key) { URBI_AT_HOOK(elementChanged); key_check(key); return content_[key]; unreachable(); // wtf? } rDictionary Dictionary::clear() { if (!empty()) { content_.clear(); elementRemoved(); } return this; } bool Dictionary::empty() const { bool res = content_.empty(); if (res) URBI_AT_HOOK(elementAdded); else URBI_AT_HOOK(elementRemoved); return res; } size_t Dictionary::size() const { URBI_AT_HOOK(elementAdded); URBI_AT_HOOK(elementRemoved); return content_.size(); } bool Dictionary::as_bool() const { return !empty(); } rDictionary Dictionary::erase(rObject key) { key_check(key); content_.erase(key); elementRemoved(); return this; } rList Dictionary::keys() { URBI_AT_HOOK(elementRemoved); URBI_AT_HOOK(elementAdded); List::value_type res; typedef const std::pair<rObject, rObject> elt_type; foreach (elt_type& elt, content_) res.push_back(elt.first); return new List(res); } bool Dictionary::has(rObject key) const { bool res = libport::mhas(content_, key); if (res) URBI_AT_HOOK(elementRemoved); else URBI_AT_HOOK(elementAdded); return res; } /* SYMBOL(elementAdded) SYMBOL(elementChanged) SYMBOL(elementRemoved) */ URBI_ATTRIBUTE_ON_DEMAND_IMPL(Dictionary, Event, elementAdded); URBI_ATTRIBUTE_ON_DEMAND_IMPL(Dictionary, Event, elementChanged); URBI_ATTRIBUTE_ON_DEMAND_IMPL(Dictionary, Event, elementRemoved); } }
Remove dead debug code.
Remove dead debug code. * src/object/dictionary.cc: Here.
C++
bsd-3-clause
aldebaran/urbi,urbiforge/urbi,aldebaran/urbi,aldebaran/urbi,aldebaran/urbi,urbiforge/urbi,urbiforge/urbi,urbiforge/urbi,aldebaran/urbi,urbiforge/urbi,urbiforge/urbi,urbiforge/urbi,aldebaran/urbi,urbiforge/urbi,aldebaran/urbi,urbiforge/urbi,aldebaran/urbi
60d5bc2e912c589ead6c5a303484e0dcb095993b
src/object/list-class.cc
src/object/list-class.cc
/** ** \file object/list-class.cc ** \brief Creation of the URBI object list. */ #include <boost/assign.hpp> #include <boost/bind.hpp> #include <libport/foreach.hh> #include <libport/ufloat.hh> #include <kernel/userver.hh> #include <object/code-class.hh> #include <object/float-class.hh> #include <object/list-class.hh> #include <object/atom.hh> #include <object/object.hh> #include <object/primitives.hh> #include <runner/runner.hh> #include <runner/interpreter.hh> using namespace boost::assign; namespace object { rObject list_class; List::List() { proto_add(list_class); } List::List(const value_type& value) : content_(value) { proto_add(list_class); } List::List(rList model) : content_(model->content_) { proto_add(list_class); } const List::value_type& List::value_get() const { return content_; } List::value_type& List::value_get() { return content_; } #define CHECK_NON_EMPTY(Name) \ if (content_.empty ()) \ throw PrimitiveError \ (Name, "operation cannot be applied onto empty list") rList List::tail() { CHECK_NON_EMPTY("tail"); value_type res = content_; res.pop_front(); return new List(res); } rObject List::operator[](rFloat idx) { unsigned i = idx->to_int(SYMBOL(nth)); if (i >= content_.size()) throw PrimitiveError("nth", "invalid index"); return content_[i]; } rFloat List::size() { return new Float(content_.size()); } rList List::remove_by_id(rObject elt) { value_type::iterator it = content_.begin(); while (it != content_.end()) if (*it == elt) it = content_.erase(it); else ++it; return this; } rList List::operator+=(rList rhs) { // Copy the list to make a += a work value_type other = rhs->value_get(); foreach (const rObject& o, other) content_.push_back(o); return this; } rList List::operator+(rList rhs) { rList res = new List(this); *res += rhs; return res; } /// Binary predicate used to sort lists. static bool compareListItems (runner::Runner& r, rObject a, rObject b) { return is_true(urbi_call(r, a, SYMBOL(LT), b), SYMBOL(sort)); } rList List::sort(runner::Runner& r) { std::list<rObject> s; foreach(const rObject& o, content_) s.push_back(o); s.sort(boost::bind(compareListItems, boost::ref(r), _1, _2)); List::value_type res; foreach(const rObject& o, s) res.push_back(o); return new List(res); } void List::each(runner::Runner& r, rObject f) { foreach(const rObject& o, content_) r.apply(f, SYMBOL(each), list_of (f) (o)); } void List::each_and(runner::Runner& r, rObject f) { scheduler::jobs_type jobs; for (objects_type::const_reverse_iterator o = content_.rbegin(); o != content_.rend(); ++o) { scheduler::rJob job = new runner::Interpreter(dynamic_cast<runner::Interpreter&>(r), f, SYMBOL(each), list_of(*o)); r.link(job); job->start_job(); jobs.push_back(job); } r.yield_until_terminated(jobs); } #define BOUNCE(Name, Ret, Arg, Check) \ IF(Ret, rObject, rList) List::Name(WHEN(Arg, rObject arg)) \ { \ WHEN(Check, CHECK_NON_EMPTY(#Name)); \ WHEN(Ret, return) content_.Name(WHEN(Arg, arg)); \ return this; \ } BOUNCE(back, true, false, true ); BOUNCE(clear, false, false, false); BOUNCE(front, true, false, true ); BOUNCE(pop_back, false, false, true ); BOUNCE(pop_front, false, false, true ); BOUNCE(push_back, false, true, false); BOUNCE(push_front, false, true, false); #undef BOUNCE void List::initialize(CxxObject::Binder<List>& bind) { bind(SYMBOL(back), &List::back ); bind(SYMBOL(clear), &List::clear ); bind(SYMBOL(each), &List::each ); bind(SYMBOL(each_AMPERSAND), &List::each_and ); bind(SYMBOL(front), &List::front ); bind(SYMBOL(PLUS), &List::operator+ ); bind(SYMBOL(PLUS_EQ), &List::operator+= ); bind(SYMBOL(nth), &List::operator[] ); bind(SYMBOL(push_back), &List::push_back ); bind(SYMBOL(push_front), &List::push_front ); bind(SYMBOL(pop_back), &List::pop_back ); bind(SYMBOL(pop_front), &List::pop_front ); bind(SYMBOL(removeById), &List::remove_by_id); bind(SYMBOL(size), &List::size ); bind(SYMBOL(sort), &List::sort ); bind(SYMBOL(tail), &List::tail ); } std::string List::type_name_get() const { return type_name; } bool List::list_added = CxxObject::add<List>("List", list_class); const std::string List::type_name = "List"; } // namespace object
/** ** \file object/list-class.cc ** \brief Creation of the URBI object list. */ #include <boost/assign.hpp> #include <boost/bind.hpp> #include <libport/foreach.hh> #include <libport/ufloat.hh> #include <kernel/userver.hh> #include <object/code-class.hh> #include <object/float-class.hh> #include <object/list-class.hh> #include <object/atom.hh> #include <object/object.hh> #include <object/primitives.hh> #include <runner/runner.hh> #include <runner/interpreter.hh> using namespace boost::assign; namespace object { rObject list_class; List::List() { proto_add(list_class); } List::List(const value_type& value) : content_(value) { proto_add(list_class); } List::List(rList model) : content_(model->content_) { proto_add(list_class); } const List::value_type& List::value_get() const { return content_; } List::value_type& List::value_get() { return content_; } #define CHECK_NON_EMPTY(Name) \ if (content_.empty ()) \ throw PrimitiveError \ (Name, "operation cannot be applied onto empty list") rList List::tail() { CHECK_NON_EMPTY("tail"); value_type res = content_; res.pop_front(); return new List(res); } rObject List::operator[](rFloat idx) { unsigned i = idx->to_int(SYMBOL(nth)); if (i >= content_.size()) throw PrimitiveError("nth", "invalid index"); return content_[i]; } rFloat List::size() { return new Float(content_.size()); } rList List::remove_by_id(rObject elt) { value_type::iterator it = content_.begin(); while (it != content_.end()) if (*it == elt) it = content_.erase(it); else ++it; return this; } rList List::operator+=(rList rhs) { // Copy the list to make a += a work value_type other = rhs->value_get(); foreach (const rObject& o, other) content_.push_back(o); return this; } rList List::operator+(rList rhs) { rList res = new List(this); *res += rhs; return res; } /// Binary predicate used to sort lists. static bool compareListItems (runner::Runner& r, rObject a, rObject b) { return is_true(urbi_call(r, a, SYMBOL(LT), b), SYMBOL(sort)); } rList List::sort(runner::Runner& r) { std::list<rObject> s; foreach(const rObject& o, content_) s.push_back(o); s.sort(boost::bind(compareListItems, boost::ref(r), _1, _2)); List::value_type res; foreach(const rObject& o, s) res.push_back(o); return new List(res); } void List::each(runner::Runner& r, rObject f) { foreach(const rObject& o, content_) r.apply(f, SYMBOL(each), list_of (f) (o)); } void List::each_and(runner::Runner& r, rObject f) { scheduler::jobs_type jobs; rforeach (rObject& o, content_) { scheduler::rJob job = new runner::Interpreter(dynamic_cast<runner::Interpreter&>(r), f, SYMBOL(each), list_of(o)); r.link(job); job->start_job(); jobs.push_back(job); } r.yield_until_terminated(jobs); } #define BOUNCE(Name, Ret, Arg, Check) \ IF(Ret, rObject, rList) List::Name(WHEN(Arg, rObject arg)) \ { \ WHEN(Check, CHECK_NON_EMPTY(#Name)); \ WHEN(Ret, return) content_.Name(WHEN(Arg, arg)); \ return this; \ } BOUNCE(back, true, false, true ); BOUNCE(clear, false, false, false); BOUNCE(front, true, false, true ); BOUNCE(pop_back, false, false, true ); BOUNCE(pop_front, false, false, true ); BOUNCE(push_back, false, true, false); BOUNCE(push_front, false, true, false); #undef BOUNCE void List::initialize(CxxObject::Binder<List>& bind) { bind(SYMBOL(back), &List::back ); bind(SYMBOL(clear), &List::clear ); bind(SYMBOL(each), &List::each ); bind(SYMBOL(each_AMPERSAND), &List::each_and ); bind(SYMBOL(front), &List::front ); bind(SYMBOL(PLUS), &List::operator+ ); bind(SYMBOL(PLUS_EQ), &List::operator+= ); bind(SYMBOL(nth), &List::operator[] ); bind(SYMBOL(push_back), &List::push_back ); bind(SYMBOL(push_front), &List::push_front ); bind(SYMBOL(pop_back), &List::pop_back ); bind(SYMBOL(pop_front), &List::pop_front ); bind(SYMBOL(removeById), &List::remove_by_id); bind(SYMBOL(size), &List::size ); bind(SYMBOL(sort), &List::sort ); bind(SYMBOL(tail), &List::tail ); } std::string List::type_name_get() const { return type_name; } bool List::list_added = CxxObject::add<List>("List", list_class); const std::string List::type_name = "List"; } // namespace object
Use rforeach.
Use rforeach. This is not just nicer, the previous code just does not compile on my machine. http://gcc.gnu.org/ml/gcc-bugs/1998-05/msg00738.html * src/object/list-class.cc (each_and): Use rforeach.
C++
bsd-3-clause
aldebaran/urbi,urbiforge/urbi,urbiforge/urbi,urbiforge/urbi,aldebaran/urbi,aldebaran/urbi,urbiforge/urbi,aldebaran/urbi,aldebaran/urbi,urbiforge/urbi,urbiforge/urbi,urbiforge/urbi,urbiforge/urbi,aldebaran/urbi,aldebaran/urbi,aldebaran/urbi,urbiforge/urbi
a14f58cda80cfdc18d63795d19d97b5a91db50d1
src/import/generic/memory/lib/spd/spd_field.H
src/import/generic/memory/lib/spd/spd_field.H
/* IBM_PROLOG_BEGIN_TAG */ /* This is an automatically generated prolog. */ /* */ /* $Source: src/import/generic/memory/lib/spd/spd_field.H $ */ /* */ /* OpenPOWER HostBoot Project */ /* */ /* Contributors Listed Below - COPYRIGHT 2018,2019 */ /* [+] International Business Machines Corp. */ /* */ /* */ /* Licensed under the Apache License, Version 2.0 (the "License"); */ /* you may not use this file except in compliance with the License. */ /* You may obtain a copy of the License at */ /* */ /* http://www.apache.org/licenses/LICENSE-2.0 */ /* */ /* Unless required by applicable law or agreed to in writing, software */ /* distributed under the License is distributed on an "AS IS" BASIS, */ /* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or */ /* implied. See the License for the specific language governing */ /* permissions and limitations under the License. */ /* */ /* IBM_PROLOG_END_TAG */
/* IBM_PROLOG_BEGIN_TAG */ /* This is an automatically generated prolog. */ /* */ /* $Source: src/import/generic/memory/lib/spd/spd_field.H $ */ /* */ /* OpenPOWER HostBoot Project */ /* */ /* Contributors Listed Below - COPYRIGHT 2018,2019 */ /* [+] International Business Machines Corp. */ /* */ /* */ /* Licensed under the Apache License, Version 2.0 (the "License"); */ /* you may not use this file except in compliance with the License. */ /* You may obtain a copy of the License at */ /* */ /* http://www.apache.org/licenses/LICENSE-2.0 */ /* */ /* Unless required by applicable law or agreed to in writing, software */ /* distributed under the License is distributed on an "AS IS" BASIS, */ /* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or */ /* implied. See the License for the specific language governing */ /* permissions and limitations under the License. */ /* */ /* IBM_PROLOG_END_TAG */ /// /// @file spd_field.H /// @brief SPD data fields /// // *HWP HWP Owner: Andre Marin <[email protected]> // *HWP HWP Backup: Stephen Glancy <[email protected]> // *HWP Team: Memory // *HWP Level: 2 // *HWP Consumed by: HB:FSP #ifndef _MSS_SPD_FIELD_H_ #define _MSS_SPD_FIELD_H_ #include <cstdint> #include <generic/memory/lib/utils/shared/mss_generic_consts.H> namespace mss { namespace spd { /// /// @class field_t /// @brief data structure for SPD byte fields /// @note holds byte index, start bit, and bit length of a decoded field /// class field_t { private: const size_t iv_byte; const size_t iv_start; const size_t iv_length; public: // default ctor deleted field_t() = delete; /// /// @brief ctor /// @param[in] i_byte_index /// @param[in] i_start_bit /// @param[in] i_bit_length /// constexpr field_t(const size_t i_byte_index, const size_t i_start_bit, const size_t i_bit_length) : iv_byte(i_byte_index), iv_start(i_start_bit), iv_length(i_bit_length) {} /// /// @brief default dtor /// ~field_t() = default; /// /// @brief Byte index getter /// @return the byte index for this SPD field /// constexpr size_t get_byte() const { return iv_byte; } /// /// @brief Starting bit getter /// @return the starting bit position for this SPD field /// constexpr size_t get_start() const { return iv_start; } /// /// @brief bit length getter /// @return the bit length of this SPD field /// constexpr size_t get_length() const { return iv_length; } };// field_t /// /// @class init_fields /// @brief Initial fields needed to know how to parse the SPD /// @note These are preliminary fields that need to be independently /// decoded from any specific DRAM generation SPEC (e.g. SPD factory) /// class init_fields { private: enum { // Byte 1 REVISION_START = 0, REVISION_LEN = 8, // Byte 2 DEVICE_TYPE_START = 0, DEVICE_TYPE_LEN = 8, // Byte 3 HYBRID_START = 0, HYBRID_LEN = 1, HYBRID_MEDIA_START = 1, HYBRID_MEDIA_LEN = 3, BASE_MODULE_START = 4, BASE_MODULE_LEN = 4, // Byte 130 REF_RAW_CARD_START = 0, REF_RAW_CARD_LEN = 8, }; public: // 1st field: Byte number // 2nd field: Start bit // 3rd field: Bit length static constexpr field_t REVISION{1, REVISION_START, REVISION_LEN}; static constexpr field_t DEVICE_TYPE{2, DEVICE_TYPE_START, DEVICE_TYPE_LEN}; static constexpr field_t BASE_MODULE{3, BASE_MODULE_START, BASE_MODULE_LEN}; static constexpr field_t HYBRID{3, HYBRID_START, HYBRID_LEN}; static constexpr field_t HYBRID_MEDIA{3, HYBRID_MEDIA_START, HYBRID_MEDIA_LEN}; static constexpr field_t REF_RAW_CARD{130, REF_RAW_CARD_START, REF_RAW_CARD_LEN}; }; /// /// @class fields /// @brief Collection of SPD fields /// @tparam D DRAM device type (e.g. DDR4) /// @tparam S SPD parameter (e.g. RDIMM_MODULE, NVDIMM_MODULE) /// template <device_type D, parameters S> class fields; }// spd }// mss #endif // _MSS_SPD_FIELD_H_
Add SPD reader and traits DDR4 def
Add SPD reader and traits DDR4 def Includes addition of a generic const file to store constants that are not controller dependent. In addition to spd::c_str for SPD decoder tracing. Change-Id: I4eb3a04bba119dbfb45ed3b885f3be411579c3b6 Original-Change-Id: I6dafe1ff3328a1ac287b29f148e63e304f626ea5 Reviewed-on: http://ralgit01.raleigh.ibm.com/gerrit1/57492 Tested-by: FSP CI Jenkins <[email protected]> Reviewed-by: Louis Stermole <[email protected]> Tested-by: Jenkins Server <[email protected]> Tested-by: HWSV CI <[email protected]> Tested-by: Hostboot CI <[email protected]> Reviewed-by: Jennifer A. Stofer <[email protected]>
C++
apache-2.0
open-power/hostboot,open-power/hostboot,open-power/hostboot,open-power/hostboot,open-power/hostboot
e12ea9e9f3c794d1e003f1d83d75195a159c3a44
dune/stuff/test/common_fixed_map.cc
dune/stuff/test/common_fixed_map.cc
// This file is part of the dune-stuff project: // https://users.dune-project.org/projects/dune-stuff // Copyright holders: Rene Milk, Felix Schindler // License: BSD 2-Clause License (http://opensource.org/licenses/BSD-2-Clause) #include "test_common.hh" #include <string> #include <array> #include <initializer_list> #include <vector> #include <dune/stuff/common/fixed_map.hh> #include <dune/stuff/common/string.hh> #include <dune/stuff/common/ranges.hh> using namespace Dune::Stuff::Common; TEST(FixedMapTest, All) { const std::initializer_list<std::pair<std::string, int>> values( {{"0", 0}, {"1", 1}, {"2", 2}} ); const FixedMap<std::string, int, 1> too_small(values); FixedMap<std::string, int, 3> fits(values); const FixedMap<std::string, int, 6> too_big(values); EXPECT_EQ(0, too_small[toString(0)]); EXPECT_THROW(too_small["1"], Dune::RangeError); for( int i : {0,1,2}) { EXPECT_EQ(i, too_big[toString(i)]); } for( int DUNE_UNUSED(i) : {3,4,5}) { EXPECT_EQ(int(), too_big[std::string()]); } auto size = fits.size(); for( auto& pt : fits) { int value = pt.second; std::string key = pt.first; EXPECT_EQ(key, toString(value)); size--; } EXPECT_EQ(0, size); for( int i : {0,1,2}) { fits[toString(i)] += 1; EXPECT_EQ(i+1, fits[toString(i)]); } EXPECT_EQ(std::make_pair(std::string("0"), 0), *too_big.begin()); //death test segfaults inside gtest -> disabled // EXPECT_DEATH(*too_big.end(), ".*"); } int main(int argc, char** argv) { test_init(argc, argv); return RUN_ALL_TESTS(); }
// This file is part of the dune-stuff project: // https://users.dune-project.org/projects/dune-stuff // Copyright holders: Rene Milk, Felix Schindler // License: BSD 2-Clause License (http://opensource.org/licenses/BSD-2-Clause) #include "test_common.hh" #include <string> #include <array> #include <initializer_list> #include <vector> #include <dune/stuff/common/fixed_map.hh> #include <dune/stuff/common/string.hh> #include <dune/stuff/common/ranges.hh> using namespace Dune::Stuff::Common; TEST(FixedMapTest, All) { const std::initializer_list<std::pair<std::string, int>> values{{"0", 0}, {"1", 1}, {"2", 2}}; const FixedMap<std::string, int, 1> too_small(values); FixedMap<std::string, int, 3> fits(values); const FixedMap<std::string, int, 6> too_big(values); EXPECT_EQ(0, too_small[toString(0)]); EXPECT_THROW(too_small["1"], Dune::RangeError); for( int i : {0,1,2}) { EXPECT_EQ(i, too_big[toString(i)]); } for( int DUNE_UNUSED(i) : {3,4,5}) { EXPECT_EQ(int(), too_big[std::string()]); } auto size = fits.size(); for( auto& pt : fits) { int value = pt.second; std::string key = pt.first; EXPECT_EQ(key, toString(value)); size--; } EXPECT_EQ(0, size); for( int i : {0,1,2}) { fits[toString(i)] += 1; EXPECT_EQ(i+1, fits[toString(i)]); } EXPECT_EQ(std::make_pair(std::string("0"), 0), *too_big.begin()); //death test segfaults inside gtest -> disabled // EXPECT_DEATH(*too_big.end(), ".*"); } int main(int argc, char** argv) { test_init(argc, argv); return RUN_ALL_TESTS(); }
fix clang builds
[test.common_fixed_map] fix clang builds
C++
bsd-2-clause
renemilk/DUNE-Stuff,renemilk/DUNE-Stuff,renemilk/DUNE-Stuff
92b07f56983c1d9b159cbcfeeb06595b6580b69b
src/overdrawanalyzer.cpp
src/overdrawanalyzer.cpp
#include "meshoptimizer.hpp" #include <algorithm> #include <cassert> #include <cfloat> #include <cstring> namespace { const int kViewport = 256; struct Vector3 { float x, y, z; }; struct OverdrawBuffer { float z[kViewport][kViewport][2]; unsigned int overdraw[kViewport][kViewport][2]; }; inline float det2x2(float a, float b, float c, float d) { // (a b) // (c d) return a * d - b * c; } inline float computeDepthGradients(float& dzdx, float& dzdy, float x1, float y1, float z1, float x2, float y2, float z2, float x3, float y3, float z3) { // z2 = z1 + dzdx * (x2 - x1) + dzdy * (y2 - y1) // z3 = z1 + dzdx * (x3 - x1) + dzdy * (y3 - y1) // (x2-x1 y2-y1)(dzdx) = (z2-z1) // (x3-x1 y3-y1)(dzdy) (z3-z1) // we'll solve it with Cramer's rule float det = det2x2(x2 - x1, y2 - y1, x3 - x1, y3 - y1); float invdet = (det == 0) ? 0 : 1 / det; dzdx = det2x2(z2 - z1, y2 - y1, z3 - z1, y3 - y1) * invdet; dzdy = det2x2(x2 - x1, z2 - z1, x3 - x1, z3 - z1) * invdet; return det; } // half-space fixed point triangle rasterizer // adapted from http://forum.devmaster.net/t/advanced-rasterization/6145 void rasterize(OverdrawBuffer* buffer, float v1x, float v1y, float v1z, float v2x, float v2y, float v2z, float v3x, float v3y, float v3z) { // compute depth gradients float DZx, DZy; float det = computeDepthGradients(DZx, DZy, v1x, v1y, v1z, v2x, v2y, v2z, v3x, v3y, v3z); int sign = det > 0; // flip backfacing triangles to simplify rasterization logic if (sign) { std::swap(v2x, v3x); std::swap(v2y, v3y); std::swap(v2z, v3z); } // 28.4 fixed-point coordinates const int X1 = int(16.0f * v1x + 0.5f); const int X2 = int(16.0f * v2x + 0.5f); const int X3 = int(16.0f * v3x + 0.5f); const int Y1 = int(16.0f * v1y + 0.5f); const int Y2 = int(16.0f * v2y + 0.5f); const int Y3 = int(16.0f * v3y + 0.5f); // deltas const int DX12 = X1 - X2; const int DX23 = X2 - X3; const int DX31 = X3 - X1; const int DY12 = Y1 - Y2; const int DY23 = Y2 - Y3; const int DY31 = Y3 - Y1; // bounding rectangle int minx = std::min(X1, std::min(X2, X3)) >> 4; int maxx = (std::max(X1, std::max(X2, X3)) + 0xF) >> 4; int miny = std::min(Y1, std::min(Y2, Y3)) >> 4; int maxy = (std::max(Y1, std::max(Y2, Y3)) + 0xF) >> 4; assert(minx >= 0 && maxx <= kViewport); assert(miny >= 0 && maxy <= kViewport); // half-edge constants int C1 = DY12 * X1 - DX12 * Y1; int C2 = DY23 * X2 - DX23 * Y2; int C3 = DY31 * X3 - DX31 * Y3; // correct for fill convention if (DY12 < 0 || (DY12 == 0 && DX12 > 0)) C1++; if (DY23 < 0 || (DY23 == 0 && DX23 > 0)) C2++; if (DY31 < 0 || (DY31 == 0 && DX31 > 0)) C3++; int CY1 = C1 + DX12 * (miny << 4) - DY12 * (minx << 4); int CY2 = C2 + DX23 * (miny << 4) - DY23 * (minx << 4); int CY3 = C3 + DX31 * (miny << 4) - DY31 * (minx << 4); float ZY = v1z + DZx * (minx - v1x) + DZy * (miny - v1y); for (int y = miny; y < maxy; y++) { int CX1 = CY1; int CX2 = CY2; int CX3 = CY3; float ZX = ZY; for (int x = minx; x < maxx; x++) { if (CX1 > 0 && CX2 > 0 && CX3 > 0) { float z = sign ? kViewport - ZX : ZX; if (z >= buffer->z[y][x][sign]) { buffer->z[y][x][sign] = z; buffer->overdraw[y][x][sign]++; } } CX1 -= DY12 << 4; CX2 -= DY23 << 4; CX3 -= DY31 << 4; ZX += DZx; } CY1 += DX12 << 4; CY2 += DX23 << 4; CY3 += DX31 << 4; ZY += DZy; } } template <typename T> OverdrawStatistics analyzeOverdrawImpl(const T* indices, size_t index_count, const float* vertex_positions, size_t vertex_positions_stride, size_t vertex_count) { assert(vertex_positions_stride > 0); assert(vertex_positions_stride % sizeof(float) == 0); size_t vertex_stride_float = vertex_positions_stride / sizeof(float); OverdrawStatistics result = {}; float minv[3] = {FLT_MAX, FLT_MAX, FLT_MAX}; float maxv[3] = {-FLT_MAX, -FLT_MAX, -FLT_MAX}; for (size_t i = 0; i < vertex_count; ++i) { const float* v = vertex_positions + i * vertex_stride_float; for (int j = 0; j < 3; ++j) { minv[j] = std::min(minv[j], v[j]); maxv[j] = std::max(maxv[j], v[j]); } } float extent = std::max(maxv[0] - minv[0], std::max(maxv[1] - minv[1], maxv[2] - minv[2])); float scale = kViewport / extent; std::vector<Vector3> triangles(index_count); for (size_t i = 0; i < index_count; i += 3) { const float* v0 = vertex_positions + indices[i + 0] * vertex_stride_float; const float* v1 = vertex_positions + indices[i + 1] * vertex_stride_float; const float* v2 = vertex_positions + indices[i + 2] * vertex_stride_float; Vector3 vn0 = {(v0[0] - minv[0]) * scale, (v0[1] - minv[1]) * scale, (v0[2] - minv[2]) * scale}; Vector3 vn1 = {(v1[0] - minv[0]) * scale, (v1[1] - minv[1]) * scale, (v1[2] - minv[2]) * scale}; Vector3 vn2 = {(v2[0] - minv[0]) * scale, (v2[1] - minv[1]) * scale, (v2[2] - minv[2]) * scale}; triangles[i + 0] = vn0; triangles[i + 1] = vn1; triangles[i + 2] = vn2; } OverdrawBuffer* buffer = new OverdrawBuffer(); for (int axis = 0; axis < 3; ++axis) { memset(buffer, 0, sizeof(OverdrawBuffer)); for (size_t i = 0; i < index_count; i += 3) { const float* vn0 = &triangles[i + 0].x; const float* vn1 = &triangles[i + 1].x; const float* vn2 = &triangles[i + 2].x; switch (axis) { case 0: rasterize(buffer, vn0[2], vn0[1], vn0[0], vn1[2], vn1[1], vn1[0], vn2[2], vn2[1], vn2[0]); break; case 1: rasterize(buffer, vn0[0], vn0[2], vn0[1], vn1[0], vn1[2], vn1[1], vn2[0], vn2[2], vn2[1]); break; case 2: rasterize(buffer, vn0[1], vn0[0], vn0[2], vn1[1], vn1[0], vn1[2], vn2[1], vn2[0], vn2[2]); break; } } for (int y = 0; y < kViewport; ++y) for (int x = 0; x < kViewport; ++x) for (int s = 0; s < 2; ++s) { unsigned int overdraw = buffer->overdraw[y][x][s]; result.pixels_covered += overdraw > 0; result.pixels_shaded += overdraw; } } delete buffer; result.overdraw = static_cast<float>(result.pixels_shaded) / static_cast<float>(result.pixels_covered); return result; } } OverdrawStatistics analyzeOverdraw(const unsigned short* indices, size_t index_count, const float* vertex_positions, size_t vertex_positions_stride, size_t vertex_count) { return analyzeOverdrawImpl(indices, index_count, vertex_positions, vertex_positions_stride, vertex_count); } OverdrawStatistics analyzeOverdraw(const unsigned int* indices, size_t index_count, const float* vertex_positions, size_t vertex_positions_stride, size_t vertex_count) { return analyzeOverdrawImpl(indices, index_count, vertex_positions, vertex_positions_stride, vertex_count); }
#include "meshoptimizer.hpp" #include <algorithm> #include <cassert> #include <cfloat> #include <cstring> namespace { const int kViewport = 256; struct Vector3 { float x, y, z; }; struct OverdrawBuffer { float z[kViewport][kViewport][2]; unsigned int overdraw[kViewport][kViewport][2]; }; inline float det2x2(float a, float b, float c, float d) { // (a b) // (c d) return a * d - b * c; } inline float computeDepthGradients(float& dzdx, float& dzdy, float x1, float y1, float z1, float x2, float y2, float z2, float x3, float y3, float z3) { // z2 = z1 + dzdx * (x2 - x1) + dzdy * (y2 - y1) // z3 = z1 + dzdx * (x3 - x1) + dzdy * (y3 - y1) // (x2-x1 y2-y1)(dzdx) = (z2-z1) // (x3-x1 y3-y1)(dzdy) (z3-z1) // we'll solve it with Cramer's rule float det = det2x2(x2 - x1, y2 - y1, x3 - x1, y3 - y1); float invdet = (det == 0) ? 0 : 1 / det; dzdx = det2x2(z2 - z1, y2 - y1, z3 - z1, y3 - y1) * invdet; dzdy = det2x2(x2 - x1, z2 - z1, x3 - x1, z3 - z1) * invdet; return det; } // half-space fixed point triangle rasterizer // adapted from http://forum.devmaster.net/t/advanced-rasterization/6145 void rasterize(OverdrawBuffer* buffer, float v1x, float v1y, float v1z, float v2x, float v2y, float v2z, float v3x, float v3y, float v3z) { // compute depth gradients float DZx, DZy; float det = computeDepthGradients(DZx, DZy, v1x, v1y, v1z, v2x, v2y, v2z, v3x, v3y, v3z); int sign = det > 0; // flip backfacing triangles to simplify rasterization logic if (sign) { std::swap(v2x, v3x); std::swap(v2y, v3y); std::swap(v2z, v3z); } // coordinates, 28.4 fixed point int X1 = int(16.0f * v1x + 0.5f); int X2 = int(16.0f * v2x + 0.5f); int X3 = int(16.0f * v3x + 0.5f); int Y1 = int(16.0f * v1y + 0.5f); int Y2 = int(16.0f * v2y + 0.5f); int Y3 = int(16.0f * v3y + 0.5f); // bounding rectangle, clipped against viewport int minx = std::max((std::min(X1, std::min(X2, X3)) + 0xF) >> 4, 0); int maxx = std::min((std::max(X1, std::max(X2, X3)) + 0xF) >> 4, kViewport); int miny = std::max((std::min(Y1, std::min(Y2, Y3)) + 0xF) >> 4, 0); int maxy = std::min((std::max(Y1, std::max(Y2, Y3)) + 0xF) >> 4, kViewport); // deltas, 28.4 fixed point int DX12 = X1 - X2; int DX23 = X2 - X3; int DX31 = X3 - X1; int DY12 = Y1 - Y2; int DY23 = Y2 - Y3; int DY31 = Y3 - Y1; // fill convention correction int TL1 = DY12 < 0 || (DY12 == 0 && DX12 > 0); int TL2 = DY23 < 0 || (DY23 == 0 && DX23 > 0); int TL3 = DY31 < 0 || (DY31 == 0 && DX31 > 0); // half edge equations, 24.8 fixed point int CY1 = DX12 * ((miny << 4) - Y1) - DY12 * ((minx << 4) - X1) + TL1 - 1; int CY2 = DX23 * ((miny << 4) - Y2) - DY23 * ((minx << 4) - X2) + TL2 - 1; int CY3 = DX31 * ((miny << 4) - Y3) - DY31 * ((minx << 4) - X3) + TL3 - 1; float ZY = v1z + (DZx * float((minx << 4) - X1) + DZy * float((miny << 4) - Y1)) * (1 / 16.f); for (int y = miny; y < maxy; y++) { int CX1 = CY1; int CX2 = CY2; int CX3 = CY3; float ZX = ZY; for (int x = minx; x < maxx; x++) { // check if all CXn are non-negative if ((CX1 | CX2 | CX3) >= 0) { float z = sign ? kViewport - ZX : ZX; if (z >= buffer->z[y][x][sign]) { buffer->z[y][x][sign] = z; buffer->overdraw[y][x][sign]++; } } CX1 -= DY12 << 4; CX2 -= DY23 << 4; CX3 -= DY31 << 4; ZX += DZx; } CY1 += DX12 << 4; CY2 += DX23 << 4; CY3 += DX31 << 4; ZY += DZy; } } template <typename T> OverdrawStatistics analyzeOverdrawImpl(const T* indices, size_t index_count, const float* vertex_positions, size_t vertex_positions_stride, size_t vertex_count) { assert(vertex_positions_stride > 0); assert(vertex_positions_stride % sizeof(float) == 0); size_t vertex_stride_float = vertex_positions_stride / sizeof(float); OverdrawStatistics result = {}; float minv[3] = {FLT_MAX, FLT_MAX, FLT_MAX}; float maxv[3] = {-FLT_MAX, -FLT_MAX, -FLT_MAX}; for (size_t i = 0; i < vertex_count; ++i) { const float* v = vertex_positions + i * vertex_stride_float; for (int j = 0; j < 3; ++j) { minv[j] = std::min(minv[j], v[j]); maxv[j] = std::max(maxv[j], v[j]); } } float extent = std::max(maxv[0] - minv[0], std::max(maxv[1] - minv[1], maxv[2] - minv[2])); float scale = kViewport / extent; std::vector<Vector3> triangles(index_count); for (size_t i = 0; i < index_count; i += 3) { const float* v0 = vertex_positions + indices[i + 0] * vertex_stride_float; const float* v1 = vertex_positions + indices[i + 1] * vertex_stride_float; const float* v2 = vertex_positions + indices[i + 2] * vertex_stride_float; Vector3 vn0 = {(v0[0] - minv[0]) * scale, (v0[1] - minv[1]) * scale, (v0[2] - minv[2]) * scale}; Vector3 vn1 = {(v1[0] - minv[0]) * scale, (v1[1] - minv[1]) * scale, (v1[2] - minv[2]) * scale}; Vector3 vn2 = {(v2[0] - minv[0]) * scale, (v2[1] - minv[1]) * scale, (v2[2] - minv[2]) * scale}; triangles[i + 0] = vn0; triangles[i + 1] = vn1; triangles[i + 2] = vn2; } OverdrawBuffer* buffer = new OverdrawBuffer(); for (int axis = 0; axis < 3; ++axis) { memset(buffer, 0, sizeof(OverdrawBuffer)); for (size_t i = 0; i < index_count; i += 3) { const float* vn0 = &triangles[i + 0].x; const float* vn1 = &triangles[i + 1].x; const float* vn2 = &triangles[i + 2].x; switch (axis) { case 0: rasterize(buffer, vn0[2], vn0[1], vn0[0], vn1[2], vn1[1], vn1[0], vn2[2], vn2[1], vn2[0]); break; case 1: rasterize(buffer, vn0[0], vn0[2], vn0[1], vn1[0], vn1[2], vn1[1], vn2[0], vn2[2], vn2[1]); break; case 2: rasterize(buffer, vn0[1], vn0[0], vn0[2], vn1[1], vn1[0], vn1[2], vn2[1], vn2[0], vn2[2]); break; } } for (int y = 0; y < kViewport; ++y) for (int x = 0; x < kViewport; ++x) for (int s = 0; s < 2; ++s) { unsigned int overdraw = buffer->overdraw[y][x][s]; result.pixels_covered += overdraw > 0; result.pixels_shaded += overdraw; } } delete buffer; result.overdraw = static_cast<float>(result.pixels_shaded) / static_cast<float>(result.pixels_covered); return result; } } OverdrawStatistics analyzeOverdraw(const unsigned short* indices, size_t index_count, const float* vertex_positions, size_t vertex_positions_stride, size_t vertex_count) { return analyzeOverdrawImpl(indices, index_count, vertex_positions, vertex_positions_stride, vertex_count); } OverdrawStatistics analyzeOverdraw(const unsigned int* indices, size_t index_count, const float* vertex_positions, size_t vertex_positions_stride, size_t vertex_count) { return analyzeOverdrawImpl(indices, index_count, vertex_positions, vertex_positions_stride, vertex_count); }
Clean up rasterization code
overdrawanalyzer: Clean up rasterization code Add slightly better comments, use one condition in the for loop to check all signs simultaneously.
C++
mit
zeux/meshoptimizer,zeux/meshoptimizer,zeux/meshoptimizer
10a175753b04882cb32f7339a6ed396dbed8cdff
src/overdrawanalyzer.cpp
src/overdrawanalyzer.cpp
// This file is part of meshoptimizer library; see meshoptimizer.h for version/license details #include "meshoptimizer.h" #include <assert.h> #include <float.h> #include <string.h> // This work is based on: // Nicolas Capens. Advanced Rasterization. 2004 namespace meshopt { const int kViewport = 256; struct OverdrawBuffer { float z[kViewport][kViewport][2]; unsigned int overdraw[kViewport][kViewport][2]; }; #ifndef min #define min(a, b) ((a) < (b) ? (a) : (b)) #endif #ifndef max #define max(a, b) ((a) > (b) ? (a) : (b)) #endif static float computeDepthGradients(float& dzdx, float& dzdy, float x1, float y1, float z1, float x2, float y2, float z2, float x3, float y3, float z3) { // z2 = z1 + dzdx * (x2 - x1) + dzdy * (y2 - y1) // z3 = z1 + dzdx * (x3 - x1) + dzdy * (y3 - y1) // (x2-x1 y2-y1)(dzdx) = (z2-z1) // (x3-x1 y3-y1)(dzdy) (z3-z1) // we'll solve it with Cramer's rule float det = (x2 - x1) * (y3 - y1) - (y2 - y1) * (x3 - x1); float invdet = (det == 0) ? 0 : 1 / det; dzdx = (z2 - z1) * (y3 - y1) - (y2 - y1) * (z3 - z1) * invdet; dzdy = (x2 - x1) * (z3 - z1) - (z2 - z1) * (x3 - x1) * invdet; return det; } // half-space fixed point triangle rasterizer static void rasterize(OverdrawBuffer* buffer, float v1x, float v1y, float v1z, float v2x, float v2y, float v2z, float v3x, float v3y, float v3z) { // compute depth gradients float DZx, DZy; float det = computeDepthGradients(DZx, DZy, v1x, v1y, v1z, v2x, v2y, v2z, v3x, v3y, v3z); int sign = det > 0; // flip backfacing triangles to simplify rasterization logic if (sign) { // flipping v2 & v3 preserves depth gradients since they're based on v1 float t; t = v2x, v2x = v3x, v3x = t; t = v2y, v2y = v3y, v3y = t; t = v2z, v2z = v3z, v3z = t; // flip depth since we rasterize backfacing triangles to second buffer with reverse Z; only v1z is used below v1z = kViewport - v1z; DZx = -DZx; DZy = -DZy; } // coordinates, 28.4 fixed point int X1 = int(16.0f * v1x + 0.5f); int X2 = int(16.0f * v2x + 0.5f); int X3 = int(16.0f * v3x + 0.5f); int Y1 = int(16.0f * v1y + 0.5f); int Y2 = int(16.0f * v2y + 0.5f); int Y3 = int(16.0f * v3y + 0.5f); // bounding rectangle, clipped against viewport // since we rasterize pixels with covered centers, min >0.5 should round up // as for max, due to top-left filling convention we will never rasterize right/bottom edges // so max >= 0.5 should round down int minx = max((min(X1, min(X2, X3)) + 7) >> 4, 0); int maxx = min((max(X1, max(X2, X3)) + 7) >> 4, kViewport); int miny = max((min(Y1, min(Y2, Y3)) + 7) >> 4, 0); int maxy = min((max(Y1, max(Y2, Y3)) + 7) >> 4, kViewport); // deltas, 28.4 fixed point int DX12 = X1 - X2; int DX23 = X2 - X3; int DX31 = X3 - X1; int DY12 = Y1 - Y2; int DY23 = Y2 - Y3; int DY31 = Y3 - Y1; // fill convention correction int TL1 = DY12 < 0 || (DY12 == 0 && DX12 > 0); int TL2 = DY23 < 0 || (DY23 == 0 && DX23 > 0); int TL3 = DY31 < 0 || (DY31 == 0 && DX31 > 0); // half edge equations, 24.8 fixed point // note that we offset minx/miny by half pixel since we want to rasterize pixels with covered centers int FX = (minx << 4) + 8; int FY = (miny << 4) + 8; int CY1 = DX12 * (FY - Y1) - DY12 * (FX - X1) + TL1 - 1; int CY2 = DX23 * (FY - Y2) - DY23 * (FX - X2) + TL2 - 1; int CY3 = DX31 * (FY - Y3) - DY31 * (FX - X3) + TL3 - 1; float ZY = v1z + (DZx * float(FX - X1) + DZy * float(FY - Y1)) * (1 / 16.f); for (int y = miny; y < maxy; y++) { int CX1 = CY1; int CX2 = CY2; int CX3 = CY3; float ZX = ZY; for (int x = minx; x < maxx; x++) { // check if all CXn are non-negative if ((CX1 | CX2 | CX3) >= 0) { if (ZX >= buffer->z[y][x][sign]) { buffer->z[y][x][sign] = ZX; buffer->overdraw[y][x][sign]++; } } // signed left shift is UB for negative numbers so use unsigned-signed casts CX1 -= int(unsigned(DY12) << 4); CX2 -= int(unsigned(DY23) << 4); CX3 -= int(unsigned(DY31) << 4); ZX += DZx; } // signed left shift is UB for negative numbers so use unsigned-signed casts CY1 += int(unsigned(DX12) << 4); CY2 += int(unsigned(DX23) << 4); CY3 += int(unsigned(DX31) << 4); ZY += DZy; } } } // namespace meshopt meshopt_OverdrawStatistics meshopt_analyzeOverdraw(const unsigned int* indices, size_t index_count, const float* vertex_positions, size_t vertex_count, size_t vertex_positions_stride) { using namespace meshopt; assert(index_count % 3 == 0); assert(vertex_positions_stride > 0 && vertex_positions_stride <= 256); assert(vertex_positions_stride % sizeof(float) == 0); meshopt_Allocator allocator; size_t vertex_stride_float = vertex_positions_stride / sizeof(float); meshopt_OverdrawStatistics result = {}; float minv[3] = {FLT_MAX, FLT_MAX, FLT_MAX}; float maxv[3] = {-FLT_MAX, -FLT_MAX, -FLT_MAX}; for (size_t i = 0; i < vertex_count; ++i) { const float* v = vertex_positions + i * vertex_stride_float; for (int j = 0; j < 3; ++j) { minv[j] = min(minv[j], v[j]); maxv[j] = max(maxv[j], v[j]); } } float extent = max(maxv[0] - minv[0], max(maxv[1] - minv[1], maxv[2] - minv[2])); float scale = kViewport / extent; float* triangles = allocator.allocate<float>(index_count * 3); for (size_t i = 0; i < index_count; ++i) { unsigned int index = indices[i]; assert(index < vertex_count); const float* v = vertex_positions + index * vertex_stride_float; triangles[i * 3 + 0] = (v[0] - minv[0]) * scale; triangles[i * 3 + 1] = (v[1] - minv[1]) * scale; triangles[i * 3 + 2] = (v[2] - minv[2]) * scale; } OverdrawBuffer* buffer = allocator.allocate<OverdrawBuffer>(1); for (int axis = 0; axis < 3; ++axis) { memset(buffer, 0, sizeof(OverdrawBuffer)); for (size_t i = 0; i < index_count; i += 3) { const float* vn0 = &triangles[3 * (i + 0)]; const float* vn1 = &triangles[3 * (i + 1)]; const float* vn2 = &triangles[3 * (i + 2)]; switch (axis) { case 0: rasterize(buffer, vn0[2], vn0[1], vn0[0], vn1[2], vn1[1], vn1[0], vn2[2], vn2[1], vn2[0]); break; case 1: rasterize(buffer, vn0[0], vn0[2], vn0[1], vn1[0], vn1[2], vn1[1], vn2[0], vn2[2], vn2[1]); break; case 2: rasterize(buffer, vn0[1], vn0[0], vn0[2], vn1[1], vn1[0], vn1[2], vn2[1], vn2[0], vn2[2]); break; } } for (int y = 0; y < kViewport; ++y) for (int x = 0; x < kViewport; ++x) for (int s = 0; s < 2; ++s) { unsigned int overdraw = buffer->overdraw[y][x][s]; result.pixels_covered += overdraw > 0; result.pixels_shaded += overdraw; } } result.overdraw = result.pixels_covered ? float(result.pixels_shaded) / float(result.pixels_covered) : 0.f; return result; }
// This file is part of meshoptimizer library; see meshoptimizer.h for version/license details #include "meshoptimizer.h" #include <assert.h> #include <float.h> #include <string.h> // This work is based on: // Nicolas Capens. Advanced Rasterization. 2004 namespace meshopt { const int kViewport = 256; struct OverdrawBuffer { float z[kViewport][kViewport][2]; unsigned int overdraw[kViewport][kViewport][2]; }; #ifndef min #define min(a, b) ((a) < (b) ? (a) : (b)) #endif #ifndef max #define max(a, b) ((a) > (b) ? (a) : (b)) #endif static float computeDepthGradients(float& dzdx, float& dzdy, float x1, float y1, float z1, float x2, float y2, float z2, float x3, float y3, float z3) { // z2 = z1 + dzdx * (x2 - x1) + dzdy * (y2 - y1) // z3 = z1 + dzdx * (x3 - x1) + dzdy * (y3 - y1) // (x2-x1 y2-y1)(dzdx) = (z2-z1) // (x3-x1 y3-y1)(dzdy) (z3-z1) // we'll solve it with Cramer's rule float det = (x2 - x1) * (y3 - y1) - (y2 - y1) * (x3 - x1); float invdet = (det == 0) ? 0 : 1 / det; dzdx = (z2 - z1) * (y3 - y1) - (y2 - y1) * (z3 - z1) * invdet; dzdy = (x2 - x1) * (z3 - z1) - (z2 - z1) * (x3 - x1) * invdet; return det; } // half-space fixed point triangle rasterizer static void rasterize(OverdrawBuffer* buffer, float v1x, float v1y, float v1z, float v2x, float v2y, float v2z, float v3x, float v3y, float v3z) { // compute depth gradients float DZx, DZy; float det = computeDepthGradients(DZx, DZy, v1x, v1y, v1z, v2x, v2y, v2z, v3x, v3y, v3z); int sign = det > 0; // flip backfacing triangles to simplify rasterization logic if (sign) { // flipping v2 & v3 preserves depth gradients since they're based on v1 float t; t = v2x, v2x = v3x, v3x = t; t = v2y, v2y = v3y, v3y = t; t = v2z, v2z = v3z, v3z = t; // flip depth since we rasterize backfacing triangles to second buffer with reverse Z; only v1z is used below v1z = kViewport - v1z; DZx = -DZx; DZy = -DZy; } // coordinates, 28.4 fixed point int X1 = int(16.0f * v1x + 0.5f); int X2 = int(16.0f * v2x + 0.5f); int X3 = int(16.0f * v3x + 0.5f); int Y1 = int(16.0f * v1y + 0.5f); int Y2 = int(16.0f * v2y + 0.5f); int Y3 = int(16.0f * v3y + 0.5f); // bounding rectangle, clipped against viewport // since we rasterize pixels with covered centers, min >0.5 should round up // as for max, due to top-left filling convention we will never rasterize right/bottom edges // so max >= 0.5 should round down int minx = max((min(X1, min(X2, X3)) + 7) >> 4, 0); int maxx = min((max(X1, max(X2, X3)) + 7) >> 4, kViewport); int miny = max((min(Y1, min(Y2, Y3)) + 7) >> 4, 0); int maxy = min((max(Y1, max(Y2, Y3)) + 7) >> 4, kViewport); // deltas, 28.4 fixed point int DX12 = X1 - X2; int DX23 = X2 - X3; int DX31 = X3 - X1; int DY12 = Y1 - Y2; int DY23 = Y2 - Y3; int DY31 = Y3 - Y1; // fill convention correction int TL1 = DY12 < 0 || (DY12 == 0 && DX12 > 0); int TL2 = DY23 < 0 || (DY23 == 0 && DX23 > 0); int TL3 = DY31 < 0 || (DY31 == 0 && DX31 > 0); // half edge equations, 24.8 fixed point // note that we offset minx/miny by half pixel since we want to rasterize pixels with covered centers int FX = (minx << 4) + 8; int FY = (miny << 4) + 8; int CY1 = DX12 * (FY - Y1) - DY12 * (FX - X1) + TL1 - 1; int CY2 = DX23 * (FY - Y2) - DY23 * (FX - X2) + TL2 - 1; int CY3 = DX31 * (FY - Y3) - DY31 * (FX - X3) + TL3 - 1; float ZY = v1z + (DZx * float(FX - X1) + DZy * float(FY - Y1)) * (1 / 16.f); for (int y = miny; y < maxy; y++) { int CX1 = CY1; int CX2 = CY2; int CX3 = CY3; float ZX = ZY; for (int x = minx; x < maxx; x++) { // check if all CXn are non-negative if ((CX1 | CX2 | CX3) >= 0) { if (ZX >= buffer->z[y][x][sign]) { buffer->z[y][x][sign] = ZX; buffer->overdraw[y][x][sign]++; } } // signed left shift is UB for negative numbers so use unsigned-signed casts CX1 -= int(unsigned(DY12) << 4); CX2 -= int(unsigned(DY23) << 4); CX3 -= int(unsigned(DY31) << 4); ZX += DZx; } // signed left shift is UB for negative numbers so use unsigned-signed casts CY1 += int(unsigned(DX12) << 4); CY2 += int(unsigned(DX23) << 4); CY3 += int(unsigned(DX31) << 4); ZY += DZy; } } } // namespace meshopt meshopt_OverdrawStatistics meshopt_analyzeOverdraw(const unsigned int* indices, size_t index_count, const float* vertex_positions, size_t vertex_count, size_t vertex_positions_stride) { using namespace meshopt; assert(index_count % 3 == 0); assert(vertex_positions_stride > 0 && vertex_positions_stride <= 256); assert(vertex_positions_stride % sizeof(float) == 0); meshopt_Allocator allocator; size_t vertex_stride_float = vertex_positions_stride / sizeof(float); meshopt_OverdrawStatistics result = {}; float minv[3] = {FLT_MAX, FLT_MAX, FLT_MAX}; float maxv[3] = {-FLT_MAX, -FLT_MAX, -FLT_MAX}; for (size_t i = 0; i < vertex_count; ++i) { const float* v = vertex_positions + i * vertex_stride_float; for (int j = 0; j < 3; ++j) { minv[j] = min(minv[j], v[j]); maxv[j] = max(maxv[j], v[j]); } } float extent = max(maxv[0] - minv[0], max(maxv[1] - minv[1], maxv[2] - minv[2])); float scale = kViewport / extent; float* triangles = allocator.allocate<float>(index_count * 3); for (size_t i = 0; i < index_count; ++i) { unsigned int index = indices[i]; assert(index < vertex_count); const float* v = vertex_positions + index * vertex_stride_float; triangles[i * 3 + 0] = (v[0] - minv[0]) * scale; triangles[i * 3 + 1] = (v[1] - minv[1]) * scale; triangles[i * 3 + 2] = (v[2] - minv[2]) * scale; } OverdrawBuffer* buffer = allocator.allocate<OverdrawBuffer>(1); for (int axis = 0; axis < 3; ++axis) { memset(buffer, 0, sizeof(OverdrawBuffer)); for (size_t i = 0; i < index_count; i += 3) { const float* vn0 = &triangles[3 * (i + 0)]; const float* vn1 = &triangles[3 * (i + 1)]; const float* vn2 = &triangles[3 * (i + 2)]; switch (axis) { case 0: rasterize(buffer, vn0[2], vn0[1], vn0[0], vn1[2], vn1[1], vn1[0], vn2[2], vn2[1], vn2[0]); break; case 1: rasterize(buffer, vn0[0], vn0[2], vn0[1], vn1[0], vn1[2], vn1[1], vn2[0], vn2[2], vn2[1]); break; case 2: rasterize(buffer, vn0[1], vn0[0], vn0[2], vn1[1], vn1[0], vn1[2], vn2[1], vn2[0], vn2[2]); break; } } for (int y = 0; y < kViewport; ++y) for (int x = 0; x < kViewport; ++x) for (int s = 0; s < 2; ++s) { unsigned int overdraw = buffer->overdraw[y][x][s]; result.pixels_covered += overdraw > 0; result.pixels_shaded += overdraw; } } result.overdraw = result.pixels_covered ? float(result.pixels_shaded) / float(result.pixels_covered) : 0.f; return result; }
Fix newline at the end of file
overdraw: Fix newline at the end of file This fixes -Wc++98-compat-pedantic warning.
C++
mit
zeux/meshoptimizer,zeux/meshoptimizer,zeux/meshoptimizer
0bc26d6a6b5631134b7a5d77dfb36c0426ff135b
result.hpp
result.hpp
#ifndef BFC_RESULT_HPP #define BFC_RESULT_HPP namespace bfc { enum class result_type { FAIL, OK, DONE }; } #endif /* BFC_RESULT_HPP */
#ifndef BFC_RESULT_HPP #define BFC_RESULT_HPP namespace bfc { enum class result_type { FAIL = -1, OK = 0, DONE = 1 }; } #endif /* BFC_RESULT_HPP */
Resolve merge conflict (keep c++11 enum class)
Resolve merge conflict (keep c++11 enum class)
C++
mit
bassettmb/bfc,bassettmb/bfc
0926bff0cc89853a4cadb9b82add978029b9bf7b
routed.cpp
routed.cpp
/* Copyright (c) 2013, Project OSRM, Dennis Luxen, others 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. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include "Library/OSRM.h" #include "Server/ServerFactory.h" #include "Util/GitDescription.h" #include "Util/InputFileUtil.h" #include "Util/OpenMPWrapper.h" #include "Util/ProgramOptions.h" #include "Util/SimpleLogger.h" #include "Util/UUID.h" #ifdef __linux__ #include "Util/LinuxStackTrace.h" #include <sys/mman.h> #endif #include <signal.h> #include <boost/bind.hpp> #include <boost/date_time.hpp> #include <boost/thread.hpp> #include <iostream> #ifdef _WIN32 boost::function0<void> console_ctrl_function; BOOL WINAPI console_ctrl_handler(DWORD ctrl_type) { switch (ctrl_type) { case CTRL_C_EVENT: case CTRL_BREAK_EVENT: case CTRL_CLOSE_EVENT: case CTRL_SHUTDOWN_EVENT: console_ctrl_function(); return TRUE; default: return FALSE; } } #endif int main (int argc, const char * argv[]) { try { LogPolicy::GetInstance().Unmute(); #ifdef __linux__ if(!mlockall(MCL_CURRENT | MCL_FUTURE)) { SimpleLogger().Write(logWARNING) << "Process " << argv[0] << "could not be locked to RAM"; } installCrashHandler(argv[0]); #endif std::string ip_address; int ip_port, requested_num_threads; ServerPaths server_paths; if( !GenerateServerProgramOptions( argc, argv, server_paths, ip_address, ip_port, requested_num_threads ) ) { return 0; } SimpleLogger().Write() << "starting up engines, " << g_GIT_DESCRIPTION << ", " << "compiled at " << __DATE__ << ", " __TIME__; SimpleLogger().Write() << "HSGR file:\t" << server_paths["hsgrdata"]; SimpleLogger().Write() << "Nodes file:\t" << server_paths["nodesdata"]; SimpleLogger().Write() << "Edges file:\t" << server_paths["edgesdata"]; SimpleLogger().Write() << "RAM file:\t" << server_paths["ramindex"]; SimpleLogger().Write() << "Index file:\t" << server_paths["fileindex"]; SimpleLogger().Write() << "Names file:\t" << server_paths["namesdata"]; SimpleLogger().Write() << "Timestamp file:\t" << server_paths["timestamp"]; SimpleLogger().Write() << "Threads:\t" << requested_num_threads; SimpleLogger().Write() << "IP address:\t" << ip_address; SimpleLogger().Write() << "IP port:\t" << ip_port; #ifndef _WIN32 int sig = 0; sigset_t new_mask; sigset_t old_mask; sigfillset(&new_mask); pthread_sigmask(SIG_BLOCK, &new_mask, &old_mask); #endif OSRM routing_machine(server_paths); Server * s = ServerFactory::CreateServer( ip_address, ip_port, requested_num_threads ); s->GetRequestHandlerPtr().RegisterRoutingMachine(&routing_machine); boost::thread t(boost::bind(&Server::Run, s)); #ifndef _WIN32 sigset_t wait_mask; pthread_sigmask(SIG_SETMASK, &old_mask, 0); sigemptyset(&wait_mask); sigaddset(&wait_mask, SIGINT); sigaddset(&wait_mask, SIGQUIT); sigaddset(&wait_mask, SIGTERM); pthread_sigmask(SIG_BLOCK, &wait_mask, 0); std::cout << "[server] running and waiting for requests" << std::endl; sigwait(&wait_mask, &sig); #else // Set console control handler to allow server to be stopped. console_ctrl_function = boost::bind(&Server::Stop, s); SetConsoleCtrlHandler(console_ctrl_handler, TRUE); std::cout << "[server] running and waiting for requests" << std::endl; s->Run(); #endif std::cout << "[server] initiating shutdown" << std::endl; s->Stop(); std::cout << "[server] stopping threads" << std::endl; if(!t.timed_join(boost::posix_time::seconds(2))) { SimpleLogger().Write(logDEBUG) << "Threads did not finish within 2 seconds. Hard abort!"; } std::cout << "[server] freeing objects" << std::endl; delete s; std::cout << "[server] shutdown completed" << std::endl; } catch (std::exception& e) { std::cerr << "[fatal error] exception: " << e.what() << std::endl; } #ifdef __linux__ munlockall(); #endif return 0; }
/* Copyright (c) 2013, Project OSRM, Dennis Luxen, others 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. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include "Library/OSRM.h" #include "Server/ServerFactory.h" #include "Util/GitDescription.h" #include "Util/InputFileUtil.h" #include "Util/OpenMPWrapper.h" #include "Util/ProgramOptions.h" #include "Util/SimpleLogger.h" #include "Util/UUID.h" #ifdef __linux__ #include "Util/LinuxStackTrace.h" #include <sys/mman.h> #endif #include <signal.h> #include <boost/bind.hpp> #include <boost/date_time.hpp> #include <boost/thread.hpp> #include <iostream> #ifdef _WIN32 boost::function0<void> console_ctrl_function; BOOL WINAPI console_ctrl_handler(DWORD ctrl_type) { switch (ctrl_type) { case CTRL_C_EVENT: case CTRL_BREAK_EVENT: case CTRL_CLOSE_EVENT: case CTRL_SHUTDOWN_EVENT: console_ctrl_function(); return TRUE; default: return FALSE; } } #endif int main (int argc, const char * argv[]) { try { LogPolicy::GetInstance().Unmute(); #ifdef __linux__ if( -1 == mlockall(MCL_CURRENT | MCL_FUTURE) ) { SimpleLogger().Write(logWARNING) << "Process " << argv[0] << " could not be locked to RAM"; } installCrashHandler(argv[0]); #endif std::string ip_address; int ip_port, requested_num_threads; ServerPaths server_paths; if( !GenerateServerProgramOptions( argc, argv, server_paths, ip_address, ip_port, requested_num_threads ) ) { return 0; } SimpleLogger().Write() << "starting up engines, " << g_GIT_DESCRIPTION << ", " << "compiled at " << __DATE__ << ", " __TIME__; SimpleLogger().Write() << "HSGR file:\t" << server_paths["hsgrdata"]; SimpleLogger().Write() << "Nodes file:\t" << server_paths["nodesdata"]; SimpleLogger().Write() << "Edges file:\t" << server_paths["edgesdata"]; SimpleLogger().Write() << "RAM file:\t" << server_paths["ramindex"]; SimpleLogger().Write() << "Index file:\t" << server_paths["fileindex"]; SimpleLogger().Write() << "Names file:\t" << server_paths["namesdata"]; SimpleLogger().Write() << "Timestamp file:\t" << server_paths["timestamp"]; SimpleLogger().Write() << "Threads:\t" << requested_num_threads; SimpleLogger().Write() << "IP address:\t" << ip_address; SimpleLogger().Write() << "IP port:\t" << ip_port; #ifndef _WIN32 int sig = 0; sigset_t new_mask; sigset_t old_mask; sigfillset(&new_mask); pthread_sigmask(SIG_BLOCK, &new_mask, &old_mask); #endif OSRM routing_machine(server_paths); Server * s = ServerFactory::CreateServer( ip_address, ip_port, requested_num_threads ); s->GetRequestHandlerPtr().RegisterRoutingMachine(&routing_machine); boost::thread t(boost::bind(&Server::Run, s)); #ifndef _WIN32 sigset_t wait_mask; pthread_sigmask(SIG_SETMASK, &old_mask, 0); sigemptyset(&wait_mask); sigaddset(&wait_mask, SIGINT); sigaddset(&wait_mask, SIGQUIT); sigaddset(&wait_mask, SIGTERM); pthread_sigmask(SIG_BLOCK, &wait_mask, 0); std::cout << "[server] running and waiting for requests" << std::endl; sigwait(&wait_mask, &sig); #else // Set console control handler to allow server to be stopped. console_ctrl_function = boost::bind(&Server::Stop, s); SetConsoleCtrlHandler(console_ctrl_handler, TRUE); std::cout << "[server] running and waiting for requests" << std::endl; s->Run(); #endif std::cout << "[server] initiating shutdown" << std::endl; s->Stop(); std::cout << "[server] stopping threads" << std::endl; if(!t.timed_join(boost::posix_time::seconds(2))) { SimpleLogger().Write(logDEBUG) << "Threads did not finish within 2 seconds. Hard abort!"; } std::cout << "[server] freeing objects" << std::endl; delete s; std::cout << "[server] shutdown completed" << std::endl; } catch (std::exception& e) { std::cerr << "[fatal error] exception: " << e.what() << std::endl; } #ifdef __linux__ munlockall(); #endif return 0; }
fix issue #761
fix issue #761
C++
bsd-2-clause
deniskoronchik/osrm-backend,stevevance/Project-OSRM,arnekaiser/osrm-backend,deniskoronchik/osrm-backend,skyborla/osrm-backend,bjtaylor1/Project-OSRM-Old,antoinegiret/osrm-geovelo,jpizarrom/osrm-backend,antoinegiret/osrm-backend,jpizarrom/osrm-backend,atsuyim/osrm-backend,prembasumatary/osrm-backend,felixguendling/osrm-backend,beemogmbh/osrm-backend,oxidase/osrm-backend,bjtaylor1/osrm-backend,raymond0/osrm-backend,Project-OSRM/osrm-backend,beemogmbh/osrm-backend,raymond0/osrm-backend,Conggge/osrm-backend,Tristramg/osrm-backend,ramyaragupathy/osrm-backend,neilbu/osrm-backend,tkhaxton/osrm-backend,prembasumatary/osrm-backend,ammeurer/osrm-backend,ramyaragupathy/osrm-backend,raymond0/osrm-backend,bjtaylor1/Project-OSRM-Old,ramyaragupathy/osrm-backend,neilbu/osrm-backend,ammeurer/osrm-backend,atsuyim/osrm-backend,ammeurer/osrm-backend,bjtaylor1/Project-OSRM-Old,raymond0/osrm-backend,tkhaxton/osrm-backend,skyborla/osrm-backend,bjtaylor1/osrm-backend,beemogmbh/osrm-backend,bitsteller/osrm-backend,neilbu/osrm-backend,jpizarrom/osrm-backend,stevevance/Project-OSRM,beemogmbh/osrm-backend,yuryleb/osrm-backend,oxidase/osrm-backend,hydrays/osrm-backend,stevevance/Project-OSRM,antoinegiret/osrm-backend,Carsten64/OSRM-aux-git,bjtaylor1/osrm-backend,frodrigo/osrm-backend,alex85k/Project-OSRM,Carsten64/OSRM-aux-git,frodrigo/osrm-backend,nagyistoce/osrm-backend,hydrays/osrm-backend,hydrays/osrm-backend,frodrigo/osrm-backend,chaupow/osrm-backend,agruss/osrm-backend,bitsteller/osrm-backend,duizendnegen/osrm-backend,Conggge/osrm-backend,hydrays/osrm-backend,prembasumatary/osrm-backend,oxidase/osrm-backend,arnekaiser/osrm-backend,ammeurer/osrm-backend,Tristramg/osrm-backend,Project-OSRM/osrm-backend,KnockSoftware/osrm-backend,yuryleb/osrm-backend,duizendnegen/osrm-backend,duizendnegen/osrm-backend,KnockSoftware/osrm-backend,stevevance/Project-OSRM,bjtaylor1/Project-OSRM-Old,frodrigo/osrm-backend,KnockSoftware/osrm-backend,oxidase/osrm-backend,tkhaxton/osrm-backend,Conggge/osrm-backend,ammeurer/osrm-backend,skyborla/osrm-backend,Carsten64/OSRM-aux-git,felixguendling/osrm-backend,antoinegiret/osrm-geovelo,alex85k/Project-OSRM,KnockSoftware/osrm-backend,atsuyim/osrm-backend,Project-OSRM/osrm-backend,bitsteller/osrm-backend,Tristramg/osrm-backend,Conggge/osrm-backend,duizendnegen/osrm-backend,antoinegiret/osrm-geovelo,Carsten64/OSRM-aux-git,chaupow/osrm-backend,yuryleb/osrm-backend,agruss/osrm-backend,nagyistoce/osrm-backend,yuryleb/osrm-backend,antoinegiret/osrm-backend,ammeurer/osrm-backend,bjtaylor1/osrm-backend,felixguendling/osrm-backend,ammeurer/osrm-backend,deniskoronchik/osrm-backend,arnekaiser/osrm-backend,deniskoronchik/osrm-backend,agruss/osrm-backend,alex85k/Project-OSRM,chaupow/osrm-backend,Project-OSRM/osrm-backend,arnekaiser/osrm-backend,neilbu/osrm-backend,nagyistoce/osrm-backend
3ecf949148ae469e7333f7a796128e7a44c10aa4
src/multimedia/qmetadatacontrolmetaobject.cpp
src/multimedia/qmetadatacontrolmetaobject.cpp
/**************************************************************************** ** ** Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies). ** All rights reserved. ** Contact: Nokia Corporation ([email protected]) ** ** This file is part of the Qt Mobility Components. ** ** $QT_BEGIN_LICENSE:LGPL$ ** No Commercial Usage ** This file contains pre-release code and may not be distributed. ** You may use this file in accordance with the terms and conditions ** contained in the Technology Preview License Agreement accompanying ** this package. ** ** GNU Lesser General Public License Usage ** Alternatively, this file may be used under the terms of the GNU Lesser ** General Public License version 2.1 as published by the Free Software ** Foundation and appearing in the file LICENSE.LGPL included in the ** packaging of this file. Please review the following information to ** ensure the GNU Lesser General Public License version 2.1 requirements ** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. ** ** In addition, as a special exception, Nokia gives you certain additional ** rights. These rights are described in the Nokia Qt LGPL Exception ** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. ** ** If you have questions regarding the use of this file, please contact ** Nokia at [email protected]. ** ** ** ** ** ** ** ** ** $QT_END_LICENSE$ ** ****************************************************************************/ #include "qmetadatacontrolmetaobject_p.h" #include "qmetadatacontrol.h" QTM_BEGIN_NAMESPACE namespace { struct MetaDataKey { QtMedia::MetaData key; const char *name; }; const MetaDataKey qt_metaDataKeys[] = { { QtMedia::Title, "title" }, { QtMedia::SubTitle, "subTitle" }, { QtMedia::Author, "author" }, { QtMedia::Comment, "comment" }, { QtMedia::Description, "description" }, { QtMedia::Category, "category" }, { QtMedia::Genre, "genre" }, { QtMedia::Year, "year" }, { QtMedia::Date, "date" }, { QtMedia::UserRating, "userRating" }, { QtMedia::Keywords, "keywords" }, { QtMedia::Language, "language" }, { QtMedia::Publisher, "publisher" }, { QtMedia::Copyright, "copyright" }, { QtMedia::ParentalRating, "parentalRating" }, { QtMedia::RatingOrganisation, "ratingOrganisation" }, // Media { QtMedia::Size, "size" }, { QtMedia::MediaType, "mediaType" }, { QtMedia::Duration, "duration" }, // Audio { QtMedia::AudioBitrate, "audioBitRate" }, { QtMedia::AudioCodec, "audioCodec" }, { QtMedia::AverageLevel, "averageLevel" }, { QtMedia::Channels, "channelCount" }, { QtMedia::PeakValue, "peakValue" }, { QtMedia::Frequency, "frequency" }, // Music { QtMedia::AlbumTitle, "albumTitle" }, { QtMedia::AlbumArtist, "albumArtist" }, { QtMedia::ContributingArtist, "contributingArtist" }, { QtMedia::Composer, "composer" }, { QtMedia::Conductor, "conductor" }, { QtMedia::Lyrics, "lyrics" }, { QtMedia::Mood, "mood" }, { QtMedia::TrackNumber, "trackNumber" }, { QtMedia::TrackCount, "trackCount" }, { QtMedia::CoverArtUriSmall, "coverArtUriSmall" }, { QtMedia::CoverArtUriLarge, "coverArtUriLarge" }, // Image/Video { QtMedia::Resolution, "resolution" }, { QtMedia::PixelAspectRatio, "pixelAspectRatio" }, // Video { QtMedia::VideoFrameRate, "videoFrameRate" }, { QtMedia::VideoBitRate, "videoBitRate" }, { QtMedia::VideoCodec, "videoCodec" }, { QtMedia::PosterUri, "posterUri" }, // Movie { QtMedia::ChapterNumber, "chapterNumber" }, { QtMedia::Director, "director" }, { QtMedia::LeadPerformer, "leadPerformer" }, { QtMedia::Writer, "writer" }, // Photos { QtMedia::CameraManufacturer, "cameraManufacturer" }, { QtMedia::CameraModel, "cameraModel" }, { QtMedia::Event, "event" }, { QtMedia::Subject, "subject" }, { QtMedia::Orientation, "orientation" }, { QtMedia::ExposureTime, "exposureTime" }, { QtMedia::FNumber, "fNumber" }, { QtMedia::ExposureProgram, "exposureProgram" }, { QtMedia::ISOSpeedRatings, "isoSpeedRatings" }, { QtMedia::ExposureBiasValue, "exposureBiasValue" }, { QtMedia::DateTimeOriginal, "dateTimeOriginal" }, { QtMedia::DateTimeDigitized, "dateTimeDigitized" }, { QtMedia::SubjectDistance, "subjectDistance" }, { QtMedia::MeteringMode, "meteringMode" }, { QtMedia::LightSource, "lightSource" }, { QtMedia::Flash, "flash" }, { QtMedia::FocalLength, "focalLength" }, { QtMedia::ExposureMode, "exposureMode" }, { QtMedia::WhiteBalance, "whiteBalance" }, { QtMedia::DigitalZoomRatio, "digitalZoomRatio" }, { QtMedia::FocalLengthIn35mmFilm, "focalLengthIn35mmFilm" }, { QtMedia::SceneCaptureType, "sceneCaptureType" }, { QtMedia::GainControl, "gainControl" }, { QtMedia::Contrast, "contrast" }, { QtMedia::Saturation, "saturation" }, { QtMedia::Sharpness, "sharpness" }, { QtMedia::DeviceSettingDescription, "deviceSettingDescription" } }; } QMetaDataControlMetaObject::QMetaDataControlMetaObject(QMetaDataControl *control, QObject *object) : m_control(control) , m_object(object) , m_mem(0) , m_propertyOffset(0) , m_signalOffset(0) { m_builder.setSuperClass(m_object->metaObject()); m_builder.setClassName(m_object->metaObject()->className()); m_builder.setFlags(QMetaObjectBuilder::DynamicMetaObject); QObjectPrivate *op = QObjectPrivate::get(m_object); if (op->metaObject) m_builder.setSuperClass(op->metaObject); m_mem = m_builder.toMetaObject(); *static_cast<QMetaObject *>(this) = *m_mem; op->metaObject = this; m_propertyOffset = propertyOffset(); m_signalOffset = methodOffset(); } QMetaDataControlMetaObject::~QMetaDataControlMetaObject() { qFree(m_mem); QObjectPrivate *op = QObjectPrivate::get(m_object); op->metaObject = 0; } int QMetaDataControlMetaObject::metaCall(QMetaObject::Call c, int id, void **a) { if (c == QMetaObject::ReadProperty && id >= m_propertyOffset) { int propId = id - m_propertyOffset; *reinterpret_cast<QVariant *>(a[0]) = m_control->metaData(m_keys.at(propId)); return -1; } else if (c == QMetaObject::WriteProperty && id >= m_propertyOffset) { int propId = id - m_propertyOffset; m_control->setMetaData(m_keys.at(propId), *reinterpret_cast<QVariant *>(a[0])); activate(m_object, m_signalOffset + propId, 0); return -1; } else { return m_object->qt_metacall(c, id, a); } } int QMetaDataControlMetaObject::createProperty(const char *name, const char *) { const int count = sizeof(qt_metaDataKeys) / sizeof(MetaDataKey); for (int i = 0; i < count; ++i) { if (qstrcmp(name, qt_metaDataKeys[i].name) == 0) { int id = m_keys.count(); m_keys.append(qt_metaDataKeys[i].key); m_builder.addSignal("__" + QByteArray::number(id) + "()"); QMetaPropertyBuilder build = m_builder.addProperty(name, "QVariant", id); build.setDynamic(true); qFree(m_mem); m_mem = m_builder.toMetaObject(); *static_cast<QMetaObject *>(this) = *m_mem; return m_propertyOffset + id; } } return -1; } void QMetaDataControlMetaObject::metaDataChanged() { if (m_keys.count() >= 1) activate(m_object, m_signalOffset, m_signalOffset + m_keys.count() - 1, 0); } QTM_END_NAMESPACE
/**************************************************************************** ** ** Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies). ** All rights reserved. ** Contact: Nokia Corporation ([email protected]) ** ** This file is part of the Qt Mobility Components. ** ** $QT_BEGIN_LICENSE:LGPL$ ** No Commercial Usage ** This file contains pre-release code and may not be distributed. ** You may use this file in accordance with the terms and conditions ** contained in the Technology Preview License Agreement accompanying ** this package. ** ** GNU Lesser General Public License Usage ** Alternatively, this file may be used under the terms of the GNU Lesser ** General Public License version 2.1 as published by the Free Software ** Foundation and appearing in the file LICENSE.LGPL included in the ** packaging of this file. Please review the following information to ** ensure the GNU Lesser General Public License version 2.1 requirements ** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. ** ** In addition, as a special exception, Nokia gives you certain additional ** rights. These rights are described in the Nokia Qt LGPL Exception ** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. ** ** If you have questions regarding the use of this file, please contact ** Nokia at [email protected]. ** ** ** ** ** ** ** ** ** $QT_END_LICENSE$ ** ****************************************************************************/ #include "qmetadatacontrolmetaobject_p.h" #include "qmetadatacontrol.h" QTM_BEGIN_NAMESPACE namespace { struct MetaDataKey { QtMedia::MetaData key; const char *name; }; const MetaDataKey qt_metaDataKeys[] = { { QtMedia::Title, "title" }, { QtMedia::SubTitle, "subTitle" }, { QtMedia::Author, "author" }, { QtMedia::Comment, "comment" }, { QtMedia::Description, "description" }, { QtMedia::Category, "category" }, { QtMedia::Genre, "genre" }, { QtMedia::Year, "year" }, { QtMedia::Date, "date" }, { QtMedia::UserRating, "userRating" }, { QtMedia::Keywords, "keywords" }, { QtMedia::Language, "language" }, { QtMedia::Publisher, "publisher" }, { QtMedia::Copyright, "copyright" }, { QtMedia::ParentalRating, "parentalRating" }, { QtMedia::RatingOrganisation, "ratingOrganisation" }, // Media { QtMedia::Size, "size" }, { QtMedia::MediaType, "mediaType" }, { QtMedia::Duration, "duration" }, // Audio { QtMedia::AudioBitRate, "audioBitRate" }, { QtMedia::AudioCodec, "audioCodec" }, { QtMedia::AverageLevel, "averageLevel" }, { QtMedia::ChannelCount, "channelCount" }, { QtMedia::PeakValue, "peakValue" }, { QtMedia::Frequency, "frequency" }, // Music { QtMedia::AlbumTitle, "albumTitle" }, { QtMedia::AlbumArtist, "albumArtist" }, { QtMedia::ContributingArtist, "contributingArtist" }, { QtMedia::Composer, "composer" }, { QtMedia::Conductor, "conductor" }, { QtMedia::Lyrics, "lyrics" }, { QtMedia::Mood, "mood" }, { QtMedia::TrackNumber, "trackNumber" }, { QtMedia::TrackCount, "trackCount" }, { QtMedia::CoverArtUriSmall, "coverArtUriSmall" }, { QtMedia::CoverArtUriLarge, "coverArtUriLarge" }, // Image/Video { QtMedia::Resolution, "resolution" }, { QtMedia::PixelAspectRatio, "pixelAspectRatio" }, // Video { QtMedia::VideoFrameRate, "videoFrameRate" }, { QtMedia::VideoBitRate, "videoBitRate" }, { QtMedia::VideoCodec, "videoCodec" }, { QtMedia::PosterUri, "posterUri" }, // Movie { QtMedia::ChapterNumber, "chapterNumber" }, { QtMedia::Director, "director" }, { QtMedia::LeadPerformer, "leadPerformer" }, { QtMedia::Writer, "writer" }, // Photos { QtMedia::CameraManufacturer, "cameraManufacturer" }, { QtMedia::CameraModel, "cameraModel" }, { QtMedia::Event, "event" }, { QtMedia::Subject, "subject" }, { QtMedia::Orientation, "orientation" }, { QtMedia::ExposureTime, "exposureTime" }, { QtMedia::FNumber, "fNumber" }, { QtMedia::ExposureProgram, "exposureProgram" }, { QtMedia::ISOSpeedRatings, "isoSpeedRatings" }, { QtMedia::ExposureBiasValue, "exposureBiasValue" }, { QtMedia::DateTimeOriginal, "dateTimeOriginal" }, { QtMedia::DateTimeDigitized, "dateTimeDigitized" }, { QtMedia::SubjectDistance, "subjectDistance" }, { QtMedia::MeteringMode, "meteringMode" }, { QtMedia::LightSource, "lightSource" }, { QtMedia::Flash, "flash" }, { QtMedia::FocalLength, "focalLength" }, { QtMedia::ExposureMode, "exposureMode" }, { QtMedia::WhiteBalance, "whiteBalance" }, { QtMedia::DigitalZoomRatio, "digitalZoomRatio" }, { QtMedia::FocalLengthIn35mmFilm, "focalLengthIn35mmFilm" }, { QtMedia::SceneCaptureType, "sceneCaptureType" }, { QtMedia::GainControl, "gainControl" }, { QtMedia::Contrast, "contrast" }, { QtMedia::Saturation, "saturation" }, { QtMedia::Sharpness, "sharpness" }, { QtMedia::DeviceSettingDescription, "deviceSettingDescription" } }; } QMetaDataControlMetaObject::QMetaDataControlMetaObject(QMetaDataControl *control, QObject *object) : m_control(control) , m_object(object) , m_mem(0) , m_propertyOffset(0) , m_signalOffset(0) { m_builder.setSuperClass(m_object->metaObject()); m_builder.setClassName(m_object->metaObject()->className()); m_builder.setFlags(QMetaObjectBuilder::DynamicMetaObject); QObjectPrivate *op = QObjectPrivate::get(m_object); if (op->metaObject) m_builder.setSuperClass(op->metaObject); m_mem = m_builder.toMetaObject(); *static_cast<QMetaObject *>(this) = *m_mem; op->metaObject = this; m_propertyOffset = propertyOffset(); m_signalOffset = methodOffset(); } QMetaDataControlMetaObject::~QMetaDataControlMetaObject() { qFree(m_mem); QObjectPrivate *op = QObjectPrivate::get(m_object); op->metaObject = 0; } int QMetaDataControlMetaObject::metaCall(QMetaObject::Call c, int id, void **a) { if (c == QMetaObject::ReadProperty && id >= m_propertyOffset) { int propId = id - m_propertyOffset; *reinterpret_cast<QVariant *>(a[0]) = m_control->metaData(m_keys.at(propId)); return -1; } else if (c == QMetaObject::WriteProperty && id >= m_propertyOffset) { int propId = id - m_propertyOffset; m_control->setMetaData(m_keys.at(propId), *reinterpret_cast<QVariant *>(a[0])); activate(m_object, m_signalOffset + propId, 0); return -1; } else { return m_object->qt_metacall(c, id, a); } } int QMetaDataControlMetaObject::createProperty(const char *name, const char *) { const int count = sizeof(qt_metaDataKeys) / sizeof(MetaDataKey); for (int i = 0; i < count; ++i) { if (qstrcmp(name, qt_metaDataKeys[i].name) == 0) { int id = m_keys.count(); m_keys.append(qt_metaDataKeys[i].key); m_builder.addSignal("__" + QByteArray::number(id) + "()"); QMetaPropertyBuilder build = m_builder.addProperty(name, "QVariant", id); build.setDynamic(true); qFree(m_mem); m_mem = m_builder.toMetaObject(); *static_cast<QMetaObject *>(this) = *m_mem; return m_propertyOffset + id; } } return -1; } void QMetaDataControlMetaObject::metaDataChanged() { if (m_keys.count() >= 1) activate(m_object, m_signalOffset, m_signalOffset + m_keys.count() - 1, 0); } QTM_END_NAMESPACE
Correct renamed enum values.
Correct renamed enum values.
C++
lgpl-2.1
kaltsi/qt-mobility,tmcguire/qt-mobility,tmcguire/qt-mobility,enthought/qt-mobility,tmcguire/qt-mobility,kaltsi/qt-mobility,tmcguire/qt-mobility,enthought/qt-mobility,qtproject/qt-mobility,enthought/qt-mobility,KDE/android-qt-mobility,kaltsi/qt-mobility,tmcguire/qt-mobility,enthought/qt-mobility,qtproject/qt-mobility,kaltsi/qt-mobility,qtproject/qt-mobility,enthought/qt-mobility,KDE/android-qt-mobility,qtproject/qt-mobility,kaltsi/qt-mobility,qtproject/qt-mobility,KDE/android-qt-mobility,enthought/qt-mobility,KDE/android-qt-mobility,qtproject/qt-mobility,kaltsi/qt-mobility
14325fd35d6056415e35d4f3c00b0a94474e0426
regen_dump.cc
regen_dump.cc
// Copyright 2016 Google Inc. All rights reserved // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // +build ignore // This command will dump the contents of a kati stamp file into a more portable // format for use by other tools. For now, it just exports the files read. // Later, this will be expanded to include the Glob and Shell commands, but // those require a more complicated output format. #include <stdio.h> #include <string> #include "io.h" #include "log.h" #include "strutil.h" int main(int argc, char* argv[]) { bool dump_files = false; bool dump_env = false; if (argc == 1) { fprintf(stderr, "Usage: ckati_stamp_dump [--env] [--files] <stamp>\n"); return 1; } for (int i = 1; i < argc - 1; i++) { const char* arg = argv[i]; if (!strcmp(arg, "--env")) { dump_env = true; } else if (!strcmp(arg, "--files")) { dump_files = true; } else { fprintf(stderr, "Unknown option: %s", arg); return 1; } } if (!dump_files && !dump_env) { dump_files = true; } FILE* fp = fopen(argv[argc - 1], "rb"); if (!fp) PERROR("fopen"); ScopedFile sfp(fp); double gen_time; size_t r = fread(&gen_time, sizeof(gen_time), 1, fp); if (r != 1) ERROR("Incomplete stamp file"); int num_files = LoadInt(fp); if (num_files < 0) ERROR("Incomplete stamp file"); for (int i = 0; i < num_files; i++) { string s; if (!LoadString(fp, &s)) ERROR("Incomplete stamp file"); if (dump_files) printf("%s\n", s.c_str()); } int num_undefineds = LoadInt(fp); if (num_undefineds < 0) ERROR("Incomplete stamp file"); for (int i = 0; i < num_undefineds; i++) { string s; if (!LoadString(fp, &s)) ERROR("Incomplete stamp file"); if (dump_env) printf("undefined: %s\n", s.c_str()); } int num_envs = LoadInt(fp); if (num_envs < 0) ERROR("Incomplete stamp file"); for (int i = 0; i < num_envs; i++) { string name; string val; if (!LoadString(fp, &name)) ERROR("Incomplete stamp file"); if (!LoadString(fp, &val)) ERROR("Incomplete stamp file"); if (dump_env) printf("%s: %s\n", name.c_str(), val.c_str()); } return 0; }
// Copyright 2016 Google Inc. All rights reserved // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // +build ignore // This command will dump the contents of a kati stamp file into a more portable // format for use by other tools. For now, it just exports the files read. // Later, this will be expanded to include the Glob and Shell commands, but // those require a more complicated output format. #include <stdio.h> #include <string> #include <vector> #include "func.h" #include "io.h" #include "log.h" #include "strutil.h" vector<string> LoadVecString(FILE* fp) { int count = LoadInt(fp); if (count < 0) { ERROR("Incomplete stamp file"); } vector<string> ret(count); for (int i = 0; i < count; i++) { if (!LoadString(fp, &ret[i])) { ERROR("Incomplete stamp file"); } } return ret; } int main(int argc, char* argv[]) { bool dump_files = false; bool dump_env = false; bool dump_globs = false; bool dump_cmds = false; bool dump_finds = false; if (argc == 1) { fprintf(stderr, "Usage: ckati_stamp_dump [--env] [--files] [--globs] [--cmds] " "[--finds] <stamp>\n"); return 1; } for (int i = 1; i < argc - 1; i++) { const char* arg = argv[i]; if (!strcmp(arg, "--env")) { dump_env = true; } else if (!strcmp(arg, "--files")) { dump_files = true; } else if (!strcmp(arg, "--globs")) { dump_globs = true; } else if (!strcmp(arg, "--cmds")) { dump_cmds = true; } else if (!strcmp(arg, "--finds")) { dump_finds = true; } else { fprintf(stderr, "Unknown option: %s", arg); return 1; } } if (!dump_files && !dump_env && !dump_globs && !dump_cmds && !dump_finds) { dump_files = true; } FILE* fp = fopen(argv[argc - 1], "rb"); if (!fp) PERROR("fopen"); ScopedFile sfp(fp); double gen_time; size_t r = fread(&gen_time, sizeof(gen_time), 1, fp); if (r != 1) ERROR("Incomplete stamp file"); // // See regen.cc CheckStep1 for how this is read normally // { auto files = LoadVecString(fp); if (dump_files) { for (auto f : files) { printf("%s\n", f.c_str()); } } } { auto undefined = LoadVecString(fp); if (dump_env) { for (auto s : undefined) { printf("undefined: %s\n", s.c_str()); } } } int num_envs = LoadInt(fp); if (num_envs < 0) ERROR("Incomplete stamp file"); for (int i = 0; i < num_envs; i++) { string name; string val; if (!LoadString(fp, &name)) ERROR("Incomplete stamp file"); if (!LoadString(fp, &val)) ERROR("Incomplete stamp file"); if (dump_env) printf("%s: %s\n", name.c_str(), val.c_str()); } int num_globs = LoadInt(fp); if (num_globs < 0) ERROR("Incomplete stamp file"); for (int i = 0; i < num_globs; i++) { string pat; if (!LoadString(fp, &pat)) ERROR("Incomplete stamp file"); auto files = LoadVecString(fp); if (dump_globs) { printf("%s\n", pat.c_str()); for (auto s : files) { printf(" %s\n", s.c_str()); } } } int num_cmds = LoadInt(fp); if (num_cmds < 0) ERROR("Incomplete stamp file"); for (int i = 0; i < num_cmds; i++) { CommandOp op = static_cast<CommandOp>(LoadInt(fp)); string shell, shellflag, cmd, result; if (!LoadString(fp, &shell)) ERROR("Incomplete stamp file"); if (!LoadString(fp, &shellflag)) ERROR("Incomplete stamp file"); if (!LoadString(fp, &cmd)) ERROR("Incomplete stamp file"); if (!LoadString(fp, &result)) ERROR("Incomplete stamp file"); if (op == CommandOp::FIND) { auto missing_dirs = LoadVecString(fp); auto files = LoadVecString(fp); auto read_dirs = LoadVecString(fp); if (dump_finds) { printf("cmd type: FIND\n"); printf(" shell: %s\n", shell.c_str()); printf(" shell flags: %s\n", shellflag.c_str()); printf(" cmd: %s\n", cmd.c_str()); if (result.length() > 0 && result.length() < 500 && result.find('\n') == std::string::npos) { printf(" output: %s\n", result.c_str()); } else { printf(" output: <%zu bytes>\n", result.length()); } printf(" missing dirs:\n"); for (auto d : missing_dirs) { printf(" %s\n", d.c_str()); } printf(" files:\n"); for (auto f : files) { printf(" %s\n", f.c_str()); } printf(" read dirs:\n"); for (auto d : read_dirs) { printf(" %s\n", d.c_str()); } printf("\n"); } } else if (dump_cmds) { if (op == CommandOp::SHELL) { printf("cmd type: SHELL\n"); printf(" shell: %s\n", shell.c_str()); printf(" shell flags: %s\n", shellflag.c_str()); } else if (op == CommandOp::READ) { printf("cmd type: READ\n"); } else if (op == CommandOp::READ_MISSING) { printf("cmd type: READ_MISSING\n"); } else if (op == CommandOp::WRITE) { printf("cmd type: WRITE\n"); } else if (op == CommandOp::APPEND) { printf("cmd type: APPEND\n"); } printf(" cmd: %s\n", cmd.c_str()); if (result.length() > 0 && result.length() < 500 && result.find('\n') == std::string::npos) { printf(" output: %s\n", result.c_str()); } else { printf(" output: <%zu bytes>\n", result.length()); } printf("\n"); } } return 0; }
Improve ckati_stamp_dump
Improve ckati_stamp_dump Support dumping out globs, shell commands, and emulated find commands to improve debugging and analysis of regen stamp files. Change-Id: I80c09a07d2c468d03d416dfa6b1cebce5d5a3fcd
C++
apache-2.0
danw/kati,google/kati,danw/kati,danw/kati,danw/kati,google/kati,danw/kati,google/kati,google/kati,google/kati,danw/kati
c6e2d8a2ffc04084dcf4a96e56aca155856aed92
lib/Analysis/CFGPrinter.cpp
lib/Analysis/CFGPrinter.cpp
//===- CFGPrinter.cpp - DOT printer for the control flow graph ------------===// // // The LLVM Compiler Infrastructure // // This file was developed by the LLVM research group and is distributed under // the University of Illinois Open Source License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // This file defines a '-print-cfg' analysis pass, which emits the // cfg.<fnname>.dot file for each function in the program, with a graph of the // CFG for that function. // // The other main feature of this file is that it implements the // Function::viewCFG method, which is useful for debugging passes which operate // on the CFG. // //===----------------------------------------------------------------------===// #include "Support/GraphWriter.h" #include "llvm/Pass.h" #include "llvm/Function.h" #include "llvm/iTerminators.h" #include "llvm/Assembly/Writer.h" #include "llvm/Support/CFG.h" #include <sstream> #include <fstream> using namespace llvm; /// CFGOnly flag - This is used to control whether or not the CFG graph printer /// prints out the contents of basic blocks or not. This is acceptable because /// this code is only really used for debugging purposes. /// static bool CFGOnly = false; namespace llvm { template<> struct DOTGraphTraits<const Function*> : public DefaultDOTGraphTraits { static std::string getGraphName(const Function *F) { return "CFG for '" + F->getName() + "' function"; } static std::string getNodeLabel(const BasicBlock *Node, const Function *Graph) { if (CFGOnly && !Node->getName().empty()) return Node->getName() + ":"; std::ostringstream Out; if (CFGOnly) { WriteAsOperand(Out, Node, false, true); return Out.str(); } if (Node->getName().empty()) { WriteAsOperand(Out, Node, false, true); Out << ":"; } Out << *Node; std::string OutStr = Out.str(); if (OutStr[0] == '\n') OutStr.erase(OutStr.begin()); // Process string output to make it nicer... for (unsigned i = 0; i != OutStr.length(); ++i) if (OutStr[i] == '\n') { // Left justify OutStr[i] = '\\'; OutStr.insert(OutStr.begin()+i+1, 'l'); } else if (OutStr[i] == ';') { // Delete comments! unsigned Idx = OutStr.find('\n', i+1); // Find end of line OutStr.erase(OutStr.begin()+i, OutStr.begin()+Idx); --i; } return OutStr; } static std::string getNodeAttributes(const BasicBlock *N) { return "fontname=Courier"; } static std::string getEdgeSourceLabel(const BasicBlock *Node, succ_const_iterator I) { // Label source of conditional branches with "T" or "F" if (const BranchInst *BI = dyn_cast<BranchInst>(Node->getTerminator())) if (BI->isConditional()) return (I == succ_begin(Node)) ? "T" : "F"; return ""; } }; } namespace { struct CFGPrinter : public FunctionPass { virtual bool runOnFunction(Function &F) { std::string Filename = "cfg." + F.getName() + ".dot"; std::cerr << "Writing '" << Filename << "'..."; std::ofstream File(Filename.c_str()); if (File.good()) WriteGraph(File, (const Function*)&F); else std::cerr << " error opening file for writing!"; std::cerr << "\n"; return false; } void print(std::ostream &OS) const {} virtual void getAnalysisUsage(AnalysisUsage &AU) const { AU.setPreservesAll(); } }; RegisterAnalysis<CFGPrinter> P1("print-cfg", "Print CFG of function to 'dot' file"); struct CFGOnlyPrinter : public CFGPrinter { virtual bool runOnFunction(Function &F) { bool OldCFGOnly = CFGOnly; CFGOnly = true; CFGPrinter::runOnFunction(F); CFGOnly = OldCFGOnly; return false; } void print(std::ostream &OS) const {} virtual void getAnalysisUsage(AnalysisUsage &AU) const { AU.setPreservesAll(); } }; RegisterAnalysis<CFGOnlyPrinter> P2("print-cfg-only", "Print CFG of function to 'dot' file (with no function bodies)"); } /// viewCFG - This function is meant for use from the debugger. You can just /// say 'call F->viewCFG()' and a ghostview window should pop up from the /// program, displaying the CFG of the current function. This depends on there /// being a 'dot' and 'gv' program in your path. /// void Function::viewCFG() const { std::string Filename = "/tmp/cfg." + getName() + ".dot"; std::cerr << "Writing '" << Filename << "'... "; std::ofstream F(Filename.c_str()); if (!F.good()) { std::cerr << " error opening file for writing!\n"; return; } WriteGraph(F, this); F.close(); std::cerr << "\n"; std::cerr << "Running 'dot' program... " << std::flush; if (system(("dot -Tps " + Filename + " > /tmp/cfg.tempgraph.ps").c_str())) { std::cerr << "Error running dot: 'dot' not in path?\n"; } else { std::cerr << "\n"; system("gv /tmp/cfg.tempgraph.ps"); } system(("rm " + Filename + " /tmp/cfg.tempgraph.ps").c_str()); } /// viewCFGOnly - This function is meant for use from the debugger. It works /// just like viewCFG, but it does not include the contents of basic blocks /// into the nodes, just the label. If you are only interested in the CFG t /// his can make the graph smaller. /// void Function::viewCFGOnly() const { CFGOnly = true; viewCFG(); CFGOnly = false; }
//===- CFGPrinter.cpp - DOT printer for the control flow graph ------------===// // // The LLVM Compiler Infrastructure // // This file was developed by the LLVM research group and is distributed under // the University of Illinois Open Source License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // This file defines a '-print-cfg' analysis pass, which emits the // cfg.<fnname>.dot file for each function in the program, with a graph of the // CFG for that function. // // The other main feature of this file is that it implements the // Function::viewCFG method, which is useful for debugging passes which operate // on the CFG. // //===----------------------------------------------------------------------===// #include "Support/GraphWriter.h" #include "llvm/Pass.h" #include "llvm/Function.h" #include "llvm/iTerminators.h" #include "llvm/Assembly/Writer.h" #include "llvm/Analysis/CFGPrinter.h" #include "llvm/Support/CFG.h" #include <sstream> #include <fstream> using namespace llvm; /// CFGOnly flag - This is used to control whether or not the CFG graph printer /// prints out the contents of basic blocks or not. This is acceptable because /// this code is only really used for debugging purposes. /// static bool CFGOnly = false; namespace llvm { template<> struct DOTGraphTraits<const Function*> : public DefaultDOTGraphTraits { static std::string getGraphName(const Function *F) { return "CFG for '" + F->getName() + "' function"; } static std::string getNodeLabel(const BasicBlock *Node, const Function *Graph) { if (CFGOnly && !Node->getName().empty()) return Node->getName() + ":"; std::ostringstream Out; if (CFGOnly) { WriteAsOperand(Out, Node, false, true); return Out.str(); } if (Node->getName().empty()) { WriteAsOperand(Out, Node, false, true); Out << ":"; } Out << *Node; std::string OutStr = Out.str(); if (OutStr[0] == '\n') OutStr.erase(OutStr.begin()); // Process string output to make it nicer... for (unsigned i = 0; i != OutStr.length(); ++i) if (OutStr[i] == '\n') { // Left justify OutStr[i] = '\\'; OutStr.insert(OutStr.begin()+i+1, 'l'); } else if (OutStr[i] == ';') { // Delete comments! unsigned Idx = OutStr.find('\n', i+1); // Find end of line OutStr.erase(OutStr.begin()+i, OutStr.begin()+Idx); --i; } return OutStr; } static std::string getNodeAttributes(const BasicBlock *N) { return "fontname=Courier"; } static std::string getEdgeSourceLabel(const BasicBlock *Node, succ_const_iterator I) { // Label source of conditional branches with "T" or "F" if (const BranchInst *BI = dyn_cast<BranchInst>(Node->getTerminator())) if (BI->isConditional()) return (I == succ_begin(Node)) ? "T" : "F"; return ""; } }; } namespace { struct CFGPrinter : public FunctionPass { virtual bool runOnFunction(Function &F) { std::string Filename = "cfg." + F.getName() + ".dot"; std::cerr << "Writing '" << Filename << "'..."; std::ofstream File(Filename.c_str()); if (File.good()) WriteGraph(File, (const Function*)&F); else std::cerr << " error opening file for writing!"; std::cerr << "\n"; return false; } void print(std::ostream &OS) const {} virtual void getAnalysisUsage(AnalysisUsage &AU) const { AU.setPreservesAll(); } }; RegisterAnalysis<CFGPrinter> P1("print-cfg", "Print CFG of function to 'dot' file"); struct CFGOnlyPrinter : public CFGPrinter { virtual bool runOnFunction(Function &F) { bool OldCFGOnly = CFGOnly; CFGOnly = true; CFGPrinter::runOnFunction(F); CFGOnly = OldCFGOnly; return false; } void print(std::ostream &OS) const {} virtual void getAnalysisUsage(AnalysisUsage &AU) const { AU.setPreservesAll(); } }; RegisterAnalysis<CFGOnlyPrinter> P2("print-cfg-only", "Print CFG of function to 'dot' file (with no function bodies)"); } /// viewCFG - This function is meant for use from the debugger. You can just /// say 'call F->viewCFG()' and a ghostview window should pop up from the /// program, displaying the CFG of the current function. This depends on there /// being a 'dot' and 'gv' program in your path. /// void Function::viewCFG() const { std::string Filename = "/tmp/cfg." + getName() + ".dot"; std::cerr << "Writing '" << Filename << "'... "; std::ofstream F(Filename.c_str()); if (!F.good()) { std::cerr << " error opening file for writing!\n"; return; } WriteGraph(F, this); F.close(); std::cerr << "\n"; std::cerr << "Running 'dot' program... " << std::flush; if (system(("dot -Tps " + Filename + " > /tmp/cfg.tempgraph.ps").c_str())) { std::cerr << "Error running dot: 'dot' not in path?\n"; } else { std::cerr << "\n"; system("gv /tmp/cfg.tempgraph.ps"); } system(("rm " + Filename + " /tmp/cfg.tempgraph.ps").c_str()); } /// viewCFGOnly - This function is meant for use from the debugger. It works /// just like viewCFG, but it does not include the contents of basic blocks /// into the nodes, just the label. If you are only interested in the CFG t /// his can make the graph smaller. /// void Function::viewCFGOnly() const { CFGOnly = true; viewCFG(); CFGOnly = false; } FunctionPass *llvm::createCFGPrinterPass () { return new CFGPrinter(); } FunctionPass *llvm::createCFGOnlyPrinterPass () { return new CFGOnlyPrinter(); }
Add functions that return instances of these printer passes
Add functions that return instances of these printer passes git-svn-id: 0ff597fd157e6f4fc38580e8d64ab130330d2411@13175 91177308-0d34-0410-b5e6-96231b3b80d8
C++
apache-2.0
apple/swift-llvm,dslab-epfl/asap,GPUOpen-Drivers/llvm,chubbymaggie/asap,GPUOpen-Drivers/llvm,dslab-epfl/asap,GPUOpen-Drivers/llvm,chubbymaggie/asap,apple/swift-llvm,GPUOpen-Drivers/llvm,llvm-mirror/llvm,apple/swift-llvm,apple/swift-llvm,apple/swift-llvm,dslab-epfl/asap,dslab-epfl/asap,chubbymaggie/asap,GPUOpen-Drivers/llvm,llvm-mirror/llvm,chubbymaggie/asap,GPUOpen-Drivers/llvm,apple/swift-llvm,apple/swift-llvm,chubbymaggie/asap,llvm-mirror/llvm,dslab-epfl/asap,llvm-mirror/llvm,llvm-mirror/llvm,GPUOpen-Drivers/llvm,llvm-mirror/llvm,apple/swift-llvm,dslab-epfl/asap,dslab-epfl/asap,llvm-mirror/llvm,llvm-mirror/llvm,GPUOpen-Drivers/llvm,llvm-mirror/llvm,chubbymaggie/asap
be45ae39c4712da0079b26fe856a71c608909db5
sw/source/ui/inc/optpage.hxx
sw/source/ui/inc/optpage.hxx
/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ /************************************************************************* * * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * Copyright 2000, 2010 Oracle and/or its affiliates. * * OpenOffice.org - a multi-platform office productivity suite * * 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 _OPTPAGE_HXX #define _OPTPAGE_HXX #include <sfx2/tabdlg.hxx> #include <vcl/group.hxx> #include <vcl/button.hxx> #include <vcl/lstbox.hxx> #include <vcl/field.hxx> #include <vcl/fixed.hxx> #include <svtools/ctrlbox.hxx> #include <svx/fntctrl.hxx> #include <fontcfg.hxx> class SvStringsDtor; class SfxPrinter; class SwWrtShell; class FontList; class SwContentOptPage : public SfxTabPage { //visual aids FixedLine aLineFL; CheckBox aCrossCB; //view FixedLine aWindowFL; CheckBox aHScrollBox; CheckBox aVScrollBox; CheckBox aAnyRulerCB; CheckBox aHRulerCBox; ListBox aHMetric; CheckBox aVRulerCBox; CheckBox aVRulerRightCBox; ListBox aVMetric; CheckBox aSmoothCBox; //display FixedLine aDispFL; CheckBox aGrfCB; CheckBox aTblCB; CheckBox aDrwCB; CheckBox aFldNameCB; CheckBox aPostItCB; FixedLine aSettingsFL; FixedText aMetricFT; ListBox aMetricLB; DECL_LINK(VertRulerHdl, CheckBox*); DECL_LINK(AnyRulerHdl, CheckBox*); public: SwContentOptPage( Window* pParent, const SfxItemSet& rSet ); ~SwContentOptPage(); static SfxTabPage* Create( Window* pParent, const SfxItemSet& rAttrSet); virtual sal_Bool FillItemSet( SfxItemSet& rSet ); virtual void Reset( const SfxItemSet& rSet ); }; /*-------------------------------------------------------- TabPage printer settings additions --------------------------------------------------------- */ class SwAddPrinterTabPage : public SfxTabPage { FixedLine aFL1; CheckBox aGrfCB; // CheckBox aTabCB; // CheckBox aDrawCB; CheckBox aCtrlFldCB; CheckBox aBackgroundCB; CheckBox aBlackFontCB; CheckBox aPrintHiddenTextCB; CheckBox aPrintTextPlaceholderCB; FixedLine aSeparatorLFL; FixedLine aFL2; CheckBox aLeftPageCB; CheckBox aRightPageCB; // CheckBox aReverseCB; CheckBox aProspectCB; CheckBox aProspectCB_RTL; FixedLine aSeparatorRFL; FixedLine aFL3; RadioButton aNoRB; RadioButton aOnlyRB; RadioButton aEndRB; RadioButton aEndPageRB; FixedLine aFL4; CheckBox aPrintEmptyPagesCB; // CheckBox aSingleJobsCB; CheckBox aPaperFromSetupCB; FixedText aFaxFT; ListBox aFaxLB; String sNone; sal_Bool bAttrModified; sal_Bool bPreview; void Init(); DECL_LINK( AutoClickHdl, CheckBox * ); DECL_LINK( SelectHdl, ListBox * ); SwAddPrinterTabPage( Window* pParent, const SfxItemSet& rSet ); public: static SfxTabPage* Create( Window* pParent, const SfxItemSet& rAttrSet ); virtual sal_Bool FillItemSet( SfxItemSet& rSet ); virtual void Reset( const SfxItemSet& rSet ); void SetFax( const SvStringsDtor& ); void SelectFax( const String& ); void SetPreview(sal_Bool bPrev); virtual void PageCreated (SfxAllItemSet aSet); }; class SwTableOptionsTabPage : public SfxTabPage { FixedLine aTableFL; CheckBox aHeaderCB; CheckBox aRepeatHeaderCB; CheckBox aDontSplitCB; CheckBox aBorderCB; FixedLine aSeparatorFL; FixedLine aTableInsertFL; CheckBox aNumFormattingCB; CheckBox aNumFmtFormattingCB; CheckBox aNumAlignmentCB; FixedLine aMoveFL; FixedText aMoveFT; FixedText aRowMoveFT; MetricField aRowMoveMF; FixedText aColMoveFT; MetricField aColMoveMF; FixedText aInsertFT; FixedText aRowInsertFT; MetricField aRowInsertMF; FixedText aColInsertFT; MetricField aColInsertMF; FixedText aHandlingFT; RadioButton aFixRB; RadioButton aFixPropRB; RadioButton aVarRB; FixedText aFixFT; FixedText aFixPropFT; FixedText aVarFT; SwWrtShell* pWrtShell; sal_Bool bHTMLMode; DECL_LINK(CheckBoxHdl, CheckBox *pCB); SwTableOptionsTabPage( Window* pParent, const SfxItemSet& rSet ); ~SwTableOptionsTabPage(); public: static SfxTabPage* Create( Window* pParent, const SfxItemSet& rAttrSet ); virtual sal_Bool FillItemSet( SfxItemSet& rSet ); virtual void Reset( const SfxItemSet& rSet ); void SetWrtShell(SwWrtShell* pSh) {pWrtShell = pSh;} virtual void PageCreated (SfxAllItemSet aSet); }; /*-------------------------------------------------- TabPage for ShadowCrsr --------------------------------------------------*/ class SwShdwCrsrOptionsTabPage : public SfxTabPage { //nonprinting characters FixedLine aUnprintFL; CheckBox aParaCB; CheckBox aSHyphCB; CheckBox aSpacesCB; CheckBox aHSpacesCB; CheckBox aTabCB; CheckBox aBreakCB; CheckBox aCharHiddenCB; CheckBox aFldHiddenCB; CheckBox aFldHiddenParaCB; FixedLine aSeparatorFL; FixedLine aFlagFL; CheckBox aOnOffCB; FixedText aFillModeFT; RadioButton aFillMarginRB; RadioButton aFillIndentRB; RadioButton aFillTabRB; RadioButton aFillSpaceRB; FixedLine aCrsrOptFL; CheckBox aCrsrInProtCB; FixedLine m_aLayoutOptionsFL; CheckBox m_aMathBaselineAlignmentCB; SwWrtShell * m_pWrtShell; SwShdwCrsrOptionsTabPage( Window* pParent, const SfxItemSet& rSet ); ~SwShdwCrsrOptionsTabPage(); public: static SfxTabPage* Create( Window* pParent, const SfxItemSet& rAttrSet ); virtual sal_Bool FillItemSet( SfxItemSet& rSet ); virtual void Reset( const SfxItemSet& rSet ); void SetWrtShell( SwWrtShell * pSh ) { m_pWrtShell = pSh; } virtual void PageCreated( SfxAllItemSet aSet ); }; /*----------------------------------------------------------------------- Description: mark preview -----------------------------------------------------------------------*/ class SwMarkPreview : public Window { Color m_aBgCol; // background Color m_aTransCol; // transparency Color m_aMarkCol; // marks Color m_aLineCol; // general lines Color m_aShadowCol; // shadow Color m_aTxtCol; // text Color m_aPrintAreaCol; // frame for print area Rectangle aPage; Rectangle aLeftPagePrtArea; Rectangle aRightPagePrtArea; sal_uInt16 nMarkPos; using OutputDevice::DrawRect; void DrawRect(const Rectangle &rRect, const Color &rFillColor, const Color &rLineColor); void Paint(const Rectangle&); void PaintPage(const Rectangle &rRect); void InitColors( void ); protected: virtual void DataChanged( const DataChangedEvent& rDCEvt ); public: SwMarkPreview(Window* pParent, const ResId& rResID); virtual ~SwMarkPreview(); inline void SetColor(const Color& rCol) { m_aMarkCol = rCol; } inline void SetMarkPos(sal_uInt16 nPos) { nMarkPos = nPos; } }; /*----------------------------------------------------------------------- Description: redlining options -----------------------------------------------------------------------*/ class SwRedlineOptionsTabPage : public SfxTabPage { FixedLine aInsertFL; FixedText aInsertFT; FixedText aInsertAttrFT; ListBox aInsertLB; FixedText aInsertColorFT; ColorListBox aInsertColorLB; SvxFontPrevWindow aInsertedPreviewWN; FixedText aDeletedFT; FixedText aDeletedAttrFT; ListBox aDeletedLB; FixedText aDeletedColorFT; ColorListBox aDeletedColorLB; SvxFontPrevWindow aDeletedPreviewWN; FixedText aChangedFT; FixedText aChangedAttrFT; ListBox aChangedLB; FixedText aChangedColorFT; ColorListBox aChangedColorLB; SvxFontPrevWindow aChangedPreviewWN; FixedLine aChangedFL; FixedText aMarkPosFT; ListBox aMarkPosLB; FixedText aMarkColorFT; ColorListBox aMarkColorLB; SwMarkPreview aMarkPreviewWN; String sAuthor; String sNone; SwRedlineOptionsTabPage( Window* pParent, const SfxItemSet& rSet ); ~SwRedlineOptionsTabPage(); DECL_LINK( AttribHdl, ListBox *pLB ); DECL_LINK( ChangedMaskPrevHdl, ListBox *pLB = 0 ); DECL_LINK( ColorHdl, ColorListBox *pColorLB ); void InitFontStyle(SvxFontPrevWindow& rExampleWin); public: static SfxTabPage* Create( Window* pParent, const SfxItemSet& rAttrSet ); virtual sal_Bool FillItemSet( SfxItemSet& rSet ); virtual void Reset( const SfxItemSet& rSet ); }; /*------------------------------------------------------- TabPage test settings for SW --------------------------------------------------------- */ #ifdef DBG_UTIL class SwTestTabPage : public SfxTabPage { public: SwTestTabPage( Window* pParent, const SfxItemSet& rSet ); static SfxTabPage* Create( Window* pParent, const SfxItemSet& rAttrSet ); virtual sal_Bool FillItemSet( SfxItemSet& rSet ); virtual void Reset( const SfxItemSet& rSet ); private: FixedLine aTestFL; CheckBox aTest1CBox; CheckBox aTest2CBox; CheckBox aTest3CBox; CheckBox aTest4CBox; CheckBox aTest5CBox; CheckBox aTest6CBox; CheckBox aTest7CBox; CheckBox aTest8CBox; CheckBox aTest9CBox; CheckBox aTest10CBox; sal_Bool bAttrModified; void Init(); DECL_LINK( AutoClickHdl, CheckBox * ); }; #endif // DBG_UTIL #endif /* vim:set shiftwidth=4 softtabstop=4 expandtab: */
/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ /************************************************************************* * * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * Copyright 2000, 2010 Oracle and/or its affiliates. * * OpenOffice.org - a multi-platform office productivity suite * * 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 _OPTPAGE_HXX #define _OPTPAGE_HXX #include <sfx2/tabdlg.hxx> #include <vcl/group.hxx> #include <vcl/button.hxx> #include <vcl/lstbox.hxx> #include <vcl/field.hxx> #include <vcl/fixed.hxx> #include <svtools/ctrlbox.hxx> #include <svx/fntctrl.hxx> #include <fontcfg.hxx> class SvStringsDtor; class SfxPrinter; class SwWrtShell; class FontList; class SwContentOptPage : public SfxTabPage { //visual aids FixedLine aLineFL; CheckBox aCrossCB; //view FixedLine aWindowFL; CheckBox aHScrollBox; CheckBox aVScrollBox; CheckBox aAnyRulerCB; CheckBox aHRulerCBox; ListBox aHMetric; CheckBox aVRulerCBox; CheckBox aVRulerRightCBox; ListBox aVMetric; CheckBox aSmoothCBox; //display FixedLine aDispFL; CheckBox aGrfCB; CheckBox aTblCB; CheckBox aDrwCB; CheckBox aFldNameCB; CheckBox aPostItCB; FixedLine aSettingsFL; FixedText aMetricFT; ListBox aMetricLB; DECL_LINK(VertRulerHdl, CheckBox*); DECL_LINK(AnyRulerHdl, CheckBox*); public: SwContentOptPage( Window* pParent, const SfxItemSet& rSet ); ~SwContentOptPage(); static SfxTabPage* Create( Window* pParent, const SfxItemSet& rAttrSet); virtual sal_Bool FillItemSet( SfxItemSet& rSet ); virtual void Reset( const SfxItemSet& rSet ); }; /*-------------------------------------------------------- TabPage printer settings additions --------------------------------------------------------- */ class SwAddPrinterTabPage : public SfxTabPage { FixedLine aFL1; CheckBox aGrfCB; // CheckBox aTabCB; // CheckBox aDrawCB; CheckBox aCtrlFldCB; CheckBox aBackgroundCB; CheckBox aBlackFontCB; CheckBox aPrintHiddenTextCB; CheckBox aPrintTextPlaceholderCB; FixedLine aSeparatorLFL; FixedLine aFL2; CheckBox aLeftPageCB; CheckBox aRightPageCB; // CheckBox aReverseCB; CheckBox aProspectCB; CheckBox aProspectCB_RTL; FixedLine aSeparatorRFL; FixedLine aFL3; RadioButton aNoRB; RadioButton aOnlyRB; RadioButton aEndRB; RadioButton aEndPageRB; FixedLine aFL4; CheckBox aPrintEmptyPagesCB; // CheckBox aSingleJobsCB; CheckBox aPaperFromSetupCB; FixedText aFaxFT; ListBox aFaxLB; String sNone; sal_Bool bAttrModified; sal_Bool bPreview; void Init(); DECL_LINK( AutoClickHdl, CheckBox * ); DECL_LINK( SelectHdl, ListBox * ); SwAddPrinterTabPage( Window* pParent, const SfxItemSet& rSet ); public: static SfxTabPage* Create( Window* pParent, const SfxItemSet& rAttrSet ); virtual sal_Bool FillItemSet( SfxItemSet& rSet ); virtual void Reset( const SfxItemSet& rSet ); void SetFax( const SvStringsDtor& ); void SelectFax( const String& ); void SetPreview(sal_Bool bPrev); virtual void PageCreated (SfxAllItemSet aSet); }; class SwTableOptionsTabPage : public SfxTabPage { FixedLine aTableFL; CheckBox aHeaderCB; CheckBox aRepeatHeaderCB; CheckBox aDontSplitCB; CheckBox aBorderCB; FixedLine aSeparatorFL; FixedLine aTableInsertFL; CheckBox aNumFormattingCB; CheckBox aNumFmtFormattingCB; CheckBox aNumAlignmentCB; FixedLine aMoveFL; FixedText aMoveFT; FixedText aRowMoveFT; MetricField aRowMoveMF; FixedText aColMoveFT; MetricField aColMoveMF; FixedText aInsertFT; FixedText aRowInsertFT; MetricField aRowInsertMF; FixedText aColInsertFT; MetricField aColInsertMF; FixedText aHandlingFT; RadioButton aFixRB; RadioButton aFixPropRB; RadioButton aVarRB; FixedText aFixFT; FixedText aFixPropFT; FixedText aVarFT; SwWrtShell* pWrtShell; sal_Bool bHTMLMode; DECL_LINK(CheckBoxHdl, CheckBox *pCB); SwTableOptionsTabPage( Window* pParent, const SfxItemSet& rSet ); ~SwTableOptionsTabPage(); public: static SfxTabPage* Create( Window* pParent, const SfxItemSet& rAttrSet ); virtual sal_Bool FillItemSet( SfxItemSet& rSet ); virtual void Reset( const SfxItemSet& rSet ); void SetWrtShell(SwWrtShell* pSh) {pWrtShell = pSh;} virtual void PageCreated (SfxAllItemSet aSet); }; /*-------------------------------------------------- TabPage for ShadowCrsr --------------------------------------------------*/ class SwShdwCrsrOptionsTabPage : public SfxTabPage { //nonprinting characters FixedLine aUnprintFL; CheckBox aParaCB; CheckBox aSHyphCB; CheckBox aSpacesCB; CheckBox aHSpacesCB; CheckBox aTabCB; CheckBox aBreakCB; CheckBox aCharHiddenCB; CheckBox aFldHiddenCB; CheckBox aFldHiddenParaCB; FixedLine aSeparatorFL; FixedLine aFlagFL; CheckBox aOnOffCB; FixedText aFillModeFT; RadioButton aFillMarginRB; RadioButton aFillIndentRB; RadioButton aFillTabRB; RadioButton aFillSpaceRB; FixedLine aCrsrOptFL; CheckBox aCrsrInProtCB; FixedLine m_aLayoutOptionsFL; CheckBox m_aMathBaselineAlignmentCB; SwWrtShell * m_pWrtShell; SwShdwCrsrOptionsTabPage( Window* pParent, const SfxItemSet& rSet ); ~SwShdwCrsrOptionsTabPage(); public: static SfxTabPage* Create( Window* pParent, const SfxItemSet& rAttrSet ); virtual sal_Bool FillItemSet( SfxItemSet& rSet ); virtual void Reset( const SfxItemSet& rSet ); void SetWrtShell( SwWrtShell * pSh ) { m_pWrtShell = pSh; } virtual void PageCreated( SfxAllItemSet aSet ); }; /*----------------------------------------------------------------------- Description: mark preview -----------------------------------------------------------------------*/ class SwMarkPreview : public Window { Color m_aBgCol; // background Color m_aTransCol; // transparency Color m_aMarkCol; // marks Color m_aLineCol; // general lines Color m_aShadowCol; // shadow Color m_aTxtCol; // text Color m_aPrintAreaCol; // frame for print area Rectangle aPage; Rectangle aLeftPagePrtArea; Rectangle aRightPagePrtArea; sal_uInt16 nMarkPos; using OutputDevice::DrawRect; void DrawRect(const Rectangle &rRect, const Color &rFillColor, const Color &rLineColor); void Paint(const Rectangle&); void PaintPage(const Rectangle &rRect); void InitColors( void ); protected: virtual void DataChanged( const DataChangedEvent& rDCEvt ); public: SwMarkPreview(Window* pParent, const ResId& rResID); virtual ~SwMarkPreview(); inline void SetColor(const Color& rCol) { m_aMarkCol = rCol; } inline void SetMarkPos(sal_uInt16 nPos) { nMarkPos = nPos; } }; /*----------------------------------------------------------------------- Description: redlining options -----------------------------------------------------------------------*/ class SwRedlineOptionsTabPage : public SfxTabPage { FixedLine aInsertFL; FixedText aInsertFT; FixedText aInsertAttrFT; ListBox aInsertLB; FixedText aInsertColorFT; ColorListBox aInsertColorLB; SvxFontPrevWindow aInsertedPreviewWN; FixedText aDeletedFT; FixedText aDeletedAttrFT; ListBox aDeletedLB; FixedText aDeletedColorFT; ColorListBox aDeletedColorLB; SvxFontPrevWindow aDeletedPreviewWN; FixedText aChangedFT; FixedText aChangedAttrFT; ListBox aChangedLB; FixedText aChangedColorFT; ColorListBox aChangedColorLB; SvxFontPrevWindow aChangedPreviewWN; FixedLine aChangedFL; FixedText aMarkPosFT; ListBox aMarkPosLB; FixedText aMarkColorFT; ColorListBox aMarkColorLB; SwMarkPreview aMarkPreviewWN; String sAuthor; String sNone; SwRedlineOptionsTabPage( Window* pParent, const SfxItemSet& rSet ); ~SwRedlineOptionsTabPage(); DECL_LINK( AttribHdl, ListBox *pLB ); DECL_LINK( ChangedMaskPrevHdl, ListBox *pLB = 0 ); DECL_LINK( ColorHdl, ColorListBox *pColorLB ); void InitFontStyle(SvxFontPrevWindow& rExampleWin); public: static SfxTabPage* Create( Window* pParent, const SfxItemSet& rAttrSet ); virtual sal_Bool FillItemSet( SfxItemSet& rSet ); virtual void Reset( const SfxItemSet& rSet ); }; /*------------------------------------------------------- TabPage test settings for SW --------------------------------------------------------- */ class SwTestTabPage : public SfxTabPage { public: SwTestTabPage( Window* pParent, const SfxItemSet& rSet ); static SfxTabPage* Create( Window* pParent, const SfxItemSet& rAttrSet ); virtual sal_Bool FillItemSet( SfxItemSet& rSet ); virtual void Reset( const SfxItemSet& rSet ); private: FixedLine aTestFL; CheckBox aTest1CBox; CheckBox aTest2CBox; CheckBox aTest3CBox; CheckBox aTest4CBox; CheckBox aTest5CBox; CheckBox aTest6CBox; CheckBox aTest7CBox; CheckBox aTest8CBox; CheckBox aTest9CBox; CheckBox aTest10CBox; sal_Bool bAttrModified; void Init(); DECL_LINK( AutoClickHdl, CheckBox * ); }; #endif /* vim:set shiftwidth=4 softtabstop=4 expandtab: */
fix build: we now use SwTestTabPage also with disabled dbgutil
fix build: we now use SwTestTabPage also with disabled dbgutil
C++
mpl-2.0
JurassicWordExcel/core,JurassicWordExcel/core,JurassicWordExcel/core,JurassicWordExcel/core,JurassicWordExcel/core,JurassicWordExcel/core,JurassicWordExcel/core,JurassicWordExcel/core,JurassicWordExcel/core,JurassicWordExcel/core
2156b48fddd6410d2652e3434cf2c7d56fce2686
code/rtkReg23ProjectionGeometry.cxx
code/rtkReg23ProjectionGeometry.cxx
/*========================================================================= * * Copyright RTK 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 "rtkReg23ProjectionGeometry.h" //std #include <math.h> //ITK #include <itkVector.h> #include <itkEuler3DTransform.h> rtk::Reg23ProjectionGeometry::Reg23ProjectionGeometry() : rtk::ThreeDCircularProjectionGeometry() { } rtk::Reg23ProjectionGeometry::~Reg23ProjectionGeometry() { } bool rtk::Reg23ProjectionGeometry::VerifyAngles(const double outOfPlaneAngleRAD, const double gantryAngleRAD, const double inPlaneAngleRAD, const Matrix3x3Type &referenceMatrix) const { typedef itk::Euler3DTransform<double> EulerType; const Matrix3x3Type &rm = referenceMatrix; // shortcut const double EPSILON = 1e-6; // internal tolerance for comparison EulerType::Pointer euler = EulerType::New(); euler->SetComputeZYX(false); // ZXY order euler->SetRotation(outOfPlaneAngleRAD, gantryAngleRAD, inPlaneAngleRAD); Matrix3x3Type m = euler->GetMatrix(); // resultant matrix for (int i = 0; i < 3; i++) // check whether matrices match for (int j = 0; j < 3; j++) if (fabs(rm[i][j] - m[i][j]) > EPSILON) return false; return true; } bool rtk::Reg23ProjectionGeometry::FixAngles(double &outOfPlaneAngleRAD, double &gantryAngleRAD, double &inPlaneAngleRAD, const Matrix3x3Type &referenceMatrix) const { const Matrix3x3Type &rm = referenceMatrix; // shortcut const double EPSILON = 1e-6; // internal tolerance for comparison if (fabs(fabs(rm[2][0]) - 1.) > EPSILON) { double oa, ga, ia; // @see Slabaugh, GG, "Computing Euler angles from a rotation matrix" // first trial: oa = asin(rm[2][1]); double coa = cos(oa); ga = atan2(-rm[2][0] / coa, rm[2][2] / coa); ia = atan2(-rm[0][1] / coa, rm[1][1] / coa); if (VerifyAngles(oa, ga, ia, rm)) { outOfPlaneAngleRAD = oa; gantryAngleRAD = ga; inPlaneAngleRAD = ia; return true; } // second trial: oa = 3.1415926535897932384626433832795 /*PI*/ - asin(rm[2][1]); coa = cos(oa); ga = atan2(-rm[2][0] / coa, rm[2][2] / coa); ia = atan2(-rm[0][1] / coa, rm[1][1] / coa); if (VerifyAngles(oa, ga, ia, rm)) { outOfPlaneAngleRAD = oa; gantryAngleRAD = ga; inPlaneAngleRAD = ia; return true; } return false; } return false; } bool rtk::Reg23ProjectionGeometry::AddReg23Projection( const PointType &sourcePosition, const PointType &detectorPosition, const VectorType &detectorRowVector, const VectorType &detectorColumnVector) { typedef itk::Euler3DTransform<double> EulerType; // these parameters relate absolutely to the WCS (IEC-based): const VectorType &r = detectorRowVector; // row dir const VectorType &c = detectorColumnVector; // column dir VectorType n = itk::CrossProduct(r, c); // normal const PointType &S = sourcePosition; // source pos const PointType &R = detectorPosition; // detector pos if (fabs(r * c) > 1e-6) // non-orthogonal row/column vectors return false; // Euler angles (ZXY convention) from detector orientation in IEC-based WCS: double ga; // gantry angle double oa; // out-of-plane angle double ia; // in-plane angle // extract Euler angles from the orthogonal matrix which is established // by the detector orientation; however, we would like RTK to internally // store the inverse of this rotation matrix, therefore the corresponding // angles are computed here: Matrix3x3Type rm; // reference matrix // NOTE: This transposed matrix should internally // set by rtk::ThreeDProjectionGeometry (inverse) // of external rotation! rm[0][0] = r[0]; rm[0][1] = r[1]; rm[0][2] = r[2]; rm[1][0] = c[0]; rm[1][1] = c[1]; rm[1][2] = c[2]; rm[2][0] = n[0]; rm[2][1] = n[1]; rm[2][2] = n[2]; // extract Euler angles by using the standard ITK implementation: EulerType::Pointer euler = EulerType::New(); euler->SetComputeZYX(false); // ZXY order // workaround: Orthogonality tolerance problem when using // Euler3DTransform->SetMatrix() due to error magnification. // Parent class MatrixOffsetTransformBase does not perform an // orthogonality check on the matrix! euler->itk::MatrixOffsetTransformBase<double>::SetMatrix(rm); oa = euler->GetAngleX(); // delivers radians ga = euler->GetAngleY(); ia = euler->GetAngleZ(); // verify that extracted ZXY angles result in the *desired* matrix: // (at some angle constellations we may run into numerical troubles, therefore, // verify angles and try to fix instabilities) if (!VerifyAngles(oa, ga, ia, rm)) { if (!FixAngles(oa, ga, ia, rm)) return false; } // since rtk::ThreeDCircularProjectionGeometry::AddProjection() mirrors the // angles (!) internally, let's invert the computed ones in order to // get at the end what we would like (see above); convert rad->deg: ga *= -57.29577951308232; oa *= -57.29577951308232; ia *= -57.29577951308232; // SID: distance from source to isocenter along detector normal double SID = n[0] * S[0] + n[1] * S[1] + n[2] * S[2]; // SDD: distance from source to detector along detector normal double SDD = n[0] * (S[0] - R[0]) + n[1] * (S[1] - R[1]) + n[2] * (S[2] - R[2]); if (fabs(SDD) < 1e-6) // source is in detector plane return false; // source offset: compute source's "in-plane" x/y shift off isocenter VectorType Sv; Sv[0] = S[0]; Sv[1] = S[1]; Sv[2] = S[2]; double oSx = Sv * r; double oSy = Sv * c; // detector offset: compute detector's in-plane x/y shift off isocenter VectorType Rv; Rv[0] = R[0]; Rv[1] = R[1]; Rv[2] = R[2]; double oRx = Rv * r; double oRy = Rv * c; // configure native RTK geometry this->Superclass::AddProjection(SID, SDD, ga, oRx, oRy, oa, ia, oSx, oSy); return true; }
/*========================================================================= * * Copyright RTK 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 "rtkReg23ProjectionGeometry.h" //std #include <math.h> //ITK #include <itkVector.h> #include <itkEuler3DTransform.h> rtk::Reg23ProjectionGeometry::Reg23ProjectionGeometry() : rtk::ThreeDCircularProjectionGeometry() { } rtk::Reg23ProjectionGeometry::~Reg23ProjectionGeometry() { } bool rtk::Reg23ProjectionGeometry::VerifyAngles(const double outOfPlaneAngleRAD, const double gantryAngleRAD, const double inPlaneAngleRAD, const Matrix3x3Type &referenceMatrix) const { // Check if parameters are Nan. Fails if they are. if(outOfPlaneAngleRAD != outOfPlaneAngleRAD || gantryAngleRAD != gantryAngleRAD || inPlaneAngleRAD != inPlaneAngleRAD) return false; typedef itk::Euler3DTransform<double> EulerType; const Matrix3x3Type &rm = referenceMatrix; // shortcut const double EPSILON = 1e-6; // internal tolerance for comparison EulerType::Pointer euler = EulerType::New(); euler->SetComputeZYX(false); // ZXY order euler->SetRotation(outOfPlaneAngleRAD, gantryAngleRAD, inPlaneAngleRAD); Matrix3x3Type m = euler->GetMatrix(); // resultant matrix for (int i = 0; i < 3; i++) // check whether matrices match for (int j = 0; j < 3; j++) if (fabs(rm[i][j] - m[i][j]) > EPSILON) return false; return true; } bool rtk::Reg23ProjectionGeometry::FixAngles(double &outOfPlaneAngleRAD, double &gantryAngleRAD, double &inPlaneAngleRAD, const Matrix3x3Type &referenceMatrix) const { const Matrix3x3Type &rm = referenceMatrix; // shortcut const double EPSILON = 1e-6; // internal tolerance for comparison if (fabs(fabs(rm[2][0]) - 1.) > EPSILON) { double oa, ga, ia; // @see Slabaugh, GG, "Computing Euler angles from a rotation matrix" // first trial: oa = asin(rm[2][1]); double coa = cos(oa); ga = atan2(-rm[2][0] / coa, rm[2][2] / coa); ia = atan2(-rm[0][1] / coa, rm[1][1] / coa); if (VerifyAngles(oa, ga, ia, rm)) { outOfPlaneAngleRAD = oa; gantryAngleRAD = ga; inPlaneAngleRAD = ia; return true; } // second trial: oa = 3.1415926535897932384626433832795 /*PI*/ - asin(rm[2][1]); coa = cos(oa); ga = atan2(-rm[2][0] / coa, rm[2][2] / coa); ia = atan2(-rm[0][1] / coa, rm[1][1] / coa); if (VerifyAngles(oa, ga, ia, rm)) { outOfPlaneAngleRAD = oa; gantryAngleRAD = ga; inPlaneAngleRAD = ia; return true; } return false; } return false; } bool rtk::Reg23ProjectionGeometry::AddReg23Projection( const PointType &sourcePosition, const PointType &detectorPosition, const VectorType &detectorRowVector, const VectorType &detectorColumnVector) { typedef itk::Euler3DTransform<double> EulerType; // these parameters relate absolutely to the WCS (IEC-based): const VectorType &r = detectorRowVector; // row dir const VectorType &c = detectorColumnVector; // column dir VectorType n = itk::CrossProduct(r, c); // normal const PointType &S = sourcePosition; // source pos const PointType &R = detectorPosition; // detector pos if (fabs(r * c) > 1e-6) // non-orthogonal row/column vectors return false; // Euler angles (ZXY convention) from detector orientation in IEC-based WCS: double ga; // gantry angle double oa; // out-of-plane angle double ia; // in-plane angle // extract Euler angles from the orthogonal matrix which is established // by the detector orientation; however, we would like RTK to internally // store the inverse of this rotation matrix, therefore the corresponding // angles are computed here: Matrix3x3Type rm; // reference matrix // NOTE: This transposed matrix should internally // set by rtk::ThreeDProjectionGeometry (inverse) // of external rotation! rm[0][0] = r[0]; rm[0][1] = r[1]; rm[0][2] = r[2]; rm[1][0] = c[0]; rm[1][1] = c[1]; rm[1][2] = c[2]; rm[2][0] = n[0]; rm[2][1] = n[1]; rm[2][2] = n[2]; // extract Euler angles by using the standard ITK implementation: EulerType::Pointer euler = EulerType::New(); euler->SetComputeZYX(false); // ZXY order // workaround: Orthogonality tolerance problem when using // Euler3DTransform->SetMatrix() due to error magnification. // Parent class MatrixOffsetTransformBase does not perform an // orthogonality check on the matrix! euler->itk::MatrixOffsetTransformBase<double>::SetMatrix(rm); oa = euler->GetAngleX(); // delivers radians ga = euler->GetAngleY(); ia = euler->GetAngleZ(); // verify that extracted ZXY angles result in the *desired* matrix: // (at some angle constellations we may run into numerical troubles, therefore, // verify angles and try to fix instabilities) if (!VerifyAngles(oa, ga, ia, rm)) { if (!FixAngles(oa, ga, ia, rm)) return false; } // since rtk::ThreeDCircularProjectionGeometry::AddProjection() mirrors the // angles (!) internally, let's invert the computed ones in order to // get at the end what we would like (see above); convert rad->deg: ga *= -57.29577951308232; oa *= -57.29577951308232; ia *= -57.29577951308232; // SID: distance from source to isocenter along detector normal double SID = n[0] * S[0] + n[1] * S[1] + n[2] * S[2]; // SDD: distance from source to detector along detector normal double SDD = n[0] * (S[0] - R[0]) + n[1] * (S[1] - R[1]) + n[2] * (S[2] - R[2]); if (fabs(SDD) < 1e-6) // source is in detector plane return false; // source offset: compute source's "in-plane" x/y shift off isocenter VectorType Sv; Sv[0] = S[0]; Sv[1] = S[1]; Sv[2] = S[2]; double oSx = Sv * r; double oSy = Sv * c; // detector offset: compute detector's in-plane x/y shift off isocenter VectorType Rv; Rv[0] = R[0]; Rv[1] = R[1]; Rv[2] = R[2]; double oRx = Rv * r; double oRy = Rv * c; // configure native RTK geometry this->Superclass::AddProjection(SID, SDD, ga, oRx, oRy, oa, ia, oSx, oSy); return true; }
Handle NaN in the verification of angles
Handle NaN in the verification of angles
C++
apache-2.0
ldqcarbon/RTK,dsarrut/RTK,fabienmomey/RTK,ldqcarbon/RTK,ipsusila/RTK,fabienmomey/RTK,ipsusila/RTK,fabienmomey/RTK,ldqcarbon/RTK,fabienmomey/RTK,ipsusila/RTK,dsarrut/RTK,dsarrut/RTK,SimonRit/RTK,ipsusila/RTK,ipsusila/RTK,ldqcarbon/RTK,SimonRit/RTK,SimonRit/RTK,ipsusila/RTK,dsarrut/RTK,ipsusila/RTK,ldqcarbon/RTK,fabienmomey/RTK,ldqcarbon/RTK,dsarrut/RTK,ldqcarbon/RTK,dsarrut/RTK,dsarrut/RTK,SimonRit/RTK,fabienmomey/RTK,fabienmomey/RTK
a2c2539d91e8ed56911667c8cf22bcb3f54d39c8
lib/RfHandler/RfHandler.cpp
lib/RfHandler/RfHandler.cpp
/** MQTT433gateway - MQTT 433.92 MHz radio gateway utilizing ESPiLight Project home: https://github.com/puuu/MQTT433gateway/ The MIT License (MIT) Copyright (c) 2017 Jan Losinski 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 <ArduinoSimpleLogging.h> #include "RfHandler.h" RfHandler::RfHandler(const Settings &settings) : settings(settings), rf(settings.rfTransmitterPin) { rf.setErrorOutput(Logger.error); } RfHandler::~RfHandler() { rf.initReceiver(-1); } void RfHandler::transmitCode(const String &protocol, const String &message) { int result = 0; Logger.info.print(F("transmit rf signal ")); Logger.info.print(message); Logger.info.print(F(" with protocol ")); Logger.info.println(protocol); if (protocol == F("RAW")) { uint16_t rawpulses[MAXPULSESTREAMLENGTH]; int rawlen = rf.stringToPulseTrain(message, rawpulses, MAXPULSESTREAMLENGTH); if (rawlen > 0) { rf.sendPulseTrain(rawpulses, rawlen); result = rawlen; } else { result = -9999; } } else { result = rf.send(protocol, message); } if (result > 0) { Logger.debug.print(F("transmitted pulse train with ")); Logger.debug.print(result); Logger.debug.println(F(" pulses")); } else { Logger.error.print(F("transmitting failed: ")); switch (result) { case ESPiLight::ERROR_UNAVAILABLE_PROTOCOL: Logger.error.println(F("protocol is not avaiable")); break; case ESPiLight::ERROR_INVALID_PILIGHT_MSG: Logger.error.println(F("message is invalid")); break; case ESPiLight::ERROR_INVALID_JSON: Logger.error.println(F("message is not a proper json object")); break; case ESPiLight::ERROR_NO_OUTPUT_PIN: Logger.error.println(F("no transmitter pin")); break; case -9999: Logger.error.println(F("invalid pulse train message")); break; } } } void RfHandler::onRfCode(const String &protocol, const String &message, int status, size_t repeats, const String &deviceID) { if (!onReceiveCallback) return; if (status == VALID) { Logger.info.print(F("rf signal received: ")); Logger.info.print(message); Logger.info.print(F(" with protocol ")); Logger.info.print(protocol); if (deviceID != nullptr) { Logger.info.print(F(" deviceID=")); Logger.info.println(deviceID); onReceiveCallback(protocol + "/" + deviceID, message); } else { Logger.info.println(deviceID); onReceiveCallback(protocol, message); } } else { Logger.debug.print(F("rf signal received: ")); Logger.debug.print(message); Logger.debug.print(F(" protocol= ")); Logger.debug.print(protocol); Logger.debug.print(F(" status=")); Logger.debug.print(status); Logger.debug.print(F(" repeats=")); Logger.debug.print(repeats); Logger.debug.print(F(" deviceID=")); Logger.debug.println(deviceID); } } void RfHandler::onRfRaw(const uint16_t *pulses, size_t length) { if (rawMode) { String data = rf.pulseTrainToString(pulses, length); if (data.length() > 0) { Logger.info.print(F("RAW RF signal (")); Logger.info.print(length); Logger.info.print(F("): ")); Logger.info.println(data); } } } void RfHandler::begin() { if (0 < settings.rfReceiverPin) { using namespace std::placeholders; if (settings.rfReceiverPinPullUp) { // 5V protection with reverse diode needs pullup pinMode(settings.rfReceiverPin, INPUT_PULLUP); } rf.setCallback(std::bind(&RfHandler::onRfCode, this, _1, _2, _3, _4, _5)); rf.setPulseTrainCallBack(std::bind(&RfHandler::onRfRaw, this, _1, _2)); rf.initReceiver(settings.rfReceiverPin); } } void RfHandler::enableReceiver() { rf.enableReceiver(); } void RfHandler::disableReceiver() { rf.disableReceiver(); } void RfHandler::setEchoEnabled(bool enabled) { rf.setEchoEnabled(enabled); } void RfHandler::filterProtocols(const String &protocols) { rf.limitProtocols(protocols); } String RfHandler::availableProtocols() { return ESPiLight::availableProtocols(); } void RfHandler::loop() { rf.loop(); } void RfHandler::registerReceiveHandler(const ReceiveCb &cb) { onReceiveCallback = cb; }
/** MQTT433gateway - MQTT 433.92 MHz radio gateway utilizing ESPiLight Project home: https://github.com/puuu/MQTT433gateway/ The MIT License (MIT) Copyright (c) 2017 Jan Losinski 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 <ArduinoSimpleLogging.h> #include "RfHandler.h" RfHandler::RfHandler(const Settings &settings) : settings(settings), rf(settings.rfTransmitterPin) { rf.setErrorOutput(Logger.error); } RfHandler::~RfHandler() { rf.initReceiver(-1); } void RfHandler::transmitCode(const String &protocol, const String &message) { int result = 0; Logger.info.print(F("transmit rf signal ")); Logger.info.print(message); Logger.info.print(F(" with protocol ")); Logger.info.println(protocol); if (protocol == F("RAW")) { uint16_t rawpulses[MAXPULSESTREAMLENGTH]; int rawlen = rf.stringToPulseTrain(message, rawpulses, MAXPULSESTREAMLENGTH); if (rawlen > 0) { rf.sendPulseTrain(rawpulses, rawlen); result = rawlen; } else { result = -9999; } } else { result = rf.send(protocol, message); } if (result > 0) { Logger.debug.print(F("transmitted pulse train with ")); Logger.debug.print(result); Logger.debug.println(F(" pulses")); } else { Logger.error.print(F("transmitting failed: ")); switch (result) { case ESPiLight::ERROR_UNAVAILABLE_PROTOCOL: Logger.error.println(F("protocol is not avaiable")); break; case ESPiLight::ERROR_INVALID_PILIGHT_MSG: Logger.error.println(F("message is invalid")); break; case ESPiLight::ERROR_INVALID_JSON: Logger.error.println(F("message is not a proper json object")); break; case ESPiLight::ERROR_NO_OUTPUT_PIN: Logger.error.println(F("no transmitter pin")); break; case -9999: Logger.error.println(F("invalid pulse train message")); break; } } } void RfHandler::onRfCode(const String &protocol, const String &message, int status, size_t repeats, const String &deviceID) { if (!onReceiveCallback) return; if (status == VALID) { Logger.info.print(F("rf signal received: ")); Logger.info.print(message); Logger.info.print(F(" with protocol ")); Logger.info.print(protocol); if (deviceID != nullptr) { Logger.info.print(F(" deviceID=")); Logger.info.println(deviceID); onReceiveCallback(protocol + "/" + deviceID, message); } else { Logger.info.println(deviceID); onReceiveCallback(protocol, message); } } else { Logger.debug.print(F("rf signal received: ")); Logger.debug.print(message); Logger.debug.print(F(" protocol=")); Logger.debug.print(protocol); Logger.debug.print(F(" status=")); Logger.debug.print(status); Logger.debug.print(F(" repeats=")); Logger.debug.print(repeats); Logger.debug.print(F(" deviceID=")); Logger.debug.println(deviceID); } } void RfHandler::onRfRaw(const uint16_t *pulses, size_t length) { if (rawMode) { String data = rf.pulseTrainToString(pulses, length); if (data.length() > 0) { Logger.info.print(F("RAW RF signal (")); Logger.info.print(length); Logger.info.print(F("): ")); Logger.info.println(data); } } } void RfHandler::begin() { if (0 < settings.rfReceiverPin) { using namespace std::placeholders; if (settings.rfReceiverPinPullUp) { // 5V protection with reverse diode needs pullup pinMode(settings.rfReceiverPin, INPUT_PULLUP); } rf.setCallback(std::bind(&RfHandler::onRfCode, this, _1, _2, _3, _4, _5)); rf.setPulseTrainCallBack(std::bind(&RfHandler::onRfRaw, this, _1, _2)); rf.initReceiver(settings.rfReceiverPin); } } void RfHandler::enableReceiver() { rf.enableReceiver(); } void RfHandler::disableReceiver() { rf.disableReceiver(); } void RfHandler::setEchoEnabled(bool enabled) { rf.setEchoEnabled(enabled); } void RfHandler::filterProtocols(const String &protocols) { rf.limitProtocols(protocols); } String RfHandler::availableProtocols() { return ESPiLight::availableProtocols(); } void RfHandler::loop() { rf.loop(); } void RfHandler::registerReceiveHandler(const ReceiveCb &cb) { onReceiveCallback = cb; }
remove superfluous space in log message
lib/RfHandler/RfHandler.cpp: remove superfluous space in log message
C++
mit
puuu/MQTT433gateway,puuu/MQTT433gateway,puuu/MQTT433gateway,puuu/MQTT433gateway,puuu/MQTT433gateway,puuu/MQTT433gateway
81faac64431118afb356848635e8730efdc6d84e
system/GlobalMemoryChunk.cpp
system/GlobalMemoryChunk.cpp
#include <glog/logging.h> #include <gflags/gflags.h> extern "C" { #include <unistd.h> #include <sys/mman.h> #include <sys/types.h> #include <sys/ipc.h> #include <sys/shm.h> } #include "Communicator.hpp" #include "GlobalMemoryChunk.hpp" DEFINE_bool( global_memory_use_hugepages, true, "use 1GB huge pages for global heap" ); DEFINE_int64( global_memory_per_node_base_address, 0x0000123400000000L, "global memory base address"); static const size_t round_to_gb_huge_page( size_t size ) { const size_t half_gb_huge_page = (1L << 30) - 1; // make sure we use at least one gb huge page size += half_gb_huge_page; // now page-align the address (30 bits) size &= 0xffffffffc0000000L; return size; } static const size_t round_to_4kb_page( size_t size ) { const size_t half_4kb_page = (1L << 12) - 1; // make sure we use at least one page size += half_4kb_page; // now page-align the address (12 bits) size &= 0xfffffffffffff000L; return size; } GlobalMemoryChunk::~GlobalMemoryChunk() { PCHECK( 0 == shmdt( memory_ ) ) << "GlobalMemoryChunk destructor failed to detach from shared memory region"; PCHECK( 0 == shmctl(shm_id_, IPC_RMID, NULL ) ) << "GlobalMemoryChunk destructor failed to deallocate shared memory region id"; } GlobalMemoryChunk::GlobalMemoryChunk( size_t size ) : shm_key_( -1 ) , shm_id_( -1 ) , size_( FLAGS_global_memory_use_hugepages ? round_to_gb_huge_page( size ) : round_to_4kb_page( size ) ) , base_( reinterpret_cast< void * >( FLAGS_global_memory_per_node_base_address ) ) , memory_( 0 ) { // build shm key from job id and node id char * job_id_str = getenv("SLURM_JOB_ID"); int job_id = -1; if( job_id_str != NULL ) { job_id = atoi( job_id_str ); } else { job_id = getpid(); } shm_key_ = job_id * global_communicator.nodes() + global_communicator.mynode(); LOG(INFO) << size << " rounded to " << size_; // get shared memory region id shm_id_ = shmget( shm_key_, size_, IPC_CREAT | SHM_R | SHM_W | (FLAGS_global_memory_use_hugepages ? SHM_HUGETLB : 0) ); PCHECK( shm_id_ != -1 ) << "Failed to get shared memory region for shared heap"; // map memory memory_ = shmat( shm_id_, base_, 0 ); PCHECK( memory_ != (void*)-1 ) << "GlobalMemoryChunk allocation didn't happen at specified base address"; }
#include <glog/logging.h> #include <gflags/gflags.h> extern "C" { #include <unistd.h> #include <sys/mman.h> #include <sys/types.h> #include <sys/ipc.h> #include <sys/shm.h> } #include "Communicator.hpp" #include "GlobalMemoryChunk.hpp" DEFINE_bool( global_memory_use_hugepages, true, "use 1GB huge pages for global heap" ); DEFINE_int64( global_memory_per_node_base_address, 0x0000123400000000L, "global memory base address"); static const size_t round_to_gb_huge_page( size_t size ) { const size_t half_gb_huge_page = (1L << 30) - 1; // make sure we use at least one gb huge page size += half_gb_huge_page; // now page-align the address (30 bits) size &= 0xffffffffc0000000L; return size; } static const size_t round_to_4kb_page( size_t size ) { const size_t half_4kb_page = (1L << 12) - 1; // make sure we use at least one page size += half_4kb_page; // now page-align the address (12 bits) size &= 0xfffffffffffff000L; return size; } GlobalMemoryChunk::~GlobalMemoryChunk() { PCHECK( 0 == shmdt( memory_ ) ) << "GlobalMemoryChunk destructor failed to detach from shared memory region"; PCHECK( 0 == shmctl(shm_id_, IPC_RMID, NULL ) ) << "GlobalMemoryChunk destructor failed to deallocate shared memory region id"; } GlobalMemoryChunk::GlobalMemoryChunk( size_t size ) : shm_key_( -1 ) , shm_id_( -1 ) , size_( FLAGS_global_memory_use_hugepages ? round_to_gb_huge_page( size ) : round_to_4kb_page( size ) ) , base_( reinterpret_cast< void * >( FLAGS_global_memory_per_node_base_address ) ) , memory_( 0 ) { // build shm key from job id and node id char * job_id_str = getenv("SLURM_JOB_ID"); int job_id = -1; if( job_id_str != NULL ) { job_id = atoi( job_id_str ); } else { job_id = getpid(); } shm_key_ = job_id * global_communicator.nodes() + global_communicator.mynode(); DVLOG(2) << size << " rounded to " << size_; // get shared memory region id shm_id_ = shmget( shm_key_, size_, IPC_CREAT | SHM_R | SHM_W | (FLAGS_global_memory_use_hugepages ? SHM_HUGETLB : 0) ); PCHECK( shm_id_ != -1 ) << "Failed to get shared memory region for shared heap"; // map memory memory_ = shmat( shm_id_, base_, 0 ); PCHECK( memory_ != (void*)-1 ) << "GlobalMemoryChunk allocation didn't happen at specified base address"; }
Make GlobalMemoryChunk slightly less verbose
Make GlobalMemoryChunk slightly less verbose
C++
bsd-3-clause
buaasun/grappa,buaasun/grappa,uwsampa/grappa,uwsampa/grappa,uwsampa/grappa,buaasun/grappa,buaasun/grappa,uwsampa/grappa,uwsampa/grappa,alexfrolov/grappa,alexfrolov/grappa,alexfrolov/grappa,uwsampa/grappa,buaasun/grappa,alexfrolov/grappa,uwsampa/grappa,buaasun/grappa,alexfrolov/grappa,alexfrolov/grappa,buaasun/grappa,alexfrolov/grappa
0a504ec7c360ecfaad8db8607862bc69ed77abfa
lib/asan/asan_allocator2.cc
lib/asan/asan_allocator2.cc
//===-- asan_allocator2.cc ------------------------------------------------===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // This file is a part of AddressSanitizer, an address sanity checker. // // Implementation of ASan's memory allocator, 2-nd version. // This variant uses the allocator from sanitizer_common, i.e. the one shared // with ThreadSanitizer and MemorySanitizer. // // Status: under development, not enabled by default yet. //===----------------------------------------------------------------------===// #include "asan_allocator.h" #if ASAN_ALLOCATOR_VERSION == 2 #include "asan_mapping.h" #include "asan_thread.h" #include "asan_thread_registry.h" #include "sanitizer/asan_interface.h" #include "sanitizer_common/sanitizer_allocator.h" #include "sanitizer_common/sanitizer_internal_defs.h" namespace __asan { struct AsanMapUnmapCallback { void OnMap(uptr p, uptr size) const { PoisonShadow(p, size, kAsanHeapLeftRedzoneMagic); } void OnUnmap(uptr p, uptr size) const { PoisonShadow(p, size, 0); } }; #if SANITIZER_WORDSIZE == 64 const uptr kAllocatorSpace = 0x600000000000ULL; const uptr kAllocatorSize = 0x10000000000ULL; // 1T. typedef SizeClassAllocator64<kAllocatorSpace, kAllocatorSize, 0 /*metadata*/, DefaultSizeClassMap, AsanMapUnmapCallback> PrimaryAllocator; #elif SANITIZER_WORDSIZE == 32 static const u64 kAddressSpaceSize = 1ULL << 32; typedef SizeClassAllocator32<0, kAddressSpaceSize, 16, CompactSizeClassMap, AsanMapUnmapCallback> PrimaryAllocator; #endif typedef SizeClassAllocatorLocalCache<PrimaryAllocator> AllocatorCache; typedef LargeMmapAllocator<AsanMapUnmapCallback> SecondaryAllocator; typedef CombinedAllocator<PrimaryAllocator, AllocatorCache, SecondaryAllocator> Allocator; static THREADLOCAL AllocatorCache cache; static Allocator allocator; static const uptr kMaxAllowedMallocSize = (SANITIZER_WORDSIZE == 32) ? 3UL << 30 : 8UL << 30; static int inited = 0; static void Init() { if (inited) return; __asan_init(); inited = true; // this must happen before any threads are created. allocator.Init(); } // Every chunk of memory allocated by this allocator can be in one of 3 states: // CHUNK_AVAILABLE: the chunk is in the free list and ready to be allocated. // CHUNK_ALLOCATED: the chunk is allocated and not yet freed. // CHUNK_QUARANTINE: the chunk was freed and put into quarantine zone. enum { CHUNK_AVAILABLE = 1, CHUNK_ALLOCATED = 2, CHUNK_QUARANTINE = 3 }; // The memory chunk allocated from the underlying allocator looks like this: // L L L L L L H H U U U U U U R R // L -- left redzone words (0 or more bytes) // H -- ChunkHeader (16 bytes on 64-bit arch, 8 bytes on 32-bit arch). // ChunkHeader is also a part of the left redzone. // U -- user memory. // R -- right redzone (0 or more bytes) // ChunkBase consists of ChunkHeader and other bytes that overlap with user // memory. #if SANITIZER_WORDSIZE == 64 struct ChunkBase { // 1-st 8 bytes. uptr chunk_state : 8; // Must be first. uptr alloc_tid : 24; uptr free_tid : 24; uptr from_memalign : 1; // 2-nd 8 bytes uptr user_requested_size; // End of ChunkHeader. // 3-rd 8 bytes. These overlap with the user memory. AsanChunk *next; }; static const uptr kChunkHeaderSize = 16; COMPILER_CHECK(sizeof(ChunkBase) == 24); #elif SANITIZER_WORDSIZE == 32 struct ChunkBase { // 1-st 8 bytes. uptr chunk_state : 8; // Must be first. uptr from_memalign : 1; uptr alloc_tid : 23; uptr user_requested_size; // End of ChunkHeader. // 2-nd 8 bytes. These overlap with the user memory. AsanChunk *next; uptr free_tid; }; COMPILER_CHECK(sizeof(ChunkBase) == 16); static const uptr kChunkHeaderSize = 8; #endif static uptr ComputeRZSize(uptr user_requested_size) { // FIXME: implement adaptive redzones. return flags()->redzone; } struct AsanChunk: ChunkBase { uptr Beg() { return reinterpret_cast<uptr>(this) + kChunkHeaderSize; } uptr UsedSize() { return user_requested_size; } // We store the alloc/free stack traces in the chunk itself. uptr AllocStackBeg() { return Beg() - ComputeRZSize(user_requested_size); } uptr AllocStackSize() { return ComputeRZSize(user_requested_size) - kChunkHeaderSize; } uptr FreeStackBeg(); uptr FreeStackSize(); }; uptr AsanChunkView::Beg() { return chunk_->Beg(); } uptr AsanChunkView::End() { return Beg() + UsedSize(); } uptr AsanChunkView::UsedSize() { return chunk_->UsedSize(); } uptr AsanChunkView::AllocTid() { return chunk_->alloc_tid; } uptr AsanChunkView::FreeTid() { return chunk_->free_tid; } void AsanChunkView::GetAllocStack(StackTrace *stack) { StackTrace::UncompressStack(stack, chunk_->AllocStackBeg(), chunk_->AllocStackSize()); } void AsanChunkView::GetFreeStack(StackTrace *stack) { stack->size = 0; } static const uptr kReturnOnZeroMalloc = 0x0123; // Zero page is protected. static void *Allocate(uptr size, uptr alignment, StackTrace *stack) { Init(); CHECK(stack); if (alignment < 8) alignment = 8; if (size == 0) return reinterpret_cast<void *>(kReturnOnZeroMalloc); CHECK(IsPowerOfTwo(alignment)); uptr rz_size = ComputeRZSize(size); uptr rounded_size = RoundUpTo(size, rz_size); uptr needed_size = rounded_size + rz_size; if (alignment > rz_size) needed_size += alignment; CHECK(IsAligned(needed_size, rz_size)); if (size > kMaxAllowedMallocSize || needed_size > kMaxAllowedMallocSize) { Report("WARNING: AddressSanitizer failed to allocate %p bytes\n", (void*)size); return 0; } AsanThread *t = asanThreadRegistry().GetCurrent(); void *allocated = allocator.Allocate(&cache, needed_size, 8, false); uptr alloc_beg = reinterpret_cast<uptr>(allocated); uptr alloc_end = alloc_beg + needed_size; uptr beg_plus_redzone = alloc_beg + rz_size; uptr user_beg = beg_plus_redzone; if (!IsAligned(user_beg, alignment)) user_beg = RoundUpTo(user_beg, alignment); uptr user_end = user_beg + size; CHECK_LE(user_end, alloc_end); uptr chunk_beg = user_beg - kChunkHeaderSize; // Printf("allocated: %p beg_plus_redzone %p chunk_beg %p\n", // allocated, beg_plus_redzone, chunk_beg); AsanChunk *m = reinterpret_cast<AsanChunk *>(chunk_beg); m->chunk_state = CHUNK_ALLOCATED; u32 alloc_tid = t ? t->tid() : 0; m->alloc_tid = alloc_tid; CHECK_EQ(alloc_tid, m->alloc_tid); // Does alloc_tid fit into the bitfield? m->free_tid = kInvalidTid; m->from_memalign = user_beg != beg_plus_redzone; m->user_requested_size = size; StackTrace::CompressStack(stack, m->AllocStackBeg(), m->AllocStackSize()); uptr size_rounded_down_to_granularity = RoundDownTo(size, SHADOW_GRANULARITY); // Unpoison the bulk of the memory region. if (size_rounded_down_to_granularity) PoisonShadow(user_beg, size_rounded_down_to_granularity, 0); // Deal with the end of the region if size is not aligned to granularity. if (size != size_rounded_down_to_granularity) { u8 *shadow = (u8*)MemToShadow(user_beg + size_rounded_down_to_granularity); *shadow = size & (SHADOW_GRANULARITY - 1); } void *res = reinterpret_cast<void *>(user_beg); ASAN_MALLOC_HOOK(res, size); return res; } static void Deallocate(void *ptr, StackTrace *stack) { uptr p = reinterpret_cast<uptr>(ptr); if (p == 0 || p == kReturnOnZeroMalloc) return; uptr chunk_beg = p - kChunkHeaderSize; AsanChunk *m = reinterpret_cast<AsanChunk *>(chunk_beg); uptr alloc_beg = p - ComputeRZSize(m->user_requested_size); if (m->from_memalign) alloc_beg = reinterpret_cast<uptr>(allocator.GetBlockBegin(ptr)); // Poison the region. PoisonShadow(m->Beg(), RoundUpTo(m->user_requested_size, SHADOW_GRANULARITY), kAsanHeapFreeMagic); ASAN_FREE_HOOK(ptr); allocator.Deallocate(&cache, reinterpret_cast<void *>(alloc_beg)); } AsanChunkView FindHeapChunkByAddress(uptr address) { UNIMPLEMENTED(); return AsanChunkView(0); } void AsanThreadLocalMallocStorage::CommitBack() { UNIMPLEMENTED(); } SANITIZER_INTERFACE_ATTRIBUTE void *asan_memalign(uptr alignment, uptr size, StackTrace *stack) { return Allocate(size, alignment, stack); } SANITIZER_INTERFACE_ATTRIBUTE void asan_free(void *ptr, StackTrace *stack) { Deallocate(ptr, stack); } SANITIZER_INTERFACE_ATTRIBUTE void *asan_malloc(uptr size, StackTrace *stack) { return Allocate(size, 8, stack); } void *asan_calloc(uptr nmemb, uptr size, StackTrace *stack) { void *ptr = Allocate(nmemb * size, 8, stack); if (ptr) REAL(memset)(ptr, 0, nmemb * size); return 0; } void *asan_realloc(void *p, uptr size, StackTrace *stack) { if (p == 0) { return Allocate(size, 8, stack); if (size == 0) { Deallocate(p, stack); return 0; } UNIMPLEMENTED; // return Reallocate((u8*)p, size, stack); } void *asan_valloc(uptr size, StackTrace *stack) { return Allocate(size, GetPageSizeCached(), stack); } void *asan_pvalloc(uptr size, StackTrace *stack) { uptr PageSize = GetPageSizeCached(); size = RoundUpTo(size, PageSize); if (size == 0) { // pvalloc(0) should allocate one page. size = PageSize; } return Allocate(size, PageSize, stack); } int asan_posix_memalign(void **memptr, uptr alignment, uptr size, StackTrace *stack) { void *ptr = Allocate(size, alignment, stack); CHECK(IsAligned((uptr)ptr, alignment)); *memptr = ptr; return 0; } uptr asan_malloc_usable_size(void *ptr, StackTrace *stack) { UNIMPLEMENTED(); return 0; } uptr asan_mz_size(const void *ptr) { UNIMPLEMENTED(); return 0; } void asan_mz_force_lock() { UNIMPLEMENTED(); } void asan_mz_force_unlock() { UNIMPLEMENTED(); } } // namespace __asan // ---------------------- Interface ---------------- {{{1 using namespace __asan; // NOLINT // ASan allocator doesn't reserve extra bytes, so normally we would // just return "size". uptr __asan_get_estimated_allocated_size(uptr size) { UNIMPLEMENTED(); return 0; } bool __asan_get_ownership(const void *p) { UNIMPLEMENTED(); return false; } uptr __asan_get_allocated_size(const void *p) { UNIMPLEMENTED(); return 0; } #if !SANITIZER_SUPPORTS_WEAK_HOOKS // Provide default (no-op) implementation of malloc hooks. extern "C" { SANITIZER_WEAK_ATTRIBUTE SANITIZER_INTERFACE_ATTRIBUTE void __asan_malloc_hook(void *ptr, uptr size) { (void)ptr; (void)size; } SANITIZER_WEAK_ATTRIBUTE SANITIZER_INTERFACE_ATTRIBUTE void __asan_free_hook(void *ptr) { (void)ptr; } } // extern "C" #endif #endif // ASAN_ALLOCATOR_VERSION
//===-- asan_allocator2.cc ------------------------------------------------===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // This file is a part of AddressSanitizer, an address sanity checker. // // Implementation of ASan's memory allocator, 2-nd version. // This variant uses the allocator from sanitizer_common, i.e. the one shared // with ThreadSanitizer and MemorySanitizer. // // Status: under development, not enabled by default yet. //===----------------------------------------------------------------------===// #include "asan_allocator.h" #if ASAN_ALLOCATOR_VERSION == 2 #include "asan_mapping.h" #include "asan_thread.h" #include "asan_thread_registry.h" #include "sanitizer/asan_interface.h" #include "sanitizer_common/sanitizer_allocator.h" #include "sanitizer_common/sanitizer_internal_defs.h" namespace __asan { struct AsanMapUnmapCallback { void OnMap(uptr p, uptr size) const { PoisonShadow(p, size, kAsanHeapLeftRedzoneMagic); } void OnUnmap(uptr p, uptr size) const { PoisonShadow(p, size, 0); } }; #if SANITIZER_WORDSIZE == 64 const uptr kAllocatorSpace = 0x600000000000ULL; const uptr kAllocatorSize = 0x10000000000ULL; // 1T. typedef SizeClassAllocator64<kAllocatorSpace, kAllocatorSize, 0 /*metadata*/, DefaultSizeClassMap, AsanMapUnmapCallback> PrimaryAllocator; #elif SANITIZER_WORDSIZE == 32 static const u64 kAddressSpaceSize = 1ULL << 32; typedef SizeClassAllocator32<0, kAddressSpaceSize, 16, CompactSizeClassMap, AsanMapUnmapCallback> PrimaryAllocator; #endif typedef SizeClassAllocatorLocalCache<PrimaryAllocator> AllocatorCache; typedef LargeMmapAllocator<AsanMapUnmapCallback> SecondaryAllocator; typedef CombinedAllocator<PrimaryAllocator, AllocatorCache, SecondaryAllocator> Allocator; static THREADLOCAL AllocatorCache cache; static Allocator allocator; static const uptr kMaxAllowedMallocSize = (SANITIZER_WORDSIZE == 32) ? 3UL << 30 : 8UL << 30; static int inited = 0; static void Init() { if (inited) return; __asan_init(); inited = true; // this must happen before any threads are created. allocator.Init(); } // Every chunk of memory allocated by this allocator can be in one of 3 states: // CHUNK_AVAILABLE: the chunk is in the free list and ready to be allocated. // CHUNK_ALLOCATED: the chunk is allocated and not yet freed. // CHUNK_QUARANTINE: the chunk was freed and put into quarantine zone. enum { CHUNK_AVAILABLE = 1, CHUNK_ALLOCATED = 2, CHUNK_QUARANTINE = 3 }; // The memory chunk allocated from the underlying allocator looks like this: // L L L L L L H H U U U U U U R R // L -- left redzone words (0 or more bytes) // H -- ChunkHeader (16 bytes on 64-bit arch, 8 bytes on 32-bit arch). // ChunkHeader is also a part of the left redzone. // U -- user memory. // R -- right redzone (0 or more bytes) // ChunkBase consists of ChunkHeader and other bytes that overlap with user // memory. #if SANITIZER_WORDSIZE == 64 struct ChunkBase { // 1-st 8 bytes. uptr chunk_state : 8; // Must be first. uptr alloc_tid : 24; uptr free_tid : 24; uptr from_memalign : 1; // 2-nd 8 bytes uptr user_requested_size; // Header2 (intersects with user memory). // 3-rd 8 bytes. These overlap with the user memory. AsanChunk *next; }; static const uptr kChunkHeaderSize = 16; static const uptr kChunkHeader2Size = 8; #elif SANITIZER_WORDSIZE == 32 struct ChunkBase { // 1-st 8 bytes. uptr chunk_state : 8; // Must be first. uptr from_memalign : 1; uptr alloc_tid : 23; uptr user_requested_size; // Header2 (intersects with user memory). // 2-nd 8 bytes. These overlap with the user memory. AsanChunk *next; uptr free_tid; }; static const uptr kChunkHeaderSize = 8; static const uptr kChunkHeader2Size = 8; #endif COMPILER_CHECK(sizeof(ChunkBase) == kChunkHeaderSize + kChunkHeader2Size); static uptr ComputeRZSize(uptr user_requested_size) { // FIXME: implement adaptive redzones. return flags()->redzone; } struct AsanChunk: ChunkBase { uptr Beg() { return reinterpret_cast<uptr>(this) + kChunkHeaderSize; } uptr UsedSize() { return user_requested_size; } // We store the alloc/free stack traces in the chunk itself. u32 *AllocStackBeg() { return (u32*)(Beg() - ComputeRZSize(UsedSize())); } uptr AllocStackSize() { return (ComputeRZSize(UsedSize()) - kChunkHeaderSize) / sizeof(u32); } u32 *FreeStackBeg() { return (u32*)(Beg() + kChunkHeader2Size); } uptr FreeStackSize() { uptr available = Max(RoundUpTo(UsedSize(), SHADOW_GRANULARITY), ComputeRZSize(UsedSize())); return (available - kChunkHeader2Size) / sizeof(u32); } }; uptr AsanChunkView::Beg() { return chunk_->Beg(); } uptr AsanChunkView::End() { return Beg() + UsedSize(); } uptr AsanChunkView::UsedSize() { return chunk_->UsedSize(); } uptr AsanChunkView::AllocTid() { return chunk_->alloc_tid; } uptr AsanChunkView::FreeTid() { return chunk_->free_tid; } void AsanChunkView::GetAllocStack(StackTrace *stack) { StackTrace::UncompressStack(stack, chunk_->AllocStackBeg(), chunk_->AllocStackSize()); } void AsanChunkView::GetFreeStack(StackTrace *stack) { StackTrace::UncompressStack(stack, chunk_->FreeStackBeg(), chunk_->FreeStackSize()); } static const uptr kReturnOnZeroMalloc = 0x0123; // Zero page is protected. static void *Allocate(uptr size, uptr alignment, StackTrace *stack) { Init(); CHECK(stack); if (alignment < 8) alignment = 8; if (size == 0) return reinterpret_cast<void *>(kReturnOnZeroMalloc); CHECK(IsPowerOfTwo(alignment)); uptr rz_size = ComputeRZSize(size); uptr rounded_size = RoundUpTo(size, rz_size); uptr needed_size = rounded_size + rz_size; if (alignment > rz_size) needed_size += alignment; CHECK(IsAligned(needed_size, rz_size)); if (size > kMaxAllowedMallocSize || needed_size > kMaxAllowedMallocSize) { Report("WARNING: AddressSanitizer failed to allocate %p bytes\n", (void*)size); return 0; } AsanThread *t = asanThreadRegistry().GetCurrent(); void *allocated = allocator.Allocate(&cache, needed_size, 8, false); uptr alloc_beg = reinterpret_cast<uptr>(allocated); uptr alloc_end = alloc_beg + needed_size; uptr beg_plus_redzone = alloc_beg + rz_size; uptr user_beg = beg_plus_redzone; if (!IsAligned(user_beg, alignment)) user_beg = RoundUpTo(user_beg, alignment); uptr user_end = user_beg + size; CHECK_LE(user_end, alloc_end); uptr chunk_beg = user_beg - kChunkHeaderSize; // Printf("allocated: %p beg_plus_redzone %p chunk_beg %p\n", // allocated, beg_plus_redzone, chunk_beg); AsanChunk *m = reinterpret_cast<AsanChunk *>(chunk_beg); m->chunk_state = CHUNK_ALLOCATED; u32 alloc_tid = t ? t->tid() : 0; m->alloc_tid = alloc_tid; CHECK_EQ(alloc_tid, m->alloc_tid); // Does alloc_tid fit into the bitfield? m->free_tid = kInvalidTid; m->from_memalign = user_beg != beg_plus_redzone; m->user_requested_size = size; StackTrace::CompressStack(stack, m->AllocStackBeg(), m->AllocStackSize()); uptr size_rounded_down_to_granularity = RoundDownTo(size, SHADOW_GRANULARITY); // Unpoison the bulk of the memory region. if (size_rounded_down_to_granularity) PoisonShadow(user_beg, size_rounded_down_to_granularity, 0); // Deal with the end of the region if size is not aligned to granularity. if (size != size_rounded_down_to_granularity) { u8 *shadow = (u8*)MemToShadow(user_beg + size_rounded_down_to_granularity); *shadow = size & (SHADOW_GRANULARITY - 1); } void *res = reinterpret_cast<void *>(user_beg); ASAN_MALLOC_HOOK(res, size); return res; } static void Deallocate(void *ptr, StackTrace *stack) { uptr p = reinterpret_cast<uptr>(ptr); if (p == 0 || p == kReturnOnZeroMalloc) return; uptr chunk_beg = p - kChunkHeaderSize; AsanChunk *m = reinterpret_cast<AsanChunk *>(chunk_beg); CHECK_GE(m->alloc_tid, 0); CHECK_EQ(m->free_tid, kInvalidTid); AsanThread *t = asanThreadRegistry().GetCurrent(); m->free_tid = t ? t->tid() : 0; StackTrace::CompressStack(stack, m->FreeStackBeg(), m->FreeStackSize()); uptr alloc_beg = p - ComputeRZSize(m->user_requested_size); if (m->from_memalign) alloc_beg = reinterpret_cast<uptr>(allocator.GetBlockBegin(ptr)); // Poison the region. PoisonShadow(m->Beg(), RoundUpTo(m->user_requested_size, SHADOW_GRANULARITY), kAsanHeapFreeMagic); ASAN_FREE_HOOK(ptr); if (!p) allocator.Deallocate(&cache, reinterpret_cast<void *>(alloc_beg)); } AsanChunkView FindHeapChunkByAddress(uptr address) { uptr alloc_beg = (uptr)allocator.GetBlockBegin((void*)address); return AsanChunkView((AsanChunk *)(alloc_beg + ComputeRZSize(0) - kChunkHeaderSize)); } void AsanThreadLocalMallocStorage::CommitBack() { UNIMPLEMENTED(); } SANITIZER_INTERFACE_ATTRIBUTE void *asan_memalign(uptr alignment, uptr size, StackTrace *stack) { return Allocate(size, alignment, stack); } SANITIZER_INTERFACE_ATTRIBUTE void asan_free(void *ptr, StackTrace *stack) { Deallocate(ptr, stack); } SANITIZER_INTERFACE_ATTRIBUTE void *asan_malloc(uptr size, StackTrace *stack) { return Allocate(size, 8, stack); } void *asan_calloc(uptr nmemb, uptr size, StackTrace *stack) { void *ptr = Allocate(nmemb * size, 8, stack); if (ptr) REAL(memset)(ptr, 0, nmemb * size); return 0; } void *asan_realloc(void *p, uptr size, StackTrace *stack) { if (p == 0) return Allocate(size, 8, stack); if (size == 0) { Deallocate(p, stack); return 0; } UNIMPLEMENTED(); // return Reallocate((u8*)p, size, stack); } void *asan_valloc(uptr size, StackTrace *stack) { return Allocate(size, GetPageSizeCached(), stack); } void *asan_pvalloc(uptr size, StackTrace *stack) { uptr PageSize = GetPageSizeCached(); size = RoundUpTo(size, PageSize); if (size == 0) { // pvalloc(0) should allocate one page. size = PageSize; } return Allocate(size, PageSize, stack); } int asan_posix_memalign(void **memptr, uptr alignment, uptr size, StackTrace *stack) { void *ptr = Allocate(size, alignment, stack); CHECK(IsAligned((uptr)ptr, alignment)); *memptr = ptr; return 0; } uptr asan_malloc_usable_size(void *ptr, StackTrace *stack) { UNIMPLEMENTED(); return 0; } uptr asan_mz_size(const void *ptr) { UNIMPLEMENTED(); return 0; } void asan_mz_force_lock() { UNIMPLEMENTED(); } void asan_mz_force_unlock() { UNIMPLEMENTED(); } } // namespace __asan // ---------------------- Interface ---------------- {{{1 using namespace __asan; // NOLINT // ASan allocator doesn't reserve extra bytes, so normally we would // just return "size". uptr __asan_get_estimated_allocated_size(uptr size) { UNIMPLEMENTED(); return 0; } bool __asan_get_ownership(const void *p) { UNIMPLEMENTED(); return false; } uptr __asan_get_allocated_size(const void *p) { UNIMPLEMENTED(); return 0; } #if !SANITIZER_SUPPORTS_WEAK_HOOKS // Provide default (no-op) implementation of malloc hooks. extern "C" { SANITIZER_WEAK_ATTRIBUTE SANITIZER_INTERFACE_ATTRIBUTE void __asan_malloc_hook(void *ptr, uptr size) { (void)ptr; (void)size; } SANITIZER_WEAK_ATTRIBUTE SANITIZER_INTERFACE_ATTRIBUTE void __asan_free_hook(void *ptr) { (void)ptr; } } // extern "C" #endif #endif // ASAN_ALLOCATOR_VERSION
implement free() stacks and actually make malloc/free stacks work
[asan] asan_alocator2: implement free() stacks and actually make malloc/free stacks work git-svn-id: c199f293c43da69278bea8e88f92242bf3aa95f7@170310 91177308-0d34-0410-b5e6-96231b3b80d8
C++
apache-2.0
llvm-mirror/compiler-rt,llvm-mirror/compiler-rt,llvm-mirror/compiler-rt,llvm-mirror/compiler-rt,llvm-mirror/compiler-rt
e85aea8f00ae43a623156720ec7e9c33df993f39
chrome/test/chromedriver/chrome/chrome_finder.cc
chrome/test/chromedriver/chrome/chrome_finder.cc
// Copyright (c) 2012 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chrome/test/chromedriver/chrome/chrome_finder.h" #include <string> #include <vector> #include "base/base_paths.h" #include "base/bind.h" #include "base/callback.h" #include "base/file_util.h" #include "base/files/file_path.h" #include "base/path_service.h" #include "build/build_config.h" #if defined(OS_WIN) #include "base/base_paths_win.h" #include "base/win/windows_version.h" #endif namespace { #if defined(OS_WIN) void GetApplicationDirs(std::vector<base::FilePath>* locations) { std::vector<base::FilePath> installation_locations; base::FilePath local_app_data, program_files, program_files_x86; if (PathService::Get(base::DIR_LOCAL_APP_DATA, &local_app_data)) installation_locations.push_back(local_app_data); if (PathService::Get(base::DIR_PROGRAM_FILES, &program_files)) installation_locations.push_back(program_files); if (PathService::Get(base::DIR_PROGRAM_FILESX86, &program_files_x86)) installation_locations.push_back(program_files_x86); for (size_t i = 0; i < installation_locations.size(); ++i) { locations->push_back( installation_locations[i].Append(L"Google\\Chrome\\Application")); } for (size_t i = 0; i < installation_locations.size(); ++i) { locations->push_back( installation_locations[i].Append(L"Chromium\\Application")); } } #elif defined(OS_LINUX) void GetApplicationDirs(std::vector<base::FilePath>* locations) { locations->push_back(base::FilePath("/opt/google/chrome")); locations->push_back(base::FilePath("/usr/local/bin")); locations->push_back(base::FilePath("/usr/local/sbin")); locations->push_back(base::FilePath("/usr/bin")); locations->push_back(base::FilePath("/usr/sbin")); locations->push_back(base::FilePath("/bin")); locations->push_back(base::FilePath("/sbin")); } #endif } // namespace namespace internal { bool FindExe( const base::Callback<bool(const base::FilePath&)>& exists_func, const std::vector<base::FilePath>& rel_paths, const std::vector<base::FilePath>& locations, base::FilePath* out_path) { for (size_t i = 0; i < rel_paths.size(); ++i) { for (size_t j = 0; j < locations.size(); ++j) { base::FilePath path = locations[j].Append(rel_paths[i]); if (exists_func.Run(path)) { *out_path = path; return true; } } } return false; } } // namespace internal #if defined(OS_MACOSX) void GetApplicationDirs(std::vector<base::FilePath>* locations); #endif bool FindChrome(base::FilePath* browser_exe) { #if defined(OS_WIN) base::FilePath browser_exes_array[] = { base::FilePath(L"nw.exe") }; #elif defined(OS_MACOSX) base::FilePath browser_exes_array[] = { base::FilePath("node-webkit") }; #elif defined(OS_LINUX) base::FilePath browser_exes_array[] = { base::FilePath("nw") }; #endif std::vector<base::FilePath> browser_exes( browser_exes_array, browser_exes_array + arraysize(browser_exes_array)); std::vector<base::FilePath> locations; base::FilePath exe_path; PathService::Get(base::DIR_EXE, &exe_path); locations.push_back(exe_path); return internal::FindExe( base::Bind(&base::PathExists), browser_exes, locations, browser_exe); }
// 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 "chrome/test/chromedriver/chrome/chrome_finder.h" #include <string> #include <vector> #include "base/base_paths.h" #include "base/bind.h" #include "base/callback.h" #include "base/file_util.h" #include "base/files/file_path.h" #include "base/path_service.h" #include "build/build_config.h" #if defined(OS_WIN) #include "base/base_paths_win.h" #include "base/win/windows_version.h" #endif namespace { #if defined(OS_WIN) void GetApplicationDirs(std::vector<base::FilePath>* locations) { std::vector<base::FilePath> installation_locations; base::FilePath local_app_data, program_files, program_files_x86; if (PathService::Get(base::DIR_LOCAL_APP_DATA, &local_app_data)) installation_locations.push_back(local_app_data); if (PathService::Get(base::DIR_PROGRAM_FILES, &program_files)) installation_locations.push_back(program_files); if (PathService::Get(base::DIR_PROGRAM_FILESX86, &program_files_x86)) installation_locations.push_back(program_files_x86); for (size_t i = 0; i < installation_locations.size(); ++i) { locations->push_back( installation_locations[i].Append(L"Google\\Chrome\\Application")); } for (size_t i = 0; i < installation_locations.size(); ++i) { locations->push_back( installation_locations[i].Append(L"Chromium\\Application")); } } #elif defined(OS_LINUX) void GetApplicationDirs(std::vector<base::FilePath>* locations) { locations->push_back(base::FilePath("/opt/google/chrome")); locations->push_back(base::FilePath("/usr/local/bin")); locations->push_back(base::FilePath("/usr/local/sbin")); locations->push_back(base::FilePath("/usr/bin")); locations->push_back(base::FilePath("/usr/sbin")); locations->push_back(base::FilePath("/bin")); locations->push_back(base::FilePath("/sbin")); } #endif } // namespace namespace internal { bool FindExe( const base::Callback<bool(const base::FilePath&)>& exists_func, const std::vector<base::FilePath>& rel_paths, const std::vector<base::FilePath>& locations, base::FilePath* out_path) { for (size_t i = 0; i < rel_paths.size(); ++i) { for (size_t j = 0; j < locations.size(); ++j) { base::FilePath path = locations[j].Append(rel_paths[i]); if (exists_func.Run(path)) { *out_path = path; return true; } } } return false; } } // namespace internal #if defined(OS_MACOSX) void GetApplicationDirs(std::vector<base::FilePath>* locations); #endif bool FindChrome(base::FilePath* browser_exe) { #if defined(OS_WIN) base::FilePath browser_exes_array[] = { base::FilePath(L"nw.exe") }; #elif defined(OS_MACOSX) base::FilePath browser_exes_array[] = { base::FilePath("node-webkit.app/Contents/MacOS/node-webkit") }; #elif defined(OS_LINUX) base::FilePath browser_exes_array[] = { base::FilePath("nw") }; #endif std::vector<base::FilePath> browser_exes( browser_exes_array, browser_exes_array + arraysize(browser_exes_array)); std::vector<base::FilePath> locations; base::FilePath exe_path; PathService::Get(base::DIR_EXE, &exe_path); locations.push_back(exe_path); return internal::FindExe( base::Bind(&base::PathExists), browser_exes, locations, browser_exe); }
fix OSX path for chrome finder
[chromedriver] fix OSX path for chrome finder
C++
bsd-3-clause
patrickm/chromium.src,patrickm/chromium.src,littlstar/chromium.src,littlstar/chromium.src,littlstar/chromium.src,patrickm/chromium.src,ondra-novak/chromium.src,littlstar/chromium.src,littlstar/chromium.src,littlstar/chromium.src,patrickm/chromium.src,ondra-novak/chromium.src,patrickm/chromium.src,littlstar/chromium.src,ondra-novak/chromium.src,patrickm/chromium.src,patrickm/chromium.src,ondra-novak/chromium.src,ondra-novak/chromium.src,patrickm/chromium.src,ondra-novak/chromium.src,ondra-novak/chromium.src,littlstar/chromium.src,ondra-novak/chromium.src,ondra-novak/chromium.src,patrickm/chromium.src
bfc5e43d1370e27591791c6c77dbd788a0bd7748
code/utils/communication/ClientCommandSender.cpp
code/utils/communication/ClientCommandSender.cpp
#include <string> #include "ClientCommandSender.h" #include "ClientSocket.h" #include "SocketUtils.h" namespace fs_testing { namespace utils { namespace communication { using std::string; ClientCommandSender::ClientCommandSender( string socket_addr, SocketMessage::CmCommand send, SocketMessage::CmCommand recv) : socket_address(socket_addr), send_command(send), return_command(recv), conn(ClientSocket(socket_address)) {} int ClientCommandSender::Run() { if (conn.Init() < 0) { return -1; } if (conn.SendCommand(send_command) != SocketError::kNone) { return -2; } SocketMessage ret; if (conn.WaitForMessage(&ret) != SocketError::kNone) { return -3; } return ret.type == return_command; } } // namesapce communication } // namesapce utils } // namesapce fs_testing
#include <string> #include "ClientCommandSender.h" #include "ClientSocket.h" #include "SocketUtils.h" namespace fs_testing { namespace utils { namespace communication { using std::string; ClientCommandSender::ClientCommandSender( string socket_addr, SocketMessage::CmCommand send, SocketMessage::CmCommand recv) : socket_address(socket_addr), send_command(send), return_command(recv), conn(ClientSocket(socket_address)) {} int ClientCommandSender::Run() { if (conn.Init() < 0) { return -1; } if (conn.SendCommand(send_command) != SocketError::kNone) { return -2; } SocketMessage ret; if (conn.WaitForMessage(&ret) != SocketError::kNone) { return -3; } return !(ret.type == return_command); } } // namesapce communication } // namesapce utils } // namesapce fs_testing
Fix return code bug.
Fix return code bug.
C++
apache-2.0
utsaslab/crashmonkey,utsaslab/crashmonkey,utsaslab/crashmonkey,utsaslab/crashmonkey
9aacb623db93e0b2db9d4aaa5684e62ad3a132ea
src/postgres/backend/postmaster/memcached.cpp
src/postgres/backend/postmaster/memcached.cpp
// https://github.com/memcached/memcached/blob/master/doc/protocol.txt // setup prepared statements // GET, SET, ADD, REPLACE, DELETE, CAS, INCR, DECR, APPEND, PREPEND // FLUSH_ALL, STATS, VERSION, VERBOSITY not implemented // TODO directly return response from sql as defined in Memcached protocol // TODO CAS semantic: gets -> unique_cas_token int setup() { std::string setup = " DROP TABLE test; CREATE TABLE test ( k VARCHAR(40) PRIMARY KEY, v VARCHAR(400) ); DEALLOCATE GET; PREPARE GET (text) AS SELECT d FROM TEST WHERE k = $1; DEALLOCATE SET; PREPARE SET (text, text) AS INSERT INTO test (k, v) VALUES ($1, $2) ON CONFLICT (k) DO UPDATE SET v = excluded.v; DEALLOCATE ADD; PREPARE ADD (text, text) AS INSERT INTO test (k, v) VALUES ($1, $2) ON CONFLICT (k) DO UPDATE SET v = excluded.v; DEALLOCATE REPLACE; PREPARE REPLACE (text, text) AS UPDATE test SET v = $2 WHERE k=$1; DEALLOCATE APPEND; PREPARE APPEND (text, text) AS UPDATE test SET v=CONCAT(v,$2) WHERE k=$1; DEALLOCATE PREPEND; PREPARE PREPEND (text, text) AS UPDATE test SET v=CONCAT($2,v) WHERE k=$1; DEALLOCATE INCR; PREPARE INCR (text) AS UPDATE test SET v=CAST(v as int)+1 WHERE k=$1; DEALLOCATE DECR; PREPARE DECR (text) AS UPDATE test SET v=CAST(v as int)+1 WHERE k=$1; DEALLOCATE DELETE; PREPARE DELETE (text) AS DELETE FROM test WHERE k=$1; DEALLOCATE CAS; PREPARE CAS (text, text, text) AS UPDATE test SET v = case when v = '' then 'Y' else 'N' end; " } int get(std::string &key, std::string &value) { std::string queryString = "EXECUTE SET (,)"; } int get(std::string &key, std::string &value) { }
// https://github.com/memcached/memcached/blob/master/doc/protocol.txt // setup prepared statements // GET, SET, ADD, REPLACE, DELETE, CAS, INCR, DECR, APPEND, PREPEND // FLUSH_ALL, STATS, VERSION, VERBOSITY not implemented // TODO directly return response from sql as defined in Memcached protocol // TODO CAS semantic: gets -> unique_cas_token int setup() { // " // CREATE FUNCTION test() RETURNS varchar AS $$ // select * from test // RETURNING 'ab'; // $$ LANGUAGE SQL; // " std::string setup = " DROP TABLE test; CREATE TABLE test ( key VARCHAR(200) PRIMARY KEY, value VARCHAR(2048), flag smallint, size smallint ); DEALLOCATE GET; PREPARE GET (text) AS SELECT key, value, flag, size FROM TEST WHERE key = $1; DEALLOCATE SET; PREPARE SET (text, text, smallint, smallint) AS INSERT INTO test (key, value, flag, size) VALUES ($1, $2, $3, $4) ON CONFLICT (key) DO UPDATE SET value = excluded.value, flag = excluded.flag, size = excluded.size; DEALLOCATE ADD; PREPARE ADD (text, text, smallint, smallint) AS INSERT INTO test (key, value, flag, size) VALUES ($1, $2, $3, $4) ON CONFLICT (key) DO UPDATE SET value = excluded.value, flag = excluded.flag, size = excluded.size; DEALLOCATE REPLACE; PREPARE REPLACE (text, text, smallint, smallint) AS UPDATE test SET value = $2, flag = $3, size = $4 WHERE key=$1; " std::string not_needed = " DEALLOCATE APPEND; PREPARE APPEND (text, text) AS UPDATE test SET value=CONCAT(value,$2) WHERE key=$1; DEALLOCATE PREPEND; PREPARE PREPEND (text, text) AS UPDATE test SET value=CONCAT($2,value) WHERE key=$1; DEALLOCATE INCR; PREPARE INCR (text) AS UPDATE test SET value=CAST(value as int)+1 WHERE key=$1; DEALLOCATE DECR; PREPARE DECR (text) AS UPDATE test SET value=CAST(value as int)+1 WHERE key=$1; DEALLOCATE DELETE; PREPARE DELETE (text) AS DELETE FROM test WHERE key=$1; DEALLOCATE CAS; PREPARE CAS (text, text, text) AS UPDATE test SET value = case when v = '' then 'Y' else 'N' end; " } int get(std::string &key, std::string &value) { std::string queryString = "EXECUTE SET (,)"; } int get(std::string &key, std::string &value) { }
update schema and prepared statement for Memcached
update schema and prepared statement for Memcached
C++
apache-2.0
malin1993ml/peloton,phisiart/peloton-p3,jessesleeping/iso_peloton,yingjunwu/peloton,eric-haibin-lin/peloton-1,PauloAmora/peloton,AllisonWang/peloton,cmu-db/peloton,haojin2/peloton,apavlo/peloton,cmu-db/peloton,haojin2/peloton,vittvolt/peloton,phisiart/peloton-p3,eric-haibin-lin/peloton-1,prashasthip/peloton,haojin2/peloton,ShuxinLin/peloton,vittvolt/15721-peloton,wangziqi2016/peloton,ShuxinLin/peloton,jessesleeping/iso_peloton,ShuxinLin/peloton,prashasthip/peloton,phisiart/peloton-p3,eric-haibin-lin/peloton-1,AllisonWang/peloton,jessesleeping/iso_peloton,seojungmin/peloton,PauloAmora/peloton,yingjunwu/peloton,seojungmin/peloton,seojungmin/peloton,yingjunwu/peloton,vittvolt/peloton,phisiart/peloton-p3,ShuxinLin/peloton,seojungmin/peloton,malin1993ml/peloton,AngLi-Leon/peloton,prashasthip/peloton,vittvolt/15721-peloton,yingjunwu/peloton,ShuxinLin/peloton,apavlo/peloton,haojin2/peloton,PauloAmora/peloton,wangziqi2016/peloton,AngLi-Leon/peloton,AngLi-Leon/peloton,PauloAmora/peloton,malin1993ml/peloton,apavlo/peloton,cmu-db/peloton,vittvolt/peloton,yingjunwu/peloton,malin1993ml/peloton,AllisonWang/peloton,PauloAmora/peloton,vittvolt/15721-peloton,AllisonWang/peloton,malin1993ml/peloton,yingjunwu/peloton,PauloAmora/peloton,seojungmin/peloton,eric-haibin-lin/peloton-1,apavlo/peloton,eric-haibin-lin/peloton-1,haojin2/peloton,jessesleeping/iso_peloton,vittvolt/peloton,jessesleeping/iso_peloton,apavlo/peloton,prashasthip/peloton,AngLi-Leon/peloton,AllisonWang/peloton,AngLi-Leon/peloton,phisiart/peloton-p3,wangziqi2016/peloton,jessesleeping/iso_peloton,malin1993ml/peloton,haojin2/peloton,ShuxinLin/peloton,vittvolt/15721-peloton,cmu-db/peloton,seojungmin/peloton,wangziqi2016/peloton,vittvolt/15721-peloton,AllisonWang/peloton,prashasthip/peloton,cmu-db/peloton,AngLi-Leon/peloton,eric-haibin-lin/peloton-1,cmu-db/peloton,wangziqi2016/peloton,phisiart/peloton-p3,vittvolt/peloton,apavlo/peloton,vittvolt/peloton,prashasthip/peloton,vittvolt/15721-peloton,jessesleeping/iso_peloton,wangziqi2016/peloton
abb9a02cd7f2dce97e248ebb0e7d4ce351c3a189
src/vistk/pipeline_util/pipe_bakery_exception.cxx
src/vistk/pipeline_util/pipe_bakery_exception.cxx
/*ckwg +5 * Copyright 2011 by Kitware, Inc. All Rights Reserved. Please refer to * KITWARE_LICENSE.TXT for licensing information, or contact General Counsel, * Kitware, Inc., 28 Corporate Drive, Clifton Park, NY 12065. */ #include "pipe_bakery_exception.h" #include <sstream> /** * \file pipe_bakery_exception.cxx * * \brief Implementations of exceptions used when baking a pipeline. */ namespace vistk { unrecognized_config_flag_exception ::unrecognized_config_flag_exception(config::key_t const& key, config_flag_t const& flag) throw() : pipe_bakery_exception() , m_key(key) , m_flag(flag) { std::stringstream sstr; sstr << "The \'" << m_key << "\' key " "has the \'" << m_flag << "\' on it " "which is unrecognized"; m_what = sstr.str(); } unrecognized_config_flag_exception ::~unrecognized_config_flag_exception() throw() { } unrecognized_provider_exception ::unrecognized_provider_exception(config::key_t const& key, config_provider_t const& provider, config::value_t const& index) throw() : pipe_bakery_exception() , m_key(key) , m_provider(provider) , m_index(index) { std::stringstream sstr; sstr << "The \'" << m_key << "\' key " "is requesting the index \'" << m_index << "\' " "from the unrecognized \'" << m_provider << "\'"; m_what = sstr.str(); } unrecognized_provider_exception ::~unrecognized_provider_exception() throw() { } circular_config_provide_exception ::circular_config_provide_exception() throw() : pipe_bakery_exception() { std::stringstream sstr; sstr << "There is a circular config provide request in the configuration"; m_what = sstr.str(); } circular_config_provide_exception ::~circular_config_provide_exception() throw() { } unrecognized_system_index_exception ::unrecognized_system_index_exception(config::value_t const& index) throw() : pipe_bakery_exception() , m_index(index) { std::stringstream sstr; sstr << "The \'" << m_index << "\' index " "does not exist for the system provider"; m_what = sstr.str(); } unrecognized_system_index_exception ::~unrecognized_system_index_exception() throw() { } }
/*ckwg +5 * Copyright 2011-2012 by Kitware, Inc. All Rights Reserved. Please refer to * KITWARE_LICENSE.TXT for licensing information, or contact General Counsel, * Kitware, Inc., 28 Corporate Drive, Clifton Park, NY 12065. */ #include "pipe_bakery_exception.h" #include <sstream> /** * \file pipe_bakery_exception.cxx * * \brief Implementations of exceptions used when baking a pipeline. */ namespace vistk { unrecognized_config_flag_exception ::unrecognized_config_flag_exception(config::key_t const& key, config_flag_t const& flag) throw() : pipe_bakery_exception() , m_key(key) , m_flag(flag) { std::stringstream sstr; sstr << "The \'" << m_key << "\' key " "has the \'" << m_flag << "\' on it " "which is unrecognized"; m_what = sstr.str(); } unrecognized_config_flag_exception ::~unrecognized_config_flag_exception() throw() { } unrecognized_provider_exception ::unrecognized_provider_exception(config::key_t const& key, config_provider_t const& provider, config::value_t const& index) throw() : pipe_bakery_exception() , m_key(key) , m_provider(provider) , m_index(index) { std::stringstream sstr; sstr << "The \'" << m_key << "\' key " "is requesting the index \'" << m_index << "\' " "from the unrecognized \'" << m_provider << "\'"; m_what = sstr.str(); } unrecognized_provider_exception ::~unrecognized_provider_exception() throw() { } circular_config_provide_exception ::circular_config_provide_exception() throw() : pipe_bakery_exception() { std::stringstream sstr; sstr << "There is a circular CONF provider request in the configuration"; m_what = sstr.str(); } circular_config_provide_exception ::~circular_config_provide_exception() throw() { } unrecognized_system_index_exception ::unrecognized_system_index_exception(config::value_t const& index) throw() : pipe_bakery_exception() , m_index(index) { std::stringstream sstr; sstr << "The \'" << m_index << "\' index " "does not exist for the SYS provider"; m_what = sstr.str(); } unrecognized_system_index_exception ::~unrecognized_system_index_exception() throw() { } }
Fix up exception messages
Fix up exception messages
C++
bsd-3-clause
mathstuf/sprokit,linus-sherrill/sprokit,Kitware/sprokit,Kitware/sprokit,linus-sherrill/sprokit,mathstuf/sprokit,mathstuf/sprokit,linus-sherrill/sprokit,mathstuf/sprokit,linus-sherrill/sprokit,Kitware/sprokit,Kitware/sprokit
b5375d537cc82986e807e28a2c33cadd50c2e264
src/xercesc/validators/common/ContentSpecNode.cpp
src/xercesc/validators/common/ContentSpecNode.cpp
/* * 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$ */ // --------------------------------------------------------------------------- // Includes // --------------------------------------------------------------------------- #include <xercesc/framework/XMLBuffer.hpp> #include <xercesc/validators/common/ContentSpecNode.hpp> #include <xercesc/validators/schema/SchemaSymbols.hpp> #include <xercesc/util/ValueStackOf.hpp> XERCES_CPP_NAMESPACE_BEGIN // --------------------------------------------------------------------------- // ContentSpecNode: Copy Constructor // // Note: this copy constructor has dependency on various get*() methods // and shall be placed after those method's declaration. // aka inline function compilation error on AIX 4.2, xlC 3 r ev.1 // --------------------------------------------------------------------------- ContentSpecNode::ContentSpecNode(const ContentSpecNode& toCopy) : XSerializable(toCopy) , XMemory(toCopy) , fMemoryManager(toCopy.fMemoryManager) , fElement(0) , fElementDecl(toCopy.fElementDecl) , fFirst(0) , fSecond(0) , fType(toCopy.fType) , fAdoptFirst(true) , fAdoptSecond(true) , fMinOccurs(toCopy.fMinOccurs) , fMaxOccurs(toCopy.fMaxOccurs) { const QName* tempElement = toCopy.getElement(); if (tempElement) fElement = new (fMemoryManager) QName(*tempElement); const ContentSpecNode *tmp = toCopy.getFirst(); if (tmp) fFirst = new (fMemoryManager) ContentSpecNode(*tmp); tmp = toCopy.getSecond(); if (tmp) fSecond = new (fMemoryManager) ContentSpecNode(*tmp); } ContentSpecNode::~ContentSpecNode() { // Delete our children, avoiding recursive cleanup if (fAdoptFirst && fFirst) { deleteChildNode(fFirst); } if (fAdoptSecond && fSecond) { deleteChildNode(fSecond); } delete fElement; } void ContentSpecNode::deleteChildNode(ContentSpecNode* node) { ValueStackOf<ContentSpecNode*> toBeDeleted(10, fMemoryManager); toBeDeleted.push(node); while(!toBeDeleted.empty()) { ContentSpecNode* node = toBeDeleted.pop(); if(node==0) continue; if(node->isFirstAdopted()) toBeDeleted.push(node->orphanFirst()); if(node->isSecondAdopted()) toBeDeleted.push(node->orphanSecond()); delete node; } } class formatNodeHolder { public: formatNodeHolder(const ContentSpecNode* n, const ContentSpecNode::NodeTypes p, XMLCh c) : node(n), parentType(p), character(c) {} formatNodeHolder& operator =(const formatNodeHolder* other) { node=other->node; parentType=other->parentType; character=other->character; } const ContentSpecNode* node; ContentSpecNode::NodeTypes parentType; XMLCh character; }; // --------------------------------------------------------------------------- // Local methods // --------------------------------------------------------------------------- static void formatNode( const ContentSpecNode* const curNode , XMLBuffer& bufToFill , MemoryManager* const memMgr) { if (!curNode) return; ValueStackOf<formatNodeHolder> toBeProcessed(10, memMgr); toBeProcessed.push(formatNodeHolder(curNode, ContentSpecNode::UnknownType, 0)); while(!toBeProcessed.empty()) { formatNodeHolder item=toBeProcessed.pop(); if(item.character!=0) { bufToFill.append(item.character); continue; } const ContentSpecNode* curNode = item.node; if(!curNode) continue; const ContentSpecNode::NodeTypes parentType = item.parentType; const ContentSpecNode* first = curNode->getFirst(); const ContentSpecNode* second = curNode->getSecond(); const ContentSpecNode::NodeTypes curType = curNode->getType(); // Get the type of the first node const ContentSpecNode::NodeTypes firstType = first ? first->getType() : ContentSpecNode::Leaf; // Calculate the parens flag for the rep nodes bool doRepParens = false; if (((firstType != ContentSpecNode::Leaf) && (parentType != ContentSpecNode::UnknownType)) || ((firstType == ContentSpecNode::Leaf) && (parentType == ContentSpecNode::UnknownType))) { doRepParens = true; } // Now handle our type switch(curType & 0x0f) { case ContentSpecNode::Leaf : if (curNode->getElement()->getURI() == XMLElementDecl::fgPCDataElemId) bufToFill.append(XMLElementDecl::fgPCDataElemName); else { bufToFill.append(curNode->getElement()->getRawName()); // show the + and * modifiers also when we have a non-infinite number of repetitions if(curNode->getMinOccurs()==0 && (curNode->getMaxOccurs()==-1 || curNode->getMaxOccurs()>1)) bufToFill.append(chAsterisk); else if(curNode->getMinOccurs()==0 && curNode->getMaxOccurs()==1) bufToFill.append(chQuestion); else if(curNode->getMinOccurs()==1 && (curNode->getMaxOccurs()==-1 || curNode->getMaxOccurs()>1)) bufToFill.append(chPlus); } break; case ContentSpecNode::ZeroOrOne : if (doRepParens) bufToFill.append(chOpenParen); toBeProcessed.push(formatNodeHolder(0, ContentSpecNode::UnknownType, chQuestion)); if (doRepParens) toBeProcessed.push(formatNodeHolder(0, ContentSpecNode::UnknownType, chCloseParen)); toBeProcessed.push(formatNodeHolder(first, curType, 0)); break; case ContentSpecNode::ZeroOrMore : if (doRepParens) bufToFill.append(chOpenParen); toBeProcessed.push(formatNodeHolder(0, ContentSpecNode::UnknownType, chAsterisk)); if (doRepParens) toBeProcessed.push(formatNodeHolder(0, ContentSpecNode::UnknownType, chCloseParen)); toBeProcessed.push(formatNodeHolder(first, curType, 0)); break; case ContentSpecNode::OneOrMore : if (doRepParens) bufToFill.append(chOpenParen); toBeProcessed.push(formatNodeHolder(0, ContentSpecNode::UnknownType, chPlus)); if (doRepParens) toBeProcessed.push(formatNodeHolder(0, ContentSpecNode::UnknownType, chCloseParen)); toBeProcessed.push(formatNodeHolder(first, curType, 0)); break; case ContentSpecNode::Choice : if ((parentType & 0x0f) != (curType & 0x0f)) bufToFill.append(chOpenParen); if ((parentType & 0x0f) != (curType & 0x0f)) toBeProcessed.push(formatNodeHolder(0, ContentSpecNode::UnknownType, chCloseParen)); if(second!=NULL) { toBeProcessed.push(formatNodeHolder(second, curType, 0)); toBeProcessed.push(formatNodeHolder(0, ContentSpecNode::UnknownType, chPipe)); } toBeProcessed.push(formatNodeHolder(first, curType, 0)); break; case ContentSpecNode::Sequence : if ((parentType & 0x0f) != (curType & 0x0f)) bufToFill.append(chOpenParen); if ((parentType & 0x0f) != (curType & 0x0f)) toBeProcessed.push(formatNodeHolder(0, ContentSpecNode::UnknownType, chCloseParen)); if(second!=NULL) { toBeProcessed.push(formatNodeHolder(second, curType, 0)); toBeProcessed.push(formatNodeHolder(0, ContentSpecNode::UnknownType, chComma)); } toBeProcessed.push(formatNodeHolder(first, curType, 0)); break; case ContentSpecNode::All : if ((parentType & 0x0f) != (curType & 0x0f)) { bufToFill.append(chLatin_A); bufToFill.append(chLatin_l); bufToFill.append(chLatin_l); bufToFill.append(chOpenParen); } if ((parentType & 0x0f) != (curType & 0x0f)) toBeProcessed.push(formatNodeHolder(0, ContentSpecNode::UnknownType, chCloseParen)); toBeProcessed.push(formatNodeHolder(second, curType, 0)); toBeProcessed.push(formatNodeHolder(0, ContentSpecNode::UnknownType, chComma)); toBeProcessed.push(formatNodeHolder(first, curType, 0)); break; } } } // --------------------------------------------------------------------------- // ContentSpecNode: Miscellaneous // --------------------------------------------------------------------------- void ContentSpecNode::formatSpec(XMLBuffer& bufToFill) const { // Clean out the buffer first bufToFill.reset(); if (fType == ContentSpecNode::Leaf) bufToFill.append(chOpenParen); formatNode ( this , bufToFill , fMemoryManager ); if (fType == ContentSpecNode::Leaf) bufToFill.append(chCloseParen); } int ContentSpecNode::getMinTotalRange() const { int min = fMinOccurs; if ((fType & 0x0f) == ContentSpecNode::Sequence || fType == ContentSpecNode::All || (fType & 0x0f) == ContentSpecNode::Choice) { int minFirst = fFirst->getMinTotalRange(); if (fSecond) { int minSecond = fSecond->getMinTotalRange(); if ((fType & 0x0f) == ContentSpecNode::Choice) { min = min * ((minFirst < minSecond)? minFirst : minSecond); } else { min = min * (minFirst + minSecond); } } else min = min * minFirst; } return min; } int ContentSpecNode::getMaxTotalRange() const { int max = fMaxOccurs; if (max == SchemaSymbols::XSD_UNBOUNDED) { return SchemaSymbols::XSD_UNBOUNDED; } if ((fType & 0x0f) == ContentSpecNode::Sequence || fType == ContentSpecNode::All || (fType & 0x0f) == ContentSpecNode::Choice) { int maxFirst = fFirst->getMaxTotalRange(); if (maxFirst == SchemaSymbols::XSD_UNBOUNDED) { return SchemaSymbols::XSD_UNBOUNDED; } if (fSecond) { int maxSecond = fSecond->getMaxTotalRange(); if (maxSecond == SchemaSymbols::XSD_UNBOUNDED) { return SchemaSymbols::XSD_UNBOUNDED; } else { if ((fType & 0x0f) == ContentSpecNode::Choice) { max = max * (maxFirst > maxSecond) ? maxFirst : maxSecond; } else { max = max * (maxFirst + maxSecond); } } } else { max = max * maxFirst; } } return max; } /*** * Support for Serialization/De-serialization ***/ IMPL_XSERIALIZABLE_TOCREATE(ContentSpecNode) void ContentSpecNode::serialize(XSerializeEngine& serEng) { /*** * Since fElement, fFirst, fSecond are NOT created by the default * constructor, we need to create them dynamically. ***/ if (serEng.isStoring()) { serEng<<fElement; XMLElementDecl::storeElementDecl(serEng, fElementDecl); serEng<<fFirst; serEng<<fSecond; serEng<<(int)fType; serEng<<fAdoptFirst; serEng<<fAdoptSecond; serEng<<fMinOccurs; serEng<<fMaxOccurs; } else { serEng>>fElement; fElementDecl = XMLElementDecl::loadElementDecl(serEng); serEng>>fFirst; serEng>>fSecond; int type; serEng>>type; fType = (NodeTypes)type; serEng>>fAdoptFirst; serEng>>fAdoptSecond; serEng>>fMinOccurs; serEng>>fMaxOccurs; } } XERCES_CPP_NAMESPACE_END
/* * 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$ */ // --------------------------------------------------------------------------- // Includes // --------------------------------------------------------------------------- #include <xercesc/framework/XMLBuffer.hpp> #include <xercesc/validators/common/ContentSpecNode.hpp> #include <xercesc/validators/schema/SchemaSymbols.hpp> #include <xercesc/util/ValueStackOf.hpp> XERCES_CPP_NAMESPACE_BEGIN // --------------------------------------------------------------------------- // ContentSpecNode: Copy Constructor // // Note: this copy constructor has dependency on various get*() methods // and shall be placed after those method's declaration. // aka inline function compilation error on AIX 4.2, xlC 3 r ev.1 // --------------------------------------------------------------------------- ContentSpecNode::ContentSpecNode(const ContentSpecNode& toCopy) : XSerializable(toCopy) , XMemory(toCopy) , fMemoryManager(toCopy.fMemoryManager) , fElement(0) , fElementDecl(toCopy.fElementDecl) , fFirst(0) , fSecond(0) , fType(toCopy.fType) , fAdoptFirst(true) , fAdoptSecond(true) , fMinOccurs(toCopy.fMinOccurs) , fMaxOccurs(toCopy.fMaxOccurs) { const QName* tempElement = toCopy.getElement(); if (tempElement) fElement = new (fMemoryManager) QName(*tempElement); const ContentSpecNode *tmp = toCopy.getFirst(); if (tmp) fFirst = new (fMemoryManager) ContentSpecNode(*tmp); tmp = toCopy.getSecond(); if (tmp) fSecond = new (fMemoryManager) ContentSpecNode(*tmp); } ContentSpecNode::~ContentSpecNode() { // Delete our children, avoiding recursive cleanup if (fAdoptFirst && fFirst) { deleteChildNode(fFirst); } if (fAdoptSecond && fSecond) { deleteChildNode(fSecond); } delete fElement; } void ContentSpecNode::deleteChildNode(ContentSpecNode* node) { ValueStackOf<ContentSpecNode*> toBeDeleted(10, fMemoryManager); toBeDeleted.push(node); while(!toBeDeleted.empty()) { ContentSpecNode* node = toBeDeleted.pop(); if(node==0) continue; if(node->isFirstAdopted()) toBeDeleted.push(node->orphanFirst()); if(node->isSecondAdopted()) toBeDeleted.push(node->orphanSecond()); delete node; } } class formatNodeHolder { public: formatNodeHolder(const ContentSpecNode* n, const ContentSpecNode::NodeTypes p, XMLCh c) : node(n), parentType(p), character(c) {} formatNodeHolder& operator =(const formatNodeHolder* other) { node=other->node; parentType=other->parentType; character=other->character; } const ContentSpecNode* node; ContentSpecNode::NodeTypes parentType; XMLCh character; }; // --------------------------------------------------------------------------- // Local methods // --------------------------------------------------------------------------- static void formatNode( const ContentSpecNode* const curNode , XMLBuffer& bufToFill , MemoryManager* const memMgr) { if (!curNode) return; ValueStackOf<formatNodeHolder> toBeProcessed(10, memMgr); toBeProcessed.push(formatNodeHolder(curNode, ContentSpecNode::UnknownType, 0)); while(!toBeProcessed.empty()) { formatNodeHolder item=toBeProcessed.pop(); if(item.character!=0) { bufToFill.append(item.character); continue; } const ContentSpecNode* curNode = item.node; if(!curNode) continue; const ContentSpecNode::NodeTypes parentType = item.parentType; const ContentSpecNode* first = curNode->getFirst(); const ContentSpecNode* second = curNode->getSecond(); const ContentSpecNode::NodeTypes curType = curNode->getType(); // Get the type of the first node const ContentSpecNode::NodeTypes firstType = first ? first->getType() : ContentSpecNode::Leaf; // Calculate the parens flag for the rep nodes bool doRepParens = false; if (((firstType != ContentSpecNode::Leaf) && (parentType != ContentSpecNode::UnknownType)) || ((firstType == ContentSpecNode::Leaf) && (parentType == ContentSpecNode::UnknownType))) { doRepParens = true; } // Now handle our type switch(curType & 0x0f) { case ContentSpecNode::Leaf : if (curNode->getElement()->getURI() == XMLElementDecl::fgPCDataElemId) bufToFill.append(XMLElementDecl::fgPCDataElemName); else { bufToFill.append(curNode->getElement()->getRawName()); // show the + and * modifiers also when we have a non-infinite number of repetitions if(curNode->getMinOccurs()==0 && (curNode->getMaxOccurs()==-1 || curNode->getMaxOccurs()>1)) bufToFill.append(chAsterisk); else if(curNode->getMinOccurs()==0 && curNode->getMaxOccurs()==1) bufToFill.append(chQuestion); else if(curNode->getMinOccurs()==1 && (curNode->getMaxOccurs()==-1 || curNode->getMaxOccurs()>1)) bufToFill.append(chPlus); } break; case ContentSpecNode::ZeroOrOne : if (doRepParens) bufToFill.append(chOpenParen); toBeProcessed.push(formatNodeHolder(0, ContentSpecNode::UnknownType, chQuestion)); if (doRepParens) toBeProcessed.push(formatNodeHolder(0, ContentSpecNode::UnknownType, chCloseParen)); toBeProcessed.push(formatNodeHolder(first, curType, 0)); break; case ContentSpecNode::ZeroOrMore : if (doRepParens) bufToFill.append(chOpenParen); toBeProcessed.push(formatNodeHolder(0, ContentSpecNode::UnknownType, chAsterisk)); if (doRepParens) toBeProcessed.push(formatNodeHolder(0, ContentSpecNode::UnknownType, chCloseParen)); toBeProcessed.push(formatNodeHolder(first, curType, 0)); break; case ContentSpecNode::OneOrMore : if (doRepParens) bufToFill.append(chOpenParen); toBeProcessed.push(formatNodeHolder(0, ContentSpecNode::UnknownType, chPlus)); if (doRepParens) toBeProcessed.push(formatNodeHolder(0, ContentSpecNode::UnknownType, chCloseParen)); toBeProcessed.push(formatNodeHolder(first, curType, 0)); break; case ContentSpecNode::Choice : if ((parentType & 0x0f) != (curType & 0x0f)) bufToFill.append(chOpenParen); if ((parentType & 0x0f) != (curType & 0x0f)) toBeProcessed.push(formatNodeHolder(0, ContentSpecNode::UnknownType, chCloseParen)); if(second!=NULL) { toBeProcessed.push(formatNodeHolder(second, curType, 0)); toBeProcessed.push(formatNodeHolder(0, ContentSpecNode::UnknownType, chPipe)); } toBeProcessed.push(formatNodeHolder(first, curType, 0)); break; case ContentSpecNode::Sequence : if ((parentType & 0x0f) != (curType & 0x0f)) bufToFill.append(chOpenParen); if ((parentType & 0x0f) != (curType & 0x0f)) toBeProcessed.push(formatNodeHolder(0, ContentSpecNode::UnknownType, chCloseParen)); if(second!=NULL) { toBeProcessed.push(formatNodeHolder(second, curType, 0)); toBeProcessed.push(formatNodeHolder(0, ContentSpecNode::UnknownType, chComma)); } toBeProcessed.push(formatNodeHolder(first, curType, 0)); break; case ContentSpecNode::All : if ((parentType & 0x0f) != (curType & 0x0f)) { bufToFill.append(chLatin_A); bufToFill.append(chLatin_l); bufToFill.append(chLatin_l); bufToFill.append(chOpenParen); } if ((parentType & 0x0f) != (curType & 0x0f)) toBeProcessed.push(formatNodeHolder(0, ContentSpecNode::UnknownType, chCloseParen)); toBeProcessed.push(formatNodeHolder(second, curType, 0)); toBeProcessed.push(formatNodeHolder(0, ContentSpecNode::UnknownType, chComma)); toBeProcessed.push(formatNodeHolder(first, curType, 0)); break; } } } // --------------------------------------------------------------------------- // ContentSpecNode: Miscellaneous // --------------------------------------------------------------------------- void ContentSpecNode::formatSpec(XMLBuffer& bufToFill) const { // Clean out the buffer first bufToFill.reset(); if (fType == ContentSpecNode::Leaf) bufToFill.append(chOpenParen); formatNode ( this , bufToFill , fMemoryManager ); if (fType == ContentSpecNode::Leaf) bufToFill.append(chCloseParen); } int ContentSpecNode::getMinTotalRange() const { int min = fMinOccurs; if ((fType & 0x0f) == ContentSpecNode::Sequence || fType == ContentSpecNode::All || (fType & 0x0f) == ContentSpecNode::Choice) { int minFirst = fFirst->getMinTotalRange(); if (fSecond) { int minSecond = fSecond->getMinTotalRange(); if ((fType & 0x0f) == ContentSpecNode::Choice) { min = min * ((minFirst < minSecond)? minFirst : minSecond); } else { min = min * (minFirst + minSecond); } } else min = min * minFirst; } return min; } int ContentSpecNode::getMaxTotalRange() const { int max = fMaxOccurs; if (max == SchemaSymbols::XSD_UNBOUNDED) { return SchemaSymbols::XSD_UNBOUNDED; } if ((fType & 0x0f) == ContentSpecNode::Sequence || fType == ContentSpecNode::All || (fType & 0x0f) == ContentSpecNode::Choice) { int maxFirst = fFirst->getMaxTotalRange(); if (maxFirst == SchemaSymbols::XSD_UNBOUNDED) { return SchemaSymbols::XSD_UNBOUNDED; } if (fSecond) { int maxSecond = fSecond->getMaxTotalRange(); if (maxSecond == SchemaSymbols::XSD_UNBOUNDED) { return SchemaSymbols::XSD_UNBOUNDED; } else { if ((fType & 0x0f) == ContentSpecNode::Choice) { max = max * ((maxFirst > maxSecond) ? maxFirst : maxSecond); } else { max = max * (maxFirst + maxSecond); } } } else { max = max * maxFirst; } } return max; } /*** * Support for Serialization/De-serialization ***/ IMPL_XSERIALIZABLE_TOCREATE(ContentSpecNode) void ContentSpecNode::serialize(XSerializeEngine& serEng) { /*** * Since fElement, fFirst, fSecond are NOT created by the default * constructor, we need to create them dynamically. ***/ if (serEng.isStoring()) { serEng<<fElement; XMLElementDecl::storeElementDecl(serEng, fElementDecl); serEng<<fFirst; serEng<<fSecond; serEng<<(int)fType; serEng<<fAdoptFirst; serEng<<fAdoptSecond; serEng<<fMinOccurs; serEng<<fMaxOccurs; } else { serEng>>fElement; fElementDecl = XMLElementDecl::loadElementDecl(serEng); serEng>>fFirst; serEng>>fSecond; int type; serEng>>type; fType = (NodeTypes)type; serEng>>fAdoptFirst; serEng>>fAdoptSecond; serEng>>fMinOccurs; serEng>>fMaxOccurs; } } XERCES_CPP_NAMESPACE_END
Fix operator precedence (XERCESC-1994)
Fix operator precedence (XERCESC-1994) git-svn-id: 95233098a850bdf68e142cb551b6b3e756f38fc7@1383366 13f79535-47bb-0310-9956-ffa450edef68
C++
apache-2.0
svn2github/xerces-c,svn2github/xerces-c,svn2github/xerces-c,svn2github/xerces-c,svn2github/xerces-c
4db9800ef1f1c4062c6a00fcd175e38988c30087
chrome/browser/ui/views/select_file_dialog_extension.cc
chrome/browser/ui/views/select_file_dialog_extension.cc
// Copyright (c) 2012 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chrome/browser/ui/views/select_file_dialog_extension.h" #include "apps/shell_window.h" #include "apps/shell_window_registry.h" #include "apps/ui/native_app_window.h" #include "base/bind.h" #include "base/callback.h" #include "base/logging.h" #include "base/memory/ref_counted.h" #include "base/memory/singleton.h" #include "base/message_loop/message_loop.h" #include "chrome/browser/chromeos/file_manager/app_id.h" #include "chrome/browser/chromeos/file_manager/fileapi_util.h" #include "chrome/browser/chromeos/file_manager/select_file_dialog_util.h" #include "chrome/browser/chromeos/file_manager/url_util.h" #include "chrome/browser/extensions/extension_host.h" #include "chrome/browser/extensions/extension_service.h" #include "chrome/browser/extensions/extension_system.h" #include "chrome/browser/profiles/profile.h" #include "chrome/browser/sessions/session_tab_helper.h" #include "chrome/browser/ui/browser.h" #include "chrome/browser/ui/browser_finder.h" #include "chrome/browser/ui/browser_list.h" #include "chrome/browser/ui/browser_window.h" #include "chrome/browser/ui/chrome_select_file_policy.h" #include "chrome/browser/ui/host_desktop.h" #include "chrome/browser/ui/tabs/tab_strip_model.h" #include "chrome/browser/ui/views/extensions/extension_dialog.h" #include "chrome/common/pref_names.h" #include "content/public/browser/browser_thread.h" #include "ui/base/base_window.h" #include "ui/shell_dialogs/selected_file_info.h" #include "ui/views/widget/widget.h" using apps::ShellWindow; using content::BrowserThread; namespace { const int kFileManagerWidth = 972; // pixels const int kFileManagerHeight = 640; // pixels // Holds references to file manager dialogs that have callbacks pending // to their listeners. class PendingDialog { public: static PendingDialog* GetInstance(); void Add(SelectFileDialogExtension::RoutingID id, scoped_refptr<SelectFileDialogExtension> dialog); void Remove(SelectFileDialogExtension::RoutingID id); scoped_refptr<SelectFileDialogExtension> Find( SelectFileDialogExtension::RoutingID id); private: friend struct DefaultSingletonTraits<PendingDialog>; typedef std::map<SelectFileDialogExtension::RoutingID, scoped_refptr<SelectFileDialogExtension> > Map; Map map_; }; // static PendingDialog* PendingDialog::GetInstance() { return Singleton<PendingDialog>::get(); } void PendingDialog::Add(SelectFileDialogExtension::RoutingID id, scoped_refptr<SelectFileDialogExtension> dialog) { DCHECK(dialog.get()); if (map_.find(id) == map_.end()) map_.insert(std::make_pair(id, dialog)); else DLOG(WARNING) << "Duplicate pending dialog " << id; } void PendingDialog::Remove(SelectFileDialogExtension::RoutingID id) { map_.erase(id); } scoped_refptr<SelectFileDialogExtension> PendingDialog::Find( SelectFileDialogExtension::RoutingID id) { Map::const_iterator it = map_.find(id); if (it == map_.end()) return NULL; return it->second; } } // namespace ///////////////////////////////////////////////////////////////////////////// // static SelectFileDialogExtension::RoutingID SelectFileDialogExtension::GetRoutingIDFromWebContents( const content::WebContents* web_contents) { // Use the raw pointer value as the identifier. Previously we have used the // tab ID for the purpose, but some web_contents, especially those of the // packaged apps, don't have tab IDs assigned. return web_contents; } // TODO(jamescook): Move this into a new file shell_dialogs_chromeos.cc // static SelectFileDialogExtension* SelectFileDialogExtension::Create( Listener* listener, ui::SelectFilePolicy* policy) { return new SelectFileDialogExtension(listener, policy); } SelectFileDialogExtension::SelectFileDialogExtension( Listener* listener, ui::SelectFilePolicy* policy) : SelectFileDialog(listener, policy), has_multiple_file_type_choices_(false), routing_id_(), profile_(NULL), owner_window_(NULL), selection_type_(CANCEL), selection_index_(0), params_(NULL) { } SelectFileDialogExtension::~SelectFileDialogExtension() { if (extension_dialog_.get()) extension_dialog_->ObserverDestroyed(); } bool SelectFileDialogExtension::IsRunning( gfx::NativeWindow owner_window) const { return owner_window_ == owner_window; } void SelectFileDialogExtension::ListenerDestroyed() { listener_ = NULL; params_ = NULL; PendingDialog::GetInstance()->Remove(routing_id_); } void SelectFileDialogExtension::ExtensionDialogClosing( ExtensionDialog* /*dialog*/) { profile_ = NULL; owner_window_ = NULL; // Release our reference to the underlying dialog to allow it to close. extension_dialog_ = NULL; PendingDialog::GetInstance()->Remove(routing_id_); // Actually invoke the appropriate callback on our listener. NotifyListener(); } void SelectFileDialogExtension::ExtensionTerminated( ExtensionDialog* dialog) { // The extension would have been unloaded because of the termination, // reload it. std::string extension_id = dialog->host()->extension()->id(); // Reload the extension after a bit; the extension may not have been unloaded // yet. We don't want to try to reload the extension only to have the Unload // code execute after us and re-unload the extension. // // TODO(rkc): This is ugly. The ideal solution is that we shouldn't need to // reload the extension at all - when we try to open the extension the next // time, the extension subsystem would automatically reload it for us. At // this time though this is broken because of some faulty wiring in // extensions::ProcessManager::CreateViewHost. Once that is fixed, remove // this. if (profile_) { base::MessageLoop::current()->PostTask( FROM_HERE, base::Bind(&ExtensionService::ReloadExtension, base::Unretained(extensions::ExtensionSystem::Get(profile_) ->extension_service()), extension_id)); } dialog->GetWidget()->Close(); } // static void SelectFileDialogExtension::OnFileSelected( RoutingID routing_id, const ui::SelectedFileInfo& file, int index) { scoped_refptr<SelectFileDialogExtension> dialog = PendingDialog::GetInstance()->Find(routing_id); if (!dialog.get()) return; dialog->selection_type_ = SINGLE_FILE; dialog->selection_files_.clear(); dialog->selection_files_.push_back(file); dialog->selection_index_ = index; } // static void SelectFileDialogExtension::OnMultiFilesSelected( RoutingID routing_id, const std::vector<ui::SelectedFileInfo>& files) { scoped_refptr<SelectFileDialogExtension> dialog = PendingDialog::GetInstance()->Find(routing_id); if (!dialog.get()) return; dialog->selection_type_ = MULTIPLE_FILES; dialog->selection_files_ = files; dialog->selection_index_ = 0; } // static void SelectFileDialogExtension::OnFileSelectionCanceled(RoutingID routing_id) { scoped_refptr<SelectFileDialogExtension> dialog = PendingDialog::GetInstance()->Find(routing_id); if (!dialog.get()) return; dialog->selection_type_ = CANCEL; dialog->selection_files_.clear(); dialog->selection_index_ = 0; } content::RenderViewHost* SelectFileDialogExtension::GetRenderViewHost() { if (extension_dialog_.get()) return extension_dialog_->host()->render_view_host(); return NULL; } void SelectFileDialogExtension::NotifyListener() { if (!listener_) return; switch (selection_type_) { case CANCEL: listener_->FileSelectionCanceled(params_); break; case SINGLE_FILE: listener_->FileSelectedWithExtraInfo(selection_files_[0], selection_index_, params_); break; case MULTIPLE_FILES: listener_->MultiFilesSelectedWithExtraInfo(selection_files_, params_); break; default: NOTREACHED(); break; } } void SelectFileDialogExtension::AddPending(RoutingID routing_id) { PendingDialog::GetInstance()->Add(routing_id, this); } // static bool SelectFileDialogExtension::PendingExists(RoutingID routing_id) { return PendingDialog::GetInstance()->Find(routing_id).get() != NULL; } bool SelectFileDialogExtension::HasMultipleFileTypeChoicesImpl() { return has_multiple_file_type_choices_; } void SelectFileDialogExtension::SelectFileImpl( Type type, const string16& title, const base::FilePath& default_path, const FileTypeInfo* file_types, int file_type_index, const base::FilePath::StringType& default_extension, gfx::NativeWindow owner_window, void* params) { if (owner_window_) { LOG(ERROR) << "File dialog already in use!"; return; } // The base window to associate the dialog with. ui::BaseWindow* base_window = NULL; // The web contents to associate the dialog with. content::WebContents* web_contents = NULL; // To get the base_window and profile, either a Browser or ShellWindow is // needed. Browser* owner_browser = NULL; ShellWindow* shell_window = NULL; // If owner_window is supplied, use that to find a browser or a shell window. if (owner_window) { owner_browser = chrome::FindBrowserWithWindow(owner_window); if (!owner_browser) { // If an owner_window was supplied but we couldn't find a browser, this // could be for a shell window. shell_window = apps::ShellWindowRegistry:: GetShellWindowForNativeWindowAnyProfile(owner_window); } } if (shell_window) { if (shell_window->window_type_is_panel()) { NOTREACHED() << "File dialog opened by panel."; return; } base_window = shell_window->GetBaseWindow(); web_contents = shell_window->web_contents(); } else { // If the owning window is still unknown, this could be a background page or // and extension popup. Use the last active browser. if (!owner_browser) { owner_browser = chrome::FindLastActiveWithHostDesktopType(chrome::GetActiveDesktop()); } DCHECK(owner_browser); if (!owner_browser) { LOG(ERROR) << "Could not find browser or shell window for popup."; return; } base_window = owner_browser->window(); web_contents = owner_browser->tab_strip_model()->GetActiveWebContents(); } DCHECK(base_window); DCHECK(web_contents); profile_ = Profile::FromBrowserContext(web_contents->GetBrowserContext()); DCHECK(profile_); // Check if we have another dialog opened for the contents. It's unlikely, but // possible. RoutingID routing_id = GetRoutingIDFromWebContents(web_contents); if (PendingExists(routing_id)) { DLOG(WARNING) << "Pending dialog exists with id " << routing_id; return; } base::FilePath default_dialog_path; const PrefService* pref_service = profile_->GetPrefs(); if (default_path.empty() && pref_service) { default_dialog_path = pref_service->GetFilePath(prefs::kDownloadDefaultDirectory); } else { default_dialog_path = default_path; } base::FilePath virtual_path; base::FilePath fallback_path = profile_->last_selected_directory().Append( default_dialog_path.BaseName()); // If an absolute path is specified as the default path, convert it to the // virtual path in the file browser extension. Due to the current design, // an invalid temporal cache file path may passed as |default_dialog_path| // (crbug.com/178013 #9-#11). In such a case, we use the last selected // directory as a workaround. Real fix is tracked at crbug.com/110119. using file_manager::kFileManagerAppId; if (default_dialog_path.IsAbsolute() && (file_manager::util::ConvertAbsoluteFilePathToRelativeFileSystemPath( profile_, kFileManagerAppId, default_dialog_path, &virtual_path) || file_manager::util::ConvertAbsoluteFilePathToRelativeFileSystemPath( profile_, kFileManagerAppId, fallback_path, &virtual_path))) { virtual_path = base::FilePath("/").Append(virtual_path); } else { // If the path was relative, or failed to convert, just use the base name, virtual_path = default_dialog_path.BaseName(); } has_multiple_file_type_choices_ = file_types ? file_types->extensions.size() > 1 : true; GURL file_manager_url = file_manager::util::GetFileManagerMainPageUrlWithParams( type, title, virtual_path, file_types, file_type_index, default_extension); ExtensionDialog* dialog = ExtensionDialog::Show(file_manager_url, base_window, profile_, web_contents, kFileManagerWidth, kFileManagerHeight, kFileManagerWidth, kFileManagerHeight, #if defined(USE_AURA) file_manager::util::GetSelectFileDialogTitle(type), #else // HTML-based header used. string16(), #endif this /* ExtensionDialog::Observer */); if (!dialog) { LOG(ERROR) << "Unable to create extension dialog"; return; } // Connect our listener to FileDialogFunction's per-tab callbacks. AddPending(routing_id); extension_dialog_ = dialog; params_ = params; routing_id_ = routing_id; owner_window_ = owner_window; }
// 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 "chrome/browser/ui/views/select_file_dialog_extension.h" #include "apps/shell_window.h" #include "apps/shell_window_registry.h" #include "apps/ui/native_app_window.h" #include "base/bind.h" #include "base/callback.h" #include "base/logging.h" #include "base/memory/ref_counted.h" #include "base/memory/singleton.h" #include "base/message_loop/message_loop.h" #include "chrome/browser/chromeos/file_manager/app_id.h" #include "chrome/browser/chromeos/file_manager/fileapi_util.h" #include "chrome/browser/chromeos/file_manager/select_file_dialog_util.h" #include "chrome/browser/chromeos/file_manager/url_util.h" #include "chrome/browser/extensions/extension_host.h" #include "chrome/browser/extensions/extension_service.h" #include "chrome/browser/extensions/extension_system.h" #include "chrome/browser/profiles/profile.h" #include "chrome/browser/sessions/session_tab_helper.h" #include "chrome/browser/ui/browser.h" #include "chrome/browser/ui/browser_finder.h" #include "chrome/browser/ui/browser_list.h" #include "chrome/browser/ui/browser_window.h" #include "chrome/browser/ui/chrome_select_file_policy.h" #include "chrome/browser/ui/host_desktop.h" #include "chrome/browser/ui/tabs/tab_strip_model.h" #include "chrome/browser/ui/views/extensions/extension_dialog.h" #include "chrome/common/pref_names.h" #include "content/public/browser/browser_thread.h" #include "ui/base/base_window.h" #include "ui/shell_dialogs/selected_file_info.h" #include "ui/views/widget/widget.h" using apps::ShellWindow; using content::BrowserThread; namespace { const int kFileManagerWidth = 972; // pixels const int kFileManagerHeight = 640; // pixels const int kFileManagerMinWidth = 320; // pixels const int kFileManagerMinHeight = 240; // pixels // Holds references to file manager dialogs that have callbacks pending // to their listeners. class PendingDialog { public: static PendingDialog* GetInstance(); void Add(SelectFileDialogExtension::RoutingID id, scoped_refptr<SelectFileDialogExtension> dialog); void Remove(SelectFileDialogExtension::RoutingID id); scoped_refptr<SelectFileDialogExtension> Find( SelectFileDialogExtension::RoutingID id); private: friend struct DefaultSingletonTraits<PendingDialog>; typedef std::map<SelectFileDialogExtension::RoutingID, scoped_refptr<SelectFileDialogExtension> > Map; Map map_; }; // static PendingDialog* PendingDialog::GetInstance() { return Singleton<PendingDialog>::get(); } void PendingDialog::Add(SelectFileDialogExtension::RoutingID id, scoped_refptr<SelectFileDialogExtension> dialog) { DCHECK(dialog.get()); if (map_.find(id) == map_.end()) map_.insert(std::make_pair(id, dialog)); else DLOG(WARNING) << "Duplicate pending dialog " << id; } void PendingDialog::Remove(SelectFileDialogExtension::RoutingID id) { map_.erase(id); } scoped_refptr<SelectFileDialogExtension> PendingDialog::Find( SelectFileDialogExtension::RoutingID id) { Map::const_iterator it = map_.find(id); if (it == map_.end()) return NULL; return it->second; } } // namespace ///////////////////////////////////////////////////////////////////////////// // static SelectFileDialogExtension::RoutingID SelectFileDialogExtension::GetRoutingIDFromWebContents( const content::WebContents* web_contents) { // Use the raw pointer value as the identifier. Previously we have used the // tab ID for the purpose, but some web_contents, especially those of the // packaged apps, don't have tab IDs assigned. return web_contents; } // TODO(jamescook): Move this into a new file shell_dialogs_chromeos.cc // static SelectFileDialogExtension* SelectFileDialogExtension::Create( Listener* listener, ui::SelectFilePolicy* policy) { return new SelectFileDialogExtension(listener, policy); } SelectFileDialogExtension::SelectFileDialogExtension( Listener* listener, ui::SelectFilePolicy* policy) : SelectFileDialog(listener, policy), has_multiple_file_type_choices_(false), routing_id_(), profile_(NULL), owner_window_(NULL), selection_type_(CANCEL), selection_index_(0), params_(NULL) { } SelectFileDialogExtension::~SelectFileDialogExtension() { if (extension_dialog_.get()) extension_dialog_->ObserverDestroyed(); } bool SelectFileDialogExtension::IsRunning( gfx::NativeWindow owner_window) const { return owner_window_ == owner_window; } void SelectFileDialogExtension::ListenerDestroyed() { listener_ = NULL; params_ = NULL; PendingDialog::GetInstance()->Remove(routing_id_); } void SelectFileDialogExtension::ExtensionDialogClosing( ExtensionDialog* /*dialog*/) { profile_ = NULL; owner_window_ = NULL; // Release our reference to the underlying dialog to allow it to close. extension_dialog_ = NULL; PendingDialog::GetInstance()->Remove(routing_id_); // Actually invoke the appropriate callback on our listener. NotifyListener(); } void SelectFileDialogExtension::ExtensionTerminated( ExtensionDialog* dialog) { // The extension would have been unloaded because of the termination, // reload it. std::string extension_id = dialog->host()->extension()->id(); // Reload the extension after a bit; the extension may not have been unloaded // yet. We don't want to try to reload the extension only to have the Unload // code execute after us and re-unload the extension. // // TODO(rkc): This is ugly. The ideal solution is that we shouldn't need to // reload the extension at all - when we try to open the extension the next // time, the extension subsystem would automatically reload it for us. At // this time though this is broken because of some faulty wiring in // extensions::ProcessManager::CreateViewHost. Once that is fixed, remove // this. if (profile_) { base::MessageLoop::current()->PostTask( FROM_HERE, base::Bind(&ExtensionService::ReloadExtension, base::Unretained(extensions::ExtensionSystem::Get(profile_) ->extension_service()), extension_id)); } dialog->GetWidget()->Close(); } // static void SelectFileDialogExtension::OnFileSelected( RoutingID routing_id, const ui::SelectedFileInfo& file, int index) { scoped_refptr<SelectFileDialogExtension> dialog = PendingDialog::GetInstance()->Find(routing_id); if (!dialog.get()) return; dialog->selection_type_ = SINGLE_FILE; dialog->selection_files_.clear(); dialog->selection_files_.push_back(file); dialog->selection_index_ = index; } // static void SelectFileDialogExtension::OnMultiFilesSelected( RoutingID routing_id, const std::vector<ui::SelectedFileInfo>& files) { scoped_refptr<SelectFileDialogExtension> dialog = PendingDialog::GetInstance()->Find(routing_id); if (!dialog.get()) return; dialog->selection_type_ = MULTIPLE_FILES; dialog->selection_files_ = files; dialog->selection_index_ = 0; } // static void SelectFileDialogExtension::OnFileSelectionCanceled(RoutingID routing_id) { scoped_refptr<SelectFileDialogExtension> dialog = PendingDialog::GetInstance()->Find(routing_id); if (!dialog.get()) return; dialog->selection_type_ = CANCEL; dialog->selection_files_.clear(); dialog->selection_index_ = 0; } content::RenderViewHost* SelectFileDialogExtension::GetRenderViewHost() { if (extension_dialog_.get()) return extension_dialog_->host()->render_view_host(); return NULL; } void SelectFileDialogExtension::NotifyListener() { if (!listener_) return; switch (selection_type_) { case CANCEL: listener_->FileSelectionCanceled(params_); break; case SINGLE_FILE: listener_->FileSelectedWithExtraInfo(selection_files_[0], selection_index_, params_); break; case MULTIPLE_FILES: listener_->MultiFilesSelectedWithExtraInfo(selection_files_, params_); break; default: NOTREACHED(); break; } } void SelectFileDialogExtension::AddPending(RoutingID routing_id) { PendingDialog::GetInstance()->Add(routing_id, this); } // static bool SelectFileDialogExtension::PendingExists(RoutingID routing_id) { return PendingDialog::GetInstance()->Find(routing_id).get() != NULL; } bool SelectFileDialogExtension::HasMultipleFileTypeChoicesImpl() { return has_multiple_file_type_choices_; } void SelectFileDialogExtension::SelectFileImpl( Type type, const string16& title, const base::FilePath& default_path, const FileTypeInfo* file_types, int file_type_index, const base::FilePath::StringType& default_extension, gfx::NativeWindow owner_window, void* params) { if (owner_window_) { LOG(ERROR) << "File dialog already in use!"; return; } // The base window to associate the dialog with. ui::BaseWindow* base_window = NULL; // The web contents to associate the dialog with. content::WebContents* web_contents = NULL; // To get the base_window and profile, either a Browser or ShellWindow is // needed. Browser* owner_browser = NULL; ShellWindow* shell_window = NULL; // If owner_window is supplied, use that to find a browser or a shell window. if (owner_window) { owner_browser = chrome::FindBrowserWithWindow(owner_window); if (!owner_browser) { // If an owner_window was supplied but we couldn't find a browser, this // could be for a shell window. shell_window = apps::ShellWindowRegistry:: GetShellWindowForNativeWindowAnyProfile(owner_window); } } if (shell_window) { if (shell_window->window_type_is_panel()) { NOTREACHED() << "File dialog opened by panel."; return; } base_window = shell_window->GetBaseWindow(); web_contents = shell_window->web_contents(); } else { // If the owning window is still unknown, this could be a background page or // and extension popup. Use the last active browser. if (!owner_browser) { owner_browser = chrome::FindLastActiveWithHostDesktopType(chrome::GetActiveDesktop()); } DCHECK(owner_browser); if (!owner_browser) { LOG(ERROR) << "Could not find browser or shell window for popup."; return; } base_window = owner_browser->window(); web_contents = owner_browser->tab_strip_model()->GetActiveWebContents(); } DCHECK(base_window); DCHECK(web_contents); profile_ = Profile::FromBrowserContext(web_contents->GetBrowserContext()); DCHECK(profile_); // Check if we have another dialog opened for the contents. It's unlikely, but // possible. RoutingID routing_id = GetRoutingIDFromWebContents(web_contents); if (PendingExists(routing_id)) { DLOG(WARNING) << "Pending dialog exists with id " << routing_id; return; } base::FilePath default_dialog_path; const PrefService* pref_service = profile_->GetPrefs(); if (default_path.empty() && pref_service) { default_dialog_path = pref_service->GetFilePath(prefs::kDownloadDefaultDirectory); } else { default_dialog_path = default_path; } base::FilePath virtual_path; base::FilePath fallback_path = profile_->last_selected_directory().Append( default_dialog_path.BaseName()); // If an absolute path is specified as the default path, convert it to the // virtual path in the file browser extension. Due to the current design, // an invalid temporal cache file path may passed as |default_dialog_path| // (crbug.com/178013 #9-#11). In such a case, we use the last selected // directory as a workaround. Real fix is tracked at crbug.com/110119. using file_manager::kFileManagerAppId; if (default_dialog_path.IsAbsolute() && (file_manager::util::ConvertAbsoluteFilePathToRelativeFileSystemPath( profile_, kFileManagerAppId, default_dialog_path, &virtual_path) || file_manager::util::ConvertAbsoluteFilePathToRelativeFileSystemPath( profile_, kFileManagerAppId, fallback_path, &virtual_path))) { virtual_path = base::FilePath("/").Append(virtual_path); } else { // If the path was relative, or failed to convert, just use the base name, virtual_path = default_dialog_path.BaseName(); } has_multiple_file_type_choices_ = file_types ? file_types->extensions.size() > 1 : true; GURL file_manager_url = file_manager::util::GetFileManagerMainPageUrlWithParams( type, title, virtual_path, file_types, file_type_index, default_extension); ExtensionDialog* dialog = ExtensionDialog::Show(file_manager_url, base_window, profile_, web_contents, kFileManagerWidth, kFileManagerHeight, kFileManagerMinWidth, kFileManagerMinHeight, #if defined(USE_AURA) file_manager::util::GetSelectFileDialogTitle(type), #else // HTML-based header used. string16(), #endif this /* ExtensionDialog::Observer */); if (!dialog) { LOG(ERROR) << "Unable to create extension dialog"; return; } // Connect our listener to FileDialogFunction's per-tab callbacks. AddPending(routing_id); extension_dialog_ = dialog; params_ = params; routing_id_ = routing_id; owner_window_ = owner_window; }
Set the minimum size of file dialog as 320px x 240px
[Files.app] Set the minimum size of file dialog as 320px x 240px BUG=310818 TEST=manually tested Review URL: https://codereview.chromium.org/70673003 git-svn-id: de016e52bd170d2d4f2344f9bf92d50478b649e0@234870 0039d316-1c4b-4281-b951-d872f2087c98
C++
bsd-3-clause
fujunwei/chromium-crosswalk,ondra-novak/chromium.src,Fireblend/chromium-crosswalk,PeterWangIntel/chromium-crosswalk,dednal/chromium.src,markYoungH/chromium.src,Jonekee/chromium.src,jaruba/chromium.src,hgl888/chromium-crosswalk-efl,M4sse/chromium.src,chuan9/chromium-crosswalk,jaruba/chromium.src,Just-D/chromium-1,ondra-novak/chromium.src,TheTypoMaster/chromium-crosswalk,fujunwei/chromium-crosswalk,hgl888/chromium-crosswalk-efl,littlstar/chromium.src,hgl888/chromium-crosswalk,chuan9/chromium-crosswalk,dushu1203/chromium.src,M4sse/chromium.src,dushu1203/chromium.src,jaruba/chromium.src,jaruba/chromium.src,patrickm/chromium.src,ChromiumWebApps/chromium,bright-sparks/chromium-spacewalk,hgl888/chromium-crosswalk-efl,Chilledheart/chromium,Chilledheart/chromium,crosswalk-project/chromium-crosswalk-efl,anirudhSK/chromium,fujunwei/chromium-crosswalk,mohamed--abdel-maksoud/chromium.src,PeterWangIntel/chromium-crosswalk,axinging/chromium-crosswalk,ChromiumWebApps/chromium,hgl888/chromium-crosswalk-efl,patrickm/chromium.src,bright-sparks/chromium-spacewalk,krieger-od/nwjs_chromium.src,jaruba/chromium.src,dednal/chromium.src,Chilledheart/chromium,hgl888/chromium-crosswalk,ondra-novak/chromium.src,dednal/chromium.src,Just-D/chromium-1,dushu1203/chromium.src,anirudhSK/chromium,jaruba/chromium.src,krieger-od/nwjs_chromium.src,bright-sparks/chromium-spacewalk,bright-sparks/chromium-spacewalk,crosswalk-project/chromium-crosswalk-efl,dednal/chromium.src,mohamed--abdel-maksoud/chromium.src,axinging/chromium-crosswalk,axinging/chromium-crosswalk,ondra-novak/chromium.src,crosswalk-project/chromium-crosswalk-efl,ChromiumWebApps/chromium,ChromiumWebApps/chromium,littlstar/chromium.src,littlstar/chromium.src,M4sse/chromium.src,ondra-novak/chromium.src,anirudhSK/chromium,Fireblend/chromium-crosswalk,axinging/chromium-crosswalk,PeterWangIntel/chromium-crosswalk,mohamed--abdel-maksoud/chromium.src,Chilledheart/chromium,TheTypoMaster/chromium-crosswalk,mohamed--abdel-maksoud/chromium.src,Chilledheart/chromium,dushu1203/chromium.src,patrickm/chromium.src,ltilve/chromium,ChromiumWebApps/chromium,M4sse/chromium.src,ondra-novak/chromium.src,Fireblend/chromium-crosswalk,axinging/chromium-crosswalk,anirudhSK/chromium,krieger-od/nwjs_chromium.src,hgl888/chromium-crosswalk,krieger-od/nwjs_chromium.src,chuan9/chromium-crosswalk,markYoungH/chromium.src,hgl888/chromium-crosswalk,ChromiumWebApps/chromium,fujunwei/chromium-crosswalk,crosswalk-project/chromium-crosswalk-efl,crosswalk-project/chromium-crosswalk-efl,chuan9/chromium-crosswalk,mohamed--abdel-maksoud/chromium.src,mohamed--abdel-maksoud/chromium.src,anirudhSK/chromium,ltilve/chromium,jaruba/chromium.src,PeterWangIntel/chromium-crosswalk,TheTypoMaster/chromium-crosswalk,M4sse/chromium.src,Just-D/chromium-1,ChromiumWebApps/chromium,Jonekee/chromium.src,jaruba/chromium.src,markYoungH/chromium.src,littlstar/chromium.src,axinging/chromium-crosswalk,ltilve/chromium,patrickm/chromium.src,hgl888/chromium-crosswalk,bright-sparks/chromium-spacewalk,bright-sparks/chromium-spacewalk,Jonekee/chromium.src,Jonekee/chromium.src,M4sse/chromium.src,Pluto-tv/chromium-crosswalk,hgl888/chromium-crosswalk,Fireblend/chromium-crosswalk,Chilledheart/chromium,M4sse/chromium.src,fujunwei/chromium-crosswalk,krieger-od/nwjs_chromium.src,hgl888/chromium-crosswalk-efl,anirudhSK/chromium,chuan9/chromium-crosswalk,mohamed--abdel-maksoud/chromium.src,mohamed--abdel-maksoud/chromium.src,dushu1203/chromium.src,ChromiumWebApps/chromium,axinging/chromium-crosswalk,markYoungH/chromium.src,mohamed--abdel-maksoud/chromium.src,hgl888/chromium-crosswalk-efl,hgl888/chromium-crosswalk,dushu1203/chromium.src,axinging/chromium-crosswalk,bright-sparks/chromium-spacewalk,Fireblend/chromium-crosswalk,ltilve/chromium,M4sse/chromium.src,Just-D/chromium-1,TheTypoMaster/chromium-crosswalk,Chilledheart/chromium,Pluto-tv/chromium-crosswalk,PeterWangIntel/chromium-crosswalk,anirudhSK/chromium,Just-D/chromium-1,ltilve/chromium,Pluto-tv/chromium-crosswalk,markYoungH/chromium.src,dednal/chromium.src,crosswalk-project/chromium-crosswalk-efl,chuan9/chromium-crosswalk,dushu1203/chromium.src,Jonekee/chromium.src,dushu1203/chromium.src,anirudhSK/chromium,ChromiumWebApps/chromium,dednal/chromium.src,krieger-od/nwjs_chromium.src,markYoungH/chromium.src,TheTypoMaster/chromium-crosswalk,Fireblend/chromium-crosswalk,Pluto-tv/chromium-crosswalk,Fireblend/chromium-crosswalk,anirudhSK/chromium,mohamed--abdel-maksoud/chromium.src,fujunwei/chromium-crosswalk,markYoungH/chromium.src,TheTypoMaster/chromium-crosswalk,hgl888/chromium-crosswalk-efl,dushu1203/chromium.src,krieger-od/nwjs_chromium.src,axinging/chromium-crosswalk,ondra-novak/chromium.src,markYoungH/chromium.src,dushu1203/chromium.src,patrickm/chromium.src,patrickm/chromium.src,dednal/chromium.src,crosswalk-project/chromium-crosswalk-efl,jaruba/chromium.src,ondra-novak/chromium.src,anirudhSK/chromium,littlstar/chromium.src,hgl888/chromium-crosswalk,hgl888/chromium-crosswalk-efl,krieger-od/nwjs_chromium.src,littlstar/chromium.src,M4sse/chromium.src,ChromiumWebApps/chromium,dednal/chromium.src,ltilve/chromium,jaruba/chromium.src,ltilve/chromium,Jonekee/chromium.src,Fireblend/chromium-crosswalk,Jonekee/chromium.src,axinging/chromium-crosswalk,ltilve/chromium,Pluto-tv/chromium-crosswalk,patrickm/chromium.src,hgl888/chromium-crosswalk,fujunwei/chromium-crosswalk,Pluto-tv/chromium-crosswalk,TheTypoMaster/chromium-crosswalk,hgl888/chromium-crosswalk-efl,Just-D/chromium-1,TheTypoMaster/chromium-crosswalk,markYoungH/chromium.src,hgl888/chromium-crosswalk-efl,Just-D/chromium-1,dushu1203/chromium.src,Chilledheart/chromium,dednal/chromium.src,Jonekee/chromium.src,anirudhSK/chromium,PeterWangIntel/chromium-crosswalk,patrickm/chromium.src,krieger-od/nwjs_chromium.src,littlstar/chromium.src,ltilve/chromium,jaruba/chromium.src,ChromiumWebApps/chromium,Fireblend/chromium-crosswalk,mohamed--abdel-maksoud/chromium.src,Chilledheart/chromium,patrickm/chromium.src,Jonekee/chromium.src,anirudhSK/chromium,Pluto-tv/chromium-crosswalk,chuan9/chromium-crosswalk,littlstar/chromium.src,fujunwei/chromium-crosswalk,Jonekee/chromium.src,markYoungH/chromium.src,bright-sparks/chromium-spacewalk,TheTypoMaster/chromium-crosswalk,Pluto-tv/chromium-crosswalk,dednal/chromium.src,krieger-od/nwjs_chromium.src,chuan9/chromium-crosswalk,crosswalk-project/chromium-crosswalk-efl,bright-sparks/chromium-spacewalk,krieger-od/nwjs_chromium.src,Pluto-tv/chromium-crosswalk,fujunwei/chromium-crosswalk,ChromiumWebApps/chromium,dednal/chromium.src,crosswalk-project/chromium-crosswalk-efl,markYoungH/chromium.src,PeterWangIntel/chromium-crosswalk,PeterWangIntel/chromium-crosswalk,Just-D/chromium-1,Just-D/chromium-1,axinging/chromium-crosswalk,chuan9/chromium-crosswalk,M4sse/chromium.src,Jonekee/chromium.src,ondra-novak/chromium.src,PeterWangIntel/chromium-crosswalk,M4sse/chromium.src
4033f277378bdc5d84c58906db9436631f06f05b
src/Error.hpp
src/Error.hpp
// // Copyright (c) 2017, Boris Popov <[email protected]> // // This Source Code Form is subject to the terms of the Mozilla Public // License, v. 2.0. If a copy of the MPL was not distributed with this // file, You can obtain one at http://mozilla.org/MPL/2.0/. // #include "Common.hpp" #ifndef __linux_posix_Error__ #define __linux_posix_Error__ namespace linux { namespace posix { ////////////////////////////////////////////////////////////////// using Message = String; using Code = int; ////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////// class Error: public std::exception { public: Error(const Message, const Code); virtual ~Error(); Code getCode() const; virtual const char* what() const noexcept; private: const Code code; const Message mess; }; ////////////////////////////////////////////////////////////////// } } #endif // __linux_posix_Error__
// // Copyright (c) 2017, Boris Popov <[email protected]> // // This Source Code Form is subject to the terms of the Mozilla Public // License, v. 2.0. If a copy of the MPL was not distributed with this // file, You can obtain one at http://mozilla.org/MPL/2.0/. // #include "Common.hpp" #ifndef __linux_posix_Error__ #define __linux_posix_Error__ namespace linux { namespace posix { ////////////////////////////////////////////////////////////////// using Message = String; using Code = int; ////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////// class Error: public std::exception { public: Error(const Message, const Code); virtual ~Error(); Code getCode() const; virtual const char* what() const noexcept; private: const Code code; const Message mess; }; ////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////// class NullPointer: public Error { public: NullPointer(): Error("Using of null pointer!", -1) { } ~NullPointer() = default; }; ////////////////////////////////////////////////////////////////// } } #endif // __linux_posix_Error__
add NullPointer
add NullPointer
C++
mpl-2.0
popovb/SharMemPlusPlus
d31d95330f7a5250129e2822724f33b339a9ed4a
xsec/enc/XSECCryptoException.cpp
xsec/enc/XSECCryptoException.cpp
/** * 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. */ /* * XSEC * * XSECCryptoException:= How we throw exceptions in XSEC * * Author(s): Berin Lautenbach * * $Id$ * */ #include <xsec/enc/XSECCryptoException.hpp> #include <stdlib.h> #include <string.h> extern const char * XSECCryptoExceptionStrings[] = { "No Error", "General error occurred somewhere in cryptographic routines", "Error Creating SHA1 MD", "Error in Base64", "Memory allocation error", "X509 Error", "DSA Error", "RSA Error", "Symmetric Error", "EC Error", "Unsupported Algorithm" }; XSECCryptoException::XSECCryptoException(XSECCryptoExceptionType eNum, const char * inMsg) { if (eNum > UnknownError) type = UnknownError; else type = eNum; if (inMsg != NULL) { msg = new char[strlen(inMsg) + 1]; strcpy(msg, inMsg); } else { msg = new char[strlen(XSECCryptoExceptionStrings[type]) + 1]; strcpy(msg, XSECCryptoExceptionStrings[type]); } } XSECCryptoException::XSECCryptoException(XSECCryptoExceptionType eNum, safeBuffer &inMsg) { if (eNum > UnknownError) type = UnknownError; else type = eNum; msg = new char[strlen((char *) inMsg.rawBuffer()) + 1]; strcpy(msg, (char *) inMsg.rawBuffer()); } XSECCryptoException::XSECCryptoException(const XSECCryptoException &toCopy) { // Copy Constructor type = toCopy.type; if (toCopy.msg == NULL) msg = NULL; else { msg = new char[strlen(toCopy.msg) + 1]; strcpy(msg, toCopy.msg); } } XSECCryptoException::~XSECCryptoException() { if (msg != NULL) delete[] msg; } const char * XSECCryptoException::getMsg(void) const { return msg; } XSECCryptoException::XSECCryptoExceptionType XSECCryptoException::getType(void) const { return type; }
/** * 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. */ /* * XSEC * * XSECCryptoException:= How we throw exceptions in XSEC * * Author(s): Berin Lautenbach * * $Id$ * */ #include <xsec/enc/XSECCryptoException.hpp> #include <stdlib.h> #include <string.h> const char* XSECCryptoExceptionStrings[] = { "No Error", "General error occurred somewhere in cryptographic routines", "Error Creating SHA1 MD", "Error in Base64", "Memory allocation error", "X509 Error", "DSA Error", "RSA Error", "Symmetric Error", "EC Error", "Unsupported Algorithm" }; XSECCryptoException::XSECCryptoException(XSECCryptoExceptionType eNum, const char * inMsg) { if (eNum > UnknownError) type = UnknownError; else type = eNum; if (inMsg != NULL) { msg = new char[strlen(inMsg) + 1]; strcpy(msg, inMsg); } else { msg = new char[strlen(XSECCryptoExceptionStrings[type]) + 1]; strcpy(msg, XSECCryptoExceptionStrings[type]); } } XSECCryptoException::XSECCryptoException(XSECCryptoExceptionType eNum, safeBuffer &inMsg) { if (eNum > UnknownError) type = UnknownError; else type = eNum; msg = new char[strlen((char *) inMsg.rawBuffer()) + 1]; strcpy(msg, (char *) inMsg.rawBuffer()); } XSECCryptoException::XSECCryptoException(const XSECCryptoException &toCopy) { // Copy Constructor type = toCopy.type; if (toCopy.msg == NULL) msg = NULL; else { msg = new char[strlen(toCopy.msg) + 1]; strcpy(msg, toCopy.msg); } } XSECCryptoException::~XSECCryptoException() { if (msg != NULL) delete[] msg; } const char * XSECCryptoException::getMsg(void) const { return msg; } XSECCryptoException::XSECCryptoExceptionType XSECCryptoException::getType(void) const { return type; }
Remove extern keyword.
Remove extern keyword. git-svn-id: ec66fee5d483d38fd03726dbcf24250c625f45aa@1807269 13f79535-47bb-0310-9956-ffa450edef68
C++
apache-2.0
apache/santuario-cpp,apache/santuario-cpp,apache/santuario-cpp
51e2d5432d2d5ed90ff126dfb19171e3d73c28f8
src/Image.cpp
src/Image.cpp
#include <Image.h> #define STB_IMAGE_IMPLEMENTATION #include "stb_image.h" #include <iostream> #include <cassert> using namespace std; using namespace canvas; static InternalFormat getFormatFromChannelCount(int channels) { switch (channels) { case 1: return R8; case 2: return LUMINANCE_ALPHA; case 3: return RGB8; case 4: return RGBA8; } assert(0); return NO_FORMAT; } bool Image::decode(const unsigned char * buffer, size_t size) { int w, h, channels; auto img_buffer = stbi_load_from_memory(buffer, size, &w, &h, &channels, 0); if (!img_buffer) { cerr << "Image decoding failed: " << stbi_failure_reason() << endl; return false; } cerr << "Image.cpp: loaded image, size = " << size << ", b = " << (void*)img_buffer << ", w = " << w << ", h = " << h << ", ch = " << channels << endl; assert(w && h && channels); InternalFormat format = getFormatFromChannelCount(channels); size_t numPixels = w * h; if (channels == 2 || channels == 3 || channels == 4) { std::unique_ptr<unsigned int[]> storage(new unsigned int[numPixels]); for (unsigned int i = 0; i < numPixels; i++) { unsigned char r = img_buffer[channels * i + 0]; unsigned char g = channels >= 2 ? img_buffer[channels * i + 1] : r; unsigned char b = channels >= 3 ? img_buffer[channels * i + 2] : g; unsigned char a = channels == 4 ? img_buffer[channels * i + 3] : 0xff; if (a) { storage[i] = (0xff * b / a) + ((0xff * g / a) << 8) + ((0xff * r / a) << 16) + (a << 24); } else { storage[i] = 0; } } data = std::make_shared<ImageData>((unsigned char *)storage.get(), format, w, h); } else { data = std::make_shared<ImageData>((unsigned char *)img_buffer, format, w, h); } stbi_image_free(img_buffer); return true; } void Image::loadFile() { assert(!filename.empty()); int w, h, channels; cerr << "trying to load " << filename << endl; auto img_buffer = stbi_load(filename.c_str(), &w, &h, &channels, 0); assert(img_buffer); cerr << "Image.cpp: loaded image, filename = " << filename << ", b = " << (void*)img_buffer << ", w = " << w << ", h = " << h << ", ch = " << channels << endl; assert(w && h && channels); InternalFormat format = getFormatFromChannelCount(channels); size_t numPixels = w * h; if (channels == 2 || channels == 3 || channels == 4) { unsigned int * storage = new unsigned int[numPixels]; for (unsigned int i = 0; i < numPixels; i++) { unsigned char r = img_buffer[channels * i + 0]; unsigned char g = channels >= 2 ? img_buffer[channels * i + 1] : r; unsigned char b = channels >= 3 ? img_buffer[channels * i + 2] : g; unsigned char a = channels == 4 ? img_buffer[channels * i + 3] : 0xff; if (a) { storage[i] = (0xff * b / a) + ((0xff * g / a) << 8) + ((0xff * r / a) << 16) + (a << 24); } else { storage[i] = 0; } } data = std::make_shared<ImageData>((unsigned char *)storage, format, w, h); delete[] storage; } else { data = std::make_shared<ImageData>((unsigned char *)img_buffer, format, w, h); } stbi_image_free(img_buffer); }
#include <Image.h> #define STB_IMAGE_IMPLEMENTATION #include "stb_image.h" #include <iostream> #include <cassert> using namespace std; using namespace canvas; static InternalFormat getFormatFromChannelCount(int channels) { switch (channels) { case 1: return R8; case 2: return LUMINANCE_ALPHA; case 3: return RGB8; case 4: return RGBA8; } assert(0); return NO_FORMAT; } bool Image::decode(const unsigned char * buffer, size_t size) { int w, h, channels; auto img_buffer = stbi_load_from_memory(buffer, size, &w, &h, &channels, 0); if (!img_buffer) { cerr << "Image decoding failed: " << stbi_failure_reason() << endl; return false; } // cerr << "Image.cpp: loaded image, size = " << size << ", b = " << (void*)img_buffer << ", w = " << w << ", h = " << h << ", ch = " << channels << endl; assert(w && h && channels); InternalFormat format = getFormatFromChannelCount(channels); size_t numPixels = w * h; if (channels == 2 || channels == 3 || channels == 4) { std::unique_ptr<unsigned int[]> storage(new unsigned int[numPixels]); for (unsigned int i = 0; i < numPixels; i++) { unsigned char r = img_buffer[channels * i + 0]; unsigned char g = channels >= 2 ? img_buffer[channels * i + 1] : r; unsigned char b = channels >= 3 ? img_buffer[channels * i + 2] : g; unsigned char a = channels == 4 ? img_buffer[channels * i + 3] : 0xff; if (a) { storage[i] = (0xff * b / a) + ((0xff * g / a) << 8) + ((0xff * r / a) << 16) + (a << 24); } else { storage[i] = 0; } } data = std::make_shared<ImageData>((unsigned char *)storage.get(), format, w, h); } else { data = std::make_shared<ImageData>((unsigned char *)img_buffer, format, w, h); } stbi_image_free(img_buffer); return true; } void Image::loadFile() { assert(!filename.empty()); int w, h, channels; cerr << "trying to load " << filename << endl; auto img_buffer = stbi_load(filename.c_str(), &w, &h, &channels, 0); assert(img_buffer); // cerr << "Image.cpp: loaded image, filename = " << filename << ", b = " << (void*)img_buffer << ", w = " << w << ", h = " << h << ", ch = " << channels << endl; assert(w && h && channels); InternalFormat format = getFormatFromChannelCount(channels); size_t numPixels = w * h; if (channels == 2 || channels == 3 || channels == 4) { unsigned int * storage = new unsigned int[numPixels]; for (unsigned int i = 0; i < numPixels; i++) { unsigned char r = img_buffer[channels * i + 0]; unsigned char g = channels >= 2 ? img_buffer[channels * i + 1] : r; unsigned char b = channels >= 3 ? img_buffer[channels * i + 2] : g; unsigned char a = channels == 4 ? img_buffer[channels * i + 3] : 0xff; if (a) { storage[i] = (0xff * b / a) + ((0xff * g / a) << 8) + ((0xff * r / a) << 16) + (a << 24); } else { storage[i] = 0; } } data = std::make_shared<ImageData>((unsigned char *)storage, format, w, h); delete[] storage; } else { data = std::make_shared<ImageData>((unsigned char *)img_buffer, format, w, h); } stbi_image_free(img_buffer); }
disable debug prints
disable debug prints
C++
mit
Sometrik/canvas,rekola/canvas,rekola/canvas,Sometrik/canvas
2818aef2a731c403696fedc1b1c269b8d619777a
test/db/fiber_query_test.cpp
test/db/fiber_query_test.cpp
/* * fiber_query_test.cpp * * Created on: Mar 29, 2017 * Author: zmij */ #include <gtest/gtest.h> #ifndef WITH_BOOST_FIBERS #define WITH_BOOST_FIBERS #endif #include <tip/db/pg.hpp> #include <tip/db/pg/log.hpp> #include <pushkin/asio/fiber/shared_work.hpp> #include <boost/fiber/all.hpp> #include "db/config.hpp" #include "test-environment.hpp" namespace tip { namespace db { namespace pg { namespace test { LOCAL_LOGGING_FACILITY(PGTEST, TRACE); TEST(FiberTest, TheOnly) { if (!environment::test_database.empty()) { auto runner = ::psst::asio::fiber::use_shared_work_algorithm( db_service::io_service() ); ASSERT_NO_THROW(db_service::add_connection(environment::test_database, environment::connection_pool)); connection_options opts = connection_options::parse(environment::test_database); const auto fiber_cnt = environment::num_requests; const auto thread_cnt = environment::num_threads; auto fib_fn = [&](boost::fibers::barrier& barrier) { try { auto trx = db_service::begin(opts.alias); local_log() << "Transaction started"; EXPECT_TRUE(trx.get()); EXPECT_NO_THROW(query(trx, "create temporary table pg_async_test(b bigint)")()); local_log() << "Query one finished"; EXPECT_NO_THROW(query(trx, "insert into pg_async_test values(1),(2),(3)")()); local_log() << "Query two finished"; auto res = query(trx, "select * from pg_async_test")(); EXPECT_TRUE(res); EXPECT_EQ(1, res.columns_size()); EXPECT_EQ(3, res.size()); local_log() << "Query tree finished"; EXPECT_NO_THROW(query(trx, "drop table pg_async_test")()); local_log() << "Query four finished"; EXPECT_NO_THROW(trx->commit()); local_log() << "Transaction committed"; } catch (::std::exception const& e) { local_log(logger::ERROR) << "Exception while running test " << e.what(); } if (barrier.wait()) { db_service::stop(); } local_log() << "Fiber exit"; }; ::std::vector< ::std::thread > threads; threads.reserve(thread_cnt); boost::fibers::barrier b(fiber_cnt * thread_cnt); for(auto i = 0; i < thread_cnt; ++i) { threads.emplace_back([&](){ auto runner = ::psst::asio::fiber::use_shared_work_algorithm( db_service::io_service() ); for (auto i = 0; i < fiber_cnt; ++i) { fiber{ fib_fn, ::std::ref(b) }.detach(); } runner->run(); local_log() << "Thread exit"; }); } for (auto& t : threads) { t.join(); } } } } /* namespace test */ } /* namespace pg */ } /* namespace db */ } /* namespace tip */
/* * fiber_query_test.cpp * * Created on: Mar 29, 2017 * Author: zmij */ #include <gtest/gtest.h> #ifndef WITH_BOOST_FIBERS #define WITH_BOOST_FIBERS #endif #include <tip/db/pg.hpp> #include <tip/db/pg/log.hpp> #include <pushkin/asio/fiber/shared_work.hpp> #include <boost/fiber/all.hpp> #include "db/config.hpp" #include "test-environment.hpp" namespace tip { namespace db { namespace pg { namespace test { LOCAL_LOGGING_FACILITY(PGTEST, TRACE); TEST(FiberTest, DISABLED_TheOnly) { if (!environment::test_database.empty()) { auto runner = ::psst::asio::fiber::use_shared_work_algorithm( db_service::io_service() ); ASSERT_NO_THROW(db_service::add_connection(environment::test_database, environment::connection_pool)); connection_options opts = connection_options::parse(environment::test_database); const auto fiber_cnt = environment::num_requests; const auto thread_cnt = environment::num_threads; auto fib_fn = [&](boost::fibers::barrier& barrier) { try { auto trx = db_service::begin(opts.alias); local_log() << "Transaction started"; EXPECT_TRUE(trx.get()); EXPECT_NO_THROW(query(trx, "create temporary table pg_async_test(b bigint)")()); local_log() << "Query one finished"; EXPECT_NO_THROW(query(trx, "insert into pg_async_test values(1),(2),(3)")()); local_log() << "Query two finished"; auto res = query(trx, "select * from pg_async_test")(); EXPECT_TRUE(res); EXPECT_EQ(1, res.columns_size()); EXPECT_EQ(3, res.size()); local_log() << "Query tree finished"; EXPECT_NO_THROW(query(trx, "drop table pg_async_test")()); local_log() << "Query four finished"; EXPECT_NO_THROW(trx->commit()); local_log() << "Transaction committed"; } catch (::std::exception const& e) { local_log(logger::ERROR) << "Exception while running test " << e.what(); } if (barrier.wait()) { db_service::stop(); } local_log() << "Fiber exit"; }; ::std::vector< ::std::thread > threads; threads.reserve(thread_cnt); boost::fibers::barrier b(fiber_cnt * thread_cnt); for(auto i = 0; i < thread_cnt; ++i) { threads.emplace_back([&](){ auto runner = ::psst::asio::fiber::use_shared_work_algorithm( db_service::io_service() ); for (auto i = 0; i < fiber_cnt; ++i) { fiber{ fib_fn, ::std::ref(b) }.detach(); } runner->run(); local_log() << "Thread exit"; }); } for (auto& t : threads) { t.join(); } } } } /* namespace test */ } /* namespace pg */ } /* namespace db */ } /* namespace tip */
Disable PG fiber test
Disable PG fiber test
C++
artistic-2.0
zmij/pg_async
ffd230975227b192dc943e2f2bb7f8d5a957fd4e
test/gtest_version_tests.cpp
test/gtest_version_tests.cpp
//====================================================================== //----------------------------------------------------------------------- /** * @file gtest_version_tests.cpp * @brief gtest version detect test * * @author t.shirayanagi * @par copyright * Copyright (C) 2018, Takazumi Shirayanagi\n * This software is released under the new BSD License, * see LICENSE */ //----------------------------------------------------------------------- //====================================================================== //====================================================================== // include #include "iutest.hpp" #if defined(IUTEST_USE_GTEST) #if defined(GTEST_EXPECT_VER) IUTEST(GTest, Version) { IUTEST_ASSUME_GT(GTEST_EXPECT_VER, 0); IUTEST_EXPECT_EQ(GTEST_EXPECT_VER, GTEST_VER); } #endif #if defined(GTEST_EXPECT_LATEST) IUTEST(GTest, Latest) { IUTEST_EXPECT_EQ(GTEST_EXPECT_LATEST, GTEST_LATEST); } #endif #endif #if defined(IUTEST_USE_GMOCK) #if !defined(GMOCK_EXPECT_VER) && defined(GTEST_EXPECT_VER) # define GMOCK_EXPECT_VER GTEST_EXPECT_VER #endif #if defined(GMOCK_EXPECT_VER) IUTEST(GMock, Version) { IUTEST_ASSUME_GT(GMOCK_EXPECT_VER, 0); IUTEST_EXPECT_EQ(GMOCK_EXPECT_VER, GMOCK_VER); } #endif #endif #if !defined(GMOCK_EXPECT_LATEST) && defined(GTEST_EXPECT_LATEST) # define GMOCK_EXPECT_LATEST GTEST_EXPECT_LATEST #endif #if defined(GMOCK_EXPECT_LATEST) IUTEST(GMock, Latest) { IUTEST_EXPECT_EQ(GMOCK_EXPECT_LATEST, GMOCK_LATEST); } #endif #ifdef UNICODE int wmain(int argc, wchar_t* argv[]) #else int main(int argc, char* argv[]) #endif { IUTEST_INIT(&argc, argv); return IUTEST_RUN_ALL_TESTS(); }
//====================================================================== //----------------------------------------------------------------------- /** * @file gtest_version_tests.cpp * @brief gtest version detect test * * @author t.shirayanagi * @par copyright * Copyright (C) 2018, Takazumi Shirayanagi\n * This software is released under the new BSD License, * see LICENSE */ //----------------------------------------------------------------------- //====================================================================== //====================================================================== // include #include "iutest.hpp" #if defined(IUTEST_USE_GTEST) #if defined(GTEST_EXPECT_VER) IUTEST(GTest, Version) { IUTEST_ASSUME_GT(GTEST_EXPECT_VER, 0); IUTEST_EXPECT_EQ(GTEST_EXPECT_VER, GTEST_VER); } #endif #if defined(GTEST_EXPECT_LATEST) IUTEST(GTest, Latest) { IUTEST_EXPECT_EQ(GTEST_EXPECT_LATEST, GTEST_LATEST); } #endif #endif #if defined(IUTEST_USE_GMOCK) #if !defined(GMOCK_EXPECT_VER) && defined(GTEST_EXPECT_VER) # define GMOCK_EXPECT_VER GTEST_EXPECT_VER #endif #if defined(GMOCK_EXPECT_VER) IUTEST(GMock, Version) { IUTEST_ASSUME_GT(GMOCK_EXPECT_VER, 0); IUTEST_EXPECT_EQ(GMOCK_EXPECT_VER, GMOCK_VER); } #endif #if !defined(GMOCK_EXPECT_LATEST) && defined(GTEST_EXPECT_LATEST) # define GMOCK_EXPECT_LATEST GTEST_EXPECT_LATEST #endif #if defined(GMOCK_EXPECT_LATEST) IUTEST(GMock, Latest) { IUTEST_EXPECT_EQ(GMOCK_EXPECT_LATEST, GMOCK_LATEST); } #endif #endif #ifdef UNICODE int wmain(int argc, wchar_t* argv[]) #else int main(int argc, char* argv[]) #endif { IUTEST_INIT(&argc, argv); return IUTEST_RUN_ALL_TESTS(); }
fix test
fix test
C++
bsd-3-clause
srz-zumix/iutest,srz-zumix/iutest,srz-zumix/iutest,srz-zumix/iutest,srz-zumix/iutest
536cecaadfe4d06ddbf27f76a0d771d6c38d89fa
STEER/AliMagFMaps.cxx
STEER/AliMagFMaps.cxx
/************************************************************************** * Copyright(c) 1998-1999, ALICE Experiment at CERN, All rights reserved. * * * * Author: The ALICE Off-line Project. * * Contributors are mentioned in the code where appropriate. * * * * Permission to use, copy, modify and distribute this software and its * * documentation strictly for non-commercial purposes is hereby granted * * without fee, provided that the above copyright notice appears in all * * copies and that both the copyright notice and this permission notice * * appear in the supporting documentation. The authors make no claims * * about the suitability of this software for any purpose. It is * * provided "as is" without express or implied warranty. * **************************************************************************/ /* $Log$ Revision 1.1 2002/02/14 11:41:28 morsch Magnetic field map for ALICE for L3+muon spectrometer stored in 3 seperate root files. */ // // Author: Andreas Morsch <[email protected]> // #include <TFile.h> #include <TSystem.h> #include "AliFieldMap.h" #include "AliMagFMaps.h" ClassImp(AliMagFMaps) //________________________________________ AliMagFMaps::AliMagFMaps(const char *name, const char *title, const Int_t integ, const Float_t factor, const Float_t fmax, const Int_t map) : AliMagF(name,title,integ,factor,fmax) { // // Standard constructor // fType = kConMesh; fFieldMap[0] = 0; char* fname; fMap = map; TFile* file = 0; if(fDebug>-1) printf("%s: Constant Mesh Field %s created: map= %d, factor= %f, file= %s\n", ClassName(),fName.Data(), fMap, factor,fTitle.Data()); if (fMap == k2kG) { fname = gSystem->ExpandPathName("$(ALICE_ROOT)/data/maps/L3B02.root"); file = new TFile(fname); fFieldMap[0] = (AliFieldMap*) file->Get("L3B02"); file->Close(); delete file; fname = gSystem->ExpandPathName("$(ALICE_ROOT)/data/maps/DipB02.root"); file = new TFile(fname); fFieldMap[1] = (AliFieldMap*) file->Get("DipB02"); file->Close(); delete file;; fname = gSystem->ExpandPathName("$(ALICE_ROOT)/data/maps/ExtB02.root"); file = new TFile(fname); fFieldMap[2] = (AliFieldMap*) file->Get("ExtB02"); file->Close(); delete file; fSolenoid = 2.; } else if (fMap == k4kG) { fname = gSystem->ExpandPathName("$(ALICE_ROOT)/data/maps/L3B04.root"); file = new TFile(fname); fFieldMap[0] = (AliFieldMap*) file->Get("L3B04"); file->Close(); delete file; fname = gSystem->ExpandPathName("$(ALICE_ROOT)/data/maps/DipB04.root"); file = new TFile(fname); fFieldMap[1] = (AliFieldMap*) file->Get("DipB04"); file->Close(); delete file;; fname = gSystem->ExpandPathName("$(ALICE_ROOT)/data/maps/ExtB04.root"); file = new TFile(fname); fFieldMap[2] = (AliFieldMap*) file->Get("ExtB04"); file->Close(); delete file; fSolenoid = 4.; } else if (fMap == k5kG) { fname = gSystem->ExpandPathName("$(ALICE_ROOT)/data/maps/L3B05.root"); file = new TFile(fname); fFieldMap[0] = (AliFieldMap*) file->Get("L3B05"); file->Close(); delete file; fname = gSystem->ExpandPathName("$(ALICE_ROOT)/data/maps/DipB05.root"); file = new TFile(fname); fFieldMap[1] = (AliFieldMap*) file->Get("DipB05"); file->Close(); delete file;; fname = gSystem->ExpandPathName("$(ALICE_ROOT)/data/maps/ExtB05.root"); file = new TFile(fname); fFieldMap[2] = (AliFieldMap*) file->Get("ExtB05"); file->Close(); delete file; fSolenoid = 5.; } SetL3ConstField(0); } //________________________________________ AliMagFMaps::AliMagFMaps(const AliMagFMaps &magf) { // // Copy constructor // magf.Copy(*this); } AliMagFMaps::~AliMagFMaps() { // // Destructor // delete fFieldMap[0]; delete fFieldMap[1]; delete fFieldMap[2]; } Float_t AliMagFMaps::SolenoidField() const { // // Returns max. L3 (solenoid) field strength // according to field map setting return fSolenoid; } //________________________________________ void AliMagFMaps::Field(Float_t *x, Float_t *b) { // // Method to calculate the magnetic field // Double_t ratx, raty, ratz, hix, hiy, hiz, ratx1, raty1, ratz1, bhyhz, bhylz, blyhz, blylz, bhz, blz, xl[3]; const Double_t kone=1; Int_t ix, iy, iz; // --- find the position in the grid --- b[0]=b[1]=b[2]=0; AliFieldMap* map = 0; if (fFieldMap[0]->Inside(x[0], x[1], x[2])) { map = fFieldMap[0]; if (fL3Option) { // // Constant L3 field, if this option was selected // b[2] = fSolenoid; return; } } else if (fFieldMap[1]->Inside(x[0], x[1], x[2])) { map = fFieldMap[1]; } else if (fFieldMap[2]->Inside(x[0], x[1], x[2])) { map = fFieldMap[2]; } if(map){ map->Field(x,b); } else { //This is the ZDC part Float_t rad2=x[0]*x[0]+x[1]*x[1]; if(x[2]>kCORBEG2 && x[2]<kCOREND2){ if(rad2<kCOR2RA2){ b[0] = kFCORN2; } } else if(x[2]>kZ1BEG && x[2]<kZ1END){ if(rad2<kZ1RA2){ b[0] = -kG1*x[1]; b[1] = -kG1*x[0]; } } else if(x[2]>kZ2BEG && x[2]<kZ2END){ if(rad2<kZ2RA2){ b[0] = kG1*x[1]; b[1] = kG1*x[0]; } } else if(x[2]>kZ3BEG && x[2]<kZ3END){ if(rad2<kZ3RA2){ b[0] = kG1*x[1]; b[1] = kG1*x[0]; } } else if(x[2]>kZ4BEG && x[2]<kZ4END){ if(rad2<kZ4RA2){ b[0] = -kG1*x[1]; b[1] = -kG1*x[0]; } } else if(x[2]>kD1BEG && x[2]<kD1END){ if(rad2<kD1RA2){ b[1] = -kFDIP; } } else if(x[2]>kD2BEG && x[2]<kD2END){ if(((x[0]-kXCEN1D2)*(x[0]-kXCEN1D2)+(x[1]-kYCEN1D2)*(x[1]-kYCEN1D2))<kD2RA2 || ((x[0]-kXCEN2D2)*(x[0]-kXCEN2D2)+(x[1]-kYCEN2D2)*(x[1]-kYCEN2D2))<kD2RA2){ b[1] = kFDIP; } } } if(fFactor!=1) { b[0]*=fFactor; b[1]*=fFactor; b[2]*=fFactor; } } //________________________________________ void AliMagFMaps::Copy(AliMagFMaps & /* magf */) const { // // Copy *this onto magf -- Not implemented // Fatal("Copy","Not implemented!\n"); } //________________________________________ AliMagFMaps & AliMagFMaps::operator =(const AliMagFMaps &magf) { magf.Copy(*this); return *this; }
/************************************************************************** * Copyright(c) 1998-1999, ALICE Experiment at CERN, All rights reserved. * * * * Author: The ALICE Off-line Project. * * Contributors are mentioned in the code where appropriate. * * * * Permission to use, copy, modify and distribute this software and its * * documentation strictly for non-commercial purposes is hereby granted * * without fee, provided that the above copyright notice appears in all * * copies and that both the copyright notice and this permission notice * * appear in the supporting documentation. The authors make no claims * * about the suitability of this software for any purpose. It is * * provided "as is" without express or implied warranty. * **************************************************************************/ /* $Log$ Revision 1.2 2002/02/19 16:14:35 morsch Reading of 0.2 T solenoid field map enabled. Revision 1.1 2002/02/14 11:41:28 morsch Magnetic field map for ALICE for L3+muon spectrometer stored in 3 seperate root files. */ // // Author: Andreas Morsch <[email protected]> // #include <TFile.h> #include <TSystem.h> #include "AliFieldMap.h" #include "AliMagFMaps.h" ClassImp(AliMagFMaps) //________________________________________ AliMagFMaps::AliMagFMaps(const char *name, const char *title, const Int_t integ, const Float_t factor, const Float_t fmax, const Int_t map) : AliMagF(name,title,integ,factor,fmax) { // // Standard constructor // fType = kConMesh; fFieldMap[0] = 0; char* fname; fMap = map; TFile* file = 0; if (fMap == k2kG) { if (fL3Option) { fFieldMap[0] = new AliFieldMap(); fFieldMap[0]->SetLimits(-800., 800., -800., 800., -700., 700.); } else { fname = gSystem->ExpandPathName("$(ALICE_ROOT)/data/maps/L3B02.root"); file = new TFile(fname); fFieldMap[0] = (AliFieldMap*) file->Get("L3B02"); file->Close(); delete file; fname = gSystem->ExpandPathName("$(ALICE_ROOT)/data/maps/DipB02.root"); file = new TFile(fname); fFieldMap[1] = (AliFieldMap*) file->Get("DipB02"); file->Close(); delete file;; fname = gSystem->ExpandPathName("$(ALICE_ROOT)/data/maps/ExtB02.root"); file = new TFile(fname); fFieldMap[2] = (AliFieldMap*) file->Get("ExtB02"); file->Close(); delete file; } fSolenoid = 2.; } else if (fMap == k4kG) { fname = gSystem->ExpandPathName("$(ALICE_ROOT)/data/maps/L3B04.root"); file = new TFile(fname); fFieldMap[0] = (AliFieldMap*) file->Get("L3B04"); file->Close(); delete file; fname = gSystem->ExpandPathName("$(ALICE_ROOT)/data/maps/DipB04.root"); file = new TFile(fname); fFieldMap[1] = (AliFieldMap*) file->Get("DipB04"); file->Close(); delete file;; fname = gSystem->ExpandPathName("$(ALICE_ROOT)/data/maps/ExtB04.root"); file = new TFile(fname); fFieldMap[2] = (AliFieldMap*) file->Get("ExtB04"); file->Close(); delete file; fSolenoid = 4.; } else if (fMap == k5kG) { fname = gSystem->ExpandPathName("$(ALICE_ROOT)/data/maps/L3B05.root"); file = new TFile(fname); fFieldMap[0] = (AliFieldMap*) file->Get("L3B05"); file->Close(); delete file; fname = gSystem->ExpandPathName("$(ALICE_ROOT)/data/maps/DipB05.root"); file = new TFile(fname); fFieldMap[1] = (AliFieldMap*) file->Get("DipB05"); file->Close(); delete file;; fname = gSystem->ExpandPathName("$(ALICE_ROOT)/data/maps/ExtB05.root"); file = new TFile(fname); fFieldMap[2] = (AliFieldMap*) file->Get("ExtB05"); file->Close(); delete file; fSolenoid = 5.; } SetL3ConstField(0); } //________________________________________ AliMagFMaps::AliMagFMaps(const AliMagFMaps &magf) { // // Copy constructor // magf.Copy(*this); } AliMagFMaps::~AliMagFMaps() { // // Destructor // delete fFieldMap[0]; delete fFieldMap[1]; delete fFieldMap[2]; } Float_t AliMagFMaps::SolenoidField() const { // // Returns max. L3 (solenoid) field strength // according to field map setting return fSolenoid; } //________________________________________ void AliMagFMaps::Field(Float_t *x, Float_t *b) { // // Method to calculate the magnetic field // const Double_t kone=1; // --- find the position in the grid --- b[0]=b[1]=b[2]=0; AliFieldMap* map = 0; if (fFieldMap[0]->Inside(x[0], x[1], x[2])) { map = fFieldMap[0]; if (fL3Option) { // // Constant L3 field, if this option was selected // b[2] = fSolenoid; return; } } else if (fFieldMap[1]->Inside(x[0], x[1], x[2])) { map = fFieldMap[1]; } else if (fFieldMap[2]->Inside(x[0], x[1], x[2])) { map = fFieldMap[2]; } if(map){ map->Field(x,b); } else { //This is the ZDC part Float_t rad2=x[0]*x[0]+x[1]*x[1]; if(x[2]>kCORBEG2 && x[2]<kCOREND2){ if(rad2<kCOR2RA2){ b[0] = kFCORN2; } } else if(x[2]>kZ1BEG && x[2]<kZ1END){ if(rad2<kZ1RA2){ b[0] = -kG1*x[1]; b[1] = -kG1*x[0]; } } else if(x[2]>kZ2BEG && x[2]<kZ2END){ if(rad2<kZ2RA2){ b[0] = kG1*x[1]; b[1] = kG1*x[0]; } } else if(x[2]>kZ3BEG && x[2]<kZ3END){ if(rad2<kZ3RA2){ b[0] = kG1*x[1]; b[1] = kG1*x[0]; } } else if(x[2]>kZ4BEG && x[2]<kZ4END){ if(rad2<kZ4RA2){ b[0] = -kG1*x[1]; b[1] = -kG1*x[0]; } } else if(x[2]>kD1BEG && x[2]<kD1END){ if(rad2<kD1RA2){ b[1] = -kFDIP; } } else if(x[2]>kD2BEG && x[2]<kD2END){ if(((x[0]-kXCEN1D2)*(x[0]-kXCEN1D2)+(x[1]-kYCEN1D2)*(x[1]-kYCEN1D2))<kD2RA2 || ((x[0]-kXCEN2D2)*(x[0]-kXCEN2D2)+(x[1]-kYCEN2D2)*(x[1]-kYCEN2D2))<kD2RA2){ b[1] = kFDIP; } } } if(fFactor!=1) { b[0]*=fFactor; b[1]*=fFactor; b[2]*=fFactor; } } //________________________________________ void AliMagFMaps::Copy(AliMagFMaps & /* magf */) const { // // Copy *this onto magf -- Not implemented // Fatal("Copy","Not implemented!\n"); } //________________________________________ AliMagFMaps & AliMagFMaps::operator =(const AliMagFMaps &magf) { magf.Copy(*this); return *this; }
Create dummy field map for L3 in case no detailed map is needed.
Create dummy field map for L3 in case no detailed map is needed.
C++
bsd-3-clause
alisw/AliRoot,sebaleh/AliRoot,mkrzewic/AliRoot,coppedis/AliRoot,coppedis/AliRoot,miranov25/AliRoot,alisw/AliRoot,ALICEHLT/AliRoot,shahor02/AliRoot,ecalvovi/AliRoot,miranov25/AliRoot,ALICEHLT/AliRoot,mkrzewic/AliRoot,shahor02/AliRoot,shahor02/AliRoot,miranov25/AliRoot,ALICEHLT/AliRoot,coppedis/AliRoot,ALICEHLT/AliRoot,shahor02/AliRoot,jgrosseo/AliRoot,miranov25/AliRoot,ALICEHLT/AliRoot,ALICEHLT/AliRoot,jgrosseo/AliRoot,jgrosseo/AliRoot,ecalvovi/AliRoot,ALICEHLT/AliRoot,jgrosseo/AliRoot,mkrzewic/AliRoot,alisw/AliRoot,mkrzewic/AliRoot,ecalvovi/AliRoot,ecalvovi/AliRoot,alisw/AliRoot,jgrosseo/AliRoot,miranov25/AliRoot,alisw/AliRoot,sebaleh/AliRoot,mkrzewic/AliRoot,shahor02/AliRoot,miranov25/AliRoot,shahor02/AliRoot,ecalvovi/AliRoot,coppedis/AliRoot,shahor02/AliRoot,sebaleh/AliRoot,mkrzewic/AliRoot,ecalvovi/AliRoot,alisw/AliRoot,coppedis/AliRoot,ecalvovi/AliRoot,jgrosseo/AliRoot,alisw/AliRoot,mkrzewic/AliRoot,alisw/AliRoot,sebaleh/AliRoot,miranov25/AliRoot,sebaleh/AliRoot,miranov25/AliRoot,coppedis/AliRoot,coppedis/AliRoot,jgrosseo/AliRoot,sebaleh/AliRoot,sebaleh/AliRoot,coppedis/AliRoot
d0de22d03e572048400618d367e1cba20718fd3c
Shooter/PlayState.cpp
Shooter/PlayState.cpp
#include "PlayState.h" #include "TextureManager.h" #include "Game.h" #include "Player.h" #include "Enemy.h" #include "InputHandler.h" #include "PauseState.h" #include "GameOverState.h" const std::string PlayState::s_playID = "PLAY"; void PlayState::update() { if (InputHandler::Instance()->isKeyDown(SDL_SCANCODE_ESCAPE)) { Game::Instance()->getStateMachine()->pushState(new PauseState()); } for (int i = 0; i < m_gameObjects.size(); i++) { m_gameObjects[i]->update(); } if (checkCollision(dynamic_cast<SDLGameObject*>(m_gameObjects[0]), dynamic_cast<SDLGameObject*>(m_gameObjects[1]))) { Game::Instance()->getStateMachine()->pushState(new GameOverState()); } } void PlayState::render() { for (int i = 0; i < m_gameObjects.size(); i++) { m_gameObjects[i]->draw(); } } bool PlayState::onEnter() { LevelParser levelParser; pLevel = levelParser.parseLevel("assets/space_tile_map.tmx"); if (!TextureManager::Instance()->load( "assets/helicopter.png", "helicopter", Game::Instance()->getRenderer())) { return false; } if (!TextureManager::Instance()->load( "assets/helicopter2.png", "helicopter2", Game::Instance()->getRenderer())) { return false; } GameObject* player = new Player( new LoaderParams(100, 100, 128, 55, "helicopter")); GameObject* enemy = new Enemy( new LoaderParams(500, 100, 128, 55, "helicopter2")); m_gameObjects.push_back(player); m_gameObjects.push_back(enemy); std::cout << "Entering PlayState" << std::endl; return true; } bool PlayState::onExit() { for (int i = 0; i < m_gameObjects.size(); i++) { m_gameObjects[i]->clean(); } m_gameObjects.clear(); TextureManager::Instance()->clearFromTextureMap("helicopter"); std::cout << "Exiting PlayState" << std::endl; return true; } bool PlayState::checkCollision(SDLGameObject* p1, SDLGameObject* p2) { int leftA, leftB; int rightA, rightB; int topA, topB; int bottomA, bottomB; leftA = p1->getPosition().getX(); rightA = leftA + p1->getWidth(); topA = p1->getPosition().getY(); bottomA = topA + p1->getHeight(); leftB = p2->getPosition().getX(); rightB = leftB + p2->getWidth(); topB = p2->getPosition().getY(); bottomB = topB + p2->getHeight(); if (bottomA < topB) return false; if (bottomB < topA) return false; if (rightA < leftB) return false; if (leftA > rightB) return false; return true; }
#include "PlayState.h" #include "TextureManager.h" #include "Game.h" #include "Player.h" #include "Enemy.h" #include "InputHandler.h" #include "PauseState.h" #include "GameOverState.h" const std::string PlayState::s_playID = "PLAY"; void PlayState::update() { if (InputHandler::Instance()->isKeyDown(SDL_SCANCODE_ESCAPE)) { Game::Instance()->getStateMachine()->pushState(new PauseState()); } for (int i = 0; i < m_gameObjects.size(); i++) { m_gameObjects[i]->update(); } if (checkCollision(dynamic_cast<SDLGameObject*>(m_gameObjects[0]), dynamic_cast<SDLGameObject*>(m_gameObjects[1]))) { Game::Instance()->getStateMachine()->changeState(new GameOverState()); } } void PlayState::render() { for (int i = 0; i < m_gameObjects.size(); i++) { m_gameObjects[i]->draw(); } } bool PlayState::onEnter() { LevelParser levelParser; pLevel = levelParser.parseLevel("assets/space_tile_map.tmx"); if (!TextureManager::Instance()->load( "assets/helicopter.png", "helicopter", Game::Instance()->getRenderer())) { return false; } if (!TextureManager::Instance()->load( "assets/helicopter2.png", "helicopter2", Game::Instance()->getRenderer())) { return false; } GameObject* player = new Player( new LoaderParams(100, 100, 128, 55, "helicopter")); GameObject* enemy = new Enemy( new LoaderParams(500, 100, 128, 55, "helicopter2")); m_gameObjects.push_back(player); m_gameObjects.push_back(enemy); std::cout << "Entering PlayState" << std::endl; return true; } bool PlayState::onExit() { for (int i = 0; i < m_gameObjects.size(); i++) { m_gameObjects[i]->clean(); } m_gameObjects.clear(); TextureManager::Instance()->clearFromTextureMap("helicopter"); std::cout << "Exiting PlayState" << std::endl; return true; } bool PlayState::checkCollision(SDLGameObject* p1, SDLGameObject* p2) { int leftA, leftB; int rightA, rightB; int topA, topB; int bottomA, bottomB; leftA = p1->getPosition().getX(); rightA = leftA + p1->getWidth(); topA = p1->getPosition().getY(); bottomA = topA + p1->getHeight(); leftB = p2->getPosition().getX(); rightB = leftB + p2->getWidth(); topB = p2->getPosition().getY(); bottomB = topB + p2->getHeight(); if (bottomA < topB) return false; if (bottomB < topA) return false; if (rightA < leftB) return false; if (leftA > rightB) return false; return true; }
Replace pushState with changeState
Replace pushState with changeState
C++
mit
ducki13/Shooter
5cf09728b6d3e29ae60633c097a8060ad8e34da3
SmartMatrixApa102.cpp
SmartMatrixApa102.cpp
#define SMARTMATRIX_ENABLED 1 #include "application.h" #if (SMARTMATRIX_ENABLED == 1) #include <SmartMatrix3.h> #endif #include "FastLED/FastLED.h" FASTLED_USING_NAMESPACE; #if (SMARTMATRIX_ENABLED == 1) #define COLOR_DEPTH 24 // known working: 24, 48 - If the sketch uses type `rgb24` directly, COLOR_DEPTH must be 24 const uint8_t kMatrixWidth = 16; // known working: 16, 32, 48, 64 const uint8_t kMatrixHeight = 16; // known working: 32, 64, 96, 128 const uint8_t kRefreshDepth = 36; // known working: 24, 36, 48 const uint8_t kDmaBufferRows = 4; // known working: 2-4, use 2 to save memory, more to keep from dropping frames and automatically lowering refresh rate const uint8_t kPanelType = 0; // use SMARTMATRIX_HUB75_16ROW_MOD8SCAN for common 16x32 panels const uint8_t kMatrixOptions = (SMARTMATRIX_OPTIONS_NONE); // see http://docs.pixelmatix.com/SmartMatrix for options const uint8_t kBackgroundLayerOptions = (SM_BACKGROUND_OPTIONS_NONE); const uint8_t kScrollingLayerOptions = (SM_SCROLLING_OPTIONS_NONE); SMARTMATRIX_ALLOCATE_BUFFERS(matrix, kMatrixWidth, kMatrixHeight, kRefreshDepth, kDmaBufferRows, kPanelType, kMatrixOptions); SMARTMATRIX_ALLOCATE_BACKGROUND_LAYER(backgroundLayer, kMatrixWidth, kMatrixHeight, COLOR_DEPTH, kBackgroundLayerOptions); SMARTMATRIX_ALLOCATE_SCROLLING_LAYER(scrollingLayer, kMatrixWidth, kMatrixHeight, COLOR_DEPTH, kScrollingLayerOptions); rgb24 *buffer; const uint16_t NUM_LEDS = kMatrixWidth * kMatrixHeight; #else #define DATA_PIN D2 #define CLOCK_PIN D4 #define COLOR_ORDER RGB #define CHIPSET APA102 // Params for width and height const uint8_t kMatrixWidth = 16; const uint8_t kMatrixHeight = 16; const uint16_t NUM_LEDS = kMatrixWidth * kMatrixHeight; CRGB leds_plus_safety_pixel[ NUM_LEDS + 1]; CRGB* leds( leds_plus_safety_pixel + 1); #endif const uint8_t scale = 256 / kMatrixWidth; #if (SMARTMATRIX_ENABLED == 1) uint16_t XY(uint8_t x, uint8_t y) { return kMatrixWidth * y + x; } #else uint16_t XY( uint8_t x, uint8_t y) { uint16_t i; if( y & 0x01) { // Odd rows run backwards uint8_t reverseX = (kMatrixWidth - 1) - x; i = (y * kMatrixWidth) + reverseX; } else { // Even rows run forwards i = (y * kMatrixWidth) + x; } return i; } #endif #if (SMARTMATRIX_ENABLED == 1) // scale the brightness of all pixels down void dimAll(byte value) { for (int i = 0; i < NUM_LEDS; i++) { CRGB c = CRGB(buffer[i].red, buffer[i].green, buffer[i].blue); c.nscale8(value); buffer[i] = c; } } #else // scale the brightness of all pixels down void dimAll(byte value) { for (int i = 0; i < NUM_LEDS; i++) { CRGB c = leds[i]; c.nscale8(value); leds[i] = c; } } #endif #define BRIGHTNESS 255 void setup() { #if (SMARTMATRIX_ENABLED == 1) matrix.addLayer(&backgroundLayer); matrix.addLayer(&scrollingLayer); matrix.begin(); matrix.setBrightness(BRIGHTNESS); backgroundLayer.enableColorCorrection(false); #else FastLED.addLeds<CHIPSET, DATA_PIN, CLOCK_PIN, COLOR_ORDER, DATA_RATE_MHZ(1)>(leds, NUM_LEDS).setCorrection(TypicalSMD5050); FastLED.setBrightness( BRIGHTNESS ); FastLED.setDither(BINARY_DITHER); #endif } void loop() { EVERY_N_MILLISECONDS(1000/60) { #if (SMARTMATRIX_ENABLED == 1) buffer = backgroundLayer.backBuffer(); #endif dimAll(250); static uint8_t theta = 0; static uint8_t hue = 0; for (uint8_t x = 0; x < kMatrixWidth; x++) { uint8_t y = quadwave8(x * 2 + theta) / scale; #if (SMARTMATRIX_ENABLED == 1) buffer[XY(x, y)] = CRGB(CHSV(x + hue, 255, 255)); #else leds[XY(x, y)] = CRGB(CHSV(x + hue, 255, 255)); #endif } theta++; hue++; #if (SMARTMATRIX_ENABLED == 1) backgroundLayer.swapBuffers(true); #endif } #if (SMARTMATRIX_ENABLED == 0) FastLED.show(); #endif }
#define SMARTMATRIX_ENABLED 1 #include "application.h" #if (SMARTMATRIX_ENABLED == 1) #include <SmartMatrix3.h> #endif #include "FastLED/FastLED.h" FASTLED_USING_NAMESPACE; #if (SMARTMATRIX_ENABLED == 1) #define COLOR_DEPTH 24 // known working: 24, 48 - If the sketch uses type `rgb24` directly, COLOR_DEPTH must be 24 const uint8_t kMatrixWidth = 16; // known working: 16, 32, 48, 64 const uint8_t kMatrixHeight = 16; // known working: 32, 64, 96, 128 const uint8_t kRefreshDepth = 36; // known working: 24, 36, 48 const uint8_t kDmaBufferRows = 4; // known working: 2-4, use 2 to save memory, more to keep from dropping frames and automatically lowering refresh rate const uint8_t kPanelType = 0; // use SMARTMATRIX_HUB75_16ROW_MOD8SCAN for common 16x32 panels const uint8_t kMatrixOptions = (SMARTMATRIX_OPTIONS_NONE); // see http://docs.pixelmatix.com/SmartMatrix for options const uint8_t kBackgroundLayerOptions = (SM_BACKGROUND_OPTIONS_NONE); const uint8_t kScrollingLayerOptions = (SM_SCROLLING_OPTIONS_NONE); SMARTMATRIX_ALLOCATE_BUFFERS(matrix, kMatrixWidth, kMatrixHeight, kRefreshDepth, kDmaBufferRows, kPanelType, kMatrixOptions); SMARTMATRIX_ALLOCATE_BACKGROUND_LAYER(backgroundLayer, kMatrixWidth, kMatrixHeight, COLOR_DEPTH, kBackgroundLayerOptions); SMARTMATRIX_ALLOCATE_SCROLLING_LAYER(scrollingLayer, kMatrixWidth, kMatrixHeight, COLOR_DEPTH, kScrollingLayerOptions); rgb24 *buffer; const uint16_t NUM_LEDS = kMatrixWidth * kMatrixHeight; #else #define DATA_PIN D2 #define CLOCK_PIN D4 #define COLOR_ORDER BGR #define CHIPSET APA102 // Params for width and height const uint8_t kMatrixWidth = 16; const uint8_t kMatrixHeight = 16; const uint16_t NUM_LEDS = kMatrixWidth * kMatrixHeight; CRGB leds_plus_safety_pixel[ NUM_LEDS + 1]; CRGB* leds( leds_plus_safety_pixel + 1); #endif const uint8_t scale = 256 / kMatrixWidth; #if (SMARTMATRIX_ENABLED == 1) uint16_t XY(uint8_t x, uint8_t y) { return kMatrixWidth * y + x; } #else uint16_t XY( uint8_t x, uint8_t y) { uint16_t i; if( y & 0x01) { // Odd rows run backwards uint8_t reverseX = (kMatrixWidth - 1) - x; i = (y * kMatrixWidth) + reverseX; } else { // Even rows run forwards i = (y * kMatrixWidth) + x; } return i; } #endif #if (SMARTMATRIX_ENABLED == 1) // scale the brightness of all pixels down void dimAll(byte value) { for (int i = 0; i < NUM_LEDS; i++) { CRGB c = CRGB(buffer[i].red, buffer[i].green, buffer[i].blue); c.nscale8(value); buffer[i] = c; } } #else // scale the brightness of all pixels down void dimAll(byte value) { for (int i = 0; i < NUM_LEDS; i++) { CRGB c = leds[i]; c.nscale8(value); leds[i] = c; } } #endif #define BRIGHTNESS 255 void setup() { #if (SMARTMATRIX_ENABLED == 1) matrix.addLayer(&backgroundLayer); matrix.addLayer(&scrollingLayer); matrix.begin(); matrix.setBrightness(BRIGHTNESS); backgroundLayer.enableColorCorrection(false); #else FastLED.addLeds<CHIPSET, DATA_PIN, CLOCK_PIN, COLOR_ORDER, DATA_RATE_MHZ(1)>(leds, NUM_LEDS).setCorrection(TypicalSMD5050); FastLED.setBrightness( BRIGHTNESS ); FastLED.setDither(BINARY_DITHER); //FastLED.setDither(DISABLE_DITHER); #endif } void loop() { EVERY_N_MILLISECONDS(1000/60) { #if (SMARTMATRIX_ENABLED == 1) buffer = backgroundLayer.backBuffer(); #endif dimAll(250); static uint8_t theta = 0; static uint8_t hue = 0; for (uint8_t x = 0; x < kMatrixWidth; x++) { uint8_t y = quadwave8(x * 2 + theta) / scale; #if (SMARTMATRIX_ENABLED == 1) buffer[XY(x, y)] = CRGB(CHSV(x + hue, 255, 255)); #else leds[XY(x, y)] = CRGB(CHSV(x + hue, 255, 255)); #endif } theta++; hue++; #if (SMARTMATRIX_ENABLED == 1) backgroundLayer.swapBuffers(true); #endif } #if (SMARTMATRIX_ENABLED == 0) FastLED.show(); #endif }
fix FastLED COLOR_ORDER
fix FastLED COLOR_ORDER
C++
mit
pixelmatix/SmartMatrix-Photon-APA102,pixelmatix/SmartMatrix-Photon-APA102
3916d70f96e87ef0285170d1225bc00051242b91
webkit/glue/webkit_glue.cc
webkit/glue/webkit_glue.cc
// Copyright (c) 2006-2008 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include <objidl.h> #include <mlang.h> #include "config.h" #include "webkit_version.h" #pragma warning(push, 0) #include "BackForwardList.h" #include "Document.h" #include "FrameTree.h" #include "FrameView.h" #include "Frame.h" #include "HistoryItem.h" #include "ImageSource.h" #include "KURL.h" #include "LogWin.h" #include "Page.h" #include "PlatformString.h" #include "RenderTreeAsText.h" #include "SharedBuffer.h" #pragma warning(pop) #if USE(V8_BINDING) || USE(JAVASCRIPTCORE_BINDINGS) #include "JSBridge.h" // for set flags #endif #undef LOG #undef notImplemented #include "webkit/glue/webkit_glue.h" #include "base/file_version_info.h" #include "base/string_util.h" #include "skia/include/SkBitmap.h" #include "webkit/glue/event_conversion.h" #include "webkit/glue/glue_util.h" #include "webkit/glue/weburlrequest_impl.h" #include "webkit/glue/webframe_impl.h" #include "webkit/glue/webview_impl.h" //------------------------------------------------------------------------------ // webkit_glue impl: namespace webkit_glue { void SetJavaScriptFlags(const std::wstring& str) { #if USE(V8_BINDING) || USE(JAVASCRIPTCORE_BINDINGS) std::string utf8_str = WideToUTF8(str); WebCore::JSBridge::setFlags(utf8_str.data(), static_cast<int>(utf8_str.size())); #endif } void SetRecordPlaybackMode(bool value) { #if USE(V8_BINDING) || USE(JAVASCRIPTCORE_BINDINGS) WebCore::JSBridge::setRecordPlaybackMode(value); #endif } static bool layout_test_mode_ = false; void SetLayoutTestMode(bool enable) { layout_test_mode_ = enable; } bool IsLayoutTestMode() { return layout_test_mode_; } MONITORINFOEX GetMonitorInfoForWindowHelper(HWND window) { HMONITOR monitor = MonitorFromWindow(window, MONITOR_DEFAULTTOPRIMARY); MONITORINFOEX monitorInfo; monitorInfo.cbSize = sizeof(MONITORINFOEX); GetMonitorInfo(monitor, &monitorInfo); return monitorInfo; } IMLangFontLink2* GetLangFontLinkHelper() { // TODO(hbono): http://b/1072298 Experimentally disabled this code to // prevent registry leaks caused by this IMLangFontLink2 interface. // If you find any font-rendering regressions. Please feel free to blame me. // TODO(hbono): http://b/1072298 The test shell does not use our font metrics // but it uses its own font metrics which heavily depend on this // IMLangFontLink2 interface. Even though we should change the test shell to // use out font metrics and re-baseline such tests, we temporarily let the // test shell use this interface until we complete the said change. if (!IsLayoutTestMode()) return NULL; static IMultiLanguage *multi_language = NULL; if (!multi_language) { if (CoCreateInstance(CLSID_CMultiLanguage, 0, CLSCTX_ALL, IID_IMultiLanguage, reinterpret_cast<void**>(&multi_language)) != S_OK) { return 0; } } static IMLangFontLink2* lang_font_link; if (!lang_font_link) { if (multi_language->QueryInterface( IID_IMLangFontLink2, reinterpret_cast<void**>(&lang_font_link)) != S_OK) { return 0; } } return lang_font_link; } std::wstring DumpDocumentText(WebFrame* web_frame) { WebFrameImpl* webFrameImpl = static_cast<WebFrameImpl*>(web_frame); WebCore::Frame* frame = webFrameImpl->frame(); // We use the document element's text instead of the body text here because // not all documents have a body, such as XML documents. return StringToStdWString(frame->document()->documentElement()->innerText()); } std::wstring DumpFramesAsText(WebFrame* web_frame, bool recursive) { WebFrameImpl* webFrameImpl = static_cast<WebFrameImpl*>(web_frame); std::wstring result; // Add header for all but the main frame. if (webFrameImpl->GetParent()) { result.append(L"\n--------\nFrame: '"); result.append(webFrameImpl->GetName()); result.append(L"'\n--------\n"); } result.append(DumpDocumentText(web_frame)); result.append(L"\n"); if (recursive) { WebCore::Frame* child = webFrameImpl->frame()->tree()->firstChild(); for (; child; child = child->tree()->nextSibling()) { result.append( DumpFramesAsText(WebFrameImpl::FromFrame(child), recursive)); } } return result; } std::wstring DumpRenderer(WebFrame* web_frame) { WebFrameImpl* webFrameImpl = static_cast<WebFrameImpl*>(web_frame); WebCore::Frame* frame = webFrameImpl->frame(); // This implicitly converts from a DeprecatedString. return StringToStdWString(WebCore::externalRepresentation(frame->renderer())); } std::wstring DumpFrameScrollPosition(WebFrame* web_frame, bool recursive) { WebFrameImpl* webFrameImpl = static_cast<WebFrameImpl*>(web_frame); WebCore::IntSize offset = webFrameImpl->frameview()->scrollOffset(); std::wstring result; if (offset.width() > 0 || offset.height() > 0) { if (webFrameImpl->GetParent()) { StringAppendF(&result, L"frame '%ls' ", StringToStdWString( webFrameImpl->frame()->tree()->name()).c_str()); } StringAppendF(&result, L"scrolled to %d,%d\n", offset.width(), offset.height()); } if (recursive) { WebCore::Frame* child = webFrameImpl->frame()->tree()->firstChild(); for (; child; child = child->tree()->nextSibling()) { result.append(DumpFrameScrollPosition(WebFrameImpl::FromFrame(child), recursive)); } } return result; } // Returns True if item1 < item2. static bool HistoryItemCompareLess(PassRefPtr<WebCore::HistoryItem> item1, PassRefPtr<WebCore::HistoryItem> item2) { std::wstring target1 = StringToStdWString(item1->target()); std::wstring target2 = StringToStdWString(item2->target()); std::transform(target1.begin(), target1.end(), target1.begin(), tolower); std::transform(target2.begin(), target2.end(), target2.begin(), tolower); return target1 < target2; } // Writes out a HistoryItem into a string in a readable format. static void DumpHistoryItem(WebCore::HistoryItem* item, int indent, bool is_current, std::wstring* result) { if (is_current) { result->append(L"curr->"); result->append(indent - 6, L' '); // 6 == L"curr->".length() } else { result->append(indent, L' '); } result->append(StringToStdWString(item->urlString())); if (!item->target().isEmpty()) { result->append(L" (in frame \"" + StringToStdWString(item->target()) + L"\")"); } if (item->isTargetItem()) result->append(L" **nav target**"); result->append(L"\n"); if (item->hasChildren()) { WebCore::HistoryItemVector children = item->children(); // Must sort to eliminate arbitrary result ordering which defeats // reproducible testing. std::sort(children.begin(), children.end(), HistoryItemCompareLess); for (unsigned i = 0; i < children.size(); i++) { DumpHistoryItem(children[i].get(), indent+4, false, result); } } } void DumpBackForwardList(WebView* view, void* previous_history_item, std::wstring* result) { result->append(L"\n============== Back Forward List ==============\n"); WebCore::Frame* frame = static_cast<WebFrameImpl*>(view->GetMainFrame())->frame(); WebCore::BackForwardList* list = frame->page()->backForwardList(); // Skip everything before the previous_history_item, if it's in the back list. // If it isn't found, assume it fell off the end, and include everything. int start_index = -list->backListCount(); WebCore::HistoryItem* prev_item = static_cast<WebCore::HistoryItem*>(previous_history_item); for (int i = -list->backListCount(); i < 0; ++i) { if (prev_item == list->itemAtIndex(i)) start_index = i+1; } for (int i = start_index; i < 0; ++i) DumpHistoryItem(list->itemAtIndex(i), 8, false, result); DumpHistoryItem(list->currentItem(), 8, true, result); for (int i = 1; i <= list->forwardListCount(); ++i) DumpHistoryItem(list->itemAtIndex(i), 8, false, result); result->append(L"===============================================\n"); } void ResetBeforeTestRun(WebView* view) { WebFrameImpl* webframe = static_cast<WebFrameImpl*>(view->GetMainFrame()); WebCore::Frame* frame = webframe->frame(); // Reset the main frame name since tests always expect it to be empty. It // is normally not reset between page loads (even in IE and FF). if (frame && frame->tree()) frame->tree()->setName(""); // This is papering over b/850700. But it passes a few more tests, so we'll // keep it for now. if (frame && frame->scriptBridge()) frame->scriptBridge()->setEventHandlerLineno(0); // Reset the last click information so the clicks generated from previous // test aren't inherited (otherwise can mistake single/double/triple clicks) MakePlatformMouseEvent::ResetLastClick(); } #ifndef NDEBUG // The log macro was having problems due to collisions with WTF, so we just // code here what that would have inlined. void DumpLeakedObject(const char* file, int line, const char* object, int count) { std::string msg = StringPrintf("%s LEAKED %d TIMES", object, count); AppendToLog(file, line, msg.c_str()); } #endif void CheckForLeaks() { #ifndef NDEBUG int count = WebFrameImpl::live_object_count(); if (count) DumpLeakedObject(__FILE__, __LINE__, "WebFrame", count); #endif } bool DecodeImage(const std::string& image_data, SkBitmap* image) { RefPtr<WebCore::SharedBuffer> buffer( new WebCore::SharedBuffer(image_data.data(), static_cast<int>(image_data.length()))); WebCore::ImageSource image_source; image_source.setData(buffer.get(), true); if (image_source.frameCount() > 0) { *image = *reinterpret_cast<SkBitmap*>(image_source.createFrameAtIndex(0)); return true; } // We failed to decode the image. return false; } // Convert from WebKit types to Glue types and notify the embedder. This should // not perform complex processing since it may be called a lot. void NotifyFormStateChanged(const WebCore::Document* document) { if (!document) return; WebCore::Frame* frame = document->frame(); if (!frame) return; // Dispatch to the delegate of the view that owns the frame. WebFrame* webframe = WebFrameImpl::FromFrame(document->frame()); WebView* webview = webframe->GetView(); if (!webview) return; WebViewDelegate* delegate = webview->GetDelegate(); if (!delegate) return; delegate->OnNavStateChanged(webview); } std::string GetWebKitVersion() { return StringPrintf("%d.%d", WEBKIT_VERSION_MAJOR, WEBKIT_VERSION_MINOR); } const std::string& GetDefaultUserAgent() { static std::string user_agent; static bool generated_user_agent; if (!generated_user_agent) { OSVERSIONINFO info = {0}; info.dwOSVersionInfoSize = sizeof(info); GetVersionEx(&info); // Get the product name and version, and replace Safari's Version/X string // with it. This is done to expose our product name in a manner that is // maximally compatible with Safari, we hope!! std::string product; #ifdef CHROME_LAST_MINUTE FileVersionInfo* version_info = FileVersionInfo::CreateFileVersionInfoForCurrentModule(); if (version_info) product = "Chrome/" + WideToASCII(version_info->product_version()); #endif if (product.empty()) product = "Version/3.1"; // Derived from Safari's UA string. StringAppendF( &user_agent, "Mozilla/5.0 (Windows; U; Windows NT %d.%d; en-US) AppleWebKit/%d.%d" " (KHTML, like Gecko) %s Safari/%d.%d", info.dwMajorVersion, info.dwMinorVersion, WEBKIT_VERSION_MAJOR, WEBKIT_VERSION_MINOR, product.c_str(), WEBKIT_VERSION_MAJOR, WEBKIT_VERSION_MINOR ); generated_user_agent = true; } return user_agent; } void NotifyJSOutOfMemory(WebCore::Frame* frame) { if (!frame) return; // Dispatch to the delegate of the view that owns the frame. WebFrame* webframe = WebFrameImpl::FromFrame(frame); WebView* webview = webframe->GetView(); if (!webview) return; WebViewDelegate* delegate = webview->GetDelegate(); if (!delegate) return; delegate->JSOutOfMemory(); } } // namespace webkit_glue
// Copyright (c) 2006-2008 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include <objidl.h> #include <mlang.h> #include "config.h" #include "webkit_version.h" #pragma warning(push, 0) #include "BackForwardList.h" #include "Document.h" #include "FrameTree.h" #include "FrameView.h" #include "Frame.h" #include "HistoryItem.h" #include "ImageSource.h" #include "KURL.h" #include "LogWin.h" #include "Page.h" #include "PlatformString.h" #include "RenderTreeAsText.h" #include "SharedBuffer.h" #pragma warning(pop) #if USE(V8_BINDING) || USE(JAVASCRIPTCORE_BINDINGS) #include "JSBridge.h" // for set flags #endif #undef LOG #undef notImplemented #include "webkit/glue/webkit_glue.h" #include "base/file_version_info.h" #include "base/string_util.h" #include "skia/include/SkBitmap.h" #include "webkit/glue/event_conversion.h" #include "webkit/glue/glue_util.h" #include "webkit/glue/weburlrequest_impl.h" #include "webkit/glue/webframe_impl.h" #include "webkit/glue/webview_impl.h" //------------------------------------------------------------------------------ // webkit_glue impl: namespace webkit_glue { void SetJavaScriptFlags(const std::wstring& str) { #if USE(V8_BINDING) || USE(JAVASCRIPTCORE_BINDINGS) std::string utf8_str = WideToUTF8(str); WebCore::JSBridge::setFlags(utf8_str.data(), static_cast<int>(utf8_str.size())); #endif } void SetRecordPlaybackMode(bool value) { #if USE(V8_BINDING) || USE(JAVASCRIPTCORE_BINDINGS) WebCore::JSBridge::setRecordPlaybackMode(value); #endif } static bool layout_test_mode_ = false; void SetLayoutTestMode(bool enable) { layout_test_mode_ = enable; } bool IsLayoutTestMode() { return layout_test_mode_; } MONITORINFOEX GetMonitorInfoForWindowHelper(HWND window) { HMONITOR monitor = MonitorFromWindow(window, MONITOR_DEFAULTTOPRIMARY); MONITORINFOEX monitorInfo; monitorInfo.cbSize = sizeof(MONITORINFOEX); GetMonitorInfo(monitor, &monitorInfo); return monitorInfo; } IMLangFontLink2* GetLangFontLinkHelper() { // TODO(hbono): http://b/1072298 Experimentally disabled this code to // prevent registry leaks caused by this IMLangFontLink2 interface. // If you find any font-rendering regressions. Please feel free to blame me. // TODO(hbono): http://b/1072298 The test shell does not use our font metrics // but it uses its own font metrics which heavily depend on this // IMLangFontLink2 interface. Even though we should change the test shell to // use out font metrics and re-baseline such tests, we temporarily let the // test shell use this interface until we complete the said change. if (!IsLayoutTestMode()) return NULL; static IMultiLanguage *multi_language = NULL; if (!multi_language) { if (CoCreateInstance(CLSID_CMultiLanguage, 0, CLSCTX_ALL, IID_IMultiLanguage, reinterpret_cast<void**>(&multi_language)) != S_OK) { return 0; } } static IMLangFontLink2* lang_font_link; if (!lang_font_link) { if (multi_language->QueryInterface( IID_IMLangFontLink2, reinterpret_cast<void**>(&lang_font_link)) != S_OK) { return 0; } } return lang_font_link; } std::wstring DumpDocumentText(WebFrame* web_frame) { WebFrameImpl* webFrameImpl = static_cast<WebFrameImpl*>(web_frame); WebCore::Frame* frame = webFrameImpl->frame(); // We use the document element's text instead of the body text here because // not all documents have a body, such as XML documents. return StringToStdWString(frame->document()->documentElement()->innerText()); } std::wstring DumpFramesAsText(WebFrame* web_frame, bool recursive) { WebFrameImpl* webFrameImpl = static_cast<WebFrameImpl*>(web_frame); std::wstring result; // Add header for all but the main frame. if (webFrameImpl->GetParent()) { result.append(L"\n--------\nFrame: '"); result.append(webFrameImpl->GetName()); result.append(L"'\n--------\n"); } result.append(DumpDocumentText(web_frame)); result.append(L"\n"); if (recursive) { WebCore::Frame* child = webFrameImpl->frame()->tree()->firstChild(); for (; child; child = child->tree()->nextSibling()) { result.append( DumpFramesAsText(WebFrameImpl::FromFrame(child), recursive)); } } return result; } std::wstring DumpRenderer(WebFrame* web_frame) { WebFrameImpl* webFrameImpl = static_cast<WebFrameImpl*>(web_frame); WebCore::Frame* frame = webFrameImpl->frame(); // This implicitly converts from a DeprecatedString. return StringToStdWString(WebCore::externalRepresentation(frame->renderer())); } std::wstring DumpFrameScrollPosition(WebFrame* web_frame, bool recursive) { WebFrameImpl* webFrameImpl = static_cast<WebFrameImpl*>(web_frame); WebCore::IntSize offset = webFrameImpl->frameview()->scrollOffset(); std::wstring result; if (offset.width() > 0 || offset.height() > 0) { if (webFrameImpl->GetParent()) { StringAppendF(&result, L"frame '%ls' ", StringToStdWString( webFrameImpl->frame()->tree()->name()).c_str()); } StringAppendF(&result, L"scrolled to %d,%d\n", offset.width(), offset.height()); } if (recursive) { WebCore::Frame* child = webFrameImpl->frame()->tree()->firstChild(); for (; child; child = child->tree()->nextSibling()) { result.append(DumpFrameScrollPosition(WebFrameImpl::FromFrame(child), recursive)); } } return result; } // Returns True if item1 < item2. static bool HistoryItemCompareLess(PassRefPtr<WebCore::HistoryItem> item1, PassRefPtr<WebCore::HistoryItem> item2) { std::wstring target1 = StringToStdWString(item1->target()); std::wstring target2 = StringToStdWString(item2->target()); std::transform(target1.begin(), target1.end(), target1.begin(), tolower); std::transform(target2.begin(), target2.end(), target2.begin(), tolower); return target1 < target2; } // Writes out a HistoryItem into a string in a readable format. static void DumpHistoryItem(WebCore::HistoryItem* item, int indent, bool is_current, std::wstring* result) { if (is_current) { result->append(L"curr->"); result->append(indent - 6, L' '); // 6 == L"curr->".length() } else { result->append(indent, L' '); } result->append(StringToStdWString(item->urlString())); if (!item->target().isEmpty()) { result->append(L" (in frame \"" + StringToStdWString(item->target()) + L"\")"); } if (item->isTargetItem()) result->append(L" **nav target**"); result->append(L"\n"); if (item->hasChildren()) { WebCore::HistoryItemVector children = item->children(); // Must sort to eliminate arbitrary result ordering which defeats // reproducible testing. std::sort(children.begin(), children.end(), HistoryItemCompareLess); for (unsigned i = 0; i < children.size(); i++) { DumpHistoryItem(children[i].get(), indent+4, false, result); } } } void DumpBackForwardList(WebView* view, void* previous_history_item, std::wstring* result) { result->append(L"\n============== Back Forward List ==============\n"); WebCore::Frame* frame = static_cast<WebFrameImpl*>(view->GetMainFrame())->frame(); WebCore::BackForwardList* list = frame->page()->backForwardList(); // Skip everything before the previous_history_item, if it's in the back list. // If it isn't found, assume it fell off the end, and include everything. int start_index = -list->backListCount(); WebCore::HistoryItem* prev_item = static_cast<WebCore::HistoryItem*>(previous_history_item); for (int i = -list->backListCount(); i < 0; ++i) { if (prev_item == list->itemAtIndex(i)) start_index = i+1; } for (int i = start_index; i < 0; ++i) DumpHistoryItem(list->itemAtIndex(i), 8, false, result); DumpHistoryItem(list->currentItem(), 8, true, result); for (int i = 1; i <= list->forwardListCount(); ++i) DumpHistoryItem(list->itemAtIndex(i), 8, false, result); result->append(L"===============================================\n"); } void ResetBeforeTestRun(WebView* view) { WebFrameImpl* webframe = static_cast<WebFrameImpl*>(view->GetMainFrame()); WebCore::Frame* frame = webframe->frame(); // Reset the main frame name since tests always expect it to be empty. It // is normally not reset between page loads (even in IE and FF). if (frame && frame->tree()) frame->tree()->setName(""); // This is papering over b/850700. But it passes a few more tests, so we'll // keep it for now. if (frame && frame->scriptBridge()) frame->scriptBridge()->setEventHandlerLineno(0); // Reset the last click information so the clicks generated from previous // test aren't inherited (otherwise can mistake single/double/triple clicks) MakePlatformMouseEvent::ResetLastClick(); } #ifndef NDEBUG // The log macro was having problems due to collisions with WTF, so we just // code here what that would have inlined. void DumpLeakedObject(const char* file, int line, const char* object, int count) { std::string msg = StringPrintf("%s LEAKED %d TIMES", object, count); AppendToLog(file, line, msg.c_str()); } #endif void CheckForLeaks() { #ifndef NDEBUG int count = WebFrameImpl::live_object_count(); if (count) DumpLeakedObject(__FILE__, __LINE__, "WebFrame", count); #endif } bool DecodeImage(const std::string& image_data, SkBitmap* image) { RefPtr<WebCore::SharedBuffer> buffer( new WebCore::SharedBuffer(image_data.data(), static_cast<int>(image_data.length()))); WebCore::ImageSource image_source; image_source.setData(buffer.get(), true); if (image_source.frameCount() > 0) { *image = *reinterpret_cast<SkBitmap*>(image_source.createFrameAtIndex(0)); return true; } // We failed to decode the image. return false; } // Convert from WebKit types to Glue types and notify the embedder. This should // not perform complex processing since it may be called a lot. void NotifyFormStateChanged(const WebCore::Document* document) { if (!document) return; WebCore::Frame* frame = document->frame(); if (!frame) return; // Dispatch to the delegate of the view that owns the frame. WebFrame* webframe = WebFrameImpl::FromFrame(document->frame()); WebView* webview = webframe->GetView(); if (!webview) return; WebViewDelegate* delegate = webview->GetDelegate(); if (!delegate) return; delegate->OnNavStateChanged(webview); } std::string GetWebKitVersion() { return StringPrintf("%d.%d", WEBKIT_VERSION_MAJOR, WEBKIT_VERSION_MINOR); } const std::string& GetDefaultUserAgent() { static std::string user_agent; static bool generated_user_agent; if (!generated_user_agent) { OSVERSIONINFO info = {0}; info.dwOSVersionInfoSize = sizeof(info); GetVersionEx(&info); // Get the product name and version, and replace Safari's Version/X string // with it. This is done to expose our product name in a manner that is // maximally compatible with Safari, we hope!! std::string product; FileVersionInfo* version_info = FileVersionInfo::CreateFileVersionInfoForCurrentModule(); if (version_info) product = "Chrome/" + WideToASCII(version_info->product_version()); if (product.empty()) product = "Version/3.1"; // Derived from Safari's UA string. StringAppendF( &user_agent, "Mozilla/5.0 (Windows; U; Windows NT %d.%d; en-US) AppleWebKit/%d.%d" " (KHTML, like Gecko) %s Safari/%d.%d", info.dwMajorVersion, info.dwMinorVersion, WEBKIT_VERSION_MAJOR, WEBKIT_VERSION_MINOR, product.c_str(), WEBKIT_VERSION_MAJOR, WEBKIT_VERSION_MINOR ); generated_user_agent = true; } return user_agent; } void NotifyJSOutOfMemory(WebCore::Frame* frame) { if (!frame) return; // Dispatch to the delegate of the view that owns the frame. WebFrame* webframe = WebFrameImpl::FromFrame(frame); WebView* webview = webframe->GetView(); if (!webview) return; WebViewDelegate* delegate = webview->GetDelegate(); if (!delegate) return; delegate->JSOutOfMemory(); } } // namespace webkit_glue
Remove last minute #define and change UA string to Chrome on trunk.
Remove last minute #define and change UA string to Chrome on trunk. BUG=1431137 TBR= [email protected] git-svn-id: dd90618784b6a4b323ea0c23a071cb1c9e6f2ac7@1625 4ff67af0-8c30-449e-8e8b-ad334ec8d88c
C++
bsd-3-clause
wistoch/meego-app-browser,wistoch/meego-app-browser,wistoch/meego-app-browser,wistoch/meego-app-browser,wistoch/meego-app-browser,wistoch/meego-app-browser,wistoch/meego-app-browser,wistoch/meego-app-browser,wistoch/meego-app-browser,wistoch/meego-app-browser
fc0678daf202b9e7d7e4280389ce81abe00b8700
src/mem/cache/prefetch/associative_set_impl.hh
src/mem/cache/prefetch/associative_set_impl.hh
/** * Copyright (c) 2018 Metempsy Technology Consulting * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are * met: redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer; * redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution; * neither the name of the copyright holders nor the names of its * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * * Authors: Javier Bueno */ #ifndef __CACHE_PREFETCH_ASSOCIATIVE_SET_IMPL_HH__ #define __CACHE_PREFETCH_ASSOCIATIVE_SET_IMPL_HH__ #include "mem/cache/prefetch/associative_set.hh" template<class Entry> AssociativeSet<Entry>::AssociativeSet(int assoc, int num_entries, BaseIndexingPolicy *idx_policy, BaseReplacementPolicy *rpl_policy, Entry const &init_value) : associativity(assoc), numEntries(num_entries), indexingPolicy(idx_policy), replacementPolicy(rpl_policy), entries(numEntries, init_value) { fatal_if(!isPowerOf2(num_entries), "The number of entries of an " "AssociativeSet<> must be a power of 2"); fatal_if(!isPowerOf2(assoc), "The associativity of an AssociativeSet<> " "must be a power of 2"); for (unsigned int entry_idx = 0; entry_idx < numEntries; entry_idx += 1) { Entry* entry = &entries[entry_idx]; indexingPolicy->setEntry(entry, entry_idx); entry->replacementData = replacementPolicy->instantiateEntry(); } } template<class Entry> Entry* AssociativeSet<Entry>::findEntry(Addr addr, bool is_secure) const { Addr tag = indexingPolicy->extractTag(addr); const std::vector<ReplaceableEntry*> selected_entries = indexingPolicy->getPossibleEntries(addr); for (const auto& location : selected_entries) { Entry* entry = static_cast<Entry *>(location); if ((entry->getTag() == tag) && entry->isValid() && entry->isSecure() == is_secure) { return entry; } } return nullptr; } template<class Entry> void AssociativeSet<Entry>::accessEntry(Entry *entry) { replacementPolicy->touch(entry->replacementData); } template<class Entry> Entry* AssociativeSet<Entry>::findVictim(Addr addr) { // Get possible entries to be victimized const std::vector<ReplaceableEntry*> selected_entries = indexingPolicy->getPossibleEntries(addr); Entry* victim = static_cast<Entry*>(replacementPolicy->getVictim( selected_entries)); // There is only one eviction for this replacement victim->reset(); return victim; } template<class Entry> std::vector<Entry *> AssociativeSet<Entry>::getPossibleEntries(const Addr addr) const { std::vector<ReplaceableEntry *> selected_entries = indexingPolicy->getPossibleEntries(addr); std::vector<Entry *> entries(selected_entries.size(), nullptr); unsigned int idx = 0; for (auto &entry : selected_entries) { entries[idx++] = static_cast<Entry *>(entry); } return entries; } template<class Entry> void AssociativeSet<Entry>::insertEntry(Addr addr, bool is_secure, Entry* entry) { entry->setValid(); entry->setTag(indexingPolicy->extractTag(addr)); entry->setSecure(is_secure); replacementPolicy->reset(entry->replacementData); } #endif//__CACHE_PREFETCH_ASSOCIATIVE_SET_IMPL_HH__
/** * Copyright (c) 2018 Metempsy Technology Consulting * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are * met: redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer; * redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution; * neither the name of the copyright holders nor the names of its * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * * Authors: Javier Bueno */ #ifndef __CACHE_PREFETCH_ASSOCIATIVE_SET_IMPL_HH__ #define __CACHE_PREFETCH_ASSOCIATIVE_SET_IMPL_HH__ #include "base/intmath.hh" #include "mem/cache/prefetch/associative_set.hh" template<class Entry> AssociativeSet<Entry>::AssociativeSet(int assoc, int num_entries, BaseIndexingPolicy *idx_policy, BaseReplacementPolicy *rpl_policy, Entry const &init_value) : associativity(assoc), numEntries(num_entries), indexingPolicy(idx_policy), replacementPolicy(rpl_policy), entries(numEntries, init_value) { fatal_if(!isPowerOf2(num_entries), "The number of entries of an " "AssociativeSet<> must be a power of 2"); fatal_if(!isPowerOf2(assoc), "The associativity of an AssociativeSet<> " "must be a power of 2"); for (unsigned int entry_idx = 0; entry_idx < numEntries; entry_idx += 1) { Entry* entry = &entries[entry_idx]; indexingPolicy->setEntry(entry, entry_idx); entry->replacementData = replacementPolicy->instantiateEntry(); } } template<class Entry> Entry* AssociativeSet<Entry>::findEntry(Addr addr, bool is_secure) const { Addr tag = indexingPolicy->extractTag(addr); const std::vector<ReplaceableEntry*> selected_entries = indexingPolicy->getPossibleEntries(addr); for (const auto& location : selected_entries) { Entry* entry = static_cast<Entry *>(location); if ((entry->getTag() == tag) && entry->isValid() && entry->isSecure() == is_secure) { return entry; } } return nullptr; } template<class Entry> void AssociativeSet<Entry>::accessEntry(Entry *entry) { replacementPolicy->touch(entry->replacementData); } template<class Entry> Entry* AssociativeSet<Entry>::findVictim(Addr addr) { // Get possible entries to be victimized const std::vector<ReplaceableEntry*> selected_entries = indexingPolicy->getPossibleEntries(addr); Entry* victim = static_cast<Entry*>(replacementPolicy->getVictim( selected_entries)); // There is only one eviction for this replacement victim->reset(); return victim; } template<class Entry> std::vector<Entry *> AssociativeSet<Entry>::getPossibleEntries(const Addr addr) const { std::vector<ReplaceableEntry *> selected_entries = indexingPolicy->getPossibleEntries(addr); std::vector<Entry *> entries(selected_entries.size(), nullptr); unsigned int idx = 0; for (auto &entry : selected_entries) { entries[idx++] = static_cast<Entry *>(entry); } return entries; } template<class Entry> void AssociativeSet<Entry>::insertEntry(Addr addr, bool is_secure, Entry* entry) { entry->setValid(); entry->setTag(indexingPolicy->extractTag(addr)); entry->setSecure(is_secure); replacementPolicy->reset(entry->replacementData); } #endif//__CACHE_PREFETCH_ASSOCIATIVE_SET_IMPL_HH__
Fix missing header in associative set
mem-cache: Fix missing header in associative set Add missing intmath header to AssociativeSet, so that isPowerOf2 can be used. error: there are no arguments to 'isPowerOf2' that depend on a template parameter, so a declaration of 'isPowerOf2' must be available Change-Id: Ib2b194f9e71284ee439786bdb76d99858e57e2f5 Signed-off-by: Daniel R. Carvalho <[email protected]> Reviewed-on: https://gem5-review.googlesource.com/c/public/gem5/+/22444 Reviewed-by: Nikos Nikoleris <[email protected]> Maintainer: Nikos Nikoleris <[email protected]> Tested-by: kokoro <[email protected]>
C++
bsd-3-clause
gem5/gem5,gem5/gem5,gem5/gem5,gem5/gem5,gem5/gem5,gem5/gem5,gem5/gem5
9d56642ccb4d48f58a675b58c79c189d3f744845
src/trace_processor/sqlite/db_sqlite_table.cc
src/trace_processor/sqlite/db_sqlite_table.cc
/* * Copyright (C) 2019 The Android Open Source Project * * 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 "src/trace_processor/sqlite/db_sqlite_table.h" #include "src/trace_processor/sqlite/sqlite_utils.h" namespace perfetto { namespace trace_processor { namespace { FilterOp SqliteOpToFilterOp(int sqlite_op) { switch (sqlite_op) { case SQLITE_INDEX_CONSTRAINT_EQ: case SQLITE_INDEX_CONSTRAINT_IS: return FilterOp::kEq; case SQLITE_INDEX_CONSTRAINT_GT: return FilterOp::kGt; case SQLITE_INDEX_CONSTRAINT_LT: return FilterOp::kLt; case SQLITE_INDEX_CONSTRAINT_NE: return FilterOp::kNeq; default: PERFETTO_FATAL("Currently unsupported constraint"); } } SqlValue SqliteValueToSqlValue(sqlite3_value* sqlite_val) { auto col_type = sqlite3_value_type(sqlite_val); SqlValue value; switch (col_type) { case SQLITE_INTEGER: value.type = SqlValue::kLong; value.long_value = sqlite3_value_int64(sqlite_val); break; case SQLITE_TEXT: value.type = SqlValue::kString; value.string_value = reinterpret_cast<const char*>(sqlite3_value_text(sqlite_val)); break; case SQLITE_FLOAT: value.type = SqlValue::kDouble; value.double_value = sqlite3_value_double(sqlite_val); break; case SQLITE_BLOB: value.type = SqlValue::kBytes; value.bytes_value = sqlite3_value_blob(sqlite_val); value.bytes_count = static_cast<size_t>(sqlite3_value_bytes(sqlite_val)); break; case SQLITE_NULL: value.type = SqlValue::kNull; break; } return value; } } // namespace DbSqliteTable::DbSqliteTable(sqlite3*, const Table* table) : table_(table) {} DbSqliteTable::~DbSqliteTable() = default; void DbSqliteTable::RegisterTable(sqlite3* db, const Table* table, const std::string& name) { SqliteTable::Register<DbSqliteTable, const Table*>(db, table, name); } util::Status DbSqliteTable::Init(int, const char* const*, Schema* schema) { std::vector<SqliteTable::Column> schema_cols; for (uint32_t i = 0; i < table_->GetColumnCount(); ++i) { const auto& col = table_->GetColumn(i); schema_cols.emplace_back(i, col.name(), col.type()); } // TODO(lalitm): this is hardcoded to be the id column but change this to be // more generic in the future. auto opt_idx = table_->FindColumnIdxByName("id"); if (!opt_idx) { PERFETTO_FATAL( "id column not found in %s. Currently all db Tables need to contain an " "id column; this constraint will be relaxed in the future.", name().c_str()); } std::vector<size_t> primary_keys; primary_keys.emplace_back(*opt_idx); *schema = Schema(std::move(schema_cols), std::move(primary_keys)); return util::OkStatus(); } int DbSqliteTable::BestIndex(const QueryConstraints& qc, BestIndexInfo* info) { // TODO(lalitm): investigate SQLITE_INDEX_SCAN_UNIQUE for id columns. info->estimated_cost = static_cast<uint32_t>(EstimateCost(qc)); return SQLITE_OK; } double DbSqliteTable::EstimateCost(const QueryConstraints& qc) { // Currently our cost estimation algorithm is quite simplistic but is good // enough for the simplest cases. // TODO(lalitm): flesh out this algorithm to cover more complex cases. // If we have no constraints, we always return the max possible value as we // want to discourage the query planner from taking this road. const auto& constraints = qc.constraints(); if (constraints.empty()) return std::numeric_limits<int32_t>::max(); // This means we have at least one constraint. Check if any of the constraints // is an equality constraint on an id column. auto id_filter = [this](const QueryConstraints::Constraint& c) { uint32_t col_idx = static_cast<uint32_t>(c.iColumn); const auto& col = table_->GetColumn(col_idx); return sqlite_utils::IsOpEq(c.op) && col.IsId(); }; // If we have a eq constraint on an id column, we return 0 as it's an O(1) // operation regardless of all the other constriants. auto it = std::find_if(constraints.begin(), constraints.end(), id_filter); if (it != constraints.end()) return 1; // Otherwise, we divide the number of rows in the table by the number of // constraints as a simple way of indiciating the more constraints we have // the better we can do. return table_->size() / constraints.size(); } std::unique_ptr<SqliteTable::Cursor> DbSqliteTable::CreateCursor() { return std::unique_ptr<Cursor>(new Cursor(this)); } DbSqliteTable::Cursor::Cursor(DbSqliteTable* table) : SqliteTable::Cursor(table), initial_db_table_(table->table_) {} int DbSqliteTable::Cursor::Filter(const QueryConstraints& qc, sqlite3_value** argv) { // We reuse this vector to reduce memory allocations on nested subqueries. constraints_.resize(qc.constraints().size()); for (size_t i = 0; i < qc.constraints().size(); ++i) { const auto& cs = qc.constraints()[i]; uint32_t col = static_cast<uint32_t>(cs.iColumn); FilterOp op = SqliteOpToFilterOp(cs.op); SqlValue value = SqliteValueToSqlValue(argv[i]); constraints_[i] = Constraint{col, op, value}; } // We reuse this vector to reduce memory allocations on nested subqueries. orders_.resize(qc.order_by().size()); for (size_t i = 0; i < qc.order_by().size(); ++i) { const auto& ob = qc.order_by()[i]; uint32_t col = static_cast<uint32_t>(ob.iColumn); orders_[i] = Order{col, static_cast<bool>(ob.desc)}; } db_table_ = initial_db_table_->Filter(constraints_).Sort(orders_); iterator_ = db_table_->IterateRows(); return Next(); } int DbSqliteTable::Cursor::Next() { eof_ = !iterator_->Next(); return SQLITE_OK; } int DbSqliteTable::Cursor::Eof() { return eof_; } int DbSqliteTable::Cursor::Column(sqlite3_context* ctx, int raw_col) { uint32_t column = static_cast<uint32_t>(raw_col); SqlValue value = iterator_->Get(column); switch (value.type) { case SqlValue::Type::kLong: sqlite3_result_int64(ctx, value.long_value); break; case SqlValue::Type::kDouble: sqlite3_result_double(ctx, value.double_value); break; case SqlValue::Type::kString: { // We can say kSqliteStatic here because all strings are expected to // come from the string pool and thus will be valid for the lifetime // of trace processor. sqlite3_result_text(ctx, value.string_value, -1, sqlite_utils::kSqliteStatic); break; } case SqlValue::Type::kBytes: { // We can say kSqliteStatic here because for our iterator will hold // onto the pointer as long as we don't call Next() but that only // happens with Next() is called on the Cursor itself at which point // SQLite no longer cares about the bytes pointer. sqlite3_result_blob(ctx, value.bytes_value, static_cast<int>(value.bytes_count), sqlite_utils::kSqliteStatic); break; } case SqlValue::Type::kNull: sqlite3_result_null(ctx); break; } return SQLITE_OK; } } // namespace trace_processor } // namespace perfetto
/* * Copyright (C) 2019 The Android Open Source Project * * 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 "src/trace_processor/sqlite/db_sqlite_table.h" #include "src/trace_processor/sqlite/sqlite_utils.h" namespace perfetto { namespace trace_processor { namespace { FilterOp SqliteOpToFilterOp(int sqlite_op) { switch (sqlite_op) { case SQLITE_INDEX_CONSTRAINT_EQ: case SQLITE_INDEX_CONSTRAINT_IS: return FilterOp::kEq; case SQLITE_INDEX_CONSTRAINT_GT: return FilterOp::kGt; case SQLITE_INDEX_CONSTRAINT_LT: return FilterOp::kLt; case SQLITE_INDEX_CONSTRAINT_NE: return FilterOp::kNeq; default: PERFETTO_FATAL("Currently unsupported constraint"); } } SqlValue SqliteValueToSqlValue(sqlite3_value* sqlite_val) { auto col_type = sqlite3_value_type(sqlite_val); SqlValue value; switch (col_type) { case SQLITE_INTEGER: value.type = SqlValue::kLong; value.long_value = sqlite3_value_int64(sqlite_val); break; case SQLITE_TEXT: value.type = SqlValue::kString; value.string_value = reinterpret_cast<const char*>(sqlite3_value_text(sqlite_val)); break; case SQLITE_FLOAT: value.type = SqlValue::kDouble; value.double_value = sqlite3_value_double(sqlite_val); break; case SQLITE_BLOB: value.type = SqlValue::kBytes; value.bytes_value = sqlite3_value_blob(sqlite_val); value.bytes_count = static_cast<size_t>(sqlite3_value_bytes(sqlite_val)); break; case SQLITE_NULL: value.type = SqlValue::kNull; break; } return value; } } // namespace DbSqliteTable::DbSqliteTable(sqlite3*, const Table* table) : table_(table) {} DbSqliteTable::~DbSqliteTable() = default; void DbSqliteTable::RegisterTable(sqlite3* db, const Table* table, const std::string& name) { SqliteTable::Register<DbSqliteTable, const Table*>(db, table, name); } util::Status DbSqliteTable::Init(int, const char* const*, Schema* schema) { std::vector<SqliteTable::Column> schema_cols; for (uint32_t i = 0; i < table_->GetColumnCount(); ++i) { const auto& col = table_->GetColumn(i); schema_cols.emplace_back(i, col.name(), col.type()); } // TODO(lalitm): this is hardcoded to be the id column but change this to be // more generic in the future. auto opt_idx = table_->FindColumnIdxByName("id"); if (!opt_idx) { PERFETTO_FATAL( "id column not found in %s. Currently all db Tables need to contain an " "id column; this constraint will be relaxed in the future.", name().c_str()); } std::vector<size_t> primary_keys; primary_keys.emplace_back(*opt_idx); *schema = Schema(std::move(schema_cols), std::move(primary_keys)); return util::OkStatus(); } int DbSqliteTable::BestIndex(const QueryConstraints& qc, BestIndexInfo* info) { // TODO(lalitm): investigate SQLITE_INDEX_SCAN_UNIQUE for id columns. info->estimated_cost = static_cast<uint32_t>(EstimateCost(qc)); return SQLITE_OK; } double DbSqliteTable::EstimateCost(const QueryConstraints& qc) { // Currently our cost estimation algorithm is quite simplistic but is good // enough for the simplest cases. // TODO(lalitm): flesh out this algorithm to cover more complex cases. // If we have no constraints, we always return the size of the table as we // want to discourage the query planner from taking this road. const auto& constraints = qc.constraints(); if (constraints.empty()) return table_->size(); // This means we have at least one constraint. Check if any of the constraints // is an equality constraint on an id column. auto id_filter = [this](const QueryConstraints::Constraint& c) { uint32_t col_idx = static_cast<uint32_t>(c.iColumn); const auto& col = table_->GetColumn(col_idx); return sqlite_utils::IsOpEq(c.op) && col.IsId(); }; // If we have a eq constraint on an id column, we return 0 as it's an O(1) // operation regardless of all the other constriants. auto it = std::find_if(constraints.begin(), constraints.end(), id_filter); if (it != constraints.end()) return 1; // Otherwise, we divide the number of rows in the table by the number of // constraints as a simple way of indiciating the more constraints we have // the better we can do. return table_->size() / constraints.size(); } std::unique_ptr<SqliteTable::Cursor> DbSqliteTable::CreateCursor() { return std::unique_ptr<Cursor>(new Cursor(this)); } DbSqliteTable::Cursor::Cursor(DbSqliteTable* table) : SqliteTable::Cursor(table), initial_db_table_(table->table_) {} int DbSqliteTable::Cursor::Filter(const QueryConstraints& qc, sqlite3_value** argv) { // We reuse this vector to reduce memory allocations on nested subqueries. constraints_.resize(qc.constraints().size()); for (size_t i = 0; i < qc.constraints().size(); ++i) { const auto& cs = qc.constraints()[i]; uint32_t col = static_cast<uint32_t>(cs.iColumn); FilterOp op = SqliteOpToFilterOp(cs.op); SqlValue value = SqliteValueToSqlValue(argv[i]); constraints_[i] = Constraint{col, op, value}; } // We reuse this vector to reduce memory allocations on nested subqueries. orders_.resize(qc.order_by().size()); for (size_t i = 0; i < qc.order_by().size(); ++i) { const auto& ob = qc.order_by()[i]; uint32_t col = static_cast<uint32_t>(ob.iColumn); orders_[i] = Order{col, static_cast<bool>(ob.desc)}; } db_table_ = initial_db_table_->Filter(constraints_).Sort(orders_); iterator_ = db_table_->IterateRows(); return Next(); } int DbSqliteTable::Cursor::Next() { eof_ = !iterator_->Next(); return SQLITE_OK; } int DbSqliteTable::Cursor::Eof() { return eof_; } int DbSqliteTable::Cursor::Column(sqlite3_context* ctx, int raw_col) { uint32_t column = static_cast<uint32_t>(raw_col); SqlValue value = iterator_->Get(column); switch (value.type) { case SqlValue::Type::kLong: sqlite3_result_int64(ctx, value.long_value); break; case SqlValue::Type::kDouble: sqlite3_result_double(ctx, value.double_value); break; case SqlValue::Type::kString: { // We can say kSqliteStatic here because all strings are expected to // come from the string pool and thus will be valid for the lifetime // of trace processor. sqlite3_result_text(ctx, value.string_value, -1, sqlite_utils::kSqliteStatic); break; } case SqlValue::Type::kBytes: { // We can say kSqliteStatic here because for our iterator will hold // onto the pointer as long as we don't call Next() but that only // happens with Next() is called on the Cursor itself at which point // SQLite no longer cares about the bytes pointer. sqlite3_result_blob(ctx, value.bytes_value, static_cast<int>(value.bytes_count), sqlite_utils::kSqliteStatic); break; } case SqlValue::Type::kNull: sqlite3_result_null(ctx); break; } return SQLITE_OK; } } // namespace trace_processor } // namespace perfetto
improve logic of best index am: 4060dd0a01 am: 913e9ac8f3 am: 489321054e am: c2b276dbdc
trace_processor: improve logic of best index am: 4060dd0a01 am: 913e9ac8f3 am: 489321054e am: c2b276dbdc Change-Id: I48b1ee9bdcb31c3d8f856dadf979579637149748
C++
apache-2.0
google/perfetto,google/perfetto,google/perfetto,google/perfetto,google/perfetto,google/perfetto,google/perfetto,google/perfetto
84f686dcddde2704ae60f97fddc72c0614cf0561
server.cpp
server.cpp
#include <sys/socket.h> #include <netinet/in.h> #include <arpa/inet.h> #include <unistd.h> #include <sys/time.h> #include <string.h> #include <iostream> #include <fstream> #include <boost/lexical_cast.hpp> #include "packet.h" #define USAGE "Usage:\r\nc \r\n[tux machine number] \r\n[probability of packet corruption in int form] \r\n[probability of packet loss in int form] \r\n[probability of packet delay] \r\n[length of delay in ms] \r\n" #define PORT 10038 #define PAKSIZE 512 #define ACK 0 #define NAK 1 #define BUFSIZE 505 #define FILENAME "Testfile" #define TIMEOUT 100 //in ms #define WIN_SIZE 16 using namespace std; bool isvpack(unsigned char * p); bool init(int argc, char** argv); bool loadFile(); bool getFile(); bool sendFile(); bool isAck(); void handleAck(); void handleNak(int& x); bool* gremlin(Packet * pack, int corruptProb, int lossProb, int delayProb); Packet createPacket(int index); void loadWindow(); bool sendPacket(); bool getGet(); struct sockaddr_in a; struct sockaddr_in ca; socklen_t calen; int rlen; int s; bool ack; string fstr; char * file; int probCorrupt; int probLoss; int probDelay; int delayT; Packet p; Packet window[16]; int length; bool dropPck; bool delayPck; int toms; unsigned char b[BUFSIZE]; int base; int main(int argc, char** argv) { if(!init(argc, argv)) return -1; sendFile(); return 0; } bool init(int argc, char** argv){ if(argc != 6) { cout << USAGE << endl; return false; } char * probCorruptStr = argv[2]; probCorrupt = boost::lexical_cast<int>(probCorruptStr); char * probLossStr = argv[3]; probLoss = boost::lexical_cast<int>(probLossStr); char * probDelayStr = argv[4]; probDelay = boost::lexical_cast<int>(probDelayStr); char* delayTStr = argv[5]; delayT = boost::lexical_cast<int>(delayTStr); struct timeval timeout; timeout.tv_usec = TIMEOUT * 1000; toms = TIMEOUT; /* Create our socket. */ if ((s = socket(AF_INET, SOCK_DGRAM, 0)) < 0) { cout << "Socket creation failed. (socket s)" << endl; return 0; } setsockopt(s, SOL_SOCKET, SO_RCVTIMEO, (char*)&timeout, sizeof(timeout)); /* * Bind our socket to an IP (whatever the computer decides) * and a specified port. * */ if (!loadFile()) { cout << "Loading file failed. (filename FILENAME)" << endl; return false; } memset((char *)&a, 0, sizeof(a)); a.sin_family = AF_INET; a.sin_addr.s_addr = htonl(INADDR_ANY); a.sin_port = htons(PORT); if (bind(s, (struct sockaddr *)&a, sizeof(a)) < 0) { cout << "Socket binding failed. (socket s, address a)" << endl; return 0; } fstr = string(file); cout << "File: " << endl << fstr << endl; base = 0; dropPck = false; calen = sizeof(ca); getGet(); return true; } bool getGet(){ unsigned char packet[PAKSIZE + 1]; rlen = recvfrom(s, packet, PAKSIZE, 0, (struct sockaddr *)&ca, &calen); return (rlen > 0) ? true : false; } bool isvpack(unsigned char * p) { cout << endl << "=== IS VALID PACKET TESTING" << endl; char * sns = new char[2]; memcpy(sns, &p[0], 1); sns[1] = '\0'; char * css = new char[7]; memcpy(css, &p[1], 6); css[6] = '\0'; char * db = new char[121 + 1]; memcpy(db, &p[2], 121); db[121] = '\0'; cout << "Seq. num: " << sns << endl; cout << "Checksum: " << css << endl; cout << "Message: " << db << endl; int sn = boost::lexical_cast<int>(sns); int cs = boost::lexical_cast<int>(css); Packet pk (0, db); pk.setSequenceNum(sn); // change to validate based on checksum and sequence number if(sn == 0) return false; //doesn't matter, only for the old version (netwark) if(cs != pk.generateCheckSum()) return false; return true; } bool getFile(){ /* Loop forever, waiting for messages from a client. */ cout << "Waiting on port " << PORT << "..." << endl; ofstream file("Dumpfile"); for (;;) { unsigned char packet[PAKSIZE + 1]; unsigned char dataPull[PAKSIZE - 7 + 1]; rlen = recvfrom(s, packet, PAKSIZE, 0, (struct sockaddr *)&ca, &calen); for(int x = 0; x < PAKSIZE - 7; x++) { dataPull[x] = packet[x + 7]; } dataPull[PAKSIZE - 7] = '\0'; packet[PAKSIZE] = '\0'; if (rlen > 0) { char * css = new char[6]; memcpy(css, &packet[1], 5); css[5] = '\0'; cout << endl << endl << "=== RECEIPT" << endl; cout << "Seq. num: " << packet[0] << endl; cout << "Checksum: " << css << endl; cout << "Received message: " << dataPull << endl; cout << "Sent response: "; if(isvpack(packet)) { ack = ACK; //seqNum = (seqNum) ? false : true; file << dataPull; } else { ack = NAK; } cout << ((ack == ACK) ? "ACK" : "NAK") << endl; Packet p (false, reinterpret_cast<const char *>(dataPull)); p.setCheckSum(boost::lexical_cast<int>(css)); p.setAckNack(ack); if(sendto(s, p.str(), PAKSIZE, 0, (struct sockaddr *)&ca, calen) < 0) { cout << "Acknowledgement failed. (socket s, acknowledgement message ack, client address ca, client address length calen)" << endl; return 0; } delete css; } } file.close(); return true; } bool loadFile() { ifstream is (FILENAME, ifstream::binary); if(is) { is.seekg(0, is.end); length = is.tellg(); is.seekg(0, is.beg); file = new char[length]; cout << "Reading " << length << " characters..." << endl; is.read(file, length); if(!is) { cout << "File reading failed. (filename " << FILENAME << "). Only " << is.gcount() << " could be read."; return false; } is.close(); } return true; } void loadWindow(){ for(int i = base; i < base + WIN_SIZE; i++) { window[i-base] = createPacket(i); if(strlen(window[i-base].getDataBuffer()) < BUFSIZE - 1 && window[i-base].getDataBuffer()[0] != 'G') { for(++i; i < base + WIN_SIZE; i++){ window[i-base].loadDataBuffer("\0"); } break; } } } bool sendFile() { /*Currently causes the program to only send the first 16 packets of file out requires additional code later to sendFile again with updated window*/ base = 0; while(base * BUFSIZE < length) { loadWindow(); for(int x = 0; x < WIN_SIZE; x++) { p = window[x]; if(!sendPacket()) continue; } if(p.str()[0] == '\0') break; for(int x = 0; x < WIN_SIZE; x++) { if(recvfrom(s, b, BUFSIZE + 7, 0, (struct sockaddr *)&ca, &calen) < 0) { cout << "=== ACK TIMEOUT" << endl; x--; continue; } if(isAck()) { handleAck(); } else { handleAck(); //handleNak(x); } memset(b, 0, BUFSIZE); } } if(sendto(s, "\0", BUFSIZE, 0, (struct sockaddr *)&ca, sizeof(ca)) < 0) { cout << "Final package sending failed. (socket s, server address sa, message m)" << endl; return false; } return true; } Packet createPacket(int index){ cout << endl; cout << "=== PACKET CREATION TESTING" << endl; string mstr = fstr.substr(index * BUFSIZE, BUFSIZE); cout << "mstr: " << mstr << endl; if(mstr.length() < BUFSIZE) { cout << "Null terminated mstr." << endl; mstr[length - (index * BUFSIZE)] = '\0'; } return Packet (index, mstr.c_str()); } bool sendPacket(){ cout << endl; cout << "=== TRANSMISSION START" << endl; int pc = probCorrupt; int pl = probLoss; int pd = probDelay; bool* pckStatus = gremlin(&p, pc, pl, pd); dropPck = pckStatus[0]; delayPck = pckStatus[1]; if (dropPck == true) return false; if (delayPck == true) p.setAckNack(1); if(sendto(s, p.str(), BUFSIZE + 8, 0, (struct sockaddr *)&ca, sizeof(ca)) < 0) { cout << "Package sending failed. (socket s, server address sa, message m)" << endl; return false; } return true; } bool isAck() { cout << endl << "=== SERVER RESPONSE TEST" << endl; cout << "Data: " << b << endl; if(b[6] == '0') return true; else return false; } void handleAck() { int ack = boost::lexical_cast<int>(b); if(base < ack) base = ack; cout << "Window base: " << base << endl; } void handleNak(int& x) { char * sns = new char[2]; memcpy(sns, &b[0], 1); sns[1] = '\0'; char * css = new char[5]; memcpy(css, &b[1], 5); char * db = new char[BUFSIZE + 1]; memcpy(db, &b[2], BUFSIZE); db[BUFSIZE] = '\0'; cout << "Sequence number: " << sns << endl; cout << "Checksum: " << css << endl; Packet pk (0, db); pk.setSequenceNum(boost::lexical_cast<int>(sns)); pk.setCheckSum(boost::lexical_cast<int>(css)); if(!pk.chksm()) x--; else x = (x - 2 > 0) ? x - 2 : 0; } bool* gremlin(Packet * pack, int corruptProb, int lossProb, int delayProb){ bool* packStatus = new bool[2]; int r = rand() % 100; cout << "Corruption probability: " << corruptProb << endl; cout << "Random number: " << r << endl; packStatus[0] = false; packStatus[1] = false; if(r <= (lossProb)){ packStatus[0] = true; cout << "Dropped!" << endl; } else if(r <= (delayProb)){ packStatus[1] = true; cout << "Delayed!" << endl; } else if(r <= (corruptProb)){ cout << "Corrupted!" << endl; pack->loadDataBuffer((char*)"GREMLIN LOL"); } cout << "Seq. num: " << pack->getSequenceNum() << endl; cout << "Checksum: " << pack->getCheckSum() << endl; //cout << "Message: " << pack->getDataBuffer() << endl; return packStatus; }
#include <sys/socket.h> #include <netinet/in.h> #include <arpa/inet.h> #include <unistd.h> #include <sys/time.h> #include <string.h> #include <iostream> #include <fstream> #include <boost/lexical_cast.hpp> #include "packet.h" #define USAGE "Usage:\r\nc \r\n[tux machine number] \r\n[probability of packet corruption in int form] \r\n[probability of packet loss in int form] \r\n[probability of packet delay] \r\n[length of delay in ms] \r\n" #define PORT 10038 #define PAKSIZE 512 #define ACK 0 #define NAK 1 #define BUFSIZE 505 #define FILENAME "Testfile" #define TIMEOUT 100 //in ms #define WIN_SIZE 16 using namespace std; bool isvpack(unsigned char * p); bool init(int argc, char** argv); bool loadFile(); bool getFile(); bool sendFile(); bool isAck(); void handleAck(); void handleNak(int& x); bool* gremlin(Packet * pack, int corruptProb, int lossProb, int delayProb); Packet createPacket(int index); void loadWindow(); bool sendPacket(); bool getGet(); struct sockaddr_in a; struct sockaddr_in ca; socklen_t calen; int rlen; int s; bool ack; string fstr; char * file; int probCorrupt; int probLoss; int probDelay; int delayT; Packet p; Packet window[16]; int length; bool dropPck; bool delayPck; int toms; unsigned char b[BUFSIZE]; int base; int main(int argc, char** argv) { if(!init(argc, argv)) return -1; sendFile(); return 0; } bool init(int argc, char** argv){ if(argc != 6) { cout << USAGE << endl; return false; } char * probCorruptStr = argv[2]; probCorrupt = boost::lexical_cast<int>(probCorruptStr); char * probLossStr = argv[3]; probLoss = boost::lexical_cast<int>(probLossStr); char * probDelayStr = argv[4]; probDelay = boost::lexical_cast<int>(probDelayStr); char* delayTStr = argv[5]; delayT = boost::lexical_cast<int>(delayTStr); struct timeval timeout; timeout.tv_usec = TIMEOUT * 1000; toms = TIMEOUT; /* Create our socket. */ if ((s = socket(AF_INET, SOCK_DGRAM, 0)) < 0) { cout << "Socket creation failed. (socket s)" << endl; return 0; } setsockopt(s, SOL_SOCKET, SO_RCVTIMEO, (char*)&timeout, sizeof(timeout)); /* * Bind our socket to an IP (whatever the computer decides) * and a specified port. * */ if (!loadFile()) { cout << "Loading file failed. (filename FILENAME)" << endl; return false; } memset((char *)&a, 0, sizeof(a)); a.sin_family = AF_INET; a.sin_addr.s_addr = htonl(INADDR_ANY); a.sin_port = htons(PORT); if (bind(s, (struct sockaddr *)&a, sizeof(a)) < 0) { cout << "Socket binding failed. (socket s, address a)" << endl; return 0; } fstr = string(file); cout << "File: " << endl << fstr << endl; base = 0; dropPck = false; calen = sizeof(ca); getGet(); return true; } bool getGet(){ unsigned char packet[PAKSIZE + 1]; rlen = recvfrom(s, packet, PAKSIZE, 0, (struct sockaddr *)&ca, &calen); return (rlen > 0) ? true : false; } bool isvpack(unsigned char * p) { cout << endl << "=== IS VALID PACKET TESTING" << endl; char * sns = new char[2]; memcpy(sns, &p[0], 1); sns[1] = '\0'; char * css = new char[7]; memcpy(css, &p[1], 6); css[6] = '\0'; char * db = new char[121 + 1]; memcpy(db, &p[2], 121); db[121] = '\0'; cout << "Seq. num: " << sns << endl; cout << "Checksum: " << css << endl; cout << "Message: " << db << endl; int sn = boost::lexical_cast<int>(sns); int cs = boost::lexical_cast<int>(css); Packet pk (0, db); pk.setSequenceNum(sn); // change to validate based on checksum and sequence number if(sn == 0) return false; //doesn't matter, only for the old version (netwark) if(cs != pk.generateCheckSum()) return false; return true; } bool getFile(){ /* Loop forever, waiting for messages from a client. */ cout << "Waiting on port " << PORT << "..." << endl; ofstream file("Dumpfile"); for (;;) { unsigned char packet[PAKSIZE + 1]; unsigned char dataPull[PAKSIZE - 7 + 1]; rlen = recvfrom(s, packet, PAKSIZE, 0, (struct sockaddr *)&ca, &calen); for(int x = 0; x < PAKSIZE - 7; x++) { dataPull[x] = packet[x + 7]; } dataPull[PAKSIZE - 7] = '\0'; packet[PAKSIZE] = '\0'; if (rlen > 0) { char * css = new char[6]; memcpy(css, &packet[1], 5); css[5] = '\0'; cout << endl << endl << "=== RECEIPT" << endl; cout << "Seq. num: " << packet[0] << endl; cout << "Checksum: " << css << endl; cout << "Received message: " << dataPull << endl; cout << "Sent response: "; if(isvpack(packet)) { ack = ACK; //seqNum = (seqNum) ? false : true; file << dataPull; } else { ack = NAK; } cout << ((ack == ACK) ? "ACK" : "NAK") << endl; Packet p (false, reinterpret_cast<const char *>(dataPull)); p.setCheckSum(boost::lexical_cast<int>(css)); p.setAckNack(ack); if(sendto(s, p.str(), PAKSIZE, 0, (struct sockaddr *)&ca, calen) < 0) { cout << "Acknowledgement failed. (socket s, acknowledgement message ack, client address ca, client address length calen)" << endl; return 0; } delete css; } } file.close(); return true; } bool loadFile() { ifstream is (FILENAME, ifstream::binary); if(is) { is.seekg(0, is.end); length = is.tellg(); is.seekg(0, is.beg); file = new char[length]; cout << "Reading " << length << " characters..." << endl; is.read(file, length); if(!is) { cout << "File reading failed. (filename " << FILENAME << "). Only " << is.gcount() << " could be read."; return false; } is.close(); } return true; } void loadWindow(){ for(int i = base; i < base + WIN_SIZE; i++) { window[i-base] = createPacket(i); if(strlen(window[i-base].getDataBuffer()) < BUFSIZE - 1 && window[i-base].getDataBuffer()[0] != 'G') { for(++i; i < base + WIN_SIZE; i++){ window[i-base].loadDataBuffer("\0"); } break; } } } bool sendFile() { /*Currently causes the program to only send the first 16 packets of file out requires additional code later to sendFile again with updated window*/ base = 0; while(base * BUFSIZE < length) { loadWindow(); for(int x = 0; x < WIN_SIZE; x++) { p = window[x]; if(!sendPacket()) continue; } if(p.str()[0] == '\0') break; for(int x = 0; x < WIN_SIZE; x++) { if(recvfrom(s, b, BUFSIZE + 7, 0, (struct sockaddr *)&ca, &calen) < 0) { cout << "=== ACK TIMEOUT" << endl; x--; continue; } if(isAck()) { handleAck(); } else { handleAck(); //handleNak(x); } memset(b, 0, BUFSIZE); } } if(sendto(s, "\0", BUFSIZE, 0, (struct sockaddr *)&ca, sizeof(ca)) < 0) { cout << "Final package sending failed. (socket s, server address sa, message m)" << endl; return false; } return true; } Packet createPacket(int index){ cout << endl; cout << "=== PACKET CREATION TESTING" << endl; string mstr = fstr.substr(index * BUFSIZE, BUFSIZE); cout << "index: " << index << endl; cout << "mstr: " << mstr << endl; if(mstr.length() < BUFSIZE) { cout << "Null terminated mstr." << endl; mstr[length - (index * BUFSIZE)] = '\0'; } return Packet (index, mstr.c_str()); } bool sendPacket(){ cout << endl; cout << "=== TRANSMISSION START" << endl; int pc = probCorrupt; int pl = probLoss; int pd = probDelay; bool* pckStatus = gremlin(&p, pc, pl, pd); dropPck = pckStatus[0]; delayPck = pckStatus[1]; if (dropPck == true) return false; if (delayPck == true) p.setAckNack(1); if(sendto(s, p.str(), BUFSIZE + 8, 0, (struct sockaddr *)&ca, sizeof(ca)) < 0) { cout << "Package sending failed. (socket s, server address sa, message m)" << endl; return false; } return true; } bool isAck() { cout << endl << "=== SERVER RESPONSE TEST" << endl; cout << "Data: " << b << endl; if(b[6] == '0') return true; else return false; } void handleAck() { int ack = boost::lexical_cast<int>(b); if(base < ack) base = ack; cout << "Window base: " << base << endl; } void handleNak(int& x) { char * sns = new char[2]; memcpy(sns, &b[0], 1); sns[1] = '\0'; char * css = new char[5]; memcpy(css, &b[1], 5); char * db = new char[BUFSIZE + 1]; memcpy(db, &b[2], BUFSIZE); db[BUFSIZE] = '\0'; cout << "Sequence number: " << sns << endl; cout << "Checksum: " << css << endl; Packet pk (0, db); pk.setSequenceNum(boost::lexical_cast<int>(sns)); pk.setCheckSum(boost::lexical_cast<int>(css)); if(!pk.chksm()) x--; else x = (x - 2 > 0) ? x - 2 : 0; } bool* gremlin(Packet * pack, int corruptProb, int lossProb, int delayProb){ bool* packStatus = new bool[2]; int r = rand() % 100; cout << "Corruption probability: " << corruptProb << endl; cout << "Random number: " << r << endl; packStatus[0] = false; packStatus[1] = false; if(r <= (lossProb)){ packStatus[0] = true; cout << "Dropped!" << endl; } else if(r <= (delayProb)){ packStatus[1] = true; cout << "Delayed!" << endl; } else if(r <= (corruptProb)){ cout << "Corrupted!" << endl; pack->loadDataBuffer((char*)"GREMLIN LOL"); } cout << "Seq. num: " << pack->getSequenceNum() << endl; cout << "Checksum: " << pack->getCheckSum() << endl; //cout << "Message: " << pack->getDataBuffer() << endl; return packStatus; }
Update testing
Update testing
C++
mit
javakat/notwork
71083e2acafe7f4f32a2c8820132611c67bddb95
cpp/pipelines/create_literary_remains_records.cc
cpp/pipelines/create_literary_remains_records.cc
/** \file create_literary_remains_records.cc * \author Dr. Johannes Ruscheinski * * A tool for creating literary remains MARC records from Beacon files. */ /* Copyright (C) 2019, 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/>. */ #include <unordered_map> #include <unordered_set> #include "BeaconFile.h" #include "MARC.h" #include "StringUtil.h" #include "util.h" namespace { void CopyMarc(MARC::Reader * const reader, MARC::Writer * const writer) { while (auto record = reader->read()) writer->write(record); } void LoadAuthorGNDNumbers(const std::string &filename, std::unordered_set<std::string> * const author_gnd_numbers, std::unordered_map<std::string, std::string> * const gnd_numbers_to_author_names_map) { auto reader(MARC::Reader::Factory(filename)); unsigned total_count(0); while (auto record = reader->read()) { ++total_count; const auto _100_field(record.findTag("100")); if (_100_field == record.end() or not _100_field->hasSubfield('a')) continue; const std::string author_name(_100_field->getFirstSubfieldWithCode('a')); for (const auto _035_field : record.getTagRange("035")) { const auto subfield_a(_035_field.getFirstSubfieldWithCode('a')); if (StringUtil::StartsWith(subfield_a, "(DE-588")) { const std::string gnd_number(subfield_a.substr(__builtin_strlen("(DE-588"))); author_gnd_numbers->emplace(gnd_number); (*gnd_numbers_to_author_names_map)[gnd_number] = author_name; break; } } } LOG_INFO("Loaded " + std::to_string(author_gnd_numbers->size()) + " author GND numbers from \"" + filename + "\" which contained a total of " + std::to_string(total_count) + " records."); } void AppendLiteraryRemainsRecords(MARC::Writer * const writer, const BeaconFile &beacon_file, const std::unordered_set<std::string> &author_gnd_numbers, const std::unordered_map<std::string, std::string> &gnd_numbers_to_author_names_map) { static char infix = 'A' - 1; ++infix; unsigned creation_count(0); for (const auto &beacon_entry : beacon_file) { if (author_gnd_numbers.find(beacon_entry.gnd_number_) != author_gnd_numbers.cend()) { ++creation_count; MARC::Record new_record(MARC::Record::TypeOfRecord::MIXED_MATERIALS, MARC::Record::BibliographicLevel::COLLECTION, "LR" + std::string(1, infix) + StringUtil::ToString(creation_count, 10, 6)); new_record.insertField("245", { { 'a', "Nachlass von " + gnd_numbers_to_author_names_map.find(beacon_entry.gnd_number_)->second } }); writer->write(new_record); } } LOG_INFO("Created " + std::to_string(creation_count) + " record(s) for \"" + beacon_file.getFileName() + "\"."); } } // unnamed namespace int Main(int argc, char **argv) { if (argc < 5) ::Usage("marc_input marc_output authority_records beacon_file1 [beacon_file2 .. beacon_fileN]"); auto reader(MARC::Reader::Factory(argv[1])); auto writer(MARC::Writer::Factory(argv[2])); CopyMarc(reader.get(), writer.get()); std::unordered_set<std::string> author_gnd_numbers; std::unordered_map<std::string, std::string> gnd_numbers_to_author_names_map; LoadAuthorGNDNumbers(argv[3], &author_gnd_numbers, &gnd_numbers_to_author_names_map); for (int arg_no(4); arg_no < argc; ++arg_no) { const BeaconFile beacon_file(argv[arg_no]); LOG_INFO("Loaded " + std::to_string(beacon_file.size()) + " entries from \"" + beacon_file.getFileName() + "\"!"); AppendLiteraryRemainsRecords(writer.get(), beacon_file, author_gnd_numbers, gnd_numbers_to_author_names_map); } return EXIT_SUCCESS; }
/** \file create_literary_remains_records.cc * \author Dr. Johannes Ruscheinski * * A tool for creating literary remains MARC records from Beacon files. */ /* Copyright (C) 2019, 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/>. */ #include <unordered_map> #include <unordered_set> #include "BeaconFile.h" #include "MARC.h" #include "StringUtil.h" #include "util.h" namespace { void CopyMarc(MARC::Reader * const reader, MARC::Writer * const writer) { while (auto record = reader->read()) writer->write(record); } void LoadAuthorGNDNumbers(const std::string &filename, std::unordered_set<std::string> * const author_gnd_numbers, std::unordered_map<std::string, std::string> * const gnd_numbers_to_author_names_map) { auto reader(MARC::Reader::Factory(filename)); unsigned total_count(0); while (auto record = reader->read()) { ++total_count; const auto _100_field(record.findTag("100")); if (_100_field == record.end() or not _100_field->hasSubfield('a')) continue; const std::string author_name(_100_field->getFirstSubfieldWithCode('a')); for (const auto _035_field : record.getTagRange("035")) { const auto subfield_a(_035_field.getFirstSubfieldWithCode('a')); if (StringUtil::StartsWith(subfield_a, "(DE-588")) { const std::string gnd_number(subfield_a.substr(__builtin_strlen("(DE-588"))); author_gnd_numbers->emplace(gnd_number); (*gnd_numbers_to_author_names_map)[gnd_number] = author_name; break; } } } LOG_INFO("Loaded " + std::to_string(author_gnd_numbers->size()) + " author GND numbers from \"" + filename + "\" which contained a total of " + std::to_string(total_count) + " records."); } void AppendLiteraryRemainsRecords(MARC::Writer * const writer, const BeaconFile &beacon_file, const std::unordered_set<std::string> &author_gnd_numbers, const std::unordered_map<std::string, std::string> &gnd_numbers_to_author_names_map) { static char infix = 'A' - 1; ++infix; unsigned creation_count(0); for (const auto &beacon_entry : beacon_file) { if (author_gnd_numbers.find(beacon_entry.gnd_number_) != author_gnd_numbers.cend()) { ++creation_count; MARC::Record new_record(MARC::Record::TypeOfRecord::MIXED_MATERIALS, MARC::Record::BibliographicLevel::COLLECTION, "LR" + std::string(1, infix) + StringUtil::ToString(creation_count, 10, 6)); const std::string &author_name(gnd_numbers_to_author_names_map.find(beacon_entry.gnd_number_)->second); new_record.insertField("100", { { 'a', author_name }, { '0', "(DE-588)" + beacon_entry.gnd_number_ } }); new_record.insertField("245", { { 'a', "Nachlass von " + author_name } }); new_record.insertField("856", { { 'u', beacon_file.getURL(beacon_entry) }, { '3', "Nachlassdatenbank" } }); writer->write(new_record); } } LOG_INFO("Created " + std::to_string(creation_count) + " record(s) for \"" + beacon_file.getFileName() + "\"."); } } // unnamed namespace int Main(int argc, char **argv) { if (argc < 5) ::Usage("marc_input marc_output authority_records beacon_file1 [beacon_file2 .. beacon_fileN]"); auto reader(MARC::Reader::Factory(argv[1])); auto writer(MARC::Writer::Factory(argv[2])); CopyMarc(reader.get(), writer.get()); std::unordered_set<std::string> author_gnd_numbers; std::unordered_map<std::string, std::string> gnd_numbers_to_author_names_map; LoadAuthorGNDNumbers(argv[3], &author_gnd_numbers, &gnd_numbers_to_author_names_map); for (int arg_no(4); arg_no < argc; ++arg_no) { const BeaconFile beacon_file(argv[arg_no]); LOG_INFO("Loaded " + std::to_string(beacon_file.size()) + " entries from \"" + beacon_file.getFileName() + "\"!"); AppendLiteraryRemainsRecords(writer.get(), beacon_file, author_gnd_numbers, gnd_numbers_to_author_names_map); } return EXIT_SUCCESS; }
Create a more useful record.
Create a more useful record.
C++
agpl-3.0
ubtue/ub_tools,ubtue/ub_tools,ubtue/ub_tools,ubtue/ub_tools,ubtue/ub_tools,ubtue/ub_tools,ubtue/ub_tools,ubtue/ub_tools
1db8775675685d1231904d2bb0e4be66968c0a9d
src/plugins/resourceeditor/resourceeditorw.cpp
src/plugins/resourceeditor/resourceeditorw.cpp
/**************************************************************************** ** ** 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 "resourceeditorw.h" #include "resourceeditorplugin.h" #include "resourceeditorconstants.h" #include "resourcefile_p.h" #include <resourceeditor/qrceditor/qrceditor.h> #include <coreplugin/icore.h> #include <coreplugin/actionmanager/actionmanager.h> #include <coreplugin/actionmanager/commandbutton.h> #include <coreplugin/editormanager/editormanager.h> #include <utils/reloadpromptutils.h> #include <utils/fileutils.h> #include <QTemporaryFile> #include <QFileInfo> #include <QDir> #include <qdebug.h> #include <QHBoxLayout> #include <QMenu> #include <QToolBar> #include <QInputDialog> #include <QClipboard> using namespace Utils; namespace ResourceEditor { namespace Internal { enum { debugResourceEditorW = 0 }; ResourceEditorDocument::ResourceEditorDocument(QObject *parent) : IDocument(parent), m_model(new RelativeResourceModel(this)) { setId(ResourceEditor::Constants::RESOURCEEDITOR_ID); setMimeType(QLatin1String(ResourceEditor::Constants::C_RESOURCE_MIMETYPE)); connect(m_model, &RelativeResourceModel::dirtyChanged, this, &ResourceEditorDocument::dirtyChanged); if (debugResourceEditorW) qDebug() << "ResourceEditorFile::ResourceEditorFile()"; } ResourceEditorW::ResourceEditorW(const Core::Context &context, ResourceEditorPlugin *plugin, QWidget *parent) : m_resourceDocument(new ResourceEditorDocument(this)), m_plugin(plugin), m_contextMenu(new QMenu), m_toolBar(new QToolBar) { m_resourceEditor = new QrcEditor(m_resourceDocument->model(), parent); setContext(context); setWidget(m_resourceEditor); Core::CommandButton *refreshButton = new Core::CommandButton(Constants::REFRESH, m_toolBar); refreshButton->setIcon(QIcon(QLatin1String(":/texteditor/images/finddocuments.png"))); connect(refreshButton, SIGNAL(clicked()), this, SLOT(onRefresh())); m_toolBar->addWidget(refreshButton); m_resourceEditor->setResourceDragEnabled(true); m_contextMenu->addAction(tr("Open File"), this, SLOT(openCurrentFile())); m_openWithMenu = m_contextMenu->addMenu(tr("Open With")); m_renameAction = m_contextMenu->addAction(tr("Rename File..."), this, SLOT(renameCurrentFile())); m_copyFileNameAction = m_contextMenu->addAction(tr("Copy Resource Path to Clipboard"), this, SLOT(copyCurrentResourcePath())); connect(m_resourceDocument, &ResourceEditorDocument::loaded, m_resourceEditor, &QrcEditor::loaded); connect(m_resourceEditor, SIGNAL(undoStackChanged(bool,bool)), this, SLOT(onUndoStackChanged(bool,bool))); connect(m_resourceEditor, SIGNAL(showContextMenu(QPoint,QString)), this, SLOT(showContextMenu(QPoint,QString))); connect(m_resourceEditor, SIGNAL(itemActivated(QString)), this, SLOT(openFile(QString))); connect(m_resourceEditor->commandHistory(), &QUndoStack::indexChanged, m_resourceDocument, [this]() { m_resourceDocument->setShouldAutoSave(true); }); if (debugResourceEditorW) qDebug() << "ResourceEditorW::ResourceEditorW()"; } ResourceEditorW::~ResourceEditorW() { if (m_resourceEditor) m_resourceEditor->deleteLater(); delete m_contextMenu; delete m_toolBar; } bool ResourceEditorW::open(QString *errorString, const QString &fileName, const QString &realFileName) { return m_resourceDocument->open(errorString, fileName, realFileName); } bool ResourceEditorDocument::open(QString *errorString, const QString &fileName, const QString &realFileName) { if (debugResourceEditorW) qDebug() << "ResourceEditorW::open: " << fileName; setBlockDirtyChanged(true); m_model->setFileName(realFileName); if (!m_model->reload()) { *errorString = m_model->errorMessage(); setBlockDirtyChanged(false); emit loaded(false); return false; } setFilePath(FileName::fromString(fileName)); setBlockDirtyChanged(false); m_model->setDirty(fileName != realFileName); m_shouldAutoSave = false; emit loaded(true); return true; } bool ResourceEditorDocument::save(QString *errorString, const QString &name, bool autoSave) { if (debugResourceEditorW) qDebug(">ResourceEditorW::save: %s", qPrintable(name)); const FileName oldFileName = filePath(); const FileName actualName = name.isEmpty() ? oldFileName : FileName::fromString(name); if (actualName.isEmpty()) return false; m_blockDirtyChanged = true; m_model->setFileName(actualName.toString()); if (!m_model->save()) { *errorString = m_model->errorMessage(); m_model->setFileName(oldFileName.toString()); m_blockDirtyChanged = false; return false; } m_shouldAutoSave = false; if (autoSave) { m_model->setFileName(oldFileName.toString()); m_model->setDirty(true); m_blockDirtyChanged = false; return true; } setFilePath(actualName); m_blockDirtyChanged = false; emit changed(); return true; } QString ResourceEditorDocument::plainText() const { return m_model->contents(); } bool ResourceEditorDocument::setContents(const QByteArray &contents) { TempFileSaver saver; saver.write(contents); if (!saver.finalize(Core::ICore::mainWindow())) return false; const QString originalFileName = m_model->fileName(); m_model->setFileName(saver.fileName()); const bool success = m_model->reload(); m_model->setFileName(originalFileName); m_shouldAutoSave = false; if (debugResourceEditorW) qDebug() << "ResourceEditorW::createNew: " << contents << " (" << saver.fileName() << ") returns " << success; emit loaded(success); return success; } void ResourceEditorDocument::setFilePath(const FileName &newName) { m_model->setFileName(newName.toString()); IDocument::setFilePath(newName); } void ResourceEditorDocument::setBlockDirtyChanged(bool value) { m_blockDirtyChanged = value; } RelativeResourceModel *ResourceEditorDocument::model() const { return m_model; } void ResourceEditorDocument::setShouldAutoSave(bool save) { m_shouldAutoSave = save; } QWidget *ResourceEditorW::toolBar() { return m_toolBar; } bool ResourceEditorDocument::shouldAutoSave() const { return m_shouldAutoSave; } bool ResourceEditorDocument::isModified() const { return m_model->dirty(); } bool ResourceEditorDocument::isSaveAsAllowed() const { return true; } bool ResourceEditorDocument::reload(QString *errorString, ReloadFlag flag, ChangeType type) { if (flag == FlagIgnore) return true; if (type == TypePermissions) { emit changed(); } else { emit aboutToReload(); QString fn = filePath().toString(); const bool success = open(errorString, fn, fn); emit reloadFinished(success); return success; } return true; } QString ResourceEditorDocument::defaultPath() const { return QString(); } QString ResourceEditorDocument::suggestedFileName() const { return QString(); } void ResourceEditorDocument::dirtyChanged(bool dirty) { if (m_blockDirtyChanged) return; // We emit changed() afterwards, unless it was an autosave if (debugResourceEditorW) qDebug() << " ResourceEditorW::dirtyChanged" << dirty; emit changed(); } void ResourceEditorW::onUndoStackChanged(bool canUndo, bool canRedo) { m_plugin->onUndoStackChanged(this, canUndo, canRedo); } void ResourceEditorW::showContextMenu(const QPoint &globalPoint, const QString &fileName) { Core::EditorManager::populateOpenWithMenu(m_openWithMenu, fileName); m_currentFileName = fileName; m_renameAction->setEnabled(!document()->isFileReadOnly()); m_contextMenu->popup(globalPoint); } void ResourceEditorW::openCurrentFile() { openFile(m_currentFileName); } void ResourceEditorW::openFile(const QString &fileName) { Core::EditorManager::openEditor(fileName); } void ResourceEditorW::onRefresh() { m_resourceEditor->refresh(); } void ResourceEditorW::renameCurrentFile() { m_resourceEditor->editCurrentItem(); } void ResourceEditorW::copyCurrentResourcePath() { QApplication::clipboard()->setText(m_resourceEditor->currentResourcePath()); } void ResourceEditorW::onUndo() { m_resourceEditor->onUndo(); } void ResourceEditorW::onRedo() { m_resourceEditor->onRedo(); } } // namespace Internal } // namespace ResourceEditor
/**************************************************************************** ** ** 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 "resourceeditorw.h" #include "resourceeditorplugin.h" #include "resourceeditorconstants.h" #include <resourceeditor/qrceditor/resourcefile_p.h> #include <resourceeditor/qrceditor/qrceditor.h> #include <coreplugin/icore.h> #include <coreplugin/actionmanager/actionmanager.h> #include <coreplugin/actionmanager/commandbutton.h> #include <coreplugin/editormanager/editormanager.h> #include <utils/reloadpromptutils.h> #include <utils/fileutils.h> #include <QTemporaryFile> #include <QFileInfo> #include <QDir> #include <qdebug.h> #include <QHBoxLayout> #include <QMenu> #include <QToolBar> #include <QInputDialog> #include <QClipboard> using namespace Utils; namespace ResourceEditor { namespace Internal { enum { debugResourceEditorW = 0 }; ResourceEditorDocument::ResourceEditorDocument(QObject *parent) : IDocument(parent), m_model(new RelativeResourceModel(this)) { setId(ResourceEditor::Constants::RESOURCEEDITOR_ID); setMimeType(QLatin1String(ResourceEditor::Constants::C_RESOURCE_MIMETYPE)); connect(m_model, &RelativeResourceModel::dirtyChanged, this, &ResourceEditorDocument::dirtyChanged); if (debugResourceEditorW) qDebug() << "ResourceEditorFile::ResourceEditorFile()"; } ResourceEditorW::ResourceEditorW(const Core::Context &context, ResourceEditorPlugin *plugin, QWidget *parent) : m_resourceDocument(new ResourceEditorDocument(this)), m_plugin(plugin), m_contextMenu(new QMenu), m_toolBar(new QToolBar) { m_resourceEditor = new QrcEditor(m_resourceDocument->model(), parent); setContext(context); setWidget(m_resourceEditor); Core::CommandButton *refreshButton = new Core::CommandButton(Constants::REFRESH, m_toolBar); refreshButton->setIcon(QIcon(QLatin1String(":/texteditor/images/finddocuments.png"))); connect(refreshButton, SIGNAL(clicked()), this, SLOT(onRefresh())); m_toolBar->addWidget(refreshButton); m_resourceEditor->setResourceDragEnabled(true); m_contextMenu->addAction(tr("Open File"), this, SLOT(openCurrentFile())); m_openWithMenu = m_contextMenu->addMenu(tr("Open With")); m_renameAction = m_contextMenu->addAction(tr("Rename File..."), this, SLOT(renameCurrentFile())); m_copyFileNameAction = m_contextMenu->addAction(tr("Copy Resource Path to Clipboard"), this, SLOT(copyCurrentResourcePath())); connect(m_resourceDocument, &ResourceEditorDocument::loaded, m_resourceEditor, &QrcEditor::loaded); connect(m_resourceEditor, SIGNAL(undoStackChanged(bool,bool)), this, SLOT(onUndoStackChanged(bool,bool))); connect(m_resourceEditor, SIGNAL(showContextMenu(QPoint,QString)), this, SLOT(showContextMenu(QPoint,QString))); connect(m_resourceEditor, SIGNAL(itemActivated(QString)), this, SLOT(openFile(QString))); connect(m_resourceEditor->commandHistory(), &QUndoStack::indexChanged, m_resourceDocument, [this]() { m_resourceDocument->setShouldAutoSave(true); }); if (debugResourceEditorW) qDebug() << "ResourceEditorW::ResourceEditorW()"; } ResourceEditorW::~ResourceEditorW() { if (m_resourceEditor) m_resourceEditor->deleteLater(); delete m_contextMenu; delete m_toolBar; } bool ResourceEditorW::open(QString *errorString, const QString &fileName, const QString &realFileName) { return m_resourceDocument->open(errorString, fileName, realFileName); } bool ResourceEditorDocument::open(QString *errorString, const QString &fileName, const QString &realFileName) { if (debugResourceEditorW) qDebug() << "ResourceEditorW::open: " << fileName; setBlockDirtyChanged(true); m_model->setFileName(realFileName); if (!m_model->reload()) { *errorString = m_model->errorMessage(); setBlockDirtyChanged(false); emit loaded(false); return false; } setFilePath(FileName::fromString(fileName)); setBlockDirtyChanged(false); m_model->setDirty(fileName != realFileName); m_shouldAutoSave = false; emit loaded(true); return true; } bool ResourceEditorDocument::save(QString *errorString, const QString &name, bool autoSave) { if (debugResourceEditorW) qDebug(">ResourceEditorW::save: %s", qPrintable(name)); const FileName oldFileName = filePath(); const FileName actualName = name.isEmpty() ? oldFileName : FileName::fromString(name); if (actualName.isEmpty()) return false; m_blockDirtyChanged = true; m_model->setFileName(actualName.toString()); if (!m_model->save()) { *errorString = m_model->errorMessage(); m_model->setFileName(oldFileName.toString()); m_blockDirtyChanged = false; return false; } m_shouldAutoSave = false; if (autoSave) { m_model->setFileName(oldFileName.toString()); m_model->setDirty(true); m_blockDirtyChanged = false; return true; } setFilePath(actualName); m_blockDirtyChanged = false; emit changed(); return true; } QString ResourceEditorDocument::plainText() const { return m_model->contents(); } bool ResourceEditorDocument::setContents(const QByteArray &contents) { TempFileSaver saver; saver.write(contents); if (!saver.finalize(Core::ICore::mainWindow())) return false; const QString originalFileName = m_model->fileName(); m_model->setFileName(saver.fileName()); const bool success = m_model->reload(); m_model->setFileName(originalFileName); m_shouldAutoSave = false; if (debugResourceEditorW) qDebug() << "ResourceEditorW::createNew: " << contents << " (" << saver.fileName() << ") returns " << success; emit loaded(success); return success; } void ResourceEditorDocument::setFilePath(const FileName &newName) { m_model->setFileName(newName.toString()); IDocument::setFilePath(newName); } void ResourceEditorDocument::setBlockDirtyChanged(bool value) { m_blockDirtyChanged = value; } RelativeResourceModel *ResourceEditorDocument::model() const { return m_model; } void ResourceEditorDocument::setShouldAutoSave(bool save) { m_shouldAutoSave = save; } QWidget *ResourceEditorW::toolBar() { return m_toolBar; } bool ResourceEditorDocument::shouldAutoSave() const { return m_shouldAutoSave; } bool ResourceEditorDocument::isModified() const { return m_model->dirty(); } bool ResourceEditorDocument::isSaveAsAllowed() const { return true; } bool ResourceEditorDocument::reload(QString *errorString, ReloadFlag flag, ChangeType type) { if (flag == FlagIgnore) return true; if (type == TypePermissions) { emit changed(); } else { emit aboutToReload(); QString fn = filePath().toString(); const bool success = open(errorString, fn, fn); emit reloadFinished(success); return success; } return true; } QString ResourceEditorDocument::defaultPath() const { return QString(); } QString ResourceEditorDocument::suggestedFileName() const { return QString(); } void ResourceEditorDocument::dirtyChanged(bool dirty) { if (m_blockDirtyChanged) return; // We emit changed() afterwards, unless it was an autosave if (debugResourceEditorW) qDebug() << " ResourceEditorW::dirtyChanged" << dirty; emit changed(); } void ResourceEditorW::onUndoStackChanged(bool canUndo, bool canRedo) { m_plugin->onUndoStackChanged(this, canUndo, canRedo); } void ResourceEditorW::showContextMenu(const QPoint &globalPoint, const QString &fileName) { Core::EditorManager::populateOpenWithMenu(m_openWithMenu, fileName); m_currentFileName = fileName; m_renameAction->setEnabled(!document()->isFileReadOnly()); m_contextMenu->popup(globalPoint); } void ResourceEditorW::openCurrentFile() { openFile(m_currentFileName); } void ResourceEditorW::openFile(const QString &fileName) { Core::EditorManager::openEditor(fileName); } void ResourceEditorW::onRefresh() { m_resourceEditor->refresh(); } void ResourceEditorW::renameCurrentFile() { m_resourceEditor->editCurrentItem(); } void ResourceEditorW::copyCurrentResourcePath() { QApplication::clipboard()->setText(m_resourceEditor->currentResourcePath()); } void ResourceEditorW::onUndo() { m_resourceEditor->onUndo(); } void ResourceEditorW::onRedo() { m_resourceEditor->onRedo(); } } // namespace Internal } // namespace ResourceEditor
Fix qbs compile
ResourceEditor: Fix qbs compile Change-Id: I49412b3e64ad63a33d03f741a9d4fdc6ba07f632 Reviewed-by: Eike Ziller <[email protected]>
C++
lgpl-2.1
xianian/qt-creator,xianian/qt-creator,xianian/qt-creator,martyone/sailfish-qtcreator,xianian/qt-creator,martyone/sailfish-qtcreator,martyone/sailfish-qtcreator,martyone/sailfish-qtcreator,xianian/qt-creator,martyone/sailfish-qtcreator,martyone/sailfish-qtcreator,xianian/qt-creator,martyone/sailfish-qtcreator,martyone/sailfish-qtcreator,xianian/qt-creator,martyone/sailfish-qtcreator,xianian/qt-creator,xianian/qt-creator
7efb0df17d18783381d25b42c69d765354a5ffb7
elang/optimizer/formatters/graphviz_formatter.cc
elang/optimizer/formatters/graphviz_formatter.cc
// Copyright 2015 Project Vogue. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include <iomanip> #include <sstream> #include <utility> #include <vector> #include "elang/optimizer/formatters/graphviz_formatter.h" #include "base/logging.h" #include "base/strings/stringprintf.h" #include "base/strings/utf_string_conversions.h" #include "elang/base/as_printable.h" #include "elang/base/atomic_string.h" #include "elang/optimizer/depth_first_traversal.h" #include "elang/optimizer/nodes.h" #include "elang/optimizer/node_visitor.h" #include "elang/optimizer/opcode.h" #include "elang/optimizer/types.h" namespace elang { namespace optimizer { namespace { bool IsBasicBlockBegin(Node* node) { switch (node->opcode()) { case Opcode::Case: case Opcode::Entry: case Opcode::IfException: case Opcode::IfFalse: case Opcode::IfSuccess: case Opcode::IfTrue: case Opcode::Loop: case Opcode::Merge: return true; } return false; } bool IsBasicBlockEnd(Node* node) { switch (node->opcode()) { case Opcode::Exit: case Opcode::Jump: case Opcode::If: case Opcode::Ret: case Opcode::Throw: return true; } return false; } bool HasConstraint(Node* from, Node* to) { if (from->opcode() == Opcode::Loop) return false; return IsBasicBlockEnd(from) || IsBasicBlockBegin(from); } base::StringPiece PrefixOf(Node* node) { if (node->IsControl()) return "%c"; if (node->IsEffect()) return "%e"; if (node->IsTuple()) return "%t"; return "%r"; } Node* ClusterOf(Node* node) { if (IsBasicBlockBegin(node)) return node; if (auto const phi = node->as<PhiNode>()) return phi->owner(); if (auto const phi = node->as<EffectPhiNode>()) return phi->owner(); if (IsBasicBlockEnd(node) || node->opcode() == Opcode::Call || node->opcode() == Opcode::GetData || node->opcode() == Opcode::GetEffect || node->opcode() == Opcode::GetTuple || node->opcode() == Opcode::Load || node->opcode() == Opcode::Store || node->opcode() == Opcode::Parameter) { return ClusterOf(node->input(0)); } return nullptr; } base::StringPiece NodeStyleOf(Node* node) { switch (node->opcode()) { case Opcode::Entry: case Opcode::Exit: return "style=diagonals"; } if (node->IsControl()) return "style=rounded"; if (node->IsEffect()) return "style=solid color=green"; return "style=solid"; } struct AsGraphvizLabel { Node* node; explicit AsGraphvizLabel(Node* node) : node(node) {} }; struct AsGraphvizNode { Node* node; explicit AsGraphvizNode(Node* node) : node(node) {} }; std::ostream& operator<<(std::ostream& ostream, const AsGraphvizLabel& wrapper); std::ostream& operator<<(std::ostream& ostream, const AsGraphvizNode& wrapper); ////////////////////////////////////////////////////////////////////// // // EdgePrinter // class EdgePrinter final : public NodeVisitor { public: explicit EdgePrinter(std::ostream* ostream); ~EdgePrinter() = default; private: // NodeVisitor void DoDefaultVisit(Node* node) final; std::ostream& ostream_; DISALLOW_COPY_AND_ASSIGN(EdgePrinter); }; EdgePrinter::EdgePrinter(std::ostream* ostream) : ostream_(*ostream) { } void EdgePrinter::DoDefaultVisit(Node* node) { if (node->IsLiteral()) return; if (auto const phi = node->as<PhiNode>()) { ostream_ << " node" << node->id() << " -> node" << phi->owner()->id() << " [style=dashed]" << std::endl; } else if (auto const phi = node->as<EffectPhiNode>()) { ostream_ << " node" << node->id() << " -> node" << phi->owner()->id() << " [style=dashed]" << std::endl; } auto index = 0; for (auto const input : node->inputs()) { if (input->IsLiteral()) { ++index; continue; } ostream_ << " "; ostream_ << "node" << node->id() << ":i" << index << " -> " << "node" << input->id() << " [" << (node->opcode() == Opcode::Loop && index ? " color=red constraint=true" : "") << (input->IsControl() ? " style=bold" : "") << (input->IsData() ? " color=transparent" : "") << (node->IsEffect() ? " style=dotted constraint=true" : "") << (input->IsEffect() ? " style=dotted" : "") << "]" << std::endl; ++index; } } ////////////////////////////////////////////////////////////////////// // // NodePrinter // class NodePrinter final : public NodeVisitor { public: explicit NodePrinter(std::ostream* ostream); ~NodePrinter() = default; private: // NodeVisitor void DoDefaultVisit(Node* node) final; std::ostream& ostream_; DISALLOW_COPY_AND_ASSIGN(NodePrinter); }; NodePrinter::NodePrinter(std::ostream* ostream) : ostream_(*ostream) { } void NodePrinter::DoDefaultVisit(Node* node) { if (node->IsLiteral()) return; ostream_ << AsGraphvizNode(node) << std::endl; } std::ostream& operator<<(std::ostream& ostream, const AsGraphvizLabel& wrapper) { static bool escape[256]; if (!escape['<']) { escape['<'] = true; escape['>'] = true; escape['|'] = true; escape['\\'] = true; escape['"'] = true; } auto const node = wrapper.node; DCHECK(node->IsLiteral()); std::stringstream stream; stream << *node; ostream << '"'; for (auto const ch : stream.str()) { if (escape[ch & 0xFF]) ostream << '\\'; ostream << ch; } return ostream << '"'; } std::ostream& operator<<(std::ostream& ostream, const AsGraphvizNode& wrapper) { auto const node = wrapper.node; auto const cluster = ClusterOf(node); ostream << " "; if (cluster) { ostream << "subgraph cluster_" << cluster->id() << " {" << " style=filled;" << (cluster->opcode() == Opcode::Loop ? " color=\"#CCCCCC\"" : " color=\"#EEEEEE\""); } ostream << "node" << node->id() << " [shape=record " << NodeStyleOf(node) << " label=\"{{" << PrefixOf(node) << node->id() << "=" << node->mnemonic(); std::vector<std::pair<Node*, int>> literals; auto index = 0; for (auto const input : node->inputs()) { ostream << "|<i" << index << ">"; if (input->IsLiteral()) literals.push_back(std::make_pair(input, index)); else ostream << PrefixOf(input) << input->id(); ++index; } ostream << "}}\"];"; for (auto const pair : literals) { auto const index = pair.second; auto const lit = pair.first; ostream << "lit" << node->id() << "_" << index << " [color=blue label=" << AsGraphvizLabel(lit) << "];" << "node" << node->id() << ":i" << index << " -> " << "lit" << node->id() << "_" << index << " [style=dashed color=blue]"; } if (cluster) ostream << "}"; return ostream; } } // namespace std::ostream& operator<<(std::ostream& ostream, const AsGraphviz& wrapper) { ostream << "digraph IR {" << std::endl // Node: when we set |concentrate| to true, "dot" is crashed with // "samples/statements/for.e". << " concentrate=false" << std::endl << " node [fontname=monospace fontsize=8, hieght=0.25]" << std::endl << " overlap=false" << std::endl << " rankdir=\"BT\"" << std::endl << " ranksep=\"1.2 equally\"" << std::endl << " splines=true" << std::endl << std::endl; auto const function = wrapper.function; DepthFirstTraversal<OnInputEdge, const Function> walker; ostream << " // Nodes" << std::endl; NodePrinter node_printer(&ostream); walker.Traverse(function, &node_printer); ostream << std::endl; ostream << " // Edges" << std::endl; EdgePrinter edge_printer(&ostream); walker.Traverse(function, &edge_printer); ostream << "}" << std::endl; return ostream; } } // namespace optimizer } // namespace elang
// Copyright 2015 Project Vogue. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include <iomanip> #include <sstream> #include <utility> #include <vector> #include "elang/optimizer/formatters/graphviz_formatter.h" #include "base/logging.h" #include "base/strings/stringprintf.h" #include "base/strings/utf_string_conversions.h" #include "elang/base/as_printable.h" #include "elang/base/atomic_string.h" #include "elang/optimizer/depth_first_traversal.h" #include "elang/optimizer/nodes.h" #include "elang/optimizer/node_visitor.h" #include "elang/optimizer/opcode.h" #include "elang/optimizer/types.h" namespace elang { namespace optimizer { namespace { bool IsBasicBlockBegin(Node* node) { switch (node->opcode()) { case Opcode::Case: case Opcode::Entry: case Opcode::IfException: case Opcode::IfFalse: case Opcode::IfSuccess: case Opcode::IfTrue: case Opcode::Loop: case Opcode::Merge: return true; } return false; } bool IsBasicBlockEnd(Node* node) { switch (node->opcode()) { case Opcode::Exit: case Opcode::Jump: case Opcode::If: case Opcode::Ret: case Opcode::Throw: return true; } return false; } bool HasConstraint(Node* from, Node* to) { if (from->opcode() == Opcode::Loop) return false; return IsBasicBlockEnd(from) || IsBasicBlockBegin(from); } base::StringPiece PrefixOf(Node* node) { if (node->IsControl()) return "%c"; if (node->IsEffect()) return "%e"; if (node->IsTuple()) return "%t"; return "%r"; } Node* ClusterOf(Node* node) { if (IsBasicBlockBegin(node)) return node; if (auto const phi = node->as<PhiNode>()) return phi->owner(); if (auto const phi = node->as<EffectPhiNode>()) return phi->owner(); if (IsBasicBlockEnd(node) || node->opcode() == Opcode::Call || node->opcode() == Opcode::GetData || node->opcode() == Opcode::GetEffect || node->opcode() == Opcode::GetTuple || node->opcode() == Opcode::Load || node->opcode() == Opcode::Store || node->opcode() == Opcode::Parameter) { return ClusterOf(node->input(0)); } return nullptr; } base::StringPiece EdgeColorOf(Node* from, Node* to, int index) { if (from->opcode() == Opcode::Loop && index) return " color=red"; if (to->IsData()) return " color=transparent"; return ""; } base::StringPiece EdgeConstraintOf(Node* from, Node* to, int index) { if (from->opcode() == Opcode::Loop && index) return " constraint=false"; if (from->opcode() == Opcode::Phi || from->opcode() == Opcode::EffectPhi) return " constraint=false"; return ""; } base::StringPiece EdgeStyleOf(Node* from, Node* to, int index) { if (from->IsControl() && to->IsControl()) return " style=bold"; if (to->IsEffect()) return " style=dotted"; return ""; } base::StringPiece NodeStyleOf(Node* node) { switch (node->opcode()) { case Opcode::Entry: case Opcode::Exit: return "style=diagonals"; } if (node->IsControl()) return "style=rounded"; if (node->IsEffect()) return "style=solid color=green"; return "style=solid"; } struct AsGraphvizLabel { Node* node; explicit AsGraphvizLabel(Node* node) : node(node) {} }; struct AsGraphvizNode { Node* node; explicit AsGraphvizNode(Node* node) : node(node) {} }; std::ostream& operator<<(std::ostream& ostream, const AsGraphvizLabel& wrapper); std::ostream& operator<<(std::ostream& ostream, const AsGraphvizNode& wrapper); ////////////////////////////////////////////////////////////////////// // // EdgePrinter // class EdgePrinter final : public NodeVisitor { public: explicit EdgePrinter(std::ostream* ostream); ~EdgePrinter() = default; private: // NodeVisitor void DoDefaultVisit(Node* node) final; std::ostream& ostream_; DISALLOW_COPY_AND_ASSIGN(EdgePrinter); }; EdgePrinter::EdgePrinter(std::ostream* ostream) : ostream_(*ostream) { } void EdgePrinter::DoDefaultVisit(Node* node) { if (node->IsLiteral()) return; if (auto const phi = node->as<PhiNode>()) { ostream_ << " node" << node->id() << " -> node" << phi->owner()->id() << " [style=dashed]" << std::endl; } else if (auto const phi = node->as<EffectPhiNode>()) { ostream_ << " node" << node->id() << " -> node" << phi->owner()->id() << " [style=dashed]" << std::endl; } auto index = 0; for (auto const input : node->inputs()) { if (input->IsLiteral()) { ++index; continue; } ostream_ << " "; ostream_ << "node" << node->id() << ":i" << index << " -> " << "node" << input->id() << " [" << EdgeColorOf(node, input, index) << EdgeConstraintOf(node, input, index) << EdgeStyleOf(node, input, index) << "]" << std::endl; ++index; } } ////////////////////////////////////////////////////////////////////// // // NodePrinter // class NodePrinter final : public NodeVisitor { public: explicit NodePrinter(std::ostream* ostream); ~NodePrinter() = default; private: // NodeVisitor void DoDefaultVisit(Node* node) final; std::ostream& ostream_; DISALLOW_COPY_AND_ASSIGN(NodePrinter); }; NodePrinter::NodePrinter(std::ostream* ostream) : ostream_(*ostream) { } void NodePrinter::DoDefaultVisit(Node* node) { if (node->IsLiteral()) return; ostream_ << AsGraphvizNode(node) << std::endl; } std::ostream& operator<<(std::ostream& ostream, const AsGraphvizLabel& wrapper) { static bool escape[256]; if (!escape['<']) { escape['<'] = true; escape['>'] = true; escape['|'] = true; escape['\\'] = true; escape['"'] = true; } auto const node = wrapper.node; DCHECK(node->IsLiteral()); std::stringstream stream; stream << *node; ostream << '"'; for (auto const ch : stream.str()) { if (escape[ch & 0xFF]) ostream << '\\'; ostream << ch; } return ostream << '"'; } std::ostream& operator<<(std::ostream& ostream, const AsGraphvizNode& wrapper) { auto const node = wrapper.node; auto const cluster = ClusterOf(node); ostream << " "; if (cluster) { ostream << "subgraph cluster_" << cluster->id() << " {" << " style=filled;" << (cluster->opcode() == Opcode::Loop ? " color=\"#CCCCCC\"" : " color=\"#EEEEEE\""); } ostream << "node" << node->id() << " [shape=record " << NodeStyleOf(node) << " label=\"{{" << PrefixOf(node) << node->id() << "=" << node->mnemonic(); std::vector<std::pair<Node*, int>> literals; auto index = 0; for (auto const input : node->inputs()) { ostream << "|<i" << index << ">"; if (input->IsLiteral()) literals.push_back(std::make_pair(input, index)); else ostream << PrefixOf(input) << input->id(); ++index; } ostream << "}}\"];"; for (auto const pair : literals) { auto const index = pair.second; auto const lit = pair.first; ostream << "lit" << node->id() << "_" << index << " [color=blue label=" << AsGraphvizLabel(lit) << "];" << "node" << node->id() << ":i" << index << " -> " << "lit" << node->id() << "_" << index << " [style=dashed color=blue]"; } if (cluster) ostream << "}"; return ostream; } } // namespace std::ostream& operator<<(std::ostream& ostream, const AsGraphviz& wrapper) { ostream << "digraph IR {" << std::endl // Node: when we set |concentrate| to true, "dot" is crashed with // "samples/statements/for.e". << " concentrate=false" << std::endl << " node [fontname=monospace fontsize=8, hieght=0.25]" << std::endl << " overlap=false" << std::endl << " rankdir=\"BT\"" << std::endl << " ranksep=\"1.2 equally\"" << std::endl << " splines=true" << std::endl << std::endl; auto const function = wrapper.function; DepthFirstTraversal<OnInputEdge, const Function> walker; ostream << " // Nodes" << std::endl; NodePrinter node_printer(&ostream); walker.Traverse(function, &node_printer); ostream << std::endl; ostream << " // Edges" << std::endl; EdgePrinter edge_printer(&ostream); walker.Traverse(function, &edge_printer); ostream << "}" << std::endl; return ostream; } } // namespace optimizer } // namespace elang
Revise edge attributes calculation in Graphiviz formatter.
elang/optimizer/formatters: Revise edge attributes calculation in Graphiviz formatter.
C++
apache-2.0
eval1749/elang,eval1749/elang,eval1749/elang,eval1749/elang,eval1749/elang
3a8b19a2e1493b74184796adaf2d4d5e7c141dd7
elements/gstqtvideosink/gstqtglvideosinkbase.cpp
elements/gstqtvideosink/gstqtglvideosinkbase.cpp
/* Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies). <[email protected]> Copyright (C) 2011-2012 Collabora Ltd. <[email protected]> This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License version 2.1 as published by the Free Software Foundation. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. */ #include "gstqtglvideosinkbase.h" #include "painters/openglsurfacepainter.h" #include "delegates/qtvideosinkdelegate.h" #define CAPS_FORMATS "{ BGRA, BGRx, ARGB, xRGB, RGB, RGB16, BGR, v308, AYUV, YV12, I420 }" const char * const GstQtGLVideoSinkBase::s_colorbalance_labels[] = { "contrast", "brightness", "hue", "saturation" }; GstQtVideoSinkBaseClass *GstQtGLVideoSinkBase::s_parent_class = 0; //------------------------------ DEFINE_TYPE_WITH_CODE(GstQtGLVideoSinkBase, GST_TYPE_QT_VIDEO_SINK_BASE, init_interfaces) void GstQtGLVideoSinkBase::init_interfaces(GType type) { static const GInterfaceInfo colorbalance_info = { (GInterfaceInitFunc) &GstQtGLVideoSinkBase::colorbalance_init, NULL, NULL }; g_type_add_interface_static(type, GST_TYPE_COLOR_BALANCE, &colorbalance_info); } //------------------------------ void GstQtGLVideoSinkBase::base_init(gpointer g_class) { GstElementClass *element_class = GST_ELEMENT_CLASS(g_class); element_class->padtemplates = NULL; //get rid of the pad template of the base class static GstStaticPadTemplate sink_pad_template = GST_STATIC_PAD_TEMPLATE("sink", GST_PAD_SINK, GST_PAD_ALWAYS, GST_STATIC_CAPS (GST_VIDEO_CAPS_MAKE (CAPS_FORMATS)) ); gst_element_class_add_pad_template( element_class, gst_static_pad_template_get(&sink_pad_template)); } void GstQtGLVideoSinkBase::class_init(gpointer g_class, gpointer class_data) { Q_UNUSED(class_data); s_parent_class = reinterpret_cast<GstQtVideoSinkBaseClass*>(g_type_class_peek_parent(g_class)); GObjectClass *object_class = G_OBJECT_CLASS(g_class); object_class->finalize = GstQtGLVideoSinkBase::finalize; object_class->set_property = GstQtGLVideoSinkBase::set_property; object_class->get_property = GstQtGLVideoSinkBase::get_property; GstBaseSinkClass *base_sink_class = GST_BASE_SINK_CLASS(g_class); base_sink_class->start = GstQtGLVideoSinkBase::start; g_object_class_install_property(object_class, PROP_CONTRAST, g_param_spec_int("contrast", "Contrast", "The contrast of the video", -100, 100, 0, static_cast<GParamFlags>(G_PARAM_READWRITE))); g_object_class_install_property(object_class, PROP_BRIGHTNESS, g_param_spec_int("brightness", "Brightness", "The brightness of the video", -100, 100, 0, static_cast<GParamFlags>(G_PARAM_READWRITE))); g_object_class_install_property(object_class, PROP_HUE, g_param_spec_int("hue", "Hue", "The hue of the video", -100, 100, 0, static_cast<GParamFlags>(G_PARAM_READWRITE))); g_object_class_install_property(object_class, PROP_SATURATION, g_param_spec_int("saturation", "Saturation", "The saturation of the video", -100, 100, 0, static_cast<GParamFlags>(G_PARAM_READWRITE))); } void GstQtGLVideoSinkBase::init(GTypeInstance *instance, gpointer g_class) { Q_UNUSED(g_class); GstQtGLVideoSinkBase *self = GST_QT_GL_VIDEO_SINK_BASE(instance); GstColorBalanceChannel *channel; self->m_channels_list = NULL; for (int i=0; i < LABEL_LAST; i++) { channel = GST_COLOR_BALANCE_CHANNEL(g_object_new(GST_TYPE_COLOR_BALANCE_CHANNEL, NULL)); channel->label = g_strdup(s_colorbalance_labels[i]); channel->min_value = -100; channel->max_value = 100; self->m_channels_list = g_list_append(self->m_channels_list, channel); } } void GstQtGLVideoSinkBase::finalize(GObject *object) { GstQtGLVideoSinkBase *self = GST_QT_GL_VIDEO_SINK_BASE(object); while (self->m_channels_list) { GstColorBalanceChannel *channel = GST_COLOR_BALANCE_CHANNEL(self->m_channels_list->data); g_object_unref(channel); self->m_channels_list = g_list_next(self->m_channels_list); } g_list_free(self->m_channels_list); G_OBJECT_CLASS(s_parent_class)->finalize(object); } //------------------------------ void GstQtGLVideoSinkBase::colorbalance_init(GstColorBalanceInterface *interface, gpointer data) { Q_UNUSED(data); interface->list_channels = GstQtGLVideoSinkBase::colorbalance_list_channels; interface->set_value = GstQtGLVideoSinkBase::colorbalance_set_value; interface->get_value = GstQtGLVideoSinkBase::colorbalance_get_value; interface->get_balance_type = NULL; //FIXME: need implementation } const GList *GstQtGLVideoSinkBase::colorbalance_list_channels(GstColorBalance *balance) { return GST_QT_GL_VIDEO_SINK_BASE(balance)->m_channels_list; } void GstQtGLVideoSinkBase::colorbalance_set_value(GstColorBalance *balance, GstColorBalanceChannel *channel, gint value) { GstQtVideoSinkBase *sink = GST_QT_VIDEO_SINK_BASE(balance); if (!qstrcmp(channel->label, s_colorbalance_labels[LABEL_CONTRAST])) { sink->delegate->setContrast(value); } else if (!qstrcmp(channel->label, s_colorbalance_labels[LABEL_BRIGHTNESS])) { sink->delegate->setBrightness(value); } else if (!qstrcmp(channel->label, s_colorbalance_labels[LABEL_HUE])) { sink->delegate->setHue(value); } else if (!qstrcmp(channel->label, s_colorbalance_labels[LABEL_SATURATION])) { sink->delegate->setSaturation(value); } else { GST_WARNING_OBJECT(sink, "Unknown colorbalance channel %s", channel->label); } } gint GstQtGLVideoSinkBase::colorbalance_get_value(GstColorBalance *balance, GstColorBalanceChannel *channel) { GstQtVideoSinkBase *sink = GST_QT_VIDEO_SINK_BASE(balance); if (!qstrcmp(channel->label, s_colorbalance_labels[LABEL_CONTRAST])) { return sink->delegate->contrast(); } else if (!qstrcmp(channel->label, s_colorbalance_labels[LABEL_BRIGHTNESS])) { return sink->delegate->brightness(); } else if (!qstrcmp(channel->label, s_colorbalance_labels[LABEL_HUE])) { return sink->delegate->hue(); } else if (!qstrcmp(channel->label, s_colorbalance_labels[LABEL_SATURATION])) { return sink->delegate->saturation(); } else { GST_WARNING_OBJECT(sink, "Unknown colorbalance channel %s", channel->label); } return 0; } //------------------------------ void GstQtGLVideoSinkBase::set_property(GObject *object, guint prop_id, const GValue *value, GParamSpec *pspec) { GstQtVideoSinkBase *sink = GST_QT_VIDEO_SINK_BASE(object); switch (prop_id) { case PROP_CONTRAST: sink->delegate->setContrast(g_value_get_int(value)); break; case PROP_BRIGHTNESS: sink->delegate->setBrightness(g_value_get_int(value)); break; case PROP_HUE: sink->delegate->setHue(g_value_get_int(value)); break; case PROP_SATURATION: sink->delegate->setSaturation(g_value_get_int(value)); break; default: G_OBJECT_WARN_INVALID_PROPERTY_ID(object, prop_id, pspec); break; } } void GstQtGLVideoSinkBase::get_property(GObject *object, guint prop_id, GValue *value, GParamSpec *pspec) { GstQtVideoSinkBase *sink = GST_QT_VIDEO_SINK_BASE(object); switch (prop_id) { case PROP_CONTRAST: g_value_set_int(value, sink->delegate->contrast()); break; case PROP_BRIGHTNESS: g_value_set_int(value, sink->delegate->brightness()); break; case PROP_HUE: g_value_set_int(value, sink->delegate->hue()); break; case PROP_SATURATION: g_value_set_int(value, sink->delegate->saturation()); break; default: G_OBJECT_WARN_INVALID_PROPERTY_ID(object, prop_id, pspec); break; } } //------------------------------ gboolean GstQtGLVideoSinkBase::start(GstBaseSink *base) { GstQtVideoSinkBase *sink = GST_QT_VIDEO_SINK_BASE(base); //fail on purpose if the user hasn't set a context if (sink->delegate->supportedPainterTypes() == QtVideoSinkDelegate::Generic) { GST_WARNING_OBJECT(sink, "Neither GLSL nor ARB Fragment Program are supported " "for painting. Did you forget to set a gl context?"); return FALSE; } else { return TRUE; } } gboolean GstQtGLVideoSinkBase::set_caps(GstBaseSink *base, GstCaps *caps) { GstQtVideoSinkBase *sink = GST_QT_VIDEO_SINK_BASE(base); GST_LOG_OBJECT(sink, "new caps %" GST_PTR_FORMAT, caps); BufferFormat format = BufferFormat::fromCaps(caps); if (OpenGLSurfacePainter::supportedPixelFormats().contains(format.videoFormat())) { sink->delegate->setBufferFormat(format); return TRUE; } else { return FALSE; } }
/* Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies). <[email protected]> Copyright (C) 2011-2012 Collabora Ltd. <[email protected]> This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License version 2.1 as published by the Free Software Foundation. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. */ #include "gstqtglvideosinkbase.h" #include "painters/openglsurfacepainter.h" #include "delegates/qtvideosinkdelegate.h" #define CAPS_FORMATS "{ BGRA, BGRx, ARGB, xRGB, RGB, RGB16, BGR, v308, AYUV, YV12, I420 }" const char * const GstQtGLVideoSinkBase::s_colorbalance_labels[] = { "contrast", "brightness", "hue", "saturation" }; GstQtVideoSinkBaseClass *GstQtGLVideoSinkBase::s_parent_class = 0; //------------------------------ DEFINE_TYPE_WITH_CODE(GstQtGLVideoSinkBase, GST_TYPE_QT_VIDEO_SINK_BASE, init_interfaces) void GstQtGLVideoSinkBase::init_interfaces(GType type) { static const GInterfaceInfo colorbalance_info = { (GInterfaceInitFunc) &GstQtGLVideoSinkBase::colorbalance_init, NULL, NULL }; g_type_add_interface_static(type, GST_TYPE_COLOR_BALANCE, &colorbalance_info); } //------------------------------ void GstQtGLVideoSinkBase::base_init(gpointer g_class) { GstElementClass *element_class = GST_ELEMENT_CLASS(g_class); element_class->padtemplates = NULL; //get rid of the pad template of the base class static GstStaticPadTemplate sink_pad_template = GST_STATIC_PAD_TEMPLATE("sink", GST_PAD_SINK, GST_PAD_ALWAYS, GST_STATIC_CAPS (GST_VIDEO_CAPS_MAKE (CAPS_FORMATS)) ); gst_element_class_add_pad_template( element_class, gst_static_pad_template_get(&sink_pad_template)); } void GstQtGLVideoSinkBase::class_init(gpointer g_class, gpointer class_data) { Q_UNUSED(class_data); s_parent_class = reinterpret_cast<GstQtVideoSinkBaseClass*>(g_type_class_peek_parent(g_class)); GObjectClass *object_class = G_OBJECT_CLASS(g_class); object_class->finalize = GstQtGLVideoSinkBase::finalize; object_class->set_property = GstQtGLVideoSinkBase::set_property; object_class->get_property = GstQtGLVideoSinkBase::get_property; GstBaseSinkClass *base_sink_class = GST_BASE_SINK_CLASS(g_class); base_sink_class->start = GstQtGLVideoSinkBase::start; base_sink_class->set_caps = GstQtGLVideoSinkBase::set_caps; g_object_class_install_property(object_class, PROP_CONTRAST, g_param_spec_int("contrast", "Contrast", "The contrast of the video", -100, 100, 0, static_cast<GParamFlags>(G_PARAM_READWRITE))); g_object_class_install_property(object_class, PROP_BRIGHTNESS, g_param_spec_int("brightness", "Brightness", "The brightness of the video", -100, 100, 0, static_cast<GParamFlags>(G_PARAM_READWRITE))); g_object_class_install_property(object_class, PROP_HUE, g_param_spec_int("hue", "Hue", "The hue of the video", -100, 100, 0, static_cast<GParamFlags>(G_PARAM_READWRITE))); g_object_class_install_property(object_class, PROP_SATURATION, g_param_spec_int("saturation", "Saturation", "The saturation of the video", -100, 100, 0, static_cast<GParamFlags>(G_PARAM_READWRITE))); } void GstQtGLVideoSinkBase::init(GTypeInstance *instance, gpointer g_class) { Q_UNUSED(g_class); GstQtGLVideoSinkBase *self = GST_QT_GL_VIDEO_SINK_BASE(instance); GstColorBalanceChannel *channel; self->m_channels_list = NULL; for (int i=0; i < LABEL_LAST; i++) { channel = GST_COLOR_BALANCE_CHANNEL(g_object_new(GST_TYPE_COLOR_BALANCE_CHANNEL, NULL)); channel->label = g_strdup(s_colorbalance_labels[i]); channel->min_value = -100; channel->max_value = 100; self->m_channels_list = g_list_append(self->m_channels_list, channel); } } void GstQtGLVideoSinkBase::finalize(GObject *object) { GstQtGLVideoSinkBase *self = GST_QT_GL_VIDEO_SINK_BASE(object); while (self->m_channels_list) { GstColorBalanceChannel *channel = GST_COLOR_BALANCE_CHANNEL(self->m_channels_list->data); g_object_unref(channel); self->m_channels_list = g_list_next(self->m_channels_list); } g_list_free(self->m_channels_list); G_OBJECT_CLASS(s_parent_class)->finalize(object); } //------------------------------ void GstQtGLVideoSinkBase::colorbalance_init(GstColorBalanceInterface *interface, gpointer data) { Q_UNUSED(data); interface->list_channels = GstQtGLVideoSinkBase::colorbalance_list_channels; interface->set_value = GstQtGLVideoSinkBase::colorbalance_set_value; interface->get_value = GstQtGLVideoSinkBase::colorbalance_get_value; interface->get_balance_type = NULL; //FIXME: need implementation } const GList *GstQtGLVideoSinkBase::colorbalance_list_channels(GstColorBalance *balance) { return GST_QT_GL_VIDEO_SINK_BASE(balance)->m_channels_list; } void GstQtGLVideoSinkBase::colorbalance_set_value(GstColorBalance *balance, GstColorBalanceChannel *channel, gint value) { GstQtVideoSinkBase *sink = GST_QT_VIDEO_SINK_BASE(balance); if (!qstrcmp(channel->label, s_colorbalance_labels[LABEL_CONTRAST])) { sink->delegate->setContrast(value); } else if (!qstrcmp(channel->label, s_colorbalance_labels[LABEL_BRIGHTNESS])) { sink->delegate->setBrightness(value); } else if (!qstrcmp(channel->label, s_colorbalance_labels[LABEL_HUE])) { sink->delegate->setHue(value); } else if (!qstrcmp(channel->label, s_colorbalance_labels[LABEL_SATURATION])) { sink->delegate->setSaturation(value); } else { GST_WARNING_OBJECT(sink, "Unknown colorbalance channel %s", channel->label); } } gint GstQtGLVideoSinkBase::colorbalance_get_value(GstColorBalance *balance, GstColorBalanceChannel *channel) { GstQtVideoSinkBase *sink = GST_QT_VIDEO_SINK_BASE(balance); if (!qstrcmp(channel->label, s_colorbalance_labels[LABEL_CONTRAST])) { return sink->delegate->contrast(); } else if (!qstrcmp(channel->label, s_colorbalance_labels[LABEL_BRIGHTNESS])) { return sink->delegate->brightness(); } else if (!qstrcmp(channel->label, s_colorbalance_labels[LABEL_HUE])) { return sink->delegate->hue(); } else if (!qstrcmp(channel->label, s_colorbalance_labels[LABEL_SATURATION])) { return sink->delegate->saturation(); } else { GST_WARNING_OBJECT(sink, "Unknown colorbalance channel %s", channel->label); } return 0; } //------------------------------ void GstQtGLVideoSinkBase::set_property(GObject *object, guint prop_id, const GValue *value, GParamSpec *pspec) { GstQtVideoSinkBase *sink = GST_QT_VIDEO_SINK_BASE(object); switch (prop_id) { case PROP_CONTRAST: sink->delegate->setContrast(g_value_get_int(value)); break; case PROP_BRIGHTNESS: sink->delegate->setBrightness(g_value_get_int(value)); break; case PROP_HUE: sink->delegate->setHue(g_value_get_int(value)); break; case PROP_SATURATION: sink->delegate->setSaturation(g_value_get_int(value)); break; default: G_OBJECT_WARN_INVALID_PROPERTY_ID(object, prop_id, pspec); break; } } void GstQtGLVideoSinkBase::get_property(GObject *object, guint prop_id, GValue *value, GParamSpec *pspec) { GstQtVideoSinkBase *sink = GST_QT_VIDEO_SINK_BASE(object); switch (prop_id) { case PROP_CONTRAST: g_value_set_int(value, sink->delegate->contrast()); break; case PROP_BRIGHTNESS: g_value_set_int(value, sink->delegate->brightness()); break; case PROP_HUE: g_value_set_int(value, sink->delegate->hue()); break; case PROP_SATURATION: g_value_set_int(value, sink->delegate->saturation()); break; default: G_OBJECT_WARN_INVALID_PROPERTY_ID(object, prop_id, pspec); break; } } //------------------------------ gboolean GstQtGLVideoSinkBase::start(GstBaseSink *base) { GstQtVideoSinkBase *sink = GST_QT_VIDEO_SINK_BASE(base); //fail on purpose if the user hasn't set a context if (sink->delegate->supportedPainterTypes() == QtVideoSinkDelegate::Generic) { GST_WARNING_OBJECT(sink, "Neither GLSL nor ARB Fragment Program are supported " "for painting. Did you forget to set a gl context?"); return FALSE; } else { return TRUE; } } gboolean GstQtGLVideoSinkBase::set_caps(GstBaseSink *base, GstCaps *caps) { GstQtVideoSinkBase *sink = GST_QT_VIDEO_SINK_BASE(base); GST_LOG_OBJECT(sink, "new caps %" GST_PTR_FORMAT, caps); BufferFormat format = BufferFormat::fromCaps(caps); if (OpenGLSurfacePainter::supportedPixelFormats().contains(format.videoFormat())) { sink->delegate->setBufferFormat(format); return TRUE; } else { return FALSE; } }
set the local set_caps implementation in the vtable of GstBaseSink
qtglvideosinkbase: set the local set_caps implementation in the vtable of GstBaseSink
C++
lgpl-2.1
dejunk/gstreamer,nasserGanjali/QtGStreamer,detrout/qt-gstreamer,iperry/qt-gstreamer,knuesel/qt-gstreamer,GStreamer/qt-gstreamer,dejunk/gstreamer,dejunk/gstreamer,nasserGanjali/QtGStreamer,tswindell/qt-gstreamer,tswindell/qt-gstreamer,freedesktop-unofficial-mirror/gstreamer__qt-gstreamer,knuesel/qt-gstreamer,GStreamer/qt-gstreamer,knuesel/qt-gstreamer,detrout/qt-gstreamer,freedesktop-unofficial-mirror/gstreamer__qt-gstreamer,tswindell/qt-gstreamer,GStreamer/qt-gstreamer,nasserGanjali/QtGStreamer,detrout/qt-gstreamer,iperry/qt-gstreamer,iperry/qt-gstreamer,freedesktop-unofficial-mirror/gstreamer__qt-gstreamer
c49b096f0ae31854408a80a78e2532e530fa6760
chrome/browser/apps/app_window_browsertest.cc
chrome/browser/apps/app_window_browsertest.cc
// Copyright 2013 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 "apps/shell_window_geometry_cache.h" #include "chrome/browser/apps/app_browsertest_util.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/extensions/application_launch.h" #include "content/public/browser/notification_service.h" #include "content/public/test/test_utils.h" #include "extensions/common/constants.h" #include "extensions/common/extension.h" using apps::ShellWindowGeometryCache; // This helper class can be used to wait for changes in the shell window // geometry cache registry for a specific window in a specific extension. class GeometryCacheChangeHelper : ShellWindowGeometryCache::Observer { public: GeometryCacheChangeHelper(ShellWindowGeometryCache* cache, const std::string& extension_id, const std::string& window_id, const gfx::Rect& bounds) : cache_(cache), extension_id_(extension_id), window_id_(window_id), bounds_(bounds) { cache_->AddObserver(this); } // This method will block until the shell window geometry cache registry will // provide a bound for |window_id_| that is entirely different (as in x/y/w/h) // from the initial |bounds_|. void WaitForEntirelyChanged() { content::RunMessageLoop(); } // Implements the content::NotificationObserver interface. virtual void OnGeometryCacheChanged(const std::string& extension_id, const std::string& window_id, const gfx::Rect& bounds) OVERRIDE { if (extension_id != extension_id_ || window_id != window_id_) return; if (bounds_.x() != bounds.x() && bounds_.y() != bounds.y() && bounds_.width() != bounds.width() && bounds_.height() != bounds.height()) { cache_->RemoveObserver(this); base::MessageLoopForUI::current()->Quit(); } } private: ShellWindowGeometryCache* cache_; std::string extension_id_; std::string window_id_; gfx::Rect bounds_; }; // Helper class for tests related to the Apps Window API (chrome.app.window). class AppWindowAPI : public extensions::PlatformAppBrowserTest { public: bool RunAppWindowAPITest(const char* testName) { ExtensionTestMessageListener launched_listener("Launched", true); LoadAndLaunchPlatformApp("window_api"); if (!launched_listener.WaitUntilSatisfied()) { message_ = "Did not get the 'Launched' message."; return false; } ResultCatcher catcher; launched_listener.Reply(testName); if (!catcher.GetNextResult()) { message_ = catcher.message(); return false; } return true; } }; // These tests are flaky after https://codereview.chromium.org/57433010/. // See http://crbug.com/319613. IN_PROC_BROWSER_TEST_F(AppWindowAPI, DISABLED_TestCreate) { ASSERT_TRUE(RunAppWindowAPITest("testCreate")) << message_; } IN_PROC_BROWSER_TEST_F(AppWindowAPI, DISABLED_TestSingleton) { ASSERT_TRUE(RunAppWindowAPITest("testSingleton")) << message_; } IN_PROC_BROWSER_TEST_F(AppWindowAPI, DISABLED_TestBounds) { ASSERT_TRUE(RunAppWindowAPITest("testBounds")) << message_; } IN_PROC_BROWSER_TEST_F(AppWindowAPI, DISABLED_TestCloseEvent) { ASSERT_TRUE(RunAppWindowAPITest("testCloseEvent")) << message_; } IN_PROC_BROWSER_TEST_F(AppWindowAPI, DISABLED_TestMaximize) { ASSERT_TRUE(RunAppWindowAPITest("testMaximize")) << message_; } IN_PROC_BROWSER_TEST_F(AppWindowAPI, DISABLED_TestRestore) { ASSERT_TRUE(RunAppWindowAPITest("testRestore")) << message_; } IN_PROC_BROWSER_TEST_F(AppWindowAPI, DISABLED_TestRestoreAfterClose) { ASSERT_TRUE(RunAppWindowAPITest("testRestoreAfterClose")) << message_; } // Flaky failures on mac_rel, see http://crbug.com/324915 #if defined(OS_MACOSX) #define MAYBE_TestRestoreGeometryCacheChange DISABLED_TestRestoreGeometryCacheChange #else #define MAYBE_TestRestoreGeometryCacheChange TestRestoreGeometryCacheChange #endif IN_PROC_BROWSER_TEST_F(AppWindowAPI, MAYBE_TestRestoreGeometryCacheChange) { // This test is similar to the other AppWindowAPI tests except that at some // point the app will send a 'ListenGeometryChange' message at which point the // test will check if the geometry cache entry for the test window has // changed. When the change happens, the test will let the app know so it can // continue running. ExtensionTestMessageListener launched_listener("Launched", true); content::WindowedNotificationObserver app_loaded_observer( content::NOTIFICATION_LOAD_COMPLETED_MAIN_FRAME, content::NotificationService::AllSources()); const extensions::Extension* extension = LoadExtension( test_data_dir_.AppendASCII("platform_apps").AppendASCII("window_api")); EXPECT_TRUE(extension); OpenApplication(AppLaunchParams( browser()->profile(), extension, extensions::LAUNCH_NONE, NEW_WINDOW)); ExtensionTestMessageListener geometry_listener("ListenGeometryChange", true); ASSERT_TRUE(launched_listener.WaitUntilSatisfied()); launched_listener.Reply("testRestoreAfterGeometryCacheChange"); ASSERT_TRUE(geometry_listener.WaitUntilSatisfied()); GeometryCacheChangeHelper geo_change_helper( ShellWindowGeometryCache::Get(browser()->profile()), extension->id(), // The next line has information that has to stay in sync with the app. "test-ps", gfx::Rect(200, 200, 200, 200)); // This call will block until the shell window geometry cache will be changed. geo_change_helper.WaitForEntirelyChanged(); ResultCatcher catcher; geometry_listener.Reply(""); ASSERT_TRUE(catcher.GetNextResult()); } IN_PROC_BROWSER_TEST_F(AppWindowAPI, DISABLED_TestSizeConstraints) { ASSERT_TRUE(RunAppWindowAPITest("testSizeConstraints")) << message_; }
// Copyright 2013 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 "apps/shell_window_geometry_cache.h" #include "chrome/browser/apps/app_browsertest_util.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/extensions/application_launch.h" #include "content/public/browser/notification_service.h" #include "content/public/test/test_utils.h" #include "extensions/common/constants.h" #include "extensions/common/extension.h" using apps::ShellWindowGeometryCache; // This helper class can be used to wait for changes in the shell window // geometry cache registry for a specific window in a specific extension. class GeometryCacheChangeHelper : ShellWindowGeometryCache::Observer { public: GeometryCacheChangeHelper(ShellWindowGeometryCache* cache, const std::string& extension_id, const std::string& window_id, const gfx::Rect& bounds) : cache_(cache), extension_id_(extension_id), window_id_(window_id), bounds_(bounds) { cache_->AddObserver(this); } // This method will block until the shell window geometry cache registry will // provide a bound for |window_id_| that is entirely different (as in x/y/w/h) // from the initial |bounds_|. void WaitForEntirelyChanged() { content::RunMessageLoop(); } // Implements the content::NotificationObserver interface. virtual void OnGeometryCacheChanged(const std::string& extension_id, const std::string& window_id, const gfx::Rect& bounds) OVERRIDE { if (extension_id != extension_id_ || window_id != window_id_) return; if (bounds_.x() != bounds.x() && bounds_.y() != bounds.y() && bounds_.width() != bounds.width() && bounds_.height() != bounds.height()) { cache_->RemoveObserver(this); base::MessageLoopForUI::current()->Quit(); } } private: ShellWindowGeometryCache* cache_; std::string extension_id_; std::string window_id_; gfx::Rect bounds_; }; // Helper class for tests related to the Apps Window API (chrome.app.window). class AppWindowAPI : public extensions::PlatformAppBrowserTest { public: bool RunAppWindowAPITest(const char* testName) { ExtensionTestMessageListener launched_listener("Launched", true); LoadAndLaunchPlatformApp("window_api"); if (!launched_listener.WaitUntilSatisfied()) { message_ = "Did not get the 'Launched' message."; return false; } ResultCatcher catcher; launched_listener.Reply(testName); if (!catcher.GetNextResult()) { message_ = catcher.message(); return false; } return true; } }; // These tests are flaky after https://codereview.chromium.org/57433010/. // See http://crbug.com/319613. IN_PROC_BROWSER_TEST_F(AppWindowAPI, DISABLED_TestCreate) { ASSERT_TRUE(RunAppWindowAPITest("testCreate")) << message_; } IN_PROC_BROWSER_TEST_F(AppWindowAPI, DISABLED_TestSingleton) { ASSERT_TRUE(RunAppWindowAPITest("testSingleton")) << message_; } IN_PROC_BROWSER_TEST_F(AppWindowAPI, DISABLED_TestBounds) { ASSERT_TRUE(RunAppWindowAPITest("testBounds")) << message_; } IN_PROC_BROWSER_TEST_F(AppWindowAPI, DISABLED_TestCloseEvent) { ASSERT_TRUE(RunAppWindowAPITest("testCloseEvent")) << message_; } IN_PROC_BROWSER_TEST_F(AppWindowAPI, DISABLED_TestMaximize) { ASSERT_TRUE(RunAppWindowAPITest("testMaximize")) << message_; } IN_PROC_BROWSER_TEST_F(AppWindowAPI, DISABLED_TestRestore) { ASSERT_TRUE(RunAppWindowAPITest("testRestore")) << message_; } IN_PROC_BROWSER_TEST_F(AppWindowAPI, DISABLED_TestRestoreAfterClose) { ASSERT_TRUE(RunAppWindowAPITest("testRestoreAfterClose")) << message_; } // Flaky failures on mac_rel and WinXP, see http://crbug.com/324915. IN_PROC_BROWSER_TEST_F(AppWindowAPI, DISABLED_TestRestoreGeometryCacheChange) { // This test is similar to the other AppWindowAPI tests except that at some // point the app will send a 'ListenGeometryChange' message at which point the // test will check if the geometry cache entry for the test window has // changed. When the change happens, the test will let the app know so it can // continue running. ExtensionTestMessageListener launched_listener("Launched", true); content::WindowedNotificationObserver app_loaded_observer( content::NOTIFICATION_LOAD_COMPLETED_MAIN_FRAME, content::NotificationService::AllSources()); const extensions::Extension* extension = LoadExtension( test_data_dir_.AppendASCII("platform_apps").AppendASCII("window_api")); EXPECT_TRUE(extension); OpenApplication(AppLaunchParams( browser()->profile(), extension, extensions::LAUNCH_NONE, NEW_WINDOW)); ExtensionTestMessageListener geometry_listener("ListenGeometryChange", true); ASSERT_TRUE(launched_listener.WaitUntilSatisfied()); launched_listener.Reply("testRestoreAfterGeometryCacheChange"); ASSERT_TRUE(geometry_listener.WaitUntilSatisfied()); GeometryCacheChangeHelper geo_change_helper( ShellWindowGeometryCache::Get(browser()->profile()), extension->id(), // The next line has information that has to stay in sync with the app. "test-ps", gfx::Rect(200, 200, 200, 200)); // This call will block until the shell window geometry cache will be changed. geo_change_helper.WaitForEntirelyChanged(); ResultCatcher catcher; geometry_listener.Reply(""); ASSERT_TRUE(catcher.GetNextResult()); } IN_PROC_BROWSER_TEST_F(AppWindowAPI, DISABLED_TestSizeConstraints) { ASSERT_TRUE(RunAppWindowAPITest("testSizeConstraints")) << message_; }
Disable TestRestoreGeometryCacheChange on all platforms, as it also flakes on WinXP.
Disable TestRestoreGeometryCacheChange on all platforms, as it also flakes on WinXP. BUG=324915 [email protected] Review URL: https://codereview.chromium.org/104333002 git-svn-id: de016e52bd170d2d4f2344f9bf92d50478b649e0@238661 0039d316-1c4b-4281-b951-d872f2087c98
C++
bsd-3-clause
patrickm/chromium.src,dednal/chromium.src,Jonekee/chromium.src,ltilve/chromium,M4sse/chromium.src,littlstar/chromium.src,Jonekee/chromium.src,mohamed--abdel-maksoud/chromium.src,ondra-novak/chromium.src,ChromiumWebApps/chromium,bright-sparks/chromium-spacewalk,hgl888/chromium-crosswalk,Just-D/chromium-1,dednal/chromium.src,hgl888/chromium-crosswalk,Chilledheart/chromium,Jonekee/chromium.src,PeterWangIntel/chromium-crosswalk,ltilve/chromium,mohamed--abdel-maksoud/chromium.src,jaruba/chromium.src,markYoungH/chromium.src,ondra-novak/chromium.src,crosswalk-project/chromium-crosswalk-efl,markYoungH/chromium.src,Pluto-tv/chromium-crosswalk,fujunwei/chromium-crosswalk,krieger-od/nwjs_chromium.src,Pluto-tv/chromium-crosswalk,crosswalk-project/chromium-crosswalk-efl,axinging/chromium-crosswalk,hgl888/chromium-crosswalk-efl,hgl888/chromium-crosswalk-efl,ChromiumWebApps/chromium,ltilve/chromium,dushu1203/chromium.src,dushu1203/chromium.src,axinging/chromium-crosswalk,bright-sparks/chromium-spacewalk,PeterWangIntel/chromium-crosswalk,TheTypoMaster/chromium-crosswalk,ltilve/chromium,markYoungH/chromium.src,dushu1203/chromium.src,Pluto-tv/chromium-crosswalk,Jonekee/chromium.src,Jonekee/chromium.src,Fireblend/chromium-crosswalk,markYoungH/chromium.src,Jonekee/chromium.src,Fireblend/chromium-crosswalk,mohamed--abdel-maksoud/chromium.src,patrickm/chromium.src,axinging/chromium-crosswalk,M4sse/chromium.src,Chilledheart/chromium,ChromiumWebApps/chromium,ChromiumWebApps/chromium,ChromiumWebApps/chromium,Chilledheart/chromium,chuan9/chromium-crosswalk,patrickm/chromium.src,krieger-od/nwjs_chromium.src,hgl888/chromium-crosswalk-efl,patrickm/chromium.src,markYoungH/chromium.src,ChromiumWebApps/chromium,ondra-novak/chromium.src,hgl888/chromium-crosswalk-efl,crosswalk-project/chromium-crosswalk-efl,patrickm/chromium.src,Jonekee/chromium.src,ChromiumWebApps/chromium,chuan9/chromium-crosswalk,ondra-novak/chromium.src,M4sse/chromium.src,PeterWangIntel/chromium-crosswalk,markYoungH/chromium.src,ltilve/chromium,chuan9/chromium-crosswalk,littlstar/chromium.src,hgl888/chromium-crosswalk,dednal/chromium.src,Pluto-tv/chromium-crosswalk,Pluto-tv/chromium-crosswalk,PeterWangIntel/chromium-crosswalk,chuan9/chromium-crosswalk,dushu1203/chromium.src,Pluto-tv/chromium-crosswalk,M4sse/chromium.src,dushu1203/chromium.src,bright-sparks/chromium-spacewalk,ChromiumWebApps/chromium,M4sse/chromium.src,fujunwei/chromium-crosswalk,chuan9/chromium-crosswalk,dushu1203/chromium.src,Just-D/chromium-1,jaruba/chromium.src,bright-sparks/chromium-spacewalk,PeterWangIntel/chromium-crosswalk,markYoungH/chromium.src,Fireblend/chromium-crosswalk,dushu1203/chromium.src,mohamed--abdel-maksoud/chromium.src,krieger-od/nwjs_chromium.src,anirudhSK/chromium,krieger-od/nwjs_chromium.src,chuan9/chromium-crosswalk,littlstar/chromium.src,Jonekee/chromium.src,dushu1203/chromium.src,Chilledheart/chromium,axinging/chromium-crosswalk,fujunwei/chromium-crosswalk,krieger-od/nwjs_chromium.src,littlstar/chromium.src,jaruba/chromium.src,jaruba/chromium.src,dednal/chromium.src,markYoungH/chromium.src,M4sse/chromium.src,anirudhSK/chromium,markYoungH/chromium.src,mohamed--abdel-maksoud/chromium.src,hgl888/chromium-crosswalk-efl,Just-D/chromium-1,Jonekee/chromium.src,ltilve/chromium,Just-D/chromium-1,fujunwei/chromium-crosswalk,TheTypoMaster/chromium-crosswalk,hgl888/chromium-crosswalk-efl,ltilve/chromium,ltilve/chromium,chuan9/chromium-crosswalk,PeterWangIntel/chromium-crosswalk,axinging/chromium-crosswalk,mohamed--abdel-maksoud/chromium.src,Chilledheart/chromium,TheTypoMaster/chromium-crosswalk,anirudhSK/chromium,anirudhSK/chromium,PeterWangIntel/chromium-crosswalk,fujunwei/chromium-crosswalk,Pluto-tv/chromium-crosswalk,anirudhSK/chromium,Fireblend/chromium-crosswalk,anirudhSK/chromium,jaruba/chromium.src,TheTypoMaster/chromium-crosswalk,Fireblend/chromium-crosswalk,M4sse/chromium.src,Just-D/chromium-1,Chilledheart/chromium,littlstar/chromium.src,ChromiumWebApps/chromium,hgl888/chromium-crosswalk,ondra-novak/chromium.src,Just-D/chromium-1,ondra-novak/chromium.src,bright-sparks/chromium-spacewalk,chuan9/chromium-crosswalk,jaruba/chromium.src,axinging/chromium-crosswalk,jaruba/chromium.src,littlstar/chromium.src,TheTypoMaster/chromium-crosswalk,patrickm/chromium.src,bright-sparks/chromium-spacewalk,crosswalk-project/chromium-crosswalk-efl,krieger-od/nwjs_chromium.src,anirudhSK/chromium,hgl888/chromium-crosswalk-efl,fujunwei/chromium-crosswalk,crosswalk-project/chromium-crosswalk-efl,Just-D/chromium-1,anirudhSK/chromium,krieger-od/nwjs_chromium.src,Pluto-tv/chromium-crosswalk,mohamed--abdel-maksoud/chromium.src,littlstar/chromium.src,anirudhSK/chromium,crosswalk-project/chromium-crosswalk-efl,jaruba/chromium.src,jaruba/chromium.src,ChromiumWebApps/chromium,bright-sparks/chromium-spacewalk,Chilledheart/chromium,littlstar/chromium.src,chuan9/chromium-crosswalk,PeterWangIntel/chromium-crosswalk,crosswalk-project/chromium-crosswalk-efl,hgl888/chromium-crosswalk-efl,ondra-novak/chromium.src,jaruba/chromium.src,markYoungH/chromium.src,mohamed--abdel-maksoud/chromium.src,Just-D/chromium-1,Chilledheart/chromium,dednal/chromium.src,dednal/chromium.src,patrickm/chromium.src,mohamed--abdel-maksoud/chromium.src,mohamed--abdel-maksoud/chromium.src,anirudhSK/chromium,axinging/chromium-crosswalk,dushu1203/chromium.src,patrickm/chromium.src,TheTypoMaster/chromium-crosswalk,jaruba/chromium.src,bright-sparks/chromium-spacewalk,dushu1203/chromium.src,TheTypoMaster/chromium-crosswalk,anirudhSK/chromium,hgl888/chromium-crosswalk,krieger-od/nwjs_chromium.src,markYoungH/chromium.src,dednal/chromium.src,krieger-od/nwjs_chromium.src,Fireblend/chromium-crosswalk,ChromiumWebApps/chromium,Pluto-tv/chromium-crosswalk,Jonekee/chromium.src,fujunwei/chromium-crosswalk,dednal/chromium.src,ChromiumWebApps/chromium,hgl888/chromium-crosswalk,Chilledheart/chromium,PeterWangIntel/chromium-crosswalk,hgl888/chromium-crosswalk,M4sse/chromium.src,hgl888/chromium-crosswalk-efl,fujunwei/chromium-crosswalk,hgl888/chromium-crosswalk,axinging/chromium-crosswalk,mohamed--abdel-maksoud/chromium.src,Just-D/chromium-1,M4sse/chromium.src,Fireblend/chromium-crosswalk,TheTypoMaster/chromium-crosswalk,Fireblend/chromium-crosswalk,ondra-novak/chromium.src,M4sse/chromium.src,dushu1203/chromium.src,patrickm/chromium.src,fujunwei/chromium-crosswalk,Fireblend/chromium-crosswalk,axinging/chromium-crosswalk,crosswalk-project/chromium-crosswalk-efl,ondra-novak/chromium.src,Jonekee/chromium.src,dednal/chromium.src,hgl888/chromium-crosswalk,dednal/chromium.src,anirudhSK/chromium,TheTypoMaster/chromium-crosswalk,hgl888/chromium-crosswalk-efl,ltilve/chromium,krieger-od/nwjs_chromium.src,dednal/chromium.src,crosswalk-project/chromium-crosswalk-efl,M4sse/chromium.src,krieger-od/nwjs_chromium.src,bright-sparks/chromium-spacewalk,axinging/chromium-crosswalk,axinging/chromium-crosswalk
c6680adec0416606340552e7974c0d0015cd3156
chrome/browser/extensions/all_urls_apitest.cc
chrome/browser/extensions/all_urls_apitest.cc
// Copyright (c) 2010 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chrome/browser/extensions/extension_apitest.h" #include "chrome/browser/extensions/extensions_service.h" #include "chrome/browser/extensions/extension_test_message_listener.h" #include "chrome/browser/profile.h" #include "chrome/browser/ui/browser.h" #include "chrome/common/extensions/extension.h" #include "chrome/test/ui_test_utils.h" const std::string kAllUrlsTarget = "files/extensions/api_test/all_urls/index.html"; typedef ExtensionApiTest AllUrlsApiTest; // Note: This test is flaky, but is actively being worked on. // See http://crbug.com/57694. Finnur is adding traces to figure out where the // problem lies and needs to check in these traces because the problem doesn't // repro locally (nor on the try bots). IN_PROC_BROWSER_TEST_F(AllUrlsApiTest, WhitelistedExtension) { // First setup the two extensions. FilePath extension_dir1 = test_data_dir_.AppendASCII("all_urls") .AppendASCII("content_script"); FilePath extension_dir2 = test_data_dir_.AppendASCII("all_urls") .AppendASCII("execute_script"); // Then add the two extensions to the whitelist. Extension::ScriptingWhitelist whitelist; whitelist.push_back(Extension::GenerateIdForPath(extension_dir1)); whitelist.push_back(Extension::GenerateIdForPath(extension_dir2)); Extension::SetScriptingWhitelist(whitelist); // Then load extensions. ExtensionsService* service = browser()->profile()->GetExtensionsService(); const size_t size_before = service->extensions()->size(); printf("***** LoadExtension1 called \n"); ASSERT_TRUE(LoadExtension(extension_dir1)); printf("***** LoadExtension2 called \n"); ASSERT_TRUE(LoadExtension(extension_dir2)); printf("***** LoadExtensions done \n"); EXPECT_EQ(size_before + 2, service->extensions()->size()); std::string url; // Now verify we run content scripts on chrome://newtab/. url = "chrome://newtab/"; printf("***** %s\n", url.c_str()); ExtensionTestMessageListener listener1a("content script: " + url, false); ExtensionTestMessageListener listener1b("execute: " + url, false); ui_test_utils::NavigateToURL(browser(), GURL(url)); printf("***** Wait 1a\n"); ASSERT_TRUE(listener1a.WaitUntilSatisfied()); printf("***** Wait 1b\n"); ASSERT_TRUE(listener1b.WaitUntilSatisfied()); // Now verify data: urls. url = "data:text/html;charset=utf-8,<html>asdf</html>"; printf("***** %s\n", url.c_str()); ExtensionTestMessageListener listener2a("content script: " + url, false); ExtensionTestMessageListener listener2b("execute: " + url, false); ui_test_utils::NavigateToURL(browser(), GURL(url)); printf("***** Wait 2a\n"); ASSERT_TRUE(listener2a.WaitUntilSatisfied()); printf("***** Wait 2b\n"); ASSERT_TRUE(listener2b.WaitUntilSatisfied()); // Now verify about:version. url = "about:version"; printf("***** %s\n", url.c_str()); ExtensionTestMessageListener listener3a("content script: " + url, false); ExtensionTestMessageListener listener3b("execute: " + url, false); ui_test_utils::NavigateToURL(browser(), GURL(url)); printf("***** Wait 3a\n"); ASSERT_TRUE(listener3a.WaitUntilSatisfied()); printf("***** Wait 3b\n"); ASSERT_TRUE(listener3b.WaitUntilSatisfied()); // Now verify about:blank. url = "about:blank"; printf("***** %s\n", url.c_str()); ExtensionTestMessageListener listener4a("content script: " + url, false); ExtensionTestMessageListener listener4b("execute: " + url, false); ui_test_utils::NavigateToURL(browser(), GURL(url)); printf("***** Wait 4a\n"); ASSERT_TRUE(listener4a.WaitUntilSatisfied()); printf("***** Wait 4b\n"); ASSERT_TRUE(listener4b.WaitUntilSatisfied()); // Now verify we can script a regular http page. ASSERT_TRUE(test_server()->Start()); GURL page_url = test_server()->GetURL(kAllUrlsTarget); printf("***** %s\n", page_url.spec().c_str()); ExtensionTestMessageListener listener5a("content script: " + page_url.spec(), false); ExtensionTestMessageListener listener5b("execute: " + page_url.spec(), false); ui_test_utils::NavigateToURL(browser(), page_url); printf("***** Wait 5a\n"); ASSERT_TRUE(listener5a.WaitUntilSatisfied()); printf("***** Wait 5b\n"); ASSERT_TRUE(listener5b.WaitUntilSatisfied()); printf("***** DONE!\n"); } // Test that an extension NOT whitelisted for scripting can ask for <all_urls> // and run scripts on non-restricted all pages. IN_PROC_BROWSER_TEST_F(AllUrlsApiTest, RegularExtensions) { // First load the two extension. FilePath extension_dir1 = test_data_dir_.AppendASCII("all_urls") .AppendASCII("content_script"); FilePath extension_dir2 = test_data_dir_.AppendASCII("all_urls") .AppendASCII("execute_script"); ExtensionsService* service = browser()->profile()->GetExtensionsService(); const size_t size_before = service->extensions()->size(); ASSERT_TRUE(LoadExtension(extension_dir1)); ASSERT_TRUE(LoadExtension(extension_dir2)); EXPECT_EQ(size_before + 2, service->extensions()->size()); // Now verify we can script a regular http page. ASSERT_TRUE(test_server()->Start()); GURL page_url = test_server()->GetURL(kAllUrlsTarget); ExtensionTestMessageListener listener1a("content script: " + page_url.spec(), false); ExtensionTestMessageListener listener1b("execute: " + page_url.spec(), false); ui_test_utils::NavigateToURL(browser(), page_url); ASSERT_TRUE(listener1a.WaitUntilSatisfied()); ASSERT_TRUE(listener1b.WaitUntilSatisfied()); }
// 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/extensions/extension_apitest.h" #include "chrome/browser/extensions/extensions_service.h" #include "chrome/browser/extensions/extension_test_message_listener.h" #include "chrome/browser/profile.h" #include "chrome/browser/ui/browser.h" #include "chrome/common/extensions/extension.h" #include "chrome/test/ui_test_utils.h" const std::string kAllUrlsTarget = "files/extensions/api_test/all_urls/index.html"; typedef ExtensionApiTest AllUrlsApiTest; namespace { void Checkpoint(const char* message, const base::TimeTicks& start_time) { LOG(INFO) << message << " : " << (base::TimeTicks::Now() - start_time).InMilliseconds() << " ms" << std::flush; } } // namespace IN_PROC_BROWSER_TEST_F(AllUrlsApiTest, WhitelistedExtension) { base::TimeTicks start_time = base::TimeTicks::Now(); Checkpoint("Setting up extensions", start_time); // First setup the two extensions. FilePath extension_dir1 = test_data_dir_.AppendASCII("all_urls") .AppendASCII("content_script"); FilePath extension_dir2 = test_data_dir_.AppendASCII("all_urls") .AppendASCII("execute_script"); // Then add the two extensions to the whitelist. Checkpoint("Setting up whitelist", start_time); Extension::ScriptingWhitelist whitelist; whitelist.push_back(Extension::GenerateIdForPath(extension_dir1)); whitelist.push_back(Extension::GenerateIdForPath(extension_dir2)); Extension::SetScriptingWhitelist(whitelist); // Then load extensions. Checkpoint("LoadExtension1", start_time); ExtensionsService* service = browser()->profile()->GetExtensionsService(); const size_t size_before = service->extensions()->size(); ASSERT_TRUE(LoadExtension(extension_dir1)); Checkpoint("LoadExtension2", start_time); ASSERT_TRUE(LoadExtension(extension_dir2)); EXPECT_EQ(size_before + 2, service->extensions()->size()); std::string url; // Now verify we run content scripts on chrome://newtab/. Checkpoint("Verify content scripts", start_time); url = "chrome://newtab/"; ExtensionTestMessageListener listener1a("content script: " + url, false); ExtensionTestMessageListener listener1b("execute: " + url, false); ui_test_utils::NavigateToURL(browser(), GURL(url)); Checkpoint("Wait for 1a", start_time); ASSERT_TRUE(listener1a.WaitUntilSatisfied()); Checkpoint("Wait for 1b", start_time); ASSERT_TRUE(listener1b.WaitUntilSatisfied()); // Now verify data: urls. Checkpoint("Verify data:urls", start_time); url = "data:text/html;charset=utf-8,<html>asdf</html>"; ExtensionTestMessageListener listener2a("content script: " + url, false); ExtensionTestMessageListener listener2b("execute: " + url, false); ui_test_utils::NavigateToURL(browser(), GURL(url)); Checkpoint("Wait for 2a", start_time); ASSERT_TRUE(listener2a.WaitUntilSatisfied()); Checkpoint("Wait for 2b", start_time); ASSERT_TRUE(listener2b.WaitUntilSatisfied()); // Now verify about:version. Checkpoint("Verify about:version", start_time); url = "about:version"; ExtensionTestMessageListener listener3a("content script: " + url, false); ExtensionTestMessageListener listener3b("execute: " + url, false); ui_test_utils::NavigateToURL(browser(), GURL(url)); Checkpoint("Wait for 3a", start_time); ASSERT_TRUE(listener3a.WaitUntilSatisfied()); Checkpoint("Wait for 3b", start_time); ASSERT_TRUE(listener3b.WaitUntilSatisfied()); // Now verify about:blank. Checkpoint("Verify about:blank", start_time); url = "about:blank"; ExtensionTestMessageListener listener4a("content script: " + url, false); ExtensionTestMessageListener listener4b("execute: " + url, false); ui_test_utils::NavigateToURL(browser(), GURL(url)); Checkpoint("Wait for 4a", start_time); ASSERT_TRUE(listener4a.WaitUntilSatisfied()); Checkpoint("Wait for 4b", start_time); ASSERT_TRUE(listener4b.WaitUntilSatisfied()); // Now verify we can script a regular http page. Checkpoint("Verify regular http page", start_time); ASSERT_TRUE(test_server()->Start()); GURL page_url = test_server()->GetURL(kAllUrlsTarget); ExtensionTestMessageListener listener5a("content script: " + page_url.spec(), false); ExtensionTestMessageListener listener5b("execute: " + page_url.spec(), false); ui_test_utils::NavigateToURL(browser(), page_url); Checkpoint("Wait for 5a", start_time); ASSERT_TRUE(listener5a.WaitUntilSatisfied()); Checkpoint("Wait for 5ba", start_time); ASSERT_TRUE(listener5b.WaitUntilSatisfied()); Checkpoint("Test complete", start_time); } // Test that an extension NOT whitelisted for scripting can ask for <all_urls> // and run scripts on non-restricted all pages. IN_PROC_BROWSER_TEST_F(AllUrlsApiTest, RegularExtensions) { // First load the two extension. FilePath extension_dir1 = test_data_dir_.AppendASCII("all_urls") .AppendASCII("content_script"); FilePath extension_dir2 = test_data_dir_.AppendASCII("all_urls") .AppendASCII("execute_script"); ExtensionsService* service = browser()->profile()->GetExtensionsService(); const size_t size_before = service->extensions()->size(); ASSERT_TRUE(LoadExtension(extension_dir1)); ASSERT_TRUE(LoadExtension(extension_dir2)); EXPECT_EQ(size_before + 2, service->extensions()->size()); // Now verify we can script a regular http page. ASSERT_TRUE(test_server()->Start()); GURL page_url = test_server()->GetURL(kAllUrlsTarget); ExtensionTestMessageListener listener1a("content script: " + page_url.spec(), false); ExtensionTestMessageListener listener1b("execute: " + page_url.spec(), false); ui_test_utils::NavigateToURL(browser(), page_url); ASSERT_TRUE(listener1a.WaitUntilSatisfied()); ASSERT_TRUE(listener1b.WaitUntilSatisfied()); }
Convert the traces in the WhitelistedExtension test.
Convert the traces in the WhitelistedExtension test. The test has been enabled for a long time and does not currently even appear on the Flakiness dashboard, nor can I find a failure on the try servers. The failure mentioned in the bug does not show the traces I added, so I'm converting the traces to another form, in case we see flakiness again. BUG=57694 TEST=Changing a test. Review URL: http://codereview.chromium.org/5255004 git-svn-id: dd90618784b6a4b323ea0c23a071cb1c9e6f2ac7@67100 4ff67af0-8c30-449e-8e8b-ad334ec8d88c
C++
bsd-3-clause
wistoch/meego-app-browser,wistoch/meego-app-browser,wistoch/meego-app-browser,wistoch/meego-app-browser,wistoch/meego-app-browser,wistoch/meego-app-browser,wistoch/meego-app-browser,wistoch/meego-app-browser,wistoch/meego-app-browser,wistoch/meego-app-browser
94182ddde75661e74cd0c7f8de492757e3065c7e
chrome/browser/instant/instant_field_trial.cc
chrome/browser/instant/instant_field_trial.cc
// 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/instant/instant_field_trial.h" #include "base/command_line.h" #include "base/metrics/field_trial.h" #include "chrome/browser/metrics/metrics_service.h" #include "chrome/browser/prefs/pref_service.h" #include "chrome/browser/profiles/profile.h" #include "chrome/common/chrome_switches.h" #include "chrome/common/pref_names.h" namespace { // Field trial IDs of the control and experiment groups. Though they are not // literally "const", they are set only once, in Activate() below. See the .h // file for what these groups represent. int g_instant_experiment_a = 0; int g_instant_experiment_b = 0; int g_hidden_experiment_a = 0; int g_hidden_experiment_b = 0; int g_silent_experiment_a = 0; int g_silent_experiment_b = 0; int g_suggest_experiment_a = 0; int g_suggest_experiment_b = 0; int g_uma_control_a = 0; int g_uma_control_b = 0; int g_all_control_a = 0; int g_all_control_b = 0; } // static void InstantFieldTrial::Activate() { scoped_refptr<base::FieldTrial> trial( new base::FieldTrial("Instant", 1000, "Inactive", 2012, 7, 1)); // Try to give the user a consistent experience, if possible. if (base::FieldTrialList::IsOneTimeRandomizationEnabled()) trial->UseOneTimeRandomization(); // Each group is of total size 10% (5% each for the _a and _b variants). g_instant_experiment_a = trial->AppendGroup("InstantExperimentA", 50); g_instant_experiment_b = trial->AppendGroup("InstantExperimentB", 50); g_hidden_experiment_a = trial->AppendGroup("HiddenExperimentA", 50); g_hidden_experiment_b = trial->AppendGroup("HiddenExperimentB", 50); g_silent_experiment_a = trial->AppendGroup("SilentExperimentA", 50); g_silent_experiment_b = trial->AppendGroup("SilentExperimentB", 50); g_suggest_experiment_a = trial->AppendGroup("SuggestExperimentA", 50); g_suggest_experiment_b = trial->AppendGroup("SuggestExperimentB", 50); g_uma_control_a = trial->AppendGroup("UmaControlA", 50); g_uma_control_b = trial->AppendGroup("UmaControlB", 50); g_all_control_a = trial->AppendGroup("AllControlA", 50); g_all_control_b = trial->AppendGroup("AllControlB", 50); } // static InstantFieldTrial::Group InstantFieldTrial::GetGroup(Profile* profile) { CommandLine* command_line = CommandLine::ForCurrentProcess(); if (command_line->HasSwitch(switches::kInstantFieldTrial)) { std::string switch_value = command_line->GetSwitchValueASCII(switches::kInstantFieldTrial); if (switch_value == switches::kInstantFieldTrialInstant) return INSTANT_EXPERIMENT_A; else if (switch_value == switches::kInstantFieldTrialHidden) return HIDDEN_EXPERIMENT_A; else if (switch_value == switches::kInstantFieldTrialSilent) return SILENT_EXPERIMENT_A; else if (switch_value == switches::kInstantFieldTrialSuggest) return SUGGEST_EXPERIMENT_A; else return INACTIVE; } const int group = base::FieldTrialList::FindValue("Instant"); if (group == base::FieldTrial::kNotFinalized || group == base::FieldTrial::kDefaultGroupNumber) { return INACTIVE; } const PrefService* prefs = profile ? profile->GetPrefs() : NULL; if (!prefs || prefs->GetBoolean(prefs::kInstantEnabledOnce) || prefs->IsManagedPreference(prefs::kInstantEnabled)) { return INACTIVE; } // First, deal with the groups that don't require UMA opt-in. if (group == g_silent_experiment_a) return SILENT_EXPERIMENT_A; if (group == g_silent_experiment_b) return SILENT_EXPERIMENT_B; if (group == g_all_control_a) return ALL_CONTROL_A; if (group == g_all_control_b) return ALL_CONTROL_B; // All other groups require UMA and suggest, else bounce back to INACTIVE. if (profile->IsOffTheRecord() || !MetricsServiceHelper::IsMetricsReportingEnabled() || !prefs->GetBoolean(prefs::kSearchSuggestEnabled)) { return INACTIVE; } if (group == g_instant_experiment_a) return INSTANT_EXPERIMENT_A; if (group == g_instant_experiment_b) return INSTANT_EXPERIMENT_B; if (group == g_hidden_experiment_a) return HIDDEN_EXPERIMENT_A; if (group == g_hidden_experiment_b) return HIDDEN_EXPERIMENT_B; if (group == g_suggest_experiment_a) return SUGGEST_EXPERIMENT_A; if (group == g_suggest_experiment_b) return SUGGEST_EXPERIMENT_B; if (group == g_uma_control_a) return UMA_CONTROL_A; if (group == g_uma_control_b) return UMA_CONTROL_B; NOTREACHED(); return INACTIVE; } // static bool InstantFieldTrial::IsInstantExperiment(Profile* profile) { Group group = GetGroup(profile); return group == INSTANT_EXPERIMENT_A || group == INSTANT_EXPERIMENT_B || group == HIDDEN_EXPERIMENT_A || group == HIDDEN_EXPERIMENT_B || group == SILENT_EXPERIMENT_A || group == SILENT_EXPERIMENT_B || group == SUGGEST_EXPERIMENT_A || group == SUGGEST_EXPERIMENT_B; } // static bool InstantFieldTrial::IsHiddenExperiment(Profile* profile) { Group group = GetGroup(profile); return group == HIDDEN_EXPERIMENT_A || group == HIDDEN_EXPERIMENT_B || group == SILENT_EXPERIMENT_A || group == SILENT_EXPERIMENT_B || group == SUGGEST_EXPERIMENT_A || group == SUGGEST_EXPERIMENT_B; } // static bool InstantFieldTrial::IsSilentExperiment(Profile* profile) { Group group = GetGroup(profile); return group == SILENT_EXPERIMENT_A || group == SILENT_EXPERIMENT_B; } // static std::string InstantFieldTrial::GetGroupName(Profile* profile) { switch (GetGroup(profile)) { case INACTIVE: return std::string(); case INSTANT_EXPERIMENT_A: return "_InstantExperimentA"; case INSTANT_EXPERIMENT_B: return "_InstantExperimentB"; case HIDDEN_EXPERIMENT_A: return "_HiddenExperimentA"; case HIDDEN_EXPERIMENT_B: return "_HiddenExperimentB"; case SILENT_EXPERIMENT_A: return "_SilentExperimentA"; case SILENT_EXPERIMENT_B: return "_SilentExperimentB"; case SUGGEST_EXPERIMENT_A: return "_SuggestExperimentA"; case SUGGEST_EXPERIMENT_B: return "_SuggestExperimentB"; case UMA_CONTROL_A: return "_UmaControlA"; case UMA_CONTROL_B: return "_UmaControlB"; case ALL_CONTROL_A: return "_AllControlA"; case ALL_CONTROL_B: return "_AllControlB"; } NOTREACHED(); return std::string(); } // static std::string InstantFieldTrial::GetGroupAsUrlParam(Profile* profile) { switch (GetGroup(profile)) { case INACTIVE: return std::string(); case INSTANT_EXPERIMENT_A: return "ix=iea&"; case INSTANT_EXPERIMENT_B: return "ix=ieb&"; case HIDDEN_EXPERIMENT_A: return "ix=hea&"; case HIDDEN_EXPERIMENT_B: return "ix=heb&"; case SILENT_EXPERIMENT_A: return "ix=sea&"; case SILENT_EXPERIMENT_B: return "ix=seb&"; case SUGGEST_EXPERIMENT_A: return "ix=tea&"; case SUGGEST_EXPERIMENT_B: return "ix=teb&"; case UMA_CONTROL_A: return "ix=uca&"; case UMA_CONTROL_B: return "ix=ucb&"; case ALL_CONTROL_A: return "ix=aca&"; case ALL_CONTROL_B: return "ix=acb&"; } NOTREACHED(); return std::string(); } // static bool InstantFieldTrial::ShouldSetSuggestedText(Profile* profile) { Group group = GetGroup(profile); return !(group == HIDDEN_EXPERIMENT_A || group == HIDDEN_EXPERIMENT_B || group == SILENT_EXPERIMENT_A || group == SILENT_EXPERIMENT_B); }
// 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/instant/instant_field_trial.h" #include "base/command_line.h" #include "base/metrics/field_trial.h" #include "chrome/browser/metrics/metrics_service.h" #include "chrome/browser/prefs/pref_service.h" #include "chrome/browser/profiles/profile.h" #include "chrome/common/chrome_switches.h" #include "chrome/common/pref_names.h" namespace { // Field trial IDs of the control and experiment groups. Though they are not // literally "const", they are set only once, in Activate() below. See the .h // file for what these groups represent. int g_instant_experiment_a = 0; int g_instant_experiment_b = 0; int g_hidden_experiment_a = 0; int g_hidden_experiment_b = 0; int g_silent_experiment_a = 0; int g_silent_experiment_b = 0; int g_suggest_experiment_a = 0; int g_suggest_experiment_b = 0; int g_uma_control_a = 0; int g_uma_control_b = 0; int g_all_control_a = 0; int g_all_control_b = 0; } // static void InstantFieldTrial::Activate() { scoped_refptr<base::FieldTrial> trial( new base::FieldTrial("Instant", 1000, "Inactive", 2012, 7, 1)); // Try to give the user a consistent experience, if possible. if (base::FieldTrialList::IsOneTimeRandomizationEnabled()) trial->UseOneTimeRandomization(); g_instant_experiment_a = trial->AppendGroup("InstantExperimentA", 50); g_instant_experiment_b = trial->AppendGroup("InstantExperimentB", 50); g_hidden_experiment_a = trial->AppendGroup("HiddenExperimentA", 50); g_hidden_experiment_b = trial->AppendGroup("HiddenExperimentB", 50); g_silent_experiment_a = trial->AppendGroup("SilentExperimentA", 340); g_silent_experiment_b = trial->AppendGroup("SilentExperimentB", 340); g_suggest_experiment_a = trial->AppendGroup("SuggestExperimentA", 50); g_suggest_experiment_b = trial->AppendGroup("SuggestExperimentB", 50); g_uma_control_a = trial->AppendGroup("UmaControlA", 5); g_uma_control_b = trial->AppendGroup("UmaControlB", 5); g_all_control_a = trial->AppendGroup("AllControlA", 5); g_all_control_b = trial->AppendGroup("AllControlB", 5); } // static InstantFieldTrial::Group InstantFieldTrial::GetGroup(Profile* profile) { CommandLine* command_line = CommandLine::ForCurrentProcess(); if (command_line->HasSwitch(switches::kInstantFieldTrial)) { std::string switch_value = command_line->GetSwitchValueASCII(switches::kInstantFieldTrial); if (switch_value == switches::kInstantFieldTrialInstant) return INSTANT_EXPERIMENT_A; else if (switch_value == switches::kInstantFieldTrialHidden) return HIDDEN_EXPERIMENT_A; else if (switch_value == switches::kInstantFieldTrialSilent) return SILENT_EXPERIMENT_A; else if (switch_value == switches::kInstantFieldTrialSuggest) return SUGGEST_EXPERIMENT_A; else return INACTIVE; } const int group = base::FieldTrialList::FindValue("Instant"); if (group == base::FieldTrial::kNotFinalized || group == base::FieldTrial::kDefaultGroupNumber) { return INACTIVE; } const PrefService* prefs = profile ? profile->GetPrefs() : NULL; if (!prefs || prefs->GetBoolean(prefs::kInstantEnabledOnce) || prefs->IsManagedPreference(prefs::kInstantEnabled)) { return INACTIVE; } // First, deal with the groups that don't require UMA opt-in. if (group == g_silent_experiment_a) return SILENT_EXPERIMENT_A; if (group == g_silent_experiment_b) return SILENT_EXPERIMENT_B; if (group == g_all_control_a) return ALL_CONTROL_A; if (group == g_all_control_b) return ALL_CONTROL_B; // All other groups require UMA and suggest, else bounce back to INACTIVE. if (profile->IsOffTheRecord() || !MetricsServiceHelper::IsMetricsReportingEnabled() || !prefs->GetBoolean(prefs::kSearchSuggestEnabled)) { return INACTIVE; } if (group == g_instant_experiment_a) return INSTANT_EXPERIMENT_A; if (group == g_instant_experiment_b) return INSTANT_EXPERIMENT_B; if (group == g_hidden_experiment_a) return HIDDEN_EXPERIMENT_A; if (group == g_hidden_experiment_b) return HIDDEN_EXPERIMENT_B; if (group == g_suggest_experiment_a) return SUGGEST_EXPERIMENT_A; if (group == g_suggest_experiment_b) return SUGGEST_EXPERIMENT_B; if (group == g_uma_control_a) return UMA_CONTROL_A; if (group == g_uma_control_b) return UMA_CONTROL_B; NOTREACHED(); return INACTIVE; } // static bool InstantFieldTrial::IsInstantExperiment(Profile* profile) { Group group = GetGroup(profile); return group == INSTANT_EXPERIMENT_A || group == INSTANT_EXPERIMENT_B || group == HIDDEN_EXPERIMENT_A || group == HIDDEN_EXPERIMENT_B || group == SILENT_EXPERIMENT_A || group == SILENT_EXPERIMENT_B || group == SUGGEST_EXPERIMENT_A || group == SUGGEST_EXPERIMENT_B; } // static bool InstantFieldTrial::IsHiddenExperiment(Profile* profile) { Group group = GetGroup(profile); return group == HIDDEN_EXPERIMENT_A || group == HIDDEN_EXPERIMENT_B || group == SILENT_EXPERIMENT_A || group == SILENT_EXPERIMENT_B || group == SUGGEST_EXPERIMENT_A || group == SUGGEST_EXPERIMENT_B; } // static bool InstantFieldTrial::IsSilentExperiment(Profile* profile) { Group group = GetGroup(profile); return group == SILENT_EXPERIMENT_A || group == SILENT_EXPERIMENT_B; } // static std::string InstantFieldTrial::GetGroupName(Profile* profile) { switch (GetGroup(profile)) { case INACTIVE: return std::string(); case INSTANT_EXPERIMENT_A: return "_InstantExperimentA"; case INSTANT_EXPERIMENT_B: return "_InstantExperimentB"; case HIDDEN_EXPERIMENT_A: return "_HiddenExperimentA"; case HIDDEN_EXPERIMENT_B: return "_HiddenExperimentB"; case SILENT_EXPERIMENT_A: return "_SilentExperimentA"; case SILENT_EXPERIMENT_B: return "_SilentExperimentB"; case SUGGEST_EXPERIMENT_A: return "_SuggestExperimentA"; case SUGGEST_EXPERIMENT_B: return "_SuggestExperimentB"; case UMA_CONTROL_A: return "_UmaControlA"; case UMA_CONTROL_B: return "_UmaControlB"; case ALL_CONTROL_A: return "_AllControlA"; case ALL_CONTROL_B: return "_AllControlB"; } NOTREACHED(); return std::string(); } // static std::string InstantFieldTrial::GetGroupAsUrlParam(Profile* profile) { switch (GetGroup(profile)) { case INACTIVE: return std::string(); case INSTANT_EXPERIMENT_A: return "ix=iea&"; case INSTANT_EXPERIMENT_B: return "ix=ieb&"; case HIDDEN_EXPERIMENT_A: return "ix=hea&"; case HIDDEN_EXPERIMENT_B: return "ix=heb&"; case SILENT_EXPERIMENT_A: return "ix=sea&"; case SILENT_EXPERIMENT_B: return "ix=seb&"; case SUGGEST_EXPERIMENT_A: return "ix=tea&"; case SUGGEST_EXPERIMENT_B: return "ix=teb&"; case UMA_CONTROL_A: return "ix=uca&"; case UMA_CONTROL_B: return "ix=ucb&"; case ALL_CONTROL_A: return "ix=aca&"; case ALL_CONTROL_B: return "ix=acb&"; } NOTREACHED(); return std::string(); } // static bool InstantFieldTrial::ShouldSetSuggestedText(Profile* profile) { Group group = GetGroup(profile); return !(group == HIDDEN_EXPERIMENT_A || group == HIDDEN_EXPERIMENT_B || group == SILENT_EXPERIMENT_A || group == SILENT_EXPERIMENT_B); }
Increase the SILENT field trial percentage.
Increase the SILENT field trial percentage. The SILENT trial shows significant improvement in latency of searches issued from the omnibox, so it's worth making this benefit available to more users. Reduce the control groups a bit, to provide more room. BUG=105670 TEST=none Review URL: http://codereview.chromium.org/8676047 git-svn-id: de016e52bd170d2d4f2344f9bf92d50478b649e0@112089 0039d316-1c4b-4281-b951-d872f2087c98
C++
bsd-3-clause
krieger-od/nwjs_chromium.src,krieger-od/nwjs_chromium.src,fujunwei/chromium-crosswalk,PeterWangIntel/chromium-crosswalk,bright-sparks/chromium-spacewalk,markYoungH/chromium.src,M4sse/chromium.src,ondra-novak/chromium.src,jaruba/chromium.src,Jonekee/chromium.src,ChromiumWebApps/chromium,jaruba/chromium.src,axinging/chromium-crosswalk,hujiajie/pa-chromium,Just-D/chromium-1,M4sse/chromium.src,fujunwei/chromium-crosswalk,Fireblend/chromium-crosswalk,Jonekee/chromium.src,zcbenz/cefode-chromium,Chilledheart/chromium,keishi/chromium,pozdnyakov/chromium-crosswalk,ChromiumWebApps/chromium,markYoungH/chromium.src,anirudhSK/chromium,robclark/chromium,PeterWangIntel/chromium-crosswalk,dednal/chromium.src,fujunwei/chromium-crosswalk,krieger-od/nwjs_chromium.src,Pluto-tv/chromium-crosswalk,nacl-webkit/chrome_deps,axinging/chromium-crosswalk,M4sse/chromium.src,axinging/chromium-crosswalk,hgl888/chromium-crosswalk,bright-sparks/chromium-spacewalk,hujiajie/pa-chromium,pozdnyakov/chromium-crosswalk,mohamed--abdel-maksoud/chromium.src,anirudhSK/chromium,zcbenz/cefode-chromium,hujiajie/pa-chromium,PeterWangIntel/chromium-crosswalk,Just-D/chromium-1,dushu1203/chromium.src,ltilve/chromium,krieger-od/nwjs_chromium.src,patrickm/chromium.src,mohamed--abdel-maksoud/chromium.src,pozdnyakov/chromium-crosswalk,pozdnyakov/chromium-crosswalk,ondra-novak/chromium.src,chuan9/chromium-crosswalk,patrickm/chromium.src,Chilledheart/chromium,littlstar/chromium.src,Jonekee/chromium.src,mogoweb/chromium-crosswalk,mogoweb/chromium-crosswalk,timopulkkinen/BubbleFish,dednal/chromium.src,hgl888/chromium-crosswalk-efl,M4sse/chromium.src,crosswalk-project/chromium-crosswalk-efl,jaruba/chromium.src,rogerwang/chromium,mohamed--abdel-maksoud/chromium.src,Fireblend/chromium-crosswalk,hgl888/chromium-crosswalk,ltilve/chromium,patrickm/chromium.src,hujiajie/pa-chromium,littlstar/chromium.src,nacl-webkit/chrome_deps,axinging/chromium-crosswalk,crosswalk-project/chromium-crosswalk-efl,mogoweb/chromium-crosswalk,markYoungH/chromium.src,Chilledheart/chromium,jaruba/chromium.src,keishi/chromium,krieger-od/nwjs_chromium.src,robclark/chromium,krieger-od/nwjs_chromium.src,markYoungH/chromium.src,rogerwang/chromium,axinging/chromium-crosswalk,Just-D/chromium-1,nacl-webkit/chrome_deps,dushu1203/chromium.src,dushu1203/chromium.src,nacl-webkit/chrome_deps,keishi/chromium,Pluto-tv/chromium-crosswalk,hgl888/chromium-crosswalk,crosswalk-project/chromium-crosswalk-efl,Fireblend/chromium-crosswalk,dushu1203/chromium.src,jaruba/chromium.src,jaruba/chromium.src,anirudhSK/chromium,krieger-od/nwjs_chromium.src,anirudhSK/chromium,M4sse/chromium.src,pozdnyakov/chromium-crosswalk,markYoungH/chromium.src,ChromiumWebApps/chromium,robclark/chromium,Fireblend/chromium-crosswalk,bright-sparks/chromium-spacewalk,anirudhSK/chromium,TheTypoMaster/chromium-crosswalk,PeterWangIntel/chromium-crosswalk,rogerwang/chromium,anirudhSK/chromium,dednal/chromium.src,Pluto-tv/chromium-crosswalk,zcbenz/cefode-chromium,ChromiumWebApps/chromium,chuan9/chromium-crosswalk,PeterWangIntel/chromium-crosswalk,mogoweb/chromium-crosswalk,keishi/chromium,hgl888/chromium-crosswalk,ondra-novak/chromium.src,Pluto-tv/chromium-crosswalk,hgl888/chromium-crosswalk,littlstar/chromium.src,hgl888/chromium-crosswalk-efl,jaruba/chromium.src,Pluto-tv/chromium-crosswalk,zcbenz/cefode-chromium,timopulkkinen/BubbleFish,junmin-zhu/chromium-rivertrail,hgl888/chromium-crosswalk-efl,junmin-zhu/chromium-rivertrail,bright-sparks/chromium-spacewalk,dushu1203/chromium.src,Chilledheart/chromium,littlstar/chromium.src,zcbenz/cefode-chromium,fujunwei/chromium-crosswalk,rogerwang/chromium,keishi/chromium,pozdnyakov/chromium-crosswalk,timopulkkinen/BubbleFish,Jonekee/chromium.src,Jonekee/chromium.src,junmin-zhu/chromium-rivertrail,krieger-od/nwjs_chromium.src,Jonekee/chromium.src,axinging/chromium-crosswalk,TheTypoMaster/chromium-crosswalk,mogoweb/chromium-crosswalk,littlstar/chromium.src,dushu1203/chromium.src,junmin-zhu/chromium-rivertrail,anirudhSK/chromium,axinging/chromium-crosswalk,ondra-novak/chromium.src,nacl-webkit/chrome_deps,pozdnyakov/chromium-crosswalk,dushu1203/chromium.src,keishi/chromium,fujunwei/chromium-crosswalk,mogoweb/chromium-crosswalk,chuan9/chromium-crosswalk,TheTypoMaster/chromium-crosswalk,hgl888/chromium-crosswalk-efl,nacl-webkit/chrome_deps,chuan9/chromium-crosswalk,zcbenz/cefode-chromium,junmin-zhu/chromium-rivertrail,krieger-od/nwjs_chromium.src,dushu1203/chromium.src,robclark/chromium,chuan9/chromium-crosswalk,keishi/chromium,bright-sparks/chromium-spacewalk,ondra-novak/chromium.src,timopulkkinen/BubbleFish,chuan9/chromium-crosswalk,hgl888/chromium-crosswalk,M4sse/chromium.src,Fireblend/chromium-crosswalk,hgl888/chromium-crosswalk-efl,hujiajie/pa-chromium,Just-D/chromium-1,timopulkkinen/BubbleFish,TheTypoMaster/chromium-crosswalk,rogerwang/chromium,dednal/chromium.src,ChromiumWebApps/chromium,hgl888/chromium-crosswalk,Fireblend/chromium-crosswalk,Fireblend/chromium-crosswalk,Jonekee/chromium.src,crosswalk-project/chromium-crosswalk-efl,hgl888/chromium-crosswalk-efl,bright-sparks/chromium-spacewalk,timopulkkinen/BubbleFish,timopulkkinen/BubbleFish,junmin-zhu/chromium-rivertrail,patrickm/chromium.src,pozdnyakov/chromium-crosswalk,dednal/chromium.src,jaruba/chromium.src,hujiajie/pa-chromium,Fireblend/chromium-crosswalk,junmin-zhu/chromium-rivertrail,nacl-webkit/chrome_deps,ltilve/chromium,mogoweb/chromium-crosswalk,zcbenz/cefode-chromium,fujunwei/chromium-crosswalk,pozdnyakov/chromium-crosswalk,fujunwei/chromium-crosswalk,PeterWangIntel/chromium-crosswalk,hgl888/chromium-crosswalk-efl,timopulkkinen/BubbleFish,ondra-novak/chromium.src,keishi/chromium,rogerwang/chromium,keishi/chromium,mohamed--abdel-maksoud/chromium.src,mohamed--abdel-maksoud/chromium.src,dednal/chromium.src,chuan9/chromium-crosswalk,ondra-novak/chromium.src,dednal/chromium.src,crosswalk-project/chromium-crosswalk-efl,Chilledheart/chromium,Jonekee/chromium.src,markYoungH/chromium.src,Fireblend/chromium-crosswalk,hujiajie/pa-chromium,TheTypoMaster/chromium-crosswalk,nacl-webkit/chrome_deps,axinging/chromium-crosswalk,fujunwei/chromium-crosswalk,M4sse/chromium.src,Just-D/chromium-1,hgl888/chromium-crosswalk-efl,nacl-webkit/chrome_deps,mohamed--abdel-maksoud/chromium.src,mohamed--abdel-maksoud/chromium.src,chuan9/chromium-crosswalk,mohamed--abdel-maksoud/chromium.src,keishi/chromium,anirudhSK/chromium,hujiajie/pa-chromium,Chilledheart/chromium,Pluto-tv/chromium-crosswalk,hgl888/chromium-crosswalk-efl,anirudhSK/chromium,Chilledheart/chromium,TheTypoMaster/chromium-crosswalk,M4sse/chromium.src,crosswalk-project/chromium-crosswalk-efl,ltilve/chromium,ChromiumWebApps/chromium,crosswalk-project/chromium-crosswalk-efl,ltilve/chromium,ChromiumWebApps/chromium,timopulkkinen/BubbleFish,ChromiumWebApps/chromium,ondra-novak/chromium.src,rogerwang/chromium,crosswalk-project/chromium-crosswalk-efl,TheTypoMaster/chromium-crosswalk,hgl888/chromium-crosswalk-efl,dednal/chromium.src,junmin-zhu/chromium-rivertrail,jaruba/chromium.src,junmin-zhu/chromium-rivertrail,hujiajie/pa-chromium,littlstar/chromium.src,ltilve/chromium,krieger-od/nwjs_chromium.src,hujiajie/pa-chromium,robclark/chromium,axinging/chromium-crosswalk,zcbenz/cefode-chromium,dushu1203/chromium.src,zcbenz/cefode-chromium,junmin-zhu/chromium-rivertrail,anirudhSK/chromium,mohamed--abdel-maksoud/chromium.src,dushu1203/chromium.src,Pluto-tv/chromium-crosswalk,patrickm/chromium.src,PeterWangIntel/chromium-crosswalk,bright-sparks/chromium-spacewalk,Jonekee/chromium.src,Just-D/chromium-1,PeterWangIntel/chromium-crosswalk,junmin-zhu/chromium-rivertrail,M4sse/chromium.src,mogoweb/chromium-crosswalk,patrickm/chromium.src,Just-D/chromium-1,Jonekee/chromium.src,M4sse/chromium.src,axinging/chromium-crosswalk,crosswalk-project/chromium-crosswalk-efl,zcbenz/cefode-chromium,ChromiumWebApps/chromium,rogerwang/chromium,mohamed--abdel-maksoud/chromium.src,Jonekee/chromium.src,zcbenz/cefode-chromium,fujunwei/chromium-crosswalk,littlstar/chromium.src,chuan9/chromium-crosswalk,Just-D/chromium-1,rogerwang/chromium,dushu1203/chromium.src,jaruba/chromium.src,axinging/chromium-crosswalk,PeterWangIntel/chromium-crosswalk,anirudhSK/chromium,markYoungH/chromium.src,hujiajie/pa-chromium,nacl-webkit/chrome_deps,ChromiumWebApps/chromium,dednal/chromium.src,ondra-novak/chromium.src,pozdnyakov/chromium-crosswalk,markYoungH/chromium.src,markYoungH/chromium.src,M4sse/chromium.src,Chilledheart/chromium,patrickm/chromium.src,dednal/chromium.src,nacl-webkit/chrome_deps,ChromiumWebApps/chromium,robclark/chromium,ltilve/chromium,mogoweb/chromium-crosswalk,TheTypoMaster/chromium-crosswalk,Chilledheart/chromium,dednal/chromium.src,pozdnyakov/chromium-crosswalk,rogerwang/chromium,markYoungH/chromium.src,markYoungH/chromium.src,jaruba/chromium.src,ChromiumWebApps/chromium,bright-sparks/chromium-spacewalk,patrickm/chromium.src,robclark/chromium,Pluto-tv/chromium-crosswalk,timopulkkinen/BubbleFish,mogoweb/chromium-crosswalk,Just-D/chromium-1,timopulkkinen/BubbleFish,robclark/chromium,hgl888/chromium-crosswalk,anirudhSK/chromium,TheTypoMaster/chromium-crosswalk,Pluto-tv/chromium-crosswalk,hgl888/chromium-crosswalk,ltilve/chromium,mohamed--abdel-maksoud/chromium.src,littlstar/chromium.src,patrickm/chromium.src,robclark/chromium,bright-sparks/chromium-spacewalk,robclark/chromium,keishi/chromium,ltilve/chromium,krieger-od/nwjs_chromium.src
61eb472c874450a295590b64da3eed89ac8acd09
chrome/browser/ui/metro_pin_tab_helper_win.cc
chrome/browser/ui/metro_pin_tab_helper_win.cc
// Copyright (c) 2012 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chrome/browser/ui/metro_pin_tab_helper_win.h" #include "base/base_paths.h" #include "base/bind.h" #include "base/file_path.h" #include "base/file_util.h" #include "base/logging.h" #include "base/memory/ref_counted.h" #include "base/memory/ref_counted_memory.h" #include "base/path_service.h" #include "base/string_number_conversions.h" #include "base/utf_string_conversions.h" #include "base/win/metro.h" #include "chrome/browser/favicon/favicon_tab_helper.h" #include "chrome/browser/ui/tab_contents/tab_contents.h" #include "chrome/common/chrome_paths.h" #include "content/public/browser/browser_thread.h" #include "content/public/browser/web_contents.h" #include "crypto/sha2.h" #include "ui/gfx/canvas.h" #include "ui/gfx/codec/png_codec.h" #include "ui/gfx/color_analysis.h" #include "ui/gfx/color_utils.h" #include "ui/gfx/image/image.h" #include "ui/gfx/rect.h" #include "ui/gfx/size.h" DEFINE_WEB_CONTENTS_USER_DATA_KEY(MetroPinTabHelper) namespace { // Generate an ID for the tile based on |url_str|. The ID is simply a hash of // the URL. string16 GenerateTileId(const string16& url_str) { uint8 hash[crypto::kSHA256Length]; crypto::SHA256HashString(UTF16ToUTF8(url_str), hash, sizeof(hash)); std::string hash_str = base::HexEncode(hash, sizeof(hash)); return UTF8ToUTF16(hash_str); } // Get the path of the directory to store the tile logos in. FilePath GetTileImagesDir() { FilePath time_images_dir; DCHECK(PathService::Get(chrome::DIR_USER_DATA, &time_images_dir)); time_images_dir = time_images_dir.Append(L"TileImages"); if (!file_util::DirectoryExists(time_images_dir) && !file_util::CreateDirectory(time_images_dir)) return FilePath(); return time_images_dir; } // For the given |image| and |tile_id|, try to create a site specific logo in // |logo_dir|. The path of any created logo is returned in |logo_path|. Return // value indicates whether a site specific logo was created. bool CreateSiteSpecificLogo(const gfx::ImageSkia& image, const string16& tile_id, const FilePath& logo_dir, FilePath* logo_path) { const int kLogoWidth = 120; const int kLogoHeight = 120; const int kBoxWidth = 40; const int kBoxHeight = 40; const int kCaptionHeight = 20; const double kBoxFade = 0.75; const int kColorMeanDarknessLimit = 100; const int kColorMeanLightnessLimit = 100; if (image.isNull()) return false; *logo_path = logo_dir.Append(tile_id).ReplaceExtension(L".png"); // Use a canvas to paint the tile logo. gfx::Canvas canvas(gfx::Size(kLogoWidth, kLogoHeight), ui::SCALE_FACTOR_100P, true); // Fill the tile logo with the average color from bitmap. To do this we need // to work out the 'average color' which is calculated using PNG encoded data // of the bitmap. SkPaint paint; std::vector<unsigned char> icon_png; if (!gfx::PNGCodec::EncodeBGRASkBitmap(*image.bitmap(), true, &icon_png)) return false; scoped_refptr<base::RefCountedStaticMemory> icon_mem( new base::RefCountedStaticMemory(&icon_png.front(), icon_png.size())); color_utils::GridSampler sampler; SkColor mean_color = color_utils::CalculateKMeanColorOfPNG( icon_mem, kColorMeanDarknessLimit, kColorMeanLightnessLimit, sampler); paint.setColor(mean_color); canvas.DrawRect(gfx::Rect(0, 0, kLogoWidth, kLogoHeight), paint); // Now paint a faded square for the favicon to go in. color_utils::HSL shift = {-1, -1, kBoxFade}; paint.setColor(color_utils::HSLShift(mean_color, shift)); int box_left = (kLogoWidth - kBoxWidth) / 2; int box_top = (kLogoHeight - kCaptionHeight - kBoxHeight) / 2; canvas.DrawRect(gfx::Rect(box_left, box_top, kBoxWidth, kBoxHeight), paint); // Now paint the favicon into the tile, leaving some room at the bottom for // the caption. int left = (kLogoWidth - image.width()) / 2; int top = (kLogoHeight - kCaptionHeight - image.height()) / 2; canvas.DrawImageInt(image, left, top); SkBitmap logo_bitmap = canvas.ExtractImageRep().sk_bitmap(); std::vector<unsigned char> logo_png; if (!gfx::PNGCodec::EncodeBGRASkBitmap(logo_bitmap, true, &logo_png)) return false; return file_util::WriteFile(*logo_path, reinterpret_cast<char*>(&logo_png[0]), logo_png.size()) > 0; } // Get the path to the backup logo. If the backup logo already exists in // |logo_dir|, it will be used, otherwise it will be copied out of the install // folder. (The version in the install folder is not used as it may disappear // after an upgrade, causing tiles to lose their images if Windows rebuilds // its tile image cache.) // The path to the logo is returned in |logo_path|, with the return value // indicating success. bool GetPathToBackupLogo(const FilePath& logo_dir, FilePath* logo_path) { const wchar_t kDefaultLogoFileName[] = L"SecondaryTile.png"; *logo_path = logo_dir.Append(kDefaultLogoFileName); if (file_util::PathExists(*logo_path)) return true; FilePath default_logo_path; DCHECK(PathService::Get(base::DIR_MODULE, &default_logo_path)); default_logo_path = default_logo_path.Append(kDefaultLogoFileName); return file_util::CopyFile(default_logo_path, *logo_path); } } // namespace class MetroPinTabHelper::TaskRunner : public base::RefCountedThreadSafe<TaskRunner> { public: TaskRunner() {} void PinPageToStartScreen(const string16& title, const string16& url, const gfx::ImageSkia& image); private: ~TaskRunner() {} friend class base::RefCountedThreadSafe<TaskRunner>; DISALLOW_COPY_AND_ASSIGN(TaskRunner); }; void MetroPinTabHelper::TaskRunner::PinPageToStartScreen( const string16& title, const string16& url, const gfx::ImageSkia& image) { DCHECK(content::BrowserThread::CurrentlyOn(content::BrowserThread::FILE)); string16 tile_id = GenerateTileId(url); FilePath logo_dir = GetTileImagesDir(); if (logo_dir.empty()) { LOG(ERROR) << "Could not create directory to store tile image."; return; } FilePath logo_path; if (!CreateSiteSpecificLogo(image, tile_id, logo_dir, &logo_path) && !GetPathToBackupLogo(logo_dir, &logo_path)) { LOG(ERROR) << "Count not get path to logo tile."; return; } HMODULE metro_module = base::win::GetMetroModule(); if (!metro_module) return; typedef void (*MetroPinToStartScreen)(const string16&, const string16&, const string16&, const FilePath&); MetroPinToStartScreen metro_pin_to_start_screen = reinterpret_cast<MetroPinToStartScreen>( ::GetProcAddress(metro_module, "MetroPinToStartScreen")); if (!metro_pin_to_start_screen) { NOTREACHED(); return; } VLOG(1) << __FUNCTION__ << " calling pin with title: " << title << " and url: " << url; metro_pin_to_start_screen(tile_id, title, url, logo_path); } MetroPinTabHelper::MetroPinTabHelper(content::WebContents* web_contents) : content::WebContentsObserver(web_contents), is_pinned_(false), task_runner_(new TaskRunner) {} MetroPinTabHelper::~MetroPinTabHelper() {} void MetroPinTabHelper::TogglePinnedToStartScreen() { UpdatePinnedStateForCurrentURL(); bool was_pinned = is_pinned_; // TODO(benwells): This will update the state incorrectly if the user // cancels. To fix this some sort of callback needs to be introduced as // the pinning happens on another thread. is_pinned_ = !is_pinned_; if (was_pinned) { UnPinPageFromStartScreen(); return; } // TODO(benwells): Handle downloading a larger favicon if there is one. GURL url = web_contents()->GetURL(); string16 url_str = UTF8ToUTF16(url.spec()); string16 title = web_contents()->GetTitle(); TabContents* tab_contents = TabContents::FromWebContents(web_contents()); DCHECK(tab_contents); FaviconTabHelper* favicon_tab_helper = FaviconTabHelper::FromWebContents( tab_contents->web_contents()); if (favicon_tab_helper->FaviconIsValid()) { gfx::Image favicon = favicon_tab_helper->GetFavicon(); gfx::ImageSkia favicon_skia = favicon.AsImageSkia().DeepCopy(); content::BrowserThread::PostTask( content::BrowserThread::FILE, FROM_HERE, base::Bind(&TaskRunner::PinPageToStartScreen, task_runner_, title, url_str, favicon_skia)); return; } content::BrowserThread::PostTask( content::BrowserThread::FILE, FROM_HERE, base::Bind(&TaskRunner::PinPageToStartScreen, task_runner_, title, url_str, gfx::ImageSkia())); } void MetroPinTabHelper::DidNavigateMainFrame( const content::LoadCommittedDetails& /*details*/, const content::FrameNavigateParams& /*params*/) { UpdatePinnedStateForCurrentURL(); } void MetroPinTabHelper::UpdatePinnedStateForCurrentURL() { HMODULE metro_module = base::win::GetMetroModule(); if (!metro_module) return; typedef BOOL (*MetroIsPinnedToStartScreen)(const string16&); MetroIsPinnedToStartScreen metro_is_pinned_to_start_screen = reinterpret_cast<MetroIsPinnedToStartScreen>( ::GetProcAddress(metro_module, "MetroIsPinnedToStartScreen")); if (!metro_is_pinned_to_start_screen) { NOTREACHED(); return; } GURL url = web_contents()->GetURL(); string16 tile_id = GenerateTileId(UTF8ToUTF16(url.spec())); is_pinned_ = metro_is_pinned_to_start_screen(tile_id) != 0; VLOG(1) << __FUNCTION__ << " with url " << UTF8ToUTF16(url.spec()) << " result: " << is_pinned_; } void MetroPinTabHelper::UnPinPageFromStartScreen() { HMODULE metro_module = base::win::GetMetroModule(); if (!metro_module) return; typedef void (*MetroUnPinFromStartScreen)(const string16&); MetroUnPinFromStartScreen metro_un_pin_from_start_screen = reinterpret_cast<MetroUnPinFromStartScreen>( ::GetProcAddress(metro_module, "MetroUnPinFromStartScreen")); if (!metro_un_pin_from_start_screen) { NOTREACHED(); return; } GURL url = web_contents()->GetURL(); VLOG(1) << __FUNCTION__ << " calling unpin with url: " << UTF8ToUTF16(url.spec()); string16 tile_id = GenerateTileId(UTF8ToUTF16(url.spec())); metro_un_pin_from_start_screen(tile_id); }
// 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 "chrome/browser/ui/metro_pin_tab_helper_win.h" #include "base/base_paths.h" #include "base/bind.h" #include "base/file_path.h" #include "base/file_util.h" #include "base/logging.h" #include "base/memory/ref_counted.h" #include "base/memory/ref_counted_memory.h" #include "base/path_service.h" #include "base/string_number_conversions.h" #include "base/utf_string_conversions.h" #include "base/win/metro.h" #include "chrome/browser/favicon/favicon_tab_helper.h" #include "chrome/browser/ui/tab_contents/tab_contents.h" #include "chrome/common/chrome_paths.h" #include "content/public/browser/browser_thread.h" #include "content/public/browser/web_contents.h" #include "crypto/sha2.h" #include "ui/gfx/canvas.h" #include "ui/gfx/codec/png_codec.h" #include "ui/gfx/color_analysis.h" #include "ui/gfx/color_utils.h" #include "ui/gfx/image/image.h" #include "ui/gfx/rect.h" #include "ui/gfx/size.h" DEFINE_WEB_CONTENTS_USER_DATA_KEY(MetroPinTabHelper) namespace { // Generate an ID for the tile based on |url_str|. The ID is simply a hash of // the URL. string16 GenerateTileId(const string16& url_str) { uint8 hash[crypto::kSHA256Length]; crypto::SHA256HashString(UTF16ToUTF8(url_str), hash, sizeof(hash)); std::string hash_str = base::HexEncode(hash, sizeof(hash)); return UTF8ToUTF16(hash_str); } // Get the path of the directory to store the tile logos in. FilePath GetTileImagesDir() { FilePath tile_images_dir; if (!PathService::Get(chrome::DIR_USER_DATA, &tile_images_dir)) return FilePath(); tile_images_dir = tile_images_dir.Append(L"TileImages"); if (!file_util::DirectoryExists(tile_images_dir) && !file_util::CreateDirectory(tile_images_dir)) return FilePath(); return tile_images_dir; } // For the given |image| and |tile_id|, try to create a site specific logo in // |logo_dir|. The path of any created logo is returned in |logo_path|. Return // value indicates whether a site specific logo was created. bool CreateSiteSpecificLogo(const gfx::ImageSkia& image, const string16& tile_id, const FilePath& logo_dir, FilePath* logo_path) { const int kLogoWidth = 120; const int kLogoHeight = 120; const int kBoxWidth = 40; const int kBoxHeight = 40; const int kCaptionHeight = 20; const double kBoxFade = 0.75; const int kColorMeanDarknessLimit = 100; const int kColorMeanLightnessLimit = 100; if (image.isNull()) return false; *logo_path = logo_dir.Append(tile_id).ReplaceExtension(L".png"); // Use a canvas to paint the tile logo. gfx::Canvas canvas(gfx::Size(kLogoWidth, kLogoHeight), ui::SCALE_FACTOR_100P, true); // Fill the tile logo with the average color from bitmap. To do this we need // to work out the 'average color' which is calculated using PNG encoded data // of the bitmap. SkPaint paint; std::vector<unsigned char> icon_png; if (!gfx::PNGCodec::EncodeBGRASkBitmap(*image.bitmap(), true, &icon_png)) return false; scoped_refptr<base::RefCountedStaticMemory> icon_mem( new base::RefCountedStaticMemory(&icon_png.front(), icon_png.size())); color_utils::GridSampler sampler; SkColor mean_color = color_utils::CalculateKMeanColorOfPNG( icon_mem, kColorMeanDarknessLimit, kColorMeanLightnessLimit, sampler); paint.setColor(mean_color); canvas.DrawRect(gfx::Rect(0, 0, kLogoWidth, kLogoHeight), paint); // Now paint a faded square for the favicon to go in. color_utils::HSL shift = {-1, -1, kBoxFade}; paint.setColor(color_utils::HSLShift(mean_color, shift)); int box_left = (kLogoWidth - kBoxWidth) / 2; int box_top = (kLogoHeight - kCaptionHeight - kBoxHeight) / 2; canvas.DrawRect(gfx::Rect(box_left, box_top, kBoxWidth, kBoxHeight), paint); // Now paint the favicon into the tile, leaving some room at the bottom for // the caption. int left = (kLogoWidth - image.width()) / 2; int top = (kLogoHeight - kCaptionHeight - image.height()) / 2; canvas.DrawImageInt(image, left, top); SkBitmap logo_bitmap = canvas.ExtractImageRep().sk_bitmap(); std::vector<unsigned char> logo_png; if (!gfx::PNGCodec::EncodeBGRASkBitmap(logo_bitmap, true, &logo_png)) return false; return file_util::WriteFile(*logo_path, reinterpret_cast<char*>(&logo_png[0]), logo_png.size()) > 0; } // Get the path to the backup logo. If the backup logo already exists in // |logo_dir|, it will be used, otherwise it will be copied out of the install // folder. (The version in the install folder is not used as it may disappear // after an upgrade, causing tiles to lose their images if Windows rebuilds // its tile image cache.) // The path to the logo is returned in |logo_path|, with the return value // indicating success. bool GetPathToBackupLogo(const FilePath& logo_dir, FilePath* logo_path) { const wchar_t kDefaultLogoFileName[] = L"SecondaryTile.png"; *logo_path = logo_dir.Append(kDefaultLogoFileName); if (file_util::PathExists(*logo_path)) return true; FilePath default_logo_path; if (!PathService::Get(base::DIR_MODULE, &default_logo_path)) return false; default_logo_path = default_logo_path.Append(kDefaultLogoFileName); return file_util::CopyFile(default_logo_path, *logo_path); } } // namespace class MetroPinTabHelper::TaskRunner : public base::RefCountedThreadSafe<TaskRunner> { public: TaskRunner() {} void PinPageToStartScreen(const string16& title, const string16& url, const gfx::ImageSkia& image); private: ~TaskRunner() {} friend class base::RefCountedThreadSafe<TaskRunner>; DISALLOW_COPY_AND_ASSIGN(TaskRunner); }; void MetroPinTabHelper::TaskRunner::PinPageToStartScreen( const string16& title, const string16& url, const gfx::ImageSkia& image) { DCHECK(content::BrowserThread::CurrentlyOn(content::BrowserThread::FILE)); string16 tile_id = GenerateTileId(url); FilePath logo_dir = GetTileImagesDir(); if (logo_dir.empty()) { LOG(ERROR) << "Could not create directory to store tile image."; return; } FilePath logo_path; if (!CreateSiteSpecificLogo(image, tile_id, logo_dir, &logo_path) && !GetPathToBackupLogo(logo_dir, &logo_path)) { LOG(ERROR) << "Count not get path to logo tile."; return; } HMODULE metro_module = base::win::GetMetroModule(); if (!metro_module) return; typedef void (*MetroPinToStartScreen)(const string16&, const string16&, const string16&, const FilePath&); MetroPinToStartScreen metro_pin_to_start_screen = reinterpret_cast<MetroPinToStartScreen>( ::GetProcAddress(metro_module, "MetroPinToStartScreen")); if (!metro_pin_to_start_screen) { NOTREACHED(); return; } VLOG(1) << __FUNCTION__ << " calling pin with title: " << title << " and url: " << url; metro_pin_to_start_screen(tile_id, title, url, logo_path); } MetroPinTabHelper::MetroPinTabHelper(content::WebContents* web_contents) : content::WebContentsObserver(web_contents), is_pinned_(false), task_runner_(new TaskRunner) {} MetroPinTabHelper::~MetroPinTabHelper() {} void MetroPinTabHelper::TogglePinnedToStartScreen() { UpdatePinnedStateForCurrentURL(); bool was_pinned = is_pinned_; // TODO(benwells): This will update the state incorrectly if the user // cancels. To fix this some sort of callback needs to be introduced as // the pinning happens on another thread. is_pinned_ = !is_pinned_; if (was_pinned) { UnPinPageFromStartScreen(); return; } // TODO(benwells): Handle downloading a larger favicon if there is one. GURL url = web_contents()->GetURL(); string16 url_str = UTF8ToUTF16(url.spec()); string16 title = web_contents()->GetTitle(); TabContents* tab_contents = TabContents::FromWebContents(web_contents()); DCHECK(tab_contents); FaviconTabHelper* favicon_tab_helper = FaviconTabHelper::FromWebContents( tab_contents->web_contents()); if (favicon_tab_helper->FaviconIsValid()) { gfx::Image favicon = favicon_tab_helper->GetFavicon(); gfx::ImageSkia favicon_skia = favicon.AsImageSkia().DeepCopy(); content::BrowserThread::PostTask( content::BrowserThread::FILE, FROM_HERE, base::Bind(&TaskRunner::PinPageToStartScreen, task_runner_, title, url_str, favicon_skia)); return; } content::BrowserThread::PostTask( content::BrowserThread::FILE, FROM_HERE, base::Bind(&TaskRunner::PinPageToStartScreen, task_runner_, title, url_str, gfx::ImageSkia())); } void MetroPinTabHelper::DidNavigateMainFrame( const content::LoadCommittedDetails& /*details*/, const content::FrameNavigateParams& /*params*/) { UpdatePinnedStateForCurrentURL(); } void MetroPinTabHelper::UpdatePinnedStateForCurrentURL() { HMODULE metro_module = base::win::GetMetroModule(); if (!metro_module) return; typedef BOOL (*MetroIsPinnedToStartScreen)(const string16&); MetroIsPinnedToStartScreen metro_is_pinned_to_start_screen = reinterpret_cast<MetroIsPinnedToStartScreen>( ::GetProcAddress(metro_module, "MetroIsPinnedToStartScreen")); if (!metro_is_pinned_to_start_screen) { NOTREACHED(); return; } GURL url = web_contents()->GetURL(); string16 tile_id = GenerateTileId(UTF8ToUTF16(url.spec())); is_pinned_ = metro_is_pinned_to_start_screen(tile_id) != 0; VLOG(1) << __FUNCTION__ << " with url " << UTF8ToUTF16(url.spec()) << " result: " << is_pinned_; } void MetroPinTabHelper::UnPinPageFromStartScreen() { HMODULE metro_module = base::win::GetMetroModule(); if (!metro_module) return; typedef void (*MetroUnPinFromStartScreen)(const string16&); MetroUnPinFromStartScreen metro_un_pin_from_start_screen = reinterpret_cast<MetroUnPinFromStartScreen>( ::GetProcAddress(metro_module, "MetroUnPinFromStartScreen")); if (!metro_un_pin_from_start_screen) { NOTREACHED(); return; } GURL url = web_contents()->GetURL(); VLOG(1) << __FUNCTION__ << " calling unpin with url: " << UTF8ToUTF16(url.spec()); string16 tile_id = GenerateTileId(UTF8ToUTF16(url.spec())); metro_un_pin_from_start_screen(tile_id); }
Fix pinning of secondary tiles on Windows 8 on release builds
Fix pinning of secondary tiles on Windows 8 on release builds I recently broke pinning of secondary tiles on release builds, this change fixes it. BUG=157939 Review URL: https://chromiumcodereview.appspot.com/11303002 git-svn-id: de016e52bd170d2d4f2344f9bf92d50478b649e0@164535 0039d316-1c4b-4281-b951-d872f2087c98
C++
bsd-3-clause
PeterWangIntel/chromium-crosswalk,pozdnyakov/chromium-crosswalk,TheTypoMaster/chromium-crosswalk,anirudhSK/chromium,axinging/chromium-crosswalk,mohamed--abdel-maksoud/chromium.src,PeterWangIntel/chromium-crosswalk,hgl888/chromium-crosswalk,Jonekee/chromium.src,pozdnyakov/chromium-crosswalk,dednal/chromium.src,hujiajie/pa-chromium,bright-sparks/chromium-spacewalk,hujiajie/pa-chromium,timopulkkinen/BubbleFish,hgl888/chromium-crosswalk,dednal/chromium.src,zcbenz/cefode-chromium,littlstar/chromium.src,anirudhSK/chromium,chuan9/chromium-crosswalk,axinging/chromium-crosswalk,Just-D/chromium-1,Chilledheart/chromium,fujunwei/chromium-crosswalk,nacl-webkit/chrome_deps,Pluto-tv/chromium-crosswalk,patrickm/chromium.src,mohamed--abdel-maksoud/chromium.src,bright-sparks/chromium-spacewalk,Pluto-tv/chromium-crosswalk,dednal/chromium.src,timopulkkinen/BubbleFish,junmin-zhu/chromium-rivertrail,junmin-zhu/chromium-rivertrail,nacl-webkit/chrome_deps,junmin-zhu/chromium-rivertrail,nacl-webkit/chrome_deps,nacl-webkit/chrome_deps,hgl888/chromium-crosswalk,zcbenz/cefode-chromium,krieger-od/nwjs_chromium.src,ondra-novak/chromium.src,TheTypoMaster/chromium-crosswalk,M4sse/chromium.src,Fireblend/chromium-crosswalk,hgl888/chromium-crosswalk,patrickm/chromium.src,junmin-zhu/chromium-rivertrail,ondra-novak/chromium.src,TheTypoMaster/chromium-crosswalk,zcbenz/cefode-chromium,chuan9/chromium-crosswalk,anirudhSK/chromium,hgl888/chromium-crosswalk,PeterWangIntel/chromium-crosswalk,dednal/chromium.src,hujiajie/pa-chromium,fujunwei/chromium-crosswalk,PeterWangIntel/chromium-crosswalk,jaruba/chromium.src,hujiajie/pa-chromium,TheTypoMaster/chromium-crosswalk,krieger-od/nwjs_chromium.src,Just-D/chromium-1,ondra-novak/chromium.src,bright-sparks/chromium-spacewalk,fujunwei/chromium-crosswalk,hujiajie/pa-chromium,Jonekee/chromium.src,anirudhSK/chromium,ChromiumWebApps/chromium,Fireblend/chromium-crosswalk,dushu1203/chromium.src,chuan9/chromium-crosswalk,jaruba/chromium.src,Chilledheart/chromium,littlstar/chromium.src,zcbenz/cefode-chromium,pozdnyakov/chromium-crosswalk,mogoweb/chromium-crosswalk,ltilve/chromium,ChromiumWebApps/chromium,hgl888/chromium-crosswalk,bright-sparks/chromium-spacewalk,M4sse/chromium.src,Fireblend/chromium-crosswalk,pozdnyakov/chromium-crosswalk,Jonekee/chromium.src,crosswalk-project/chromium-crosswalk-efl,markYoungH/chromium.src,dednal/chromium.src,Fireblend/chromium-crosswalk,dushu1203/chromium.src,Jonekee/chromium.src,fujunwei/chromium-crosswalk,timopulkkinen/BubbleFish,fujunwei/chromium-crosswalk,krieger-od/nwjs_chromium.src,chuan9/chromium-crosswalk,ltilve/chromium,ltilve/chromium,Just-D/chromium-1,markYoungH/chromium.src,ChromiumWebApps/chromium,dednal/chromium.src,M4sse/chromium.src,bright-sparks/chromium-spacewalk,anirudhSK/chromium,pozdnyakov/chromium-crosswalk,PeterWangIntel/chromium-crosswalk,Fireblend/chromium-crosswalk,patrickm/chromium.src,jaruba/chromium.src,dushu1203/chromium.src,axinging/chromium-crosswalk,mogoweb/chromium-crosswalk,Just-D/chromium-1,axinging/chromium-crosswalk,littlstar/chromium.src,ondra-novak/chromium.src,mogoweb/chromium-crosswalk,Fireblend/chromium-crosswalk,krieger-od/nwjs_chromium.src,ondra-novak/chromium.src,jaruba/chromium.src,jaruba/chromium.src,dushu1203/chromium.src,dednal/chromium.src,M4sse/chromium.src,crosswalk-project/chromium-crosswalk-efl,PeterWangIntel/chromium-crosswalk,hgl888/chromium-crosswalk-efl,markYoungH/chromium.src,PeterWangIntel/chromium-crosswalk,Chilledheart/chromium,mohamed--abdel-maksoud/chromium.src,krieger-od/nwjs_chromium.src,patrickm/chromium.src,patrickm/chromium.src,M4sse/chromium.src,crosswalk-project/chromium-crosswalk-efl,ChromiumWebApps/chromium,mogoweb/chromium-crosswalk,markYoungH/chromium.src,Chilledheart/chromium,ondra-novak/chromium.src,hujiajie/pa-chromium,pozdnyakov/chromium-crosswalk,markYoungH/chromium.src,bright-sparks/chromium-spacewalk,nacl-webkit/chrome_deps,chuan9/chromium-crosswalk,timopulkkinen/BubbleFish,axinging/chromium-crosswalk,mohamed--abdel-maksoud/chromium.src,junmin-zhu/chromium-rivertrail,markYoungH/chromium.src,littlstar/chromium.src,dushu1203/chromium.src,fujunwei/chromium-crosswalk,timopulkkinen/BubbleFish,dushu1203/chromium.src,jaruba/chromium.src,hujiajie/pa-chromium,mogoweb/chromium-crosswalk,Jonekee/chromium.src,dednal/chromium.src,patrickm/chromium.src,jaruba/chromium.src,ChromiumWebApps/chromium,Pluto-tv/chromium-crosswalk,M4sse/chromium.src,M4sse/chromium.src,junmin-zhu/chromium-rivertrail,mohamed--abdel-maksoud/chromium.src,Jonekee/chromium.src,zcbenz/cefode-chromium,jaruba/chromium.src,axinging/chromium-crosswalk,mohamed--abdel-maksoud/chromium.src,Jonekee/chromium.src,hgl888/chromium-crosswalk-efl,fujunwei/chromium-crosswalk,timopulkkinen/BubbleFish,anirudhSK/chromium,axinging/chromium-crosswalk,timopulkkinen/BubbleFish,dushu1203/chromium.src,patrickm/chromium.src,Pluto-tv/chromium-crosswalk,krieger-od/nwjs_chromium.src,krieger-od/nwjs_chromium.src,Fireblend/chromium-crosswalk,zcbenz/cefode-chromium,TheTypoMaster/chromium-crosswalk,Chilledheart/chromium,pozdnyakov/chromium-crosswalk,bright-sparks/chromium-spacewalk,Jonekee/chromium.src,mohamed--abdel-maksoud/chromium.src,junmin-zhu/chromium-rivertrail,nacl-webkit/chrome_deps,krieger-od/nwjs_chromium.src,timopulkkinen/BubbleFish,chuan9/chromium-crosswalk,chuan9/chromium-crosswalk,timopulkkinen/BubbleFish,anirudhSK/chromium,PeterWangIntel/chromium-crosswalk,axinging/chromium-crosswalk,crosswalk-project/chromium-crosswalk-efl,crosswalk-project/chromium-crosswalk-efl,Just-D/chromium-1,Jonekee/chromium.src,anirudhSK/chromium,chuan9/chromium-crosswalk,krieger-od/nwjs_chromium.src,markYoungH/chromium.src,krieger-od/nwjs_chromium.src,Fireblend/chromium-crosswalk,jaruba/chromium.src,jaruba/chromium.src,TheTypoMaster/chromium-crosswalk,crosswalk-project/chromium-crosswalk-efl,TheTypoMaster/chromium-crosswalk,zcbenz/cefode-chromium,Pluto-tv/chromium-crosswalk,zcbenz/cefode-chromium,ChromiumWebApps/chromium,hgl888/chromium-crosswalk-efl,nacl-webkit/chrome_deps,ChromiumWebApps/chromium,hgl888/chromium-crosswalk,junmin-zhu/chromium-rivertrail,M4sse/chromium.src,ChromiumWebApps/chromium,dednal/chromium.src,M4sse/chromium.src,hgl888/chromium-crosswalk,M4sse/chromium.src,junmin-zhu/chromium-rivertrail,anirudhSK/chromium,dushu1203/chromium.src,mogoweb/chromium-crosswalk,mohamed--abdel-maksoud/chromium.src,ltilve/chromium,mogoweb/chromium-crosswalk,anirudhSK/chromium,littlstar/chromium.src,Pluto-tv/chromium-crosswalk,crosswalk-project/chromium-crosswalk-efl,axinging/chromium-crosswalk,littlstar/chromium.src,junmin-zhu/chromium-rivertrail,PeterWangIntel/chromium-crosswalk,anirudhSK/chromium,Chilledheart/chromium,ChromiumWebApps/chromium,Pluto-tv/chromium-crosswalk,chuan9/chromium-crosswalk,ltilve/chromium,hgl888/chromium-crosswalk-efl,ondra-novak/chromium.src,Just-D/chromium-1,dushu1203/chromium.src,hujiajie/pa-chromium,Chilledheart/chromium,hgl888/chromium-crosswalk-efl,mohamed--abdel-maksoud/chromium.src,dushu1203/chromium.src,hujiajie/pa-chromium,Jonekee/chromium.src,Just-D/chromium-1,fujunwei/chromium-crosswalk,ltilve/chromium,ChromiumWebApps/chromium,timopulkkinen/BubbleFish,pozdnyakov/chromium-crosswalk,nacl-webkit/chrome_deps,zcbenz/cefode-chromium,dednal/chromium.src,ChromiumWebApps/chromium,hujiajie/pa-chromium,anirudhSK/chromium,markYoungH/chromium.src,fujunwei/chromium-crosswalk,nacl-webkit/chrome_deps,hgl888/chromium-crosswalk-efl,jaruba/chromium.src,markYoungH/chromium.src,zcbenz/cefode-chromium,Chilledheart/chromium,junmin-zhu/chromium-rivertrail,pozdnyakov/chromium-crosswalk,ltilve/chromium,mohamed--abdel-maksoud/chromium.src,mogoweb/chromium-crosswalk,zcbenz/cefode-chromium,markYoungH/chromium.src,crosswalk-project/chromium-crosswalk-efl,hgl888/chromium-crosswalk-efl,Chilledheart/chromium,TheTypoMaster/chromium-crosswalk,Just-D/chromium-1,hgl888/chromium-crosswalk-efl,crosswalk-project/chromium-crosswalk-efl,mohamed--abdel-maksoud/chromium.src,hgl888/chromium-crosswalk,krieger-od/nwjs_chromium.src,hujiajie/pa-chromium,dednal/chromium.src,ondra-novak/chromium.src,bright-sparks/chromium-spacewalk,axinging/chromium-crosswalk,nacl-webkit/chrome_deps,markYoungH/chromium.src,patrickm/chromium.src,Fireblend/chromium-crosswalk,mogoweb/chromium-crosswalk,ltilve/chromium,Pluto-tv/chromium-crosswalk,littlstar/chromium.src,ltilve/chromium,pozdnyakov/chromium-crosswalk,M4sse/chromium.src,ondra-novak/chromium.src,TheTypoMaster/chromium-crosswalk,bright-sparks/chromium-spacewalk,Just-D/chromium-1,mogoweb/chromium-crosswalk,pozdnyakov/chromium-crosswalk,timopulkkinen/BubbleFish,dushu1203/chromium.src,nacl-webkit/chrome_deps,hgl888/chromium-crosswalk-efl,littlstar/chromium.src,axinging/chromium-crosswalk,Pluto-tv/chromium-crosswalk,hgl888/chromium-crosswalk-efl,ChromiumWebApps/chromium,Jonekee/chromium.src,patrickm/chromium.src
86c2486ab128f8e8651c53e54ac4ea9f72587c4b
chrome/test/ui/inspector_controller_uitest.cc
chrome/test/ui/inspector_controller_uitest.cc
// Copyright (c) 2006-2008 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "base/command_line.h" #include "base/no_windows2000_unittest.h" #include "base/win_util.h" #include "chrome/common/chrome_switches.h" #include "chrome/test/automation/browser_proxy.h" #include "chrome/test/automation/tab_proxy.h" #include "chrome/test/ui/ui_test.h" #include "net/url_request/url_request_unittest.h" // This test does not work on win2k. See http://b/1070036 class InspectorControllerTest : public NoWindows2000Test<UITest> { protected: TabProxy* GetActiveTabProxy() { scoped_ptr<BrowserProxy> window_proxy(automation()->GetBrowserWindow(0)); EXPECT_TRUE(window_proxy.get()); int active_tab_index = 0; EXPECT_TRUE(window_proxy->GetActiveTabIndex(&active_tab_index)); return window_proxy->GetTab(active_tab_index); } void NavigateTab(TabProxy* tab_proxy, const GURL& url) { ASSERT_TRUE(tab_proxy->NavigateToURL(url)); } }; // This test also does not work in single process. See http://b/1214920 TEST_F(InspectorControllerTest, InspectElement) { if (IsTestCaseDisabled()) return; if (CommandLine().HasSwitch(switches::kSingleProcess)) return; TestServer server(L"chrome/test/data"); ::scoped_ptr<TabProxy> tab(GetActiveTabProxy()); // We don't track resources until we've opened the inspector. NavigateTab(tab.get(), server.TestServerPageW(L"files/inspector/test1.html")); tab->InspectElement(0, 0); NavigateTab(tab.get(), server.TestServerPageW(L"files/inspector/test1.html")); EXPECT_EQ(1, tab->InspectElement(0, 0)); NavigateTab(tab.get(), server.TestServerPageW(L"files/inspector/test2.html")); EXPECT_EQ(2, tab->InspectElement(0, 0)); }
// Copyright (c) 2006-2008 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "base/command_line.h" #include "base/no_windows2000_unittest.h" #include "base/win_util.h" #include "chrome/common/chrome_switches.h" #include "chrome/test/automation/browser_proxy.h" #include "chrome/test/automation/tab_proxy.h" #include "chrome/test/ui/ui_test.h" #include "net/url_request/url_request_unittest.h" // This test does not work on win2k. See http://b/1070036 class InspectorControllerTest : public NoWindows2000Test<UITest> { protected: TabProxy* GetActiveTabProxy() { scoped_ptr<BrowserProxy> window_proxy(automation()->GetBrowserWindow(0)); EXPECT_TRUE(window_proxy.get()); int active_tab_index = 0; EXPECT_TRUE(window_proxy->GetActiveTabIndex(&active_tab_index)); return window_proxy->GetTab(active_tab_index); } void NavigateTab(TabProxy* tab_proxy, const GURL& url) { ASSERT_TRUE(tab_proxy->NavigateToURL(url)); } }; // This test also does not work in single process. See http://b/1214920 // Disabled, see http://crbug.com/4655 TEST_F(InspectorControllerTest, DISABLED_InspectElement) { if (IsTestCaseDisabled()) return; if (CommandLine().HasSwitch(switches::kSingleProcess)) return; TestServer server(L"chrome/test/data"); ::scoped_ptr<TabProxy> tab(GetActiveTabProxy()); // We don't track resources until we've opened the inspector. NavigateTab(tab.get(), server.TestServerPageW(L"files/inspector/test1.html")); tab->InspectElement(0, 0); NavigateTab(tab.get(), server.TestServerPageW(L"files/inspector/test1.html")); EXPECT_EQ(1, tab->InspectElement(0, 0)); NavigateTab(tab.get(), server.TestServerPageW(L"files/inspector/test2.html")); EXPECT_EQ(2, tab->InspectElement(0, 0)); }
Disable inspector UI test. Review URL: http://codereview.chromium.org/11340
Disable inspector UI test. Review URL: http://codereview.chromium.org/11340 git-svn-id: de016e52bd170d2d4f2344f9bf92d50478b649e0@5815 0039d316-1c4b-4281-b951-d872f2087c98
C++
bsd-3-clause
adobe/chromium,adobe/chromium,yitian134/chromium,Crystalnix/house-of-life-chromium,ropik/chromium,yitian134/chromium,gavinp/chromium,ropik/chromium,ropik/chromium,yitian134/chromium,adobe/chromium,yitian134/chromium,adobe/chromium,gavinp/chromium,ropik/chromium,yitian134/chromium,gavinp/chromium,adobe/chromium,ropik/chromium,gavinp/chromium,yitian134/chromium,adobe/chromium,Crystalnix/house-of-life-chromium,adobe/chromium,gavinp/chromium,Crystalnix/house-of-life-chromium,gavinp/chromium,adobe/chromium,Crystalnix/house-of-life-chromium,ropik/chromium,ropik/chromium,ropik/chromium,gavinp/chromium,adobe/chromium,gavinp/chromium,ropik/chromium,Crystalnix/house-of-life-chromium,yitian134/chromium,yitian134/chromium,Crystalnix/house-of-life-chromium,adobe/chromium,gavinp/chromium,Crystalnix/house-of-life-chromium,Crystalnix/house-of-life-chromium,Crystalnix/house-of-life-chromium,Crystalnix/house-of-life-chromium,yitian134/chromium,Crystalnix/house-of-life-chromium,adobe/chromium,yitian134/chromium,gavinp/chromium
2164ade80582b7a52c499d94551a56f9f01f28ea
thorlcr/thorutil/thmem.hpp
thorlcr/thorutil/thmem.hpp
/*############################################################################## Copyright (C) 2011 HPCC Systems. 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/>. ############################################################################## */ #ifndef __THMEM__ #define __THMEM__ #ifdef _WIN32 #ifdef GRAPH_EXPORTS #define graph_decl __declspec(dllexport) #else #define graph_decl __declspec(dllimport) #endif #else #define graph_decl #endif #include "jexcept.hpp" #include "jbuff.hpp" #include "jsort.hpp" #include "thormisc.hpp" #include "eclhelper.hpp" #include "rtlread_imp.hpp" #define NO_BWD_COMPAT_MAXSIZE #include "thorcommon.hpp" #include "thorcommon.ipp" interface IRecordSize; interface ILargeMemLimitNotify; interface ISortKeySerializer; interface ICompare; #ifdef _DEBUG #define TEST_ROW_LINKS //#define PARANOID_TEST_ROW_LINKS #endif //#define INCLUDE_POINTER_ARRAY_SIZE graph_decl void setThorInABox(unsigned num); // used for non-row allocations #define ThorMalloc(a) malloc(a) #define ThorRealloc(p,a) realloc(p,a) #define ThorFree(p) free(p) // --------------------------------------------------------- // Thor link counted rows // these may be inline later #ifdef TEST_ROW_LINKS #define TESTROW(r) if (r) { LinkThorRow(r); ReleaseThorRow(r); } #else #define TESTROW(r) #endif #ifdef PARANOID_TEST_ROW_LINKS #define PARANOIDTESTROW(r) if (r) { LinkThorRow(r); ReleaseThorRow(r); } #else #define PARANOIDTESTROW(r) #endif extern graph_decl void ReleaseThorRow(const void *ptr); extern graph_decl void ReleaseClearThorRow(const void *&ptr); extern graph_decl void LinkThorRow(const void *ptr); extern graph_decl bool isThorRowShared(const void *ptr); class OwnedConstThorRow { public: inline OwnedConstThorRow() { ptr = NULL; } inline OwnedConstThorRow(const void * _ptr) { TESTROW(_ptr); ptr = _ptr; } inline OwnedConstThorRow(const OwnedConstThorRow & other) { ptr = other.getLink(); } inline ~OwnedConstThorRow() { ReleaseThorRow(ptr); } private: /* these overloaded operators are the devil of memory leak. Use set, setown instead. */ void operator = (const void * _ptr) { set(_ptr); } void operator = (const OwnedConstThorRow & other) { set(other.get()); } /* this causes -ve memory leak */ void setown(const OwnedConstThorRow &other) { } public: inline const void * operator -> () const { PARANOIDTESTROW(ptr); return ptr; } inline operator const void *() const { PARANOIDTESTROW(ptr); return ptr; } inline void clear() { const void *temp=ptr; ptr=NULL; ReleaseThorRow(temp); } inline const void * get() const { PARANOIDTESTROW(ptr); return ptr; } inline const void * getClear() { const void * ret = ptr; ptr = NULL; TESTROW(ret); return ret; } inline const void * getLink() const { LinkThorRow(ptr); return ptr; } inline void set(const void * _ptr) { const void * temp = ptr; LinkThorRow(_ptr); ptr = _ptr; if (temp) ReleaseThorRow(temp); } inline void setown(const void * _ptr) { TESTROW(_ptr); const void * temp = ptr; ptr = _ptr; if (temp) ReleaseThorRow(temp); } inline void set(const OwnedConstThorRow &other) { set(other.get()); } inline void deserialize(IRowInterfaces *rowif, size32_t memsz, const void *mem) { if (memsz) { RtlDynamicRowBuilder rowBuilder(rowif->queryRowAllocator()); //GH->NH This now has a higher overhead than you are likely to want at this point... CThorStreamDeserializerSource dsz(memsz,mem); size32_t size = rowif->queryRowDeserializer()->deserialize(rowBuilder,dsz); setown(rowBuilder.finalizeRowClear(size)); } else clear(); } private: const void * ptr; }; interface IThorRowAllocator: extends IEngineRowAllocator { }; extern graph_decl void initThorMemoryManager(size32_t sz, unsigned memtracelevel, unsigned memstatinterval); extern graph_decl void resetThorMemoryManager(); extern graph_decl IThorRowAllocator *createThorRowAllocator(IOutputMetaData * _meta, unsigned _activityId); extern graph_decl IOutputMetaData *createOutputMetaDataWithExtra(IOutputMetaData *meta, size32_t sz); extern graph_decl IOutputMetaData *createOutputMetaDataWithChildRow(IEngineRowAllocator *childAllocator, size32_t extraSz); class CThorRowLinkCounter: public CSimpleInterface, implements IRowLinkCounter { public: IMPLEMENT_IINTERFACE_USING(CSimpleInterface); virtual void releaseRow(const void *row) { ReleaseThorRow(row); } virtual void linkRow(const void *row) { LinkThorRow(row); } }; extern graph_decl memsize_t ThorRowMemoryAvailable(); // --------------------------------------------------------- interface CLargeThorLinkedRowArrayOutOfMemException: extends IException { }; interface IThorRowSequenceCompare: implements ICompare, extends IInterface { }; #define PERROWOVERHEAD (sizeof(atomic_t) + sizeof(unsigned) + sizeof(void *)) // link + activityid + stable sort ptr interface IThorRowArrayException: extends IException { }; extern graph_decl void checkMultiThorMemoryThreshold(bool inc); extern graph_decl void setMultiThorMemoryNotify(size32_t size,ILargeMemLimitNotify *notify); class graph_decl CThorRowArray { MemoryBuffer ptrbuf; unsigned numelem; memsize_t totalsize; memsize_t maxtotal; size32_t overhead; Linked<IOutputRowSerializer> serializer; bool keepsize; bool sizing; bool raiseexceptions; memsize_t minRemaining; void adjSize(const void *row, bool inc); public: CThorRowArray() { numelem = 0; totalsize = 0; overhead = 0; sizing = false; raiseexceptions = false; memsize_t tmp = ((unsigned __int64)ThorRowMemoryAvailable())*7/8; // don't fill up completely if (tmp>0xffffffff) maxtotal = 0xffffffff; else maxtotal = (unsigned)tmp; if (maxtotal<0x100000) maxtotal = 0x100000; minRemaining = maxtotal/8; } ~CThorRowArray() { reset(true); } void reset(bool freeptrs) { const void ** row = (const void **)base(); unsigned remn = 0; while (numelem) { const void * r = *(row++); if (r) { remn++; ReleaseThorRow(r); } numelem--; } if (freeptrs) ptrbuf.resetBuffer(); else ptrbuf.setLength(0); if (sizing&&remn) checkMultiThorMemoryThreshold(false); totalsize = 0; overhead = 0; } inline void clear() { reset(true); } void append(const void *row) // takes ownership { if (sizing) adjSize(row,true); ptrbuf.append(sizeof(row),&row); numelem++; } void removeRows(unsigned i,unsigned n); inline const byte * item(unsigned idx) const { if (idx>=numelem) return NULL; return *(((const byte **)ptrbuf.toByteArray())+idx); } inline const byte ** base() const { return (const byte **)ptrbuf.toByteArray(); } inline const byte * itemClear(unsigned idx) // sets old to NULL { if (idx>=numelem) return NULL; byte ** rp = ((byte **)ptrbuf.toByteArray())+idx; const byte *ret = *rp; if (sizing) adjSize(ret,false); *rp = NULL; return ret; } inline unsigned ordinality() const { return numelem; } inline memsize_t totalSize() const { #ifdef _DEBUG assertex(sizing); #endif return totalsize; } void setMaxTotal(memsize_t tot) { maxtotal = tot; } inline memsize_t totalMem() { return #ifdef INCLUDE_POINTER_ARRAY_SIZE ptrbuf.length()+ptrbuf.capacity()+ #endif totalsize+overhead; } inline bool isFull() { memsize_t sz = totalMem(); #ifdef _DEBUG assertex(sizing&&!raiseexceptions); #endif if (sz>maxtotal) { #ifdef _DEBUG PROGLOG("CThorRowArray isFull(totalsize=%"I64F"u,ptrbuf.length()=%u,ptrbuf.capacity()=%u,overhead=%u,maxtotal=%"I64F"u", (unsigned __int64) totalsize,ptrbuf.length(),ptrbuf.capacity(),overhead,(unsigned __int64) maxtotal); #endif return true; } else { // maxtotal is estimate of how much this rowarray is using, but allocator may still be short of available memory. memsize_t asz = ThorRowMemoryAvailable(); if (asz < minRemaining) { #ifdef _DEBUG StringBuffer msg("CThorRowArray isFull(), ThorMemoryManager remaining() : "); PROGLOG("%s", msg.append(asz)); #endif return true; } else return false; } } void sort(ICompare & compare, bool stable) { unsigned n = ordinality(); if (n>1) { const byte ** res = base(); if (stable) { MemoryAttr tmp; void ** ptrs = (void **)tmp.allocate(n*sizeof(void *)); memcpy(ptrs,res,n*sizeof(void **)); parqsortvecstable(ptrs, n, compare, (void ***)res); // use res for index while (n--) { *res = **((byte ***)res); res++; } } else parqsortvec((void **)res, n, compare); } } void partition(ICompare & compare,unsigned num,UnsignedArray &out) // returns num+1 points { unsigned p=0; unsigned n = ordinality(); const byte **ptrs = (const byte **)ptrbuf.toByteArray(); while (num) { out.append(p); if (p<n) { unsigned q = p+(n-p)/num; if (p==q) { // skip to next group while (q<n) { q++; if ((q<n)&&(compare.docompare(ptrs[p],ptrs[q])!=0)) // ensure at next group break; } } else { while ((q<n)&&(q!=p)&&(compare.docompare(ptrs[q-1],ptrs[q])==0)) // ensure at start of group q--; } p = q; } num--; } out.append(n); } void setSizing(bool _sizing,bool _raiseexceptions) // ,IOutputRowSerializer *_serializer) { sizing = _sizing; raiseexceptions = _raiseexceptions; } unsigned load(IRowStream &stream,bool ungroup); // doesn't check for overflow unsigned load(IRowStream &stream, bool ungroup, bool &abort, bool *overflowed=NULL); unsigned load2(IRowStream &stream, bool ungroup, CThorRowArray &prev, IFile &savefile, IOutputRowSerializer *prevserializer, IEngineRowAllocator *preallocator, bool &prevsaved, bool &overflowed); IRowStream *createRowStream(unsigned start=0,unsigned num=(unsigned)-1, bool streamowns=true); unsigned save(IRowWriter *writer,unsigned start=0,unsigned num=(unsigned)-1, bool streamowns=true); void setNull(unsigned idx); void transfer(CThorRowArray &from); void swapWith(CThorRowArray &from); void serialize(IOutputRowSerializer *_serializer,IRowSerializerTarget &out); void serialize(IOutputRowSerializer *_serializer,MemoryBuffer &mb,bool hasnulls); unsigned serializeblk(IOutputRowSerializer *_serializer,MemoryBuffer &mb,size32_t dstmax, unsigned idx, unsigned count); void deserialize(IEngineRowAllocator &allocator,IOutputRowDeserializer *deserializer,size32_t sz,const void *buf,bool hasnulls); void deserializerow(IEngineRowAllocator &allocator,IOutputRowDeserializer *deserializer,IRowDeserializerSource &in); // NB single row not NULL void reorder(unsigned start,unsigned num, unsigned *neworder); void setRaiseExceptions(bool on=true) { raiseexceptions=on; } void reserve(unsigned n); void setRow(unsigned idx,const void *row) // takes ownership of row { assertex(idx<numelem); const byte ** rp = ((const byte **)ptrbuf.toByteArray())+idx; OwnedConstThorRow old = *rp; if (old&&sizing) adjSize(old,false); *rp = (const byte *)row; if (sizing) adjSize(row,true); } void ensure(unsigned size) { if (size<=numelem) return; reserve(size-numelem); } }; class CSDSServerStatus; extern graph_decl ILargeMemLimitNotify *createMultiThorResourceMutex(const char *grpname,CSDSServerStatus *status=NULL); extern graph_decl void setThorVMSwapDirectory(const char *swapdir); class IPerfMonHook; extern graph_decl IPerfMonHook *createThorMemStatsPerfMonHook(IPerfMonHook *chain=NULL); // for passing to jdebug startPerformanceMonitor extern graph_decl void setLCRrowCRCchecking(bool on=true); #endif
/*############################################################################## Copyright (C) 2011 HPCC Systems. 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/>. ############################################################################## */ #ifndef __THMEM__ #define __THMEM__ #ifdef _WIN32 #ifdef GRAPH_EXPORTS #define graph_decl __declspec(dllexport) #else #define graph_decl __declspec(dllimport) #endif #else #define graph_decl #endif #include "jexcept.hpp" #include "jbuff.hpp" #include "jsort.hpp" #include "thormisc.hpp" #include "eclhelper.hpp" #include "rtlread_imp.hpp" #define NO_BWD_COMPAT_MAXSIZE #include "thorcommon.hpp" #include "thorcommon.ipp" interface IRecordSize; interface ILargeMemLimitNotify; interface ISortKeySerializer; interface ICompare; #ifdef _DEBUG #define TEST_ROW_LINKS //#define PARANOID_TEST_ROW_LINKS #endif //#define INCLUDE_POINTER_ARRAY_SIZE graph_decl void setThorInABox(unsigned num); // used for non-row allocations #define ThorMalloc(a) malloc(a) #define ThorRealloc(p,a) realloc(p,a) #define ThorFree(p) free(p) // --------------------------------------------------------- // Thor link counted rows // these may be inline later #ifdef TEST_ROW_LINKS #define TESTROW(r) if (r) { LinkThorRow(r); ReleaseThorRow(r); } #else #define TESTROW(r) #endif #ifdef PARANOID_TEST_ROW_LINKS #define PARANOIDTESTROW(r) if (r) { LinkThorRow(r); ReleaseThorRow(r); } #else #define PARANOIDTESTROW(r) #endif extern graph_decl void ReleaseThorRow(const void *ptr); extern graph_decl void ReleaseClearThorRow(const void *&ptr); extern graph_decl void LinkThorRow(const void *ptr); extern graph_decl bool isThorRowShared(const void *ptr); class OwnedConstThorRow { public: inline OwnedConstThorRow() { ptr = NULL; } inline OwnedConstThorRow(const void * _ptr) { TESTROW(_ptr); ptr = _ptr; } inline OwnedConstThorRow(const OwnedConstThorRow & other) { ptr = other.getLink(); } inline ~OwnedConstThorRow() { ReleaseThorRow(ptr); } private: /* these overloaded operators are the devil of memory leak. Use set, setown instead. */ void operator = (const void * _ptr) { set(_ptr); } void operator = (const OwnedConstThorRow & other) { set(other.get()); } /* this causes -ve memory leak */ void setown(const OwnedConstThorRow &other) { } public: inline const void * operator -> () const { PARANOIDTESTROW(ptr); return ptr; } inline operator const void *() const { PARANOIDTESTROW(ptr); return ptr; } inline void clear() { const void *temp=ptr; ptr=NULL; ReleaseThorRow(temp); } inline const void * get() const { PARANOIDTESTROW(ptr); return ptr; } inline const void * getClear() { const void * ret = ptr; ptr = NULL; TESTROW(ret); return ret; } inline const void * getLink() const { LinkThorRow(ptr); return ptr; } inline void set(const void * _ptr) { const void * temp = ptr; LinkThorRow(_ptr); ptr = _ptr; if (temp) ReleaseThorRow(temp); } inline void setown(const void * _ptr) { TESTROW(_ptr); const void * temp = ptr; ptr = _ptr; if (temp) ReleaseThorRow(temp); } inline void set(const OwnedConstThorRow &other) { set(other.get()); } inline void deserialize(IRowInterfaces *rowif, size32_t memsz, const void *mem) { if (memsz) { RtlDynamicRowBuilder rowBuilder(rowif->queryRowAllocator()); //GH->NH This now has a higher overhead than you are likely to want at this point... CThorStreamDeserializerSource dsz(memsz,mem); size32_t size = rowif->queryRowDeserializer()->deserialize(rowBuilder,dsz); setown(rowBuilder.finalizeRowClear(size)); } else clear(); } private: const void * ptr; }; interface IThorRowAllocator: extends IEngineRowAllocator { }; extern graph_decl void initThorMemoryManager(size32_t sz, unsigned memtracelevel, unsigned memstatinterval); extern graph_decl void resetThorMemoryManager(); extern graph_decl IThorRowAllocator *createThorRowAllocator(IOutputMetaData * _meta, unsigned _activityId); extern graph_decl IOutputMetaData *createOutputMetaDataWithExtra(IOutputMetaData *meta, size32_t sz); extern graph_decl IOutputMetaData *createOutputMetaDataWithChildRow(IEngineRowAllocator *childAllocator, size32_t extraSz); class CThorRowLinkCounter: public CSimpleInterface, implements IRowLinkCounter { public: IMPLEMENT_IINTERFACE_USING(CSimpleInterface); virtual void releaseRow(const void *row) { ReleaseThorRow(row); } virtual void linkRow(const void *row) { LinkThorRow(row); } }; extern graph_decl memsize_t ThorRowMemoryAvailable(); // --------------------------------------------------------- interface CLargeThorLinkedRowArrayOutOfMemException: extends IException { }; interface IThorRowSequenceCompare: implements ICompare, extends IInterface { }; #define PERROWOVERHEAD (sizeof(atomic_t) + sizeof(unsigned) + sizeof(void *)) // link + activityid + stable sort ptr interface IThorRowArrayException: extends IException { }; extern graph_decl void checkMultiThorMemoryThreshold(bool inc); extern graph_decl void setMultiThorMemoryNotify(size32_t size,ILargeMemLimitNotify *notify); class graph_decl CThorRowArray { MemoryBuffer ptrbuf; unsigned numelem; memsize_t totalsize; memsize_t maxtotal; size32_t overhead; Linked<IOutputRowSerializer> serializer; bool keepsize; bool sizing; bool raiseexceptions; void adjSize(const void *row, bool inc); public: CThorRowArray() { numelem = 0; totalsize = 0; overhead = 0; sizing = false; raiseexceptions = false; memsize_t tmp = ((unsigned __int64)ThorRowMemoryAvailable())*7/8; // don't fill up completely if (tmp>0xffffffff) maxtotal = 0xffffffff; else maxtotal = (unsigned)tmp; if (maxtotal<0x100000) maxtotal = 0x100000; } ~CThorRowArray() { reset(true); } void reset(bool freeptrs) { const void ** row = (const void **)base(); unsigned remn = 0; while (numelem) { const void * r = *(row++); if (r) { remn++; ReleaseThorRow(r); } numelem--; } if (freeptrs) ptrbuf.resetBuffer(); else ptrbuf.setLength(0); if (sizing&&remn) checkMultiThorMemoryThreshold(false); totalsize = 0; overhead = 0; } inline void clear() { reset(true); } void append(const void *row) // takes ownership { if (sizing) adjSize(row,true); ptrbuf.append(sizeof(row),&row); numelem++; } void removeRows(unsigned i,unsigned n); inline const byte * item(unsigned idx) const { if (idx>=numelem) return NULL; return *(((const byte **)ptrbuf.toByteArray())+idx); } inline const byte ** base() const { return (const byte **)ptrbuf.toByteArray(); } inline const byte * itemClear(unsigned idx) // sets old to NULL { if (idx>=numelem) return NULL; byte ** rp = ((byte **)ptrbuf.toByteArray())+idx; const byte *ret = *rp; if (sizing) adjSize(ret,false); *rp = NULL; return ret; } inline unsigned ordinality() const { return numelem; } inline memsize_t totalSize() const { #ifdef _DEBUG assertex(sizing); #endif return totalsize; } void setMaxTotal(memsize_t tot) { maxtotal = tot; } inline memsize_t totalMem() { return #ifdef INCLUDE_POINTER_ARRAY_SIZE ptrbuf.length()+ptrbuf.capacity()+ #endif totalsize+overhead; } inline bool isFull() { memsize_t sz = totalMem(); #ifdef _DEBUG assertex(sizing&&!raiseexceptions); #endif if (sz>maxtotal) { #ifdef _DEBUG PROGLOG("CThorRowArray isFull(totalsize=%"I64F"u,ptrbuf.length()=%u,ptrbuf.capacity()=%u,overhead=%u,maxtotal=%"I64F"u", (unsigned __int64) totalsize,ptrbuf.length(),ptrbuf.capacity(),overhead,(unsigned __int64) maxtotal); #endif return true; } else return false; } void sort(ICompare & compare, bool stable) { unsigned n = ordinality(); if (n>1) { const byte ** res = base(); if (stable) { MemoryAttr tmp; void ** ptrs = (void **)tmp.allocate(n*sizeof(void *)); memcpy(ptrs,res,n*sizeof(void **)); parqsortvecstable(ptrs, n, compare, (void ***)res); // use res for index while (n--) { *res = **((byte ***)res); res++; } } else parqsortvec((void **)res, n, compare); } } void partition(ICompare & compare,unsigned num,UnsignedArray &out) // returns num+1 points { unsigned p=0; unsigned n = ordinality(); const byte **ptrs = (const byte **)ptrbuf.toByteArray(); while (num) { out.append(p); if (p<n) { unsigned q = p+(n-p)/num; if (p==q) { // skip to next group while (q<n) { q++; if ((q<n)&&(compare.docompare(ptrs[p],ptrs[q])!=0)) // ensure at next group break; } } else { while ((q<n)&&(q!=p)&&(compare.docompare(ptrs[q-1],ptrs[q])==0)) // ensure at start of group q--; } p = q; } num--; } out.append(n); } void setSizing(bool _sizing,bool _raiseexceptions) // ,IOutputRowSerializer *_serializer) { sizing = _sizing; raiseexceptions = _raiseexceptions; } unsigned load(IRowStream &stream,bool ungroup); // doesn't check for overflow unsigned load(IRowStream &stream, bool ungroup, bool &abort, bool *overflowed=NULL); unsigned load2(IRowStream &stream, bool ungroup, CThorRowArray &prev, IFile &savefile, IOutputRowSerializer *prevserializer, IEngineRowAllocator *preallocator, bool &prevsaved, bool &overflowed); IRowStream *createRowStream(unsigned start=0,unsigned num=(unsigned)-1, bool streamowns=true); unsigned save(IRowWriter *writer,unsigned start=0,unsigned num=(unsigned)-1, bool streamowns=true); void setNull(unsigned idx); void transfer(CThorRowArray &from); void swapWith(CThorRowArray &from); void serialize(IOutputRowSerializer *_serializer,IRowSerializerTarget &out); void serialize(IOutputRowSerializer *_serializer,MemoryBuffer &mb,bool hasnulls); unsigned serializeblk(IOutputRowSerializer *_serializer,MemoryBuffer &mb,size32_t dstmax, unsigned idx, unsigned count); void deserialize(IEngineRowAllocator &allocator,IOutputRowDeserializer *deserializer,size32_t sz,const void *buf,bool hasnulls); void deserializerow(IEngineRowAllocator &allocator,IOutputRowDeserializer *deserializer,IRowDeserializerSource &in); // NB single row not NULL void reorder(unsigned start,unsigned num, unsigned *neworder); void setRaiseExceptions(bool on=true) { raiseexceptions=on; } void reserve(unsigned n); void setRow(unsigned idx,const void *row) // takes ownership of row { assertex(idx<numelem); const byte ** rp = ((const byte **)ptrbuf.toByteArray())+idx; OwnedConstThorRow old = *rp; if (old&&sizing) adjSize(old,false); *rp = (const byte *)row; if (sizing) adjSize(row,true); } void ensure(unsigned size) { if (size<=numelem) return; reserve(size-numelem); } }; class CSDSServerStatus; extern graph_decl ILargeMemLimitNotify *createMultiThorResourceMutex(const char *grpname,CSDSServerStatus *status=NULL); extern graph_decl void setThorVMSwapDirectory(const char *swapdir); class IPerfMonHook; extern graph_decl IPerfMonHook *createThorMemStatsPerfMonHook(IPerfMonHook *chain=NULL); // for passing to jdebug startPerformanceMonitor extern graph_decl void setLCRrowCRCchecking(bool on=true); #endif
Rollback flawed memory frag. protetion
Rollback flawed memory frag. protetion A checked added to spot low memory conditions, when/if memory was fragmented was causing more problems than it fixed Signed-off-by: Jake Smith <[email protected]>
C++
agpl-3.0
afishbeck/HPCC-Platform,afishbeck/HPCC-Platform,afishbeck/HPCC-Platform,afishbeck/HPCC-Platform,afishbeck/HPCC-Platform,afishbeck/HPCC-Platform
319ad64e88d8f6ea2d487ee866f391654278ce1e
tml/src/tmlListenerObj.cpp
tml/src/tmlListenerObj.cpp
/* * libTML: A BEEP based Messaging Suite * Copyright (C) 2015 wobe-systems GmbH * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public License * as published by the Free Software Foundation; either version 2.1 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this program; if not, write to the Free * Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA * 02111-1307 USA * * You may find a copy of the license under this software is released * at COPYING file. This is LGPL software: you are welcome to develop * proprietary applications using this library without any royalty or * fee but returning back any change, improvement or addition in the * form of source code, project image, documentation patches, etc. * * Homepage: * http://www.libtml.org * * For professional support contact us: * * wobe-systems GmbH * [email protected] * * Contributors: * wobe-systems GmbH */ #include <stdio.h> #include <string.h> #include "tmlListenerObj.h" #include "tmlCore.h" #include "tmlCoreWrapper.h" #include "logValues.h" /** * @brief callback in case of new connection request */ axl_bool listenerObj_connection_accept_handler (VortexConnection * conn, axlPointer ptr) { VORTEXLimitCheckDataCallbackData* limitCheckData = (VORTEXLimitCheckDataCallbackData*) ptr; /* check if connection limit was reached */ limitCheckData->pLog->log (TML_LOG_VORTEX_CMD, "tmlListenerObj", "listenerObj_connection_accept_handler", "Vortex CMD", "vortex_connection_get_ctx"); VortexCtx* ctx = vortex_connection_get_ctx (conn); limitCheckData->pLog->log (TML_LOG_VORTEX_CMD, "tmlListenerObj", "listenerObj_connection_accept_handler", "Vortex CMD", "vortex_reader_connections_watched"); int iConnectionsWartched = vortex_reader_connections_watched (ctx); if (-1 != limitCheckData->iMax && iConnectionsWartched > limitCheckData->iMax) { return axl_false; } /* accept connection */ return axl_true; } /** * @brief Constructor. */ tmlListenerObj::tmlListenerObj(TML_CORE_HANDLE coreHandle, VortexCtx* ctx, const char* sNetAddress) { initListenerObj(coreHandle, ctx, sNetAddress); } /** * @brief Constructor. */ tmlListenerObj::tmlListenerObj(TML_CORE_HANDLE coreHandle, VortexCtx* ctx, const char* sHost, const char* sPort) { int iLength = strlen(sHost) + strlen(sPort) + 2; char* sNetAddress = new char[iLength]; #if defined(LINUX) || defined (MINGW_BUILD) sprintf(sNetAddress, "%s:%s", sHost, sPort); #else // LINUX sprintf_s(sNetAddress, iLength, "%s:%s", sHost, sPort); #endif // LINUX initListenerObj(coreHandle, ctx, sNetAddress); delete[]sNetAddress; } /** * @brief Destructor. */ tmlListenerObj::~tmlListenerObj() { cleanUp(); } /** * @brief init the object */ void tmlListenerObj::initListenerObj(TML_CORE_HANDLE coreHandle, VortexCtx* ctx, const char* sNetAddress){ m_ctx = ctx; m_bListnerIsEnabled = TML_FALSE; m_coreHandle = coreHandle; m_vortexConnection = NULL; m_binding = new tmlNetBinding(sNetAddress); tmlLogHandler* log = ((tmlCoreWrapper*)m_coreHandle)->getLogHandler(); m_connectionsLimitCheckData.iMax = -1; m_connectionsLimitCheckData.pLog = log; m_iRefCounter = 1; m_iErr = TML_SUCCESS; } /** * @brief Cleans up refCounter dependent allocations. */ void tmlListenerObj::cleanUp(){ if (getRef()){ if (decRef() == 0){ set_Enabled(TML_FALSE); delete m_binding; } } } /** * @brief Get the TML core handle. */ TML_CORE_HANDLE tmlListenerObj::getCoreHandle(){ return m_coreHandle; } /** * @brief Get the network hostname / IP of the listener binding. */ TML_INT32 tmlListenerObj::getHost(char** sHost){ TML_INT32 iRet = m_binding->getHost(sHost); return iRet; } /** * @brief Get the network hostname / IP of the listener binding. */ TML_INT32 tmlListenerObj::getHost(wchar_t** sHost){ TML_INT32 iRet = m_binding->getHost(sHost); return iRet; } /** * @brief Get the network hostname / IP of the listener binding. */ TML_INT32 tmlListenerObj::getHost(char16_t** sHost){ TML_INT32 iRet = m_binding->getHost(sHost); return iRet; } /** * @brief Get the network port of the listener binding. */ TML_INT32 tmlListenerObj::getPort(char** sPort){ TML_INT32 iRet = m_binding->getPort(sPort); return iRet; } /** * @brief Get the network port of the listener binding. */ TML_INT32 tmlListenerObj::getPort(wchar_t** sPort){ TML_INT32 iRet = m_binding->getPort(sPort); return iRet; } /** * @brief Get the network port of the listener binding. */ TML_INT32 tmlListenerObj::getPort(char16_t** sPort){ TML_INT32 iRet = m_binding->getPort(sPort); return iRet; } /** * @brief Get the network address of the listener binding. */ TML_INT32 tmlListenerObj::getAddress(char** sAddress){ TML_INT32 iRet = m_binding->getAddress(sAddress); return iRet; } /** * @brief Get the network address of the listener binding. */ TML_INT32 tmlListenerObj::getAddress(wchar_t** sAddress){ TML_INT32 iRet = m_binding->getAddress(sAddress); return iRet; } /** * @brief Get the network address of the listener binding. */ TML_INT32 tmlListenerObj::getAddress(char16_t** sAddress){ TML_INT32 iRet = m_binding->getAddress(sAddress); return iRet; } /** * @brief Check for equality of this listener with the requested parameter. */ bool tmlListenerObj::isEqual(const char* sAddress){ bool bEqual = false; char* sRefAddress; TML_INT32 iRet = getAddress(&sRefAddress); if (TML_SUCCESS == iRet){ if (0 == strcmp(sRefAddress, sAddress)){ bEqual = true; } } return bEqual; } /** * @brief Enable or disable the listener. */ TML_INT32 tmlListenerObj::set_Enabled(TML_BOOL bEnable){ TML_INT32 iRet = TML_SUCCESS; if (bEnable == m_bListnerIsEnabled){ iRet = TML_SUCCESS; } else{ tmlLogHandler* log = ((tmlCoreWrapper*)m_coreHandle)->getLogHandler(); if (!m_bListnerIsEnabled){ char* sHost; char* sPort; TML_BOOL bIsIPV6 = TML_FALSE; iRet = m_binding->getHost(&sHost); if (TML_SUCCESS == iRet){ iRet = m_binding->getPort(&sPort); } if (TML_SUCCESS == iRet){ bIsIPV6 = m_binding->isIPV6(); } if (TML_SUCCESS == iRet){ // create a vortex listener: if (bIsIPV6){ log->log (TML_LOG_VORTEX_CMD, "tmlListenerObj", "set_Enabled", "Vortex CMD", "vortex_listener_new"); m_vortexConnection = vortex_listener_new6 (m_ctx, sHost, sPort, NULL, NULL); } else{ log->log (TML_LOG_VORTEX_CMD, "tmlListenerObj", "set_Enabled", "Vortex CMD", "vortex_listener_new"); m_vortexConnection = vortex_listener_new (m_ctx, sHost, sPort, NULL, NULL); } // Check the vortex listener: log->log (TML_LOG_VORTEX_CMD, "tmlListenerObj", "set_Enabled", "Vortex CMD", "vortex_connection_is_ok"); if (! vortex_connection_is_ok (m_vortexConnection, axl_false)) { log->log (TML_LOG_VORTEX_CMD, "tmlListenerObj", "set_Enabled", "Vortex CMD", "vortex_connection_get_status"); VortexStatus status = vortex_connection_get_status (m_vortexConnection); log->log (TML_LOG_VORTEX_CMD, "tmlListenerObj", "set_Enabled", "Vortex CMD", "vortex_connection_get_message"); const char* msg = vortex_connection_get_message (m_vortexConnection); log->log ("tmlListenerObj", "tmlListenerObj:set_Enabled", "ERROR: failed to start listener, error msg", msg); // Error / unable to create the listener: log->log (TML_LOG_VORTEX_CMD, "tmlListenerObj", "set_Enabled", "Vortex CMD", "vortex_listener_shutdown"); vortex_listener_shutdown(m_vortexConnection, axl_true); m_vortexConnection = NULL; if (VortexBindError == status){ iRet = TML_ERR_LISTENER_ADDRESS_BINDING; } else{ iRet = TML_ERR_LISTENER_NOT_INITIALIZED; } } else{ ////////////////////////////////////////////////////////////// // in case of port equals 0 the vortex_listener_new will find // the next free port, so I want to know it's identification: log->log (TML_LOG_VORTEX_CMD, "tmlListenerObj", "set_Enabled", "Vortex CMD", "vortex_connection_get_port"); const char* resPort = vortex_connection_get_port(m_vortexConnection); if (NULL == resPort){ vortex_listener_shutdown(m_vortexConnection, axl_true); m_vortexConnection = NULL; iRet = TML_ERR_LISTENER_NOT_INITIALIZED; } else{ if (0 != strcmp(resPort, sPort)){ char* sHost; TML_BOOL bIsIPV6 = TML_FALSE; iRet = m_binding->getHost(&sHost); if (TML_SUCCESS == iRet){ bIsIPV6 = m_binding->isIPV6(); } if (TML_SUCCESS == iRet){ delete m_binding; char buffer[256]; if (bIsIPV6){ sprintf_s(buffer,256, "[%s]:%s", sHost, resPort); } else{ sprintf_s(buffer,256, "%s:%s", sHost, resPort); } m_binding = new tmlNetBinding(buffer); } } } } if (TML_SUCCESS == iRet){ /////////////////////////////////////////////////////////////////////////// // configure connection notification callback: log->log (TML_LOG_VORTEX_CMD, "tmlListenerObj", "set_Enabled", "Vortex CMD", "vortex_listener_set_on_connection_accepted"); vortex_listener_set_on_connection_accepted (m_ctx, listenerObj_connection_accept_handler, &m_connectionsLimitCheckData); } } } else{ if (NULL != m_vortexConnection){ log->log (TML_LOG_VORTEX_CMD, "tmlListenerObj", "set_Enabled", "Vortex CMD", "vortex_listener_shutdown"); vortex_listener_shutdown(m_vortexConnection, axl_true); /////////////////////////////////////////////////////////////////////////// // deregister connection notification callback: log->log (TML_LOG_VORTEX_CMD, "tmlListenerObj", "set_Enabled", "Vortex CMD", "vortex_listener_set_on_connection_accepted"); vortex_listener_set_on_connection_accepted (m_ctx, NULL, NULL); m_vortexConnection = NULL; } } // In case of TML_SUCCESS: if (TML_SUCCESS == iRet) m_bListnerIsEnabled = bEnable; } return iRet; } /** * @brief Get listener status. */ TML_BOOL tmlListenerObj::get_Enabled(){ return m_bListnerIsEnabled; } /** * @brief Decrement the reference counter value of this data object for the memory management. * */ int tmlListenerObj::decRef(){ return --m_iRefCounter; } /** * @brief Increment the reference counter value of this data object for the memory management. */ int tmlListenerObj::incRef(){ return ++m_iRefCounter; } /** * @brief Get the reference counter value of this data object for the memory management. */ int tmlListenerObj::getRef(){ return m_iRefCounter; } /** * @brief returns the last error code */ TML_INT32 tmlListenerObj::getLastErr(){ return m_iErr; } /** * @brief Get Vortex connection */ VortexConnection* tmlListenerObj::getVortexConnection(){ return m_vortexConnection; }
/* * libTML: A BEEP based Messaging Suite * Copyright (C) 2015 wobe-systems GmbH * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public License * as published by the Free Software Foundation; either version 2.1 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this program; if not, write to the Free * Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA * 02111-1307 USA * * You may find a copy of the license under this software is released * at COPYING file. This is LGPL software: you are welcome to develop * proprietary applications using this library without any royalty or * fee but returning back any change, improvement or addition in the * form of source code, project image, documentation patches, etc. * * Homepage: * http://www.libtml.org * * For professional support contact us: * * wobe-systems GmbH * [email protected] * * Contributors: * wobe-systems GmbH */ #include <stdio.h> #include <string.h> #include "tmlListenerObj.h" #include "tmlCore.h" #include "tmlCoreWrapper.h" #include "logValues.h" /** * @brief callback in case of new connection request */ axl_bool listenerObj_connection_accept_handler (VortexConnection * conn, axlPointer ptr) { VORTEXLimitCheckDataCallbackData* limitCheckData = (VORTEXLimitCheckDataCallbackData*) ptr; /* check if connection limit was reached */ limitCheckData->pLog->log (TML_LOG_VORTEX_CMD, "tmlListenerObj", "listenerObj_connection_accept_handler", "Vortex CMD", "vortex_connection_get_ctx"); VortexCtx* ctx = vortex_connection_get_ctx (conn); limitCheckData->pLog->log (TML_LOG_VORTEX_CMD, "tmlListenerObj", "listenerObj_connection_accept_handler", "Vortex CMD", "vortex_reader_connections_watched"); int iConnectionsWartched = vortex_reader_connections_watched (ctx); if (-1 != limitCheckData->iMax && iConnectionsWartched > limitCheckData->iMax) { return axl_false; } /* accept connection */ return axl_true; } /** * @brief Constructor. */ tmlListenerObj::tmlListenerObj(TML_CORE_HANDLE coreHandle, VortexCtx* ctx, const char* sNetAddress) { initListenerObj(coreHandle, ctx, sNetAddress); } /** * @brief Constructor. */ tmlListenerObj::tmlListenerObj(TML_CORE_HANDLE coreHandle, VortexCtx* ctx, const char* sHost, const char* sPort) { int iLength = strlen(sHost) + strlen(sPort) + 2; char* sNetAddress = new char[iLength]; #if defined(LINUX) || defined (MINGW_BUILD) sprintf(sNetAddress, "%s:%s", sHost, sPort); #else // LINUX sprintf_s(sNetAddress, iLength, "%s:%s", sHost, sPort); #endif // LINUX initListenerObj(coreHandle, ctx, sNetAddress); delete[]sNetAddress; } /** * @brief Destructor. */ tmlListenerObj::~tmlListenerObj() { cleanUp(); } /** * @brief init the object */ void tmlListenerObj::initListenerObj(TML_CORE_HANDLE coreHandle, VortexCtx* ctx, const char* sNetAddress){ m_ctx = ctx; m_bListnerIsEnabled = TML_FALSE; m_coreHandle = coreHandle; m_vortexConnection = NULL; m_binding = new tmlNetBinding(sNetAddress); tmlLogHandler* log = ((tmlCoreWrapper*)m_coreHandle)->getLogHandler(); m_connectionsLimitCheckData.iMax = -1; m_connectionsLimitCheckData.pLog = log; m_iRefCounter = 1; m_iErr = TML_SUCCESS; } /** * @brief Cleans up refCounter dependent allocations. */ void tmlListenerObj::cleanUp(){ if (getRef()){ if (decRef() == 0){ set_Enabled(TML_FALSE); delete m_binding; } } } /** * @brief Get the TML core handle. */ TML_CORE_HANDLE tmlListenerObj::getCoreHandle(){ return m_coreHandle; } /** * @brief Get the network hostname / IP of the listener binding. */ TML_INT32 tmlListenerObj::getHost(char** sHost){ TML_INT32 iRet = m_binding->getHost(sHost); return iRet; } /** * @brief Get the network hostname / IP of the listener binding. */ TML_INT32 tmlListenerObj::getHost(wchar_t** sHost){ TML_INT32 iRet = m_binding->getHost(sHost); return iRet; } /** * @brief Get the network hostname / IP of the listener binding. */ TML_INT32 tmlListenerObj::getHost(char16_t** sHost){ TML_INT32 iRet = m_binding->getHost(sHost); return iRet; } /** * @brief Get the network port of the listener binding. */ TML_INT32 tmlListenerObj::getPort(char** sPort){ TML_INT32 iRet = m_binding->getPort(sPort); return iRet; } /** * @brief Get the network port of the listener binding. */ TML_INT32 tmlListenerObj::getPort(wchar_t** sPort){ TML_INT32 iRet = m_binding->getPort(sPort); return iRet; } /** * @brief Get the network port of the listener binding. */ TML_INT32 tmlListenerObj::getPort(char16_t** sPort){ TML_INT32 iRet = m_binding->getPort(sPort); return iRet; } /** * @brief Get the network address of the listener binding. */ TML_INT32 tmlListenerObj::getAddress(char** sAddress){ TML_INT32 iRet = m_binding->getAddress(sAddress); return iRet; } /** * @brief Get the network address of the listener binding. */ TML_INT32 tmlListenerObj::getAddress(wchar_t** sAddress){ TML_INT32 iRet = m_binding->getAddress(sAddress); return iRet; } /** * @brief Get the network address of the listener binding. */ TML_INT32 tmlListenerObj::getAddress(char16_t** sAddress){ TML_INT32 iRet = m_binding->getAddress(sAddress); return iRet; } /** * @brief Check for equality of this listener with the requested parameter. */ bool tmlListenerObj::isEqual(const char* sAddress){ bool bEqual = false; char* sRefAddress; TML_INT32 iRet = getAddress(&sRefAddress); if (TML_SUCCESS == iRet){ if (0 == strcmp(sRefAddress, sAddress)){ bEqual = true; } } return bEqual; } /** * @brief Enable or disable the listener. */ TML_INT32 tmlListenerObj::set_Enabled(TML_BOOL bEnable){ TML_INT32 iRet = TML_SUCCESS; if (bEnable == m_bListnerIsEnabled){ iRet = TML_SUCCESS; } else{ tmlLogHandler* log = ((tmlCoreWrapper*)m_coreHandle)->getLogHandler(); if (!m_bListnerIsEnabled){ char* sHost; char* sPort; TML_BOOL bIsIPV6 = TML_FALSE; iRet = m_binding->getHost(&sHost); if (TML_SUCCESS == iRet){ iRet = m_binding->getPort(&sPort); } if (TML_SUCCESS == iRet){ bIsIPV6 = m_binding->isIPV6(); } if (TML_SUCCESS == iRet){ // create a vortex listener: if (bIsIPV6){ log->log (TML_LOG_VORTEX_CMD, "tmlListenerObj", "set_Enabled", "Vortex CMD", "vortex_listener_new"); m_vortexConnection = vortex_listener_new6 (m_ctx, sHost, sPort, NULL, NULL); } else{ log->log (TML_LOG_VORTEX_CMD, "tmlListenerObj", "set_Enabled", "Vortex CMD", "vortex_listener_new"); m_vortexConnection = vortex_listener_new (m_ctx, sHost, sPort, NULL, NULL); } // Check the vortex listener: log->log (TML_LOG_VORTEX_CMD, "tmlListenerObj", "set_Enabled", "Vortex CMD", "vortex_connection_is_ok"); if (! vortex_connection_is_ok (m_vortexConnection, axl_false)) { log->log (TML_LOG_VORTEX_CMD, "tmlListenerObj", "set_Enabled", "Vortex CMD", "vortex_connection_get_status"); VortexStatus status = vortex_connection_get_status (m_vortexConnection); log->log (TML_LOG_VORTEX_CMD, "tmlListenerObj", "set_Enabled", "Vortex CMD", "vortex_connection_get_message"); const char* msg = vortex_connection_get_message (m_vortexConnection); log->log ("tmlListenerObj", "tmlListenerObj:set_Enabled", "ERROR: failed to start listener, error msg", msg); // Error / unable to create the listener: log->log (TML_LOG_VORTEX_CMD, "tmlListenerObj", "set_Enabled", "Vortex CMD", "vortex_listener_shutdown"); vortex_listener_shutdown(m_vortexConnection, axl_true); m_vortexConnection = NULL; if (VortexBindError == status){ iRet = TML_ERR_LISTENER_ADDRESS_BINDING; } else{ iRet = TML_ERR_LISTENER_NOT_INITIALIZED; } } else{ ////////////////////////////////////////////////////////////// // in case of port equals 0 the vortex_listener_new will find // the next free port, so I want to know it's identification: log->log (TML_LOG_VORTEX_CMD, "tmlListenerObj", "set_Enabled", "Vortex CMD", "vortex_connection_get_port"); const char* resPort = vortex_connection_get_port(m_vortexConnection); if (NULL == resPort){ vortex_listener_shutdown(m_vortexConnection, axl_true); m_vortexConnection = NULL; iRet = TML_ERR_LISTENER_NOT_INITIALIZED; } else{ if (0 != strcmp(resPort, sPort)){ char* sHost; TML_BOOL bIsIPV6 = TML_FALSE; iRet = m_binding->getHost(&sHost); if (TML_SUCCESS == iRet){ bIsIPV6 = m_binding->isIPV6(); } if (TML_SUCCESS == iRet){ delete m_binding; char buffer[256]; if (bIsIPV6){ #if defined(LINUX) || defined (MINGW_BUILD) sprintf(buffer, "[%s]:%s", sHost, resPort); #else // LINUX sprintf_s(buffer,256, "[%s]:%s", sHost, resPort); #endif // LINUX } else{ #if defined(LINUX) || defined (MINGW_BUILD) sprintf(buffer, "%s:%s", sHost, resPort); #else // LINUX sprintf_s(buffer,256, "%s:%s", sHost, resPort); #endif // LINUX } m_binding = new tmlNetBinding(buffer); } } } } if (TML_SUCCESS == iRet){ /////////////////////////////////////////////////////////////////////////// // configure connection notification callback: log->log (TML_LOG_VORTEX_CMD, "tmlListenerObj", "set_Enabled", "Vortex CMD", "vortex_listener_set_on_connection_accepted"); vortex_listener_set_on_connection_accepted (m_ctx, listenerObj_connection_accept_handler, &m_connectionsLimitCheckData); } } } else{ if (NULL != m_vortexConnection){ log->log (TML_LOG_VORTEX_CMD, "tmlListenerObj", "set_Enabled", "Vortex CMD", "vortex_listener_shutdown"); vortex_listener_shutdown(m_vortexConnection, axl_true); /////////////////////////////////////////////////////////////////////////// // deregister connection notification callback: log->log (TML_LOG_VORTEX_CMD, "tmlListenerObj", "set_Enabled", "Vortex CMD", "vortex_listener_set_on_connection_accepted"); vortex_listener_set_on_connection_accepted (m_ctx, NULL, NULL); m_vortexConnection = NULL; } } // In case of TML_SUCCESS: if (TML_SUCCESS == iRet) m_bListnerIsEnabled = bEnable; } return iRet; } /** * @brief Get listener status. */ TML_BOOL tmlListenerObj::get_Enabled(){ return m_bListnerIsEnabled; } /** * @brief Decrement the reference counter value of this data object for the memory management. * */ int tmlListenerObj::decRef(){ return --m_iRefCounter; } /** * @brief Increment the reference counter value of this data object for the memory management. */ int tmlListenerObj::incRef(){ return ++m_iRefCounter; } /** * @brief Get the reference counter value of this data object for the memory management. */ int tmlListenerObj::getRef(){ return m_iRefCounter; } /** * @brief returns the last error code */ TML_INT32 tmlListenerObj::getLastErr(){ return m_iErr; } /** * @brief Get Vortex connection */ VortexConnection* tmlListenerObj::getVortexConnection(){ return m_vortexConnection; }
Implement API into libTML-c library to handle multiple listener instances
Implement API into libTML-c library to handle multiple listener instances
C++
lgpl-2.1
tml21/libtml-c,tml21/libtml-c
9d70b6b306a44d98c5d87f40526666b4ebd107c3
tools/llvm-ld/Optimize.cpp
tools/llvm-ld/Optimize.cpp
//===- Optimize.cpp - Optimize a complete program -------------------------===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // This file implements all optimization of the linked module for llvm-ld. // //===----------------------------------------------------------------------===// #include "llvm/Module.h" #include "llvm/PassManager.h" #include "llvm/Support/CommandLine.h" #include "llvm/Support/StandardPasses.h" #include "llvm/Support/raw_ostream.h" #include "llvm/Support/DynamicLibrary.h" #include "llvm/Target/TargetData.h" #include "llvm/Target/TargetMachine.h" #include "llvm/Support/PassNameParser.h" #include "llvm/Support/PluginLoader.h" using namespace llvm; // Pass Name Options as generated by the PassNameParser static cl::list<const PassInfo*, bool, PassNameParser> OptimizationList(cl::desc("Optimizations available:")); //Don't verify at the end static cl::opt<bool> DontVerify("disable-verify", cl::ReallyHidden); static cl::opt<bool> DisableInline("disable-inlining", cl::desc("Do not run the inliner pass")); static cl::opt<bool> DisableOptimizations("disable-opt", cl::desc("Do not run any optimization passes")); static cl::opt<bool> DisableInternalize("disable-internalize", cl::desc("Do not mark all symbols as internal")); static cl::opt<bool> VerifyEach("verify-each", cl::desc("Verify intermediate results of all passes")); static cl::alias ExportDynamic("export-dynamic", cl::aliasopt(DisableInternalize), cl::desc("Alias for -disable-internalize")); static cl::opt<bool> Strip("strip-all", cl::desc("Strip all symbol info from executable")); static cl::alias A0("s", cl::desc("Alias for --strip-all"), cl::aliasopt(Strip)); static cl::opt<bool> StripDebug("strip-debug", cl::desc("Strip debugger symbol info from executable")); static cl::alias A1("S", cl::desc("Alias for --strip-debug"), cl::aliasopt(StripDebug)); // A utility function that adds a pass to the pass manager but will also add // a verifier pass after if we're supposed to verify. static inline void addPass(PassManager &PM, Pass *P) { // Add the pass to the pass manager... PM.add(P); // If we are verifying all of the intermediate steps, add the verifier... if (VerifyEach) PM.add(createVerifierPass()); } namespace llvm { /// Optimize - Perform link time optimizations. This will run the scalar /// optimizations, any loaded plugin-optimization modules, and then the /// inter-procedural optimizations if applicable. void Optimize(Module* M) { // Instantiate the pass manager to organize the passes. PassManager Passes; // If we're verifying, start off with a verification pass. if (VerifyEach) Passes.add(createVerifierPass()); // Add an appropriate TargetData instance for this module... addPass(Passes, new TargetData(M)); if (!DisableOptimizations) createStandardLTOPasses(&Passes, !DisableInternalize, !DisableInline, VerifyEach); // If the -s or -S command line options were specified, strip the symbols out // of the resulting program to make it smaller. -s and -S are GNU ld options // that we are supporting; they alias -strip-all and -strip-debug. if (Strip || StripDebug) addPass(Passes, createStripSymbolsPass(StripDebug && !Strip)); // Create a new optimization pass for each one specified on the command line std::auto_ptr<TargetMachine> target; for (unsigned i = 0; i < OptimizationList.size(); ++i) { const PassInfo *Opt = OptimizationList[i]; if (Opt->getNormalCtor()) addPass(Passes, Opt->getNormalCtor()()); else errs() << "llvm-ld: cannot create pass: " << Opt->getPassName() << "\n"; } // The user's passes may leave cruft around. Clean up after them them but // only if we haven't got DisableOptimizations set if (!DisableOptimizations) { addPass(Passes, createInstructionCombiningPass()); addPass(Passes, createCFGSimplificationPass()); addPass(Passes, createAggressiveDCEPass()); addPass(Passes, createGlobalDCEPass()); } // Make sure everything is still good. if (!DontVerify) Passes.add(createVerifierPass()); // Run our queue of passes all at once now, efficiently. Passes.run(*M); } }
//===- Optimize.cpp - Optimize a complete program -------------------------===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // This file implements all optimization of the linked module for llvm-ld. // //===----------------------------------------------------------------------===// #include "llvm/Module.h" #include "llvm/Support/CommandLine.h" #include "llvm/Support/PassMAnagerBuilder.h" #include "llvm/Support/raw_ostream.h" #include "llvm/Support/DynamicLibrary.h" #include "llvm/Target/TargetData.h" #include "llvm/Target/TargetMachine.h" #include "llvm/Support/PassNameParser.h" #include "llvm/Support/PluginLoader.h" using namespace llvm; // Pass Name Options as generated by the PassNameParser static cl::list<const PassInfo*, bool, PassNameParser> OptimizationList(cl::desc("Optimizations available:")); //Don't verify at the end static cl::opt<bool> DontVerify("disable-verify", cl::ReallyHidden); static cl::opt<bool> DisableInline("disable-inlining", cl::desc("Do not run the inliner pass")); static cl::opt<bool> DisableOptimizations("disable-opt", cl::desc("Do not run any optimization passes")); static cl::opt<bool> DisableInternalize("disable-internalize", cl::desc("Do not mark all symbols as internal")); static cl::opt<bool> VerifyEach("verify-each", cl::desc("Verify intermediate results of all passes")); static cl::alias ExportDynamic("export-dynamic", cl::aliasopt(DisableInternalize), cl::desc("Alias for -disable-internalize")); static cl::opt<bool> Strip("strip-all", cl::desc("Strip all symbol info from executable")); static cl::alias A0("s", cl::desc("Alias for --strip-all"), cl::aliasopt(Strip)); static cl::opt<bool> StripDebug("strip-debug", cl::desc("Strip debugger symbol info from executable")); static cl::alias A1("S", cl::desc("Alias for --strip-debug"), cl::aliasopt(StripDebug)); // A utility function that adds a pass to the pass manager but will also add // a verifier pass after if we're supposed to verify. static inline void addPass(PassManager &PM, Pass *P) { // Add the pass to the pass manager... PM.add(P); // If we are verifying all of the intermediate steps, add the verifier... if (VerifyEach) PM.add(createVerifierPass()); } namespace llvm { /// Optimize - Perform link time optimizations. This will run the scalar /// optimizations, any loaded plugin-optimization modules, and then the /// inter-procedural optimizations if applicable. void Optimize(Module *M) { // Instantiate the pass manager to organize the passes. PassManager Passes; // If we're verifying, start off with a verification pass. if (VerifyEach) Passes.add(createVerifierPass()); // Add an appropriate TargetData instance for this module... addPass(Passes, new TargetData(M)); if (!DisableOptimizations) PassManagerBuilder().populateLTOPassManager(Passes, !DisableInternalize, !DisableInline); // If the -s or -S command line options were specified, strip the symbols out // of the resulting program to make it smaller. -s and -S are GNU ld options // that we are supporting; they alias -strip-all and -strip-debug. if (Strip || StripDebug) addPass(Passes, createStripSymbolsPass(StripDebug && !Strip)); // Create a new optimization pass for each one specified on the command line std::auto_ptr<TargetMachine> target; for (unsigned i = 0; i < OptimizationList.size(); ++i) { const PassInfo *Opt = OptimizationList[i]; if (Opt->getNormalCtor()) addPass(Passes, Opt->getNormalCtor()()); else errs() << "llvm-ld: cannot create pass: " << Opt->getPassName() << "\n"; } // The user's passes may leave cruft around. Clean up after them them but // only if we haven't got DisableOptimizations set if (!DisableOptimizations) { addPass(Passes, createInstructionCombiningPass()); addPass(Passes, createCFGSimplificationPass()); addPass(Passes, createAggressiveDCEPass()); addPass(Passes, createGlobalDCEPass()); } // Make sure everything is still good. if (!DontVerify) Passes.add(createVerifierPass()); // Run our queue of passes all at once now, efficiently. Passes.run(*M); } }
switch llvm-ld. It has a terrible mechanism that people can add extra passes, it should be converted to use extension points.
switch llvm-ld. It has a terrible mechanism that people can add extra passes, it should be converted to use extension points. git-svn-id: 0ff597fd157e6f4fc38580e8d64ab130330d2411@131823 91177308-0d34-0410-b5e6-96231b3b80d8
C++
apache-2.0
apple/swift-llvm,apple/swift-llvm,dslab-epfl/asap,llvm-mirror/llvm,chubbymaggie/asap,llvm-mirror/llvm,llvm-mirror/llvm,GPUOpen-Drivers/llvm,apple/swift-llvm,llvm-mirror/llvm,apple/swift-llvm,llvm-mirror/llvm,chubbymaggie/asap,GPUOpen-Drivers/llvm,apple/swift-llvm,GPUOpen-Drivers/llvm,GPUOpen-Drivers/llvm,chubbymaggie/asap,llvm-mirror/llvm,GPUOpen-Drivers/llvm,dslab-epfl/asap,GPUOpen-Drivers/llvm,apple/swift-llvm,apple/swift-llvm,dslab-epfl/asap,chubbymaggie/asap,GPUOpen-Drivers/llvm,GPUOpen-Drivers/llvm,dslab-epfl/asap,chubbymaggie/asap,llvm-mirror/llvm,dslab-epfl/asap,dslab-epfl/asap,chubbymaggie/asap,dslab-epfl/asap,llvm-mirror/llvm,llvm-mirror/llvm,apple/swift-llvm
8320a90992a1ddd9cfa717009c4a2f4116487666
tree/src/TBranchObject.cxx
tree/src/TBranchObject.cxx
// @(#)root/tree:$Name: $:$Id: TBranchObject.cxx,v 1.12 2001/03/12 07:19:03 brun Exp $ // Author: Rene Brun 11/02/96 /************************************************************************* * Copyright (C) 1995-2000, Rene Brun and Fons Rademakers. * * All rights reserved. * * * * For the licensing terms see $ROOTSYS/LICENSE. * * For the list of contributors see $ROOTSYS/README/CREDITS. * *************************************************************************/ ////////////////////////////////////////////////////////////////////////// // // // TBranchObject // // // // A Branch for the case of an object // // // // ////////////////////////////////////////////////////////////////////////// #include "TROOT.h" #include "TFile.h" #include "TBranchObject.h" #include "TBranchClones.h" #include "TTree.h" #include "TBasket.h" #include "TLeafObject.h" #include "TVirtualPad.h" #include "TClass.h" #include "TRealData.h" #include "TDataType.h" #include "TDataMember.h" #include "TBrowser.h" R__EXTERN TTree *gTree; ClassImp(TBranchObject) //______________________________________________________________________________ TBranchObject::TBranchObject(): TBranch() { //*-*-*-*-*-*Default constructor for BranchObject*-*-*-*-*-*-*-*-*-* //*-* ==================================== fNleaves = 1; fOldObject = 0; } //______________________________________________________________________________ TBranchObject::TBranchObject(const char *name, const char *classname, void *addobj, Int_t basketsize, Int_t splitlevel, Int_t compress) :TBranch() { //*-*-*-*-*-*-*-*-*-*-*-*-*Create a BranchObject*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-* //*-* ===================== // TClass *cl = gROOT->GetClass(classname); if (!cl) { Error("TBranchObject","Cannot find class:%s",classname); return; } char **apointer = (char**)(addobj); TObject *obj = (TObject*)(*apointer); Bool_t delobj = kFALSE; if (!obj) { obj = (TObject*)cl->New(); delobj = kTRUE; } gTree->BuildStreamerInfo(cl,obj); if (delobj) delete obj; SetName(name); SetTitle(name); fCompress = compress; if (compress == -1) { TFile *bfile = gTree->GetDirectory()->GetFile(); if (bfile) fCompress = bfile->GetCompressionLevel(); } if (basketsize < 100) basketsize = 100; fBasketSize = basketsize; fAddress = (char*)addobj; fClassName = classname; fBasketEntry = new Int_t[fMaxBaskets]; fBasketBytes = new Int_t[fMaxBaskets]; fBasketSeek = new Seek_t[fMaxBaskets]; fOldObject = 0; fBasketEntry[0] = fEntryNumber; fBasketBytes[0] = 0; TLeaf *leaf = new TLeafObject(name,classname); leaf->SetBranch(this); leaf->SetAddress(addobj); fNleaves = 1; fLeaves.Add(leaf); gTree->GetListOfLeaves()->Add(leaf); // Set the bit kAutoDelete to specify that when reading // in TLeafObject::ReadBasket, the object should be deleted // before calling Streamer. // It is foreseen to not set this bit in a future version. SetAutoDelete(kTRUE); fTree = gTree; fDirectory = fTree->GetDirectory(); fFileName = ""; //*-*- Create the first basket if (splitlevel) return; TBasket *basket = new TBasket(name,fTree->GetName(),this); fBaskets.Add(basket); } //______________________________________________________________________________ TBranchObject::~TBranchObject() { //*-*-*-*-*-*Default destructor for a BranchObject*-*-*-*-*-*-*-*-*-*-*-* //*-* ===================================== fBranches.Delete(); } //______________________________________________________________________________ void TBranchObject::Browse(TBrowser *b) { Int_t nbranches = fBranches.GetEntriesFast(); if (nbranches > 1) { fBranches.Browse( b ); } } //______________________________________________________________________________ Int_t TBranchObject::Fill() { //*-*-*-*-*-*-*-*Loop on all leaves of this branch to fill Basket buffer*-*-* //*-* ======================================================= Int_t nbytes = 0; Int_t i; Int_t nbranches = fBranches.GetEntriesFast(); if (nbranches) { fEntries++; UpdateAddress(); for (i=0;i<nbranches;i++) { TBranch *branch = (TBranch*)fBranches[i]; if (!branch->TestBit(kDoNotProcess)) nbytes += branch->Fill(); } } else { if (!TestBit(kDoNotProcess)) nbytes += TBranch::Fill(); } return nbytes; } //______________________________________________________________________________ Int_t TBranchObject::GetEntry(Int_t entry, Int_t getall) { //*-*-*-*-*Read all branches of a BranchObject and return total number of bytes //*-* ==================================================================== // If entry = 0 take current entry number + 1 // If entry < 0 reset entry number to 0 // // The function returns the number of bytes read from the input buffer. // If entry does not exist or an I/O error occurs, the function returns 0. // if entry is the same as the previous call, the function returns 1. if (TestBit(kDoNotProcess) && !getall) return 0; Int_t nbytes; Int_t nbranches = fBranches.GetEntriesFast(); if (nbranches) { if (fAddress == 0) { // try to create object if (!TestBit(kWarn)) { TClass *cl = gROOT->GetClass(fClassName); if (cl) { TObject** voidobj = (TObject**) new Long_t[1]; *voidobj = (TObject*)cl->New(); SetAddress(voidobj); } else { Warning("GetEntry","Cannot get class: %s",fClassName.Data()); SetBit(kWarn); } } } nbytes = 0; for (Int_t i=0;i<nbranches;i++) { TBranch *branch = (TBranch*)fBranches[i]; nbytes += branch->GetEntry(entry); } } else { nbytes = TBranch::GetEntry(entry); } return nbytes; } //______________________________________________________________________________ Bool_t TBranchObject::IsFolder() const { //*-*-*-*-*Return TRUE if more than one leaf, FALSE otherwise*-* //*-* ================================================== Int_t nbranches = fBranches.GetEntriesFast(); if (nbranches >= 1) return kTRUE; else return kFALSE; } //______________________________________________________________________________ void TBranchObject::Print(Option_t *option) const { //*-*-*-*-*-*-*-*-*-*-*-*Print TBranch parameters*-*-*-*-*-*-*-*-*-*-*-*-*-*-* //*-* ======================== Int_t i; Int_t nbranches = fBranches.GetEntriesFast(); if (nbranches) { Printf("*Branch :%-9s : %-54s *",GetName(),GetTitle()); Printf("*Entries : %8d : BranchObject (see below) *",Int_t(fEntries)); Printf("*............................................................................*"); for (i=0;i<nbranches;i++) { TBranch *branch = (TBranch*)fBranches.At(i); if (branch) branch->Print(option); } } else { TBranch::Print(option); } } //______________________________________________________________________________ void TBranchObject::Reset(Option_t *option) { //*-*-*-*-*-*-*-*Reset a Branch*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-* //*-* ==================== // // Existing buffers are deleted // Entries, max and min are reset // TBranch::Reset(option); Int_t i; Int_t nbranches = fBranches.GetEntriesFast(); for (i=0;i<nbranches;i++) { TBranch *branch = (TBranch*)fBranches[i]; branch->Reset(option); } } //______________________________________________________________________________ void TBranchObject::SetAddress(void *add) { //*-*-*-*-*-*-*-*Set address of this branch*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-* //*-* ==================== // //special case when called from code generated by TTree::MakeClass if (Long_t(add) == -1) { SetBit(kWarn); return; } fReadEntry = -1; Int_t nbranches = fBranches.GetEntriesFast(); TLeaf *leaf = (TLeaf*)fLeaves.UncheckedAt(0); if (leaf) leaf->SetAddress(add); TBranch *branch; fAddress = (char*)add; char *pointer = fAddress; void **ppointer = (void**)add; TObject *obj = 0; if (add) obj = (TObject*)(*ppointer); TClass *cl = gROOT->GetClass(fClassName.Data()); if (!obj && cl) { obj = (TObject*)cl->New(); *ppointer = (void*)obj; } //fOldObject = obj; Int_t i, offset; if (!cl) { for (i=0;i<nbranches;i++) { branch = (TBranch*)fBranches[i]; pointer = (char*)obj; branch->SetAddress(pointer); } return; } if (!cl->GetListOfRealData()) cl->BuildRealData(obj); char *fullname = new char[200]; const char *bname = GetName(); Int_t lenName = strlen(bname); Int_t isDot = 0; if (bname[lenName-1] == '.') isDot = 1; const char *rdname; TRealData *rd; TIter next(cl->GetListOfRealData()); while ((rd = (TRealData *) next())) { TDataMember *dm = rd->GetDataMember(); if (!dm->IsPersistent()) continue; rdname = rd->GetName(); TDataType *dtype = dm->GetDataType(); Int_t code = 0; if (dtype) code = dm->GetDataType()->GetType(); offset = rd->GetThisOffset(); pointer = (char*)obj + offset; branch = 0; if (dm->IsaPointer()) { TClass *clobj = 0; if (!dm->IsBasic()) clobj = gROOT->GetClass(dm->GetTypeName()); if (clobj && clobj->InheritsFrom("TClonesArray")) { if (isDot) sprintf(fullname,"%s%s",bname,&rdname[1]); else sprintf(fullname,"%s",&rdname[1]); branch = (TBranch*)fBranches.FindObject(fullname); } else { if (!clobj) { // this is a basic type we can handle only if // he has a dimension: const char * index = dm->GetArrayIndex(); if (strlen(index)==0) { if (code==1) { // Case of a string ... we do not need the size if (isDot) sprintf(fullname,"%s%s",bname,&rdname[0]); else sprintf(fullname,"%s",&rdname[0]); } else { continue; } } if (isDot) sprintf(fullname,"%s%s",bname,&rdname[0]); else sprintf(fullname,"%s",&rdname[0]); // let's remove the stars! UInt_t cursor,pos; for( cursor = 0, pos = 0; cursor < strlen(fullname); cursor ++ ) { if (fullname[cursor]!='*') { fullname[pos++] = fullname[cursor]; }; }; fullname[pos] = '\0'; branch = (TBranch*)fBranches.FindObject(fullname); } else { if (!clobj->InheritsFrom(TObject::Class())) continue; if (isDot) sprintf(fullname,"%s%s",bname,&rdname[1]); else sprintf(fullname,"%s",&rdname[1]); branch = (TBranch*)fBranches.FindObject(fullname); } } } else { if (dm->IsBasic()) { if (isDot) sprintf(fullname,"%s%s",bname,&rdname[0]); else sprintf(fullname,"%s",&rdname[0]); branch = (TBranch*)fBranches.FindObject(fullname); } } if(branch) branch->SetAddress(pointer); } delete [] fullname; } //______________________________________________________________________________ void TBranchObject::SetAutoDelete(Bool_t autodel) { //*-*-*-*-*-*-*-*Set the AutoDelete bit //*-* ==================== // This function can be used to instruct Root in TBranchObject::ReadBasket // to not delete the object referenced by a branchobject before reading a // new entry. By default, the object is deleted. // If autodel is kTRUE, this existing object will be deleted, a new object // created by the default constructor, then object->Streamer called. // If autodel is kFALSE, the existing object is not deleted. Root assumes // that the user is taking care of deleting any internal object or array // This can be done in Streamer itself. // If this branch has sub-branches, the function sets autodel for these // branches as well. // We STRONGLY suggest to activate this option by default when you create // the top level branch. This will make the read phase more efficient // because it minimizes the numbers of new/delete operations. // Once this option has been set and the Tree is written to a file, it is // not necessary to specify the option again when reading, unless you // want to set the opposite mode. // TBranch::SetAutoDelete(autodel); Int_t nbranches = fBranches.GetEntriesFast(); for (Int_t i=0;i<nbranches;i++) { TBranch *branch = (TBranch*)fBranches[i]; branch->SetAutoDelete(autodel); } } //______________________________________________________________________________ void TBranchObject::SetBasketSize(Int_t buffsize) { //*-*-*-*-*-*-*-*Reset basket size for all subbranches of this branchobject //*-* ========================================================== // fBasketSize = buffsize; Int_t i; Int_t nbranches = fBranches.GetEntriesFast(); for (i=0;i<nbranches;i++) { TBranch *branch = (TBranch*)fBranches[i]; branch->SetBasketSize(buffsize); } } //______________________________________________________________________________ void TBranchObject::UpdateAddress() { //*-*-*-*-*-*-*-*Update branch addresses if a new object was created*-*-* //*-* =================================================== // void **ppointer = (void**)fAddress; if (ppointer == 0) return; TObject *obj = (TObject*)(*ppointer); if (obj != fOldObject) { fOldObject = obj; SetAddress(fAddress); } }
// @(#)root/tree:$Name: $:$Id: TBranchObject.cxx,v 1.13 2001/04/28 11:39:53 brun Exp $ // Author: Rene Brun 11/02/96 /************************************************************************* * Copyright (C) 1995-2000, Rene Brun and Fons Rademakers. * * All rights reserved. * * * * For the licensing terms see $ROOTSYS/LICENSE. * * For the list of contributors see $ROOTSYS/README/CREDITS. * *************************************************************************/ ////////////////////////////////////////////////////////////////////////// // // // TBranchObject // // // // A Branch for the case of an object // // // // ////////////////////////////////////////////////////////////////////////// #include "TROOT.h" #include "TFile.h" #include "TBranchObject.h" #include "TBranchClones.h" #include "TTree.h" #include "TBasket.h" #include "TLeafObject.h" #include "TVirtualPad.h" #include "TClass.h" #include "TRealData.h" #include "TDataType.h" #include "TDataMember.h" #include "TBrowser.h" R__EXTERN TTree *gTree; ClassImp(TBranchObject) //______________________________________________________________________________ TBranchObject::TBranchObject(): TBranch() { //*-*-*-*-*-*Default constructor for BranchObject*-*-*-*-*-*-*-*-*-* //*-* ==================================== fNleaves = 1; fOldObject = 0; } //______________________________________________________________________________ TBranchObject::TBranchObject(const char *name, const char *classname, void *addobj, Int_t basketsize, Int_t splitlevel, Int_t compress) :TBranch() { //*-*-*-*-*-*-*-*-*-*-*-*-*Create a BranchObject*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-* //*-* ===================== // TClass *cl = gROOT->GetClass(classname); if (!cl) { Error("TBranchObject","Cannot find class:%s",classname); return; } char **apointer = (char**)(addobj); TObject *obj = (TObject*)(*apointer); Bool_t delobj = kFALSE; if (!obj) { obj = (TObject*)cl->New(); delobj = kTRUE; } gTree->BuildStreamerInfo(cl,obj); if (delobj) delete obj; SetName(name); SetTitle(name); fCompress = compress; if (compress == -1) { TFile *bfile = gTree->GetDirectory()->GetFile(); if (bfile) fCompress = bfile->GetCompressionLevel(); } if (basketsize < 100) basketsize = 100; fBasketSize = basketsize; fAddress = (char*)addobj; fClassName = classname; fBasketEntry = new Int_t[fMaxBaskets]; fBasketBytes = new Int_t[fMaxBaskets]; fBasketSeek = new Seek_t[fMaxBaskets]; fOldObject = 0; fBasketEntry[0] = fEntryNumber; fBasketBytes[0] = 0; TLeaf *leaf = new TLeafObject(name,classname); leaf->SetBranch(this); leaf->SetAddress(addobj); fNleaves = 1; fLeaves.Add(leaf); gTree->GetListOfLeaves()->Add(leaf); // Set the bit kAutoDelete to specify that when reading // in TLeafObject::ReadBasket, the object should be deleted // before calling Streamer. // It is foreseen to not set this bit in a future version. SetAutoDelete(kTRUE); fTree = gTree; fDirectory = fTree->GetDirectory(); fFileName = ""; //*-*- Create the first basket if (splitlevel) return; TBasket *basket = new TBasket(name,fTree->GetName(),this); fBaskets.Add(basket); } //______________________________________________________________________________ TBranchObject::~TBranchObject() { //*-*-*-*-*-*Default destructor for a BranchObject*-*-*-*-*-*-*-*-*-*-*-* //*-* ===================================== fBranches.Delete(); } //______________________________________________________________________________ void TBranchObject::Browse(TBrowser *b) { Int_t nbranches = fBranches.GetEntriesFast(); if (nbranches > 1) { fBranches.Browse( b ); } } //______________________________________________________________________________ Int_t TBranchObject::Fill() { //*-*-*-*-*-*-*-*Loop on all leaves of this branch to fill Basket buffer*-*-* //*-* ======================================================= Int_t nbytes = 0; Int_t i; Int_t nbranches = fBranches.GetEntriesFast(); if (nbranches) { fEntries++; UpdateAddress(); for (i=0;i<nbranches;i++) { TBranch *branch = (TBranch*)fBranches[i]; if (!branch->TestBit(kDoNotProcess)) nbytes += branch->Fill(); } } else { if (!TestBit(kDoNotProcess)) nbytes += TBranch::Fill(); } return nbytes; } //______________________________________________________________________________ Int_t TBranchObject::GetEntry(Int_t entry, Int_t getall) { //*-*-*-*-*Read all branches of a BranchObject and return total number of bytes //*-* ==================================================================== // If entry = 0 take current entry number + 1 // If entry < 0 reset entry number to 0 // // The function returns the number of bytes read from the input buffer. // If entry does not exist or an I/O error occurs, the function returns 0. // if entry is the same as the previous call, the function returns 1. if (TestBit(kDoNotProcess) && !getall) return 0; Int_t nbytes; Int_t nbranches = fBranches.GetEntriesFast(); if (nbranches) { if (fAddress == 0) { // try to create object if (!TestBit(kWarn)) { TClass *cl = gROOT->GetClass(fClassName); if (cl) { TObject** voidobj = (TObject**) new Long_t[1]; *voidobj = (TObject*)cl->New(); SetAddress(voidobj); } else { Warning("GetEntry","Cannot get class: %s",fClassName.Data()); SetBit(kWarn); } } } nbytes = 0; for (Int_t i=0;i<nbranches;i++) { TBranch *branch = (TBranch*)fBranches[i]; if (branch) nbytes += branch->GetEntry(entry); } } else { nbytes = TBranch::GetEntry(entry); } return nbytes; } //______________________________________________________________________________ Bool_t TBranchObject::IsFolder() const { //*-*-*-*-*Return TRUE if more than one leaf, FALSE otherwise*-* //*-* ================================================== Int_t nbranches = fBranches.GetEntriesFast(); if (nbranches >= 1) return kTRUE; else return kFALSE; } //______________________________________________________________________________ void TBranchObject::Print(Option_t *option) const { //*-*-*-*-*-*-*-*-*-*-*-*Print TBranch parameters*-*-*-*-*-*-*-*-*-*-*-*-*-*-* //*-* ======================== Int_t i; Int_t nbranches = fBranches.GetEntriesFast(); if (nbranches) { Printf("*Branch :%-9s : %-54s *",GetName(),GetTitle()); Printf("*Entries : %8d : BranchObject (see below) *",Int_t(fEntries)); Printf("*............................................................................*"); for (i=0;i<nbranches;i++) { TBranch *branch = (TBranch*)fBranches.At(i); if (branch) branch->Print(option); } } else { TBranch::Print(option); } } //______________________________________________________________________________ void TBranchObject::Reset(Option_t *option) { //*-*-*-*-*-*-*-*Reset a Branch*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-* //*-* ==================== // // Existing buffers are deleted // Entries, max and min are reset // TBranch::Reset(option); Int_t i; Int_t nbranches = fBranches.GetEntriesFast(); for (i=0;i<nbranches;i++) { TBranch *branch = (TBranch*)fBranches[i]; branch->Reset(option); } } //______________________________________________________________________________ void TBranchObject::SetAddress(void *add) { //*-*-*-*-*-*-*-*Set address of this branch*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-* //*-* ==================== // //special case when called from code generated by TTree::MakeClass if (Long_t(add) == -1) { SetBit(kWarn); return; } fReadEntry = -1; Int_t nbranches = fBranches.GetEntriesFast(); TLeaf *leaf = (TLeaf*)fLeaves.UncheckedAt(0); if (leaf) leaf->SetAddress(add); TBranch *branch; fAddress = (char*)add; char *pointer = fAddress; void **ppointer = (void**)add; TObject *obj = 0; if (add) obj = (TObject*)(*ppointer); TClass *cl = gROOT->GetClass(fClassName.Data()); if (!obj && cl) { obj = (TObject*)cl->New(); *ppointer = (void*)obj; } //fOldObject = obj; Int_t i, offset; if (!cl) { for (i=0;i<nbranches;i++) { branch = (TBranch*)fBranches[i]; pointer = (char*)obj; branch->SetAddress(pointer); } return; } if (!cl->GetListOfRealData()) cl->BuildRealData(obj); char *fullname = new char[200]; const char *bname = GetName(); Int_t lenName = strlen(bname); Int_t isDot = 0; if (bname[lenName-1] == '.') isDot = 1; const char *rdname; TRealData *rd; TIter next(cl->GetListOfRealData()); while ((rd = (TRealData *) next())) { TDataMember *dm = rd->GetDataMember(); if (!dm->IsPersistent()) continue; rdname = rd->GetName(); TDataType *dtype = dm->GetDataType(); Int_t code = 0; if (dtype) code = dm->GetDataType()->GetType(); offset = rd->GetThisOffset(); pointer = (char*)obj + offset; branch = 0; if (dm->IsaPointer()) { TClass *clobj = 0; if (!dm->IsBasic()) clobj = gROOT->GetClass(dm->GetTypeName()); if (clobj && clobj->InheritsFrom("TClonesArray")) { if (isDot) sprintf(fullname,"%s%s",bname,&rdname[1]); else sprintf(fullname,"%s",&rdname[1]); branch = (TBranch*)fBranches.FindObject(fullname); } else { if (!clobj) { // this is a basic type we can handle only if // he has a dimension: const char * index = dm->GetArrayIndex(); if (strlen(index)==0) { if (code==1) { // Case of a string ... we do not need the size if (isDot) sprintf(fullname,"%s%s",bname,&rdname[0]); else sprintf(fullname,"%s",&rdname[0]); } else { continue; } } if (isDot) sprintf(fullname,"%s%s",bname,&rdname[0]); else sprintf(fullname,"%s",&rdname[0]); // let's remove the stars! UInt_t cursor,pos; for( cursor = 0, pos = 0; cursor < strlen(fullname); cursor ++ ) { if (fullname[cursor]!='*') { fullname[pos++] = fullname[cursor]; }; }; fullname[pos] = '\0'; branch = (TBranch*)fBranches.FindObject(fullname); } else { if (!clobj->InheritsFrom(TObject::Class())) continue; if (isDot) sprintf(fullname,"%s%s",bname,&rdname[1]); else sprintf(fullname,"%s",&rdname[1]); branch = (TBranch*)fBranches.FindObject(fullname); } } } else { if (dm->IsBasic()) { if (isDot) sprintf(fullname,"%s%s",bname,&rdname[0]); else sprintf(fullname,"%s",&rdname[0]); branch = (TBranch*)fBranches.FindObject(fullname); } } if(branch) branch->SetAddress(pointer); } delete [] fullname; } //______________________________________________________________________________ void TBranchObject::SetAutoDelete(Bool_t autodel) { //*-*-*-*-*-*-*-*Set the AutoDelete bit //*-* ==================== // This function can be used to instruct Root in TBranchObject::ReadBasket // to not delete the object referenced by a branchobject before reading a // new entry. By default, the object is deleted. // If autodel is kTRUE, this existing object will be deleted, a new object // created by the default constructor, then object->Streamer called. // If autodel is kFALSE, the existing object is not deleted. Root assumes // that the user is taking care of deleting any internal object or array // This can be done in Streamer itself. // If this branch has sub-branches, the function sets autodel for these // branches as well. // We STRONGLY suggest to activate this option by default when you create // the top level branch. This will make the read phase more efficient // because it minimizes the numbers of new/delete operations. // Once this option has been set and the Tree is written to a file, it is // not necessary to specify the option again when reading, unless you // want to set the opposite mode. // TBranch::SetAutoDelete(autodel); Int_t nbranches = fBranches.GetEntriesFast(); for (Int_t i=0;i<nbranches;i++) { TBranch *branch = (TBranch*)fBranches[i]; branch->SetAutoDelete(autodel); } } //______________________________________________________________________________ void TBranchObject::SetBasketSize(Int_t buffsize) { //*-*-*-*-*-*-*-*Reset basket size for all subbranches of this branchobject //*-* ========================================================== // fBasketSize = buffsize; Int_t i; Int_t nbranches = fBranches.GetEntriesFast(); for (i=0;i<nbranches;i++) { TBranch *branch = (TBranch*)fBranches[i]; branch->SetBasketSize(buffsize); } } //______________________________________________________________________________ void TBranchObject::UpdateAddress() { //*-*-*-*-*-*-*-*Update branch addresses if a new object was created*-*-* //*-* =================================================== // void **ppointer = (void**)fAddress; if (ppointer == 0) return; TObject *obj = (TObject*)(*ppointer); if (obj != fOldObject) { fOldObject = obj; SetAddress(fAddress); } }
Add protection against branch=0 in TBranchObject::GetEntry.
Add protection against branch=0 in TBranchObject::GetEntry. git-svn-id: acec3fd5b7ea1eb9e79d6329d318e8118ee2e14f@2175 27541ba8-7e3a-0410-8455-c3a389f83636
C++
lgpl-2.1
omazapa/root-old,georgtroska/root,karies/root,vukasinmilosevic/root,esakellari/root,georgtroska/root,mattkretz/root,omazapa/root-old,georgtroska/root,smarinac/root,BerserkerTroll/root,strykejern/TTreeReader,dfunke/root,beniz/root,CristinaCristescu/root,thomaskeck/root,thomaskeck/root,agarciamontoro/root,sbinet/cxx-root,pspe/root,smarinac/root,dfunke/root,kirbyherm/root-r-tools,gganis/root,root-mirror/root,pspe/root,omazapa/root-old,vukasinmilosevic/root,thomaskeck/root,olifre/root,bbockelm/root,davidlt/root,sawenzel/root,tc3t/qoot,zzxuanyuan/root,vukasinmilosevic/root,lgiommi/root,dfunke/root,davidlt/root,agarciamontoro/root,beniz/root,smarinac/root,gbitzes/root,karies/root,vukasinmilosevic/root,strykejern/TTreeReader,root-mirror/root,sawenzel/root,davidlt/root,karies/root,mkret2/root,satyarth934/root,pspe/root,nilqed/root,CristinaCristescu/root,satyarth934/root,omazapa/root,satyarth934/root,davidlt/root,mkret2/root,vukasinmilosevic/root,perovic/root,esakellari/root,zzxuanyuan/root-compressor-dummy,jrtomps/root,sirinath/root,satyarth934/root,Dr15Jones/root,veprbl/root,nilqed/root,evgeny-boger/root,sbinet/cxx-root,gganis/root,beniz/root,abhinavmoudgil95/root,smarinac/root,jrtomps/root,beniz/root,omazapa/root-old,veprbl/root,root-mirror/root,veprbl/root,pspe/root,zzxuanyuan/root-compressor-dummy,CristinaCristescu/root,veprbl/root,lgiommi/root,kirbyherm/root-r-tools,sawenzel/root,smarinac/root,esakellari/root,pspe/root,gganis/root,zzxuanyuan/root,root-mirror/root,sawenzel/root,vukasinmilosevic/root,gganis/root,sirinath/root,evgeny-boger/root,dfunke/root,nilqed/root,sbinet/cxx-root,thomaskeck/root,dfunke/root,lgiommi/root,omazapa/root-old,zzxuanyuan/root-compressor-dummy,georgtroska/root,Y--/root,mhuwiler/rootauto,sbinet/cxx-root,nilqed/root,Duraznos/root,gbitzes/root,esakellari/root,BerserkerTroll/root,Y--/root,buuck/root,ffurano/root5,georgtroska/root,evgeny-boger/root,esakellari/my_root_for_test,mkret2/root,vukasinmilosevic/root,esakellari/my_root_for_test,veprbl/root,abhinavmoudgil95/root,strykejern/TTreeReader,mattkretz/root,simonpf/root,buuck/root,mattkretz/root,abhinavmoudgil95/root,gbitzes/root,sirinath/root,smarinac/root,gganis/root,kirbyherm/root-r-tools,kirbyherm/root-r-tools,gganis/root,CristinaCristescu/root,perovic/root,jrtomps/root,mkret2/root,Y--/root,cxx-hep/root-cern,sbinet/cxx-root,evgeny-boger/root,omazapa/root-old,gbitzes/root,BerserkerTroll/root,bbockelm/root,alexschlueter/cern-root,CristinaCristescu/root,jrtomps/root,buuck/root,abhinavmoudgil95/root,omazapa/root,BerserkerTroll/root,davidlt/root,buuck/root,tc3t/qoot,thomaskeck/root,mattkretz/root,esakellari/my_root_for_test,lgiommi/root,omazapa/root-old,vukasinmilosevic/root,CristinaCristescu/root,ffurano/root5,krafczyk/root,ffurano/root5,cxx-hep/root-cern,zzxuanyuan/root-compressor-dummy,beniz/root,abhinavmoudgil95/root,agarciamontoro/root,zzxuanyuan/root,Duraznos/root,mhuwiler/rootauto,krafczyk/root,sirinath/root,pspe/root,Dr15Jones/root,omazapa/root,krafczyk/root,omazapa/root,gbitzes/root,BerserkerTroll/root,beniz/root,dfunke/root,mattkretz/root,abhinavmoudgil95/root,pspe/root,arch1tect0r/root,georgtroska/root,bbockelm/root,sbinet/cxx-root,zzxuanyuan/root,esakellari/root,Duraznos/root,dfunke/root,mhuwiler/rootauto,nilqed/root,alexschlueter/cern-root,root-mirror/root,cxx-hep/root-cern,esakellari/my_root_for_test,olifre/root,jrtomps/root,abhinavmoudgil95/root,dfunke/root,agarciamontoro/root,krafczyk/root,gbitzes/root,ffurano/root5,omazapa/root,Dr15Jones/root,simonpf/root,zzxuanyuan/root,karies/root,pspe/root,tc3t/qoot,strykejern/TTreeReader,zzxuanyuan/root-compressor-dummy,lgiommi/root,karies/root,bbockelm/root,olifre/root,sirinath/root,bbockelm/root,omazapa/root,cxx-hep/root-cern,esakellari/my_root_for_test,davidlt/root,davidlt/root,tc3t/qoot,perovic/root,sbinet/cxx-root,Duraznos/root,0x0all/ROOT,omazapa/root,karies/root,smarinac/root,karies/root,simonpf/root,beniz/root,olifre/root,nilqed/root,arch1tect0r/root,zzxuanyuan/root,cxx-hep/root-cern,arch1tect0r/root,alexschlueter/cern-root,gganis/root,buuck/root,0x0all/ROOT,beniz/root,evgeny-boger/root,lgiommi/root,sirinath/root,omazapa/root-old,vukasinmilosevic/root,lgiommi/root,agarciamontoro/root,simonpf/root,lgiommi/root,karies/root,arch1tect0r/root,Y--/root,arch1tect0r/root,thomaskeck/root,abhinavmoudgil95/root,mattkretz/root,CristinaCristescu/root,Duraznos/root,evgeny-boger/root,Y--/root,mattkretz/root,evgeny-boger/root,arch1tect0r/root,jrtomps/root,zzxuanyuan/root-compressor-dummy,olifre/root,sirinath/root,cxx-hep/root-cern,tc3t/qoot,BerserkerTroll/root,agarciamontoro/root,zzxuanyuan/root,tc3t/qoot,thomaskeck/root,omazapa/root,mhuwiler/rootauto,mkret2/root,mkret2/root,georgtroska/root,evgeny-boger/root,davidlt/root,veprbl/root,thomaskeck/root,sirinath/root,perovic/root,nilqed/root,CristinaCristescu/root,thomaskeck/root,sawenzel/root,mhuwiler/rootauto,sirinath/root,Dr15Jones/root,buuck/root,thomaskeck/root,esakellari/my_root_for_test,Y--/root,ffurano/root5,tc3t/qoot,alexschlueter/cern-root,CristinaCristescu/root,satyarth934/root,nilqed/root,beniz/root,nilqed/root,karies/root,buuck/root,perovic/root,ffurano/root5,0x0all/ROOT,simonpf/root,simonpf/root,mattkretz/root,mkret2/root,mhuwiler/rootauto,krafczyk/root,Duraznos/root,zzxuanyuan/root-compressor-dummy,perovic/root,0x0all/ROOT,zzxuanyuan/root,satyarth934/root,Dr15Jones/root,perovic/root,tc3t/qoot,olifre/root,esakellari/my_root_for_test,simonpf/root,agarciamontoro/root,krafczyk/root,Y--/root,zzxuanyuan/root-compressor-dummy,simonpf/root,evgeny-boger/root,esakellari/root,buuck/root,jrtomps/root,ffurano/root5,Y--/root,kirbyherm/root-r-tools,0x0all/ROOT,cxx-hep/root-cern,satyarth934/root,jrtomps/root,olifre/root,gganis/root,zzxuanyuan/root,kirbyherm/root-r-tools,sbinet/cxx-root,gganis/root,nilqed/root,omazapa/root,sbinet/cxx-root,georgtroska/root,pspe/root,root-mirror/root,sawenzel/root,perovic/root,tc3t/qoot,agarciamontoro/root,Duraznos/root,0x0all/ROOT,Y--/root,arch1tect0r/root,olifre/root,BerserkerTroll/root,mhuwiler/rootauto,bbockelm/root,sirinath/root,Dr15Jones/root,esakellari/root,satyarth934/root,Duraznos/root,Dr15Jones/root,zzxuanyuan/root-compressor-dummy,esakellari/root,olifre/root,perovic/root,buuck/root,agarciamontoro/root,omazapa/root,bbockelm/root,dfunke/root,CristinaCristescu/root,zzxuanyuan/root,BerserkerTroll/root,0x0all/ROOT,mhuwiler/rootauto,0x0all/ROOT,Duraznos/root,krafczyk/root,alexschlueter/cern-root,abhinavmoudgil95/root,gbitzes/root,krafczyk/root,mhuwiler/rootauto,jrtomps/root,veprbl/root,jrtomps/root,nilqed/root,satyarth934/root,gbitzes/root,esakellari/my_root_for_test,arch1tect0r/root,sbinet/cxx-root,evgeny-boger/root,simonpf/root,mattkretz/root,georgtroska/root,root-mirror/root,mkret2/root,strykejern/TTreeReader,strykejern/TTreeReader,root-mirror/root,gganis/root,georgtroska/root,esakellari/root,gbitzes/root,mattkretz/root,dfunke/root,bbockelm/root,zzxuanyuan/root,0x0all/ROOT,alexschlueter/cern-root,smarinac/root,Duraznos/root,georgtroska/root,arch1tect0r/root,zzxuanyuan/root-compressor-dummy,mhuwiler/rootauto,veprbl/root,perovic/root,strykejern/TTreeReader,jrtomps/root,cxx-hep/root-cern,gbitzes/root,evgeny-boger/root,karies/root,beniz/root,satyarth934/root,pspe/root,sawenzel/root,krafczyk/root,abhinavmoudgil95/root,kirbyherm/root-r-tools,davidlt/root,dfunke/root,simonpf/root,gbitzes/root,root-mirror/root,veprbl/root,root-mirror/root,buuck/root,agarciamontoro/root,omazapa/root-old,vukasinmilosevic/root,arch1tect0r/root,mkret2/root,veprbl/root,bbockelm/root,sawenzel/root,smarinac/root,pspe/root,omazapa/root-old,perovic/root,omazapa/root-old,Duraznos/root,veprbl/root,karies/root,krafczyk/root,lgiommi/root,esakellari/root,sawenzel/root,zzxuanyuan/root,smarinac/root,gganis/root,mkret2/root,lgiommi/root,zzxuanyuan/root-compressor-dummy,CristinaCristescu/root,sawenzel/root,satyarth934/root,root-mirror/root,beniz/root,davidlt/root,BerserkerTroll/root,mkret2/root,esakellari/my_root_for_test,krafczyk/root,agarciamontoro/root,Y--/root,BerserkerTroll/root,vukasinmilosevic/root,arch1tect0r/root,tc3t/qoot,olifre/root,BerserkerTroll/root,mattkretz/root,mhuwiler/rootauto,alexschlueter/cern-root,olifre/root,Y--/root,sawenzel/root,abhinavmoudgil95/root,bbockelm/root,davidlt/root,esakellari/my_root_for_test,buuck/root,omazapa/root,sbinet/cxx-root,bbockelm/root,esakellari/root,sirinath/root,lgiommi/root,simonpf/root
7cae021ba556b543f258868ded21907dcc429883
core/src/misc/filesystem.cc
core/src/misc/filesystem.cc
/* ** Copyright 2015,2017 Centreon ** ** 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. ** ** For more information : [email protected] */ #include "com/centreon/broker/misc/filesystem.hh" #include <dirent.h> #include <fnmatch.h> #include <sys/stat.h> #include <sys/types.h> #include <cstring> #include <fstream> #include "com/centreon/broker/logging/logging.hh" using namespace com::centreon::broker; using namespace com::centreon::broker::misc; /** * Fill a strings list with the files listed in the directory. * * @param path The directory name * * @return a list of names. */ std::list<std::string> filesystem::dir_content(std::string const& path, bool recursive) { std::list<std::string> retval; DIR* dir{opendir(path.c_str())}; if (dir) { struct dirent* ent; bool add_slash; if (path.size() > 0 && path[path.size() - 1] == '/') add_slash = false; else add_slash = true; while ((ent = readdir(dir))) { if (strncmp(ent->d_name, ".", 2) == 0 || strncmp(ent->d_name, "..", 3) == 0) continue; std::string fullname{path}; if (add_slash) fullname.append("/"); fullname.append(ent->d_name); if (recursive && ent->d_type & DT_DIR) { std::list<std::string> res{filesystem::dir_content(fullname, true)}; retval.splice(retval.end(), res); } else if (ent->d_type == DT_REG) { retval.push_back(std::move(fullname)); } else if (ent->d_type == DT_UNKNOWN) { struct stat st; stat(fullname.c_str(), &st); if (recursive && S_ISDIR(st.st_mode)) { std::list<std::string> res{filesystem::dir_content(fullname, true)}; retval.splice(retval.end(), res); } else if (S_ISREG(st.st_mode)) retval.push_back(std::move(fullname)); } } closedir(dir); } else logging::error(logging::medium) << "directory_dumper: unable to read directory '" << path << "'"; return retval; } /** * Get the file names contained in a directory that match a given wildcard * match. * * @param path The directory where to get files. * @param filter A filter, the same we could give to a `ls` call. * * @return The list of the files matching the filter. */ std::list<std::string> filesystem::dir_content_with_filter( std::string const& path, std::string const& filter) { std::list<std::string> retval; std::list<std::string> list{filesystem::dir_content(path, false)}; std::string flt; flt.reserve(path.size() + 1 + filter.size()); flt = path; if (flt.size() == 0 || flt[flt.size() - 1] != '/') flt.append("/"); flt.append(filter); for (std::string& f : list) { if (fnmatch(flt.c_str(), f.c_str(), FNM_PATHNAME | FNM_NOESCAPE | FNM_PERIOD) == 0) retval.push_back(std::move(f)); } return retval; } /** * Check if the file exists. * * @param path The file name * * @return a boolean. */ bool filesystem::file_exists(std::string const& path) { struct stat info; if (stat(path.c_str(), &info) != 0) return false; return info.st_mode & S_IFREG; } /** * Check if the directory exists. * * @param path The directory name * * @return a boolean. */ bool filesystem::dir_exists(std::string const& path) { struct stat info; if (stat(path.c_str(), &info) != 0) return false; return (info.st_mode & S_IFDIR); } /** * Create a directory with all the needed parent directories * * @param path A directory name * * @return A boolean that is true on success. */ bool filesystem::mkpath(std::string const& path) { mode_t mode = 0755; /* In almost all the cases, the parent directories exist */ int ret = mkdir(path.c_str(), mode); if (ret == 0) return true; switch (errno) { case ENOENT: // parent didn't exist, try to create it { size_t pos = path.find_last_of('/'); if (pos == std::string::npos) return false; if (!mkpath(path.substr(0, pos))) return false; } // now, try to create again return mkdir(path.c_str(), mode) == 0; case EEXIST: return dir_exists(path); default: return false; } } int64_t filesystem::file_size(std::string const& path) { std::ifstream file{path, std::ios::binary | std::ios::ate}; int64_t size{file.tellg()}; return size; }
/* ** Copyright 2015,2017 Centreon ** ** 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. ** ** For more information : [email protected] */ #include "com/centreon/broker/misc/filesystem.hh" #include <dirent.h> #include <fnmatch.h> #include <sys/stat.h> #include <sys/types.h> #include <cstring> #include <fstream> #include "com/centreon/broker/logging/logging.hh" using namespace com::centreon::broker; using namespace com::centreon::broker::misc; /** * Fill a strings list with the files listed in the directory. * * @param path The directory name * * @return a list of names. */ std::list<std::string> filesystem::dir_content(std::string const& path, bool recursive) { std::list<std::string> retval; DIR* dir{opendir(path.c_str())}; if (dir) { struct dirent* ent; bool add_slash; if (path.size() > 0 && path[path.size() - 1] == '/') add_slash = false; else add_slash = true; while ((ent = readdir(dir))) { if (strncmp(ent->d_name, ".", 2) == 0 || strncmp(ent->d_name, "..", 3) == 0) continue; std::string fullname{path}; if (add_slash) fullname.append("/"); fullname.append(ent->d_name); if (recursive && ent->d_type == DT_DIR) { std::list<std::string> res{filesystem::dir_content(fullname, true)}; retval.splice(retval.end(), res); } else if (ent->d_type == DT_REG) { retval.push_back(std::move(fullname)); } else if (ent->d_type == DT_UNKNOWN) { struct stat st; stat(fullname.c_str(), &st); if (recursive && S_ISDIR(st.st_mode)) { std::list<std::string> res{filesystem::dir_content(fullname, true)}; retval.splice(retval.end(), res); } else if (S_ISREG(st.st_mode)) retval.push_back(std::move(fullname)); } } closedir(dir); } else logging::error(logging::medium) << "directory_dumper: unable to read directory '" << path << "'"; return retval; } /** * Get the file names contained in a directory that match a given wildcard * match. * * @param path The directory where to get files. * @param filter A filter, the same we could give to a `ls` call. * * @return The list of the files matching the filter. */ std::list<std::string> filesystem::dir_content_with_filter( std::string const& path, std::string const& filter) { std::list<std::string> retval; std::list<std::string> list{filesystem::dir_content(path, false)}; std::string flt; flt.reserve(path.size() + 1 + filter.size()); flt = path; if (flt.size() == 0 || flt[flt.size() - 1] != '/') flt.append("/"); flt.append(filter); for (std::string& f : list) { if (fnmatch(flt.c_str(), f.c_str(), FNM_PATHNAME | FNM_NOESCAPE | FNM_PERIOD) == 0) retval.push_back(std::move(f)); } return retval; } /** * Check if the file exists. * * @param path The file name * * @return a boolean. */ bool filesystem::file_exists(std::string const& path) { struct stat info; if (stat(path.c_str(), &info) != 0) return false; return info.st_mode & S_IFREG; } /** * Check if the directory exists. * * @param path The directory name * * @return a boolean. */ bool filesystem::dir_exists(std::string const& path) { struct stat info; if (stat(path.c_str(), &info) != 0) return false; return (info.st_mode & S_IFDIR); } /** * Create a directory with all the needed parent directories * * @param path A directory name * * @return A boolean that is true on success. */ bool filesystem::mkpath(std::string const& path) { mode_t mode = 0755; /* In almost all the cases, the parent directories exist */ int ret = mkdir(path.c_str(), mode); if (ret == 0) return true; switch (errno) { case ENOENT: // parent didn't exist, try to create it { size_t pos = path.find_last_of('/'); if (pos == std::string::npos) return false; if (!mkpath(path.substr(0, pos))) return false; } // now, try to create again return mkdir(path.c_str(), mode) == 0; case EEXIST: return dir_exists(path); default: return false; } } int64_t filesystem::file_size(std::string const& path) { std::ifstream file{path, std::ios::binary | std::ios::ate}; int64_t size{file.tellg()}; return size; }
use stat only when needed
fix(perf): use stat only when needed
C++
apache-2.0
centreon/centreon-broker,centreon/centreon-broker,centreon/centreon-broker,centreon/centreon-broker,centreon/centreon-broker
97d4baf58e55ed2c5a11765921cff2845603a0c2
cpp/src/name-components.cpp
cpp/src/name-components.cpp
// // name-components.cpp // libndnrtc // // Copyright 2013 Regents of the University of California // For licensing details see the LICENSE file. // // Author: Peter Gusev // #include <string> #include <sstream> #include <algorithm> #include <iterator> #include <boost/algorithm/string/split.hpp> #include <boost/algorithm/string/classification.hpp> #include <boost/algorithm/string.hpp> #include "name-components.hpp" using namespace std; using namespace ndnrtc; using namespace ndn; const string NameComponents::NameComponentApp = "ndnrtc"; const string NameComponents::NameComponentAudio = "audio"; const string NameComponents::NameComponentVideo = "video"; const string NameComponents::NameComponentMeta = "_meta"; const string NameComponents::NameComponentDelta = "d"; const string NameComponents::NameComponentKey = "k"; const string NameComponents::NameComponentParity = "_parity"; const string NameComponents::NameComponentManifest = "_manifest"; #include <bitset> Name NamespaceInfo::getPrefix(int filter) const { using namespace prefix_filter; Name prefix(basePrefix_); if (filter) { if (filter&(Library^Base)) prefix.append(Name(NameComponents::NameComponentApp)).appendVersion(apiVersion_); if (filter&(Stream^Library)) prefix.append((streamType_ == MediaStreamParams::MediaStreamType::MediaStreamTypeAudio ? NameComponents::NameComponentAudio : NameComponents::NameComponentVideo)).append(streamName_); if (filter&(StreamTS^Stream) && threadName_ != "") prefix.appendTimestamp(streamTimestamp_); if (threadName_ != "" && (filter&(Thread^StreamTS) || filter&(ThreadNT^StreamTS) & streamType_ == MediaStreamParams::MediaStreamType::MediaStreamTypeVideo)) { prefix.append(threadName_); } if (isMeta_) { if (filter&(Segment^Thread)) prefix.append(NameComponents::NameComponentMeta); if (filter&(Segment^Sample)) { prefix.appendVersion(metaVersion_).appendSegment(segNo_); } } else { if (filter&(Thread^ThreadNT) && threadName_ != "" && streamType_ == MediaStreamParams::MediaStreamType::MediaStreamTypeVideo) prefix.append((class_ == SampleClass::Delta ? NameComponents::NameComponentDelta : NameComponents::NameComponentKey)); if (filter&(Sample^Thread)) prefix.appendSequenceNumber(sampleNo_); if (filter&(Segment^Sample)) { if (isParity_) prefix.append(NameComponents::NameComponentParity); prefix.appendSegment(segNo_); } } } return prefix; } Name NamespaceInfo::getSuffix(int filter) const { using namespace suffix_filter; Name suffix; if (filter) { if (filter&(Library^Stream)) suffix.append(Name(NameComponents::NameComponentApp)).appendVersion(apiVersion_); if (filter&(Stream^Thread)) { suffix.append((streamType_ == MediaStreamParams::MediaStreamType::MediaStreamTypeAudio ? NameComponents::NameComponentAudio : NameComponents::NameComponentVideo)).append(streamName_); if (threadName_ != "") suffix.appendTimestamp(streamTimestamp_); } if (filter&(Thread^Sample) && threadName_ != "") suffix.append(threadName_); if (isMeta_) { if ((filter&(Thread^Sample) && threadName_ != "") || filter&(Stream^Thread)) suffix.append(NameComponents::NameComponentMeta); } if (filter&(Thread^Sample) && threadName_ != "" && streamType_ == MediaStreamParams::MediaStreamType::MediaStreamTypeVideo && !isMeta_) suffix.append((class_ == SampleClass::Delta ? NameComponents::NameComponentDelta : NameComponents::NameComponentKey)); if (filter&(Sample^Segment)) { if (isMeta_) suffix.appendVersion(metaVersion_); else suffix.appendSequenceNumber(sampleNo_); } if (filter&(Segment) && hasSegNo_) { if (isParity_) suffix.append(NameComponents::NameComponentParity); suffix.appendSegment(segNo_); } } return suffix; } //****************************************************************************** vector<string> ndnrtcVersionComponents() { string version = NameComponents::fullVersion(); std::vector<string> components; boost::erase_all(version, "v"); boost::split(components, version, boost::is_any_of("."), boost::token_compress_on); return components; } std::string NameComponents::fullVersion() { return std::string(PACKAGE_VERSION); } unsigned int NameComponents::nameApiVersion() { return (unsigned int)atoi(ndnrtcVersionComponents().front().c_str()); } Name NameComponents::ndnrtcSuffix() { return Name(NameComponentApp).appendVersion(nameApiVersion()); } Name NameComponents::streamPrefix(MediaStreamParams::MediaStreamType type, std::string basePrefix) { Name n = Name(basePrefix); n.append(ndnrtcSuffix()); return ((type == MediaStreamParams::MediaStreamType::MediaStreamTypeAudio) ? n.append(NameComponentAudio) : n.append(NameComponentVideo)); } Name NameComponents::audioStreamPrefix(string basePrefix) { return streamPrefix(MediaStreamParams::MediaStreamType::MediaStreamTypeAudio, basePrefix); } Name NameComponents::videoStreamPrefix(string basePrefix) { return streamPrefix(MediaStreamParams::MediaStreamType::MediaStreamTypeVideo, basePrefix); } //****************************************************************************** bool extractMeta(const ndn::Name& name, NamespaceInfo& info) { // example: name == %FD%05/%00%00 if (name.size() >= 1 && name[0].isVersion()) { info.metaVersion_ = name[0].toVersion(); if (name.size() >= 2) { info.segNo_ = name[1].toSegment(); info.hasSegNo_ = true; } else info.hasSegNo_ = false; return true; } return false; } bool extractVideoStreamInfo(const ndn::Name& name, NamespaceInfo& info) { if (name.size() == 1) { info.streamName_ = name[0].toEscapedString(); return true; } if (name.size() == 2 && name[1].isTimestamp()) { info.streamName_ = name[0].toEscapedString(); info.streamTimestamp_ = name[1].toTimestamp(); return true; } if (name.size() < 3) return false; int idx = 0; info.streamName_ = name[idx++].toEscapedString(); info.isMeta_ = (name[idx++] == Name::Component(NameComponents::NameComponentMeta)); if (info.isMeta_) { // example: name == camera/_meta/%FD%05/%00%00 info.segmentClass_ = SegmentClass::Meta; info.threadName_ = ""; return extractMeta(name.getSubName(idx), info); } else { // example: name == camera/%FC%00%00%01c_%27%DE%D6/hi/d/%FE%07/%00%00 info.class_ = SampleClass::Unknown; info.segmentClass_ = SegmentClass::Unknown; info.streamTimestamp_ = name[idx-1].toTimestamp(); info.threadName_ = name[idx++].toEscapedString(); if (name.size() <= idx) return true; info.isMeta_ = (name[idx++] == Name::Component(NameComponents::NameComponentMeta)); if (info.isMeta_) { // example: camera/%FC%00%00%01c_%27%DE%D6/hi/_meta/%FD%05/%00%00 info.segmentClass_ = SegmentClass::Meta; if(name.size() > idx-1 && extractMeta(name.getSubName(idx), info)) return true; return false; } if (name[idx-1] == Name::Component(NameComponents::NameComponentDelta) || name[idx-1] == Name::Component(NameComponents::NameComponentKey)) { info.isDelta_ = (name[idx-1] == Name::Component(NameComponents::NameComponentDelta)); info.class_ = (info.isDelta_ ? SampleClass::Delta : SampleClass::Key); try{ if (name.size() > idx) info.sampleNo_ = (PacketNumber)name[idx++].toSequenceNumber(); else { info.hasSeqNo_ = false; return true; } info.hasSeqNo_ = true; if (name.size() > idx) { info.isParity_ = (name[idx] == Name::Component(NameComponents::NameComponentParity)); info.hasSegNo_ = true; if (info.isParity_ && name.size() > idx+1) { info.segmentClass_ = SegmentClass::Parity; info.segNo_ = name[idx+1].toSegment(); return true; } else { if (info.isParity_) return false; else { if (name[idx] == Name::Component(NameComponents::NameComponentManifest)) info.segmentClass_ = SegmentClass::Manifest; else { info.segmentClass_ = SegmentClass::Data; info.segNo_ = name[idx].toSegment(); } } return true; } } else { info.segmentClass_ = SegmentClass::Unknown; info.hasSegNo_ = false; return true; } } catch (std::runtime_error& e) { return false; } } } return false; } bool extractAudioStreamInfo(const ndn::Name& name, NamespaceInfo& info) { if (name.size() == 1) { info.streamName_ = name[0].toEscapedString(); return true; } if (name.size() == 2 && name[1].isTimestamp()) { info.streamName_ = name[0].toEscapedString(); info.streamTimestamp_ = name[1].toTimestamp(); return true; } if (name.size() < 2) return false; int idx = 0; info.streamName_ = name[idx++].toEscapedString(); info.isMeta_ = (name[idx++] == Name::Component(NameComponents::NameComponentMeta)); if (info.isMeta_) { info.segmentClass_ = SegmentClass::Meta; if (name.size() < idx+1) return false; info.threadName_ = ""; return extractMeta(name.getSubName(idx), info);; } else { info.class_ = SampleClass::Unknown; info.segmentClass_ = SegmentClass::Unknown; info.streamTimestamp_ = name[idx-1].toTimestamp(); info.threadName_ = name[idx++].toEscapedString(); if (name.size() == 3) { info.hasSeqNo_ = false; return true; } info.isMeta_ = (name[idx] == Name::Component(NameComponents::NameComponentMeta)); if (info.isMeta_) { info.segmentClass_ = SegmentClass::Meta; if (name.size() > idx+1 && extractMeta(name.getSubName(idx+1), info)) return true; return false; } info.isDelta_ = true; info.class_ = SampleClass::Delta; try { if (name.size() > 3) info.sampleNo_ = (PacketNumber)name[idx++].toSequenceNumber(); info.hasSeqNo_ = true; if (name.size() > idx) { if (name[idx] == Name::Component(NameComponents::NameComponentManifest)) info.segmentClass_ = SegmentClass::Manifest; else { info.hasSegNo_ = true; info.segmentClass_ = SegmentClass::Data; info.segNo_ = name[idx].toSegment(); } return true; } else { info.hasSegNo_ = false; return true; } } catch (std::runtime_error& e) { return false; } } return false; } bool NameComponents::extractInfo(const ndn::Name& name, NamespaceInfo& info) { bool goodName = false; static Name ndnrtcSubName(NameComponents::NameComponentApp); Name subName; int i; for (i = name.size()-2; i > 0 && !goodName; --i) { subName = name.getSubName(i); goodName = ndnrtcSubName.match(subName); } if (goodName) { info.basePrefix_ = name.getSubName(0, i+1); if ((goodName = subName[1].isVersion())) { info.apiVersion_ = subName[1].toVersion(); if (subName.size() > 2 && (goodName = (subName[2] == Name::Component(NameComponents::NameComponentAudio) || subName[2] == Name::Component(NameComponents::NameComponentVideo))) ) { info.streamType_ = (subName[2] == Name::Component(NameComponents::NameComponentAudio) ? MediaStreamParams::MediaStreamType::MediaStreamTypeAudio : MediaStreamParams::MediaStreamType::MediaStreamTypeVideo ); if (info.streamType_ == MediaStreamParams::MediaStreamType::MediaStreamTypeAudio) return extractAudioStreamInfo(subName.getSubName(3), info); else return extractVideoStreamInfo(subName.getSubName(3), info); } } } return false; }
// // name-components.cpp // libndnrtc // // Copyright 2013 Regents of the University of California // For licensing details see the LICENSE file. // // Author: Peter Gusev // #include <string> #include <sstream> #include <algorithm> #include <iterator> #include <boost/algorithm/string/split.hpp> #include <boost/algorithm/string/classification.hpp> #include <boost/algorithm/string.hpp> #include "name-components.hpp" using namespace std; using namespace ndnrtc; using namespace ndn; const string NameComponents::NameComponentApp = "ndnrtc"; const string NameComponents::NameComponentAudio = "audio"; const string NameComponents::NameComponentVideo = "video"; const string NameComponents::NameComponentMeta = "_meta"; const string NameComponents::NameComponentDelta = "d"; const string NameComponents::NameComponentKey = "k"; const string NameComponents::NameComponentParity = "_parity"; const string NameComponents::NameComponentManifest = "_manifest"; #include <bitset> Name NamespaceInfo::getPrefix(int filter) const { using namespace prefix_filter; Name prefix(basePrefix_); if (filter) { if (filter&(Library^Base)) prefix.append(Name(NameComponents::NameComponentApp)).appendVersion(apiVersion_); if (filter&(Stream^Library)) prefix.append((streamType_ == MediaStreamParams::MediaStreamType::MediaStreamTypeAudio ? NameComponents::NameComponentAudio : NameComponents::NameComponentVideo)).append(streamName_); if (filter&(StreamTS^Stream) && threadName_ != "") prefix.appendTimestamp(streamTimestamp_); if (threadName_ != "" && (filter&(Thread^StreamTS) || filter&(ThreadNT^StreamTS) & streamType_ == MediaStreamParams::MediaStreamType::MediaStreamTypeVideo)) { prefix.append(threadName_); } if (isMeta_) { if (filter&(Segment^Thread)) prefix.append(NameComponents::NameComponentMeta); if (filter&(Segment^Sample)) { prefix.appendVersion(metaVersion_).appendSegment(segNo_); } } else { if (filter&(Thread^ThreadNT) && threadName_ != "" && streamType_ == MediaStreamParams::MediaStreamType::MediaStreamTypeVideo) prefix.append((class_ == SampleClass::Delta ? NameComponents::NameComponentDelta : NameComponents::NameComponentKey)); if (filter&(Sample^Thread)) prefix.appendSequenceNumber(sampleNo_); if (filter&(Segment^Sample)) { if (isParity_) prefix.append(NameComponents::NameComponentParity); prefix.appendSegment(segNo_); } } } return prefix; } Name NamespaceInfo::getSuffix(int filter) const { using namespace suffix_filter; Name suffix; if (filter) { if (filter&(Library^Stream)) suffix.append(Name(NameComponents::NameComponentApp)).appendVersion(apiVersion_); if (filter&(Stream^Thread)) { suffix.append((streamType_ == MediaStreamParams::MediaStreamType::MediaStreamTypeAudio ? NameComponents::NameComponentAudio : NameComponents::NameComponentVideo)).append(streamName_); if (threadName_ != "") suffix.appendTimestamp(streamTimestamp_); } if (filter&(Thread^Sample) && threadName_ != "") suffix.append(threadName_); if (isMeta_) { if ((filter&(Thread^Sample) && threadName_ != "") || filter&(Stream^Thread)) suffix.append(NameComponents::NameComponentMeta); } if (filter&(Thread^Sample) && threadName_ != "" && streamType_ == MediaStreamParams::MediaStreamType::MediaStreamTypeVideo && !isMeta_) suffix.append((class_ == SampleClass::Delta ? NameComponents::NameComponentDelta : NameComponents::NameComponentKey)); if (filter&(Sample^Segment)) { if (isMeta_) suffix.appendVersion(metaVersion_); else suffix.appendSequenceNumber(sampleNo_); } if (filter&(Segment) && hasSegNo_) { if (isParity_) suffix.append(NameComponents::NameComponentParity); suffix.appendSegment(segNo_); } } return suffix; } //****************************************************************************** vector<string> ndnrtcVersionComponents() { string version = NameComponents::fullVersion(); std::vector<string> components; boost::erase_all(version, "v"); boost::split(components, version, boost::is_any_of("."), boost::token_compress_on); return components; } std::string NameComponents::fullVersion() { return std::string(PACKAGE_VERSION); } unsigned int NameComponents::nameApiVersion() { return (unsigned int)atoi(ndnrtcVersionComponents().front().c_str()); } Name NameComponents::ndnrtcSuffix() { return Name(NameComponentApp).appendVersion(nameApiVersion()); } Name NameComponents::streamPrefix(MediaStreamParams::MediaStreamType type, std::string basePrefix) { Name n = Name(basePrefix); n.append(ndnrtcSuffix()); return ((type == MediaStreamParams::MediaStreamType::MediaStreamTypeAudio) ? n.append(NameComponentAudio) : n.append(NameComponentVideo)); } Name NameComponents::audioStreamPrefix(string basePrefix) { return streamPrefix(MediaStreamParams::MediaStreamType::MediaStreamTypeAudio, basePrefix); } Name NameComponents::videoStreamPrefix(string basePrefix) { return streamPrefix(MediaStreamParams::MediaStreamType::MediaStreamTypeVideo, basePrefix); } //****************************************************************************** bool extractMeta(const ndn::Name& name, NamespaceInfo& info) { // example: name == %FD%05/%00%00 if (name.size() >= 1 && name[0].isVersion()) { info.metaVersion_ = name[0].toVersion(); if (name.size() >= 2) { info.segNo_ = name[1].toSegment(); info.hasSegNo_ = true; } else info.hasSegNo_ = false; return true; } return false; } bool extractVideoStreamInfo(const ndn::Name& name, NamespaceInfo& info) { if (name.size() == 1) { info.streamName_ = name[0].toEscapedString(); return true; } if (name.size() == 2 && name[1].isTimestamp()) { info.streamName_ = name[0].toEscapedString(); info.streamTimestamp_ = name[1].toTimestamp(); return true; } if (name.size() < 3) return false; int idx = 0; info.streamName_ = name[idx++].toEscapedString(); info.isMeta_ = (name[idx++] == Name::Component(NameComponents::NameComponentMeta)); if (info.isMeta_) { // example: name == camera/_meta/%FD%05/%00%00 info.segmentClass_ = SegmentClass::Meta; info.threadName_ = ""; return extractMeta(name.getSubName(idx), info); } else { // example: name == camera/%FC%00%00%01c_%27%DE%D6/hi/d/%FE%07/%00%00 info.class_ = SampleClass::Unknown; info.segmentClass_ = SegmentClass::Unknown; info.streamTimestamp_ = name[idx-1].toTimestamp(); info.threadName_ = name[idx++].toEscapedString(); if (name.size() <= idx) return true; info.isMeta_ = (name[idx++] == Name::Component(NameComponents::NameComponentMeta)); if (info.isMeta_) { // example: camera/%FC%00%00%01c_%27%DE%D6/hi/_meta/%FD%05/%00%00 info.segmentClass_ = SegmentClass::Meta; if(name.size() > idx-1 && extractMeta(name.getSubName(idx), info)) return true; return true; } if (name[idx-1] == Name::Component(NameComponents::NameComponentDelta) || name[idx-1] == Name::Component(NameComponents::NameComponentKey)) { info.isDelta_ = (name[idx-1] == Name::Component(NameComponents::NameComponentDelta)); info.class_ = (info.isDelta_ ? SampleClass::Delta : SampleClass::Key); try{ if (name.size() > idx) info.sampleNo_ = (PacketNumber)name[idx++].toSequenceNumber(); else { info.hasSeqNo_ = false; return true; } info.hasSeqNo_ = true; if (name.size() > idx) { info.isParity_ = (name[idx] == Name::Component(NameComponents::NameComponentParity)); info.hasSegNo_ = true; if (info.isParity_ && name.size() > idx+1) { info.segmentClass_ = SegmentClass::Parity; info.segNo_ = name[idx+1].toSegment(); return true; } else { if (info.isParity_) return false; else { if (name[idx] == Name::Component(NameComponents::NameComponentManifest)) info.segmentClass_ = SegmentClass::Manifest; else { info.segmentClass_ = SegmentClass::Data; info.segNo_ = name[idx].toSegment(); } } return true; } } else { info.segmentClass_ = SegmentClass::Unknown; info.hasSegNo_ = false; return true; } } catch (std::runtime_error& e) { return false; } } } return false; } bool extractAudioStreamInfo(const ndn::Name& name, NamespaceInfo& info) { if (name.size() == 1) { info.streamName_ = name[0].toEscapedString(); return true; } if (name.size() == 2 && name[1].isTimestamp()) { info.streamName_ = name[0].toEscapedString(); info.streamTimestamp_ = name[1].toTimestamp(); return true; } if (name.size() < 2) return false; int idx = 0; info.streamName_ = name[idx++].toEscapedString(); info.isMeta_ = (name[idx++] == Name::Component(NameComponents::NameComponentMeta)); if (info.isMeta_) { info.segmentClass_ = SegmentClass::Meta; if (name.size() < idx+1) return false; info.threadName_ = ""; return extractMeta(name.getSubName(idx), info);; } else { info.class_ = SampleClass::Unknown; info.segmentClass_ = SegmentClass::Unknown; info.streamTimestamp_ = name[idx-1].toTimestamp(); info.threadName_ = name[idx++].toEscapedString(); if (name.size() == 3) { info.hasSeqNo_ = false; return true; } info.isMeta_ = (name[idx] == Name::Component(NameComponents::NameComponentMeta)); if (info.isMeta_) { info.segmentClass_ = SegmentClass::Meta; if (name.size() > idx+1 && extractMeta(name.getSubName(idx+1), info)) return true; return true; } info.isDelta_ = true; info.class_ = SampleClass::Delta; try { if (name.size() > 3) info.sampleNo_ = (PacketNumber)name[idx++].toSequenceNumber(); info.hasSeqNo_ = true; if (name.size() > idx) { if (name[idx] == Name::Component(NameComponents::NameComponentManifest)) info.segmentClass_ = SegmentClass::Manifest; else { info.hasSegNo_ = true; info.segmentClass_ = SegmentClass::Data; info.segNo_ = name[idx].toSegment(); } return true; } else { info.hasSegNo_ = false; return true; } } catch (std::runtime_error& e) { return false; } } return false; } bool NameComponents::extractInfo(const ndn::Name& name, NamespaceInfo& info) { bool goodName = false; static Name ndnrtcSubName(NameComponents::NameComponentApp); Name subName; int i; for (i = name.size()-2; i > 0 && !goodName; --i) { subName = name.getSubName(i); goodName = ndnrtcSubName.match(subName); } if (goodName) { info.basePrefix_ = name.getSubName(0, i+1); if ((goodName = subName[1].isVersion())) { info.apiVersion_ = subName[1].toVersion(); if (subName.size() > 2 && (goodName = (subName[2] == Name::Component(NameComponents::NameComponentAudio) || subName[2] == Name::Component(NameComponents::NameComponentVideo))) ) { info.streamType_ = (subName[2] == Name::Component(NameComponents::NameComponentAudio) ? MediaStreamParams::MediaStreamType::MediaStreamTypeAudio : MediaStreamParams::MediaStreamType::MediaStreamTypeVideo ); if (info.streamType_ == MediaStreamParams::MediaStreamType::MediaStreamTypeAudio) return extractAudioStreamInfo(subName.getSubName(3), info); else return extractVideoStreamInfo(subName.getSubName(3), info); } } } return false; }
fix NameComponent::extractInfo()
fix NameComponent::extractInfo()
C++
bsd-2-clause
remap/ndnrtc,remap/ndnrtc,remap/ndnrtc,remap/ndnrtc
c8bb79978e287d991897e98a539a92e6b744f14e
util/dynamic_bloom_test.cc
util/dynamic_bloom_test.cc
// Copyright (c) 2013, Facebook, Inc. All rights reserved. // This source code is licensed under the BSD-style license found in the // LICENSE file in the root directory of this source tree. An additional grant // of patent rights can be found in the PATENTS file in the same directory. #include <algorithm> #include <gflags/gflags.h> #include "dynamic_bloom.h" #include "port/port.h" #include "util/logging.h" #include "util/testharness.h" #include "util/testutil.h" #include "util/stop_watch.h" DEFINE_int32(bits_per_key, 10, ""); DEFINE_int32(num_probes, 6, ""); DEFINE_bool(enable_perf, false, ""); namespace rocksdb { static Slice Key(uint64_t i, char* buffer) { memcpy(buffer, &i, sizeof(i)); return Slice(buffer, sizeof(i)); } class DynamicBloomTest { }; TEST(DynamicBloomTest, EmptyFilter) { DynamicBloom bloom1(100, 0, 2); ASSERT_TRUE(!bloom1.MayContain("hello")); ASSERT_TRUE(!bloom1.MayContain("world")); DynamicBloom bloom2(CACHE_LINE_SIZE * 8 * 2 - 1, 1, 2); ASSERT_TRUE(!bloom2.MayContain("hello")); ASSERT_TRUE(!bloom2.MayContain("world")); } TEST(DynamicBloomTest, Small) { DynamicBloom bloom1(100, 0, 2); bloom1.Add("hello"); bloom1.Add("world"); ASSERT_TRUE(bloom1.MayContain("hello")); ASSERT_TRUE(bloom1.MayContain("world")); ASSERT_TRUE(!bloom1.MayContain("x")); ASSERT_TRUE(!bloom1.MayContain("foo")); DynamicBloom bloom2(CACHE_LINE_SIZE * 8 * 2 - 1, 1, 2); bloom2.Add("hello"); bloom2.Add("world"); ASSERT_TRUE(bloom2.MayContain("hello")); ASSERT_TRUE(bloom2.MayContain("world")); ASSERT_TRUE(!bloom2.MayContain("x")); ASSERT_TRUE(!bloom2.MayContain("foo")); } static uint32_t NextNum(uint32_t num) { if (num < 10) { num += 1; } else if (num < 100) { num += 10; } else if (num < 1000) { num += 100; } else { num += 1000; } return num; } TEST(DynamicBloomTest, VaryingLengths) { char buffer[sizeof(int)]; // Count number of filters that significantly exceed the false positive rate int mediocre_filters = 0; int good_filters = 0; fprintf(stderr, "bits_per_key: %d num_probes: %d\n", FLAGS_bits_per_key, FLAGS_num_probes); for (uint32_t cl_per_block = 0; cl_per_block < FLAGS_num_probes; ++cl_per_block) { for (uint32_t num = 1; num <= 10000; num = NextNum(num)) { uint32_t bloom_bits = 0; if (cl_per_block == 0) { bloom_bits = std::max(num * FLAGS_bits_per_key, 64U); } else { bloom_bits = std::max(num * FLAGS_bits_per_key, cl_per_block * CACHE_LINE_SIZE * 8); } DynamicBloom bloom(bloom_bits, cl_per_block, FLAGS_num_probes); for (uint64_t i = 0; i < num; i++) { bloom.Add(Key(i, buffer)); ASSERT_TRUE(bloom.MayContain(Key(i, buffer))); } // All added keys must match for (uint64_t i = 0; i < num; i++) { ASSERT_TRUE(bloom.MayContain(Key(i, buffer))) << "Num " << num << "; key " << i; } // Check false positive rate int result = 0; for (uint64_t i = 0; i < 10000; i++) { if (bloom.MayContain(Key(i + 1000000000, buffer))) { result++; } } double rate = result / 10000.0; fprintf(stderr, "False positives: %5.2f%% @ num = %6u, bloom_bits = %6u, " "cl per block = %u\n", rate*100.0, num, bloom_bits, cl_per_block); if (rate > 0.0125) mediocre_filters++; // Allowed, but not too often else good_filters++; } fprintf(stderr, "Filters: %d good, %d mediocre\n", good_filters, mediocre_filters); ASSERT_LE(mediocre_filters, good_filters/5); } } TEST(DynamicBloomTest, perf) { StopWatchNano timer(Env::Default()); if (!FLAGS_enable_perf) { return; } for (uint64_t m = 1; m <= 8; ++m) { const uint64_t num_keys = m * 8 * 1024 * 1024; fprintf(stderr, "testing %luM keys\n", m * 8); DynamicBloom std_bloom(num_keys * 10, 0, FLAGS_num_probes); timer.Start(); for (uint64_t i = 1; i <= num_keys; ++i) { std_bloom.Add(Slice(reinterpret_cast<const char*>(&i), 8)); } uint64_t elapsed = timer.ElapsedNanos(); fprintf(stderr, "standard bloom, avg add latency %lu\n", elapsed / num_keys); uint64_t count = 0; timer.Start(); for (uint64_t i = 1; i <= num_keys; ++i) { if (std_bloom.MayContain(Slice(reinterpret_cast<const char*>(&i), 8))) { ++count; } } elapsed = timer.ElapsedNanos(); fprintf(stderr, "standard bloom, avg query latency %lu\n", elapsed / count); ASSERT_TRUE(count == num_keys); for (int cl_per_block = 1; cl_per_block <= FLAGS_num_probes; ++cl_per_block) { DynamicBloom blocked_bloom(num_keys * 10, cl_per_block, FLAGS_num_probes); timer.Start(); for (uint64_t i = 1; i <= num_keys; ++i) { blocked_bloom.Add(Slice(reinterpret_cast<const char*>(&i), 8)); } uint64_t elapsed = timer.ElapsedNanos(); fprintf(stderr, "blocked bloom(%d), avg add latency %lu\n", cl_per_block, elapsed / num_keys); uint64_t count = 0; timer.Start(); for (uint64_t i = 1; i <= num_keys; ++i) { if (blocked_bloom.MayContain( Slice(reinterpret_cast<const char*>(&i), 8))) { ++count; } } elapsed = timer.ElapsedNanos(); fprintf(stderr, "blocked bloom(%d), avg query latency %lu\n", cl_per_block, elapsed / count); ASSERT_TRUE(count == num_keys); } } } } // namespace rocksdb int main(int argc, char** argv) { google::ParseCommandLineFlags(&argc, &argv, true); return rocksdb::test::RunAllTests(); }
// Copyright (c) 2013, Facebook, Inc. All rights reserved. // This source code is licensed under the BSD-style license found in the // LICENSE file in the root directory of this source tree. An additional grant // of patent rights can be found in the PATENTS file in the same directory. #include <algorithm> #include <gflags/gflags.h> #include "dynamic_bloom.h" #include "port/port.h" #include "util/logging.h" #include "util/testharness.h" #include "util/testutil.h" #include "util/stop_watch.h" DEFINE_int32(bits_per_key, 10, ""); DEFINE_int32(num_probes, 6, ""); DEFINE_bool(enable_perf, false, ""); namespace rocksdb { static Slice Key(uint64_t i, char* buffer) { memcpy(buffer, &i, sizeof(i)); return Slice(buffer, sizeof(i)); } class DynamicBloomTest { }; TEST(DynamicBloomTest, EmptyFilter) { DynamicBloom bloom1(100, 0, 2); ASSERT_TRUE(!bloom1.MayContain("hello")); ASSERT_TRUE(!bloom1.MayContain("world")); DynamicBloom bloom2(CACHE_LINE_SIZE * 8 * 2 - 1, 1, 2); ASSERT_TRUE(!bloom2.MayContain("hello")); ASSERT_TRUE(!bloom2.MayContain("world")); } TEST(DynamicBloomTest, Small) { DynamicBloom bloom1(100, 0, 2); bloom1.Add("hello"); bloom1.Add("world"); ASSERT_TRUE(bloom1.MayContain("hello")); ASSERT_TRUE(bloom1.MayContain("world")); ASSERT_TRUE(!bloom1.MayContain("x")); ASSERT_TRUE(!bloom1.MayContain("foo")); DynamicBloom bloom2(CACHE_LINE_SIZE * 8 * 2 - 1, 1, 2); bloom2.Add("hello"); bloom2.Add("world"); ASSERT_TRUE(bloom2.MayContain("hello")); ASSERT_TRUE(bloom2.MayContain("world")); ASSERT_TRUE(!bloom2.MayContain("x")); ASSERT_TRUE(!bloom2.MayContain("foo")); } static uint32_t NextNum(uint32_t num) { if (num < 10) { num += 1; } else if (num < 100) { num += 10; } else if (num < 1000) { num += 100; } else { num += 1000; } return num; } TEST(DynamicBloomTest, VaryingLengths) { char buffer[sizeof(uint64_t)]; // Count number of filters that significantly exceed the false positive rate int mediocre_filters = 0; int good_filters = 0; fprintf(stderr, "bits_per_key: %d num_probes: %d\n", FLAGS_bits_per_key, FLAGS_num_probes); for (uint32_t cl_per_block = 0; cl_per_block < FLAGS_num_probes; ++cl_per_block) { for (uint32_t num = 1; num <= 10000; num = NextNum(num)) { uint32_t bloom_bits = 0; if (cl_per_block == 0) { bloom_bits = std::max(num * FLAGS_bits_per_key, 64U); } else { bloom_bits = std::max(num * FLAGS_bits_per_key, cl_per_block * CACHE_LINE_SIZE * 8); } DynamicBloom bloom(bloom_bits, cl_per_block, FLAGS_num_probes); for (uint64_t i = 0; i < num; i++) { bloom.Add(Key(i, buffer)); ASSERT_TRUE(bloom.MayContain(Key(i, buffer))); } // All added keys must match for (uint64_t i = 0; i < num; i++) { ASSERT_TRUE(bloom.MayContain(Key(i, buffer))) << "Num " << num << "; key " << i; } // Check false positive rate int result = 0; for (uint64_t i = 0; i < 10000; i++) { if (bloom.MayContain(Key(i + 1000000000, buffer))) { result++; } } double rate = result / 10000.0; fprintf(stderr, "False positives: %5.2f%% @ num = %6u, bloom_bits = %6u, " "cl per block = %u\n", rate*100.0, num, bloom_bits, cl_per_block); if (rate > 0.0125) mediocre_filters++; // Allowed, but not too often else good_filters++; } fprintf(stderr, "Filters: %d good, %d mediocre\n", good_filters, mediocre_filters); ASSERT_LE(mediocre_filters, good_filters/5); } } TEST(DynamicBloomTest, perf) { StopWatchNano timer(Env::Default()); if (!FLAGS_enable_perf) { return; } for (uint64_t m = 1; m <= 8; ++m) { const uint64_t num_keys = m * 8 * 1024 * 1024; fprintf(stderr, "testing %luM keys\n", m * 8); DynamicBloom std_bloom(num_keys * 10, 0, FLAGS_num_probes); timer.Start(); for (uint64_t i = 1; i <= num_keys; ++i) { std_bloom.Add(Slice(reinterpret_cast<const char*>(&i), 8)); } uint64_t elapsed = timer.ElapsedNanos(); fprintf(stderr, "standard bloom, avg add latency %lu\n", elapsed / num_keys); uint64_t count = 0; timer.Start(); for (uint64_t i = 1; i <= num_keys; ++i) { if (std_bloom.MayContain(Slice(reinterpret_cast<const char*>(&i), 8))) { ++count; } } elapsed = timer.ElapsedNanos(); fprintf(stderr, "standard bloom, avg query latency %lu\n", elapsed / count); ASSERT_TRUE(count == num_keys); for (int cl_per_block = 1; cl_per_block <= FLAGS_num_probes; ++cl_per_block) { DynamicBloom blocked_bloom(num_keys * 10, cl_per_block, FLAGS_num_probes); timer.Start(); for (uint64_t i = 1; i <= num_keys; ++i) { blocked_bloom.Add(Slice(reinterpret_cast<const char*>(&i), 8)); } uint64_t elapsed = timer.ElapsedNanos(); fprintf(stderr, "blocked bloom(%d), avg add latency %lu\n", cl_per_block, elapsed / num_keys); uint64_t count = 0; timer.Start(); for (uint64_t i = 1; i <= num_keys; ++i) { if (blocked_bloom.MayContain( Slice(reinterpret_cast<const char*>(&i), 8))) { ++count; } } elapsed = timer.ElapsedNanos(); fprintf(stderr, "blocked bloom(%d), avg query latency %lu\n", cl_per_block, elapsed / count); ASSERT_TRUE(count == num_keys); } } } } // namespace rocksdb int main(int argc, char** argv) { google::ParseCommandLineFlags(&argc, &argv, true); return rocksdb::test::RunAllTests(); }
fix the buffer overflow in dynamic_bloom_test
fix the buffer overflow in dynamic_bloom_test Summary: int -> uint64_t Test Plan: it think it is pretty obvious will run asan_check before committing Reviewers: igor, haobo Reviewed By: igor CC: leveldb Differential Revision: https://reviews.facebook.net/D17241
C++
bsd-3-clause
tsheasha/rocksdb,lgscofield/rocksdb,tschottdorf/rocksdb,biddyweb/rocksdb,vmx/rocksdb,msb-at-yahoo/rocksdb,kaschaeffer/rocksdb,alihalabyah/rocksdb,vmx/rocksdb,Vaisman/rocksdb,kaschaeffer/rocksdb,SunguckLee/RocksDB,hobinyoon/rocksdb,JackLian/rocksdb,Andymic/rocksdb,geraldoandradee/rocksdb,siddhartharay007/rocksdb,skunkwerks/rocksdb,amyvmiwei/rocksdb,norton/rocksdb,jalexanderqed/rocksdb,OverlordQ/rocksdb,alihalabyah/rocksdb,wenduo/rocksdb,kaschaeffer/rocksdb,anagav/rocksdb,alihalabyah/rocksdb,virtdb/rocksdb,kaschaeffer/rocksdb,rDSN-Projects/rocksdb.replicated,alihalabyah/rocksdb,JackLian/rocksdb,sorphi/rocksdb,wenduo/rocksdb,OverlordQ/rocksdb,sorphi/rocksdb,Applied-Duality/rocksdb,JackLian/rocksdb,fengshao0907/rocksdb,amyvmiwei/rocksdb,tsheasha/rocksdb,sorphi/rocksdb,wat-ze-hex/rocksdb,kaschaeffer/rocksdb,caijieming-baidu/rocksdb,anagav/rocksdb,RyanTech/rocksdb,norton/rocksdb,luckywhu/rocksdb,facebook/rocksdb,tizzybec/rocksdb,zhangpng/rocksdb,geraldoandradee/rocksdb,JohnPJenkins/rocksdb,makelivedotnet/rocksdb,JoeWoo/rocksdb,NickCis/rocksdb,biddyweb/rocksdb,hobinyoon/rocksdb,msb-at-yahoo/rocksdb,wlqGit/rocksdb,JohnPJenkins/rocksdb,facebook/rocksdb,caijieming-baidu/rocksdb,biddyweb/rocksdb,tizzybec/rocksdb,temicai/rocksdb,sorphi/rocksdb,msb-at-yahoo/rocksdb,zhangpng/rocksdb,lgscofield/rocksdb,Vaisman/rocksdb,lgscofield/rocksdb,hobinyoon/rocksdb,bbiao/rocksdb,tsheasha/rocksdb,mbarbon/rocksdb,JackLian/rocksdb,vmx/rocksdb,anagav/rocksdb,wskplho/rocksdb,wenduo/rocksdb,tizzybec/rocksdb,norton/rocksdb,OverlordQ/rocksdb,sorphi/rocksdb,flabby/rocksdb,dkorolev/rocksdb,mbarbon/rocksdb,anagav/rocksdb,biddyweb/rocksdb,temicai/rocksdb,rDSN-Projects/rocksdb.replicated,virtdb/rocksdb,skunkwerks/rocksdb,luckywhu/rocksdb,ylong/rocksdb,flabby/rocksdb,temicai/rocksdb,virtdb/rocksdb,geraldoandradee/rocksdb,Andymic/rocksdb,ryneli/rocksdb,vmx/rocksdb,amyvmiwei/rocksdb,dkorolev/rocksdb,JoeWoo/rocksdb,bbiao/rocksdb,tizzybec/rocksdb,Applied-Duality/rocksdb,SunguckLee/RocksDB,caijieming-baidu/rocksdb,luckywhu/rocksdb,tsheasha/rocksdb,luckywhu/rocksdb,geraldoandradee/rocksdb,JohnPJenkins/rocksdb,ryneli/rocksdb,RyanTech/rocksdb,norton/rocksdb,temicai/rocksdb,flabby/rocksdb,makelivedotnet/rocksdb,tschottdorf/rocksdb,mbarbon/rocksdb,vashstorm/rocksdb,facebook/rocksdb,JoeWoo/rocksdb,Andymic/rocksdb,luckywhu/rocksdb,bbiao/rocksdb,vmx/rocksdb,wskplho/rocksdb,wenduo/rocksdb,hobinyoon/rocksdb,luckywhu/rocksdb,anagav/rocksdb,wenduo/rocksdb,flabby/rocksdb,fengshao0907/rocksdb,siddhartharay007/rocksdb,dkorolev/rocksdb,dkorolev/rocksdb,wat-ze-hex/rocksdb,RyanTech/rocksdb,msb-at-yahoo/rocksdb,siddhartharay007/rocksdb,biddyweb/rocksdb,mbarbon/rocksdb,vashstorm/rocksdb,Vaisman/rocksdb,wat-ze-hex/rocksdb,JohnPJenkins/rocksdb,JackLian/rocksdb,NickCis/rocksdb,skunkwerks/rocksdb,Applied-Duality/rocksdb,wat-ze-hex/rocksdb,ylong/rocksdb,mbarbon/rocksdb,virtdb/rocksdb,rDSN-Projects/rocksdb.replicated,virtdb/rocksdb,Applied-Duality/rocksdb,flabby/rocksdb,RyanTech/rocksdb,OverlordQ/rocksdb,fengshao0907/rocksdb,tschottdorf/rocksdb,hobinyoon/rocksdb,geraldoandradee/rocksdb,vashstorm/rocksdb,virtdb/rocksdb,ryneli/rocksdb,wlqGit/rocksdb,ryneli/rocksdb,amyvmiwei/rocksdb,msb-at-yahoo/rocksdb,biddyweb/rocksdb,tsheasha/rocksdb,vmx/rocksdb,dkorolev/rocksdb,Vaisman/rocksdb,tsheasha/rocksdb,skunkwerks/rocksdb,wskplho/rocksdb,lgscofield/rocksdb,amyvmiwei/rocksdb,makelivedotnet/rocksdb,tsheasha/rocksdb,SunguckLee/RocksDB,Andymic/rocksdb,alihalabyah/rocksdb,zhangpng/rocksdb,Vaisman/rocksdb,temicai/rocksdb,zhangpng/rocksdb,vashstorm/rocksdb,jalexanderqed/rocksdb,bbiao/rocksdb,vashstorm/rocksdb,geraldoandradee/rocksdb,bbiao/rocksdb,NickCis/rocksdb,makelivedotnet/rocksdb,skunkwerks/rocksdb,SunguckLee/RocksDB,rDSN-Projects/rocksdb.replicated,bbiao/rocksdb,NickCis/rocksdb,makelivedotnet/rocksdb,wlqGit/rocksdb,lgscofield/rocksdb,ryneli/rocksdb,tschottdorf/rocksdb,Applied-Duality/rocksdb,wenduo/rocksdb,RyanTech/rocksdb,facebook/rocksdb,flabby/rocksdb,makelivedotnet/rocksdb,jalexanderqed/rocksdb,hobinyoon/rocksdb,siddhartharay007/rocksdb,JohnPJenkins/rocksdb,alihalabyah/rocksdb,alihalabyah/rocksdb,JoeWoo/rocksdb,wskplho/rocksdb,wskplho/rocksdb,OverlordQ/rocksdb,norton/rocksdb,Andymic/rocksdb,JoeWoo/rocksdb,ryneli/rocksdb,anagav/rocksdb,facebook/rocksdb,hobinyoon/rocksdb,tizzybec/rocksdb,RyanTech/rocksdb,vashstorm/rocksdb,Andymic/rocksdb,zhangpng/rocksdb,bbiao/rocksdb,wskplho/rocksdb,ylong/rocksdb,tschottdorf/rocksdb,mbarbon/rocksdb,norton/rocksdb,caijieming-baidu/rocksdb,JohnPJenkins/rocksdb,siddhartharay007/rocksdb,SunguckLee/RocksDB,temicai/rocksdb,tizzybec/rocksdb,kaschaeffer/rocksdb,ylong/rocksdb,wenduo/rocksdb,IMCG/RcoksDB,NickCis/rocksdb,luckywhu/rocksdb,caijieming-baidu/rocksdb,siddhartharay007/rocksdb,wlqGit/rocksdb,ryneli/rocksdb,dkorolev/rocksdb,mbarbon/rocksdb,lgscofield/rocksdb,amyvmiwei/rocksdb,ylong/rocksdb,tsheasha/rocksdb,IMCG/RcoksDB,wlqGit/rocksdb,vmx/rocksdb,siddhartharay007/rocksdb,flabby/rocksdb,fengshao0907/rocksdb,SunguckLee/RocksDB,RyanTech/rocksdb,wskplho/rocksdb,wat-ze-hex/rocksdb,fengshao0907/rocksdb,tizzybec/rocksdb,JoeWoo/rocksdb,Applied-Duality/rocksdb,jalexanderqed/rocksdb,biddyweb/rocksdb,jalexanderqed/rocksdb,norton/rocksdb,jalexanderqed/rocksdb,caijieming-baidu/rocksdb,lgscofield/rocksdb,fengshao0907/rocksdb,rDSN-Projects/rocksdb.replicated,anagav/rocksdb,Vaisman/rocksdb,IMCG/RcoksDB,wat-ze-hex/rocksdb,IMCG/RcoksDB,zhangpng/rocksdb,skunkwerks/rocksdb,rDSN-Projects/rocksdb.replicated,Andymic/rocksdb,rDSN-Projects/rocksdb.replicated,facebook/rocksdb,vmx/rocksdb,fengshao0907/rocksdb,wlqGit/rocksdb,OverlordQ/rocksdb,msb-at-yahoo/rocksdb,JoeWoo/rocksdb,sorphi/rocksdb,caijieming-baidu/rocksdb,tschottdorf/rocksdb,wat-ze-hex/rocksdb,virtdb/rocksdb,kaschaeffer/rocksdb,sorphi/rocksdb,IMCG/RcoksDB,IMCG/RcoksDB,IMCG/RcoksDB,norton/rocksdb,wlqGit/rocksdb,facebook/rocksdb,NickCis/rocksdb,jalexanderqed/rocksdb,ylong/rocksdb,skunkwerks/rocksdb,wenduo/rocksdb,bbiao/rocksdb,JackLian/rocksdb,SunguckLee/RocksDB,SunguckLee/RocksDB,zhangpng/rocksdb,vashstorm/rocksdb,OverlordQ/rocksdb,dkorolev/rocksdb,temicai/rocksdb,Vaisman/rocksdb,wat-ze-hex/rocksdb,amyvmiwei/rocksdb,JohnPJenkins/rocksdb,JackLian/rocksdb,facebook/rocksdb,geraldoandradee/rocksdb,Applied-Duality/rocksdb,NickCis/rocksdb,hobinyoon/rocksdb,Andymic/rocksdb,ylong/rocksdb,makelivedotnet/rocksdb
dfecd62235af1209c11bfc359ef9338e4349f3f5
scene/gui/option_button.cpp
scene/gui/option_button.cpp
/*************************************************************************/ /* option_button.cpp */ /*************************************************************************/ /* This file is part of: */ /* GODOT ENGINE */ /* https://godotengine.org */ /*************************************************************************/ /* Copyright (c) 2007-2019 Juan Linietsky, Ariel Manzur. */ /* Copyright (c) 2014-2019 Godot Engine contributors (cf. AUTHORS.md) */ /* */ /* 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 "option_button.h" #include "core/print_string.h" Size2 OptionButton::get_minimum_size() const { Size2 minsize = Button::get_minimum_size(); if (has_icon("arrow")) minsize.width += Control::get_icon("arrow")->get_width() + get_constant("hseparation"); return minsize; } void OptionButton::_notification(int p_what) { if (p_what == NOTIFICATION_DRAW) { if (!has_icon("arrow")) return; RID ci = get_canvas_item(); Ref<Texture> arrow = Control::get_icon("arrow"); Ref<StyleBox> normal = get_stylebox("normal"); Color clr = Color(1, 1, 1); if (get_constant("modulate_arrow")) { switch (get_draw_mode()) { case DRAW_PRESSED: clr = get_color("font_color_pressed"); break; case DRAW_HOVER: clr = get_color("font_color_hover"); break; case DRAW_DISABLED: clr = get_color("font_color_disabled"); break; default: clr = get_color("font_color"); } } Size2 size = get_size(); Point2 ofs(size.width - arrow->get_width() - get_constant("arrow_margin"), int(Math::abs((size.height - arrow->get_height()) / 2))); arrow->draw(ci, ofs, clr); } else if (p_what == NOTIFICATION_VISIBILITY_CHANGED) { if (!is_visible_in_tree()) { popup->hide(); } } } void OptionButton::_focused(int p_which) { emit_signal("item_focused", p_which); } void OptionButton::_selected(int p_which) { _select(p_which, true); } void OptionButton::pressed() { Size2 size = get_size(); popup->set_global_position(get_global_position() + Size2(0, size.height * get_global_transform().get_scale().y)); popup->set_size(Size2(size.width, 0)); popup->set_scale(get_global_transform().get_scale()); popup->popup(); } void OptionButton::add_icon_item(const Ref<Texture> &p_icon, const String &p_label, int p_id) { popup->add_icon_radio_check_item(p_icon, p_label, p_id); if (popup->get_item_count() == 1) select(0); } void OptionButton::add_item(const String &p_label, int p_id) { popup->add_radio_check_item(p_label, p_id); if (popup->get_item_count() == 1) select(0); } void OptionButton::set_item_text(int p_idx, const String &p_text) { popup->set_item_text(p_idx, p_text); } void OptionButton::set_item_icon(int p_idx, const Ref<Texture> &p_icon) { popup->set_item_icon(p_idx, p_icon); } void OptionButton::set_item_id(int p_idx, int p_id) { popup->set_item_id(p_idx, p_id); } void OptionButton::set_item_metadata(int p_idx, const Variant &p_metadata) { popup->set_item_metadata(p_idx, p_metadata); } void OptionButton::set_item_disabled(int p_idx, bool p_disabled) { popup->set_item_disabled(p_idx, p_disabled); } String OptionButton::get_item_text(int p_idx) const { return popup->get_item_text(p_idx); } Ref<Texture> OptionButton::get_item_icon(int p_idx) const { return popup->get_item_icon(p_idx); } int OptionButton::get_item_id(int p_idx) const { return popup->get_item_id(p_idx); } int OptionButton::get_item_index(int p_id) const { return popup->get_item_index(p_id); } Variant OptionButton::get_item_metadata(int p_idx) const { return popup->get_item_metadata(p_idx); } bool OptionButton::is_item_disabled(int p_idx) const { return popup->is_item_disabled(p_idx); } int OptionButton::get_item_count() const { return popup->get_item_count(); } void OptionButton::add_separator() { popup->add_separator(); } void OptionButton::clear() { popup->clear(); set_text(""); current = -1; } void OptionButton::_select(int p_which, bool p_emit) { if (p_which < 0) return; if (p_which == current) return; ERR_FAIL_INDEX(p_which, popup->get_item_count()); for (int i = 0; i < popup->get_item_count(); i++) { popup->set_item_checked(i, i == p_which); } current = p_which; set_text(popup->get_item_text(current)); set_icon(popup->get_item_icon(current)); if (is_inside_tree() && p_emit) emit_signal("item_selected", current); } void OptionButton::_select_int(int p_which) { if (p_which < 0 || p_which >= popup->get_item_count()) return; _select(p_which, false); } void OptionButton::select(int p_idx) { _select(p_idx, false); } int OptionButton::get_selected() const { return current; } int OptionButton::get_selected_id() const { int idx = get_selected(); if (idx < 0) return 0; return get_item_id(current); } Variant OptionButton::get_selected_metadata() const { int idx = get_selected(); if (idx < 0) return Variant(); return get_item_metadata(current); } void OptionButton::remove_item(int p_idx) { popup->remove_item(p_idx); } PopupMenu *OptionButton::get_popup() const { return popup; } Array OptionButton::_get_items() const { Array items; for (int i = 0; i < get_item_count(); i++) { items.push_back(get_item_text(i)); items.push_back(get_item_icon(i)); items.push_back(is_item_disabled(i)); items.push_back(get_item_id(i)); items.push_back(get_item_metadata(i)); } return items; } void OptionButton::_set_items(const Array &p_items) { ERR_FAIL_COND(p_items.size() % 5); clear(); for (int i = 0; i < p_items.size(); i += 5) { String text = p_items[i + 0]; Ref<Texture> icon = p_items[i + 1]; bool disabled = p_items[i + 2]; int id = p_items[i + 3]; Variant meta = p_items[i + 4]; int idx = get_item_count(); add_item(text, id); set_item_icon(idx, icon); set_item_disabled(idx, disabled); set_item_metadata(idx, meta); } } void OptionButton::get_translatable_strings(List<String> *p_strings) const { popup->get_translatable_strings(p_strings); } void OptionButton::_bind_methods() { ClassDB::bind_method(D_METHOD("_selected"), &OptionButton::_selected); ClassDB::bind_method(D_METHOD("_focused"), &OptionButton::_focused); ClassDB::bind_method(D_METHOD("add_item", "label", "id"), &OptionButton::add_item, DEFVAL(-1)); ClassDB::bind_method(D_METHOD("add_icon_item", "texture", "label", "id"), &OptionButton::add_icon_item, DEFVAL(-1)); ClassDB::bind_method(D_METHOD("set_item_text", "idx", "text"), &OptionButton::set_item_text); ClassDB::bind_method(D_METHOD("set_item_icon", "idx", "texture"), &OptionButton::set_item_icon); ClassDB::bind_method(D_METHOD("set_item_disabled", "idx", "disabled"), &OptionButton::set_item_disabled); ClassDB::bind_method(D_METHOD("set_item_id", "idx", "id"), &OptionButton::set_item_id); ClassDB::bind_method(D_METHOD("set_item_metadata", "idx", "metadata"), &OptionButton::set_item_metadata); ClassDB::bind_method(D_METHOD("get_item_text", "idx"), &OptionButton::get_item_text); ClassDB::bind_method(D_METHOD("get_item_icon", "idx"), &OptionButton::get_item_icon); ClassDB::bind_method(D_METHOD("get_item_id", "idx"), &OptionButton::get_item_id); ClassDB::bind_method(D_METHOD("get_item_index", "id"), &OptionButton::get_item_index); ClassDB::bind_method(D_METHOD("get_item_metadata", "idx"), &OptionButton::get_item_metadata); ClassDB::bind_method(D_METHOD("is_item_disabled", "idx"), &OptionButton::is_item_disabled); ClassDB::bind_method(D_METHOD("get_item_count"), &OptionButton::get_item_count); ClassDB::bind_method(D_METHOD("add_separator"), &OptionButton::add_separator); ClassDB::bind_method(D_METHOD("clear"), &OptionButton::clear); ClassDB::bind_method(D_METHOD("select", "idx"), &OptionButton::select); ClassDB::bind_method(D_METHOD("get_selected"), &OptionButton::get_selected); ClassDB::bind_method(D_METHOD("get_selected_id"), &OptionButton::get_selected_id); ClassDB::bind_method(D_METHOD("get_selected_metadata"), &OptionButton::get_selected_metadata); ClassDB::bind_method(D_METHOD("remove_item", "idx"), &OptionButton::remove_item); ClassDB::bind_method(D_METHOD("_select_int"), &OptionButton::_select_int); ClassDB::bind_method(D_METHOD("get_popup"), &OptionButton::get_popup); ClassDB::bind_method(D_METHOD("_set_items"), &OptionButton::_set_items); ClassDB::bind_method(D_METHOD("_get_items"), &OptionButton::_get_items); ADD_PROPERTY(PropertyInfo(Variant::ARRAY, "items", PROPERTY_HINT_NONE, "", PROPERTY_USAGE_NOEDITOR | PROPERTY_USAGE_INTERNAL), "_set_items", "_get_items"); // "selected" property must come after "items", otherwise GH-10213 occurs ADD_PROPERTY(PropertyInfo(Variant::INT, "selected"), "_select_int", "get_selected"); ADD_SIGNAL(MethodInfo("item_selected", PropertyInfo(Variant::INT, "id"))); ADD_SIGNAL(MethodInfo("item_focused", PropertyInfo(Variant::INT, "id"))); } OptionButton::OptionButton() { current = -1; set_toggle_mode(true); set_text_align(ALIGN_LEFT); set_action_mode(ACTION_MODE_BUTTON_PRESS); popup = memnew(PopupMenu); popup->hide(); add_child(popup); popup->set_pass_on_modal_close_click(false); popup->set_notify_transform(true); popup->set_allow_search(true); popup->connect("index_pressed", this, "_selected"); popup->connect("id_focused", this, "_focused"); popup->connect("popup_hide", this, "set_pressed", varray(false)); } OptionButton::~OptionButton() { }
/*************************************************************************/ /* option_button.cpp */ /*************************************************************************/ /* This file is part of: */ /* GODOT ENGINE */ /* https://godotengine.org */ /*************************************************************************/ /* Copyright (c) 2007-2019 Juan Linietsky, Ariel Manzur. */ /* Copyright (c) 2014-2019 Godot Engine contributors (cf. AUTHORS.md) */ /* */ /* 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 "option_button.h" #include "core/print_string.h" Size2 OptionButton::get_minimum_size() const { Size2 minsize = Button::get_minimum_size(); if (has_icon("arrow")) minsize.width += Control::get_icon("arrow")->get_width() + get_constant("hseparation"); return minsize; } void OptionButton::_notification(int p_what) { switch (p_what) { case NOTIFICATION_DRAW: { if (!has_icon("arrow")) return; RID ci = get_canvas_item(); Ref<Texture> arrow = Control::get_icon("arrow"); Ref<StyleBox> normal = get_stylebox("normal"); Color clr = Color(1, 1, 1); if (get_constant("modulate_arrow")) { switch (get_draw_mode()) { case DRAW_PRESSED: clr = get_color("font_color_pressed"); break; case DRAW_HOVER: clr = get_color("font_color_hover"); break; case DRAW_DISABLED: clr = get_color("font_color_disabled"); break; default: clr = get_color("font_color"); } } Size2 size = get_size(); Point2 ofs(size.width - arrow->get_width() - get_constant("arrow_margin"), int(Math::abs((size.height - arrow->get_height()) / 2))); arrow->draw(ci, ofs, clr); } break; case NOTIFICATION_VISIBILITY_CHANGED: { if (!is_visible_in_tree()) { popup->hide(); } } break; } } void OptionButton::_focused(int p_which) { emit_signal("item_focused", p_which); } void OptionButton::_selected(int p_which) { _select(p_which, true); } void OptionButton::pressed() { Size2 size = get_size(); popup->set_global_position(get_global_position() + Size2(0, size.height * get_global_transform().get_scale().y)); popup->set_size(Size2(size.width, 0)); popup->set_scale(get_global_transform().get_scale()); popup->popup(); } void OptionButton::add_icon_item(const Ref<Texture> &p_icon, const String &p_label, int p_id) { popup->add_icon_radio_check_item(p_icon, p_label, p_id); if (popup->get_item_count() == 1) select(0); } void OptionButton::add_item(const String &p_label, int p_id) { popup->add_radio_check_item(p_label, p_id); if (popup->get_item_count() == 1) select(0); } void OptionButton::set_item_text(int p_idx, const String &p_text) { popup->set_item_text(p_idx, p_text); } void OptionButton::set_item_icon(int p_idx, const Ref<Texture> &p_icon) { popup->set_item_icon(p_idx, p_icon); } void OptionButton::set_item_id(int p_idx, int p_id) { popup->set_item_id(p_idx, p_id); } void OptionButton::set_item_metadata(int p_idx, const Variant &p_metadata) { popup->set_item_metadata(p_idx, p_metadata); } void OptionButton::set_item_disabled(int p_idx, bool p_disabled) { popup->set_item_disabled(p_idx, p_disabled); } String OptionButton::get_item_text(int p_idx) const { return popup->get_item_text(p_idx); } Ref<Texture> OptionButton::get_item_icon(int p_idx) const { return popup->get_item_icon(p_idx); } int OptionButton::get_item_id(int p_idx) const { return popup->get_item_id(p_idx); } int OptionButton::get_item_index(int p_id) const { return popup->get_item_index(p_id); } Variant OptionButton::get_item_metadata(int p_idx) const { return popup->get_item_metadata(p_idx); } bool OptionButton::is_item_disabled(int p_idx) const { return popup->is_item_disabled(p_idx); } int OptionButton::get_item_count() const { return popup->get_item_count(); } void OptionButton::add_separator() { popup->add_separator(); } void OptionButton::clear() { popup->clear(); set_text(""); current = -1; } void OptionButton::_select(int p_which, bool p_emit) { if (p_which < 0) return; if (p_which == current) return; ERR_FAIL_INDEX(p_which, popup->get_item_count()); for (int i = 0; i < popup->get_item_count(); i++) { popup->set_item_checked(i, i == p_which); } current = p_which; set_text(popup->get_item_text(current)); set_icon(popup->get_item_icon(current)); if (is_inside_tree() && p_emit) emit_signal("item_selected", current); } void OptionButton::_select_int(int p_which) { if (p_which < 0 || p_which >= popup->get_item_count()) return; _select(p_which, false); } void OptionButton::select(int p_idx) { _select(p_idx, false); } int OptionButton::get_selected() const { return current; } int OptionButton::get_selected_id() const { int idx = get_selected(); if (idx < 0) return 0; return get_item_id(current); } Variant OptionButton::get_selected_metadata() const { int idx = get_selected(); if (idx < 0) return Variant(); return get_item_metadata(current); } void OptionButton::remove_item(int p_idx) { popup->remove_item(p_idx); } PopupMenu *OptionButton::get_popup() const { return popup; } Array OptionButton::_get_items() const { Array items; for (int i = 0; i < get_item_count(); i++) { items.push_back(get_item_text(i)); items.push_back(get_item_icon(i)); items.push_back(is_item_disabled(i)); items.push_back(get_item_id(i)); items.push_back(get_item_metadata(i)); } return items; } void OptionButton::_set_items(const Array &p_items) { ERR_FAIL_COND(p_items.size() % 5); clear(); for (int i = 0; i < p_items.size(); i += 5) { String text = p_items[i + 0]; Ref<Texture> icon = p_items[i + 1]; bool disabled = p_items[i + 2]; int id = p_items[i + 3]; Variant meta = p_items[i + 4]; int idx = get_item_count(); add_item(text, id); set_item_icon(idx, icon); set_item_disabled(idx, disabled); set_item_metadata(idx, meta); } } void OptionButton::get_translatable_strings(List<String> *p_strings) const { popup->get_translatable_strings(p_strings); } void OptionButton::_bind_methods() { ClassDB::bind_method(D_METHOD("_selected"), &OptionButton::_selected); ClassDB::bind_method(D_METHOD("_focused"), &OptionButton::_focused); ClassDB::bind_method(D_METHOD("add_item", "label", "id"), &OptionButton::add_item, DEFVAL(-1)); ClassDB::bind_method(D_METHOD("add_icon_item", "texture", "label", "id"), &OptionButton::add_icon_item, DEFVAL(-1)); ClassDB::bind_method(D_METHOD("set_item_text", "idx", "text"), &OptionButton::set_item_text); ClassDB::bind_method(D_METHOD("set_item_icon", "idx", "texture"), &OptionButton::set_item_icon); ClassDB::bind_method(D_METHOD("set_item_disabled", "idx", "disabled"), &OptionButton::set_item_disabled); ClassDB::bind_method(D_METHOD("set_item_id", "idx", "id"), &OptionButton::set_item_id); ClassDB::bind_method(D_METHOD("set_item_metadata", "idx", "metadata"), &OptionButton::set_item_metadata); ClassDB::bind_method(D_METHOD("get_item_text", "idx"), &OptionButton::get_item_text); ClassDB::bind_method(D_METHOD("get_item_icon", "idx"), &OptionButton::get_item_icon); ClassDB::bind_method(D_METHOD("get_item_id", "idx"), &OptionButton::get_item_id); ClassDB::bind_method(D_METHOD("get_item_index", "id"), &OptionButton::get_item_index); ClassDB::bind_method(D_METHOD("get_item_metadata", "idx"), &OptionButton::get_item_metadata); ClassDB::bind_method(D_METHOD("is_item_disabled", "idx"), &OptionButton::is_item_disabled); ClassDB::bind_method(D_METHOD("get_item_count"), &OptionButton::get_item_count); ClassDB::bind_method(D_METHOD("add_separator"), &OptionButton::add_separator); ClassDB::bind_method(D_METHOD("clear"), &OptionButton::clear); ClassDB::bind_method(D_METHOD("select", "idx"), &OptionButton::select); ClassDB::bind_method(D_METHOD("get_selected"), &OptionButton::get_selected); ClassDB::bind_method(D_METHOD("get_selected_id"), &OptionButton::get_selected_id); ClassDB::bind_method(D_METHOD("get_selected_metadata"), &OptionButton::get_selected_metadata); ClassDB::bind_method(D_METHOD("remove_item", "idx"), &OptionButton::remove_item); ClassDB::bind_method(D_METHOD("_select_int"), &OptionButton::_select_int); ClassDB::bind_method(D_METHOD("get_popup"), &OptionButton::get_popup); ClassDB::bind_method(D_METHOD("_set_items"), &OptionButton::_set_items); ClassDB::bind_method(D_METHOD("_get_items"), &OptionButton::_get_items); ADD_PROPERTY(PropertyInfo(Variant::ARRAY, "items", PROPERTY_HINT_NONE, "", PROPERTY_USAGE_NOEDITOR | PROPERTY_USAGE_INTERNAL), "_set_items", "_get_items"); // "selected" property must come after "items", otherwise GH-10213 occurs ADD_PROPERTY(PropertyInfo(Variant::INT, "selected"), "_select_int", "get_selected"); ADD_SIGNAL(MethodInfo("item_selected", PropertyInfo(Variant::INT, "id"))); ADD_SIGNAL(MethodInfo("item_focused", PropertyInfo(Variant::INT, "id"))); } OptionButton::OptionButton() { current = -1; set_toggle_mode(true); set_text_align(ALIGN_LEFT); set_action_mode(ACTION_MODE_BUTTON_PRESS); popup = memnew(PopupMenu); popup->hide(); add_child(popup); popup->set_pass_on_modal_close_click(false); popup->set_notify_transform(true); popup->set_allow_search(true); popup->connect("index_pressed", this, "_selected"); popup->connect("id_focused", this, "_focused"); popup->connect("popup_hide", this, "set_pressed", varray(false)); } OptionButton::~OptionButton() { }
Change if to switch in OptionButton
Change if to switch in OptionButton
C++
mit
godotengine/godot,Valentactive/godot,sanikoyes/godot,firefly2442/godot,ZuBsPaCe/godot,Paulloz/godot,honix/godot,josempans/godot,BastiaanOlij/godot,vnen/godot,vnen/godot,honix/godot,BastiaanOlij/godot,godotengine/godot,firefly2442/godot,josempans/godot,vkbsb/godot,MarianoGnu/godot,firefly2442/godot,Shockblast/godot,BastiaanOlij/godot,MarianoGnu/godot,MarianoGnu/godot,ZuBsPaCe/godot,DmitriySalnikov/godot,ZuBsPaCe/godot,akien-mga/godot,akien-mga/godot,Zylann/godot,DmitriySalnikov/godot,guilhermefelipecgs/godot,josempans/godot,Valentactive/godot,guilhermefelipecgs/godot,Zylann/godot,godotengine/godot,firefly2442/godot,MarianoGnu/godot,honix/godot,MarianoGnu/godot,vkbsb/godot,pkowal1982/godot,MarianoGnu/godot,BastiaanOlij/godot,Valentactive/godot,godotengine/godot,pkowal1982/godot,DmitriySalnikov/godot,Valentactive/godot,akien-mga/godot,sanikoyes/godot,Zylann/godot,josempans/godot,Zylann/godot,MarianoGnu/godot,josempans/godot,Paulloz/godot,ex/godot,BastiaanOlij/godot,vkbsb/godot,josempans/godot,sanikoyes/godot,ZuBsPaCe/godot,guilhermefelipecgs/godot,guilhermefelipecgs/godot,Faless/godot,ex/godot,Paulloz/godot,guilhermefelipecgs/godot,firefly2442/godot,BastiaanOlij/godot,BastiaanOlij/godot,vkbsb/godot,honix/godot,ZuBsPaCe/godot,Paulloz/godot,guilhermefelipecgs/godot,pkowal1982/godot,sanikoyes/godot,ex/godot,godotengine/godot,Faless/godot,ex/godot,vnen/godot,Faless/godot,sanikoyes/godot,vnen/godot,pkowal1982/godot,godotengine/godot,DmitriySalnikov/godot,vnen/godot,ZuBsPaCe/godot,Shockblast/godot,firefly2442/godot,Faless/godot,Shockblast/godot,Faless/godot,Paulloz/godot,Faless/godot,Valentactive/godot,josempans/godot,godotengine/godot,vkbsb/godot,BastiaanOlij/godot,sanikoyes/godot,pkowal1982/godot,DmitriySalnikov/godot,Faless/godot,firefly2442/godot,ex/godot,akien-mga/godot,guilhermefelipecgs/godot,ex/godot,pkowal1982/godot,Shockblast/godot,Shockblast/godot,ZuBsPaCe/godot,DmitriySalnikov/godot,ZuBsPaCe/godot,Zylann/godot,Valentactive/godot,Zylann/godot,Shockblast/godot,vnen/godot,sanikoyes/godot,vnen/godot,vnen/godot,akien-mga/godot,Paulloz/godot,DmitriySalnikov/godot,Faless/godot,pkowal1982/godot,ex/godot,vkbsb/godot,akien-mga/godot,honix/godot,akien-mga/godot,MarianoGnu/godot,Valentactive/godot,vkbsb/godot,Shockblast/godot,josempans/godot,Valentactive/godot,vkbsb/godot,firefly2442/godot,honix/godot,akien-mga/godot,ex/godot,Shockblast/godot,sanikoyes/godot,godotengine/godot,guilhermefelipecgs/godot,Paulloz/godot,pkowal1982/godot,Zylann/godot,Zylann/godot
50dd9d3336c4b43e02884f2fb44c5fa0331a9d63
runtime/browser/ui/native_app_window_tizen.cc
runtime/browser/ui/native_app_window_tizen.cc
// Copyright (c) 2013 Intel Corporation. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "xwalk/runtime/browser/ui/native_app_window_tizen.h" #include "base/logging.h" #include "base/memory/scoped_ptr.h" #include "ui/aura/root_window.h" #include "ui/aura/window.h" #include "ui/gfx/transform.h" #include "ui/gfx/rect.h" #include "ui/gfx/screen.h" #include "ui/views/view.h" #include "ui/views/widget/widget.h" #include "xwalk/runtime/browser/ui/top_view_layout_views.h" #include "xwalk/runtime/browser/xwalk_browser_main_parts_tizen.h" namespace xwalk { NativeAppWindowTizen::NativeAppWindowTizen( const NativeAppWindow::CreateParams& create_params) : NativeAppWindowViews(create_params), #if defined(OS_TIZEN_MOBILE) indicator_widget_(new TizenSystemIndicatorWidget()), indicator_container_(new WidgetContainerView(indicator_widget_)), #endif allowed_orientations_(ANY) { } void NativeAppWindowTizen::Initialize() { NativeAppWindowViews::Initialize(); // Get display info such as device_scale_factor, and current // rotation (orientation). NOTE: This is a local copy of the info. display_ = gfx::Screen::GetNativeScreen()->GetPrimaryDisplay(); aura::Window* root_window = GetNativeWindow()->GetRootWindow(); DCHECK(root_window); root_window->AddObserver(this); OrientationMask ua_default = XWalkBrowserMainPartsTizen::GetAllowedUAOrientations(); OnAllowedOrientationsChanged(ua_default); if (SensorProvider* sensor = SensorProvider::GetInstance()) { gfx::Display::Rotation rotation = GetClosestAllowedRotation(sensor->GetCurrentRotation()); display_.set_rotation(rotation); ApplyDisplayRotation(); sensor->AddObserver(this); } } NativeAppWindowTizen::~NativeAppWindowTizen() { if (SensorProvider::GetInstance()) SensorProvider::GetInstance()->RemoveObserver(this); } void NativeAppWindowTizen::ViewHierarchyChanged( const ViewHierarchyChangedDetails& details) { if (details.is_add && details.child == this) { NativeAppWindowViews::ViewHierarchyChanged(details); #if defined(OS_TIZEN_MOBILE) indicator_widget_->Initialize(GetNativeWindow()); top_view_layout()->set_top_view(indicator_container_.get()); AddChildView(indicator_container_.get()); #endif } } void NativeAppWindowTizen::OnWindowBoundsChanged( aura::Window* window, const gfx::Rect& old_bounds, const gfx::Rect& new_bounds) { aura::Window* root_window = GetNativeWindow()->GetRootWindow(); DCHECK_EQ(root_window, window); // Change the bounds of child windows to make touch work correctly. GetNativeWindow()->parent()->SetBounds(new_bounds); GetNativeWindow()->SetBounds(new_bounds); GetWidget()->GetRootView()->SetSize(new_bounds.size()); } void NativeAppWindowTizen::OnWindowDestroying(aura::Window* window) { // Must be removed here and not in the destructor, as the aura::Window is // already destroyed when our destructor runs. window->RemoveObserver(this); } void NativeAppWindowTizen::OnWindowVisibilityChanging( aura::Window* window, bool visible) { if (visible) ApplyDisplayRotation(); } gfx::Transform NativeAppWindowTizen::GetRotationTransform() const { // This method assumed a fixed portrait device. As everything // is calculated from the fixed position we do not update the // display bounds after rotation change. gfx::Transform rotate; float one_pixel = 1.0f / display_.device_scale_factor(); switch (display_.rotation()) { case gfx::Display::ROTATE_0: break; case gfx::Display::ROTATE_90: rotate.Translate(display_.bounds().width() - one_pixel, 0); rotate.Rotate(90); break; case gfx::Display::ROTATE_270: rotate.Translate(0, display_.bounds().height() - one_pixel); rotate.Rotate(270); break; case gfx::Display::ROTATE_180: rotate.Translate(display_.bounds().width() - one_pixel, display_.bounds().height() - one_pixel); rotate.Rotate(180); break; } return rotate; } namespace { // Rotates a binary mask of 4 positions to the left. unsigned rotl4(unsigned value, int shift) { unsigned res = (value << shift); if (res > (1 << 4) - 1) res = res >> 4; return res; } bool IsLandscapeOrientation(const gfx::Display::Rotation& rotation) { return rotation == gfx::Display::ROTATE_90 || rotation == gfx::Display::ROTATE_270; } } // namespace. gfx::Display::Rotation NativeAppWindowTizen::GetClosestAllowedRotation( gfx::Display::Rotation rotation) const { unsigned result = PORTRAIT_PRIMARY; // gfx::Display::Rotation starts at portrait-primary and // belongs to the set [0:3]. result = rotl4(result, rotation); // Test current orientation if (allowed_orientations_ & result) return rotation; // Test orientation right of current one. if (allowed_orientations_ & rotl4(result, 1)) return static_cast<gfx::Display::Rotation>((rotation + 1) % 4); // Test orientation left of current one. if (allowed_orientations_ & rotl4(result, 3)) return static_cast<gfx::Display::Rotation>((rotation + 3) % 4); // Test orientation opposite of current one. if (allowed_orientations_ & rotl4(result, 2)) return static_cast<gfx::Display::Rotation>((rotation + 2) % 4); NOTREACHED(); return rotation; } Orientation NativeAppWindowTizen::GetCurrentOrientation() const { switch (display_.rotation()) { case gfx::Display::ROTATE_0: return PORTRAIT_PRIMARY; case gfx::Display::ROTATE_90: return LANDSCAPE_PRIMARY; case gfx::Display::ROTATE_180: return PORTRAIT_SECONDARY; case gfx::Display::ROTATE_270: return LANDSCAPE_SECONDARY; default: NOTREACHED(); return PORTRAIT_PRIMARY; } } void NativeAppWindowTizen::OnAllowedOrientationsChanged( OrientationMask orientations) { allowed_orientations_ = orientations; // As we might have been locked before our current orientation // might not fit with the sensor orienation. gfx::Display::Rotation rotation = display_.rotation(); if (SensorProvider* sensor = SensorProvider::GetInstance()) rotation = sensor->GetCurrentRotation(); rotation = GetClosestAllowedRotation(rotation); if (display_.rotation() == rotation) return; display_.set_rotation(rotation); ApplyDisplayRotation(); } void NativeAppWindowTizen::OnRotationChanged( gfx::Display::Rotation rotation) { // We always store the current sensor position, even if we do not // apply it in case the window is invisible. rotation = GetClosestAllowedRotation(rotation); if (display_.rotation() == rotation) return; display_.set_rotation(rotation); ApplyDisplayRotation(); } void NativeAppWindowTizen::UpdateTopViewOverlay() { top_view_layout()->SetUseOverlay( IsLandscapeOrientation(display_.rotation())); } void NativeAppWindowTizen::ApplyDisplayRotation() { if (observer()) observer()->OnOrientationChanged(GetCurrentOrientation()); aura::Window* root_window = GetNativeWindow()->GetRootWindow(); if (!root_window->IsVisible()) return; UpdateTopViewOverlay(); #if defined(OS_TIZEN_MOBILE) indicator_widget_->SetDisplay(display_); #endif root_window->SetTransform(GetRotationTransform()); } } // namespace xwalk
// Copyright (c) 2013 Intel Corporation. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "xwalk/runtime/browser/ui/native_app_window_tizen.h" #include "base/logging.h" #include "base/memory/scoped_ptr.h" #include "ui/aura/window.h" #include "ui/gfx/transform.h" #include "ui/gfx/rect.h" #include "ui/gfx/screen.h" #include "ui/views/view.h" #include "ui/views/widget/widget.h" #include "xwalk/runtime/browser/ui/top_view_layout_views.h" #include "xwalk/runtime/browser/xwalk_browser_main_parts_tizen.h" namespace xwalk { NativeAppWindowTizen::NativeAppWindowTizen( const NativeAppWindow::CreateParams& create_params) : NativeAppWindowViews(create_params), #if defined(OS_TIZEN_MOBILE) indicator_widget_(new TizenSystemIndicatorWidget()), indicator_container_(new WidgetContainerView(indicator_widget_)), #endif allowed_orientations_(ANY) { } void NativeAppWindowTizen::Initialize() { NativeAppWindowViews::Initialize(); // Get display info such as device_scale_factor, and current // rotation (orientation). NOTE: This is a local copy of the info. display_ = gfx::Screen::GetNativeScreen()->GetPrimaryDisplay(); aura::Window* root_window = GetNativeWindow()->GetRootWindow(); DCHECK(root_window); root_window->AddObserver(this); OrientationMask ua_default = XWalkBrowserMainPartsTizen::GetAllowedUAOrientations(); OnAllowedOrientationsChanged(ua_default); if (SensorProvider* sensor = SensorProvider::GetInstance()) { gfx::Display::Rotation rotation = GetClosestAllowedRotation(sensor->GetCurrentRotation()); display_.set_rotation(rotation); ApplyDisplayRotation(); sensor->AddObserver(this); } } NativeAppWindowTizen::~NativeAppWindowTizen() { if (SensorProvider::GetInstance()) SensorProvider::GetInstance()->RemoveObserver(this); } void NativeAppWindowTizen::ViewHierarchyChanged( const ViewHierarchyChangedDetails& details) { if (details.is_add && details.child == this) { NativeAppWindowViews::ViewHierarchyChanged(details); #if defined(OS_TIZEN_MOBILE) indicator_widget_->Initialize(GetNativeWindow()); top_view_layout()->set_top_view(indicator_container_.get()); AddChildView(indicator_container_.get()); #endif } } void NativeAppWindowTizen::OnWindowBoundsChanged( aura::Window* window, const gfx::Rect& old_bounds, const gfx::Rect& new_bounds) { aura::Window* root_window = GetNativeWindow()->GetRootWindow(); DCHECK_EQ(root_window, window); // Change the bounds of child windows to make touch work correctly. GetNativeWindow()->parent()->SetBounds(new_bounds); GetNativeWindow()->SetBounds(new_bounds); GetWidget()->GetRootView()->SetSize(new_bounds.size()); } void NativeAppWindowTizen::OnWindowDestroying(aura::Window* window) { // Must be removed here and not in the destructor, as the aura::Window is // already destroyed when our destructor runs. window->RemoveObserver(this); } void NativeAppWindowTizen::OnWindowVisibilityChanging( aura::Window* window, bool visible) { if (visible) ApplyDisplayRotation(); } gfx::Transform NativeAppWindowTizen::GetRotationTransform() const { // This method assumed a fixed portrait device. As everything // is calculated from the fixed position we do not update the // display bounds after rotation change. gfx::Transform rotate; float one_pixel = 1.0f / display_.device_scale_factor(); switch (display_.rotation()) { case gfx::Display::ROTATE_0: break; case gfx::Display::ROTATE_90: rotate.Translate(display_.bounds().width() - one_pixel, 0); rotate.Rotate(90); break; case gfx::Display::ROTATE_270: rotate.Translate(0, display_.bounds().height() - one_pixel); rotate.Rotate(270); break; case gfx::Display::ROTATE_180: rotate.Translate(display_.bounds().width() - one_pixel, display_.bounds().height() - one_pixel); rotate.Rotate(180); break; } return rotate; } namespace { // Rotates a binary mask of 4 positions to the left. unsigned rotl4(unsigned value, int shift) { unsigned res = (value << shift); if (res > (1 << 4) - 1) res = res >> 4; return res; } bool IsLandscapeOrientation(const gfx::Display::Rotation& rotation) { return rotation == gfx::Display::ROTATE_90 || rotation == gfx::Display::ROTATE_270; } } // namespace. gfx::Display::Rotation NativeAppWindowTizen::GetClosestAllowedRotation( gfx::Display::Rotation rotation) const { unsigned result = PORTRAIT_PRIMARY; // gfx::Display::Rotation starts at portrait-primary and // belongs to the set [0:3]. result = rotl4(result, rotation); // Test current orientation if (allowed_orientations_ & result) return rotation; // Test orientation right of current one. if (allowed_orientations_ & rotl4(result, 1)) return static_cast<gfx::Display::Rotation>((rotation + 1) % 4); // Test orientation left of current one. if (allowed_orientations_ & rotl4(result, 3)) return static_cast<gfx::Display::Rotation>((rotation + 3) % 4); // Test orientation opposite of current one. if (allowed_orientations_ & rotl4(result, 2)) return static_cast<gfx::Display::Rotation>((rotation + 2) % 4); NOTREACHED(); return rotation; } Orientation NativeAppWindowTizen::GetCurrentOrientation() const { switch (display_.rotation()) { case gfx::Display::ROTATE_0: return PORTRAIT_PRIMARY; case gfx::Display::ROTATE_90: return LANDSCAPE_PRIMARY; case gfx::Display::ROTATE_180: return PORTRAIT_SECONDARY; case gfx::Display::ROTATE_270: return LANDSCAPE_SECONDARY; default: NOTREACHED(); return PORTRAIT_PRIMARY; } } void NativeAppWindowTizen::OnAllowedOrientationsChanged( OrientationMask orientations) { allowed_orientations_ = orientations; // As we might have been locked before our current orientation // might not fit with the sensor orienation. gfx::Display::Rotation rotation = display_.rotation(); if (SensorProvider* sensor = SensorProvider::GetInstance()) rotation = sensor->GetCurrentRotation(); rotation = GetClosestAllowedRotation(rotation); if (display_.rotation() == rotation) return; display_.set_rotation(rotation); ApplyDisplayRotation(); } void NativeAppWindowTizen::OnRotationChanged( gfx::Display::Rotation rotation) { // We always store the current sensor position, even if we do not // apply it in case the window is invisible. rotation = GetClosestAllowedRotation(rotation); if (display_.rotation() == rotation) return; display_.set_rotation(rotation); ApplyDisplayRotation(); } void NativeAppWindowTizen::UpdateTopViewOverlay() { top_view_layout()->SetUseOverlay( IsLandscapeOrientation(display_.rotation())); } void NativeAppWindowTizen::ApplyDisplayRotation() { if (observer()) observer()->OnOrientationChanged(GetCurrentOrientation()); aura::Window* root_window = GetNativeWindow()->GetRootWindow(); if (!root_window->IsVisible()) return; UpdateTopViewOverlay(); #if defined(OS_TIZEN_MOBILE) indicator_widget_->SetDisplay(display_); #endif root_window->SetTransform(GetRotationTransform()); } } // namespace xwalk
Fix header file changes
runtime/browser: Fix header file changes Offending CL: https://codereview.chromium.org/174803002
C++
bsd-3-clause
hgl888/crosswalk-efl,stonegithubs/crosswalk,crosswalk-project/crosswalk-efl,marcuspridham/crosswalk,jondong/crosswalk,baleboy/crosswalk,jondwillis/crosswalk,fujunwei/crosswalk,DonnaWuDongxia/crosswalk,shaochangbin/crosswalk,weiyirong/crosswalk-1,tedshroyer/crosswalk,minggangw/crosswalk,weiyirong/crosswalk-1,minggangw/crosswalk,tomatell/crosswalk,lincsoon/crosswalk,marcuspridham/crosswalk,Bysmyyr/crosswalk,hgl888/crosswalk,heke123/crosswalk,tedshroyer/crosswalk,DonnaWuDongxia/crosswalk,myroot/crosswalk,crosswalk-project/crosswalk,zliang7/crosswalk,tedshroyer/crosswalk,zeropool/crosswalk,heke123/crosswalk,xzhan96/crosswalk,darktears/crosswalk,TheDirtyCalvinist/spacewalk,RafuCater/crosswalk,ZhengXinCN/crosswalk,darktears/crosswalk,tedshroyer/crosswalk,xzhan96/crosswalk,zliang7/crosswalk,marcuspridham/crosswalk,myroot/crosswalk,rakuco/crosswalk,lincsoon/crosswalk,Bysmyyr/crosswalk,ZhengXinCN/crosswalk,axinging/crosswalk,pk-sam/crosswalk,lincsoon/crosswalk,crosswalk-project/crosswalk,jpike88/crosswalk,tedshroyer/crosswalk,pk-sam/crosswalk,zeropool/crosswalk,pk-sam/crosswalk,qjia7/crosswalk,weiyirong/crosswalk-1,PeterWangIntel/crosswalk,ZhengXinCN/crosswalk,Pluto-tv/crosswalk,rakuco/crosswalk,hgl888/crosswalk,leonhsl/crosswalk,myroot/crosswalk,zliang7/crosswalk,xzhan96/crosswalk,minggangw/crosswalk,jpike88/crosswalk,alex-zhang/crosswalk,stonegithubs/crosswalk,baleboy/crosswalk,Bysmyyr/crosswalk,qjia7/crosswalk,chuan9/crosswalk,siovene/crosswalk,darktears/crosswalk,huningxin/crosswalk,heke123/crosswalk,bestwpw/crosswalk,minggangw/crosswalk,lincsoon/crosswalk,dreamsxin/crosswalk,RafuCater/crosswalk,TheDirtyCalvinist/spacewalk,zliang7/crosswalk,leonhsl/crosswalk,DonnaWuDongxia/crosswalk,TheDirtyCalvinist/spacewalk,hgl888/crosswalk-efl,PeterWangIntel/crosswalk,pk-sam/crosswalk,crosswalk-project/crosswalk,myroot/crosswalk,xzhan96/crosswalk,zeropool/crosswalk,marcuspridham/crosswalk,chinakids/crosswalk,zeropool/crosswalk,Pluto-tv/crosswalk,siovene/crosswalk,baleboy/crosswalk,ZhengXinCN/crosswalk,chuan9/crosswalk,qjia7/crosswalk,baleboy/crosswalk,lincsoon/crosswalk,jondwillis/crosswalk,stonegithubs/crosswalk,jpike88/crosswalk,fujunwei/crosswalk,hgl888/crosswalk,xzhan96/crosswalk,chinakids/crosswalk,bestwpw/crosswalk,siovene/crosswalk,pk-sam/crosswalk,ZhengXinCN/crosswalk,Pluto-tv/crosswalk,hgl888/crosswalk,leonhsl/crosswalk,mrunalk/crosswalk,huningxin/crosswalk,shaochangbin/crosswalk,rakuco/crosswalk,PeterWangIntel/crosswalk,minggangw/crosswalk,dreamsxin/crosswalk,jondwillis/crosswalk,zeropool/crosswalk,weiyirong/crosswalk-1,bestwpw/crosswalk,alex-zhang/crosswalk,DonnaWuDongxia/crosswalk,baleboy/crosswalk,minggangw/crosswalk,bestwpw/crosswalk,minggangw/crosswalk,mrunalk/crosswalk,huningxin/crosswalk,shaochangbin/crosswalk,crosswalk-project/crosswalk-efl,chinakids/crosswalk,hgl888/crosswalk,jpike88/crosswalk,fujunwei/crosswalk,siovene/crosswalk,minggangw/crosswalk,pk-sam/crosswalk,hgl888/crosswalk-efl,marcuspridham/crosswalk,baleboy/crosswalk,crosswalk-project/crosswalk,jondong/crosswalk,darktears/crosswalk,rakuco/crosswalk,stonegithubs/crosswalk,mrunalk/crosswalk,zeropool/crosswalk,crosswalk-project/crosswalk-efl,crosswalk-project/crosswalk,jpike88/crosswalk,amaniak/crosswalk,XiaosongWei/crosswalk,fujunwei/crosswalk,rakuco/crosswalk,crosswalk-project/crosswalk,xzhan96/crosswalk,stonegithubs/crosswalk,qjia7/crosswalk,amaniak/crosswalk,crosswalk-project/crosswalk,stonegithubs/crosswalk,heke123/crosswalk,zeropool/crosswalk,heke123/crosswalk,shaochangbin/crosswalk,Bysmyyr/crosswalk,XiaosongWei/crosswalk,siovene/crosswalk,alex-zhang/crosswalk,hgl888/crosswalk-efl,jondong/crosswalk,zliang7/crosswalk,hgl888/crosswalk,chinakids/crosswalk,baleboy/crosswalk,rakuco/crosswalk,heke123/crosswalk,crosswalk-project/crosswalk-efl,Pluto-tv/crosswalk,dreamsxin/crosswalk,fujunwei/crosswalk,chinakids/crosswalk,hgl888/crosswalk,crosswalk-project/crosswalk-efl,crosswalk-project/crosswalk-efl,dreamsxin/crosswalk,bestwpw/crosswalk,amaniak/crosswalk,darktears/crosswalk,darktears/crosswalk,marcuspridham/crosswalk,DonnaWuDongxia/crosswalk,jpike88/crosswalk,tedshroyer/crosswalk,XiaosongWei/crosswalk,mrunalk/crosswalk,jondwillis/crosswalk,Pluto-tv/crosswalk,rakuco/crosswalk,XiaosongWei/crosswalk,jondwillis/crosswalk,RafuCater/crosswalk,tedshroyer/crosswalk,zliang7/crosswalk,baleboy/crosswalk,dreamsxin/crosswalk,alex-zhang/crosswalk,leonhsl/crosswalk,chuan9/crosswalk,axinging/crosswalk,PeterWangIntel/crosswalk,axinging/crosswalk,bestwpw/crosswalk,lincsoon/crosswalk,chuan9/crosswalk,XiaosongWei/crosswalk,bestwpw/crosswalk,fujunwei/crosswalk,tomatell/crosswalk,stonegithubs/crosswalk,mrunalk/crosswalk,TheDirtyCalvinist/spacewalk,weiyirong/crosswalk-1,jpike88/crosswalk,axinging/crosswalk,xzhan96/crosswalk,PeterWangIntel/crosswalk,Bysmyyr/crosswalk,hgl888/crosswalk-efl,Bysmyyr/crosswalk,huningxin/crosswalk,DonnaWuDongxia/crosswalk,jondwillis/crosswalk,jondong/crosswalk,tomatell/crosswalk,RafuCater/crosswalk,tomatell/crosswalk,amaniak/crosswalk,qjia7/crosswalk,zliang7/crosswalk,lincsoon/crosswalk,pk-sam/crosswalk,PeterWangIntel/crosswalk,weiyirong/crosswalk-1,mrunalk/crosswalk,qjia7/crosswalk,Bysmyyr/crosswalk,marcuspridham/crosswalk,DonnaWuDongxia/crosswalk,Pluto-tv/crosswalk,amaniak/crosswalk,axinging/crosswalk,zliang7/crosswalk,axinging/crosswalk,alex-zhang/crosswalk,chinakids/crosswalk,RafuCater/crosswalk,RafuCater/crosswalk,heke123/crosswalk,ZhengXinCN/crosswalk,heke123/crosswalk,jondong/crosswalk,fujunwei/crosswalk,lincsoon/crosswalk,dreamsxin/crosswalk,jondong/crosswalk,TheDirtyCalvinist/spacewalk,marcuspridham/crosswalk,shaochangbin/crosswalk,darktears/crosswalk,leonhsl/crosswalk,huningxin/crosswalk,PeterWangIntel/crosswalk,darktears/crosswalk,Bysmyyr/crosswalk,crosswalk-project/crosswalk-efl,XiaosongWei/crosswalk,crosswalk-project/crosswalk,RafuCater/crosswalk,myroot/crosswalk,xzhan96/crosswalk,tomatell/crosswalk,shaochangbin/crosswalk,chuan9/crosswalk,XiaosongWei/crosswalk,TheDirtyCalvinist/spacewalk,weiyirong/crosswalk-1,ZhengXinCN/crosswalk,dreamsxin/crosswalk,tomatell/crosswalk,siovene/crosswalk,chuan9/crosswalk,tomatell/crosswalk,myroot/crosswalk,siovene/crosswalk,axinging/crosswalk,huningxin/crosswalk,jondong/crosswalk,hgl888/crosswalk-efl,amaniak/crosswalk,amaniak/crosswalk,jondwillis/crosswalk,chuan9/crosswalk,hgl888/crosswalk-efl,alex-zhang/crosswalk,rakuco/crosswalk,hgl888/crosswalk,leonhsl/crosswalk,jondong/crosswalk,Pluto-tv/crosswalk,leonhsl/crosswalk,alex-zhang/crosswalk
a85f756efea60c1f6f13ac3010678c0a781ab960
samples/ExternalFunction/ExternalFunction.cpp
samples/ExternalFunction/ExternalFunction.cpp
// Base header file. Must be first. #include <Include/PlatformDefinitions.hpp> #include <cmath> #include <ctime> #include <iostream> #include <fstream> #include <util/PlatformUtils.hpp> #include <PlatformSupport/DOMStringHelper.hpp> #include <DOMSupport/DOMSupportDefault.hpp> #include <XPath/XObjectFactoryDefault.hpp> #include <XPath/XPath.hpp> #include <XPath/XPathSupportDefault.hpp> #include <XPath/XPathFactoryDefault.hpp> #include <XSLT/StylesheetConstructionContextDefault.hpp> #include <XSLT/StylesheetExecutionContextDefault.hpp> #include <XSLT/XSLTEngineImpl.hpp> #include <XSLT/XSLTInit.hpp> #include <XSLT/XSLTInputSource.hpp> #include <XSLT/XSLTProcessorEnvSupportDefault.hpp> #include <XSLT/XSLTResultTarget.hpp> #include <XercesParserLiaison/XercesDOMSupport.hpp> #include <XercesParserLiaison/XercesParserLiaison.hpp> // This class defines a function that will return the square root // of its argument. class FunctionSquareRoot : public Function { public: /** * Execute an XPath function object. The function must return a valid * object. * * @param executionContext executing context * @param context current context node * @param opPos current op position * @param args vector of pointers to XObject arguments * @return pointer to the result XObject */ virtual XObjectPtr execute( XPathExecutionContext& executionContext, XalanNode* context, int /* opPos */, const XObjectArgVectorType& args) { if (args.size() != 1) { executionContext.error("The square-root() function takes one argument!", context); } assert(args[0].null() == false); return executionContext.getXObjectFactory().createNumber(sqrt(args[0]->num())); } /** * Create a copy of the function object. * * @return pointer to the new object */ #if defined(XALAN_NO_COVARIANT_RETURN_TYPE) virtual Function* #else virtual FunctionSquareRoot* #endif clone() const { return new FunctionSquareRoot(*this); } private: // Not implemented... FunctionSquareRoot& operator=(const FunctionSquareRoot&); bool operator==(const FunctionSquareRoot&) const; }; // This class defines a function that will return the cube // of its argument. class FunctionCube : public Function { public: /** * Execute an XPath function object. The function must return a valid * object. * * @param executionContext executing context * @param context current context node * @param opPos current op position * @param args vector of pointers to XObject arguments * @return pointer to the result XObject */ virtual XObjectPtr execute( XPathExecutionContext& executionContext, XalanNode* context, int /* opPos */, const XObjectArgVectorType& args) { if (args.size() != 1) { executionContext.error("The cube() function takes one argument!", context); } assert(args[0].null() == false); return executionContext.getXObjectFactory().createNumber(pow(args[0]->num(), 3)); } /** * Create a copy of the function object. * * @return pointer to the new object */ #if defined(XALAN_NO_COVARIANT_RETURN_TYPE) virtual Function* #else virtual FunctionCube* #endif clone() const { return new FunctionCube(*this); } private: // Not implemented... FunctionCube& operator=(const FunctionCube&); bool operator==(const FunctionCube&) const; }; // This class defines a function that runs the C function // asctime() using the current system time. class FunctionAsctime : public Function { public: /** * Execute an XPath function object. The function must return a valid * object. Called if function has no parameters. * * @param executionContext executing context * @param context current context node * @return pointer to the result XObject */ virtual XObjectPtr execute( XPathExecutionContext& executionContext, XalanNode* context) { //if (args.size() != 0) //{ // executionContext.error("The asctime() function takes no arguments!", context); //} time_t theTime; time(&theTime); char* const theTimeString = asctime(localtime(&theTime)); // The resulting string has a newline character at the end, // so get rid of it. theTimeString[strlen(theTimeString) - 1] = '\0'; return executionContext.getXObjectFactory().createString(XalanDOMString(theTimeString)); } /** * Create a copy of the function object. * * @return pointer to the new object */ #if defined(XALAN_NO_COVARIANT_RETURN_TYPE) virtual Function* #else virtual FunctionAsctime* #endif clone() const { return new FunctionAsctime(*this); } private: // Not implemented... FunctionAsctime& operator=(const FunctionAsctime&); bool operator==(const FunctionAsctime&) const; }; int main( int argc, const char* /* argv */[]) { #if !defined(XALAN_NO_NAMESPACES) using std::cerr; using std::endl; using std::ofstream; #endif if (argc != 1) { cerr << "Usage: ExternalFunction" << endl << endl; } else { try { // Call the static initializer for Xerces... XMLPlatformUtils::Initialize(); { // Initialize the Xalan XSLT subsystem... XSLTInit theInit; // Create the support objects that are necessary for running the processor... XercesDOMSupport theDOMSupport; XercesParserLiaison theParserLiaison(theDOMSupport); XPathSupportDefault theXPathSupport(theDOMSupport); XSLTProcessorEnvSupportDefault theXSLTProcessorEnvSupport; XObjectFactoryDefault theXObjectFactory; XPathFactoryDefault theXPathFactory; // Create a processor... XSLTEngineImpl theProcessor( theParserLiaison, theXPathSupport, theXSLTProcessorEnvSupport, theDOMSupport, theXObjectFactory, theXPathFactory); // Connect the processor to the support object... theXSLTProcessorEnvSupport.setProcessor(&theProcessor); // Create a stylesheet construction context, and a stylesheet // execution context... StylesheetConstructionContextDefault theConstructionContext( theProcessor, theXSLTProcessorEnvSupport, theXPathFactory); StylesheetExecutionContextDefault theExecutionContext( theProcessor, theXSLTProcessorEnvSupport, theXPathSupport, theXObjectFactory); // Our input files... // WARNING!!! You may need to modify these absolute paths depending on where // you've put the Xalan sources. const XalanDOMString theXMLFileName("foo.xml"); const XalanDOMString theXSLFileName("foo.xsl"); // Our input sources... XSLTInputSource theInputSource(c_wstr(theXMLFileName)); XSLTInputSource theStylesheetSource(c_wstr(theXSLFileName)); // Our output target... const XalanDOMString theOutputFile("foo.out"); XSLTResultTarget theResultTarget(theOutputFile); // Install the function directly into the XPath // function table. We don't recommend doing this, // but you can if you want to be evil! ;-) Since // the function is in the XPath table, the XPath // parser will treat it like any other XPath // function. Therefore, it cannot have a namespace // prefix. It will also be available to every // processor in the executable's process, since there // is one static XPath function table. XPath::installFunction( XalanDOMString("asctime"), FunctionAsctime()); // The namespace for our functions... const XalanDOMString theNamespace("http://ExternalFunction.xalan-c++.xml.apache.org"); // Install the function in the global space. All // instances will know about the function, so all // processors which use an instance of this the // class XPathEnvSupportDefault will be able to // use the function. XSLTProcessorEnvSupportDefault::installExternalFunctionGlobal( theNamespace, XalanDOMString("square-root"), FunctionSquareRoot()); // Install the function in the local space. It will only // be installed in this instance, so no other instances // will know about the function... theXSLTProcessorEnvSupport.installExternalFunctionLocal( theNamespace, XalanDOMString("cube"), FunctionCube()); theProcessor.process( theInputSource, theStylesheetSource, theResultTarget, theConstructionContext, theExecutionContext); } // Call the static terminator for Xerces... XMLPlatformUtils::Terminate(); } catch(...) { cerr << "Exception caught!!!" << endl << endl; } } return 0; }
// Base header file. Must be first. #include <Include/PlatformDefinitions.hpp> #include <cmath> #include <ctime> #include <iostream> #include <fstream> #include <util/PlatformUtils.hpp> #include <PlatformSupport/DOMStringHelper.hpp> #include <DOMSupport/DOMSupportDefault.hpp> #include <XPath/XObjectFactoryDefault.hpp> #include <XPath/XPath.hpp> #include <XPath/XPathSupportDefault.hpp> #include <XPath/XPathFactoryDefault.hpp> #include <XSLT/StylesheetConstructionContextDefault.hpp> #include <XSLT/StylesheetExecutionContextDefault.hpp> #include <XSLT/XSLTEngineImpl.hpp> #include <XSLT/XSLTInit.hpp> #include <XSLT/XSLTInputSource.hpp> #include <XSLT/XSLTProcessorEnvSupportDefault.hpp> #include <XSLT/XSLTResultTarget.hpp> #include <XercesParserLiaison/XercesDOMSupport.hpp> #include <XercesParserLiaison/XercesParserLiaison.hpp> // This class defines a function that will return the square root // of its argument. class FunctionSquareRoot : public Function { public: /** * Execute an XPath function object. The function must return a valid * object. * * @param executionContext executing context * @param context current context node * @param opPos current op position * @param args vector of pointers to XObject arguments * @return pointer to the result XObject */ virtual XObjectPtr execute( XPathExecutionContext& executionContext, XalanNode* context, int /* opPos */, const XObjectArgVectorType& args) { if (args.size() != 1) { executionContext.error("The square-root() function takes one argument!", context); } assert(args[0].null() == false); return executionContext.getXObjectFactory().createNumber(sqrt(args[0]->num())); } /** * Create a copy of the function object. * * @return pointer to the new object */ #if defined(XALAN_NO_COVARIANT_RETURN_TYPE) virtual Function* #else virtual FunctionSquareRoot* #endif clone() const { return new FunctionSquareRoot(*this); } private: // Not implemented... FunctionSquareRoot& operator=(const FunctionSquareRoot&); bool operator==(const FunctionSquareRoot&) const; }; // This class defines a function that will return the cube // of its argument. class FunctionCube : public Function { public: /** * Execute an XPath function object. The function must return a valid * object. * * @param executionContext executing context * @param context current context node * @param opPos current op position * @param args vector of pointers to XObject arguments * @return pointer to the result XObject */ virtual XObjectPtr execute( XPathExecutionContext& executionContext, XalanNode* context, int /* opPos */, const XObjectArgVectorType& args) { if (args.size() != 1) { executionContext.error("The cube() function takes one argument!", context); } assert(args[0].null() == false); return executionContext.getXObjectFactory().createNumber(pow(args[0]->num(), 3)); } /** * Create a copy of the function object. * * @return pointer to the new object */ #if defined(XALAN_NO_COVARIANT_RETURN_TYPE) virtual Function* #else virtual FunctionCube* #endif clone() const { return new FunctionCube(*this); } private: // Not implemented... FunctionCube& operator=(const FunctionCube&); bool operator==(const FunctionCube&) const; }; // This class defines a function that runs the C function // asctime() using the current system time. class FunctionAsctime : public Function { public: /** * Execute an XPath function object. The function must return a valid * object. Called if function has no parameters. * * @param executionContext executing context * @param context current context node * @return pointer to the result XObject */ virtual XObjectPtr execute( XPathExecutionContext& executionContext, XalanNode* context) { time_t theTime; time(&theTime); char* const theTimeString = asctime(localtime(&theTime)); // The resulting string has a newline character at the end, // so get rid of it. theTimeString[strlen(theTimeString) - 1] = '\0'; return executionContext.getXObjectFactory().createString(XalanDOMString(theTimeString)); } /** * Create a copy of the function object. * * @return pointer to the new object */ #if defined(XALAN_NO_COVARIANT_RETURN_TYPE) virtual Function* #else virtual FunctionAsctime* #endif clone() const { return new FunctionAsctime(*this); } const XalanDOMString getError() const { return XalanDOMString("The asctime() function takes no arguments!"); } private: // Not implemented... FunctionAsctime& operator=(const FunctionAsctime&); bool operator==(const FunctionAsctime&) const; }; int main( int argc, const char* /* argv */[]) { #if !defined(XALAN_NO_NAMESPACES) using std::cerr; using std::endl; using std::ofstream; #endif if (argc != 1) { cerr << "Usage: ExternalFunction" << endl << endl; } else { try { // Call the static initializer for Xerces... XMLPlatformUtils::Initialize(); { // Initialize the Xalan XSLT subsystem... XSLTInit theInit; // Create the support objects that are necessary for running the processor... XercesDOMSupport theDOMSupport; XercesParserLiaison theParserLiaison(theDOMSupport); XPathSupportDefault theXPathSupport(theDOMSupport); XSLTProcessorEnvSupportDefault theXSLTProcessorEnvSupport; XObjectFactoryDefault theXObjectFactory; XPathFactoryDefault theXPathFactory; // Create a processor... XSLTEngineImpl theProcessor( theParserLiaison, theXPathSupport, theXSLTProcessorEnvSupport, theDOMSupport, theXObjectFactory, theXPathFactory); // Connect the processor to the support object... theXSLTProcessorEnvSupport.setProcessor(&theProcessor); // Create a stylesheet construction context, and a stylesheet // execution context... StylesheetConstructionContextDefault theConstructionContext( theProcessor, theXSLTProcessorEnvSupport, theXPathFactory); StylesheetExecutionContextDefault theExecutionContext( theProcessor, theXSLTProcessorEnvSupport, theXPathSupport, theXObjectFactory); // Our input files... // WARNING!!! You may need to modify these absolute paths depending on where // you've put the Xalan sources. const XalanDOMString theXMLFileName("foo.xml"); const XalanDOMString theXSLFileName("foo.xsl"); // Our input sources... XSLTInputSource theInputSource(c_wstr(theXMLFileName)); XSLTInputSource theStylesheetSource(c_wstr(theXSLFileName)); // Our output target... const XalanDOMString theOutputFile("foo.out"); XSLTResultTarget theResultTarget(theOutputFile); // Install the function directly into the XPath // function table. We don't recommend doing this, // but you can if you want to be evil! ;-) Since // the function is in the XPath table, the XPath // parser will treat it like any other XPath // function. Therefore, it cannot have a namespace // prefix. It will also be available to every // processor in the executable's process, since there // is one static XPath function table. XPath::installFunction( XalanDOMString("asctime"), FunctionAsctime()); // The namespace for our functions... const XalanDOMString theNamespace("http://ExternalFunction.xalan-c++.xml.apache.org"); // Install the function in the global space. All // instances will know about the function, so all // processors which use an instance of this the // class XPathEnvSupportDefault will be able to // use the function. XSLTProcessorEnvSupportDefault::installExternalFunctionGlobal( theNamespace, XalanDOMString("square-root"), FunctionSquareRoot()); // Install the function in the local space. It will only // be installed in this instance, so no other instances // will know about the function... theXSLTProcessorEnvSupport.installExternalFunctionLocal( theNamespace, XalanDOMString("cube"), FunctionCube()); theProcessor.process( theInputSource, theStylesheetSource, theResultTarget, theConstructionContext, theExecutionContext); } // Call the static terminator for Xerces... XMLPlatformUtils::Terminate(); } catch(...) { cerr << "Exception caught!!!" << endl << endl; } } return 0; }
Update sample for latest changes.
Update sample for latest changes.
C++
apache-2.0
apache/xalan-c,apache/xalan-c,apache/xalan-c,apache/xalan-c
c5d4497bb38cf8004e0af99d1d386b6832cd89fb
chrome/browser/extensions/default_apps.cc
chrome/browser/extensions/default_apps.cc
// Copyright (c) 2010 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chrome/browser/extensions/default_apps.h" #include "base/command_line.h" #include "base/metrics/histogram.h" #include "chrome/browser/prefs/pref_service.h" #include "chrome/common/chrome_switches.h" #include "chrome/common/pref_names.h" const int DefaultApps::kAppsPromoCounterMax = 10; // static void DefaultApps::RegisterUserPrefs(PrefService* prefs) { prefs->RegisterBooleanPref(prefs::kDefaultAppsInstalled, false); prefs->RegisterIntegerPref(prefs::kAppsPromoCounter, 0); } DefaultApps::DefaultApps(PrefService* prefs) : prefs_(prefs) { #if !defined(OS_CHROMEOS) // gmail, docs ids_.insert("pjkljhegncpnkpknbcohdijeoejaedia"); ids_.insert("apdfllckaahabafndbhieahigkjlhalf"); #endif // OS_CHROMEOS } DefaultApps::~DefaultApps() {} const ExtensionIdSet* DefaultApps::GetAppsToInstall() const { if (GetDefaultAppsInstalled()) return NULL; else return &ids_; } const ExtensionIdSet* DefaultApps::GetDefaultApps() const { return &ids_; } void DefaultApps::DidInstallApp(const ExtensionIdSet& installed_ids) { // If all the default apps have been installed, stop trying to install them. // Note that we use std::includes here instead of == because apps might have // been manually installed while the the default apps were installing and we // wouldn't want to keep trying to install them in that case. if (!GetDefaultAppsInstalled() && std::includes(installed_ids.begin(), installed_ids.end(), ids_.begin(), ids_.end())) { SetDefaultAppsInstalled(true); } } bool DefaultApps::ShouldShowPromo(const ExtensionIdSet& installed_ids) { #if defined(OS_CHROMEOS) // Don't show the promo at all on Chrome OS. return false; #endif if (CommandLine::ForCurrentProcess()->HasSwitch( switches::kForceAppsPromoVisible)) { return true; } if (GetDefaultAppsInstalled() && GetPromoCounter() < kAppsPromoCounterMax) { // If we have the exact set of default apps, show the promo. If we don't // have the exact set of default apps, this means that the user manually // installed one. The promo doesn't make sense if it shows apps the user // manually installed, so expire it immediately in that situation. if (installed_ids == ids_) return true; else SetPromoHidden(); } return false; } void DefaultApps::DidShowPromo() { if (!GetDefaultAppsInstalled()) { NOTREACHED() << "Should not show promo until default apps are installed."; return; } int promo_counter = GetPromoCounter(); if (promo_counter == kAppsPromoCounterMax) { NOTREACHED() << "Promo has already been shown the maximum number of times."; return; } if (promo_counter < kAppsPromoCounterMax) { if (promo_counter + 1 == kAppsPromoCounterMax) UMA_HISTOGRAM_ENUMERATION(extension_misc::kAppsPromoHistogram, extension_misc::PROMO_EXPIRE, extension_misc::PROMO_BUCKET_BOUNDARY); SetPromoCounter(++promo_counter); } else { SetPromoHidden(); } } void DefaultApps::SetPromoHidden() { SetPromoCounter(kAppsPromoCounterMax); } int DefaultApps::GetPromoCounter() const { return prefs_->GetInteger(prefs::kAppsPromoCounter); } void DefaultApps::SetPromoCounter(int val) { prefs_->SetInteger(prefs::kAppsPromoCounter, val); prefs_->ScheduleSavePersistentPrefs(); } bool DefaultApps::GetDefaultAppsInstalled() const { return prefs_->GetBoolean(prefs::kDefaultAppsInstalled); } void DefaultApps::SetDefaultAppsInstalled(bool val) { prefs_->SetBoolean(prefs::kDefaultAppsInstalled, val); prefs_->ScheduleSavePersistentPrefs(); }
// 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/extensions/default_apps.h" #include "base/command_line.h" #include "base/metrics/histogram.h" #include "chrome/browser/prefs/pref_service.h" #include "chrome/common/chrome_switches.h" #include "chrome/common/pref_names.h" const int DefaultApps::kAppsPromoCounterMax = 10; // static void DefaultApps::RegisterUserPrefs(PrefService* prefs) { prefs->RegisterBooleanPref(prefs::kDefaultAppsInstalled, false); prefs->RegisterIntegerPref(prefs::kAppsPromoCounter, 0); } DefaultApps::DefaultApps(PrefService* prefs) : prefs_(prefs) { #if !defined(OS_CHROMEOS) // Poppit, Entanglement ids_.insert("mcbkbpnkkkipelfledbfocopglifcfmi"); ids_.insert("aciahcmjmecflokailenpkdchphgkefd"); #endif // OS_CHROMEOS } DefaultApps::~DefaultApps() {} const ExtensionIdSet* DefaultApps::GetAppsToInstall() const { if (GetDefaultAppsInstalled()) return NULL; else return &ids_; } const ExtensionIdSet* DefaultApps::GetDefaultApps() const { return &ids_; } void DefaultApps::DidInstallApp(const ExtensionIdSet& installed_ids) { // If all the default apps have been installed, stop trying to install them. // Note that we use std::includes here instead of == because apps might have // been manually installed while the the default apps were installing and we // wouldn't want to keep trying to install them in that case. if (!GetDefaultAppsInstalled() && std::includes(installed_ids.begin(), installed_ids.end(), ids_.begin(), ids_.end())) { SetDefaultAppsInstalled(true); } } bool DefaultApps::ShouldShowPromo(const ExtensionIdSet& installed_ids) { #if defined(OS_CHROMEOS) // Don't show the promo at all on Chrome OS. return false; #endif if (CommandLine::ForCurrentProcess()->HasSwitch( switches::kForceAppsPromoVisible)) { return true; } if (GetDefaultAppsInstalled() && GetPromoCounter() < kAppsPromoCounterMax) { // If we have the exact set of default apps, show the promo. If we don't // have the exact set of default apps, this means that the user manually // installed one. The promo doesn't make sense if it shows apps the user // manually installed, so expire it immediately in that situation. if (installed_ids == ids_) return true; else SetPromoHidden(); } return false; } void DefaultApps::DidShowPromo() { if (!GetDefaultAppsInstalled()) { NOTREACHED() << "Should not show promo until default apps are installed."; return; } int promo_counter = GetPromoCounter(); if (promo_counter == kAppsPromoCounterMax) { NOTREACHED() << "Promo has already been shown the maximum number of times."; return; } if (promo_counter < kAppsPromoCounterMax) { if (promo_counter + 1 == kAppsPromoCounterMax) UMA_HISTOGRAM_ENUMERATION(extension_misc::kAppsPromoHistogram, extension_misc::PROMO_EXPIRE, extension_misc::PROMO_BUCKET_BOUNDARY); SetPromoCounter(++promo_counter); } else { SetPromoHidden(); } } void DefaultApps::SetPromoHidden() { SetPromoCounter(kAppsPromoCounterMax); } int DefaultApps::GetPromoCounter() const { return prefs_->GetInteger(prefs::kAppsPromoCounter); } void DefaultApps::SetPromoCounter(int val) { prefs_->SetInteger(prefs::kAppsPromoCounter, val); prefs_->ScheduleSavePersistentPrefs(); } bool DefaultApps::GetDefaultAppsInstalled() const { return prefs_->GetBoolean(prefs::kDefaultAppsInstalled); } void DefaultApps::SetDefaultAppsInstalled(bool val) { prefs_->SetBoolean(prefs::kDefaultAppsInstalled, val); prefs_->ScheduleSavePersistentPrefs(); }
Update default apps.
Update default apps. [email protected] git-svn-id: de016e52bd170d2d4f2344f9bf92d50478b649e0@67693 0039d316-1c4b-4281-b951-d872f2087c98
C++
bsd-3-clause
Crystalnix/house-of-life-chromium,Crystalnix/house-of-life-chromium,gavinp/chromium,yitian134/chromium,ropik/chromium,adobe/chromium,adobe/chromium,adobe/chromium,Crystalnix/house-of-life-chromium,gavinp/chromium,adobe/chromium,gavinp/chromium,ropik/chromium,yitian134/chromium,yitian134/chromium,adobe/chromium,Crystalnix/house-of-life-chromium,gavinp/chromium,gavinp/chromium,Crystalnix/house-of-life-chromium,ropik/chromium,adobe/chromium,adobe/chromium,yitian134/chromium,gavinp/chromium,yitian134/chromium,Crystalnix/house-of-life-chromium,ropik/chromium,Crystalnix/house-of-life-chromium,ropik/chromium,Crystalnix/house-of-life-chromium,gavinp/chromium,yitian134/chromium,yitian134/chromium,gavinp/chromium,gavinp/chromium,adobe/chromium,adobe/chromium,yitian134/chromium,yitian134/chromium,Crystalnix/house-of-life-chromium,ropik/chromium,ropik/chromium,adobe/chromium,ropik/chromium,Crystalnix/house-of-life-chromium,adobe/chromium,ropik/chromium,gavinp/chromium,Crystalnix/house-of-life-chromium,yitian134/chromium
96ed6d9092bf498d6e49c3f8111043213bf2e29f
chrome/browser/printing/print_settings.cc
chrome/browser/printing/print_settings.cc
// Copyright (c) 2006-2008 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chrome/browser/printing/print_settings.h" #include "base/atomic_sequence_num.h" #include "base/logging.h" #include "chrome/common/render_messages.h" #include "printing/units.h" namespace printing { // Global SequenceNumber used for generating unique cookie values. static base::AtomicSequenceNumber cookie_seq(base::LINKER_INITIALIZED); PrintSettings::PrintSettings() : min_shrink(1.25), max_shrink(2.0), desired_dpi(72), selection_only(false), dpi_(0), landscape_(false) { } void PrintSettings::Clear() { ranges.clear(); min_shrink = 1.25; max_shrink = 2.; desired_dpi = 72; selection_only = false; printer_name_.clear(); device_name_.clear(); page_setup_pixels_.Clear(); dpi_ = 0; landscape_ = false; } #ifdef WIN32 void PrintSettings::Init(HDC hdc, const DEVMODE& dev_mode, const PageRanges& new_ranges, const std::wstring& new_device_name, bool print_selection_only) { DCHECK(hdc); printer_name_ = dev_mode.dmDeviceName; device_name_ = new_device_name; ranges = new_ranges; landscape_ = dev_mode.dmOrientation == DMORIENT_LANDSCAPE; selection_only = print_selection_only; dpi_ = GetDeviceCaps(hdc, LOGPIXELSX); // No printer device is known to advertise different dpi in X and Y axis; even // the fax device using the 200x100 dpi setting. It's ought to break so many // applications that it's not even needed to care about. WebKit doesn't // support different dpi settings in X and Y axis. DCHECK_EQ(dpi_, GetDeviceCaps(hdc, LOGPIXELSY)); DCHECK_EQ(GetDeviceCaps(hdc, SCALINGFACTORX), 0); DCHECK_EQ(GetDeviceCaps(hdc, SCALINGFACTORY), 0); // Initialize page_setup_pixels_. gfx::Size physical_size_pixels(GetDeviceCaps(hdc, PHYSICALWIDTH), GetDeviceCaps(hdc, PHYSICALHEIGHT)); gfx::Rect printable_area_pixels(GetDeviceCaps(hdc, PHYSICALOFFSETX), GetDeviceCaps(hdc, PHYSICALOFFSETY), GetDeviceCaps(hdc, HORZRES), GetDeviceCaps(hdc, VERTRES)); SetPrinterPrintableArea(physical_size_pixels, printable_area_pixels); } #endif void PrintSettings::SetPrinterPrintableArea( gfx::Size const& physical_size_pixels, gfx::Rect const& printable_area_pixels) { // Start by setting the user configuration // Hard-code text_height = 0.5cm = ~1/5 of inch page_setup_pixels_.Init(physical_size_pixels, printable_area_pixels, ConvertUnit(500, kHundrethsMMPerInch, dpi_)); // Now apply user configured settings. PageMargins margins; margins.header = 500; margins.footer = 500; margins.left = 500; margins.top = 500; margins.right = 500; margins.bottom = 500; page_setup_pixels_.SetRequestedMargins(margins); } void PrintSettings::RenderParams(ViewMsg_Print_Params* params) const { DCHECK(params); params->printable_size.SetSize(page_setup_pixels_.content_area().width(), page_setup_pixels_.content_area().height()); params->dpi = dpi_; // Currently hardcoded at 1.25. See PrintSettings' constructor. params->min_shrink = min_shrink; // Currently hardcoded at 2.0. See PrintSettings' constructor. params->max_shrink = max_shrink; // Currently hardcoded at 72dpi. See PrintSettings' constructor. params->desired_dpi = desired_dpi; // Always use an invalid cookie. params->document_cookie = 0; params->selection_only = selection_only; } bool PrintSettings::Equals(const PrintSettings& rhs) const { // Do not test the display device name (printer_name_) for equality since it // may sometimes be chopped off at 30 chars. As long as device_name is the // same, that's fine. return ranges == rhs.ranges && min_shrink == rhs.min_shrink && max_shrink == rhs.max_shrink && desired_dpi == rhs.desired_dpi && overlays.Equals(rhs.overlays) && device_name_ == rhs.device_name_ && page_setup_pixels_.Equals(rhs.page_setup_pixels_) && dpi_ == rhs.dpi_ && landscape_ == rhs.landscape_; } int PrintSettings::NewCookie() { // A cookie of 0 is used to mark a document as unassigned, count from 1. return cookie_seq.GetNext() + 1; } } // namespace printing
// Copyright (c) 2006-2008 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chrome/browser/printing/print_settings.h" #include "base/atomic_sequence_num.h" #include "base/logging.h" #include "chrome/common/render_messages.h" #include "printing/units.h" namespace printing { // Global SequenceNumber used for generating unique cookie values. static base::AtomicSequenceNumber cookie_seq(base::LINKER_INITIALIZED); PrintSettings::PrintSettings() : min_shrink(1.25), max_shrink(2.0), desired_dpi(72), selection_only(false), dpi_(0), landscape_(false) { } void PrintSettings::Clear() { ranges.clear(); min_shrink = 1.25; max_shrink = 2.; desired_dpi = 72; selection_only = false; printer_name_.clear(); device_name_.clear(); page_setup_pixels_.Clear(); dpi_ = 0; landscape_ = false; } #ifdef WIN32 void PrintSettings::Init(HDC hdc, const DEVMODE& dev_mode, const PageRanges& new_ranges, const std::wstring& new_device_name, bool print_selection_only) { DCHECK(hdc); printer_name_ = dev_mode.dmDeviceName; device_name_ = new_device_name; ranges = new_ranges; landscape_ = dev_mode.dmOrientation == DMORIENT_LANDSCAPE; selection_only = print_selection_only; dpi_ = GetDeviceCaps(hdc, LOGPIXELSX); // No printer device is known to advertise different dpi in X and Y axis; even // the fax device using the 200x100 dpi setting. It's ought to break so many // applications that it's not even needed to care about. WebKit doesn't // support different dpi settings in X and Y axis. DCHECK_EQ(dpi_, GetDeviceCaps(hdc, LOGPIXELSY)); DCHECK_EQ(GetDeviceCaps(hdc, SCALINGFACTORX), 0); DCHECK_EQ(GetDeviceCaps(hdc, SCALINGFACTORY), 0); // Initialize page_setup_pixels_. gfx::Size physical_size_pixels(GetDeviceCaps(hdc, PHYSICALWIDTH), GetDeviceCaps(hdc, PHYSICALHEIGHT)); gfx::Rect printable_area_pixels(GetDeviceCaps(hdc, PHYSICALOFFSETX), GetDeviceCaps(hdc, PHYSICALOFFSETY), GetDeviceCaps(hdc, HORZRES), GetDeviceCaps(hdc, VERTRES)); SetPrinterPrintableArea(physical_size_pixels, printable_area_pixels); } #endif void PrintSettings::SetPrinterPrintableArea( gfx::Size const& physical_size_pixels, gfx::Rect const& printable_area_pixels) { int margin_printer_units = ConvertUnit(500, kHundrethsMMPerInch, dpi_); // Start by setting the user configuration // Hard-code text_height = 0.5cm = ~1/5 of inch page_setup_pixels_.Init(physical_size_pixels, printable_area_pixels, margin_printer_units); // Now apply user configured settings. PageMargins margins; margins.header = margin_printer_units; margins.footer = margin_printer_units; margins.left = margin_printer_units; margins.top = margin_printer_units; margins.right = margin_printer_units; margins.bottom = margin_printer_units; page_setup_pixels_.SetRequestedMargins(margins); } void PrintSettings::RenderParams(ViewMsg_Print_Params* params) const { DCHECK(params); params->printable_size.SetSize(page_setup_pixels_.content_area().width(), page_setup_pixels_.content_area().height()); params->dpi = dpi_; // Currently hardcoded at 1.25. See PrintSettings' constructor. params->min_shrink = min_shrink; // Currently hardcoded at 2.0. See PrintSettings' constructor. params->max_shrink = max_shrink; // Currently hardcoded at 72dpi. See PrintSettings' constructor. params->desired_dpi = desired_dpi; // Always use an invalid cookie. params->document_cookie = 0; params->selection_only = selection_only; } bool PrintSettings::Equals(const PrintSettings& rhs) const { // Do not test the display device name (printer_name_) for equality since it // may sometimes be chopped off at 30 chars. As long as device_name is the // same, that's fine. return ranges == rhs.ranges && min_shrink == rhs.min_shrink && max_shrink == rhs.max_shrink && desired_dpi == rhs.desired_dpi && overlays.Equals(rhs.overlays) && device_name_ == rhs.device_name_ && page_setup_pixels_.Equals(rhs.page_setup_pixels_) && dpi_ == rhs.dpi_ && landscape_ == rhs.landscape_; } int PrintSettings::NewCookie() { // A cookie of 0 is used to mark a document as unassigned, count from 1. return cookie_seq.GetNext() + 1; } } // namespace printing
Scale the margins according to the DPI of the printer. The margins were fixed at 500 units which caused the margins to be huge for low DPI (low quality) printing output.
Scale the margins according to the DPI of the printer. The margins were fixed at 500 units which caused the margins to be huge for low DPI (low quality) printing output. BUG=http://crbug.com/14502 TEST=Print with different DPI settings and notice how the margins stay the same physical width. Review URL: http://codereview.chromium.org/145008 git-svn-id: http://src.chromium.org/svn/trunk/src@19032 4ff67af0-8c30-449e-8e8b-ad334ec8d88c Former-commit-id: b2bfa17a034155368364339c3aaae4a3283f9e68
C++
bsd-3-clause
meego-tablet-ux/meego-app-browser,meego-tablet-ux/meego-app-browser,meego-tablet-ux/meego-app-browser,meego-tablet-ux/meego-app-browser,meego-tablet-ux/meego-app-browser,meego-tablet-ux/meego-app-browser,meego-tablet-ux/meego-app-browser,meego-tablet-ux/meego-app-browser,meego-tablet-ux/meego-app-browser,meego-tablet-ux/meego-app-browser
2e5703b5d5bb3c4e61321013297867ad2daf2903
TOUCH_sample/main.cpp
TOUCH_sample/main.cpp
//=====================================================================// /*! @file @brief タッチ・スイッチのサンプル @n ・プルアップ抵抗は1Mオーム @author 平松邦仁 ([email protected]) */ //=====================================================================// #include "G13/system.hpp" #include "common/port_utils.hpp" #include "common/fifo.hpp" #include "common/uart_io.hpp" #include "common/format.hpp" #include "common/itimer.hpp" #include "common/delay.hpp" namespace { // 送信、受信バッファの定義 typedef utils::fifo<uint8_t, 16> buffer; // UART1 の定義(SAU2、SAU3) device::uart_io<device::SAU02, device::SAU03, buffer, buffer> uart_; device::itimer<uint8_t> itm_; } const void* ivec_[] __attribute__ ((section (".ivec"))) = { /* 0 */ nullptr, /* 1 */ nullptr, /* 2 */ nullptr, /* 3 */ nullptr, /* 4 */ nullptr, /* 5 */ nullptr, /* 6 */ nullptr, /* 7 */ nullptr, /* 8 */ nullptr, /* 9 */ nullptr, /* 10 */ nullptr, /* 11 */ nullptr, /* 12 */ nullptr, /* 13 */ nullptr, /* 14 */ nullptr, /* 15 */ nullptr, /* 16 */ reinterpret_cast<void*>(uart_.send_task), // UART1-TX /* 17 */ reinterpret_cast<void*>(uart_.recv_task), // UART1-RX /* 18 */ reinterpret_cast<void*>(uart_.error_task), // UART1-ER /* 19 */ nullptr, /* 20 */ nullptr, /* 21 */ nullptr, /* 22 */ nullptr, /* 23 */ nullptr, /* 24 */ nullptr, /* 25 */ nullptr, /* 26 */ reinterpret_cast<void*>(itm_.task), }; extern "C" { void sci_putch(char ch) { uart_.putch(ch); } void sci_puts(const char* str) { uart_.puts(str); } }; namespace { uint8_t count_active_() { uint8_t n = 0; device::PM2.B2 = 1; // input do { ++n; } while(device::P2.B2() == 0) ; device::PM2.B2 = 0; // output device::P2.B2 = 0; // 仮想コンデンサをショートしてリセット return n; } } int main(int argc, char* argv[]) { utils::port::pullup_all(); ///< 安全の為、全ての入力をプルアップ device::PM4.B3 = 0; // output { // 割り込みを使う場合、intr_level を設定 // ポーリングなら「0」 uint8_t intr_level = 1; uart_.start(115200, intr_level); } // インターバルタイマー設定 { uint8_t intr_level = 1; itm_.start(60, intr_level); } utils::format("Start RL78/G13 touch switch sample\n"); uint8_t touch_ref = 0; // タッチ入力ポートの設定 // プルアップ設定がある場合は、OFF にする。 { device::ADPC = 0x01; // All A/D chanel for digital I/O device::PM2.B2 = 0; // 初期は出力にする uint16_t sum = 0; for(uint8_t i = 0; i < 30; ++i) { itm_.sync(); sum += count_active_(); } touch_ref = sum / 30; utils::format("Touch refarence: %d\n") % touch_ref; } uint8_t n = 0; bool touch = false; bool touch_back = false; uint8_t touch_cnt = 0; uint8_t untouch_cnt = 0; while(1) { itm_.sync(); ++n; if(n >= 30) n = 0; device::P4.B3 = n < 10 ? false : true; { auto ref = count_active_(); if(ref >= (touch_ref - 1) && ref <= (touch_ref + 1)) { touch_cnt = 0; if(untouch_cnt < 255) { untouch_cnt++; } if(untouch_cnt >= 10) { touch = false; } } else { untouch_cnt = 0; if(ref >= 110) { if(touch_cnt < 255) { touch_cnt++; } if(touch_cnt >= 10) { touch = true; } } /// utils::format("%d\n") % static_cast<int>(ref); } if(touch && !touch_back) { utils::format("Touch on\n"); } if(!touch && touch_back) { utils::format("Touch off\n"); } touch_back = touch; } } }
//=====================================================================// /*! @file @brief タッチ・スイッチのサンプル @n ・プルアップ抵抗は1Mオーム @author 平松邦仁 ([email protected]) */ //=====================================================================// #include "G13/system.hpp" #include "common/port_utils.hpp" #include "common/fifo.hpp" #include "common/uart_io.hpp" #include "common/format.hpp" #include "common/itimer.hpp" #include "common/delay.hpp" namespace { // 送信、受信バッファの定義 typedef utils::fifo<uint8_t, 16> buffer; // UART1 の定義(SAU2、SAU3) device::uart_io<device::SAU02, device::SAU03, buffer, buffer> uart_; device::itimer<uint8_t> itm_; } const void* ivec_[] __attribute__ ((section (".ivec"))) = { /* 0 */ nullptr, /* 1 */ nullptr, /* 2 */ nullptr, /* 3 */ nullptr, /* 4 */ nullptr, /* 5 */ nullptr, /* 6 */ nullptr, /* 7 */ nullptr, /* 8 */ nullptr, /* 9 */ nullptr, /* 10 */ nullptr, /* 11 */ nullptr, /* 12 */ nullptr, /* 13 */ nullptr, /* 14 */ nullptr, /* 15 */ nullptr, /* 16 */ reinterpret_cast<void*>(uart_.send_task), // UART1-TX /* 17 */ reinterpret_cast<void*>(uart_.recv_task), // UART1-RX /* 18 */ reinterpret_cast<void*>(uart_.error_task), // UART1-ER /* 19 */ nullptr, /* 20 */ nullptr, /* 21 */ nullptr, /* 22 */ nullptr, /* 23 */ nullptr, /* 24 */ nullptr, /* 25 */ nullptr, /* 26 */ reinterpret_cast<void*>(itm_.task), }; extern "C" { void sci_putch(char ch) { uart_.putch(ch); } void sci_puts(const char* str) { uart_.puts(str); } }; namespace { uint16_t count_active_() { uint16_t n = 0; device::PM2.B2 = 1; // input do { ++n; } while(device::P2.B2() == 0) ; device::PM2.B2 = 0; // output device::P2.B2 = 0; // 仮想コンデンサをショートしてリセット return n; } } int main(int argc, char* argv[]) { utils::port::pullup_all(); ///< 安全の為、全ての入力をプルアップ device::PM4.B3 = 0; // output { // 割り込みを使う場合、intr_level を設定 // ポーリングなら「0」 uint8_t intr_level = 1; uart_.start(115200, intr_level); } // インターバルタイマー設定 { uint8_t intr_level = 1; itm_.start(60, intr_level); } utils::format("Start RL78/G13 touch switch sample\n"); uint16_t touch_ref = 0; // タッチ入力ポートの設定 // プルアップ設定がある場合は、OFF にする。 { device::ADPC = 0x01; // All A/D chanel for digital I/O device::PM2.B2 = 0; // 初期は出力にする uint16_t sum = 0; for(uint8_t i = 0; i < 30; ++i) { itm_.sync(); sum += count_active_(); } touch_ref = sum / 30; utils::format("Touch refarence: %d\n") % touch_ref; } uint8_t n = 0; bool touch = false; bool touch_back = false; uint8_t touch_cnt = 0; uint8_t untouch_cnt = 0; while(1) { itm_.sync(); ++n; if(n >= 30) n = 0; device::P4.B3 = n < 10 ? false : true; { auto ref = count_active_(); if(ref >= (touch_ref - 1) && ref <= (touch_ref + 1)) { touch_cnt = 0; if(untouch_cnt < 255) { untouch_cnt++; } if(untouch_cnt >= 10) { touch = false; } } else { untouch_cnt = 0; if(ref >= 110) { if(touch_cnt < 255) { touch_cnt++; } if(touch_cnt >= 10) { touch = true; } } /// utils::format("%d\n") % static_cast<int>(ref); } if(touch && !touch_back) { utils::format("Touch on\n"); } if(!touch && touch_back) { utils::format("Touch off\n"); } touch_back = touch; } } }
fix loop counter size
fix loop counter size
C++
bsd-3-clause
hirakuni45/RL78,hirakuni45/RL78,hirakuni45/RL78
91bbe1226b119d18b7117c51008bed2704d54136
TableGen/TableGen.cpp
TableGen/TableGen.cpp
//===- TableGen.cpp - Top-Level TableGen implementation -------------------===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // TableGen is a tool which can be used to build up a description of something, // then invoke one or more "tablegen backends" to emit information about the // description in some predefined format. In practice, this is used by the LLVM // code generators to automate generation of a code generator through a // high-level description of the target. // //===----------------------------------------------------------------------===// #include "Record.h" #include "TGParser.h" #include "llvm/Support/CommandLine.h" #include "llvm/Support/Streams.h" #include "llvm/System/Signals.h" #include "llvm/Support/FileUtilities.h" #include "llvm/Support/MemoryBuffer.h" #include "CallingConvEmitter.h" #include "CodeEmitterGen.h" #include "RegisterInfoEmitter.h" #include "InstrInfoEmitter.h" #include "InstrEnumEmitter.h" #include "AsmWriterEmitter.h" #include "DAGISelEmitter.h" #include "FastISelEmitter.h" #include "SubtargetEmitter.h" #include "IntrinsicEmitter.h" #include "LLVMCConfigurationEmitter.h" #include <algorithm> #include <cstdio> #include <fstream> #include <ios> using namespace llvm; enum ActionType { PrintRecords, GenEmitter, GenRegisterEnums, GenRegister, GenRegisterHeader, GenInstrEnums, GenInstrs, GenAsmWriter, GenCallingConv, GenDAGISel, GenFastISel, GenSubtarget, GenIntrinsic, GenLLVMCConf, PrintEnums }; namespace { cl::opt<ActionType> Action(cl::desc("Action to perform:"), cl::values(clEnumValN(PrintRecords, "print-records", "Print all records to stdout (default)"), clEnumValN(GenEmitter, "gen-emitter", "Generate machine code emitter"), clEnumValN(GenRegisterEnums, "gen-register-enums", "Generate enum values for registers"), clEnumValN(GenRegister, "gen-register-desc", "Generate a register info description"), clEnumValN(GenRegisterHeader, "gen-register-desc-header", "Generate a register info description header"), clEnumValN(GenInstrEnums, "gen-instr-enums", "Generate enum values for instructions"), clEnumValN(GenInstrs, "gen-instr-desc", "Generate instruction descriptions"), clEnumValN(GenCallingConv, "gen-callingconv", "Generate calling convention descriptions"), clEnumValN(GenAsmWriter, "gen-asm-writer", "Generate assembly writer"), clEnumValN(GenDAGISel, "gen-dag-isel", "Generate a DAG instruction selector"), clEnumValN(GenFastISel, "gen-fast-isel", "Generate a \"fast\" instruction selector"), clEnumValN(GenSubtarget, "gen-subtarget", "Generate subtarget enumerations"), clEnumValN(GenIntrinsic, "gen-intrinsic", "Generate intrinsic information"), clEnumValN(GenLLVMCConf, "gen-llvmc", "Generate LLVMC configuration library"), clEnumValN(PrintEnums, "print-enums", "Print enum values for a class"), clEnumValEnd)); cl::opt<std::string> Class("class", cl::desc("Print Enum list for this class"), cl::value_desc("class name")); cl::opt<std::string> OutputFilename("o", cl::desc("Output filename"), cl::value_desc("filename"), cl::init("-")); cl::opt<std::string> InputFilename(cl::Positional, cl::desc("<input file>"), cl::init("-")); cl::list<std::string> IncludeDirs("I", cl::desc("Directory of include files"), cl::value_desc("directory"), cl::Prefix); } RecordKeeper llvm::Records; /// ParseFile - this function begins the parsing of the specified tablegen /// file. static bool ParseFile(const std::string &Filename, const std::vector<std::string> &IncludeDirs) { std::string ErrorStr; MemoryBuffer *F = MemoryBuffer::getFileOrSTDIN(Filename.c_str(), &ErrorStr); if (F == 0) { cerr << "Could not open input file '" + Filename + "': " << ErrorStr <<"\n"; return true; } TGParser Parser(F); // Record the location of the include directory so that the lexer can find // it later. Parser.setIncludeDirs(IncludeDirs); return Parser.ParseFile(); } int main(int argc, char **argv) { cl::ParseCommandLineOptions(argc, argv); // Parse the input file. if (ParseFile(InputFilename, IncludeDirs)) return 1; std::ostream *Out = cout.stream(); if (OutputFilename != "-") { Out = new std::ofstream(OutputFilename.c_str()); if (!Out->good()) { cerr << argv[0] << ": error opening " << OutputFilename << "!\n"; return 1; } // Make sure the file gets removed if *gasp* tablegen crashes... sys::RemoveFileOnSignal(sys::Path(OutputFilename)); } try { switch (Action) { case PrintRecords: *Out << Records; // No argument, dump all contents break; case GenEmitter: CodeEmitterGen(Records).run(*Out); break; case GenRegisterEnums: RegisterInfoEmitter(Records).runEnums(*Out); break; case GenRegister: RegisterInfoEmitter(Records).run(*Out); break; case GenRegisterHeader: RegisterInfoEmitter(Records).runHeader(*Out); break; case GenInstrEnums: InstrEnumEmitter(Records).run(*Out); break; case GenInstrs: InstrInfoEmitter(Records).run(*Out); break; case GenCallingConv: CallingConvEmitter(Records).run(*Out); break; case GenAsmWriter: AsmWriterEmitter(Records).run(*Out); break; case GenDAGISel: DAGISelEmitter(Records).run(*Out); break; case GenFastISel: FastISelEmitter(Records).run(*Out); break; case GenSubtarget: SubtargetEmitter(Records).run(*Out); break; case GenIntrinsic: IntrinsicEmitter(Records).run(*Out); break; case GenLLVMCConf: LLVMCConfigurationEmitter(Records).run(*Out); break; case PrintEnums: { std::vector<Record*> Recs = Records.getAllDerivedDefinitions(Class); for (unsigned i = 0, e = Recs.size(); i != e; ++i) *Out << Recs[i]->getName() << ", "; *Out << "\n"; break; } default: assert(1 && "Invalid Action"); return 1; } } catch (const std::string &Error) { cerr << argv[0] << ": " << Error << "\n"; if (Out != cout.stream()) { delete Out; // Close the file std::remove(OutputFilename.c_str()); // Remove the file, it's broken } return 1; } catch (...) { cerr << argv[0] << ": Unknown unexpected exception occurred.\n"; if (Out != cout.stream()) { delete Out; // Close the file std::remove(OutputFilename.c_str()); // Remove the file, it's broken } return 2; } if (Out != cout.stream()) { delete Out; // Close the file } return 0; }
//===- TableGen.cpp - Top-Level TableGen implementation -------------------===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // TableGen is a tool which can be used to build up a description of something, // then invoke one or more "tablegen backends" to emit information about the // description in some predefined format. In practice, this is used by the LLVM // code generators to automate generation of a code generator through a // high-level description of the target. // //===----------------------------------------------------------------------===// #include "Record.h" #include "TGParser.h" #include "llvm/Support/CommandLine.h" #include "llvm/Support/Streams.h" #include "llvm/System/Signals.h" #include "llvm/Support/FileUtilities.h" #include "llvm/Support/MemoryBuffer.h" #include "CallingConvEmitter.h" #include "CodeEmitterGen.h" #include "RegisterInfoEmitter.h" #include "InstrInfoEmitter.h" #include "InstrEnumEmitter.h" #include "AsmWriterEmitter.h" #include "DAGISelEmitter.h" #include "FastISelEmitter.h" #include "SubtargetEmitter.h" #include "IntrinsicEmitter.h" #include "LLVMCConfigurationEmitter.h" #include <algorithm> #include <cstdio> #include <fstream> #include <ios> using namespace llvm; enum ActionType { PrintRecords, GenEmitter, GenRegisterEnums, GenRegister, GenRegisterHeader, GenInstrEnums, GenInstrs, GenAsmWriter, GenCallingConv, GenDAGISel, GenFastISel, GenSubtarget, GenIntrinsic, GenLLVMCConf, PrintEnums }; namespace { cl::opt<ActionType> Action(cl::desc("Action to perform:"), cl::values(clEnumValN(PrintRecords, "print-records", "Print all records to stdout (default)"), clEnumValN(GenEmitter, "gen-emitter", "Generate machine code emitter"), clEnumValN(GenRegisterEnums, "gen-register-enums", "Generate enum values for registers"), clEnumValN(GenRegister, "gen-register-desc", "Generate a register info description"), clEnumValN(GenRegisterHeader, "gen-register-desc-header", "Generate a register info description header"), clEnumValN(GenInstrEnums, "gen-instr-enums", "Generate enum values for instructions"), clEnumValN(GenInstrs, "gen-instr-desc", "Generate instruction descriptions"), clEnumValN(GenCallingConv, "gen-callingconv", "Generate calling convention descriptions"), clEnumValN(GenAsmWriter, "gen-asm-writer", "Generate assembly writer"), clEnumValN(GenDAGISel, "gen-dag-isel", "Generate a DAG instruction selector"), clEnumValN(GenFastISel, "gen-fast-isel", "Generate a \"fast\" instruction selector"), clEnumValN(GenSubtarget, "gen-subtarget", "Generate subtarget enumerations"), clEnumValN(GenIntrinsic, "gen-intrinsic", "Generate intrinsic information"), clEnumValN(GenLLVMCConf, "gen-llvmc", "Generate LLVMC configuration library"), clEnumValN(PrintEnums, "print-enums", "Print enum values for a class"), clEnumValEnd)); cl::opt<std::string> Class("class", cl::desc("Print Enum list for this class"), cl::value_desc("class name")); cl::opt<std::string> OutputFilename("o", cl::desc("Output filename"), cl::value_desc("filename"), cl::init("-")); cl::opt<std::string> InputFilename(cl::Positional, cl::desc("<input file>"), cl::init("-")); cl::list<std::string> IncludeDirs("I", cl::desc("Directory of include files"), cl::value_desc("directory"), cl::Prefix); } RecordKeeper llvm::Records; /// ParseFile - this function begins the parsing of the specified tablegen /// file. static bool ParseFile(const std::string &Filename, const std::vector<std::string> &IncludeDirs) { std::string ErrorStr; MemoryBuffer *F = MemoryBuffer::getFileOrSTDIN(Filename.c_str(), &ErrorStr); if (F == 0) { cerr << "Could not open input file '" + Filename + "': " << ErrorStr <<"\n"; return true; } TGParser Parser(F); // Record the location of the include directory so that the lexer can find // it later. Parser.setIncludeDirs(IncludeDirs); return Parser.ParseFile(); } int main(int argc, char **argv) { cl::ParseCommandLineOptions(argc, argv); // Parse the input file. if (ParseFile(InputFilename, IncludeDirs)) return 1; std::ostream *Out = cout.stream(); if (OutputFilename != "-") { Out = new std::ofstream(OutputFilename.c_str()); if (!Out->good()) { cerr << argv[0] << ": error opening " << OutputFilename << "!\n"; return 1; } // Make sure the file gets removed if *gasp* tablegen crashes... sys::RemoveFileOnSignal(sys::Path(OutputFilename)); } try { switch (Action) { case PrintRecords: *Out << Records; // No argument, dump all contents break; case GenEmitter: CodeEmitterGen(Records).run(*Out); break; case GenRegisterEnums: RegisterInfoEmitter(Records).runEnums(*Out); break; case GenRegister: RegisterInfoEmitter(Records).run(*Out); break; case GenRegisterHeader: RegisterInfoEmitter(Records).runHeader(*Out); break; case GenInstrEnums: InstrEnumEmitter(Records).run(*Out); break; case GenInstrs: InstrInfoEmitter(Records).run(*Out); break; case GenCallingConv: CallingConvEmitter(Records).run(*Out); break; case GenAsmWriter: AsmWriterEmitter(Records).run(*Out); break; case GenDAGISel: DAGISelEmitter(Records).run(*Out); break; case GenFastISel: FastISelEmitter(Records).run(*Out); break; case GenSubtarget: SubtargetEmitter(Records).run(*Out); break; case GenIntrinsic: IntrinsicEmitter(Records).run(*Out); break; case GenLLVMCConf: LLVMCConfigurationEmitter(Records).run(*Out); break; case PrintEnums: { std::vector<Record*> Recs = Records.getAllDerivedDefinitions(Class); for (unsigned i = 0, e = Recs.size(); i != e; ++i) *Out << Recs[i]->getName() << ", "; *Out << "\n"; break; } default: assert(1 && "Invalid Action"); return 1; } } catch (const std::string &Error) { cerr << argv[0] << ": " << Error << "\n"; if (Out != cout.stream()) { delete Out; // Close the file std::remove(OutputFilename.c_str()); // Remove the file, it's broken } return 1; } catch (const char *Error) { cerr << argv[0] << ": " << Error << "\n"; if (Out != cout.stream()) { delete Out; // Close the file std::remove(OutputFilename.c_str()); // Remove the file, it's broken } return 1; } catch (...) { cerr << argv[0] << ": Unknown unexpected exception occurred.\n"; if (Out != cout.stream()) { delete Out; // Close the file std::remove(OutputFilename.c_str()); // Remove the file, it's broken } return 2; } if (Out != cout.stream()) { delete Out; // Close the file } return 0; }
Make tablegen print out a nice error message for a const char* exception, like it does for a std::string exception.
Make tablegen print out a nice error message for a const char* exception, like it does for a std::string exception. git-svn-id: a4a6f32337ebd29ad4763b423022f00f68d1c7b7@58865 91177308-0d34-0410-b5e6-96231b3b80d8
C++
bsd-3-clause
lodyagin/bare_cxx,lodyagin/bare_cxx,lodyagin/bare_cxx,lodyagin/bare_cxx,lodyagin/bare_cxx
53ccf26750847b1025ca198513f59f68824f7d7a
cpp/tests/unit-tests/mqtt/MqttMessagingSkeletonTest.cpp
cpp/tests/unit-tests/mqtt/MqttMessagingSkeletonTest.cpp
/* * #%L * %% * Copyright (C) 2011 - 2017 BMW Car IT GmbH * %% * 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. * #L% */ #include <chrono> #include <functional> #include <memory> #include <string> #include <gtest/gtest.h> #include <gmock/gmock.h> #include "joynr/MqttMessagingSkeleton.h" #include "joynr/MqttReceiver.h" #include "libjoynrclustercontroller/mqtt/MosquittoConnection.h" #include "joynr/BroadcastSubscriptionRequest.h" #include "joynr/MessagingSettings.h" #include "joynr/ClusterControllerSettings.h" #include "joynr/MulticastPublication.h" #include "joynr/MulticastSubscriptionRequest.h" #include "joynr/Request.h" #include "joynr/Settings.h" #include "joynr/SingleThreadedIOService.h" #include "joynr/SubscriptionRequest.h" #include "joynr/system/RoutingTypes/MqttAddress.h" #include "joynr/MutableMessageFactory.h" #include "joynr/MutableMessage.h" #include "joynr/ImmutableMessage.h" #include "joynr/MessagingQos.h" #include "tests/JoynrTest.h" #include "tests/mock/MockMessageRouter.h" using ::testing::A; using ::testing::_; using ::testing::Eq; using ::testing::AllOf; using ::testing::Property; using ::testing::Pointee; using namespace ::testing; using namespace joynr; class MockMqttReceiver : public joynr::MqttReceiver { public: MockMqttReceiver(const MessagingSettings& messagingSettings, const ClusterControllerSettings& ccSettings) : MqttReceiver(std::make_shared<MosquittoConnection>(messagingSettings, ccSettings, "receiverId"), messagingSettings, "channelId", ccSettings.getMqttMulticastTopicPrefix()) { } MOCK_METHOD1(subscribeToTopic, void(const std::string& topic)); MOCK_METHOD1(unsubscribeFromTopic, void(const std::string& topic)); }; class MqttMessagingSkeletonTest : public ::testing::Test { public: MqttMessagingSkeletonTest() : singleThreadedIOService(std::make_shared<SingleThreadedIOService>()), mockMessageRouter(std::make_shared<MockMessageRouter>(singleThreadedIOService->getIOService())), isLocalMessage(false), settings(), ccSettings(settings) { singleThreadedIOService->start(); } void SetUp(){ // create a fake message std::string postFix; postFix = "_" + util::createUuid(); senderID = "senderId" + postFix; receiverID = "receiverID" + postFix; qosSettings = MessagingQos(456000); Request request; request.setMethodName("methodName"); request.setParams(42, std::string("value")); std::vector<std::string> paramDatatypes; paramDatatypes.push_back("Integer"); paramDatatypes.push_back("String"); request.setParamDatatypes(paramDatatypes); mutableMessage = messageFactory.createRequest( senderID, receiverID, qosSettings, request, isLocalMessage ); } protected: void transmitSetsIsReceivedFromGlobal(); std::shared_ptr<SingleThreadedIOService> singleThreadedIOService; std::shared_ptr<MockMessageRouter> mockMessageRouter; MutableMessageFactory messageFactory; MutableMessage mutableMessage; std::string senderID; std::string receiverID; MessagingQos qosSettings; const bool isLocalMessage; Settings settings; ClusterControllerSettings ccSettings; }; MATCHER_P(pointerToMqttAddressWithChannelId, channelId, "") { if (arg == nullptr) { return false; } std::shared_ptr<const joynr::system::RoutingTypes::MqttAddress> mqttAddress = std::dynamic_pointer_cast<const joynr::system::RoutingTypes::MqttAddress>(arg); if (mqttAddress == nullptr) { return false; } return mqttAddress->getTopic() == channelId; } TEST_F(MqttMessagingSkeletonTest, transmitTest) { MqttMessagingSkeleton mqttMessagingSkeleton(mockMessageRouter, nullptr, ccSettings.getMqttMulticastTopicPrefix()); std::shared_ptr<ImmutableMessage> immutableMessage = mutableMessage.getImmutableMessage(); EXPECT_CALL(*mockMessageRouter, route(immutableMessage,_)).Times(1); auto onFailure = [](const exceptions::JoynrRuntimeException& e) { FAIL() << "onFailure called"; }; mqttMessagingSkeleton.transmit(immutableMessage, onFailure); } void MqttMessagingSkeletonTest::transmitSetsIsReceivedFromGlobal() { MqttMessagingSkeleton mqttMessagingSkeleton(mockMessageRouter, nullptr, ccSettings.getMqttMulticastTopicPrefix()); std::shared_ptr<ImmutableMessage> immutableMessage = mutableMessage.getImmutableMessage(); EXPECT_FALSE(immutableMessage->isReceivedFromGlobal()); auto onFailure = [](const exceptions::JoynrRuntimeException& e) { FAIL() << "onFailure called"; }; mqttMessagingSkeleton.transmit(immutableMessage, onFailure); EXPECT_TRUE(immutableMessage->isReceivedFromGlobal()); } TEST_F(MqttMessagingSkeletonTest, transmitSetsReceivedFromGlobalForMulticastPublications) { MulticastPublication publication; mutableMessage = messageFactory.createMulticastPublication( senderID, qosSettings, publication ); transmitSetsIsReceivedFromGlobal(); } TEST_F(MqttMessagingSkeletonTest, transmitSetsReceivedFromGlobalForRequests) { Request request; mutableMessage = messageFactory.createRequest( senderID, receiverID, qosSettings, request, isLocalMessage ); transmitSetsIsReceivedFromGlobal(); } TEST_F(MqttMessagingSkeletonTest, transmitSetsReceivedFromGlobalForSubscriptionRequests) { SubscriptionRequest request; mutableMessage = messageFactory.createSubscriptionRequest( senderID, receiverID, qosSettings, request, isLocalMessage ); transmitSetsIsReceivedFromGlobal(); } TEST_F(MqttMessagingSkeletonTest, transmitSetsIsReceivedFromGlobalForBroadcastSubscriptionRequests) { BroadcastSubscriptionRequest request; mutableMessage = messageFactory.createBroadcastSubscriptionRequest( senderID, receiverID, qosSettings, request, isLocalMessage ); transmitSetsIsReceivedFromGlobal(); } TEST_F(MqttMessagingSkeletonTest, transmitSetsIsReceivedFromGlobalForMulticastSubscriptionRequests) { MulticastSubscriptionRequest request; mutableMessage = messageFactory.createMulticastSubscriptionRequest( senderID, receiverID, qosSettings, request, isLocalMessage ); transmitSetsIsReceivedFromGlobal(); } TEST_F(MqttMessagingSkeletonTest, onMessageReceivedTest) { MqttMessagingSkeleton mqttMessagingSkeleton(mockMessageRouter, nullptr, ccSettings.getMqttMulticastTopicPrefix()); std::unique_ptr<ImmutableMessage> immutableMessage = mutableMessage.getImmutableMessage(); EXPECT_CALL(*mockMessageRouter, route( AllOf( MessageHasType(mutableMessage.getType()), ImmutableMessageHasPayload(mutableMessage.getPayload()) ), _ ) ).Times(1); smrf::ByteVector serializedMessage = immutableMessage->getSerializedMessage(); mqttMessagingSkeleton.onMessageReceived(std::move(serializedMessage)); } TEST_F(MqttMessagingSkeletonTest, registerMulticastSubscription_subscribesToMqttTopic) { std::string multicastId = "multicastId"; Settings settings; ClusterControllerSettings ccSettings(settings); MessagingSettings messagingSettings(settings); auto mockMqttReceiver = std::make_shared<MockMqttReceiver>(messagingSettings, ccSettings); MqttMessagingSkeleton mqttMessagingSkeleton(mockMessageRouter, mockMqttReceiver, ""); EXPECT_CALL(*mockMqttReceiver, subscribeToTopic(multicastId)); mqttMessagingSkeleton.registerMulticastSubscription(multicastId); } TEST_F(MqttMessagingSkeletonTest, registerMulticastSubscription_subscribesToMqttTopicOnlyOnce) { std::string multicastId = "multicastId"; MessagingSettings messagingSettings(settings); auto mockMqttReceiver = std::make_shared<MockMqttReceiver>(messagingSettings, ccSettings); MqttMessagingSkeleton mqttMessagingSkeleton(mockMessageRouter, mockMqttReceiver, ccSettings.getMqttMulticastTopicPrefix()); EXPECT_CALL(*mockMqttReceiver, subscribeToTopic(multicastId)).Times(1); mqttMessagingSkeleton.registerMulticastSubscription(multicastId); mqttMessagingSkeleton.registerMulticastSubscription(multicastId); } TEST_F(MqttMessagingSkeletonTest, unregisterMulticastSubscription_unsubscribesFromMqttTopic) { std::string multicastId = "multicastId"; MessagingSettings messagingSettings(settings); auto mockMqttReceiver = std::make_shared<MockMqttReceiver>(messagingSettings, ccSettings); MqttMessagingSkeleton mqttMessagingSkeleton(mockMessageRouter, mockMqttReceiver, ccSettings.getMqttMulticastTopicPrefix()); EXPECT_CALL(*mockMqttReceiver, subscribeToTopic(multicastId)).Times(1); mqttMessagingSkeleton.registerMulticastSubscription(multicastId); EXPECT_CALL(*mockMqttReceiver, unsubscribeFromTopic(multicastId)); mqttMessagingSkeleton.unregisterMulticastSubscription(multicastId); } TEST_F(MqttMessagingSkeletonTest, unregisterMulticastSubscription_unsubscribesFromMqttTopicOnlyForUnsubscribeOfLastReceiver) { std::string multicastId = "multicastId"; MessagingSettings messagingSettings(settings); auto mockMqttReceiver = std::make_shared<MockMqttReceiver>(messagingSettings, ccSettings); MqttMessagingSkeleton mqttMessagingSkeleton(mockMessageRouter, mockMqttReceiver, ccSettings.getMqttMulticastTopicPrefix()); EXPECT_CALL(*mockMqttReceiver, subscribeToTopic(multicastId)).Times(1); mqttMessagingSkeleton.registerMulticastSubscription(multicastId); mqttMessagingSkeleton.registerMulticastSubscription(multicastId); EXPECT_CALL(*mockMqttReceiver, unsubscribeFromTopic(multicastId)).Times(0); mqttMessagingSkeleton.unregisterMulticastSubscription(multicastId); Mock::VerifyAndClearExpectations(mockMqttReceiver.get()); EXPECT_CALL(*mockMqttReceiver, unsubscribeFromTopic(multicastId)).Times(1); mqttMessagingSkeleton.unregisterMulticastSubscription(multicastId); } TEST_F(MqttMessagingSkeletonTest, translateWildcard) { std::map<std::string, std::string> input2expected = { {"partion0/partion1", "partion0/partion1"}, {"partion0/partion1/*", "partion0/partion1/#"}, {"partion0/partion1/+", "partion0/partion1/+"} }; for(auto& testCase : input2expected) { std::string inputPartition = testCase.first; std::string expectedPartition = testCase.second; EXPECT_EQ(expectedPartition, MqttMessagingSkeleton::translateMulticastWildcard(inputPartition) ); } }
/* * #%L * %% * Copyright (C) 2011 - 2017 BMW Car IT GmbH * %% * 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. * #L% */ #include <chrono> #include <functional> #include <memory> #include <string> #include <gtest/gtest.h> #include <gmock/gmock.h> #include "joynr/MqttMessagingSkeleton.h" #include "joynr/MqttReceiver.h" #include "libjoynrclustercontroller/mqtt/MosquittoConnection.h" #include "joynr/BroadcastSubscriptionRequest.h" #include "joynr/MessagingSettings.h" #include "joynr/ClusterControllerSettings.h" #include "joynr/MulticastPublication.h" #include "joynr/MulticastSubscriptionRequest.h" #include "joynr/Request.h" #include "joynr/Settings.h" #include "joynr/SingleThreadedIOService.h" #include "joynr/SubscriptionRequest.h" #include "joynr/system/RoutingTypes/MqttAddress.h" #include "joynr/MutableMessageFactory.h" #include "joynr/MutableMessage.h" #include "joynr/ImmutableMessage.h" #include "joynr/MessagingQos.h" #include "tests/JoynrTest.h" #include "tests/mock/MockMessageRouter.h" using ::testing::A; using ::testing::_; using ::testing::Eq; using ::testing::AllOf; using ::testing::Property; using ::testing::Pointee; using namespace ::testing; using namespace joynr; class MockMqttReceiver : public joynr::MqttReceiver { public: MockMqttReceiver(const MessagingSettings& messagingSettings, const ClusterControllerSettings& ccSettings) : MqttReceiver(std::make_shared<MosquittoConnection>(messagingSettings, ccSettings, "receiverId"), messagingSettings, "channelId", ccSettings.getMqttMulticastTopicPrefix()) { } MOCK_METHOD1(subscribeToTopic, void(const std::string& topic)); MOCK_METHOD1(unsubscribeFromTopic, void(const std::string& topic)); }; class MqttMessagingSkeletonTest : public ::testing::Test { public: MqttMessagingSkeletonTest() : singleThreadedIOService(std::make_shared<SingleThreadedIOService>()), mockMessageRouter(std::make_shared<MockMessageRouter>(singleThreadedIOService->getIOService())), isLocalMessage(false), settings(), ccSettings(settings) { singleThreadedIOService->start(); } ~MqttMessagingSkeletonTest() { singleThreadedIOService->stop(); } void SetUp(){ // create a fake message std::string postFix; postFix = "_" + util::createUuid(); senderID = "senderId" + postFix; receiverID = "receiverID" + postFix; qosSettings = MessagingQos(456000); Request request; request.setMethodName("methodName"); request.setParams(42, std::string("value")); std::vector<std::string> paramDatatypes; paramDatatypes.push_back("Integer"); paramDatatypes.push_back("String"); request.setParamDatatypes(paramDatatypes); mutableMessage = messageFactory.createRequest( senderID, receiverID, qosSettings, request, isLocalMessage ); } protected: void transmitSetsIsReceivedFromGlobal(); std::shared_ptr<SingleThreadedIOService> singleThreadedIOService; std::shared_ptr<MockMessageRouter> mockMessageRouter; MutableMessageFactory messageFactory; MutableMessage mutableMessage; std::string senderID; std::string receiverID; MessagingQos qosSettings; const bool isLocalMessage; Settings settings; ClusterControllerSettings ccSettings; }; MATCHER_P(pointerToMqttAddressWithChannelId, channelId, "") { if (arg == nullptr) { return false; } std::shared_ptr<const joynr::system::RoutingTypes::MqttAddress> mqttAddress = std::dynamic_pointer_cast<const joynr::system::RoutingTypes::MqttAddress>(arg); if (mqttAddress == nullptr) { return false; } return mqttAddress->getTopic() == channelId; } TEST_F(MqttMessagingSkeletonTest, transmitTest) { MqttMessagingSkeleton mqttMessagingSkeleton(mockMessageRouter, nullptr, ccSettings.getMqttMulticastTopicPrefix()); std::shared_ptr<ImmutableMessage> immutableMessage = mutableMessage.getImmutableMessage(); EXPECT_CALL(*mockMessageRouter, route(immutableMessage,_)).Times(1); auto onFailure = [](const exceptions::JoynrRuntimeException& e) { FAIL() << "onFailure called"; }; mqttMessagingSkeleton.transmit(immutableMessage, onFailure); } void MqttMessagingSkeletonTest::transmitSetsIsReceivedFromGlobal() { MqttMessagingSkeleton mqttMessagingSkeleton(mockMessageRouter, nullptr, ccSettings.getMqttMulticastTopicPrefix()); std::shared_ptr<ImmutableMessage> immutableMessage = mutableMessage.getImmutableMessage(); EXPECT_FALSE(immutableMessage->isReceivedFromGlobal()); auto onFailure = [](const exceptions::JoynrRuntimeException& e) { FAIL() << "onFailure called"; }; mqttMessagingSkeleton.transmit(immutableMessage, onFailure); EXPECT_TRUE(immutableMessage->isReceivedFromGlobal()); } TEST_F(MqttMessagingSkeletonTest, transmitSetsReceivedFromGlobalForMulticastPublications) { MulticastPublication publication; mutableMessage = messageFactory.createMulticastPublication( senderID, qosSettings, publication ); transmitSetsIsReceivedFromGlobal(); } TEST_F(MqttMessagingSkeletonTest, transmitSetsReceivedFromGlobalForRequests) { Request request; mutableMessage = messageFactory.createRequest( senderID, receiverID, qosSettings, request, isLocalMessage ); transmitSetsIsReceivedFromGlobal(); } TEST_F(MqttMessagingSkeletonTest, transmitSetsReceivedFromGlobalForSubscriptionRequests) { SubscriptionRequest request; mutableMessage = messageFactory.createSubscriptionRequest( senderID, receiverID, qosSettings, request, isLocalMessage ); transmitSetsIsReceivedFromGlobal(); } TEST_F(MqttMessagingSkeletonTest, transmitSetsIsReceivedFromGlobalForBroadcastSubscriptionRequests) { BroadcastSubscriptionRequest request; mutableMessage = messageFactory.createBroadcastSubscriptionRequest( senderID, receiverID, qosSettings, request, isLocalMessage ); transmitSetsIsReceivedFromGlobal(); } TEST_F(MqttMessagingSkeletonTest, transmitSetsIsReceivedFromGlobalForMulticastSubscriptionRequests) { MulticastSubscriptionRequest request; mutableMessage = messageFactory.createMulticastSubscriptionRequest( senderID, receiverID, qosSettings, request, isLocalMessage ); transmitSetsIsReceivedFromGlobal(); } TEST_F(MqttMessagingSkeletonTest, onMessageReceivedTest) { MqttMessagingSkeleton mqttMessagingSkeleton(mockMessageRouter, nullptr, ccSettings.getMqttMulticastTopicPrefix()); std::unique_ptr<ImmutableMessage> immutableMessage = mutableMessage.getImmutableMessage(); EXPECT_CALL(*mockMessageRouter, route( AllOf( MessageHasType(mutableMessage.getType()), ImmutableMessageHasPayload(mutableMessage.getPayload()) ), _ ) ).Times(1); smrf::ByteVector serializedMessage = immutableMessage->getSerializedMessage(); mqttMessagingSkeleton.onMessageReceived(std::move(serializedMessage)); } TEST_F(MqttMessagingSkeletonTest, registerMulticastSubscription_subscribesToMqttTopic) { std::string multicastId = "multicastId"; Settings settings; ClusterControllerSettings ccSettings(settings); MessagingSettings messagingSettings(settings); auto mockMqttReceiver = std::make_shared<MockMqttReceiver>(messagingSettings, ccSettings); MqttMessagingSkeleton mqttMessagingSkeleton(mockMessageRouter, mockMqttReceiver, ""); EXPECT_CALL(*mockMqttReceiver, subscribeToTopic(multicastId)); mqttMessagingSkeleton.registerMulticastSubscription(multicastId); } TEST_F(MqttMessagingSkeletonTest, registerMulticastSubscription_subscribesToMqttTopicOnlyOnce) { std::string multicastId = "multicastId"; MessagingSettings messagingSettings(settings); auto mockMqttReceiver = std::make_shared<MockMqttReceiver>(messagingSettings, ccSettings); MqttMessagingSkeleton mqttMessagingSkeleton(mockMessageRouter, mockMqttReceiver, ccSettings.getMqttMulticastTopicPrefix()); EXPECT_CALL(*mockMqttReceiver, subscribeToTopic(multicastId)).Times(1); mqttMessagingSkeleton.registerMulticastSubscription(multicastId); mqttMessagingSkeleton.registerMulticastSubscription(multicastId); } TEST_F(MqttMessagingSkeletonTest, unregisterMulticastSubscription_unsubscribesFromMqttTopic) { std::string multicastId = "multicastId"; MessagingSettings messagingSettings(settings); auto mockMqttReceiver = std::make_shared<MockMqttReceiver>(messagingSettings, ccSettings); MqttMessagingSkeleton mqttMessagingSkeleton(mockMessageRouter, mockMqttReceiver, ccSettings.getMqttMulticastTopicPrefix()); EXPECT_CALL(*mockMqttReceiver, subscribeToTopic(multicastId)).Times(1); mqttMessagingSkeleton.registerMulticastSubscription(multicastId); EXPECT_CALL(*mockMqttReceiver, unsubscribeFromTopic(multicastId)); mqttMessagingSkeleton.unregisterMulticastSubscription(multicastId); } TEST_F(MqttMessagingSkeletonTest, unregisterMulticastSubscription_unsubscribesFromMqttTopicOnlyForUnsubscribeOfLastReceiver) { std::string multicastId = "multicastId"; MessagingSettings messagingSettings(settings); auto mockMqttReceiver = std::make_shared<MockMqttReceiver>(messagingSettings, ccSettings); MqttMessagingSkeleton mqttMessagingSkeleton(mockMessageRouter, mockMqttReceiver, ccSettings.getMqttMulticastTopicPrefix()); EXPECT_CALL(*mockMqttReceiver, subscribeToTopic(multicastId)).Times(1); mqttMessagingSkeleton.registerMulticastSubscription(multicastId); mqttMessagingSkeleton.registerMulticastSubscription(multicastId); EXPECT_CALL(*mockMqttReceiver, unsubscribeFromTopic(multicastId)).Times(0); mqttMessagingSkeleton.unregisterMulticastSubscription(multicastId); Mock::VerifyAndClearExpectations(mockMqttReceiver.get()); EXPECT_CALL(*mockMqttReceiver, unsubscribeFromTopic(multicastId)).Times(1); mqttMessagingSkeleton.unregisterMulticastSubscription(multicastId); } TEST_F(MqttMessagingSkeletonTest, translateWildcard) { std::map<std::string, std::string> input2expected = { {"partion0/partion1", "partion0/partion1"}, {"partion0/partion1/*", "partion0/partion1/#"}, {"partion0/partion1/+", "partion0/partion1/+"} }; for(auto& testCase : input2expected) { std::string inputPartition = testCase.first; std::string expectedPartition = testCase.second; EXPECT_EQ(expectedPartition, MqttMessagingSkeleton::translateMulticastWildcard(inputPartition) ); } }
Stop SingleThreadedIOService in MqttMessagingSkeletonTest
[C++] Stop SingleThreadedIOService in MqttMessagingSkeletonTest Change-Id: I7a83a55a0b8befcb5a2095d39a067f05dde3e06f
C++
apache-2.0
bmwcarit/joynr,bmwcarit/joynr,bmwcarit/joynr,bmwcarit/joynr,bmwcarit/joynr,bmwcarit/joynr,bmwcarit/joynr,bmwcarit/joynr,bmwcarit/joynr
e121ef45809e2585ac40bbf33e472c107a6b2879
dali-toolkit/internal/builder/tree-node-manipulator.cpp
dali-toolkit/internal/builder/tree-node-manipulator.cpp
/* * Copyright (c) 2014 Samsung Electronics Co., Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ // EXTERNAL INCLUDES #include <cstring> #include <sstream> // INTERNAL INCLUDES #include <dali-toolkit/internal/builder/tree-node-manipulator.h> #include <dali-toolkit/devel-api/builder/tree-node.h> namespace Dali { namespace Toolkit { namespace Internal { namespace { void Indent(std::ostream& o, int level, int indentWidth) { for (int i = 0; i < level*indentWidth; ++i) { o << " "; } } std::string EscapeQuotes( const char* aString) { std::string escapedString; int length = strlen(aString); escapedString.reserve(length); const char* end = aString+length; for( const char* iter = aString; iter != end ; ++iter) { if(*iter != '\"') { escapedString.push_back(*iter); } else { escapedString.append("\\\""); } } return escapedString; } } // anonymous namespace TreeNodeManipulator::TreeNodeManipulator(TreeNode* node) : mNode(node) { } TreeNode* TreeNodeManipulator::NewTreeNode() { return new TreeNode(); } void TreeNodeManipulator::ShallowCopy(const TreeNode* from, TreeNode* to) { DALI_ASSERT_DEBUG(from); DALI_ASSERT_DEBUG(to); if( from ) { to->mName = from->mName; to->mType = from->mType; to->mSubstituion = from->mSubstituion; switch(from->mType) { case TreeNode::INTEGER: { to->mIntValue = from->mIntValue; break; } case TreeNode::FLOAT: { to->mFloatValue = from->mFloatValue; break; } case TreeNode::STRING: { to->mStringValue = from->mStringValue; break; } case TreeNode::BOOLEAN: { to->mIntValue = from->mIntValue; break; } case TreeNode::IS_NULL: case TreeNode::OBJECT: case TreeNode::ARRAY: { break; } } } } void TreeNodeManipulator::MoveNodeStrings(VectorCharIter& start, const VectorCharIter& sentinel) { DALI_ASSERT_DEBUG(mNode && "Operation on NULL JSON node"); if(mNode->mName) { mNode->mName = CopyString(mNode->mName, start, sentinel); } if(TreeNode::STRING == mNode->mType) { mNode->mStringValue = CopyString(mNode->mStringValue, start, sentinel); } } void TreeNodeManipulator::MoveStrings(VectorCharIter& start, const VectorCharIter& sentinel) { DALI_ASSERT_DEBUG(mNode && "Operation on NULL JSON node"); TreeNodeManipulator modify(mNode); modify.MoveNodeStrings(start, sentinel); RecurseMoveChildStrings(start, sentinel); } void TreeNodeManipulator::RecurseMoveChildStrings(VectorCharIter& start, const VectorCharIter& sentinel) { DALI_ASSERT_DEBUG(mNode && "Operation on NULL JSON node"); TreeNode* child = mNode->mFirstChild; while(child) { TreeNodeManipulator manipChild(child); manipChild.MoveNodeStrings(start, sentinel); child = child->mNextSibling; } child = mNode->mFirstChild; while(child) { TreeNodeManipulator manipChild(child); manipChild.RecurseMoveChildStrings(start, sentinel); child = child->mNextSibling; } } void TreeNodeManipulator::RemoveChildren() { DALI_ASSERT_DEBUG(mNode && "Operation on NULL JSON node"); CollectNodes collector; DepthFirst( mNode, collector ); for(CollectNodes::iterator iter = collector.nodes.begin(); iter != collector.nodes.end(); ++iter) { if( *iter != mNode) { delete *iter; } } mNode->mFirstChild = NULL; mNode->mLastChild = NULL; } TreeNode* TreeNodeManipulator::Copy(const TreeNode& tree, int& numberNodes, int& numberChars) { TreeNode* root = NewTreeNode(); ShallowCopy(&tree, root); if(tree.mName) { numberChars += std::strlen(tree.mName) + 1; } if(TreeNode::STRING == tree.mType) { numberChars += std::strlen(tree.mStringValue) + 1; } ++numberNodes; CopyChildren(&tree, root, numberNodes, numberChars); return root; } void TreeNodeManipulator::CopyChildren(const TreeNode* from, TreeNode* to, int& numberNodes, int& numberChars) { DALI_ASSERT_DEBUG(from && "Operation on NULL JSON node"); DALI_ASSERT_DEBUG(to); for( TreeNode::ConstIterator iter = from->CBegin(); iter != from->CEnd(); ++iter) { const TreeNode* child = &((*iter).second); if(child->mName) { numberChars += std::strlen(child->mName) + 1; } if(TreeNode::STRING == child->mType) { numberChars += std::strlen(child->mStringValue) + 1; } TreeNode* newNode = NewTreeNode(); ShallowCopy(child, newNode); TreeNodeManipulator modify(to); modify.AddChild(newNode); ++numberNodes; CopyChildren(child, newNode, numberNodes, numberChars); } } TreeNode *TreeNodeManipulator::AddChild(TreeNode *rhs) { DALI_ASSERT_DEBUG(mNode && "Operation on NULL JSON node"); rhs->mParent = mNode; if (mNode->mLastChild) { mNode->mLastChild = mNode->mLastChild->mNextSibling = rhs; } else { mNode->mFirstChild = mNode->mLastChild = rhs; } return rhs; } TreeNode::NodeType TreeNodeManipulator::GetType() const { DALI_ASSERT_DEBUG(mNode && "Operation on NULL JSON node"); return mNode->GetType(); } size_t TreeNodeManipulator::Size() const { DALI_ASSERT_DEBUG(mNode && "Operation on NULL JSON node"); return mNode->Size(); } void TreeNodeManipulator::SetType( TreeNode::NodeType type) { DALI_ASSERT_DEBUG(mNode && "Operation on NULL JSON node"); if( mNode->mType != type ) { mNode->mType = type; if( NULL != mNode->mFirstChild ) { // value types have no children bool removeChildren = ! (TreeNode::OBJECT == type || TreeNode::ARRAY == type); // ie if swapping array for object removeChildren = (removeChildren == true) ? true : type != mNode->mType; // so remove any children if( removeChildren && NULL != mNode->mFirstChild) { RemoveChildren(); } } } else if( TreeNode::ARRAY == mNode->mType ) { if( mNode->mFirstChild != NULL ) { TreeNode::NodeType type = mNode->mFirstChild->GetType(); if( TreeNode::FLOAT == type || TreeNode::INTEGER == type ) { // Arrays of numbers should be replaced, not appended to. RemoveChildren(); } } } } void TreeNodeManipulator::SetName( const char* name ) { DALI_ASSERT_DEBUG(mNode && "Operation on NULL JSON node"); mNode->mName = name; } void TreeNodeManipulator::SetSubstitution( bool b ) { DALI_ASSERT_DEBUG(mNode && "Operation on NULL JSON node"); mNode->mSubstituion = b; } TreeNode* TreeNodeManipulator::GetParent() const { DALI_ASSERT_DEBUG(mNode && "Operation on NULL JSON node"); return NULL == mNode ? NULL : mNode->mParent; } const TreeNode* TreeNodeManipulator::GetChild(const std::string& name) const { DALI_ASSERT_DEBUG(mNode && "Operation on NULL JSON node"); return NULL == mNode ? NULL : mNode->GetChild(name); } void TreeNodeManipulator::SetString( const char* string ) { DALI_ASSERT_DEBUG(mNode && "Operation on NULL JSON node"); SetType(TreeNode::STRING); mNode->mStringValue = string; } void TreeNodeManipulator::SetInteger( int i ) { DALI_ASSERT_DEBUG(mNode && "Operation on NULL JSON node"); SetType(TreeNode::INTEGER); mNode->mIntValue = i; } void TreeNodeManipulator::SetFloat( float f ) { DALI_ASSERT_DEBUG(mNode && "Operation on NULL JSON node"); SetType(TreeNode::FLOAT); mNode->mFloatValue = f; } void TreeNodeManipulator::SetBoolean( bool b ) { DALI_ASSERT_DEBUG(mNode && "Operation on NULL JSON node"); SetType(TreeNode::BOOLEAN); mNode->mIntValue = b == true ? 1 : 0; } void TreeNodeManipulator::Write(std::ostream& output, int indent) const { DALI_ASSERT_DEBUG(mNode && "Operation on NULL JSON node"); DoWrite(mNode, output, 0, indent, false); } void TreeNodeManipulator::DoWrite(const TreeNode *value, std::ostream& output, int level, int indentWidth, bool groupChildren) const { DALI_ASSERT_DEBUG(value && "Operation on NULL JSON node"); if(!groupChildren) { Indent(output, level, indentWidth); } if (value->GetName()) { output << "\"" << value->GetName() << "\":"; } switch(value->GetType()) { case TreeNode::IS_NULL: { output << "null"; if(NULL != value->mNextSibling) { output << ", "; } if( !groupChildren ) { output << std::endl; } break; } case TreeNode::OBJECT: case TreeNode::ARRAY: { bool groupMyChildren = false; if( TreeNode::ARRAY == value->GetType() && ( TreeNode::INTEGER == value->mFirstChild->GetType() || TreeNode::FLOAT == value->mFirstChild->GetType() ) ) { groupMyChildren = true; } if( value->GetType() == TreeNode::OBJECT) { output << std::endl; Indent(output, level, indentWidth); output << "{"; } else { if( !groupMyChildren ) { output << std::endl; Indent(output, level, indentWidth); } output << "["; } if( groupMyChildren ) { output << " "; } else { output << std::endl; } for (TreeNode::ConstIterator it = value->CBegin(); it != value->CEnd(); ++it) { DoWrite( &((*it).second), output, level+1, indentWidth, groupMyChildren ); } if( !groupMyChildren ) { Indent(output, level, indentWidth); } if( value->GetType() == TreeNode::OBJECT ) { output << "}"; } else { output << "]"; } if( NULL != value->mNextSibling ) { output << ","; } if( !groupChildren ) { output << std::endl; } groupChildren = false; break; } case TreeNode::STRING: { std::string escapedString = EscapeQuotes(value->GetString()); output << "\"" << escapedString << "\""; if(NULL != value->mNextSibling) { output << ","; } if( groupChildren ) { output << " "; } else { output << std::endl; } break; } case TreeNode::INTEGER: { output << value->GetInteger(); if(NULL != value->mNextSibling) { output << ","; } if( groupChildren ) { output << " "; } else { output << std::endl; } break; } case TreeNode::FLOAT: { output.setf( std::ios::floatfield ); output << value->GetFloat(); output.unsetf( std::ios::floatfield ); if(NULL != value->mNextSibling) { output << ","; } if( groupChildren ) { output << " "; } else { output << std::endl; } break; } case TreeNode::BOOLEAN: { if( value->GetInteger() ) { output << "true"; } else { output << "false"; } if(NULL != value->mNextSibling) { output << ","; } if( groupChildren ) { output << " "; } else { output << std::endl; } break; } } // switch } // DoWrite const TreeNode* FindIt(const std::string& childName, const TreeNode* node) { DALI_ASSERT_DEBUG(node); const TreeNode* found = NULL; if( node ) { if( NULL != (found = node->GetChild(childName)) ) { return found; } else { for(TreeNode::ConstIterator iter = node->CBegin(); iter != node->CEnd(); ++iter) { if( NULL != (found = FindIt(childName, &((*iter).second)) ) ) { return found; } } } } return found; } char *CopyString( const char *fromString, VectorCharIter& iter, const VectorCharIter& sentinel) { DALI_ASSERT_DEBUG(fromString); DALI_ASSERT_DEBUG(iter != sentinel); char *start= &(*iter); const char *ptr = fromString; if(ptr) { while(*ptr != 0) { DALI_ASSERT_DEBUG(iter != sentinel); *iter++ = *ptr++; } *iter++ = 0; } return start; } } // namespace internal } // namespace Toolkit } // namespace Dali
/* * Copyright (c) 2014 Samsung Electronics Co., Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ // EXTERNAL INCLUDES #include <cstring> #include <sstream> // INTERNAL INCLUDES #include <dali-toolkit/internal/builder/tree-node-manipulator.h> #include <dali-toolkit/devel-api/builder/tree-node.h> namespace Dali { namespace Toolkit { namespace Internal { namespace { void Indent(std::ostream& o, int level, int indentWidth) { for (int i = 0; i < level*indentWidth; ++i) { o << " "; } } std::string EscapeQuotes( const char* aString) { std::string escapedString; int length = strlen(aString); escapedString.reserve(length); const char* end = aString+length; for( const char* iter = aString; iter != end ; ++iter) { if(*iter != '\"') { escapedString.push_back(*iter); } else { escapedString.append("\\\""); } } return escapedString; } } // anonymous namespace TreeNodeManipulator::TreeNodeManipulator(TreeNode* node) : mNode(node) { } TreeNode* TreeNodeManipulator::NewTreeNode() { return new TreeNode(); } void TreeNodeManipulator::ShallowCopy(const TreeNode* from, TreeNode* to) { DALI_ASSERT_DEBUG(from); DALI_ASSERT_DEBUG(to); if( from ) { to->mName = from->mName; to->mType = from->mType; to->mSubstituion = from->mSubstituion; switch(from->mType) { case TreeNode::INTEGER: { to->mIntValue = from->mIntValue; break; } case TreeNode::FLOAT: { to->mFloatValue = from->mFloatValue; break; } case TreeNode::STRING: { to->mStringValue = from->mStringValue; break; } case TreeNode::BOOLEAN: { to->mIntValue = from->mIntValue; break; } case TreeNode::IS_NULL: case TreeNode::OBJECT: case TreeNode::ARRAY: { break; } } } } void TreeNodeManipulator::MoveNodeStrings(VectorCharIter& start, const VectorCharIter& sentinel) { DALI_ASSERT_DEBUG(mNode && "Operation on NULL JSON node"); if(mNode->mName) { mNode->mName = CopyString(mNode->mName, start, sentinel); } if(TreeNode::STRING == mNode->mType) { mNode->mStringValue = CopyString(mNode->mStringValue, start, sentinel); } } void TreeNodeManipulator::MoveStrings(VectorCharIter& start, const VectorCharIter& sentinel) { DALI_ASSERT_DEBUG(mNode && "Operation on NULL JSON node"); TreeNodeManipulator modify(mNode); modify.MoveNodeStrings(start, sentinel); RecurseMoveChildStrings(start, sentinel); } void TreeNodeManipulator::RecurseMoveChildStrings(VectorCharIter& start, const VectorCharIter& sentinel) { DALI_ASSERT_DEBUG(mNode && "Operation on NULL JSON node"); TreeNode* child = mNode->mFirstChild; while(child) { TreeNodeManipulator manipChild(child); manipChild.MoveNodeStrings(start, sentinel); child = child->mNextSibling; } child = mNode->mFirstChild; while(child) { TreeNodeManipulator manipChild(child); manipChild.RecurseMoveChildStrings(start, sentinel); child = child->mNextSibling; } } void TreeNodeManipulator::RemoveChildren() { DALI_ASSERT_DEBUG(mNode && "Operation on NULL JSON node"); CollectNodes collector; DepthFirst( mNode, collector ); for(CollectNodes::iterator iter = collector.nodes.begin(); iter != collector.nodes.end(); ++iter) { if( *iter != mNode) { delete *iter; } } mNode->mFirstChild = NULL; mNode->mLastChild = NULL; } TreeNode* TreeNodeManipulator::Copy(const TreeNode& tree, int& numberNodes, int& numberChars) { TreeNode* root = NewTreeNode(); ShallowCopy(&tree, root); if(tree.mName) { numberChars += std::strlen(tree.mName) + 1; } if(TreeNode::STRING == tree.mType) { numberChars += std::strlen(tree.mStringValue) + 1; } ++numberNodes; CopyChildren(&tree, root, numberNodes, numberChars); return root; } void TreeNodeManipulator::CopyChildren(const TreeNode* from, TreeNode* to, int& numberNodes, int& numberChars) { DALI_ASSERT_DEBUG(from && "Operation on NULL JSON node"); DALI_ASSERT_DEBUG(to); for( TreeNode::ConstIterator iter = from->CBegin(); iter != from->CEnd(); ++iter) { const TreeNode* child = &((*iter).second); if(child->mName) { numberChars += std::strlen(child->mName) + 1; } if(TreeNode::STRING == child->mType) { numberChars += std::strlen(child->mStringValue) + 1; } TreeNode* newNode = NewTreeNode(); ShallowCopy(child, newNode); TreeNodeManipulator modify(to); modify.AddChild(newNode); ++numberNodes; CopyChildren(child, newNode, numberNodes, numberChars); } } TreeNode *TreeNodeManipulator::AddChild(TreeNode *rhs) { DALI_ASSERT_DEBUG(mNode && "Operation on NULL JSON node"); rhs->mParent = mNode; if (mNode->mLastChild) { mNode->mLastChild = mNode->mLastChild->mNextSibling = rhs; } else { mNode->mFirstChild = mNode->mLastChild = rhs; } return rhs; } TreeNode::NodeType TreeNodeManipulator::GetType() const { DALI_ASSERT_DEBUG(mNode && "Operation on NULL JSON node"); return mNode->GetType(); } size_t TreeNodeManipulator::Size() const { DALI_ASSERT_DEBUG(mNode && "Operation on NULL JSON node"); return mNode->Size(); } void TreeNodeManipulator::SetType( TreeNode::NodeType type) { DALI_ASSERT_DEBUG(mNode && "Operation on NULL JSON node"); if( mNode->mType != type ) { mNode->mType = type; if( NULL != mNode->mFirstChild ) { // value types have no children bool removeChildren = ! (TreeNode::OBJECT == type || TreeNode::ARRAY == type); // ie if swapping array for object removeChildren = (removeChildren == true) ? true : type != mNode->mType; // so remove any children if( removeChildren && NULL != mNode->mFirstChild) { RemoveChildren(); } } } else if( TreeNode::ARRAY == mNode->mType ) { if( mNode->mFirstChild != NULL ) { TreeNode::NodeType type = mNode->mFirstChild->GetType(); if( TreeNode::FLOAT == type || TreeNode::INTEGER == type ) { // Arrays of numbers should be replaced, not appended to. RemoveChildren(); } } } } void TreeNodeManipulator::SetName( const char* name ) { DALI_ASSERT_DEBUG(mNode && "Operation on NULL JSON node"); mNode->mName = name; } void TreeNodeManipulator::SetSubstitution( bool b ) { DALI_ASSERT_DEBUG(mNode && "Operation on NULL JSON node"); mNode->mSubstituion = b; } TreeNode* TreeNodeManipulator::GetParent() const { DALI_ASSERT_DEBUG(mNode && "Operation on NULL JSON node"); return NULL == mNode ? NULL : mNode->mParent; } const TreeNode* TreeNodeManipulator::GetChild(const std::string& name) const { DALI_ASSERT_DEBUG(mNode && "Operation on NULL JSON node"); return NULL == mNode ? NULL : mNode->GetChild(name); } void TreeNodeManipulator::SetString( const char* string ) { DALI_ASSERT_DEBUG(mNode && "Operation on NULL JSON node"); SetType(TreeNode::STRING); mNode->mStringValue = string; } void TreeNodeManipulator::SetInteger( int i ) { DALI_ASSERT_DEBUG(mNode && "Operation on NULL JSON node"); SetType(TreeNode::INTEGER); mNode->mIntValue = i; } void TreeNodeManipulator::SetFloat( float f ) { DALI_ASSERT_DEBUG(mNode && "Operation on NULL JSON node"); SetType(TreeNode::FLOAT); mNode->mFloatValue = f; } void TreeNodeManipulator::SetBoolean( bool b ) { DALI_ASSERT_DEBUG(mNode && "Operation on NULL JSON node"); SetType(TreeNode::BOOLEAN); mNode->mIntValue = b == true ? 1 : 0; } void TreeNodeManipulator::Write(std::ostream& output, int indent) const { DALI_ASSERT_DEBUG(mNode && "Operation on NULL JSON node"); DoWrite(mNode, output, 0, indent, false); } void TreeNodeManipulator::DoWrite(const TreeNode *value, std::ostream& output, int level, int indentWidth, bool groupChildren) const { DALI_ASSERT_DEBUG(value && "Operation on NULL JSON node"); if(!groupChildren) { Indent(output, level, indentWidth); } if (value->GetName()) { output << "\"" << value->GetName() << "\":"; } switch(value->GetType()) { case TreeNode::IS_NULL: { output << "null"; if(NULL != value->mNextSibling) { output << ", "; } if( !groupChildren ) { output << std::endl; } break; } case TreeNode::OBJECT: case TreeNode::ARRAY: { bool groupMyChildren = false; if( TreeNode::ARRAY == value->GetType() && value->mFirstChild && ( TreeNode::INTEGER == value->mFirstChild->GetType() || TreeNode::FLOAT == value->mFirstChild->GetType() ) ) { groupMyChildren = true; } if( value->GetType() == TreeNode::OBJECT) { output << std::endl; Indent(output, level, indentWidth); output << "{"; } else { if( !groupMyChildren ) { output << std::endl; Indent(output, level, indentWidth); } output << "["; } if( groupMyChildren ) { output << " "; } else { output << std::endl; } for (TreeNode::ConstIterator it = value->CBegin(); it != value->CEnd(); ++it) { DoWrite( &((*it).second), output, level+1, indentWidth, groupMyChildren ); } if( !groupMyChildren ) { Indent(output, level, indentWidth); } if( value->GetType() == TreeNode::OBJECT ) { output << "}"; } else { output << "]"; } if( NULL != value->mNextSibling ) { output << ","; } if( !groupChildren ) { output << std::endl; } groupChildren = false; break; } case TreeNode::STRING: { std::string escapedString = EscapeQuotes(value->GetString()); output << "\"" << escapedString << "\""; if(NULL != value->mNextSibling) { output << ","; } if( groupChildren ) { output << " "; } else { output << std::endl; } break; } case TreeNode::INTEGER: { output << value->GetInteger(); if(NULL != value->mNextSibling) { output << ","; } if( groupChildren ) { output << " "; } else { output << std::endl; } break; } case TreeNode::FLOAT: { output.setf( std::ios::floatfield ); output << value->GetFloat(); output.unsetf( std::ios::floatfield ); if(NULL != value->mNextSibling) { output << ","; } if( groupChildren ) { output << " "; } else { output << std::endl; } break; } case TreeNode::BOOLEAN: { if( value->GetInteger() ) { output << "true"; } else { output << "false"; } if(NULL != value->mNextSibling) { output << ","; } if( groupChildren ) { output << " "; } else { output << std::endl; } break; } } // switch } // DoWrite const TreeNode* FindIt(const std::string& childName, const TreeNode* node) { DALI_ASSERT_DEBUG(node); const TreeNode* found = NULL; if( node ) { if( NULL != (found = node->GetChild(childName)) ) { return found; } else { for(TreeNode::ConstIterator iter = node->CBegin(); iter != node->CEnd(); ++iter) { if( NULL != (found = FindIt(childName, &((*iter).second)) ) ) { return found; } } } } return found; } char *CopyString( const char *fromString, VectorCharIter& iter, const VectorCharIter& sentinel) { DALI_ASSERT_DEBUG(fromString); DALI_ASSERT_DEBUG(iter != sentinel); char *start= &(*iter); const char *ptr = fromString; if(ptr) { while(*ptr != 0) { DALI_ASSERT_DEBUG(iter != sentinel); *iter++ = *ptr++; } *iter++ = 0; } return start; } } // namespace internal } // namespace Toolkit } // namespace Dali
Enable json tree dump to work with empty arrays
Enable json tree dump to work with empty arrays If the json contains an empty array it would crash as there was no check before dereferencing a pointer. Below constant section should be added to json to get debug output "constants": { "CONFIG_SCRIPT_LOG_LEVEL":"Verbose", "DUMP_TREE":1 }, Change-Id: I9584fa0c4202ea7907a9235cdfb81264ab3596c6
C++
apache-2.0
dalihub/dali-toolkit,dalihub/dali-toolkit,dalihub/dali-toolkit,dalihub/dali-toolkit
123c182033cd6caf9125842bae60c5c4ce48cb2a
features/FEATURE_COMMON_PAL/nanostack-hal-mbed-cmsis-rtos/arm_hal_timer.cpp
features/FEATURE_COMMON_PAL/nanostack-hal-mbed-cmsis-rtos/arm_hal_timer.cpp
/* * Copyright (c) 2016 ARM Limited, All Rights Reserved */ // Include before mbed.h to properly get UINT*_C() #include "ns_types.h" #include "mbed.h" #include "platform/arm_hal_timer.h" #include "platform/arm_hal_interrupt.h" #include <mbed_assert.h> static Timer timer; static Timeout timeout; // If critical sections are implemented using mutexes, timers must be called in thread context, and // we use the high-priority event queue for this. // If critical sections disable interrupts, we can call timers directly from interrupt. Avoiding the // event queue can save ~1600B of RAM if the rest of the system is not using the event queue either. // Caveats of this tunable are listed on arm_hal_interrupt.c. #if !MBED_CONF_NANOSTACK_HAL_CRITICAL_SECTION_USABLE_FROM_INTERRUPT static EventQueue *equeue; #endif static uint32_t due; static void (*arm_hal_callback)(void); // Called once at boot void platform_timer_enable(void) { #if !MBED_CONF_NANOSTACK_HAL_CRITICAL_SECTION_USABLE_FROM_INTERRUPT equeue = mbed_highprio_event_queue(); MBED_ASSERT(equeue != NULL); #endif } // Actually cancels a timer, not the opposite of enable void platform_timer_disable(void) { timeout.detach(); } // Not called while running, fortunately void platform_timer_set_cb(void (*new_fp)(void)) { arm_hal_callback = new_fp; } static void timer_callback(void) { due = 0; #if MBED_CONF_NANOSTACK_HAL_CRITICAL_SECTION_USABLE_FROM_INTERRUPT // Callback is interrupt safe so it can be called directly without // bouncing via event queue thread. arm_hal_callback(); #else equeue->call(arm_hal_callback); #endif } // This is called from inside platform_enter_critical - IRQs can't happen void platform_timer_start(uint16_t slots) { timer.reset(); due = slots * UINT32_C(50); timeout.attach_us(timer_callback, due); } // This is called from inside platform_enter_critical - IRQs can't happen uint16_t platform_timer_get_remaining_slots(void) { uint32_t elapsed = timer.read_us(); if (elapsed < due) { return (uint16_t) ((due - elapsed) / 50); } else { return 0; } }
/* * Copyright (c) 2016 ARM Limited, All Rights Reserved */ // Include before mbed.h to properly get UINT*_C() #include "ns_types.h" #include "mbed.h" #include "platform/SingletonPtr.h" #include "platform/arm_hal_timer.h" #include "platform/arm_hal_interrupt.h" #include <mbed_assert.h> static SingletonPtr<Timer> timer; static SingletonPtr<Timeout> timeout; // If critical sections are implemented using mutexes, timers must be called in thread context, and // we use the high-priority event queue for this. // If critical sections disable interrupts, we can call timers directly from interrupt. Avoiding the // event queue can save ~1600B of RAM if the rest of the system is not using the event queue either. // Caveats of this tunable are listed on arm_hal_interrupt.c. #if !MBED_CONF_NANOSTACK_HAL_CRITICAL_SECTION_USABLE_FROM_INTERRUPT static EventQueue *equeue; #endif static uint32_t due; static void (*arm_hal_callback)(void); // Called once at boot void platform_timer_enable(void) { #if !MBED_CONF_NANOSTACK_HAL_CRITICAL_SECTION_USABLE_FROM_INTERRUPT equeue = mbed_highprio_event_queue(); MBED_ASSERT(equeue != NULL); #endif // Prime the SingletonPtrs - can't construct from IRQ/critical section timer.get(); timeout.get(); } // Actually cancels a timer, not the opposite of enable void platform_timer_disable(void) { timeout->detach(); } // Not called while running, fortunately void platform_timer_set_cb(void (*new_fp)(void)) { arm_hal_callback = new_fp; } static void timer_callback(void) { due = 0; #if MBED_CONF_NANOSTACK_HAL_CRITICAL_SECTION_USABLE_FROM_INTERRUPT // Callback is interrupt safe so it can be called directly without // bouncing via event queue thread. arm_hal_callback(); #else equeue->call(arm_hal_callback); #endif } // This is called from inside platform_enter_critical - IRQs can't happen void platform_timer_start(uint16_t slots) { timer->reset(); due = slots * UINT32_C(50); timeout->attach_us(timer_callback, due); } // This is called from inside platform_enter_critical - IRQs can't happen uint16_t platform_timer_get_remaining_slots(void) { uint32_t elapsed = timer->read_us(); if (elapsed < due) { return (uint16_t) ((due - elapsed) / 50); } else { return 0; } }
Use SingletonPtr in Nanostack HAL
Use SingletonPtr in Nanostack HAL Avoid static data/code overhead when Nanostack HAL isn't in use. Preparation for removal of FEATURE_COMMON_PAL.
C++
apache-2.0
c1728p9/mbed-os,c1728p9/mbed-os,mbedmicro/mbed,betzw/mbed-os,kjbracey-arm/mbed,andcor02/mbed-os,mbedmicro/mbed,betzw/mbed-os,c1728p9/mbed-os,betzw/mbed-os,c1728p9/mbed-os,mbedmicro/mbed,betzw/mbed-os,kjbracey-arm/mbed,betzw/mbed-os,betzw/mbed-os,andcor02/mbed-os,andcor02/mbed-os,c1728p9/mbed-os,c1728p9/mbed-os,andcor02/mbed-os,mbedmicro/mbed,kjbracey-arm/mbed,mbedmicro/mbed,andcor02/mbed-os,andcor02/mbed-os,kjbracey-arm/mbed
103453b899e0133100a72ebe82157fe499a18f8b
src/Tests/CoreTests/Geometry/GeometryTests.hpp
src/Tests/CoreTests/Geometry/GeometryTests.hpp
#ifndef RADIUM_GEOMETRYTESTS_HPP_ #define RADIUM_GEOMETRYTESTS_HPP_ #include <Core/Geometry/Distance/DistanceQueries.hpp> #include <Core/Math/PolyLine.hpp> using Ra::Core::DistanceQueries::pointToLineSq; using Ra::Core::DistanceQueries::pointToSegmentSq; using Ra::Core::DistanceQueries::pointToTriSq; using Ra::Core::DistanceQueries::PointToTriangleOutput; using Ra::Core::DistanceQueries::FlagsInternal; using Ra::Core::Math::areApproxEqual; using Ra::Core::Vector3; namespace RaTests { class GeometryTests : public Test { void run() override { Vector3 a(1.f, 2.3f, 4.5f); Vector3 b(-6.f, 7.f, 8.9f); Vector3 c(-3.f, 12.3f, -42.1f); // Midpoint. Vector3 m = 0.5f*(a+b); // Point on the line, before A Vector3 na = a - 12.f*(b-a); // Point on the line after B Vector3 nb = a + 42.f*(b-a); Vector3 y,z; Ra::Core::Vector::getOrthogonalVectors(b-a, y, z); // Test line queries. RA_UNIT_TEST( pointToLineSq(a, a, b-a) == 0.f, "distance from A to AB" ); RA_UNIT_TEST( areApproxEqual(pointToLineSq(b, a, b-a), 0.f), "distance from B to AB" ); RA_UNIT_TEST( areApproxEqual(pointToLineSq(na, a, b-a), 0.f), "point on the line."); RA_UNIT_TEST( areApproxEqual(pointToLineSq(nb, a, b-a), 0.f), "point on the line."); RA_UNIT_TEST( areApproxEqual(pointToLineSq(m + y, a, b-a), y.squaredNorm()), "point perpendicular to segment."); // Test segment queries RA_UNIT_TEST( pointToSegmentSq(a, a, b-a) == 0.f, "Segment extremity" ); RA_UNIT_TEST( pointToSegmentSq(b, a, b-a) == 0.f, "Segment extremity" ); RA_UNIT_TEST( areApproxEqual(pointToSegmentSq(na, a, b-a) , (na-a).squaredNorm()), "point on the line."); RA_UNIT_TEST( areApproxEqual(pointToSegmentSq(nb, a, b-a) , (nb-b).squaredNorm()), "point on the line."); RA_UNIT_TEST( areApproxEqual(pointToSegmentSq(m + y, a, b-a) , y.squaredNorm()), "point perpendicular to segment."); // Test triangle queries // Test that each vertex returns itself auto da = pointToTriSq(a,a,b,c); RA_UNIT_TEST( da.distanceSquared == 0.f, "distance from A to ABC" ); RA_UNIT_TEST( da.meshPoint == a, "distance from A to ABC"); RA_UNIT_TEST( da.flags == FlagsInternal::HIT_A , "distance from A to ABC"); auto db = pointToTriSq(b,a,b,c); RA_UNIT_TEST( db.distanceSquared == 0.f, "distance from B to ABC" ); RA_UNIT_TEST( db.meshPoint == b, "distance from B to ABC"); RA_UNIT_TEST( db.flags == FlagsInternal::HIT_B, "distance from B to ABC"); auto dc = pointToTriSq(c,a,b,c); RA_UNIT_TEST( dc.distanceSquared == 0.f, "distance from C to ABC" ); RA_UNIT_TEST( dc.meshPoint == c, "distance from C to ABC"); RA_UNIT_TEST( dc.flags == FlagsInternal::HIT_C, "distance from C to ABC"); // Test midpoints of edges Vector3 mab = 0.5f * (a+b); Vector3 mac = 0.5f * (a+c); Vector3 mbc = 0.5f * (b+c); auto dmab = pointToTriSq(mab, a,b,c); RA_UNIT_TEST( areApproxEqual(dmab.distanceSquared, 0.f), "Distance from AB midpoint to ABC"); RA_UNIT_TEST( dmab.meshPoint.isApprox(mab), "Distance from AB midpoint to ABC"); RA_UNIT_TEST( dmab.flags == FlagsInternal::HIT_AB, "Distance from AB midpoint to ABC"); auto dmac = pointToTriSq(mac, a,b,c); RA_UNIT_TEST( areApproxEqual(dmac.distanceSquared, 0.f), "Distance from AC midpoint to ABC"); RA_UNIT_TEST( dmac.meshPoint.isApprox(mac), "Distance from AC midpoint to ABC"); RA_UNIT_TEST( dmac.flags == FlagsInternal::HIT_CA, "Distance from AC midpoint to ABC"); auto dmbc = pointToTriSq(mbc, a,b,c); RA_UNIT_TEST( areApproxEqual(dmbc.distanceSquared, 0.f), "Distance from BC midpoint to ABC"); RA_UNIT_TEST( dmbc.meshPoint.isApprox(mbc), "Distance from BC midpoint to ACC"); RA_UNIT_TEST( dmbc.flags == FlagsInternal::HIT_BC, "Distance from BC midpoint to ACC"); // Point inside the triangle Vector3 g = (1.f/3.f) * (a+b+c); auto dg = pointToTriSq(g,a,b,c); RA_UNIT_TEST( areApproxEqual(dg.distanceSquared, 0.f), "Distance from centroid to ABC"); RA_UNIT_TEST( dg.meshPoint.isApprox(g), "Distance from centroid to ABC"); RA_UNIT_TEST( dg.flags == FlagsInternal::HIT_FACE, "Distance from centroid to ABC"); } }; //DECLARE class PolylineTests : public Test { void run() override { // 2 points polyline { Ra::Core::Vector3Array v2 { {1,2,3}, {4,5,6}}; Ra::Core::PolyLine p(v2); Ra::Core::Vector3 m = 0.5f * (v2[0] + v2[1]); RA_UNIT_TEST(p.f(0) == v2[0], "Parametrization fail"); RA_UNIT_TEST(p.f(1) == v2[1], "Parametrization fail"); RA_UNIT_TEST(p.f(0.5f).isApprox(m), "Parametrization fail"); RA_UNIT_TEST (Ra::Core::Math::areApproxEqual(p.distance(m), 0.f), "Distance fail" ); } // 4 points polyline { Ra::Core::Vector3Array v4{{2, 3, 5}, {7, 11, 13}, {17, 23, 29}, {-1, -1, 30}}; Ra::Core::PolyLine p(v4); RA_UNIT_TEST(p.f(0) == v4[0], "Parametrization fail"); RA_UNIT_TEST(p.f(1) == v4[3], "Parametrization fail"); RA_UNIT_TEST(p.f(-10.) == p.f(0), "Parametrization clamp fail"); RA_UNIT_TEST(p.f(10.) == p.f(1), "Parametrization clamp fail"); for (const auto& x : v4) { RA_UNIT_TEST(p.distance(x) == 0.f, "Distance fail"); } } } }; RA_TEST_CLASS(GeometryTests); RA_TEST_CLASS(PolylineTests); } #endif //RADIUM_GEOMETRYTESTS_HPP_
#ifndef RADIUM_GEOMETRYTESTS_HPP_ #define RADIUM_GEOMETRYTESTS_HPP_ #include <Core/Geometry/Distance/DistanceQueries.hpp> #include <Core/Math/PolyLine.hpp> using Ra::Core::DistanceQueries::pointToLineSq; using Ra::Core::DistanceQueries::pointToSegmentSq; using Ra::Core::DistanceQueries::pointToTriSq; using Ra::Core::DistanceQueries::PointToTriangleOutput; using Ra::Core::DistanceQueries::FlagsInternal; using Ra::Core::Math::areApproxEqual; using Ra::Core::Vector3; namespace RaTests { class GeometryTests : public Test { void run() override { Vector3 a(1., 2.3, 4.5); Vector3 b(-6., 7., 8.9); Vector3 c(-3., 12.3, -42.1); // Midpoint. Vector3 m = 0.5*(a+b); // Point on the line, before A Vector3 na = a - 12.*(b-a); // Point on the line after B Vector3 nb = a + 42.*(b-a); Vector3 y,z; Ra::Core::Vector::getOrthogonalVectors(b-a, y, z); // Test line queries. RA_UNIT_TEST( areApproxEqual(pointToLineSq(a, a, b-a), Scalar(0.)), "distance from A to AB" ); RA_UNIT_TEST( areApproxEqual(pointToLineSq(b, a, b-a), Scalar(0.)), "distance from B to AB" ); RA_UNIT_TEST( areApproxEqual(pointToLineSq(na, a, b-a), Scalar(0.)), "point on the line."); RA_UNIT_TEST( areApproxEqual(pointToLineSq(nb, a, b-a), Scalar(0.)), "point on the line."); RA_UNIT_TEST( areApproxEqual(pointToLineSq(m + y, a, b-a), y.squaredNorm()), "point perpendicular to segment."); // Test segment queries RA_UNIT_TEST( areApproxEqual(pointToSegmentSq(a, a, b-a), Scalar(0.)), "Segment extremity" ); RA_UNIT_TEST( areApproxEqual(pointToSegmentSq(b, a, b-a), Scalar(0.)), "Segment extremity" ); RA_UNIT_TEST( areApproxEqual(pointToSegmentSq(na, a, b-a) , (na-a).squaredNorm()), "point on the line."); RA_UNIT_TEST( areApproxEqual(pointToSegmentSq(nb, a, b-a) , (nb-b).squaredNorm()), "point on the line."); RA_UNIT_TEST( areApproxEqual(pointToSegmentSq(m + y, a, b-a) , y.squaredNorm()), "point perpendicular to segment."); // Test triangle queries // Test that each vertex returns itself auto da = pointToTriSq(a,a,b,c); RA_UNIT_TEST( da.distanceSquared == Scalar(0.), "distance from A to ABC" ); RA_UNIT_TEST( da.meshPoint == a, "distance from A to ABC"); RA_UNIT_TEST( da.flags == FlagsInternal::HIT_A , "distance from A to ABC"); auto db = pointToTriSq(b,a,b,c); RA_UNIT_TEST( db.distanceSquared == Scalar(0.), "distance from B to ABC" ); RA_UNIT_TEST( db.meshPoint == b, "distance from B to ABC"); RA_UNIT_TEST( db.flags == FlagsInternal::HIT_B, "distance from B to ABC"); auto dc = pointToTriSq(c,a,b,c); RA_UNIT_TEST( dc.distanceSquared == Scalar(0.), "distance from C to ABC" ); RA_UNIT_TEST( dc.meshPoint == c, "distance from C to ABC"); RA_UNIT_TEST( dc.flags == FlagsInternal::HIT_C, "distance from C to ABC"); // Test midpoints of edges Vector3 mab = 0.5f * (a+b); Vector3 mac = 0.5f * (a+c); Vector3 mbc = 0.5f * (b+c); auto dmab = pointToTriSq(mab, a,b,c); RA_UNIT_TEST( areApproxEqual(dmab.distanceSquared, Scalar(0.)), "Distance from AB midpoint to ABC"); RA_UNIT_TEST( dmab.meshPoint.isApprox(mab), "Distance from AB midpoint to ABC"); RA_UNIT_TEST( dmab.flags == FlagsInternal::HIT_AB, "Distance from AB midpoint to ABC"); auto dmac = pointToTriSq(mac, a,b,c); RA_UNIT_TEST( areApproxEqual(dmac.distanceSquared, Scalar(0.)), "Distance from AC midpoint to ABC"); RA_UNIT_TEST( dmac.meshPoint.isApprox(mac), "Distance from AC midpoint to ABC"); RA_UNIT_TEST( dmac.flags == FlagsInternal::HIT_CA, "Distance from AC midpoint to ABC"); auto dmbc = pointToTriSq(mbc, a,b,c); RA_UNIT_TEST( areApproxEqual(dmbc.distanceSquared, Scalar(0.)), "Distance from BC midpoint to ABC"); RA_UNIT_TEST( dmbc.meshPoint.isApprox(mbc), "Distance from BC midpoint to ACC"); RA_UNIT_TEST( dmbc.flags == FlagsInternal::HIT_BC, "Distance from BC midpoint to ACC"); // Point inside the triangle Vector3 g = (1.f/3.f) * (a+b+c); auto dg = pointToTriSq(g,a,b,c); RA_UNIT_TEST( areApproxEqual(dg.distanceSquared, Scalar(0.)), "Distance from centroid to ABC"); RA_UNIT_TEST( dg.meshPoint.isApprox(g), "Distance from centroid to ABC"); RA_UNIT_TEST( dg.flags == FlagsInternal::HIT_FACE, "Distance from centroid to ABC"); } }; //DECLARE class PolylineTests : public Test { void run() override { // 2 points polyline { Ra::Core::Vector3Array v2 { {1,2,3}, {4,5,6}}; Ra::Core::PolyLine p(v2); Ra::Core::Vector3 m = 0.5f * (v2[0] + v2[1]); RA_UNIT_TEST(p.f(0) == v2[0], "Parametrization fail"); RA_UNIT_TEST(p.f(1) == v2[1], "Parametrization fail"); RA_UNIT_TEST(p.f(0.5f).isApprox(m), "Parametrization fail"); RA_UNIT_TEST (Ra::Core::Math::areApproxEqual(p.distance(m), Scalar(0.)), "Distance fail" ); } // 4 points polyline { Ra::Core::Vector3Array v4{{2, 3, 5}, {7, 11, 13}, {17, 23, 29}, {-1, -1, 30}}; Ra::Core::PolyLine p(v4); RA_UNIT_TEST(p.f(0) == v4[0], "Parametrization fail"); RA_UNIT_TEST(p.f(1) == v4[3], "Parametrization fail"); RA_UNIT_TEST(p.f(-10.) == p.f(0), "Parametrization clamp fail"); RA_UNIT_TEST(p.f(10.) == p.f(1), "Parametrization clamp fail"); for (const auto& x : v4) { RA_UNIT_TEST(p.distance(x) == Scalar(0.), "Distance fail"); } } } }; RA_TEST_CLASS(GeometryTests); RA_TEST_CLASS(PolylineTests); } #endif //RADIUM_GEOMETRYTESTS_HPP_
use approxEqual in comparisons to expected values
use approxEqual in comparisons to expected values
C++
bsd-3-clause
Zouch/Radium-Engine,AGGA-IRIT/Radium-Engine,Zouch/Radium-Engine,AGGA-IRIT/Radium-Engine
0cf5a07da0ae5e6f24ea397dc3341f6a54229c41
mtTorrent/Core/TrackerManager.cpp
mtTorrent/Core/TrackerManager.cpp
#include "TrackerManager.h" #include "HttpTrackerComm.h" #include "UdpTrackerComm.h" #include "Configuration.h" #include "Torrent.h" #include "HttpsTrackerComm.h" mtt::TrackerManager::TrackerManager(TorrentPtr t) : torrent(t) { } void mtt::TrackerManager::start(AnnounceCallback callbk) { std::lock_guard<std::mutex> guard(trackersMutex); announceCallback = callbk; for (size_t i = 0; i < 3 && i < trackers.size(); i++) { auto& t = trackers[i]; if (!t.comm) { start(&t); } } } void mtt::TrackerManager::stop() { std::lock_guard<std::mutex> guard(trackersMutex); stopAll(); announceCallback = nullptr; } void mtt::TrackerManager::addTracker(std::string addr) { std::lock_guard<std::mutex> guard(trackersMutex); TrackerInfo info; info.uri = Uri::Parse(addr); info.fullAddress = addr; if (!info.uri.port.empty()) { auto i = findTrackerInfo(info.uri.host); if (i && i->uri.port == info.uri.port) { if ((i->uri.protocol == "http" || info.uri.protocol == "http") && (i->uri.protocol == "udp" || info.uri.protocol == "udp") && !i->comm) { i->uri.protocol = "udp"; i->httpFallback = true; } } else trackers.push_back(info); } else if(info.uri.protocol == "https") trackers.push_back(info); } void mtt::TrackerManager::addTrackers(const std::vector<std::string>& trackers) { for (auto& t : trackers) { addTracker(t); } } void mtt::TrackerManager::removeTrackers() { std::lock_guard<std::mutex> guard(trackersMutex); trackers.clear(); } std::shared_ptr<mtt::Tracker> mtt::TrackerManager::getTrackerByAddr(const std::string& addr) { std::lock_guard<std::mutex> guard(trackersMutex); for (auto& tracker : trackers) { if (tracker.fullAddress == addr) return tracker.comm; } return nullptr; } std::vector<std::pair<std::string, std::shared_ptr<mtt::Tracker>>> mtt::TrackerManager::getTrackers() { std::vector<std::pair<std::string, std::shared_ptr<mtt::Tracker>>> out; std::lock_guard<std::mutex> guard(trackersMutex); for (auto& t : trackers) { out.push_back({ t.fullAddress, t.comm }); } return out; } uint32_t mtt::TrackerManager::getTrackersCount() { return (uint32_t)trackers.size(); } void mtt::TrackerManager::onAnnounce(AnnounceResponse& resp, Tracker* t) { torrent->service.io.post([this, resp, t]() { std::lock_guard<std::mutex> guard(trackersMutex); if (auto trackerInfo = findTrackerInfo(t)) { trackerInfo->retryCount = 0; trackerInfo->timer->schedule(resp.interval); trackerInfo->comm->info.nextAnnounce = (uint32_t)time(0) + resp.interval; } if (announceCallback) announceCallback(Status::Success, &resp, t); startNext(); }); } void mtt::TrackerManager::onTrackerFail(Tracker* t) { std::lock_guard<std::mutex> guard(trackersMutex); if (auto trackerInfo = findTrackerInfo(t)) { if (trackerInfo->httpFallback && !trackerInfo->httpFallbackUsed && trackerInfo->uri.protocol == "udp") { trackerInfo->httpFallbackUsed = true; trackerInfo->uri.protocol = "http"; start(trackerInfo); } else { if (trackerInfo->httpFallback && trackerInfo->httpFallbackUsed && trackerInfo->uri.protocol == "http") { trackerInfo->uri.protocol = "udp"; start(trackerInfo); } else { trackerInfo->retryCount++; uint32_t nextRetry = 30 * trackerInfo->retryCount; trackerInfo->timer->schedule(nextRetry); trackerInfo->comm->info.nextAnnounce = (uint32_t)time(0) + nextRetry; } startNext(); } if(announceCallback) announceCallback(Status::E_Unknown, nullptr, t); } } void mtt::TrackerManager::start(TrackerInfo* tracker) { if (tracker->uri.protocol == "udp") tracker->comm = std::make_shared<UdpTrackerComm>(); else if (tracker->uri.protocol == "http") tracker->comm = std::make_shared<HttpTrackerComm>(); #ifdef MTT_WITH_SSL else if (tracker->uri.protocol == "https") tracker->comm = std::make_shared<HttpsTrackerComm>(); #endif else return; tracker->comm->onFail = std::bind(&TrackerManager::onTrackerFail, this, tracker->comm.get()); tracker->comm->onAnnounceResult = std::bind(&TrackerManager::onAnnounce, this, std::placeholders::_1, tracker->comm.get()); tracker->comm->init(tracker->uri.host, tracker->uri.port, tracker->uri.path, torrent); tracker->timer = ScheduledTimer::create(torrent->service.io, std::bind(&Tracker::announce, tracker->comm.get())); tracker->retryCount = 0; tracker->comm->announce(); } void mtt::TrackerManager::startNext() { for (auto& tracker : trackers) { if (!tracker.comm) start(&tracker); } } void mtt::TrackerManager::stopAll() { for (auto& tracker : trackers) { if(tracker.comm) tracker.comm->deinit(); tracker.comm = nullptr; if(tracker.timer) tracker.timer->disable(); tracker.timer = nullptr; tracker.retryCount = 0; } } mtt::TrackerManager::TrackerInfo* mtt::TrackerManager::findTrackerInfo(Tracker* t) { for (auto& tracker : trackers) { if (tracker.comm.get() == t) return &tracker; } return nullptr; } mtt::TrackerManager::TrackerInfo* mtt::TrackerManager::findTrackerInfo(std::string host) { for (auto& tracker : trackers) { if (tracker.uri.host == host) return &tracker; } return nullptr; }
#include "TrackerManager.h" #include "HttpTrackerComm.h" #include "UdpTrackerComm.h" #include "Configuration.h" #include "Torrent.h" #include "HttpsTrackerComm.h" mtt::TrackerManager::TrackerManager(TorrentPtr t) : torrent(t) { } void mtt::TrackerManager::start(AnnounceCallback callbk) { std::lock_guard<std::mutex> guard(trackersMutex); announceCallback = callbk; for (size_t i = 0; i < 3 && i < trackers.size(); i++) { auto& t = trackers[i]; if (!t.comm) { start(&t); } } } void mtt::TrackerManager::stop() { std::lock_guard<std::mutex> guard(trackersMutex); stopAll(); announceCallback = nullptr; } void mtt::TrackerManager::addTracker(std::string addr) { std::lock_guard<std::mutex> guard(trackersMutex); TrackerInfo info; info.uri = Uri::Parse(addr); info.fullAddress = addr; if (!info.uri.port.empty()) { auto i = findTrackerInfo(info.uri.host); if (i && i->uri.port == info.uri.port) { if ((i->uri.protocol == "http" || info.uri.protocol == "http") && (i->uri.protocol == "udp" || info.uri.protocol == "udp") && !i->comm) { i->uri.protocol = "udp"; i->httpFallback = true; } } else trackers.push_back(info); } else if(info.uri.protocol == "https") trackers.push_back(info); } void mtt::TrackerManager::addTrackers(const std::vector<std::string>& trackers) { for (auto& t : trackers) { addTracker(t); } } void mtt::TrackerManager::removeTrackers() { std::lock_guard<std::mutex> guard(trackersMutex); trackers.clear(); } std::shared_ptr<mtt::Tracker> mtt::TrackerManager::getTrackerByAddr(const std::string& addr) { std::lock_guard<std::mutex> guard(trackersMutex); for (auto& tracker : trackers) { if (tracker.fullAddress == addr) return tracker.comm; } return nullptr; } std::vector<std::pair<std::string, std::shared_ptr<mtt::Tracker>>> mtt::TrackerManager::getTrackers() { std::vector<std::pair<std::string, std::shared_ptr<mtt::Tracker>>> out; std::lock_guard<std::mutex> guard(trackersMutex); for (auto& t : trackers) { out.push_back({ t.fullAddress, t.comm }); } return out; } uint32_t mtt::TrackerManager::getTrackersCount() { return (uint32_t)trackers.size(); } void mtt::TrackerManager::onAnnounce(AnnounceResponse& resp, Tracker* t) { torrent->service.io.post([this, resp, t]() { std::lock_guard<std::mutex> guard(trackersMutex); if (auto trackerInfo = findTrackerInfo(t)) { trackerInfo->retryCount = 0; trackerInfo->timer->schedule(resp.interval); trackerInfo->comm->info.nextAnnounce = (uint32_t)time(0) + resp.interval; } if (announceCallback) announceCallback(Status::Success, &resp, t); startNext(); }); } void mtt::TrackerManager::onTrackerFail(Tracker* t) { std::lock_guard<std::mutex> guard(trackersMutex); if (auto trackerInfo = findTrackerInfo(t)) { if (trackerInfo->httpFallback && !trackerInfo->httpFallbackUsed && trackerInfo->uri.protocol == "udp") { trackerInfo->httpFallbackUsed = true; trackerInfo->uri.protocol = "http"; torrent->service.io.post([this, trackerInfo]() { trackerInfo->comm.reset(); std::lock_guard<std::mutex> guard(trackersMutex); start(trackerInfo); }); } else { if (trackerInfo->httpFallback && trackerInfo->httpFallbackUsed && trackerInfo->uri.protocol == "http") { trackerInfo->uri.protocol = "udp"; start(trackerInfo); } else { trackerInfo->retryCount++; uint32_t nextRetry = 30 * trackerInfo->retryCount; trackerInfo->timer->schedule(nextRetry); trackerInfo->comm->info.nextAnnounce = (uint32_t)time(0) + nextRetry; } startNext(); } if(announceCallback) announceCallback(Status::E_Unknown, nullptr, t); } } void mtt::TrackerManager::start(TrackerInfo* tracker) { if (tracker->uri.protocol == "udp") tracker->comm = std::make_shared<UdpTrackerComm>(); else if (tracker->uri.protocol == "http") tracker->comm = std::make_shared<HttpTrackerComm>(); #ifdef MTT_WITH_SSL else if (tracker->uri.protocol == "https") tracker->comm = std::make_shared<HttpsTrackerComm>(); #endif else return; tracker->comm->onFail = std::bind(&TrackerManager::onTrackerFail, this, tracker->comm.get()); tracker->comm->onAnnounceResult = std::bind(&TrackerManager::onAnnounce, this, std::placeholders::_1, tracker->comm.get()); tracker->comm->init(tracker->uri.host, tracker->uri.port, tracker->uri.path, torrent); tracker->timer = ScheduledTimer::create(torrent->service.io, std::bind(&Tracker::announce, tracker->comm.get())); tracker->retryCount = 0; tracker->comm->announce(); } void mtt::TrackerManager::startNext() { for (auto& tracker : trackers) { if (!tracker.comm) start(&tracker); } } void mtt::TrackerManager::stopAll() { for (auto& tracker : trackers) { if(tracker.comm) tracker.comm->deinit(); tracker.comm = nullptr; if(tracker.timer) tracker.timer->disable(); tracker.timer = nullptr; tracker.retryCount = 0; } } mtt::TrackerManager::TrackerInfo* mtt::TrackerManager::findTrackerInfo(Tracker* t) { for (auto& tracker : trackers) { if (tracker.comm.get() == t) return &tracker; } return nullptr; } mtt::TrackerManager::TrackerInfo* mtt::TrackerManager::findTrackerInfo(std::string host) { for (auto& tracker : trackers) { if (tracker.uri.host == host) return &tracker; } return nullptr; }
initialize http tracker fallback in separate thread to avoid deadlocks in udp deinitialization
initialize http tracker fallback in separate thread to avoid deadlocks in udp deinitialization
C++
mit
RazielXT/mtTorrent,RazielXT/mtTorrent,RazielXT/mtTorrent,RazielXT/mtTorrent
e52a36a7114d9ed8203775e73152f03fddc94a30
cmd/main.cc
cmd/main.cc
#include "./flags.h" #include <fstlib.h> #include <fstream> #include <sstream> using namespace std; template <typename output_t> struct traints { static output_t convert(uint32_t n) {} static output_t convert(const string &s) {} }; template <> struct traints<uint32_t> { static uint32_t convert(uint32_t n) { return n; } static uint32_t convert(const string &s) { return stoi(s); } }; template <> struct traints<string> { static string convert(uint32_t n) { return to_string(n); } static string convert(const string &s) { return s; } }; vector<string> split(const string &input, char delimiter) { istringstream stream(input); string field; vector<string> result; while (getline(stream, field, delimiter)) { result.push_back(field); } return result; } template <typename output_t> vector<pair<string, output_t>> load_input(istream &fin, char delimiter) { vector<pair<string, output_t>> input; string line; while (getline(fin, line)) { auto fields = split(line, delimiter); if (fields.size() > 1) { input.emplace_back(fields[0], traints<output_t>::convert(fields[1])); } else { input.emplace_back(line, traints<output_t>::convert(static_cast<uint32_t>(input.size()))); } } sort(input.begin(), input.end(), [](const auto &a, const auto &b) { return a.first < b.first; }); return input; } template <typename output_t> vector<pair<string, output_t>> load_input(istream &fin, string_view format) { vector<pair<string, output_t>> input; if (format == "csv") { input = load_input<output_t>(fin, ','); } else if (format == "tsv") { input = load_input<output_t>(fin, '\t'); } else { throw runtime_error("invalid format..."); } return input; } vector<string> load_input(istream &fin) { vector<string> input; string line; while (getline(fin, line)) { input.emplace_back(line); } sort(input.begin(), input.end()); return input; } vector<char> load_byte_code(istream &is) { is.seekg(0, ios_base::end); auto size = (unsigned int)is.tellg(); is.seekg(0, ios_base::beg); vector<char> byte_code(size); is.read(byte_code.data(), size); return byte_code; } void show_error_message(fst::Result result, size_t line) { string error_message; switch (result) { case fst::Result::EmptyKey: error_message = "empty key"; break; case fst::Result::UnsortedKey: error_message = "unsorted key"; break; case fst::Result::DuplicateKey: error_message = "duplicate key"; break; default: error_message = "Unknown"; break; } cerr << "line " << line << ": " << error_message << endl; } template <typename output_t> void regression_test(const vector<pair<string, output_t>> &input, const string &byte_code) { fst::Matcher<output_t> matcher(byte_code.data(), byte_code.size()); if (matcher) { for (const auto &[word, expected] : input) { auto actual = fst::OutputTraits<output_t>::initial_value(); auto ret = matcher.exact_match_search(word.data(), word.size(), actual); if (!ret) { cerr << "couldn't find '" << word << "'" << endl; } else { if (expected != actual) { cerr << "word: " << word << endl; cerr << "expected value: " << expected << endl; cerr << "actual value: " << actual << endl; } } } } else { cerr << "someting is wrong in byte_code..." << endl; } } void regression_test(const vector<string> &input, const string &byte_code) { fst::Matcher<uint32_t> matcher(byte_code.data(), byte_code.size()); if (matcher) { uint32_t expected = 0; for (const auto &word : input) { uint32_t actual = 0; auto ret = matcher.exact_match_search(word.data(), word.size(), actual); if (!ret) { cerr << "couldn't find '" << word << "'" << endl; } else { if (expected != actual) { cerr << "word: " << word << endl; cerr << "expected value: " << expected << endl; cerr << "actual value: " << actual << endl; } } expected++; } } else { cerr << "someting is wrong in byte_code..." << endl; } } template <typename output_t, typename T, typename U, typename V> void build(istream &is, T format, U fn1, V fn2) { fst::Result result; size_t line; if (format) { auto input = load_input<output_t>(is, *format); tie(result, line) = fn1(input); } else { auto input = load_input(is); tie(result, line) = fn2(input); } if (result != fst::Result::Success) { show_error_message(result, line); } } template <typename output_t, typename T, typename U> void search_word(const T &byte_code, string_view cmd, bool verbose, const U& matcher, string_view word) { bool ret; if (cmd == "search") { output_t output; ret = matcher.exact_match_search(word.data(), word.size(), output); if (ret) { cout << output << endl; } } else { // "prefix" ret = matcher.common_prefix_search( word.data(), word.size(), [&](size_t len, const auto &output) { cout << word.substr(0, len) << ": " << output << endl; }); } if (!ret) { cout << "not found..." << endl; } } template <typename output_t, typename T> void search(const T &byte_code, string_view cmd, bool verbose, string_view word) { fst::Matcher<output_t> matcher(byte_code.data(), byte_code.size()); matcher.set_trace(verbose); if (matcher) { search_word<output_t>(byte_code, cmd, verbose, matcher, word); } else { cout << "invalid file..." << endl; } } template <typename output_t, typename T> void search(const T &byte_code, string_view cmd, bool verbose) { fst::Matcher<output_t> matcher(byte_code.data(), byte_code.size()); matcher.set_trace(verbose); if (matcher) { string word; while (getline(cin, word)) { search_word<output_t>(byte_code, cmd, verbose, matcher, word); } } else { cout << "invalid file..." << endl; } } void usage() { cout << R"(usage: fst [options] <command> [<args>] commends: compile source FST - make fst byte code decompile FST - decompile fst byte code search FST [word] - exact match search prefix FST [word] - common prefix search dot source - convert to dot format options: -f: source file format ('csv' or 'tsv') -t: output type ('uint32_t' or 'string') -v: verbose output note: On macOS, you can show FST graph with `./fst dot source | dot -T png | open -a Preview.app -f`. )"; } int error(int code) { usage(); return code; } int main(int argc, char **argv) { const flags::args args(argc, argv); if (args.positional().size() < 2) { return error(1); } auto format = args.get<string>("f"); auto verbose = args.get<bool>("v", false); auto output_type = args.get<string>("t"); auto cmd = args.positional().at(0); const string in_path{args.positional().at(1)}; try { if (cmd == "compile") { if (args.positional().size() < 3) { return error(1); } const string out_path{args.positional().at(2)}; ifstream fin(in_path); if (!fin) { return error(1); } ofstream fout(out_path, ios_base::binary); if (!fout) { return error(1); } if (*output_type == "string") { build<string>( fin, format, [&](const auto &input) { return fst::compile<string>(input, fout, verbose); }, [&](const auto &input) { return fst::compile(input, fout, verbose); }); } else { build<uint32_t>( fin, format, [&](const auto &input) { return fst::compile<uint32_t>(input, fout, verbose); }, [&](const auto &input) { return fst::compile(input, fout, verbose); }); } } else if (cmd == "dump") { ifstream fin(in_path); if (!fin) { return error(1); } if (*output_type == "string") { build<string>( fin, format, [&](const auto &input) { return fst::dump<string>(input, cout, verbose); }, [&](const auto &input) { return fst::dump(input, cout, verbose); }); } else { build<uint32_t>( fin, format, [&](const auto &input) { return fst::dump<uint32_t>(input, cout, verbose); }, [&](const auto &input) { return fst::dump(input, cout, verbose); }); } } else if (cmd == "dot") { ifstream fin(in_path); if (!fin) { return error(1); } if (*output_type == "string") { build<string>( fin, format, [&](const auto &input) { return fst::dot<string>(input, cout); }, [&](const auto &input) { return fst::dot(input, cout); }); } else { build<uint32_t>( fin, format, [&](const auto &input) { return fst::dot<uint32_t>(input, cout); }, [&](const auto &input) { return fst::dot(input, cout); }); } } else if (cmd == "search" || cmd == "prefix") { ifstream fin(in_path, ios_base::binary); if (!fin) { return error(1); } auto byte_code = load_byte_code(fin); auto type = fst::get_output_type(byte_code.data(), byte_code.size()); if (args.positional().size() > 2) { auto word = args.positional().at(2); if (type == fst::OutputType::uint32_t) { search<uint32_t>(byte_code, cmd, verbose, word); } else if (type == fst::OutputType::string) { search<string>(byte_code, cmd, verbose, word); } } else { if (type == fst::OutputType::uint32_t) { search<uint32_t>(byte_code, cmd, verbose); } else if (type == fst::OutputType::string) { search<string>(byte_code, cmd, verbose); } } } else if (cmd == "test") { ifstream fin(in_path); if (!fin) { return error(1); } stringstream ss; if (*output_type == "string") { build<string>( fin, format, [&](const auto &input) { auto ret = fst::compile<string>(input, ss, verbose); if (ret.first == fst::Result::Success) { regression_test(input, ss.str()); } return ret; }, [&](const auto &input) { auto ret = fst::compile(input, ss, verbose); if (ret.first == fst::Result::Success) { regression_test(input, ss.str()); } return ret; }); } else { build<uint32_t>( fin, format, [&](const auto &input) { auto ret = fst::compile<uint32_t>(input, ss, verbose); if (ret.first == fst::Result::Success) { regression_test(input, ss.str()); } return ret; }, [&](const auto &input) { auto ret = fst::compile(input, ss, verbose); if (ret.first == fst::Result::Success) { regression_test(input, ss.str()); } return ret; }); } } else { return error(1); } } catch (const invalid_argument &) { cerr << "invalid format..." << endl; return 1; } catch (const runtime_error &err) { cerr << err.what() << endl; } return 0; }
#include "./flags.h" #include <fstlib.h> #include <fstream> #include <sstream> using namespace std; template <typename output_t> struct traints { static output_t convert(uint32_t n) {} static output_t convert(const string &s) {} }; template <> struct traints<uint32_t> { static uint32_t convert(uint32_t n) { return n; } static uint32_t convert(const string &s) { return stoi(s); } }; template <> struct traints<string> { static string convert(uint32_t n) { return to_string(n); } static string convert(const string &s) { return s; } }; vector<string> split(const string &input, char delimiter) { istringstream stream(input); string field; vector<string> result; while (getline(stream, field, delimiter)) { result.push_back(field); } return result; } template <typename output_t> vector<pair<string, output_t>> load_input(istream &fin, char delimiter) { vector<pair<string, output_t>> input; string line; while (getline(fin, line)) { auto fields = split(line, delimiter); if (fields.size() > 1) { input.emplace_back(fields[0], traints<output_t>::convert(fields[1])); } else { input.emplace_back(line, traints<output_t>::convert( static_cast<uint32_t>(input.size()))); } } sort(input.begin(), input.end(), [](const auto &a, const auto &b) { return a.first < b.first; }); return input; } template <typename output_t> vector<pair<string, output_t>> load_input(istream &fin, string_view format) { vector<pair<string, output_t>> input; if (format == "csv") { input = load_input<output_t>(fin, ','); } else if (format == "tsv") { input = load_input<output_t>(fin, '\t'); } else { throw runtime_error("invalid format..."); } return input; } vector<string> load_input(istream &fin) { vector<string> input; string line; while (getline(fin, line)) { input.emplace_back(line); } sort(input.begin(), input.end()); return input; } vector<char> load_byte_code(istream &is) { is.seekg(0, ios_base::end); auto size = (unsigned int)is.tellg(); is.seekg(0, ios_base::beg); vector<char> byte_code(size); is.read(byte_code.data(), size); return byte_code; } void show_error_message(fst::Result result, size_t line) { string error_message; switch (result) { case fst::Result::EmptyKey: error_message = "empty key"; break; case fst::Result::UnsortedKey: error_message = "unsorted key"; break; case fst::Result::DuplicateKey: error_message = "duplicate key"; break; default: error_message = "Unknown"; break; } cerr << "line " << line << ": " << error_message << endl; } template <typename output_t> void regression_test(const vector<pair<string, output_t>> &input, const string &byte_code) { fst::Matcher<output_t> matcher(byte_code.data(), byte_code.size()); if (matcher) { for (const auto &[word, expected] : input) { auto actual = fst::OutputTraits<output_t>::initial_value(); auto ret = matcher.exact_match_search(word.data(), word.size(), actual); if (!ret) { cerr << "couldn't find '" << word << "'" << endl; } else { if (expected != actual) { cerr << "word: " << word << endl; cerr << "expected value: " << expected << endl; cerr << "actual value: " << actual << endl; } } } } else { cerr << "someting is wrong in byte_code..." << endl; } } void regression_test(const vector<string> &input, const string &byte_code) { fst::Matcher<uint32_t> matcher(byte_code.data(), byte_code.size()); if (matcher) { uint32_t expected = 0; for (const auto &word : input) { uint32_t actual = 0; auto ret = matcher.exact_match_search(word.data(), word.size(), actual); if (!ret) { cerr << "couldn't find '" << word << "'" << endl; } else { if (expected != actual) { cerr << "word: " << word << endl; cerr << "expected value: " << expected << endl; cerr << "actual value: " << actual << endl; } } expected++; } } else { cerr << "someting is wrong in byte_code..." << endl; } } template <typename output_t, typename T, typename U, typename V> int build(istream &is, T format, U fn1, V fn2) { fst::Result result; size_t line; if (format) { auto input = load_input<output_t>(is, *format); tie(result, line) = fn1(input); } else { auto input = load_input(is); tie(result, line) = fn2(input); } if (result == fst::Result::Success) { return 0; } show_error_message(result, line); return 1; } template <typename output_t, typename T, typename U> void search_word(const T &byte_code, string_view cmd, bool verbose, const U &matcher, string_view word) { bool ret; if (cmd == "search") { output_t output; ret = matcher.exact_match_search(word.data(), word.size(), output); if (ret) { cout << output << endl; } } else { // "prefix" ret = matcher.common_prefix_search( word.data(), word.size(), [&](size_t len, const auto &output) { cout << word.substr(0, len) << ": " << output << endl; }); } if (!ret) { cout << "not found..." << endl; } } template <typename output_t, typename T> void search(const T &byte_code, string_view cmd, bool verbose, string_view word) { fst::Matcher<output_t> matcher(byte_code.data(), byte_code.size()); matcher.set_trace(verbose); if (matcher) { search_word<output_t>(byte_code, cmd, verbose, matcher, word); } else { cout << "invalid file..." << endl; } } template <typename output_t, typename T> void search(const T &byte_code, string_view cmd, bool verbose) { fst::Matcher<output_t> matcher(byte_code.data(), byte_code.size()); matcher.set_trace(verbose); if (matcher) { string word; while (getline(cin, word)) { search_word<output_t>(byte_code, cmd, verbose, matcher, word); } } else { cout << "invalid file..." << endl; } } void usage() { cout << R"(usage: fst [options] <command> [<args>] commends: compile source FST - make fst byte code decompile FST - decompile fst byte code search FST [word] - exact match search prefix FST [word] - common prefix search dot source - convert to dot format options: -f: source file format ('csv' or 'tsv') -t: output type ('uint32_t' or 'string') -v: verbose output note: On macOS, you can show FST graph with `./fst dot source | dot -T png | open -a Preview.app -f`. )"; } int error(int code) { usage(); return code; } int main(int argc, char **argv) { const flags::args args(argc, argv); if (args.positional().size() < 2) { return error(1); } auto format = args.get<string>("f"); auto verbose = args.get<bool>("v", false); auto output_type = args.get<string>("t"); auto cmd = args.positional().at(0); const string in_path{args.positional().at(1)}; try { if (cmd == "compile") { if (args.positional().size() < 3) { return error(1); } const string out_path{args.positional().at(2)}; ifstream fin(in_path); if (!fin) { return error(1); } ofstream fout(out_path, ios_base::binary); if (!fout) { return error(1); } if (*output_type == "string") { return build<string>( fin, format, [&](const auto &input) { return fst::compile<string>(input, fout, verbose); }, [&](const auto &input) { return fst::compile(input, fout, verbose); }); } else { return build<uint32_t>( fin, format, [&](const auto &input) { return fst::compile<uint32_t>(input, fout, verbose); }, [&](const auto &input) { return fst::compile(input, fout, verbose); }); } } else if (cmd == "dump") { ifstream fin(in_path); if (!fin) { return error(1); } if (*output_type == "string") { return build<string>( fin, format, [&](const auto &input) { return fst::dump<string>(input, cout, verbose); }, [&](const auto &input) { return fst::dump(input, cout, verbose); }); } else { return build<uint32_t>( fin, format, [&](const auto &input) { return fst::dump<uint32_t>(input, cout, verbose); }, [&](const auto &input) { return fst::dump(input, cout, verbose); }); } } else if (cmd == "dot") { ifstream fin(in_path); if (!fin) { return error(1); } if (*output_type == "string") { return build<string>( fin, format, [&](const auto &input) { return fst::dot<string>(input, cout); }, [&](const auto &input) { return fst::dot(input, cout); }); } else { return build<uint32_t>( fin, format, [&](const auto &input) { return fst::dot<uint32_t>(input, cout); }, [&](const auto &input) { return fst::dot(input, cout); }); } } else if (cmd == "search" || cmd == "prefix") { ifstream fin(in_path, ios_base::binary); if (!fin) { return error(1); } auto byte_code = load_byte_code(fin); auto type = fst::get_output_type(byte_code.data(), byte_code.size()); if (args.positional().size() > 2) { auto word = args.positional().at(2); if (type == fst::OutputType::uint32_t) { search<uint32_t>(byte_code, cmd, verbose, word); } else if (type == fst::OutputType::string) { search<string>(byte_code, cmd, verbose, word); } } else { if (type == fst::OutputType::uint32_t) { search<uint32_t>(byte_code, cmd, verbose); } else if (type == fst::OutputType::string) { search<string>(byte_code, cmd, verbose); } } } else if (cmd == "test") { ifstream fin(in_path); if (!fin) { return error(1); } stringstream ss; if (*output_type == "string") { return build<string>( fin, format, [&](const auto &input) { auto ret = fst::compile<string>(input, ss, verbose); if (ret.first == fst::Result::Success) { regression_test(input, ss.str()); } return ret; }, [&](const auto &input) { auto ret = fst::compile(input, ss, verbose); if (ret.first == fst::Result::Success) { regression_test(input, ss.str()); } return ret; }); } else { return build<uint32_t>( fin, format, [&](const auto &input) { auto ret = fst::compile<uint32_t>(input, ss, verbose); if (ret.first == fst::Result::Success) { regression_test(input, ss.str()); } return ret; }, [&](const auto &input) { auto ret = fst::compile(input, ss, verbose); if (ret.first == fst::Result::Success) { regression_test(input, ss.str()); } return ret; }); } } else { return error(1); } } catch (const invalid_argument &) { cerr << "invalid format..." << endl; return 1; } catch (const runtime_error &err) { cerr << err.what() << endl; } return 0; }
Handle exit code properly in cli
Handle exit code properly in cli
C++
mit
yhirose/cpp-fstlib,yhirose/cpp-fstlib,yhirose/cpp-fstlib,yhirose/cpp-fstlib,yhirose/cpp-fstlib,yhirose/cpp-fstlib
0797fa25dbd1ea4903a3d4139db4ba9c7a5d6f8e
moveit_planners/chomp/chomp_motion_planner/src/chomp_planner.cpp
moveit_planners/chomp/chomp_motion_planner/src/chomp_planner.cpp
/********************************************************************* * Software License Agreement (BSD License) * * Copyright (c) 2012, Willow Garage, Inc. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above * copyright notice, this list of conditions and the following * disclaimer in the documentation and/or other materials provided * with the distribution. * * Neither the name of Willow Garage 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. *********************************************************************/ /* Author: E. Gil Jones */ #include <ros/ros.h> #include <chomp_motion_planner/chomp_planner.h> #include <chomp_motion_planner/chomp_trajectory.h> #include <chomp_motion_planner/chomp_optimizer.h> #include <moveit/robot_state/conversions.h> #include <moveit_msgs/MotionPlanRequest.h> namespace chomp { ChompPlanner::ChompPlanner() { } bool ChompPlanner::solve(const planning_scene::PlanningSceneConstPtr& planning_scene, const moveit_msgs::MotionPlanRequest& req, const chomp::ChompParameters& params, moveit_msgs::MotionPlanDetailedResponse& res) const { if (!planning_scene) { ROS_ERROR_STREAM("No planning scene initialized."); res.error_code.val = moveit_msgs::MoveItErrorCodes::FAILURE; return false; } if (req.start_state.joint_state.position.empty()) { ROS_ERROR_STREAM("Starting state is empty"); res.error_code.val = moveit_msgs::MoveItErrorCodes::INVALID_ROBOT_STATE; return false; } if (not planning_scene->getRobotModel()->satisfiesPositionBounds(req.start_state.joint_state.position.data())) { ROS_ERROR_STREAM("Start state violates joint limits"); res.error_code.val = moveit_msgs::MoveItErrorCodes::INVALID_ROBOT_STATE; return false; } ros::WallTime start_time = ros::WallTime::now(); ChompTrajectory trajectory(planning_scene->getRobotModel(), 3.0, .03, req.group_name); jointStateToArray(planning_scene->getRobotModel(), req.start_state.joint_state, req.group_name, trajectory.getTrajectoryPoint(0)); if (req.goal_constraints[0].joint_constraints.empty()) { ROS_ERROR_STREAM("CHOMP only supports joint-space goals"); res.error_code.val = moveit_msgs::MoveItErrorCodes::INVALID_GOAL_CONSTRAINTS; return false; } int goal_index = trajectory.getNumPoints() - 1; trajectory.getTrajectoryPoint(goal_index) = trajectory.getTrajectoryPoint(0); sensor_msgs::JointState js; for (unsigned int i = 0; i < req.goal_constraints[0].joint_constraints.size(); i++) { js.name.push_back(req.goal_constraints[0].joint_constraints[i].joint_name); js.position.push_back(req.goal_constraints[0].joint_constraints[i].position); ROS_INFO_STREAM("Setting joint " << req.goal_constraints[0].joint_constraints[i].joint_name << " to position " << req.goal_constraints[0].joint_constraints[i].position); } jointStateToArray(planning_scene->getRobotModel(), js, req.group_name, trajectory.getTrajectoryPoint(goal_index)); const moveit::core::JointModelGroup* model_group = planning_scene->getRobotModel()->getJointModelGroup(req.group_name); // fix the goal to move the shortest angular distance for wrap-around joints: for (size_t i = 0; i < model_group->getActiveJointModels().size(); i++) { const moveit::core::JointModel* model = model_group->getActiveJointModels()[i]; const moveit::core::RevoluteJointModel* revolute_joint = dynamic_cast<const moveit::core::RevoluteJointModel*>(model); if (revolute_joint != NULL) { if (revolute_joint->isContinuous()) { double start = (trajectory)(0, i); double end = (trajectory)(goal_index, i); ROS_INFO_STREAM("Start is " << start << " end " << end << " short " << shortestAngularDistance(start, end)); (trajectory)(goal_index, i) = start + shortestAngularDistance(start, end); } } } const Eigen::MatrixXd goal_state = trajectory.getTrajectoryPoint(goal_index); if (not planning_scene->getRobotModel()->satisfiesPositionBounds(goal_state.data())) { ROS_ERROR_STREAM("Goal state violates joint limits"); res.error_code.val = moveit_msgs::MoveItErrorCodes::INVALID_ROBOT_STATE; return false; } // fill in an initial quintic spline trajectory trajectory.fillInMinJerk(); // optimize! moveit::core::RobotState start_state(planning_scene->getCurrentState()); moveit::core::robotStateMsgToRobotState(req.start_state, start_state); start_state.update(); ros::WallTime create_time = ros::WallTime::now(); ChompOptimizer optimizer(&trajectory, planning_scene, req.group_name, &params, start_state); if (!optimizer.isInitialized()) { ROS_WARN_STREAM("Could not initialize optimizer"); res.error_code.val = moveit_msgs::MoveItErrorCodes::PLANNING_FAILED; return false; } ROS_DEBUG("Optimization took %f sec to create", (ros::WallTime::now() - create_time).toSec()); optimizer.optimize(); ROS_INFO("Optimization actually took %f sec to run", (ros::WallTime::now() - create_time).toSec()); create_time = ros::WallTime::now(); // assume that the trajectory is now optimized, fill in the output structure: ROS_DEBUG("Output trajectory has %d joints", trajectory.getNumJoints()); res.trajectory.resize(1); for (size_t i = 0; i < model_group->getActiveJointModels().size(); i++) { res.trajectory[0].joint_trajectory.joint_names.push_back(model_group->getActiveJointModels()[i]->getName()); } res.trajectory[0].joint_trajectory.header = req.start_state.joint_state.header; // @TODO this is probably a hack // fill in the entire trajectory res.trajectory[0].joint_trajectory.points.resize(trajectory.getNumPoints()); for (int i = 0; i < trajectory.getNumPoints(); i++) { res.trajectory[0].joint_trajectory.points[i].positions.resize(trajectory.getNumJoints()); for (size_t j = 0; j < res.trajectory[0].joint_trajectory.points[i].positions.size(); j++) { res.trajectory[0].joint_trajectory.points[i].positions[j] = trajectory.getTrajectoryPoint(i)(j); if (i == trajectory.getNumPoints() - 1) { ROS_INFO_STREAM("Joint " << j << " " << res.trajectory[0].joint_trajectory.points[i].positions[j]); } } // Setting invalid timestamps. // Further filtering is required to set valid timestamps accounting for velocity and acceleration constraints. res.trajectory[0].joint_trajectory.points[i].time_from_start = ros::Duration(0.0); } ROS_DEBUG("Bottom took %f sec to create", (ros::WallTime::now() - create_time).toSec()); ROS_DEBUG("Serviced planning request in %f wall-seconds, trajectory duration is %f", (ros::WallTime::now() - start_time).toSec(), res.trajectory[0].joint_trajectory.points[goal_index].time_from_start.toSec()); res.error_code.val = moveit_msgs::MoveItErrorCodes::SUCCESS; res.processing_time.push_back((ros::WallTime::now() - start_time).toSec()); // report planning failure if path has collisions if (not optimizer.isCollisionFree()) { res.error_code.val = moveit_msgs::MoveItErrorCodes::INVALID_MOTION_PLAN; return false; } // check that final state is within goal tolerances kinematic_constraints::JointConstraint jc(planning_scene->getRobotModel()); robot_state::RobotState last_state(planning_scene->getRobotModel()); last_state.setVariablePositions(res.trajectory[0].joint_trajectory.points.back().positions.data()); last_state.printStatePositions(std::cout); ROS_ERROR_STREAM("Goal is " << goal_state); bool constraints_are_ok = true; for (const moveit_msgs::JointConstraint& constraint : req.goal_constraints[0].joint_constraints) { ROS_ERROR_STREAM("Validating constraint for " << constraint.joint_name << "..."); constraints_are_ok = constraints_are_ok and jc.configure(constraint); constraints_are_ok = constraints_are_ok and jc.decide(last_state).satisfied; if (not constraints_are_ok) { res.error_code.val = moveit_msgs::MoveItErrorCodes::GOAL_CONSTRAINTS_VIOLATED; return false; } } return true; } }
/********************************************************************* * Software License Agreement (BSD License) * * Copyright (c) 2012, Willow Garage, Inc. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above * copyright notice, this list of conditions and the following * disclaimer in the documentation and/or other materials provided * with the distribution. * * Neither the name of Willow Garage 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. *********************************************************************/ /* Author: E. Gil Jones */ #include <ros/ros.h> #include <chomp_motion_planner/chomp_planner.h> #include <chomp_motion_planner/chomp_trajectory.h> #include <chomp_motion_planner/chomp_optimizer.h> #include <moveit/robot_state/conversions.h> #include <moveit_msgs/MotionPlanRequest.h> namespace chomp { ChompPlanner::ChompPlanner() { } bool ChompPlanner::solve(const planning_scene::PlanningSceneConstPtr& planning_scene, const moveit_msgs::MotionPlanRequest& req, const chomp::ChompParameters& params, moveit_msgs::MotionPlanDetailedResponse& res) const { if (!planning_scene) { ROS_ERROR_STREAM("No planning scene initialized."); res.error_code.val = moveit_msgs::MoveItErrorCodes::FAILURE; return false; } if (req.start_state.joint_state.position.empty()) { ROS_ERROR_STREAM("Starting state is empty"); res.error_code.val = moveit_msgs::MoveItErrorCodes::INVALID_ROBOT_STATE; return false; } if (not planning_scene->getRobotModel()->satisfiesPositionBounds(req.start_state.joint_state.position.data())) { ROS_ERROR_STREAM("Start state violates joint limits"); res.error_code.val = moveit_msgs::MoveItErrorCodes::INVALID_ROBOT_STATE; return false; } ros::WallTime start_time = ros::WallTime::now(); ChompTrajectory trajectory(planning_scene->getRobotModel(), 3.0, .03, req.group_name); jointStateToArray(planning_scene->getRobotModel(), req.start_state.joint_state, req.group_name, trajectory.getTrajectoryPoint(0)); if (req.goal_constraints.empty()) { ROS_ERROR_STREAM("No goal constraints specified!"); res.error_code.val = moveit_msgs::MoveItErrorCodes::INVALID_GOAL_CONSTRAINTS; return false; } if (req.goal_constraints[0].joint_constraints.empty()) { ROS_ERROR_STREAM("CHOMP only supports joint-space goals"); res.error_code.val = moveit_msgs::MoveItErrorCodes::INVALID_GOAL_CONSTRAINTS; return false; } int goal_index = trajectory.getNumPoints() - 1; trajectory.getTrajectoryPoint(goal_index) = trajectory.getTrajectoryPoint(0); sensor_msgs::JointState js; for (unsigned int i = 0; i < req.goal_constraints[0].joint_constraints.size(); i++) { js.name.push_back(req.goal_constraints[0].joint_constraints[i].joint_name); js.position.push_back(req.goal_constraints[0].joint_constraints[i].position); ROS_INFO_STREAM("Setting joint " << req.goal_constraints[0].joint_constraints[i].joint_name << " to position " << req.goal_constraints[0].joint_constraints[i].position); } jointStateToArray(planning_scene->getRobotModel(), js, req.group_name, trajectory.getTrajectoryPoint(goal_index)); const moveit::core::JointModelGroup* model_group = planning_scene->getRobotModel()->getJointModelGroup(req.group_name); // fix the goal to move the shortest angular distance for wrap-around joints: for (size_t i = 0; i < model_group->getActiveJointModels().size(); i++) { const moveit::core::JointModel* model = model_group->getActiveJointModels()[i]; const moveit::core::RevoluteJointModel* revolute_joint = dynamic_cast<const moveit::core::RevoluteJointModel*>(model); if (revolute_joint != NULL) { if (revolute_joint->isContinuous()) { double start = (trajectory)(0, i); double end = (trajectory)(goal_index, i); ROS_INFO_STREAM("Start is " << start << " end " << end << " short " << shortestAngularDistance(start, end)); (trajectory)(goal_index, i) = start + shortestAngularDistance(start, end); } } } const Eigen::MatrixXd goal_state = trajectory.getTrajectoryPoint(goal_index); if (not planning_scene->getRobotModel()->satisfiesPositionBounds(goal_state.data())) { ROS_ERROR_STREAM("Goal state violates joint limits"); res.error_code.val = moveit_msgs::MoveItErrorCodes::INVALID_ROBOT_STATE; return false; } // fill in an initial quintic spline trajectory trajectory.fillInMinJerk(); // optimize! moveit::core::RobotState start_state(planning_scene->getCurrentState()); moveit::core::robotStateMsgToRobotState(req.start_state, start_state); start_state.update(); ros::WallTime create_time = ros::WallTime::now(); ChompOptimizer optimizer(&trajectory, planning_scene, req.group_name, &params, start_state); if (!optimizer.isInitialized()) { ROS_WARN_STREAM("Could not initialize optimizer"); res.error_code.val = moveit_msgs::MoveItErrorCodes::PLANNING_FAILED; return false; } ROS_DEBUG("Optimization took %f sec to create", (ros::WallTime::now() - create_time).toSec()); optimizer.optimize(); ROS_INFO("Optimization actually took %f sec to run", (ros::WallTime::now() - create_time).toSec()); create_time = ros::WallTime::now(); // assume that the trajectory is now optimized, fill in the output structure: ROS_DEBUG("Output trajectory has %d joints", trajectory.getNumJoints()); res.trajectory.resize(1); for (size_t i = 0; i < model_group->getActiveJointModels().size(); i++) { res.trajectory[0].joint_trajectory.joint_names.push_back(model_group->getActiveJointModels()[i]->getName()); } res.trajectory[0].joint_trajectory.header = req.start_state.joint_state.header; // @TODO this is probably a hack // fill in the entire trajectory res.trajectory[0].joint_trajectory.points.resize(trajectory.getNumPoints()); for (int i = 0; i < trajectory.getNumPoints(); i++) { res.trajectory[0].joint_trajectory.points[i].positions.resize(trajectory.getNumJoints()); for (size_t j = 0; j < res.trajectory[0].joint_trajectory.points[i].positions.size(); j++) { res.trajectory[0].joint_trajectory.points[i].positions[j] = trajectory.getTrajectoryPoint(i)(j); if (i == trajectory.getNumPoints() - 1) { ROS_INFO_STREAM("Joint " << j << " " << res.trajectory[0].joint_trajectory.points[i].positions[j]); } } // Setting invalid timestamps. // Further filtering is required to set valid timestamps accounting for velocity and acceleration constraints. res.trajectory[0].joint_trajectory.points[i].time_from_start = ros::Duration(0.0); } ROS_DEBUG("Bottom took %f sec to create", (ros::WallTime::now() - create_time).toSec()); ROS_DEBUG("Serviced planning request in %f wall-seconds, trajectory duration is %f", (ros::WallTime::now() - start_time).toSec(), res.trajectory[0].joint_trajectory.points[goal_index].time_from_start.toSec()); res.error_code.val = moveit_msgs::MoveItErrorCodes::SUCCESS; res.processing_time.push_back((ros::WallTime::now() - start_time).toSec()); // report planning failure if path has collisions if (not optimizer.isCollisionFree()) { res.error_code.val = moveit_msgs::MoveItErrorCodes::INVALID_MOTION_PLAN; return false; } // check that final state is within goal tolerances kinematic_constraints::JointConstraint jc(planning_scene->getRobotModel()); robot_state::RobotState last_state(planning_scene->getRobotModel()); last_state.setVariablePositions(res.trajectory[0].joint_trajectory.points.back().positions.data()); last_state.printStatePositions(std::cout); ROS_ERROR_STREAM("Goal is " << goal_state); bool constraints_are_ok = true; for (const moveit_msgs::JointConstraint& constraint : req.goal_constraints[0].joint_constraints) { ROS_ERROR_STREAM("Validating constraint for " << constraint.joint_name << "..."); constraints_are_ok = constraints_are_ok and jc.configure(constraint); constraints_are_ok = constraints_are_ok and jc.decide(last_state).satisfied; if (not constraints_are_ok) { res.error_code.val = moveit_msgs::MoveItErrorCodes::GOAL_CONSTRAINTS_VIOLATED; return false; } } return true; } }
Check if there are any goal constraints
Check if there are any goal constraints
C++
bsd-3-clause
davetcoleman/moveit,ros-planning/moveit,davetcoleman/moveit,ros-planning/moveit,ros-planning/moveit,davetcoleman/moveit,davetcoleman/moveit,ros-planning/moveit,ros-planning/moveit
b4e3fcb428b7b58ce29db2771bf09d4920740846
src/Gui/QuantitySpinBox.cpp
src/Gui/QuantitySpinBox.cpp
/*************************************************************************** * Copyright (c) 2014 Werner Mayer <wmayer[at]users.sourceforge.net> * * * * This file is part of the FreeCAD CAx development system. * * * * This library is free software; you can redistribute it and/or * * modify it under the terms of the GNU Library General Public * * License as published by the Free Software Foundation; either * * version 2 of the License, or (at your option) any later version. * * * * This library is distributed in the hope that it will be useful, * * but WITHOUT ANY WARRANTY; without even the implied warranty of * * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * * GNU Library General Public License for more details. * * * * You should have received a copy of the GNU Library General Public * * License along with this library; see the file COPYING.LIB. If not, * * write to the Free Software Foundation, Inc., 51 Franklin Street, * * Fifth Floor, Boston, MA 02110-1301, USA * * * ***************************************************************************/ #include "PreCompiled.h" #ifndef _PreComp_ # include <QLineEdit> # include <QFocusEvent> #endif #include "QuantitySpinBox.h" #include <Base/Exception.h> using namespace Gui; namespace Gui { class QuantitySpinBoxPrivate { public: QuantitySpinBoxPrivate() : validInput(true), unitValue(0), maximum(DOUBLE_MAX), minimum(-DOUBLE_MAX), singleStep(1.0) { } ~QuantitySpinBoxPrivate() { } QString stripped(const QString &t, int *pos) const { QString text = t; const int s = text.size(); text = text.trimmed(); if (pos) (*pos) -= (s - text.size()); return text; } Base::Quantity validateAndInterpret(QString& input, int& pos, QValidator::State& state) const { Base::Quantity res; const double max = this->maximum; const double min = this->minimum; QString copy = input; int len = copy.size(); pos = len; const bool plus = max >= 0; const bool minus = min <= 0; switch (len) { case 0: state = max != min ? QValidator::Intermediate : QValidator::Invalid; goto end; case 1: if (copy.at(0) == locale.decimalPoint()) { state = QValidator::Intermediate; copy.prepend(QLatin1Char('0')); pos++; len++; goto end; } else if (copy.at(0) == QLatin1Char('+')) { // the quantity parser doesn't allow numbers of the form '+1.0' state = QValidator::Invalid; goto end; } else if (copy.at(0) == QLatin1Char('-')) { if (minus) state = QValidator::Intermediate; else state = QValidator::Invalid; goto end; } break; case 2: if (copy.at(1) == locale.decimalPoint() && (plus && copy.at(0) == QLatin1Char('+'))) { state = QValidator::Intermediate; goto end; } if (copy.at(1) == locale.decimalPoint() && (minus && copy.at(0) == QLatin1Char('-'))) { state = QValidator::Intermediate; copy.insert(1, QLatin1Char('0')); pos++; len++; goto end; } break; default: break; } { if (copy.at(0) == locale.groupSeparator()) { state = QValidator::Invalid; goto end; } else if (len > 1) { const int dec = copy.indexOf(locale.decimalPoint()); if (dec != -1) { if (dec + 1 < copy.size() && copy.at(dec + 1) == locale.decimalPoint() && pos == dec + 1) { copy.remove(dec + 1, 1); } else if (copy.indexOf(locale.decimalPoint(), dec + 1) != -1) { // trying to add a second decimal point is not allowed state = QValidator::Invalid; goto end; } for (int i=dec + 1; i<copy.size(); ++i) { // a group separator after the decimal point is not allowed if (copy.at(i) == locale.groupSeparator()) { state = QValidator::Invalid; goto end; } } } } bool ok = false; double value = min; if (locale.negativeSign() != QLatin1Char('-')) copy.replace(locale.negativeSign(), QLatin1Char('-')); if (locale.positiveSign() != QLatin1Char('+')) copy.replace(locale.positiveSign(), QLatin1Char('+')); try { QString copy2 = copy; copy2.remove(locale.groupSeparator()); res = Base::Quantity::parse(copy2); value = res.getValue(); ok = true; } catch (Base::Exception&) { } if (!ok) { // input may not be finished state = QValidator::Intermediate; } else if (value >= min && value <= max) { if (copy.endsWith(locale.decimalPoint())) { // input shouldn't end with a decimal point state = QValidator::Intermediate; } else if (res.getUnit().isEmpty() && !this->unit.isEmpty()) { // if not dimensionless the input should have a dimension state = QValidator::Intermediate; } else if (res.getUnit() != this->unit) { state = QValidator::Invalid; } else { state = QValidator::Acceptable; } } else if (max == min) { // when max and min is the same the only non-Invalid input is max (or min) state = QValidator::Invalid; } else { if ((value >= 0 && value > max) || (value < 0 && value < min)) { state = QValidator::Invalid; } else { state = QValidator::Intermediate; } } } end: if (state != QValidator::Acceptable) { res.setValue(max > 0 ? min : max); } input = copy; return res; } QLocale locale; bool validInput; QString validStr; Base::Quantity quantity; Base::Unit unit; double unitValue; QString unitStr; double maximum; double minimum; double singleStep; }; } QuantitySpinBox::QuantitySpinBox(QWidget *parent) : QAbstractSpinBox(parent), d_ptr(new QuantitySpinBoxPrivate()) { d_ptr->locale = locale(); this->setContextMenuPolicy(Qt::DefaultContextMenu); QObject::connect(lineEdit(), SIGNAL(textChanged(QString)), this, SLOT(userInput(QString))); } QuantitySpinBox::~QuantitySpinBox() { } void QuantitySpinBox::updateText(const Base::Quantity& quant) { Q_D(QuantitySpinBox); double dFactor; QString txt = quant.getUserString(dFactor,d->unitStr); d->unitValue = quant.getValue()/dFactor; lineEdit()->setText(txt); } Base::Quantity QuantitySpinBox::value() const { Q_D(const QuantitySpinBox); return d->quantity; } void QuantitySpinBox::setValue(const Base::Quantity& value) { Q_D(QuantitySpinBox); d->quantity = value; // check limits if (d->quantity.getValue() > d->maximum) d->quantity.setValue(d->maximum); if (d->quantity.getValue() < d->minimum) d->quantity.setValue(d->minimum); d->unit = value.getUnit(); updateText(value); } void QuantitySpinBox::setValue(double value) { Q_D(QuantitySpinBox); setValue(Base::Quantity(value, d->unit)); } bool QuantitySpinBox::hasValidInput() const { Q_D(const QuantitySpinBox); return d->validInput; } // Gets called after call of 'validateAndInterpret' void QuantitySpinBox::userInput(const QString & text) { Q_D(QuantitySpinBox); QString tmp = text; int pos = 0; QValidator::State state; Base::Quantity res = d->validateAndInterpret(tmp, pos, state); if (state == QValidator::Acceptable) { d->validInput = true; d->validStr = text; } else if (state == QValidator::Intermediate) { tmp = tmp.trimmed(); tmp += QLatin1Char(' '); tmp += d->unitStr; Base::Quantity res2 = d->validateAndInterpret(tmp, pos, state); if (state == QValidator::Acceptable) { d->validInput = true; d->validStr = tmp; res = res2; } else { d->validInput = false; return; } } else { d->validInput = false; return; } double factor; res.getUserString(factor,d->unitStr); d->unitValue = res.getValue()/factor; d->quantity = res; // signaling valueChanged(res); valueChanged(res.getValue()); } Base::Unit QuantitySpinBox::unit() const { Q_D(const QuantitySpinBox); return d->unit; } void QuantitySpinBox::setUnit(const Base::Unit &unit) { Q_D(QuantitySpinBox); d->unit = unit; d->quantity.setUnit(unit); updateText(d->quantity); } void QuantitySpinBox::setUnitText(const QString& str) { Base::Quantity quant = Base::Quantity::parse(str); setUnit(quant.getUnit()); } QString QuantitySpinBox::unitText(void) { Q_D(QuantitySpinBox); return d->unitStr; } double QuantitySpinBox::singleStep() const { Q_D(const QuantitySpinBox); return d->singleStep; } void QuantitySpinBox::setSingleStep(double value) { Q_D(QuantitySpinBox); if (value >= 0) { d->singleStep = value; } } double QuantitySpinBox::minimum() const { Q_D(const QuantitySpinBox); return d->minimum; } void QuantitySpinBox::setMinimum(double minimum) { Q_D(QuantitySpinBox); d->minimum = minimum; } double QuantitySpinBox::maximum() const { Q_D(const QuantitySpinBox); return d->maximum; } void QuantitySpinBox::setMaximum(double maximum) { Q_D(QuantitySpinBox); d->maximum = maximum; } void QuantitySpinBox::setRange(double minimum, double maximum) { Q_D(QuantitySpinBox); d->minimum = minimum; d->maximum = maximum; } QAbstractSpinBox::StepEnabled QuantitySpinBox::stepEnabled() const { Q_D(const QuantitySpinBox); if (isReadOnly()/* || !d->validInput*/) return StepNone; if (wrapping()) return StepEnabled(StepUpEnabled | StepDownEnabled); StepEnabled ret = StepNone; if (d->quantity.getValue() < d->maximum) { ret |= StepUpEnabled; } if (d->quantity.getValue() > d->minimum) { ret |= StepDownEnabled; } return ret; } void QuantitySpinBox::stepBy(int steps) { Q_D(QuantitySpinBox); double step = d->singleStep * steps; double val = d->unitValue + step; if (val > d->maximum) val = d->maximum; else if (val < d->minimum) val = d->minimum; lineEdit()->setText(QString::fromUtf8("%L1 %2").arg(val).arg(d->unitStr)); update(); selectNumber(); } void QuantitySpinBox::showEvent(QShowEvent * event) { Q_D(QuantitySpinBox); QAbstractSpinBox::showEvent(event); bool selected = lineEdit()->hasSelectedText(); updateText(d->quantity); if (selected) selectNumber(); } void QuantitySpinBox::focusInEvent(QFocusEvent * event) { bool hasSel = lineEdit()->hasSelectedText(); QAbstractSpinBox::focusInEvent(event); if (event->reason() == Qt::TabFocusReason || event->reason() == Qt::BacktabFocusReason || event->reason() == Qt::ShortcutFocusReason) { if (!hasSel) selectNumber(); } } void QuantitySpinBox::focusOutEvent(QFocusEvent * event) { Q_D(QuantitySpinBox); int pos = 0; QString text = lineEdit()->text(); QValidator::State state; d->validateAndInterpret(text, pos, state); if (state != QValidator::Acceptable) { lineEdit()->setText(d->validStr); } QAbstractSpinBox::focusOutEvent(event); } void QuantitySpinBox::clear() { QAbstractSpinBox::clear(); } void QuantitySpinBox::selectNumber() { QString str = lineEdit()->text(); unsigned int i = 0; QChar d = locale().decimalPoint(); QChar g = locale().groupSeparator(); QChar n = locale().negativeSign(); for (QString::iterator it = str.begin(); it != str.end(); ++it) { if (it->isDigit()) i++; else if (*it == d) i++; else if (*it == g) i++; else if (*it == n) i++; else // any non-number character break; } lineEdit()->setSelection(0, i); } QString QuantitySpinBox::textFromValue(const Base::Quantity& value) const { double factor; QString unitStr; QString str = value.getUserString(factor, unitStr); if (qAbs(value.getValue()) >= 1000.0) { str.remove(locale().groupSeparator()); } return str; } Base::Quantity QuantitySpinBox::valueFromText(const QString &text) const { Q_D(const QuantitySpinBox); QString copy = text; int pos = lineEdit()->cursorPosition(); QValidator::State state = QValidator::Acceptable; Base::Quantity quant = d->validateAndInterpret(copy, pos, state); if (state != QValidator::Acceptable) { fixup(copy); quant = d->validateAndInterpret(copy, pos, state); } return quant; } QValidator::State QuantitySpinBox::validate(QString &text, int &pos) const { Q_D(const QuantitySpinBox); QValidator::State state; d->validateAndInterpret(text, pos, state); return state; } void QuantitySpinBox::fixup(QString &input) const { input.remove(locale().groupSeparator()); } #include "moc_QuantitySpinBox.cpp"
/*************************************************************************** * Copyright (c) 2014 Werner Mayer <wmayer[at]users.sourceforge.net> * * * * This file is part of the FreeCAD CAx development system. * * * * This library is free software; you can redistribute it and/or * * modify it under the terms of the GNU Library General Public * * License as published by the Free Software Foundation; either * * version 2 of the License, or (at your option) any later version. * * * * This library is distributed in the hope that it will be useful, * * but WITHOUT ANY WARRANTY; without even the implied warranty of * * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * * GNU Library General Public License for more details. * * * * You should have received a copy of the GNU Library General Public * * License along with this library; see the file COPYING.LIB. If not, * * write to the Free Software Foundation, Inc., 51 Franklin Street, * * Fifth Floor, Boston, MA 02110-1301, USA * * * ***************************************************************************/ #include "PreCompiled.h" #ifndef _PreComp_ # include <QLineEdit> # include <QFocusEvent> #endif #include "QuantitySpinBox.h" #include <Base/Exception.h> using namespace Gui; namespace Gui { class QuantitySpinBoxPrivate { public: QuantitySpinBoxPrivate() : validInput(true), unitValue(0), maximum(DOUBLE_MAX), minimum(-DOUBLE_MAX), singleStep(1.0) { } ~QuantitySpinBoxPrivate() { } QString stripped(const QString &t, int *pos) const { QString text = t; const int s = text.size(); text = text.trimmed(); if (pos) (*pos) -= (s - text.size()); return text; } Base::Quantity validateAndInterpret(QString& input, int& pos, QValidator::State& state) const { Base::Quantity res; const double max = this->maximum; const double min = this->minimum; QString copy = input; int len = copy.size(); const bool plus = max >= 0; const bool minus = min <= 0; switch (len) { case 0: state = max != min ? QValidator::Intermediate : QValidator::Invalid; goto end; case 1: if (copy.at(0) == locale.decimalPoint()) { state = QValidator::Intermediate; copy.prepend(QLatin1Char('0')); pos++; len++; goto end; } else if (copy.at(0) == QLatin1Char('+')) { // the quantity parser doesn't allow numbers of the form '+1.0' state = QValidator::Invalid; goto end; } else if (copy.at(0) == QLatin1Char('-')) { if (minus) state = QValidator::Intermediate; else state = QValidator::Invalid; goto end; } break; case 2: if (copy.at(1) == locale.decimalPoint() && (plus && copy.at(0) == QLatin1Char('+'))) { state = QValidator::Intermediate; goto end; } if (copy.at(1) == locale.decimalPoint() && (minus && copy.at(0) == QLatin1Char('-'))) { state = QValidator::Intermediate; copy.insert(1, QLatin1Char('0')); pos++; len++; goto end; } break; default: break; } { if (copy.at(0) == locale.groupSeparator()) { state = QValidator::Invalid; goto end; } else if (len > 1) { const int dec = copy.indexOf(locale.decimalPoint()); if (dec != -1) { if (dec + 1 < copy.size() && copy.at(dec + 1) == locale.decimalPoint() && pos == dec + 1) { copy.remove(dec + 1, 1); } else if (copy.indexOf(locale.decimalPoint(), dec + 1) != -1) { // trying to add a second decimal point is not allowed state = QValidator::Invalid; goto end; } for (int i=dec + 1; i<copy.size(); ++i) { // a group separator after the decimal point is not allowed if (copy.at(i) == locale.groupSeparator()) { state = QValidator::Invalid; goto end; } } } } bool ok = false; double value = min; if (locale.negativeSign() != QLatin1Char('-')) copy.replace(locale.negativeSign(), QLatin1Char('-')); if (locale.positiveSign() != QLatin1Char('+')) copy.replace(locale.positiveSign(), QLatin1Char('+')); try { QString copy2 = copy; copy2.remove(locale.groupSeparator()); res = Base::Quantity::parse(copy2); value = res.getValue(); ok = true; } catch (Base::Exception&) { } if (!ok) { // input may not be finished state = QValidator::Intermediate; } else if (value >= min && value <= max) { if (copy.endsWith(locale.decimalPoint())) { // input shouldn't end with a decimal point state = QValidator::Intermediate; } else if (res.getUnit().isEmpty() && !this->unit.isEmpty()) { // if not dimensionless the input should have a dimension state = QValidator::Intermediate; } else if (res.getUnit() != this->unit) { state = QValidator::Invalid; } else { state = QValidator::Acceptable; } } else if (max == min) { // when max and min is the same the only non-Invalid input is max (or min) state = QValidator::Invalid; } else { if ((value >= 0 && value > max) || (value < 0 && value < min)) { state = QValidator::Invalid; } else { state = QValidator::Intermediate; } } } end: if (state != QValidator::Acceptable) { res.setValue(max > 0 ? min : max); } input = copy; return res; } QLocale locale; bool validInput; QString validStr; Base::Quantity quantity; Base::Unit unit; double unitValue; QString unitStr; double maximum; double minimum; double singleStep; }; } QuantitySpinBox::QuantitySpinBox(QWidget *parent) : QAbstractSpinBox(parent), d_ptr(new QuantitySpinBoxPrivate()) { d_ptr->locale = locale(); this->setContextMenuPolicy(Qt::DefaultContextMenu); QObject::connect(lineEdit(), SIGNAL(textChanged(QString)), this, SLOT(userInput(QString))); } QuantitySpinBox::~QuantitySpinBox() { } void QuantitySpinBox::updateText(const Base::Quantity& quant) { Q_D(QuantitySpinBox); double dFactor; QString txt = quant.getUserString(dFactor,d->unitStr); d->unitValue = quant.getValue()/dFactor; lineEdit()->setText(txt); } Base::Quantity QuantitySpinBox::value() const { Q_D(const QuantitySpinBox); return d->quantity; } void QuantitySpinBox::setValue(const Base::Quantity& value) { Q_D(QuantitySpinBox); d->quantity = value; // check limits if (d->quantity.getValue() > d->maximum) d->quantity.setValue(d->maximum); if (d->quantity.getValue() < d->minimum) d->quantity.setValue(d->minimum); d->unit = value.getUnit(); updateText(value); } void QuantitySpinBox::setValue(double value) { Q_D(QuantitySpinBox); setValue(Base::Quantity(value, d->unit)); } bool QuantitySpinBox::hasValidInput() const { Q_D(const QuantitySpinBox); return d->validInput; } // Gets called after call of 'validateAndInterpret' void QuantitySpinBox::userInput(const QString & text) { Q_D(QuantitySpinBox); QString tmp = text; int pos = 0; QValidator::State state; Base::Quantity res = d->validateAndInterpret(tmp, pos, state); if (state == QValidator::Acceptable) { d->validInput = true; d->validStr = text; } else if (state == QValidator::Intermediate) { tmp = tmp.trimmed(); tmp += QLatin1Char(' '); tmp += d->unitStr; Base::Quantity res2 = d->validateAndInterpret(tmp, pos, state); if (state == QValidator::Acceptable) { d->validInput = true; d->validStr = tmp; res = res2; } else { d->validInput = false; return; } } else { d->validInput = false; return; } double factor; res.getUserString(factor,d->unitStr); d->unitValue = res.getValue()/factor; d->quantity = res; // signaling valueChanged(res); valueChanged(res.getValue()); } Base::Unit QuantitySpinBox::unit() const { Q_D(const QuantitySpinBox); return d->unit; } void QuantitySpinBox::setUnit(const Base::Unit &unit) { Q_D(QuantitySpinBox); d->unit = unit; d->quantity.setUnit(unit); updateText(d->quantity); } void QuantitySpinBox::setUnitText(const QString& str) { Base::Quantity quant = Base::Quantity::parse(str); setUnit(quant.getUnit()); } QString QuantitySpinBox::unitText(void) { Q_D(QuantitySpinBox); return d->unitStr; } double QuantitySpinBox::singleStep() const { Q_D(const QuantitySpinBox); return d->singleStep; } void QuantitySpinBox::setSingleStep(double value) { Q_D(QuantitySpinBox); if (value >= 0) { d->singleStep = value; } } double QuantitySpinBox::minimum() const { Q_D(const QuantitySpinBox); return d->minimum; } void QuantitySpinBox::setMinimum(double minimum) { Q_D(QuantitySpinBox); d->minimum = minimum; } double QuantitySpinBox::maximum() const { Q_D(const QuantitySpinBox); return d->maximum; } void QuantitySpinBox::setMaximum(double maximum) { Q_D(QuantitySpinBox); d->maximum = maximum; } void QuantitySpinBox::setRange(double minimum, double maximum) { Q_D(QuantitySpinBox); d->minimum = minimum; d->maximum = maximum; } QAbstractSpinBox::StepEnabled QuantitySpinBox::stepEnabled() const { Q_D(const QuantitySpinBox); if (isReadOnly()/* || !d->validInput*/) return StepNone; if (wrapping()) return StepEnabled(StepUpEnabled | StepDownEnabled); StepEnabled ret = StepNone; if (d->quantity.getValue() < d->maximum) { ret |= StepUpEnabled; } if (d->quantity.getValue() > d->minimum) { ret |= StepDownEnabled; } return ret; } void QuantitySpinBox::stepBy(int steps) { Q_D(QuantitySpinBox); double step = d->singleStep * steps; double val = d->unitValue + step; if (val > d->maximum) val = d->maximum; else if (val < d->minimum) val = d->minimum; lineEdit()->setText(QString::fromUtf8("%L1 %2").arg(val).arg(d->unitStr)); update(); selectNumber(); } void QuantitySpinBox::showEvent(QShowEvent * event) { Q_D(QuantitySpinBox); QAbstractSpinBox::showEvent(event); bool selected = lineEdit()->hasSelectedText(); updateText(d->quantity); if (selected) selectNumber(); } void QuantitySpinBox::focusInEvent(QFocusEvent * event) { bool hasSel = lineEdit()->hasSelectedText(); QAbstractSpinBox::focusInEvent(event); if (event->reason() == Qt::TabFocusReason || event->reason() == Qt::BacktabFocusReason || event->reason() == Qt::ShortcutFocusReason) { if (!hasSel) selectNumber(); } } void QuantitySpinBox::focusOutEvent(QFocusEvent * event) { Q_D(QuantitySpinBox); int pos = 0; QString text = lineEdit()->text(); QValidator::State state; d->validateAndInterpret(text, pos, state); if (state != QValidator::Acceptable) { lineEdit()->setText(d->validStr); } QAbstractSpinBox::focusOutEvent(event); } void QuantitySpinBox::clear() { QAbstractSpinBox::clear(); } void QuantitySpinBox::selectNumber() { QString str = lineEdit()->text(); unsigned int i = 0; QChar d = locale().decimalPoint(); QChar g = locale().groupSeparator(); QChar n = locale().negativeSign(); for (QString::iterator it = str.begin(); it != str.end(); ++it) { if (it->isDigit()) i++; else if (*it == d) i++; else if (*it == g) i++; else if (*it == n) i++; else // any non-number character break; } lineEdit()->setSelection(0, i); } QString QuantitySpinBox::textFromValue(const Base::Quantity& value) const { double factor; QString unitStr; QString str = value.getUserString(factor, unitStr); if (qAbs(value.getValue()) >= 1000.0) { str.remove(locale().groupSeparator()); } return str; } Base::Quantity QuantitySpinBox::valueFromText(const QString &text) const { Q_D(const QuantitySpinBox); QString copy = text; int pos = lineEdit()->cursorPosition(); QValidator::State state = QValidator::Acceptable; Base::Quantity quant = d->validateAndInterpret(copy, pos, state); if (state != QValidator::Acceptable) { fixup(copy); quant = d->validateAndInterpret(copy, pos, state); } return quant; } QValidator::State QuantitySpinBox::validate(QString &text, int &pos) const { Q_D(const QuantitySpinBox); QValidator::State state; d->validateAndInterpret(text, pos, state); return state; } void QuantitySpinBox::fixup(QString &input) const { input.remove(locale().groupSeparator()); } #include "moc_QuantitySpinBox.cpp"
Fix for bugs #2236 & #2237
Fix for bugs #2236 & #2237
C++
lgpl-2.1
Fat-Zer/FreeCAD_sf_master,kkoksvik/FreeCAD,wood-galaxy/FreeCAD,jonnor/FreeCAD,bblacey/FreeCAD-MacOS-CI,chrisjaquet/FreeCAD,maurerpe/FreeCAD,chrisjaquet/FreeCAD,wood-galaxy/FreeCAD,kkoksvik/FreeCAD,cpollard1001/FreeCAD_sf_master,marcoitur/FreeCAD,usakhelo/FreeCAD,cpollard1001/FreeCAD_sf_master,Fat-Zer/FreeCAD_sf_master,marcoitur/Freecad_test,timthelion/FreeCAD,cpollard1001/FreeCAD_sf_master,chrisjaquet/FreeCAD,dsbrown/FreeCAD,jonnor/FreeCAD,bblacey/FreeCAD-MacOS-CI,chrisjaquet/FreeCAD,cpollard1001/FreeCAD_sf_master,timthelion/FreeCAD,jonnor/FreeCAD,Fat-Zer/FreeCAD_sf_master,maurerpe/FreeCAD,mickele77/FreeCAD,marcoitur/Freecad_test,chrisjaquet/FreeCAD,YuanYouYuan/FreeCAD,timthelion/FreeCAD,YuanYouYuan/FreeCAD,maurerpe/FreeCAD,usakhelo/FreeCAD,wood-galaxy/FreeCAD,maurerpe/FreeCAD,kkoksvik/FreeCAD,YuanYouYuan/FreeCAD,usakhelo/FreeCAD,bblacey/FreeCAD-MacOS-CI,bblacey/FreeCAD-MacOS-CI,dsbrown/FreeCAD,wood-galaxy/FreeCAD,chrisjaquet/FreeCAD,usakhelo/FreeCAD,wood-galaxy/FreeCAD,timthelion/FreeCAD,usakhelo/FreeCAD,Fat-Zer/FreeCAD_sf_master,kkoksvik/FreeCAD,dsbrown/FreeCAD,marcoitur/FreeCAD,timthelion/FreeCAD,chrisjaquet/FreeCAD,timthelion/FreeCAD,maurerpe/FreeCAD,YuanYouYuan/FreeCAD,marcoitur/FreeCAD,usakhelo/FreeCAD,marcoitur/FreeCAD,dsbrown/FreeCAD,YuanYouYuan/FreeCAD,wood-galaxy/FreeCAD,bblacey/FreeCAD-MacOS-CI,mickele77/FreeCAD,jonnor/FreeCAD,marcoitur/Freecad_test,kkoksvik/FreeCAD,dsbrown/FreeCAD,marcoitur/Freecad_test,cpollard1001/FreeCAD_sf_master,Fat-Zer/FreeCAD_sf_master,mickele77/FreeCAD,marcoitur/FreeCAD,mickele77/FreeCAD,usakhelo/FreeCAD,bblacey/FreeCAD-MacOS-CI,marcoitur/Freecad_test,bblacey/FreeCAD-MacOS-CI,mickele77/FreeCAD,jonnor/FreeCAD
2f872cb92d2717bf73daafa9ba06ab50e72f1455
osquery/killswitch/plugins/tests/killswitch_filesystem_tests.cpp
osquery/killswitch/plugins/tests/killswitch_filesystem_tests.cpp
/** * Copyright (c) 2014-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under both the Apache 2.0 license (found in the * LICENSE file in the root directory of this source tree) and the GPLv2 (found * in the COPYING file in the root directory of this source tree). * You may select, at your option, one of the above-listed licenses. */ #include <gtest/gtest.h> #include <osquery/flags.h> #include "osquery/killswitch/plugins/killswitch_filesystem.h" #include "osquery/tests/test_util.h" namespace osquery { DECLARE_uint32(killswitch_refresh_rate); class KillswitchFilesystemTests : public testing::Test {}; TEST_F(KillswitchFilesystemTests, test_killswitch_filesystem_plugin) { KillswitchFilesystem plugin(kTestDataPath + "test_killswitch.conf"); plugin.refresh(); { auto result = plugin.isEnabled("testSwitch"); ASSERT_TRUE(result); ASSERT_TRUE(*result); } { auto result = plugin.isEnabled("test2Switch"); ASSERT_TRUE(result); ASSERT_FALSE(*result); } } } // namespace osquery
/** * Copyright (c) 2014-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under both the Apache 2.0 license (found in the * LICENSE file in the root directory of this source tree) and the GPLv2 (found * in the COPYING file in the root directory of this source tree). * You may select, at your option, one of the above-listed licenses. */ #include <gtest/gtest.h> #include <osquery/flags.h> #include "osquery/killswitch/plugins/killswitch_filesystem.h" #include "osquery/tests/test_util.h" namespace osquery { DECLARE_uint32(killswitch_refresh_rate); class KillswitchFilesystemTests : public testing::Test {}; TEST_F(KillswitchFilesystemTests, test_killswitch_filesystem_plugin) { KillswitchFilesystem plugin(kTestDataPath + "test_killswitch.conf"); EXPECT_TRUE(plugin.refresh()); { auto result = plugin.isEnabled("testSwitch"); ASSERT_TRUE(result); ASSERT_TRUE(*result); } { auto result = plugin.isEnabled("test2Switch"); ASSERT_TRUE(result); ASSERT_FALSE(*result); } } } // namespace osquery
Handle expect in test (#4756)
Handle expect in test (#4756)
C++
bsd-3-clause
jedi22/osquery,jedi22/osquery,hackgnar/osquery,hackgnar/osquery,hackgnar/osquery,jedi22/osquery
136865d5d745b7ad93185d74faf0f5dcdba687f3
Base/Analysis/voPLSStatistics.cpp
Base/Analysis/voPLSStatistics.cpp
// Qt includes #include <QDebug> // QtPropertyBrowser includes #include <QtVariantPropertyManager> // Visomics includes #include "voPLSStatistics.h" #include "voTableDataObject.h" #include "voUtils.h" #include "vtkExtendedTable.h" // VTK includes #include <vtkArrayData.h> #include <vtkDoubleArray.h> #include <vtkRCalculatorFilter.h> #include <vtkSmartPointer.h> #include <vtkStringArray.h> #include <vtkNew.h> #include <vtkTable.h> // -------------------------------------------------------------------------- // voPLSStatisticsPrivate methods // -------------------------------------------------------------------------- class voPLSStatisticsPrivate { public: vtkSmartPointer<vtkRCalculatorFilter> RCalc; }; // -------------------------------------------------------------------------- // voPLSStatistics methods // -------------------------------------------------------------------------- voPLSStatistics::voPLSStatistics(): Superclass(), d_ptr(new voPLSStatisticsPrivate) { Q_D(voPLSStatistics); d->RCalc = vtkSmartPointer<vtkRCalculatorFilter>::New(); } // -------------------------------------------------------------------------- voPLSStatistics::~voPLSStatistics() { } // -------------------------------------------------------------------------- void voPLSStatistics::setInputInformation() { this->addInputType("input", "vtkExtendedTable"); } // -------------------------------------------------------------------------- void voPLSStatistics::setOutputInformation() { this->addOutputType("scores", "vtkTable" , "", "", "voTableView", "Table (Scores)"); this->addOutputType("yScores", "vtkTable" , "", "", "voTableView", "Table (Y-Scores)"); this->addOutputType("loadings", "vtkTable" , "", "", "voTableView", "Table (Loadings)"); this->addOutputType("loadingWeights", "vtkTable" , "", "", "voTableView", "Table (Loading Weights)"); this->addOutputType("yLoadings", "vtkTable" , "", "", "voTableView", "Table (Y-Loadings)"); } // -------------------------------------------------------------------------- void voPLSStatistics::setParameterInformation() { QList<QtProperty*> pls_parameters; pls_parameters << this->addStringParameter("predictor_range", QObject::tr("Predictor Analyte(s)"), "1-3,6"); pls_parameters << this->addStringParameter("response_range", QObject::tr("Response Analyte(s)"), "4,5,7-10"); pls_parameters << this->addEnumParameter("algorithm", tr("Algorithm"), (QStringList() << "Kernel" << "Wide Kernel" << "SIMPLS" << "Orthogonal Scores"), "Kernel"); this->addParameterGroup("PLS parameters", pls_parameters); } // -------------------------------------------------------------------------- bool voPLSStatistics::execute() { Q_D(voPLSStatistics); // Get and parse parameters QString algorithmString; if (this->enumParameter("algorithm") == QLatin1String("Kernel")) { algorithmString = "kernelpls"; } else if (this->enumParameter("algorithm") == QLatin1String("Wide Kernel")) { algorithmString = "widekernelpls"; } else if (this->enumParameter("algorithm") == QLatin1String("SIMPLS")) { algorithmString = "simpls"; } else //if (this->enumParameter("algorithm") == QString("Orthogonal Scores")) { algorithmString = "oscorespls"; } bool result; QList<int> predictorRangeList; result = voUtils::parseRangeString(this->stringParameter("predictor_range"), predictorRangeList, false); if(!result || predictorRangeList.empty()) { qWarning() << QObject::tr("Invalid paramater, could not parse Predictor Measure(s)"); return false; } QList<int> responseRangeList; result= voUtils::parseRangeString(this->stringParameter("response_range"), responseRangeList, false); if(!result || responseRangeList.empty()) { qWarning() << QObject::tr("Invalid paramater, could not parse Response Measure(s)"); return false; } // Import data table locally vtkExtendedTable* extendedTable = vtkExtendedTable::SafeDownCast(this->input()->dataAsVTKDataObject()); if (!extendedTable) { qWarning() << "Input is Null"; return false; } vtkSmartPointer<vtkTable> inputDataTable = extendedTable->GetData(); // PLS expects each measure (analyte) as a column, and each sample (experiment) as a row, so we must transpose vtkNew<vtkTable> inputDataTableTransposed; bool transposeResult = voUtils::transposeTable(inputDataTable.GetPointer(), inputDataTableTransposed.GetPointer()); if (!transposeResult) { qWarning() << QObject::tr("Error: could not transpose input table"); return false; } // Build array for predictor measure range vtkSmartPointer<vtkArray> predictorArray; bool tabToArrResult = voUtils::tableToArray(inputDataTableTransposed.GetPointer(), predictorArray, predictorRangeList); if (!tabToArrResult) { qWarning() << QObject::tr("Invalid paramater, out of range: Predictor Measure(s)"); return false; } // Build array for response measure vtkSmartPointer<vtkArray> responseArray; tabToArrResult = voUtils::tableToArray(inputDataTableTransposed.GetPointer(), responseArray, responseRangeList); if (!tabToArrResult) { qWarning() << QObject::tr("Invalid paramater, out of range: Response Measure(s)"); return false; } // Combine sample 1 and 2 array groups vtkNew<vtkArrayData> RInputArrayData; RInputArrayData->AddArray(predictorArray.GetPointer()); RInputArrayData->AddArray(responseArray.GetPointer()); // Run R code d->RCalc->SetRoutput(0); d->RCalc->SetInputConnection(RInputArrayData->GetProducerPort()); d->RCalc->PutArray("0", "predictorArray"); d->RCalc->PutArray("1", "responseArray"); d->RCalc->GetArray("scoresArray","scoresArray"); d->RCalc->GetArray("yScoresArray","yScoresArray"); d->RCalc->GetArray("loadingsArray","loadingsArray"); d->RCalc->GetArray("loadingWeightsArray","loadingWeightsArray"); d->RCalc->GetArray("yLoadingsArray","yLoadingsArray"); d->RCalc->GetArray("RerrValue","RerrValue"); d->RCalc->SetRscript(QString( "library(\"pls\", warn.conflicts=FALSE)\n" "PLSdata <- data.frame(response=I(responseArray), predictor=I(predictorArray) )\n" "PLSresult <- plsr(response ~ predictor, data = PLSdata, method = \"%1\")\n" "if(exists(\"PLSresult\")) {" "RerrValue<-1" "}else{" "RerrValue<-0" "}\n" "scoresArray <- t(PLSresult$scores)\n" "yScoresArray <- t(PLSresult$Yscores)\n" "loadingsArray <- PLSresult$loadings[,]\n" "loadingWeightsArray <- PLSresult$loading.weights[,]\n" "yLoadingsArray <- PLSresult$Yloadings[,]\n" ).arg(algorithmString).toLatin1()); d->RCalc->Update(); vtkSmartPointer<vtkArrayData> outputArrayData = vtkArrayData::SafeDownCast(d->RCalc->GetOutput()); // Check for errors "thrown" by R script if(outputArrayData->GetArrayByName("RerrValue")->GetVariantValue(0).ToInt() > 1) { qWarning() << QObject::tr("Error: R could not calculate PLS"); return false; } // ------------------------------------------------ // Extract table for scores and Y-scores // No need to transpose scoresArray, it was done within the R code vtkNew<vtkTable> scoresTable; vtkNew<vtkTable> yScoresTable; { voUtils::arrayToTable(outputArrayData->GetArrayByName("scoresArray"), scoresTable.GetPointer()); voUtils::arrayToTable(outputArrayData->GetArrayByName("yScoresArray"), yScoresTable.GetPointer()); // Add column labels (experiment names) voUtils::setTableColumnNames(scoresTable.GetPointer(), extendedTable->GetColumnMetaDataOfInterestAsString()); voUtils::setTableColumnNames(yScoresTable.GetPointer(), extendedTable->GetColumnMetaDataOfInterestAsString()); // Add row labels (components) vtkNew<vtkStringArray> headerArr; for (vtkIdType r = 0;r < scoresTable->GetNumberOfRows(); ++r) { headerArr->InsertNextValue(QString("Comp %1").arg(r + 1).toLatin1()); } voUtils::insertColumnIntoTable(scoresTable.GetPointer(), 0, headerArr.GetPointer()); voUtils::insertColumnIntoTable(yScoresTable.GetPointer(), 0, headerArr.GetPointer()); } this->setOutput("scores", new voTableDataObject("scores", scoresTable.GetPointer())); this->setOutput("yScores", new voTableDataObject("yScores", yScoresTable.GetPointer())); // ------------------------------------------------ // Extract table for loadings and loading weights vtkNew<vtkTable> loadingsTable; vtkNew<vtkTable> loadingWeightsTable; { voUtils::arrayToTable(outputArrayData->GetArrayByName("loadingsArray"), loadingsTable.GetPointer()); voUtils::arrayToTable(outputArrayData->GetArrayByName("loadingWeightsArray"), loadingWeightsTable.GetPointer()); // Add column labels (components) for(vtkIdType c = 0; c < loadingsTable->GetNumberOfColumns(); ++c) { QByteArray colName = QString("Comp %1").arg(c + 1).toLatin1(); loadingsTable->GetColumn(c)->SetName(colName); loadingWeightsTable->GetColumn(c)->SetName(colName); } // Add row labels (predictor analytes) vtkNew<vtkStringArray> headerArr; vtkStringArray* analyteNames = extendedTable->GetRowMetaDataOfInterestAsString(); foreach(int r, predictorRangeList) { headerArr->InsertNextValue(analyteNames->GetValue(r)); } voUtils::insertColumnIntoTable(loadingsTable.GetPointer(), 0, headerArr.GetPointer()); voUtils::insertColumnIntoTable(loadingWeightsTable.GetPointer(), 0, headerArr.GetPointer()); } this->setOutput("loadings", new voTableDataObject("loadings", loadingsTable.GetPointer())); this->setOutput("loadingWeights", new voTableDataObject("loadingWeights", loadingWeightsTable.GetPointer())); // ------------------------------------------------ // Extract table for Y-loadings vtkNew<vtkTable> yLoadingsTable; { voUtils::arrayToTable(outputArrayData->GetArrayByName("yLoadingsArray"), yLoadingsTable.GetPointer()); // Add column labels (components) for(vtkIdType c = 0; c < yLoadingsTable->GetNumberOfColumns(); ++c) { yLoadingsTable->GetColumn(c)->SetName(QString("Comp %1").arg(c + 1).toLatin1()); } // Add row labels (response analytes) vtkNew<vtkStringArray> headerArr; vtkStringArray* analyteNames = extendedTable->GetRowMetaDataOfInterestAsString(); foreach(int r, responseRangeList) { headerArr->InsertNextValue(analyteNames->GetValue(r)); } voUtils::insertColumnIntoTable(yLoadingsTable.GetPointer(), 0, headerArr.GetPointer()); } this->setOutput("yLoadings", new voTableDataObject("yLoadings", yLoadingsTable.GetPointer())); return true; }
// Qt includes #include <QDebug> // QtPropertyBrowser includes #include <QtVariantPropertyManager> // Visomics includes #include "voPLSStatistics.h" #include "voTableDataObject.h" #include "voUtils.h" #include "vtkExtendedTable.h" // VTK includes #include <vtkArrayData.h> #include <vtkDoubleArray.h> #include <vtkRCalculatorFilter.h> #include <vtkSmartPointer.h> #include <vtkStringArray.h> #include <vtkNew.h> #include <vtkTable.h> // -------------------------------------------------------------------------- // voPLSStatisticsPrivate methods // -------------------------------------------------------------------------- class voPLSStatisticsPrivate { public: vtkSmartPointer<vtkRCalculatorFilter> RCalc; }; // -------------------------------------------------------------------------- // voPLSStatistics methods // -------------------------------------------------------------------------- voPLSStatistics::voPLSStatistics(): Superclass(), d_ptr(new voPLSStatisticsPrivate) { Q_D(voPLSStatistics); d->RCalc = vtkSmartPointer<vtkRCalculatorFilter>::New(); } // -------------------------------------------------------------------------- voPLSStatistics::~voPLSStatistics() { } // -------------------------------------------------------------------------- void voPLSStatistics::setInputInformation() { this->addInputType("input", "vtkExtendedTable"); } // -------------------------------------------------------------------------- void voPLSStatistics::setOutputInformation() { this->addOutputType("scores", "vtkTable" , "voPCAProjectionView", "Plot (Scores)", "voTableView", "Table (Scores)"); this->addOutputType("yScores", "vtkTable" , "voPCAProjectionView", "Plot (Y-Scores)", "voTableView", "Table (Y-Scores)"); this->addOutputType("loadings", "vtkTable" , "", "", "voTableView", "Table (Loadings)"); this->addOutputType("loadings_transposed", "vtkTable" , "voPCAProjectionView", "Plot (Loadings)", "", ""); this->addOutputType("loadingWeights", "vtkTable" , "", "", "voTableView", "Table (Loading Weights)"); this->addOutputType("loadingWeights_transposed", "vtkTable" , "voPCAProjectionView", "Plot (Loading Weights)", "", ""); this->addOutputType("yLoadings", "vtkTable" , "", "", "voTableView", "Table (Y-Loadings)"); this->addOutputType("yLoadings_transposed", "vtkTable" , "voPCAProjectionView", "Plot (Y-Loadings)", "", ""); } // -------------------------------------------------------------------------- void voPLSStatistics::setParameterInformation() { QList<QtProperty*> pls_parameters; pls_parameters << this->addStringParameter("predictor_range", QObject::tr("Predictor Analyte(s)"), "1-3,6"); pls_parameters << this->addStringParameter("response_range", QObject::tr("Response Analyte(s)"), "4,5,7-10"); pls_parameters << this->addEnumParameter("algorithm", tr("Algorithm"), (QStringList() << "Kernel" << "Wide Kernel" << "SIMPLS" << "Orthogonal Scores"), "Kernel"); this->addParameterGroup("PLS parameters", pls_parameters); } // -------------------------------------------------------------------------- bool voPLSStatistics::execute() { Q_D(voPLSStatistics); // Get and parse parameters QString algorithmString; if (this->enumParameter("algorithm") == QLatin1String("Kernel")) { algorithmString = "kernelpls"; } else if (this->enumParameter("algorithm") == QLatin1String("Wide Kernel")) { algorithmString = "widekernelpls"; } else if (this->enumParameter("algorithm") == QLatin1String("SIMPLS")) { algorithmString = "simpls"; } else //if (this->enumParameter("algorithm") == QString("Orthogonal Scores")) { algorithmString = "oscorespls"; } bool result; QList<int> predictorRangeList; result = voUtils::parseRangeString(this->stringParameter("predictor_range"), predictorRangeList, false); if(!result || predictorRangeList.empty()) { qWarning() << QObject::tr("Invalid paramater, could not parse Predictor Measure(s)"); return false; } QList<int> responseRangeList; result= voUtils::parseRangeString(this->stringParameter("response_range"), responseRangeList, false); if(!result || responseRangeList.empty()) { qWarning() << QObject::tr("Invalid paramater, could not parse Response Measure(s)"); return false; } // Import data table locally vtkExtendedTable* extendedTable = vtkExtendedTable::SafeDownCast(this->input()->dataAsVTKDataObject()); if (!extendedTable) { qWarning() << "Input is Null"; return false; } vtkSmartPointer<vtkTable> inputDataTable = extendedTable->GetData(); // PLS expects each measure (analyte) as a column, and each sample (experiment) as a row, so we must transpose vtkNew<vtkTable> inputDataTableTransposed; bool transposeResult = voUtils::transposeTable(inputDataTable.GetPointer(), inputDataTableTransposed.GetPointer()); if (!transposeResult) { qWarning() << QObject::tr("Error: could not transpose input table"); return false; } // Build array for predictor measure range vtkSmartPointer<vtkArray> predictorArray; bool tabToArrResult = voUtils::tableToArray(inputDataTableTransposed.GetPointer(), predictorArray, predictorRangeList); if (!tabToArrResult) { qWarning() << QObject::tr("Invalid paramater, out of range: Predictor Measure(s)"); return false; } // Build array for response measure vtkSmartPointer<vtkArray> responseArray; tabToArrResult = voUtils::tableToArray(inputDataTableTransposed.GetPointer(), responseArray, responseRangeList); if (!tabToArrResult) { qWarning() << QObject::tr("Invalid paramater, out of range: Response Measure(s)"); return false; } // Combine sample 1 and 2 array groups vtkNew<vtkArrayData> RInputArrayData; RInputArrayData->AddArray(predictorArray.GetPointer()); RInputArrayData->AddArray(responseArray.GetPointer()); // Run R code d->RCalc->SetRoutput(0); d->RCalc->SetInputConnection(RInputArrayData->GetProducerPort()); d->RCalc->PutArray("0", "predictorArray"); d->RCalc->PutArray("1", "responseArray"); d->RCalc->GetArray("scoresArray","scoresArray"); d->RCalc->GetArray("yScoresArray","yScoresArray"); d->RCalc->GetArray("loadingsArray","loadingsArray"); d->RCalc->GetArray("loadingWeightsArray","loadingWeightsArray"); d->RCalc->GetArray("yLoadingsArray","yLoadingsArray"); d->RCalc->GetArray("RerrValue","RerrValue"); d->RCalc->SetRscript(QString( "library(\"pls\", warn.conflicts=FALSE)\n" "PLSdata <- data.frame(response=I(responseArray), predictor=I(predictorArray) )\n" "PLSresult <- plsr(response ~ predictor, data = PLSdata, method = \"%1\")\n" "if(exists(\"PLSresult\")) {" "RerrValue<-1" "}else{" "RerrValue<-0" "}\n" "scoresArray <- t(PLSresult$scores)\n" "yScoresArray <- t(PLSresult$Yscores)\n" "loadingsArray <- PLSresult$loadings[,]\n" "loadingWeightsArray <- PLSresult$loading.weights[,]\n" "yLoadingsArray <- PLSresult$Yloadings[,]\n" ).arg(algorithmString).toLatin1()); d->RCalc->Update(); vtkSmartPointer<vtkArrayData> outputArrayData = vtkArrayData::SafeDownCast(d->RCalc->GetOutput()); // Check for errors "thrown" by R script if(outputArrayData->GetArrayByName("RerrValue")->GetVariantValue(0).ToInt() > 1) { qWarning() << QObject::tr("Error: R could not calculate PLS"); return false; } // ------------------------------------------------ // Extract table for scores and Y-scores // No need to transpose scoresArray, it was done within the R code vtkNew<vtkTable> scoresTable; vtkNew<vtkTable> yScoresTable; { voUtils::arrayToTable(outputArrayData->GetArrayByName("scoresArray"), scoresTable.GetPointer()); voUtils::arrayToTable(outputArrayData->GetArrayByName("yScoresArray"), yScoresTable.GetPointer()); // Add column labels (experiment names) voUtils::setTableColumnNames(scoresTable.GetPointer(), extendedTable->GetColumnMetaDataOfInterestAsString()); voUtils::setTableColumnNames(yScoresTable.GetPointer(), extendedTable->GetColumnMetaDataOfInterestAsString()); // Add row labels (components) vtkNew<vtkStringArray> headerArr; for (vtkIdType r = 0;r < scoresTable->GetNumberOfRows(); ++r) { headerArr->InsertNextValue(QString("Comp %1").arg(r + 1).toLatin1()); } voUtils::insertColumnIntoTable(scoresTable.GetPointer(), 0, headerArr.GetPointer()); voUtils::insertColumnIntoTable(yScoresTable.GetPointer(), 0, headerArr.GetPointer()); } this->setOutput("scores", new voTableDataObject("scores", scoresTable.GetPointer())); this->setOutput("yScores", new voTableDataObject("yScores", yScoresTable.GetPointer())); // ------------------------------------------------ // Extract table for loadings and loading weights vtkNew<vtkTable> loadingsTable; vtkNew<vtkTable> loadingWeightsTable; { voUtils::arrayToTable(outputArrayData->GetArrayByName("loadingsArray"), loadingsTable.GetPointer()); voUtils::arrayToTable(outputArrayData->GetArrayByName("loadingWeightsArray"), loadingWeightsTable.GetPointer()); // Add column labels (components) for(vtkIdType c = 0; c < loadingsTable->GetNumberOfColumns(); ++c) { QByteArray colName = QString("Comp %1").arg(c + 1).toLatin1(); loadingsTable->GetColumn(c)->SetName(colName); loadingWeightsTable->GetColumn(c)->SetName(colName); } // Add row labels (predictor analytes) vtkNew<vtkStringArray> headerArr; vtkStringArray* analyteNames = extendedTable->GetRowMetaDataOfInterestAsString(); foreach(int r, predictorRangeList) { headerArr->InsertNextValue(analyteNames->GetValue(r)); } voUtils::insertColumnIntoTable(loadingsTable.GetPointer(), 0, headerArr.GetPointer()); voUtils::insertColumnIntoTable(loadingWeightsTable.GetPointer(), 0, headerArr.GetPointer()); } this->setOutput("loadings", new voTableDataObject("loadings", loadingsTable.GetPointer())); vtkNew<vtkTable> loadingsTableTransposed; voUtils::transposeTable(loadingsTable.GetPointer(), loadingsTableTransposed.GetPointer(), voUtils::Headers); this->setOutput("loadings_transposed", new voTableDataObject("loadings_transposed", loadingsTableTransposed.GetPointer())); this->setOutput("loadingWeights", new voTableDataObject("loadingWeights", loadingWeightsTable.GetPointer())); vtkNew<vtkTable> loadingWeightsTableTransposed; voUtils::transposeTable(loadingWeightsTable.GetPointer(), loadingWeightsTableTransposed.GetPointer(), voUtils::Headers); this->setOutput("loadingWeights_transposed", new voTableDataObject("loadingWeights_transposed", loadingWeightsTableTransposed.GetPointer())); // ------------------------------------------------ // Extract table for Y-loadings vtkNew<vtkTable> yLoadingsTable; { voUtils::arrayToTable(outputArrayData->GetArrayByName("yLoadingsArray"), yLoadingsTable.GetPointer()); // Add column labels (components) for(vtkIdType c = 0; c < yLoadingsTable->GetNumberOfColumns(); ++c) { yLoadingsTable->GetColumn(c)->SetName(QString("Comp %1").arg(c + 1).toLatin1()); } // Add row labels (response analytes) vtkNew<vtkStringArray> headerArr; vtkStringArray* analyteNames = extendedTable->GetRowMetaDataOfInterestAsString(); foreach(int r, responseRangeList) { headerArr->InsertNextValue(analyteNames->GetValue(r)); } voUtils::insertColumnIntoTable(yLoadingsTable.GetPointer(), 0, headerArr.GetPointer()); } this->setOutput("yLoadings", new voTableDataObject("yLoadings", yLoadingsTable.GetPointer())); vtkNew<vtkTable> yLoadingsTableTransposed; voUtils::transposeTable(yLoadingsTable.GetPointer(), yLoadingsTableTransposed.GetPointer(), voUtils::Headers); this->setOutput("yLoadings_transposed", new voTableDataObject("yLoadings_transposed", yLoadingsTableTransposed.GetPointer())); return true; }
Add visualizations to voPLSStatistics
Add visualizations to voPLSStatistics
C++
apache-2.0
Visomics/Visomics,Visomics/Visomics,Visomics/Visomics,arborworkflows/Visomics,arborworkflows/Visomics,arborworkflows/Visomics,Visomics/Visomics,arborworkflows/Visomics,Visomics/Visomics,arborworkflows/Visomics,Visomics/Visomics,arborworkflows/Visomics
41314c8aaeed46f4083d6e1b54ba0e4f0bb769d5
client-server/server.cpp
client-server/server.cpp
#include <iostream> #include <vector> #include <cstdio> #include <cstdlib> #include <cstring> #include <unistd.h> #include <sys/socket.h> #include <sys/poll.h> #include <netinet/in.h> using namespace std; const size_t BUFFER_SIZE = 1024; const int POLL_TIMEOUT = 60 * 1000; void die(const char *message); int main(int argc, char *argv[]) { if (argc < 2) { cerr << "Error: port required" << endl; cerr << "Usage: ./server <port>" << endl; return EXIT_FAILURE; } int server_fd = socket(AF_INET, SOCK_STREAM, 0); if (server_fd < 0) { die("Error on opening socket"); } struct sockaddr_in server_addr, client_addr; server_addr.sin_family = AF_INET; server_addr.sin_addr.s_addr = INADDR_ANY; server_addr.sin_port = htons(atoi(argv[1])); char* buffer = new char[BUFFER_SIZE]; int res; res = bind(server_fd, (struct sockaddr *) &server_addr, sizeof(server_addr)); if (res < 0) { die("Error on binding"); } res = listen(server_fd, SOMAXCONN); if (res < 0) { die("Error on listening"); } vector<struct pollfd> watch_fd(1); watch_fd[0].fd = server_fd; watch_fd[0].events = POLLIN; while (true) { cout << "polling..." << endl; res = poll(watch_fd.data(), watch_fd.size(), POLL_TIMEOUT); if (res < 0) { die("Error on poll()"); } if (res == 0) { cout << "poll() timed out, nothing happend" << endl; continue; } for (size_t i = 1; i < watch_fd.size(); i++) { if (watch_fd[i].revents == 0) { continue; } else { if (watch_fd[i].revents == POLLIN) { memset(buffer, 0, BUFFER_SIZE); res = recv(watch_fd[i].fd, buffer, BUFFER_SIZE, 0); if (res <= 0) { if (res == 0) { cout << "Close connection" << endl; } else { perror("Error on recv()"); } close(watch_fd[i].fd); watch_fd.erase(watch_fd.begin() + i); continue; } cout << "Message: " << buffer << " Length: " << res << endl; string response = "Recv: "; response += buffer; res = send(watch_fd[i].fd, response.c_str(), response.length(), 0); if (res < 0) { perror("Error on send()"); close(watch_fd[i].fd); watch_fd.erase(watch_fd.begin() + i); continue; } watch_fd[i].revents = 0; } else { cerr << "Unexpected events happend" << endl; cout << watch_fd[i].revents << endl; close(watch_fd[i].fd); watch_fd.erase(watch_fd.begin() + i); } } } if (watch_fd[0].revents == POLLIN) { socklen_t client_addr_length = sizeof(client_addr); int client_fd = accept(server_fd, (struct sockaddr *) &client_addr, &client_addr_length); if (client_fd < 0) { die("Error on accept()"); } struct pollfd new_fd; new_fd.fd = client_fd; new_fd.events = POLLIN; watch_fd.push_back(new_fd); watch_fd[0].revents = 0; } } close(server_fd); return EXIT_SUCCESS; } void die(const char *message) { perror(message); exit(EXIT_FAILURE); }
#include <iostream> #include <vector> #include <cstdio> #include <cstdlib> #include <cstring> #include <unistd.h> #include <sys/socket.h> #include <sys/poll.h> #include <netinet/in.h> using namespace std; const size_t BUFFER_SIZE = 1024; const int POLL_TIMEOUT = 60 * 1000; void die(const char *message); int main(int argc, char *argv[]) { if (argc < 2) { cerr << "Error: port required" << endl; cerr << "Usage: ./server <port>" << endl; return EXIT_FAILURE; } int server_fd = socket(AF_INET, SOCK_STREAM, 0); if (server_fd < 0) { die("Error on opening socket"); } struct sockaddr_in server_addr, client_addr; server_addr.sin_family = AF_INET; server_addr.sin_addr.s_addr = INADDR_ANY; server_addr.sin_port = htons(atoi(argv[1])); char* buffer = new char[BUFFER_SIZE]; int res; res = bind(server_fd, (struct sockaddr *) &server_addr, sizeof(server_addr)); if (res < 0) { die("Error on binding"); } res = listen(server_fd, SOMAXCONN); if (res < 0) { die("Error on listening"); } vector<struct pollfd> watch_fd(1); watch_fd[0].fd = server_fd; watch_fd[0].events = POLLIN; while (true) { cout << "polling..." << endl; res = poll(watch_fd.data(), watch_fd.size(), POLL_TIMEOUT); if (res < 0) { die("Error on poll()"); } if (res == 0) { cout << "poll() timed out, nothing happend" << endl; continue; } for (size_t i = 1; i < watch_fd.size(); i++) { if (watch_fd[i].revents == 0) { continue; } else { if (watch_fd[i].revents == POLLIN) { memset(buffer, 0, BUFFER_SIZE); res = recv(watch_fd[i].fd, buffer, BUFFER_SIZE, 0); if (res > 0) { cout << "Message: " << buffer << " Length: " << res << endl; string response = "Recv: "; response += buffer; res = send(watch_fd[i].fd, response.c_str(), response.length(), 0); if (res > 0) { watch_fd[i].revents = 0; continue; } else { perror("Error on send()"); } } else { if (res == 0) { cout << "Close connection" << endl; } else { perror("Error on recv()"); } } } else { cerr << "Unexpected events happend" << endl; cout << watch_fd[i].revents << endl; } close(watch_fd[i].fd); watch_fd.erase(watch_fd.begin() + i); } } if (watch_fd[0].revents == POLLIN) { socklen_t client_addr_length = sizeof(client_addr); int client_fd = accept(server_fd, (struct sockaddr *) &client_addr, &client_addr_length); if (client_fd < 0) { perror("Error on accept()"); } struct pollfd new_fd; new_fd.fd = client_fd; new_fd.events = POLLIN; watch_fd.push_back(new_fd); watch_fd[0].revents = 0; } } close(server_fd); return EXIT_SUCCESS; } void die(const char *message) { perror(message); exit(EXIT_FAILURE); }
revise with new error control
revise with new error control
C++
mit
Preffer/learning-network,Preffer/learning-network
62f8eaa20ebed383e1a586a0a19b03527c205c48
thorlcr/activities/aggregate/thaggregateslave.cpp
thorlcr/activities/aggregate/thaggregateslave.cpp
/*############################################################################## Copyright (C) 2011 HPCC Systems. 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 "platform.h" #include "jlib.hpp" #include "jiface.hpp" // IInterface defined in jlib #include "mpbuff.hpp" #include "mpcomm.hpp" #include "mptag.hpp" #include "eclhelper.hpp" // for IHThorAggregateArg #include "slave.ipp" #include "thbufdef.hpp" #include "thactivityutil.ipp" #include "thaggregateslave.ipp" class AggregateSlaveBase : public CSlaveActivity, public CThorDataLink { public: AggregateSlaveBase(CGraphElementBase *_container) : CSlaveActivity(_container), CThorDataLink(this) { input = NULL; hadElement = false; } const void *getResult(const void *firstRow) { IHThorAggregateArg *helper = (IHThorAggregateArg *)baseHelper.get(); unsigned numPartialResults = container.queryJob().querySlaves(); if (1 == numPartialResults) return firstRow; CThorRowArray partialResults; partialResults.reserve(numPartialResults); partialResults.setRow(0, firstRow); --numPartialResults; size32_t sz; while (numPartialResults--) { CMessageBuffer msg; rank_t sender; if (!receiveMsg(msg, RANK_ALL, mpTag, &sender)) return NULL; if (abortSoon) return NULL; msg.read(sz); if (sz) { assertex(NULL == partialResults.item(sender-1)); CThorStreamDeserializerSource mds(sz, msg.readDirect(sz)); RtlDynamicRowBuilder rowBuilder(queryRowAllocator()); size32_t sz = queryRowDeserializer()->deserialize(rowBuilder, mds); partialResults.setRow(sender-1, rowBuilder.finalizeRowClear(sz)); } } RtlDynamicRowBuilder rowBuilder(queryRowAllocator(), false); bool first = true; numPartialResults = container.queryJob().querySlaves(); unsigned p=0; for (;p<numPartialResults; p++) { const void *row = partialResults.item(p); if (row) { if (first) { first = false; sz = cloneRow(rowBuilder, partialResults.item(p), queryRowMetaData()); } else sz = helper->mergeAggregate(rowBuilder, row); } } if (first) sz = helper->clearAggregate(rowBuilder); return rowBuilder.finalizeRowClear(sz); } void sendResult(const void *row, IOutputRowSerializer *serializer, rank_t dst) { CMessageBuffer mb; size32_t start = mb.length(); size32_t sz = 0; mb.append(sz); if (row&&hadElement) { CMemoryRowSerializer mbs(mb); serializer->serialize(mbs,(const byte *)row); sz = mb.length()-start-sizeof(size32_t); mb.writeDirect(start,sizeof(size32_t),&sz); } container.queryJob().queryJobComm().send(mb, dst, mpTag); } void init(MemoryBuffer &data, MemoryBuffer &slaveData) { if (!container.queryLocal()) mpTag = container.queryJob().deserializeMPTag(data); } virtual void doStopInput() { stopInput(input); } protected: bool hadElement; IThorDataLink *input; }; // class AggregateSlaveActivity : public AggregateSlaveBase { bool eof; IHThorAggregateArg * helper; bool inputStopped; public: IMPLEMENT_IINTERFACE_USING(CSimpleInterface); AggregateSlaveActivity(CGraphElementBase *container) : AggregateSlaveBase(container) { } void init(MemoryBuffer &data, MemoryBuffer &slaveData) { AggregateSlaveBase::init(data, slaveData); appendOutputLinked(this); helper = (IHThorAggregateArg *)queryHelper(); } void abort() { AggregateSlaveBase::abort(); if (firstNode()) cancelReceiveMsg(1, mpTag); } void start() { ActivityTimer s(totalCycles, timeActivities, NULL); eof = false; inputStopped = false; dataLinkStart("AGGREGATE", container.queryId()); input = inputs.item(0); startInput(input); if (input->isGrouped()) ActPrintLog("AGGREGATE: Grouped mismatch"); } void stop() { if (!inputStopped) { inputStopped = true; doStopInput(); } dataLinkStop(); } CATCH_NEXTROW() { ActivityTimer t(totalCycles, timeActivities, NULL); if (abortSoon || eof) return NULL; eof = true; OwnedConstThorRow next = input->ungroupedNextRow(); RtlDynamicRowBuilder resultcr(queryRowAllocator()); size32_t sz = helper->clearAggregate(resultcr); if (next) { hadElement = true; sz = helper->processFirst(resultcr, next); loop { next.setown(input->ungroupedNextRow()); if (!next) break; sz = helper->processNext(resultcr, next); } } inputStopped = true; doStopInput(); if (!firstNode()) { OwnedConstThorRow result(resultcr.finalizeRowClear(sz)); sendResult(result.get(),queryRowSerializer(), 1); // send partial result return NULL; } OwnedConstThorRow ret = getResult(resultcr.finalizeRowClear(sz)); if (ret) { dataLinkIncrement(); return ret.getClear(); } sz = helper->clearAggregate(resultcr); return resultcr.finalizeRowClear(sz); } bool isGrouped() { return false; } void getMetaInfo(ThorDataLinkMetaInfo &info) { initMetaInfo(info); info.singleRowOutput = true; info.totalRowsMin=1; info.totalRowsMax=1; } }; // class ThroughAggregateSlaveActivity : public AggregateSlaveBase { IHThorThroughAggregateArg *helper; RtlDynamicRowBuilder partResult; size32_t partResultSize; bool inputStopped; Owned<IRowInterfaces> aggrowif; public: IMPLEMENT_IINTERFACE_USING(CSimpleInterface); ThroughAggregateSlaveActivity(CGraphElementBase *container) : AggregateSlaveBase(container), partResult(NULL) { partResultSize = 0; } void init(MemoryBuffer &data, MemoryBuffer &slaveData) { AggregateSlaveBase::init(data, slaveData); appendOutputLinked(this); helper = (IHThorThroughAggregateArg *)queryHelper(); } void readRest() { loop { OwnedConstThorRow row = ungroupedNextRow(); if (!row) break; } } void process(const void *r) { if (hadElement) partResultSize = helper->processNext(partResult, r); else { partResultSize = helper->processFirst(partResult, r); hadElement = true; } } void doStopInput() { if (inputStopped) return; inputStopped = true; OwnedConstThorRow partrow = partResult.finalizeRowClear(partResultSize); if (!firstNode()) sendResult(partrow.get(), aggrowif->queryRowSerializer(), 1); else { OwnedConstThorRow ret = getResult(partrow.getClear()); sendResult(ret, aggrowif->queryRowSerializer(), 0); // send to master } AggregateSlaveBase::doStopInput(); dataLinkStop(); } virtual void start() { ActivityTimer s(totalCycles, timeActivities, NULL); dataLinkStart("THROUGHAGGREGATE", container.queryId()); input = inputs.item(0); inputStopped = false; startInput(input); if (input->isGrouped()) ActPrintLog("THROUGHAGGREGATE: Grouped mismatch"); aggrowif.setown(createRowInterfaces(helper->queryAggregateRecordSize(),queryActivityId(),queryCodeContext())); partResult.setAllocator(aggrowif->queryRowAllocator()).ensureRow(); helper->clearAggregate(partResult); } virtual void stop() { if (inputStopped) return; readRest(); doStopInput(); //GH: Shouldn't there be something like the following - in all activities with a member, otherwise the allocator may have gone?? partResult.clear(); } CATCH_NEXTROW() { ActivityTimer t(totalCycles, timeActivities, NULL); if (inputStopped) return NULL; OwnedConstThorRow row = input->ungroupedNextRow(); if (!row) return NULL; process(row); dataLinkIncrement(); return row.getClear(); } bool isGrouped() { return false; } void getMetaInfo(ThorDataLinkMetaInfo &info) { inputs.item(0)->getMetaInfo(info); } }; CActivityBase *createAggregateSlave(CGraphElementBase *container) { //NB: only used if global, createGroupAggregateSlave used if child,local or grouped return new AggregateSlaveActivity(container); } CActivityBase *createThroughAggregateSlave(CGraphElementBase *container) { if (container->queryOwner().queryOwner() && !container->queryOwner().isGlobal()) throwUnexpected(); return new ThroughAggregateSlaveActivity(container); }
/*############################################################################## Copyright (C) 2011 HPCC Systems. 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 "platform.h" #include "jlib.hpp" #include "jiface.hpp" // IInterface defined in jlib #include "mpbuff.hpp" #include "mpcomm.hpp" #include "mptag.hpp" #include "eclhelper.hpp" // for IHThorAggregateArg #include "slave.ipp" #include "thbufdef.hpp" #include "thactivityutil.ipp" #include "thaggregateslave.ipp" class AggregateSlaveBase : public CSlaveActivity, public CThorDataLink { protected: bool hadElement; IThorDataLink *input; public: AggregateSlaveBase(CGraphElementBase *_container) : CSlaveActivity(_container), CThorDataLink(this) { input = NULL; hadElement = false; } const void *getResult(const void *firstRow) { IHThorAggregateArg *helper = (IHThorAggregateArg *)baseHelper.get(); unsigned numPartialResults = container.queryJob().querySlaves(); if (1 == numPartialResults) return firstRow; CThorRowArray partialResults; partialResults.reserve(numPartialResults); partialResults.setRow(0, firstRow); --numPartialResults; size32_t sz; while (numPartialResults--) { CMessageBuffer msg; rank_t sender; if (!receiveMsg(msg, RANK_ALL, mpTag, &sender)) return NULL; if (abortSoon) return NULL; msg.read(sz); if (sz) { assertex(NULL == partialResults.item(sender-1)); CThorStreamDeserializerSource mds(sz, msg.readDirect(sz)); RtlDynamicRowBuilder rowBuilder(queryRowAllocator()); size32_t sz = queryRowDeserializer()->deserialize(rowBuilder, mds); partialResults.setRow(sender-1, rowBuilder.finalizeRowClear(sz)); } } RtlDynamicRowBuilder rowBuilder(queryRowAllocator(), false); bool first = true; numPartialResults = container.queryJob().querySlaves(); unsigned p=0; for (;p<numPartialResults; p++) { const void *row = partialResults.item(p); if (row) { if (first) { first = false; sz = cloneRow(rowBuilder, partialResults.item(p), queryRowMetaData()); } else sz = helper->mergeAggregate(rowBuilder, row); } } if (first) sz = helper->clearAggregate(rowBuilder); return rowBuilder.finalizeRowClear(sz); } void sendResult(const void *row, IOutputRowSerializer *serializer, rank_t dst) { CMessageBuffer mb; size32_t start = mb.length(); size32_t sz = 0; mb.append(sz); if (row&&hadElement) { CMemoryRowSerializer mbs(mb); serializer->serialize(mbs,(const byte *)row); sz = mb.length()-start-sizeof(size32_t); mb.writeDirect(start,sizeof(size32_t),&sz); } container.queryJob().queryJobComm().send(mb, dst, mpTag); } void init(MemoryBuffer &data, MemoryBuffer &slaveData) { if (!container.queryLocal()) mpTag = container.queryJob().deserializeMPTag(data); } void start() { hadElement = false; } virtual void doStopInput() { stopInput(input); } }; // class AggregateSlaveActivity : public AggregateSlaveBase { bool eof; IHThorAggregateArg * helper; bool inputStopped; public: IMPLEMENT_IINTERFACE_USING(CSimpleInterface); AggregateSlaveActivity(CGraphElementBase *container) : AggregateSlaveBase(container) { } void init(MemoryBuffer &data, MemoryBuffer &slaveData) { AggregateSlaveBase::init(data, slaveData); appendOutputLinked(this); helper = (IHThorAggregateArg *)queryHelper(); } void abort() { AggregateSlaveBase::abort(); if (firstNode()) cancelReceiveMsg(1, mpTag); } void start() { ActivityTimer s(totalCycles, timeActivities, NULL); AggregateSlaveBase::start(); eof = false; inputStopped = false; dataLinkStart("AGGREGATE", container.queryId()); input = inputs.item(0); startInput(input); if (input->isGrouped()) ActPrintLog("AGGREGATE: Grouped mismatch"); } void stop() { if (!inputStopped) { inputStopped = true; doStopInput(); } dataLinkStop(); } CATCH_NEXTROW() { ActivityTimer t(totalCycles, timeActivities, NULL); if (abortSoon || eof) return NULL; eof = true; OwnedConstThorRow next = input->ungroupedNextRow(); RtlDynamicRowBuilder resultcr(queryRowAllocator()); size32_t sz = helper->clearAggregate(resultcr); if (next) { hadElement = true; sz = helper->processFirst(resultcr, next); loop { next.setown(input->ungroupedNextRow()); if (!next) break; sz = helper->processNext(resultcr, next); } } inputStopped = true; doStopInput(); if (!firstNode()) { OwnedConstThorRow result(resultcr.finalizeRowClear(sz)); sendResult(result.get(),queryRowSerializer(), 1); // send partial result return NULL; } OwnedConstThorRow ret = getResult(resultcr.finalizeRowClear(sz)); if (ret) { dataLinkIncrement(); return ret.getClear(); } sz = helper->clearAggregate(resultcr); return resultcr.finalizeRowClear(sz); } bool isGrouped() { return false; } void getMetaInfo(ThorDataLinkMetaInfo &info) { initMetaInfo(info); info.singleRowOutput = true; info.totalRowsMin=1; info.totalRowsMax=1; } }; // class ThroughAggregateSlaveActivity : public AggregateSlaveBase { IHThorThroughAggregateArg *helper; RtlDynamicRowBuilder partResult; size32_t partResultSize; bool inputStopped; Owned<IRowInterfaces> aggrowif; public: IMPLEMENT_IINTERFACE_USING(CSimpleInterface); ThroughAggregateSlaveActivity(CGraphElementBase *container) : AggregateSlaveBase(container), partResult(NULL) { partResultSize = 0; } void init(MemoryBuffer &data, MemoryBuffer &slaveData) { AggregateSlaveBase::init(data, slaveData); appendOutputLinked(this); helper = (IHThorThroughAggregateArg *)queryHelper(); } void readRest() { loop { OwnedConstThorRow row = ungroupedNextRow(); if (!row) break; } } void process(const void *r) { if (hadElement) partResultSize = helper->processNext(partResult, r); else { partResultSize = helper->processFirst(partResult, r); hadElement = true; } } void doStopInput() { if (inputStopped) return; inputStopped = true; OwnedConstThorRow partrow = partResult.finalizeRowClear(partResultSize); if (!firstNode()) sendResult(partrow.get(), aggrowif->queryRowSerializer(), 1); else { OwnedConstThorRow ret = getResult(partrow.getClear()); sendResult(ret, aggrowif->queryRowSerializer(), 0); // send to master } AggregateSlaveBase::doStopInput(); dataLinkStop(); } virtual void start() { ActivityTimer s(totalCycles, timeActivities, NULL); dataLinkStart("THROUGHAGGREGATE", container.queryId()); input = inputs.item(0); inputStopped = false; startInput(input); if (input->isGrouped()) ActPrintLog("THROUGHAGGREGATE: Grouped mismatch"); aggrowif.setown(createRowInterfaces(helper->queryAggregateRecordSize(),queryActivityId(),queryCodeContext())); partResult.setAllocator(aggrowif->queryRowAllocator()).ensureRow(); helper->clearAggregate(partResult); } virtual void stop() { if (inputStopped) return; readRest(); doStopInput(); //GH: Shouldn't there be something like the following - in all activities with a member, otherwise the allocator may have gone?? partResult.clear(); } CATCH_NEXTROW() { ActivityTimer t(totalCycles, timeActivities, NULL); if (inputStopped) return NULL; OwnedConstThorRow row = input->ungroupedNextRow(); if (!row) return NULL; process(row); dataLinkIncrement(); return row.getClear(); } bool isGrouped() { return false; } void getMetaInfo(ThorDataLinkMetaInfo &info) { inputs.item(0)->getMetaInfo(info); } }; CActivityBase *createAggregateSlave(CGraphElementBase *container) { //NB: only used if global, createGroupAggregateSlave used if child,local or grouped return new AggregateSlaveActivity(container); } CActivityBase *createThroughAggregateSlave(CGraphElementBase *container) { if (container->queryOwner().queryOwner() && !container->queryOwner().isGlobal()) throwUnexpected(); return new ThroughAggregateSlaveActivity(container); }
Fix potential aggregate child query issue
Fix potential aggregate child query issue Failing to reset a boolean (hadElement), could call processNext instead of processFirst on next child query. Or sendResult spuriously if no records on next run. Signed-off-by: Jake Smith <[email protected]>
C++
agpl-3.0
afishbeck/HPCC-Platform,afishbeck/HPCC-Platform,afishbeck/HPCC-Platform,afishbeck/HPCC-Platform,afishbeck/HPCC-Platform,afishbeck/HPCC-Platform
784a5a6a181035896ec42b45a28a10ce6e891882
src/tests/runtime_tests.cpp
src/tests/runtime_tests.cpp
// Copyright 2008 Paul Hodge #include "branch.h" #include "builtins.h" #include "cpp_interface.h" #include "introspection.h" #include "parser.h" #include "runtime.h" #include "testing.h" #include "term.h" #include "type.h" #include "ref_list.h" #include "values.h" namespace circa { namespace runtime_tests { void safe_delete() { Branch branch; Term* term1 = apply_statement(branch, "term1 = 1"); Term* termSum = apply_statement(branch, "sum = add(term1,2)"); test_assert(branch.containsName("term1")); test_assert(branch.containsName("sum")); test_assert(termSum->inputs[0] == term1); delete term1; test_assert(termSum->inputs[0] == NULL); test_assert(!branch.containsName("term1")); for (int i=0; i < branch.numTerms(); i++) { if (branch[i] == term1) test_fail(); } } void test_create_var() { Branch branch; Term *term = create_var(&branch, INT_TYPE); test_assert(term->type == INT_TYPE); } void test_int_var() { Branch branch; Term *term = int_var(branch, -2); test_assert(as_int(term) == -2); Term *term2 = int_var(branch, 154, "george"); test_assert(term2 == branch.getNamed("george")); test_assert(term2->name == "george"); test_assert(as_int(term2) == 154); } void test_misc() { test_assert(is_type(TYPE_TYPE)); test_assert(TYPE_TYPE->type == TYPE_TYPE); test_assert(is_type(FUNCTION_TYPE)); test_assert(FUNCTION_TYPE->type == TYPE_TYPE); } void test_find_existing_equivalent() { Branch branch; Term* add_func = eval_statement(branch, "add"); Term* a = eval_statement(branch, "a = 1"); Term* b = eval_statement(branch, "b = 1"); Term* addition = eval_statement(branch, "add(a,b)"); test_assert(is_equivalent(addition, add_func, ReferenceList(a,b))); test_assert(addition == find_equivalent(add_func, ReferenceList(a,b))); test_assert(NULL == find_equivalent(add_func, ReferenceList(b,a))); Term* another_addition = eval_statement(branch, "add(a,b)"); test_assert(addition == another_addition); Term* a_different_addition = eval_statement(branch, "add(b,a)"); test_assert(addition != a_different_addition); } void var_function_reuse() { Branch branch; Term* function = get_var_function(branch, INT_TYPE); Term* function2 = get_var_function(branch, INT_TYPE); test_assert(function == function2); Term* a = int_var(branch, 3); Term* b = int_var(branch, 4); test_assert(a->function == b->function); } void null_input_errors() { Branch branch; Term* one = float_var(branch, 1.0); Term* term1 = apply_function(branch, get_global("add"), ReferenceList(NULL, one)); evaluate_term(term1); test_assert(term1->hasError()); test_assert(term1->getErrorMessage() == "Input 0 is NULL"); term1->function = NULL; evaluate_term(term1); test_assert(term1->hasError()); test_assert(term1->getErrorMessage() == "Function is NULL"); Term* term2 = apply_function(branch, get_global("add"), ReferenceList(one, NULL)); evaluate_term(term2); test_assert(term2->hasError()); test_assert(term2->getErrorMessage() == "Input 1 is NULL"); set_input(term2, 1, one); evaluate_term(term2); test_assert(!term2->hasError()); test_assert(term2->getErrorMessage() == ""); test_assert(term2->asFloat() == 2.0); } void test_eval_as() { test_assert(eval_as<float>("add(1.0,2.0)") == 3); } void test_runtime_type_error() { // this test might become invalid when compile-time type checking is added Branch branch; Term* term = eval_statement(branch, "add('hello', true)"); evaluate_term(term); test_assert(term->hasError()); } } // namespace runtime_tests void register_runtime_tests() { REGISTER_TEST_CASE(runtime_tests::safe_delete); REGISTER_TEST_CASE(runtime_tests::test_create_var); REGISTER_TEST_CASE(runtime_tests::test_int_var); REGISTER_TEST_CASE(runtime_tests::test_misc); REGISTER_TEST_CASE(runtime_tests::test_find_existing_equivalent); REGISTER_TEST_CASE(runtime_tests::var_function_reuse); REGISTER_TEST_CASE(runtime_tests::null_input_errors); REGISTER_TEST_CASE(runtime_tests::test_eval_as); REGISTER_TEST_CASE(runtime_tests::test_runtime_type_error); } } // namespace circa
// Copyright 2008 Paul Hodge #include "branch.h" #include "builtins.h" #include "cpp_interface.h" #include "introspection.h" #include "parser.h" #include "runtime.h" #include "testing.h" #include "term.h" #include "type.h" #include "ref_list.h" #include "values.h" namespace circa { namespace runtime_tests { void test_create_var() { Branch branch; Term *term = create_var(&branch, INT_TYPE); test_assert(term->type == INT_TYPE); } void test_int_var() { Branch branch; Term *term = int_var(branch, -2); test_assert(as_int(term) == -2); Term *term2 = int_var(branch, 154, "george"); test_assert(term2 == branch.getNamed("george")); test_assert(term2->name == "george"); test_assert(as_int(term2) == 154); } void test_misc() { test_assert(is_type(TYPE_TYPE)); test_assert(TYPE_TYPE->type == TYPE_TYPE); test_assert(is_type(FUNCTION_TYPE)); test_assert(FUNCTION_TYPE->type == TYPE_TYPE); } void test_find_existing_equivalent() { Branch branch; Term* add_func = eval_statement(branch, "add"); Term* a = eval_statement(branch, "a = 1"); Term* b = eval_statement(branch, "b = 1"); Term* addition = eval_statement(branch, "add(a,b)"); test_assert(is_equivalent(addition, add_func, ReferenceList(a,b))); test_assert(addition == find_equivalent(add_func, ReferenceList(a,b))); test_assert(NULL == find_equivalent(add_func, ReferenceList(b,a))); Term* another_addition = eval_statement(branch, "add(a,b)"); test_assert(addition == another_addition); Term* a_different_addition = eval_statement(branch, "add(b,a)"); test_assert(addition != a_different_addition); } void var_function_reuse() { Branch branch; Term* function = get_var_function(branch, INT_TYPE); Term* function2 = get_var_function(branch, INT_TYPE); test_assert(function == function2); Term* a = int_var(branch, 3); Term* b = int_var(branch, 4); test_assert(a->function == b->function); } void null_input_errors() { Branch branch; Term* one = float_var(branch, 1.0); Term* term1 = apply_function(branch, get_global("add"), ReferenceList(NULL, one)); evaluate_term(term1); test_assert(term1->hasError()); test_assert(term1->getErrorMessage() == "Input 0 is NULL"); term1->function = NULL; evaluate_term(term1); test_assert(term1->hasError()); test_assert(term1->getErrorMessage() == "Function is NULL"); Term* term2 = apply_function(branch, get_global("add"), ReferenceList(one, NULL)); evaluate_term(term2); test_assert(term2->hasError()); test_assert(term2->getErrorMessage() == "Input 1 is NULL"); set_input(term2, 1, one); evaluate_term(term2); test_assert(!term2->hasError()); test_assert(term2->getErrorMessage() == ""); test_assert(term2->asFloat() == 2.0); } void test_eval_as() { test_assert(eval_as<float>("add(1.0,2.0)") == 3); } void test_runtime_type_error() { // this test might become invalid when compile-time type checking is added Branch branch; Term* term = eval_statement(branch, "add('hello', true)"); evaluate_term(term); test_assert(term->hasError()); } } // namespace runtime_tests void register_runtime_tests() { REGISTER_TEST_CASE(runtime_tests::test_create_var); REGISTER_TEST_CASE(runtime_tests::test_int_var); REGISTER_TEST_CASE(runtime_tests::test_misc); REGISTER_TEST_CASE(runtime_tests::test_find_existing_equivalent); REGISTER_TEST_CASE(runtime_tests::var_function_reuse); REGISTER_TEST_CASE(runtime_tests::null_input_errors); REGISTER_TEST_CASE(runtime_tests::test_eval_as); REGISTER_TEST_CASE(runtime_tests::test_runtime_type_error); } } // namespace circa
Remove runtime_tests::safe_delete, this kind of deletion is no longer allowed
Remove runtime_tests::safe_delete, this kind of deletion is no longer allowed
C++
mit
andyfischer/circa,andyfischer/circa,andyfischer/circa,andyfischer/circa
25231b4e330571d46b68c5641c1317b4fc8fc92c
thorlcr/activities/nsplitter/thnsplitterslave.cpp
thorlcr/activities/nsplitter/thnsplitterslave.cpp
/*############################################################################## Copyright (C) 2011 HPCC Systems. 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 "thnsplitterslave.ipp" #include "thbuf.hpp" #include "thormisc.hpp" #include "thexception.hpp" #include "thbufdef.hpp" interface ISharedSmartBuffer; class NSplitterSlaveActivity; class CSplitterOutputBase : public CSimpleInterface, implements IRowStream { public: IMPLEMENT_IINTERFACE_USING(CSimpleInterface); virtual void start() = 0; virtual void getMetaInfo(ThorDataLinkMetaInfo &info) = 0; }; class CSplitterOutput : public CSplitterOutputBase { NSplitterSlaveActivity &activity; unsigned __int64 totalCycles; unsigned output; rowcount_t rec, max; public: IMPLEMENT_IINTERFACE_USING(CSimpleInterface); CSplitterOutput(NSplitterSlaveActivity &_activity, unsigned output); virtual void getMetaInfo(ThorDataLinkMetaInfo &info); void addCycles(unsigned __int64 elapsedCycles); virtual void start(); virtual void stop(); virtual const void *nextRow(); unsigned __int64 queryTotalCycles() const; }; #ifdef TIME_ACTIVITIES struct Timer : public ActivityTimer { CSplitterOutput &output; unsigned __int64 elapsedCycles; inline Timer(CSplitterOutput &_output, const bool &enabled) : ActivityTimer(elapsedCycles, enabled, NULL), output(_output) { } inline ~Timer() { if (enabled) output.addCycles(elapsedCycles); } }; #else //optimized away completely? struct Timer { inline Timer(CSplitterOutput &_output, const bool &enabled) { } }; #endif // // NSplitterSlaveActivity // class NSplitterSlaveActivity : public CSlaveActivity { bool spill; bool eofHit; bool inputsConfigured; CriticalSection startLock; unsigned nstopped; rowcount_t recsReady; SpinLock timingLock; IThorDataLink *input; bool grouped; Owned<IException> startException, writeAheadException; Owned<ISharedSmartBuffer> smartBuf; class CWriter : public CSimpleInterface, IThreaded { NSplitterSlaveActivity &parent; CThreadedPersistent threaded; Semaphore sem; bool stopped; rowcount_t writerMax; unsigned requestN; SpinLock recLock; public: CWriter(NSplitterSlaveActivity &_parent) : parent(_parent), threaded("CWriter", this) { stopped = true; writerMax = 0; requestN = 1000; } ~CWriter() { stop(); } virtual void main() { loop { sem.wait(); if (stopped) break; rowcount_t request; { SpinBlock block(recLock); request = writerMax; } parent.writeahead(request, stopped); if (parent.eofHit) break; } } void start() { stopped = false; writerMax = 0; threaded.start(); } virtual void stop() { if (!stopped) { stopped = true; sem.signal(); threaded.join(); } } void more(rowcount_t &max) // called if output hit it's max, returns new max { if (stopped) return; SpinBlock block(recLock); if (writerMax <= max) { writerMax += requestN; sem.signal(); } max = writerMax; } } writer; class CNullInput : public CSplitterOutputBase { public: IMPLEMENT_IINTERFACE_USING(CSimpleInterface); virtual const void *nextRow() { throwUnexpected(); return NULL; } virtual void stop() { throwUnexpected(); } virtual void start() { throwUnexpected(); } virtual void getMetaInfo(ThorDataLinkMetaInfo &info) { info.totalRowsMin=0; info.totalRowsMax=0; } }; class CInputWrapper : public CSplitterOutputBase { IThorDataLink *input; NSplitterSlaveActivity &activity; public: IMPLEMENT_IINTERFACE_USING(CSimpleInterface); CInputWrapper(NSplitterSlaveActivity &_activity, IThorDataLink *_input) : activity(_activity), input(_input) { } virtual const void *nextRow() { return input->nextRow(); } virtual void stop() { input->stop(); } virtual void start() { input->start(); } virtual void getMetaInfo(ThorDataLinkMetaInfo &info) { input->getMetaInfo(info); } }; class CDelayedInput : public CSimpleInterface, public CThorDataLink { Owned<CSplitterOutputBase> input; NSplitterSlaveActivity &activity; unsigned id; public: IMPLEMENT_IINTERFACE_USING(CSimpleInterface); CDelayedInput(NSplitterSlaveActivity &_activity) : CThorDataLink(&_activity), activity(_activity), id(0) { } void setInput(CSplitterOutputBase *_input, unsigned _id=0) { input.setown(_input); id = _id; } virtual const void *nextRow() { OwnedConstThorRow row = input->nextRow(); if (row) dataLinkIncrement(); return row.getClear(); } virtual void stop() { input->stop(); dataLinkStop(); } // IThorDataLink impl. virtual void start() { activity.ensureInputsConfigured(); input->start(); dataLinkStart("SPLITTEROUTPUT", activity.queryContainer().queryId(), id); } virtual bool isGrouped() { return activity.inputs.item(0)->isGrouped(); } virtual void getMetaInfo(ThorDataLinkMetaInfo &info) { initMetaInfo(info); input->getMetaInfo(info); } }; public: IMPLEMENT_IINTERFACE_USING(CSimpleInterface); NSplitterSlaveActivity(CGraphElementBase *container) : CSlaveActivity(container), writer(*this) { spill = false; input = NULL; nstopped = 0; eofHit = inputsConfigured = false; recsReady = 0; } void ensureInputsConfigured() { CriticalBlock block(startLock); if (inputsConfigured) return; inputsConfigured = true; unsigned noutputs = container.connectedOutputs.getCount(); if (1 == noutputs) { CIOConnection *io = NULL; ForEachItemIn(o, container.connectedOutputs) { io = container.connectedOutputs.item(o); if (io) break; } assertex(io); ForEachItemIn(o2, outputs) { CDelayedInput *delayedInput = (CDelayedInput *)outputs.item(o2); if (o2 == o) delayedInput->setInput(new CInputWrapper(*this, inputs.item(0))); else delayedInput->setInput(new CNullInput()); } } else { ForEachItemIn(o, outputs) { CDelayedInput *delayedInput = (CDelayedInput *)outputs.item(o); if (NULL != container.connectedOutputs.queryItem(o)) delayedInput->setInput(new CSplitterOutput(*this, o), o); else delayedInput->setInput(new CNullInput()); } } } void reset() { CSlaveActivity::reset(); nstopped = 0; grouped = false; eofHit = false; recsReady = 0; inputsConfigured = false; } void init(MemoryBuffer &data, MemoryBuffer &slaveData) { ForEachItemIn(o, container.outputs) appendOutput(new CDelayedInput(*this)); IHThorSplitArg *helper = (IHThorSplitArg *)queryHelper(); int dV = (int)container.queryJob().getWorkUnitValueInt("splitterSpills", -1); if (-1 == dV) { spill = !helper->isBalanced(); bool forcedUnbalanced = queryContainer().queryXGMML().getPropBool("@unbalanced", false); if (!spill && forcedUnbalanced) { ActPrintLog("Was marked balanced, but forced unbalanced due to UPDATE changes."); spill = true; } } else spill = dV>0; } inline void more(rowcount_t &max) { writer.more(max); } void prepareInput(unsigned output) { CriticalBlock block(startLock); if (!input) { input = inputs.item(0); try { startInput(input); grouped = input->isGrouped(); nstopped = outputs.ordinality(); if (smartBuf) smartBuf->reset(); else { if (spill) { StringBuffer tempname; GetTempName(tempname,"nsplit",true); // use alt temp dir smartBuf.setown(createSharedSmartDiskBuffer(this, tempname.str(), outputs.ordinality(), queryRowInterfaces(input), &container.queryJob().queryIDiskUsage())); ActPrintLog("Using temp spill file: %s", tempname.str()); } else { ActPrintLog("Spill is 'balanced'"); smartBuf.setown(createSharedSmartMemBuffer(this, outputs.ordinality(), queryRowInterfaces(input), NSPLITTER_SPILL_BUFFER_SIZE)); } } writer.start(); } catch (IException *e) { startException.setown(e); } } } inline const void *nextRow(unsigned output) { OwnedConstThorRow row = smartBuf->queryOutput(output)->nextRow(); // will block until available if (writeAheadException) throw LINK(writeAheadException); return row.getClear(); } void writeahead(const rowcount_t &requested, const bool &stopped) { if (eofHit) return; OwnedConstThorRow row; loop { if (abortSoon || stopped || requested<recsReady) break; try { row.setown(input->nextRow()); if (!row) { row.setown(input->nextRow()); if (row) { ++recsReady; smartBuf->putRow(NULL); } } } catch (IException *e) { writeAheadException.setown(e); } if (!row || writeAheadException.get()) { ActPrintLog("Splitter activity, hit end of input @ rec = %"RCPF"d", recsReady); eofHit = true; smartBuf->flush(); // signals no more rows will be written. break; } ++recsReady; smartBuf->putRow(row.getClear()); // can block if mem limited, but other readers can progress which is the point } } void inputStopped() { if (nstopped && --nstopped==0) { writer.stop(); stopInput(input); input = NULL; } } void abort() { CSlaveActivity::abort(); if (smartBuf) smartBuf->cancel(); } friend class CInputWrapper; friend class CSplitterOutput; friend class CWriter; }; // // CSplitterOutput // CSplitterOutput::CSplitterOutput(NSplitterSlaveActivity &_activity, unsigned _output) : activity(_activity), output(_output) { rec = max = 0; totalCycles = 0; } void CSplitterOutput::addCycles(unsigned __int64 elapsedCycles) { totalCycles += elapsedCycles; // per output SpinBlock b(activity.timingLock); activity.getTotalCyclesRef() += elapsedCycles; // Splitter act aggregate time. } // IThorDataLink void CSplitterOutput::start() { Timer s(*this, activity.queryTimeActivities()); rec = max = 0; activity.prepareInput(output); if (activity.startException) throw LINK(activity.startException); } void CSplitterOutput::stop() { CriticalBlock block(activity.startLock); activity.smartBuf->queryOutput(output)->stop(); activity.inputStopped(); } const void *CSplitterOutput::nextRow() { Timer t(*this, activity.queryTimeActivities()); if (rec == max) activity.more(max); const void *row = activity.nextRow(output); // pass ptr to max if need more ++rec; return row; } void CSplitterOutput::getMetaInfo(ThorDataLinkMetaInfo &info) { info.canStall = !activity.spill; CThorDataLink::calcMetaInfoSize(info, activity.inputs.item(0)); } unsigned __int64 CSplitterOutput::queryTotalCycles() const { return totalCycles; } CActivityBase *createNSplitterSlave(CGraphElementBase *container) { return new NSplitterSlaveActivity(container); }
/*############################################################################## Copyright (C) 2011 HPCC Systems. 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 "thnsplitterslave.ipp" #include "thbuf.hpp" #include "thormisc.hpp" #include "thexception.hpp" #include "thbufdef.hpp" interface ISharedSmartBuffer; class NSplitterSlaveActivity; class CSplitterOutputBase : public CSimpleInterface, implements IRowStream { public: IMPLEMENT_IINTERFACE_USING(CSimpleInterface); virtual void start() = 0; virtual void getMetaInfo(ThorDataLinkMetaInfo &info) = 0; }; class CSplitterOutput : public CSplitterOutputBase { NSplitterSlaveActivity &activity; unsigned __int64 totalCycles; unsigned output; rowcount_t rec, max; public: IMPLEMENT_IINTERFACE_USING(CSimpleInterface); CSplitterOutput(NSplitterSlaveActivity &_activity, unsigned output); virtual void getMetaInfo(ThorDataLinkMetaInfo &info); void addCycles(unsigned __int64 elapsedCycles); virtual void start(); virtual void stop(); virtual const void *nextRow(); unsigned __int64 queryTotalCycles() const; }; #ifdef TIME_ACTIVITIES struct Timer : public ActivityTimer { CSplitterOutput &output; unsigned __int64 elapsedCycles; inline Timer(CSplitterOutput &_output, const bool &enabled) : ActivityTimer(elapsedCycles, enabled, NULL), output(_output) { } inline ~Timer() { if (enabled) output.addCycles(elapsedCycles); } }; #else //optimized away completely? struct Timer { inline Timer(CSplitterOutput &_output, const bool &enabled) { } }; #endif // // NSplitterSlaveActivity // class NSplitterSlaveActivity : public CSlaveActivity { bool spill; bool eofHit; bool inputsConfigured; CriticalSection startLock; unsigned nstopped; rowcount_t recsReady; SpinLock timingLock; IThorDataLink *input; bool grouped; Owned<IException> startException, writeAheadException; Owned<ISharedSmartBuffer> smartBuf; class CWriter : public CSimpleInterface, IThreaded { NSplitterSlaveActivity &parent; CThreadedPersistent threaded; Semaphore sem; bool stopped; rowcount_t writerMax; unsigned requestN; SpinLock recLock; public: CWriter(NSplitterSlaveActivity &_parent) : parent(_parent), threaded("CWriter", this) { stopped = true; writerMax = 0; requestN = 1000; } ~CWriter() { stop(); } virtual void main() { loop { sem.wait(); if (stopped) break; rowcount_t request; { SpinBlock block(recLock); request = writerMax; } parent.writeahead(request, stopped); if (parent.eofHit) break; } } void start() { stopped = false; writerMax = 0; threaded.start(); } virtual void stop() { if (!stopped) { stopped = true; sem.signal(); threaded.join(); } } void more(rowcount_t &max) // called if output hit it's max, returns new max { if (stopped) return; SpinBlock block(recLock); if (writerMax <= max) { writerMax += requestN; sem.signal(); } max = writerMax; } } writer; class CNullInput : public CSplitterOutputBase { public: IMPLEMENT_IINTERFACE_USING(CSimpleInterface); virtual const void *nextRow() { throwUnexpected(); return NULL; } virtual void stop() { throwUnexpected(); } virtual void start() { throwUnexpected(); } virtual void getMetaInfo(ThorDataLinkMetaInfo &info) { info.totalRowsMin=0; info.totalRowsMax=0; } }; class CInputWrapper : public CSplitterOutputBase { IThorDataLink *input; NSplitterSlaveActivity &activity; public: IMPLEMENT_IINTERFACE_USING(CSimpleInterface); CInputWrapper(NSplitterSlaveActivity &_activity, IThorDataLink *_input) : activity(_activity), input(_input) { } virtual const void *nextRow() { return input->nextRow(); } virtual void stop() { input->stop(); } virtual void start() { input->start(); } virtual void getMetaInfo(ThorDataLinkMetaInfo &info) { input->getMetaInfo(info); } }; class CDelayedInput : public CSimpleInterface, public CThorDataLink { Owned<CSplitterOutputBase> input; NSplitterSlaveActivity &activity; unsigned id; public: IMPLEMENT_IINTERFACE_USING(CSimpleInterface); CDelayedInput(NSplitterSlaveActivity &_activity) : CThorDataLink(&_activity), activity(_activity), id(0) { } void setInput(CSplitterOutputBase *_input, unsigned _id=0) { input.setown(_input); id = _id; } virtual const void *nextRow() { OwnedConstThorRow row = input->nextRow(); if (row) dataLinkIncrement(); return row.getClear(); } virtual void stop() { input->stop(); dataLinkStop(); } // IThorDataLink impl. virtual void start() { activity.ensureInputsConfigured(); input->start(); dataLinkStart("SPLITTEROUTPUT", activity.queryContainer().queryId(), id); } virtual bool isGrouped() { return activity.inputs.item(0)->isGrouped(); } virtual void getMetaInfo(ThorDataLinkMetaInfo &info) { initMetaInfo(info); if (input) input->getMetaInfo(info); else activity.inputs.item(0)->getMetaInfo(info); } }; public: IMPLEMENT_IINTERFACE_USING(CSimpleInterface); NSplitterSlaveActivity(CGraphElementBase *container) : CSlaveActivity(container), writer(*this) { spill = false; input = NULL; nstopped = 0; eofHit = inputsConfigured = false; recsReady = 0; } void ensureInputsConfigured() { CriticalBlock block(startLock); if (inputsConfigured) return; inputsConfigured = true; unsigned noutputs = container.connectedOutputs.getCount(); if (1 == noutputs) { CIOConnection *io = NULL; ForEachItemIn(o, container.connectedOutputs) { io = container.connectedOutputs.item(o); if (io) break; } assertex(io); ForEachItemIn(o2, outputs) { CDelayedInput *delayedInput = (CDelayedInput *)outputs.item(o2); if (o2 == o) delayedInput->setInput(new CInputWrapper(*this, inputs.item(0))); else delayedInput->setInput(new CNullInput()); } } else { ForEachItemIn(o, outputs) { CDelayedInput *delayedInput = (CDelayedInput *)outputs.item(o); if (NULL != container.connectedOutputs.queryItem(o)) delayedInput->setInput(new CSplitterOutput(*this, o), o); else delayedInput->setInput(new CNullInput()); } } } void reset() { CSlaveActivity::reset(); nstopped = 0; grouped = false; eofHit = false; recsReady = 0; inputsConfigured = false; } void init(MemoryBuffer &data, MemoryBuffer &slaveData) { ForEachItemIn(o, container.outputs) appendOutput(new CDelayedInput(*this)); IHThorSplitArg *helper = (IHThorSplitArg *)queryHelper(); int dV = (int)container.queryJob().getWorkUnitValueInt("splitterSpills", -1); if (-1 == dV) { spill = !helper->isBalanced(); bool forcedUnbalanced = queryContainer().queryXGMML().getPropBool("@unbalanced", false); if (!spill && forcedUnbalanced) { ActPrintLog("Was marked balanced, but forced unbalanced due to UPDATE changes."); spill = true; } } else spill = dV>0; } inline void more(rowcount_t &max) { writer.more(max); } void prepareInput(unsigned output) { CriticalBlock block(startLock); if (!input) { input = inputs.item(0); try { startInput(input); grouped = input->isGrouped(); nstopped = outputs.ordinality(); if (smartBuf) smartBuf->reset(); else { if (spill) { StringBuffer tempname; GetTempName(tempname,"nsplit",true); // use alt temp dir smartBuf.setown(createSharedSmartDiskBuffer(this, tempname.str(), outputs.ordinality(), queryRowInterfaces(input), &container.queryJob().queryIDiskUsage())); ActPrintLog("Using temp spill file: %s", tempname.str()); } else { ActPrintLog("Spill is 'balanced'"); smartBuf.setown(createSharedSmartMemBuffer(this, outputs.ordinality(), queryRowInterfaces(input), NSPLITTER_SPILL_BUFFER_SIZE)); } } writer.start(); } catch (IException *e) { startException.setown(e); } } } inline const void *nextRow(unsigned output) { OwnedConstThorRow row = smartBuf->queryOutput(output)->nextRow(); // will block until available if (writeAheadException) throw LINK(writeAheadException); return row.getClear(); } void writeahead(const rowcount_t &requested, const bool &stopped) { if (eofHit) return; OwnedConstThorRow row; loop { if (abortSoon || stopped || requested<recsReady) break; try { row.setown(input->nextRow()); if (!row) { row.setown(input->nextRow()); if (row) { ++recsReady; smartBuf->putRow(NULL); } } } catch (IException *e) { writeAheadException.setown(e); } if (!row || writeAheadException.get()) { ActPrintLog("Splitter activity, hit end of input @ rec = %"RCPF"d", recsReady); eofHit = true; smartBuf->flush(); // signals no more rows will be written. break; } ++recsReady; smartBuf->putRow(row.getClear()); // can block if mem limited, but other readers can progress which is the point } } void inputStopped() { if (nstopped && --nstopped==0) { writer.stop(); stopInput(input); input = NULL; } } void abort() { CSlaveActivity::abort(); if (smartBuf) smartBuf->cancel(); } friend class CInputWrapper; friend class CSplitterOutput; friend class CWriter; }; // // CSplitterOutput // CSplitterOutput::CSplitterOutput(NSplitterSlaveActivity &_activity, unsigned _output) : activity(_activity), output(_output) { rec = max = 0; totalCycles = 0; } void CSplitterOutput::addCycles(unsigned __int64 elapsedCycles) { totalCycles += elapsedCycles; // per output SpinBlock b(activity.timingLock); activity.getTotalCyclesRef() += elapsedCycles; // Splitter act aggregate time. } // IThorDataLink void CSplitterOutput::start() { Timer s(*this, activity.queryTimeActivities()); rec = max = 0; activity.prepareInput(output); if (activity.startException) throw LINK(activity.startException); } void CSplitterOutput::stop() { CriticalBlock block(activity.startLock); activity.smartBuf->queryOutput(output)->stop(); activity.inputStopped(); } const void *CSplitterOutput::nextRow() { Timer t(*this, activity.queryTimeActivities()); if (rec == max) activity.more(max); const void *row = activity.nextRow(output); // pass ptr to max if need more ++rec; return row; } void CSplitterOutput::getMetaInfo(ThorDataLinkMetaInfo &info) { info.canStall = !activity.spill; CThorDataLink::calcMetaInfoSize(info, activity.inputs.item(0)); } unsigned __int64 CSplitterOutput::queryTotalCycles() const { return totalCycles; } CActivityBase *createNSplitterSlave(CGraphElementBase *container) { return new NSplitterSlaveActivity(container); }
Fix regression from splitter-progress-fix
Fix regression from splitter-progress-fix Guard against getMetaInfo being called early. Join for one does, probably it shouldn't. Signed-off-by: Jake Smith <[email protected]>
C++
agpl-3.0
afishbeck/HPCC-Platform,afishbeck/HPCC-Platform,afishbeck/HPCC-Platform,afishbeck/HPCC-Platform,afishbeck/HPCC-Platform,afishbeck/HPCC-Platform
54ae50b5382b1e6d7285d222ce9e6d5175f186e5
tests/a-framework/compile.cc
tests/a-framework/compile.cc
//---------------------------- timer.cc --------------------------- // $Id$ // Version: $Name$ // // Copyright (C) 2010by the deal.II authors // // This file is subject to QPL and may not be distributed // without copyright and license information. Please refer // to the file deal.II/doc/license.html for the text and // further information on this license. // //---------------------------- timer.cc --------------------------- // test the testsuite framework. this test is supposed to compile successfully // but not run #include "../tests.h" #include <base/logstream.h> #include <fstream> #include <cstdlib> int main () { std::ofstream logfile("run/output"); deallog.attach(logfile); deallog.depth_console(0); std::abort (); deallog << "OK" << std::endl; }
//---------------------------- timer.cc --------------------------- // $Id$ // Version: $Name$ // // Copyright (C) 2010by the deal.II authors // // This file is subject to QPL and may not be distributed // without copyright and license information. Please refer // to the file deal.II/doc/license.html for the text and // further information on this license. // //---------------------------- timer.cc --------------------------- // test the testsuite framework. this test is supposed to compile successfully // but not run #include "../tests.h" #include <base/logstream.h> #include <fstream> #include <cstdlib> int main () { std::ofstream logfile("compile/output"); deallog.attach(logfile); deallog.depth_console(0); std::abort (); deallog << "OK" << std::endl; }
Fix output file.
Fix output file. git-svn-id: 31d9d2f6432a47c86a3640814024c107794ea77c@20701 0785d39b-7218-0410-832d-ea1e28bc413d
C++
lgpl-2.1
lue/dealii,EGP-CIG-REU/dealii,Arezou-gh/dealii,kalj/dealii,pesser/dealii,rrgrove6/dealii,adamkosik/dealii,andreamola/dealii,rrgrove6/dealii,johntfoster/dealii,EGP-CIG-REU/dealii,flow123d/dealii,msteigemann/dealii,pesser/dealii,gpitton/dealii,lue/dealii,JaeryunYim/dealii,kalj/dealii,angelrca/dealii,mac-a/dealii,nicolacavallini/dealii,shakirbsm/dealii,natashasharma/dealii,YongYang86/dealii,adamkosik/dealii,ibkim11/dealii,jperryhouts/dealii,danshapero/dealii,nicolacavallini/dealii,naliboff/dealii,adamkosik/dealii,sriharisundar/dealii,flow123d/dealii,gpitton/dealii,pesser/dealii,nicolacavallini/dealii,adamkosik/dealii,Arezou-gh/dealii,lue/dealii,angelrca/dealii,maieneuro/dealii,Arezou-gh/dealii,andreamola/dealii,sairajat/dealii,jperryhouts/dealii,JaeryunYim/dealii,spco/dealii,flow123d/dealii,msteigemann/dealii,ESeNonFossiIo/dealii,lpolster/dealii,shakirbsm/dealii,spco/dealii,sriharisundar/dealii,EGP-CIG-REU/dealii,andreamola/dealii,EGP-CIG-REU/dealii,andreamola/dealii,msteigemann/dealii,mtezzele/dealii,adamkosik/dealii,andreamola/dealii,ibkim11/dealii,lue/dealii,Arezou-gh/dealii,shakirbsm/dealii,angelrca/dealii,mtezzele/dealii,sriharisundar/dealii,pesser/dealii,mtezzele/dealii,ESeNonFossiIo/dealii,kalj/dealii,sriharisundar/dealii,danshapero/dealii,mac-a/dealii,gpitton/dealii,rrgrove6/dealii,sairajat/dealii,shakirbsm/dealii,mtezzele/dealii,jperryhouts/dealii,ESeNonFossiIo/dealii,mac-a/dealii,naliboff/dealii,ibkim11/dealii,nicolacavallini/dealii,sairajat/dealii,jperryhouts/dealii,naliboff/dealii,gpitton/dealii,mac-a/dealii,naliboff/dealii,spco/dealii,msteigemann/dealii,nicolacavallini/dealii,natashasharma/dealii,JaeryunYim/dealii,rrgrove6/dealii,lue/dealii,maieneuro/dealii,danshapero/dealii,andreamola/dealii,adamkosik/dealii,johntfoster/dealii,angelrca/dealii,kalj/dealii,lpolster/dealii,spco/dealii,shakirbsm/dealii,flow123d/dealii,maieneuro/dealii,gpitton/dealii,lue/dealii,jperryhouts/dealii,mtezzele/dealii,natashasharma/dealii,EGP-CIG-REU/dealii,nicolacavallini/dealii,natashasharma/dealii,Arezou-gh/dealii,danshapero/dealii,naliboff/dealii,gpitton/dealii,angelrca/dealii,kalj/dealii,ibkim11/dealii,rrgrove6/dealii,johntfoster/dealii,flow123d/dealii,ESeNonFossiIo/dealii,lue/dealii,pesser/dealii,sairajat/dealii,Arezou-gh/dealii,maieneuro/dealii,ibkim11/dealii,danshapero/dealii,danshapero/dealii,maieneuro/dealii,sairajat/dealii,spco/dealii,johntfoster/dealii,kalj/dealii,natashasharma/dealii,rrgrove6/dealii,lpolster/dealii,johntfoster/dealii,msteigemann/dealii,pesser/dealii,sriharisundar/dealii,ESeNonFossiIo/dealii,mtezzele/dealii,angelrca/dealii,JaeryunYim/dealii,lpolster/dealii,YongYang86/dealii,YongYang86/dealii,msteigemann/dealii,sriharisundar/dealii,YongYang86/dealii,nicolacavallini/dealii,EGP-CIG-REU/dealii,danshapero/dealii,JaeryunYim/dealii,ESeNonFossiIo/dealii,maieneuro/dealii,JaeryunYim/dealii,mac-a/dealii,naliboff/dealii,angelrca/dealii,sriharisundar/dealii,Arezou-gh/dealii,YongYang86/dealii,gpitton/dealii,msteigemann/dealii,natashasharma/dealii,spco/dealii,mtezzele/dealii,EGP-CIG-REU/dealii,naliboff/dealii,mac-a/dealii,YongYang86/dealii,maieneuro/dealii,flow123d/dealii,ESeNonFossiIo/dealii,ibkim11/dealii,shakirbsm/dealii,JaeryunYim/dealii,pesser/dealii,kalj/dealii,lpolster/dealii,rrgrove6/dealii,sairajat/dealii,jperryhouts/dealii,ibkim11/dealii,mac-a/dealii,johntfoster/dealii,johntfoster/dealii,shakirbsm/dealii,YongYang86/dealii,andreamola/dealii,natashasharma/dealii,flow123d/dealii,lpolster/dealii,spco/dealii,jperryhouts/dealii,lpolster/dealii,sairajat/dealii,adamkosik/dealii
a86dd1fa94efcc2f9e01924340b1f6844b79c84e
Charts/vtkScalarsToColorsItem.cxx
Charts/vtkScalarsToColorsItem.cxx
/*========================================================================= Program: Visualization Toolkit Module: vtkScalarsToColorsItem.cxx Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen All rights reserved. See Copyright.txt or http://www.kitware.com/Copyright.htm for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notice for more information. =========================================================================*/ #include "vtkBrush.h" #include "vtkCallbackCommand.h" #include "vtkContext2D.h" #include "vtkContextDevice2D.h" #include "vtkContextScene.h" #include "vtkFloatArray.h" #include "vtkImageData.h" #include "vtkObjectFactory.h" #include "vtkPen.h" #include "vtkPoints2D.h" #include "vtkScalarsToColorsItem.h" #include "vtkSmartPointer.h" #include "vtkTransform2D.h" #include <cassert> //----------------------------------------------------------------------------- vtkScalarsToColorsItem::vtkScalarsToColorsItem() { this->PolyLinePen = vtkPen::New(); this->PolyLinePen->SetWidth(2.); this->PolyLinePen->SetColor(64, 64, 72); // Payne's grey, why not this->PolyLinePen->SetLineType(vtkPen::NO_PEN); this->Texture = 0; this->Interpolate = true; this->Shape = vtkPoints2D::New(); this->Shape->SetDataTypeToFloat(); this->Shape->SetNumberOfPoints(0); this->Callback = vtkCallbackCommand::New(); this->Callback->SetClientData(this); this->Callback->SetCallback( vtkScalarsToColorsItem::OnScalarsToColorsModified); this->MaskAboveCurve = false; } //----------------------------------------------------------------------------- vtkScalarsToColorsItem::~vtkScalarsToColorsItem() { if (this->PolyLinePen) { this->PolyLinePen->Delete(); this->PolyLinePen = 0; } if (this->Texture) { this->Texture->Delete(); this->Texture = 0; } if (this->Shape) { this->Shape->Delete(); this->Shape = 0; } if (this->Callback) { this->Callback->Delete(); this->Callback = 0; } } //----------------------------------------------------------------------------- void vtkScalarsToColorsItem::PrintSelf(ostream &os, vtkIndent indent) { this->Superclass::PrintSelf(os, indent); os << indent << "Interpolate: " << this->Interpolate << endl; } //----------------------------------------------------------------------------- void vtkScalarsToColorsItem::GetBounds(double bounds[4]) { if (this->UserBounds[1] > this->UserBounds[0] && this->UserBounds[3] > this->UserBounds[2]) { bounds[0] = this->UserBounds[0]; bounds[1] = this->UserBounds[1]; bounds[2] = this->UserBounds[2]; bounds[3] = this->UserBounds[3]; return; } this->ComputeBounds(bounds); } //----------------------------------------------------------------------------- void vtkScalarsToColorsItem::ComputeBounds(double bounds[4]) { bounds[0] = 0.; bounds[1] = 1.; bounds[2] = 0.; bounds[3] = 1.; } //----------------------------------------------------------------------------- bool vtkScalarsToColorsItem::Paint(vtkContext2D* painter) { this->TextureWidth = this->GetScene()->GetViewWidth(); if (this->Texture == 0 || this->Texture->GetMTime() < this->GetMTime()) { this->ComputeTexture(); } if (this->Texture == 0) { return false; } vtkSmartPointer<vtkPen> transparentPen = vtkSmartPointer<vtkPen>::New(); transparentPen->SetLineType(vtkPen::NO_PEN); painter->ApplyPen(transparentPen); painter->GetBrush()->SetColorF(0., 0.,0.,1.); painter->GetBrush()->SetColorF(1., 1., 1., 1.); painter->GetBrush()->SetTexture(this->Texture); painter->GetBrush()->SetTextureProperties( (this->Interpolate ? vtkBrush::Nearest : vtkBrush::Linear) | vtkBrush::Stretch); const int size = this->Shape->GetNumberOfPoints(); if (!this->MaskAboveCurve || size < 2) { double bounds[4]; this->GetBounds(bounds); painter->DrawQuad(bounds[0], bounds[2], bounds[0], bounds[3], bounds[1], bounds[3], bounds[1], bounds[2]); } else { vtkPoints2D* trapezoids = vtkPoints2D::New(); trapezoids->SetNumberOfPoints(2*size); double point[2]; vtkIdType j = -1; for (vtkIdType i = 0; i < size; ++i) { this->Shape->GetPoint(i, point); trapezoids->SetPoint(++j, point[0], 0.); trapezoids->SetPoint(++j, point); } painter->DrawQuadStrip(trapezoids); trapezoids->Delete(); } if (this->PolyLinePen->GetLineType() != vtkPen::NO_PEN) { painter->ApplyPen(this->PolyLinePen); painter->DrawPoly(this->Shape); } return true; } //----------------------------------------------------------------------------- void vtkScalarsToColorsItem::OnScalarsToColorsModified(vtkObject* caller, unsigned long eid, void *clientdata, void* calldata) { vtkScalarsToColorsItem* self = reinterpret_cast<vtkScalarsToColorsItem*>(clientdata); self->ScalarsToColorsModified(caller, eid, calldata); } //----------------------------------------------------------------------------- void vtkScalarsToColorsItem::ScalarsToColorsModified(vtkObject* vtkNotUsed(object), unsigned long vtkNotUsed(eid), void* vtkNotUsed(calldata)) { this->Modified(); }
/*========================================================================= Program: Visualization Toolkit Module: vtkScalarsToColorsItem.cxx Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen All rights reserved. See Copyright.txt or http://www.kitware.com/Copyright.htm for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notice for more information. =========================================================================*/ #include "vtkBrush.h" #include "vtkCallbackCommand.h" #include "vtkContext2D.h" #include "vtkContextDevice2D.h" #include "vtkContextScene.h" #include "vtkFloatArray.h" #include "vtkImageData.h" #include "vtkObjectFactory.h" #include "vtkPen.h" #include "vtkPoints2D.h" #include "vtkScalarsToColorsItem.h" #include "vtkSmartPointer.h" #include "vtkTransform2D.h" #include <cassert> //----------------------------------------------------------------------------- vtkScalarsToColorsItem::vtkScalarsToColorsItem() { this->PolyLinePen = vtkPen::New(); this->PolyLinePen->SetWidth(2.); this->PolyLinePen->SetColor(64, 64, 72); // Payne's grey, why not this->PolyLinePen->SetLineType(vtkPen::NO_PEN); this->Texture = 0; this->Interpolate = true; this->Shape = vtkPoints2D::New(); this->Shape->SetDataTypeToFloat(); this->Shape->SetNumberOfPoints(0); this->Callback = vtkCallbackCommand::New(); this->Callback->SetClientData(this); this->Callback->SetCallback( vtkScalarsToColorsItem::OnScalarsToColorsModified); this->MaskAboveCurve = false; this->UserBounds[0] = this->UserBounds[1] = this->UserBounds[2] = this->UserBounds[3] = 0.0; } //----------------------------------------------------------------------------- vtkScalarsToColorsItem::~vtkScalarsToColorsItem() { if (this->PolyLinePen) { this->PolyLinePen->Delete(); this->PolyLinePen = 0; } if (this->Texture) { this->Texture->Delete(); this->Texture = 0; } if (this->Shape) { this->Shape->Delete(); this->Shape = 0; } if (this->Callback) { this->Callback->Delete(); this->Callback = 0; } } //----------------------------------------------------------------------------- void vtkScalarsToColorsItem::PrintSelf(ostream &os, vtkIndent indent) { this->Superclass::PrintSelf(os, indent); os << indent << "Interpolate: " << this->Interpolate << endl; } //----------------------------------------------------------------------------- void vtkScalarsToColorsItem::GetBounds(double bounds[4]) { if (this->UserBounds[1] > this->UserBounds[0] && this->UserBounds[3] > this->UserBounds[2]) { bounds[0] = this->UserBounds[0]; bounds[1] = this->UserBounds[1]; bounds[2] = this->UserBounds[2]; bounds[3] = this->UserBounds[3]; return; } this->ComputeBounds(bounds); } //----------------------------------------------------------------------------- void vtkScalarsToColorsItem::ComputeBounds(double bounds[4]) { bounds[0] = 0.; bounds[1] = 1.; bounds[2] = 0.; bounds[3] = 1.; } //----------------------------------------------------------------------------- bool vtkScalarsToColorsItem::Paint(vtkContext2D* painter) { this->TextureWidth = this->GetScene()->GetViewWidth(); if (this->Texture == 0 || this->Texture->GetMTime() < this->GetMTime()) { this->ComputeTexture(); } if (this->Texture == 0) { return false; } vtkSmartPointer<vtkPen> transparentPen = vtkSmartPointer<vtkPen>::New(); transparentPen->SetLineType(vtkPen::NO_PEN); painter->ApplyPen(transparentPen); painter->GetBrush()->SetColorF(0., 0.,0.,1.); painter->GetBrush()->SetColorF(1., 1., 1., 1.); painter->GetBrush()->SetTexture(this->Texture); painter->GetBrush()->SetTextureProperties( (this->Interpolate ? vtkBrush::Nearest : vtkBrush::Linear) | vtkBrush::Stretch); const int size = this->Shape->GetNumberOfPoints(); if (!this->MaskAboveCurve || size < 2) { double bounds[4]; this->GetBounds(bounds); painter->DrawQuad(bounds[0], bounds[2], bounds[0], bounds[3], bounds[1], bounds[3], bounds[1], bounds[2]); } else { vtkPoints2D* trapezoids = vtkPoints2D::New(); trapezoids->SetNumberOfPoints(2*size); double point[2]; vtkIdType j = -1; for (vtkIdType i = 0; i < size; ++i) { this->Shape->GetPoint(i, point); trapezoids->SetPoint(++j, point[0], 0.); trapezoids->SetPoint(++j, point); } painter->DrawQuadStrip(trapezoids); trapezoids->Delete(); } if (this->PolyLinePen->GetLineType() != vtkPen::NO_PEN) { painter->ApplyPen(this->PolyLinePen); painter->DrawPoly(this->Shape); } return true; } //----------------------------------------------------------------------------- void vtkScalarsToColorsItem::OnScalarsToColorsModified(vtkObject* caller, unsigned long eid, void *clientdata, void* calldata) { vtkScalarsToColorsItem* self = reinterpret_cast<vtkScalarsToColorsItem*>(clientdata); self->ScalarsToColorsModified(caller, eid, calldata); } //----------------------------------------------------------------------------- void vtkScalarsToColorsItem::ScalarsToColorsModified(vtkObject* vtkNotUsed(object), unsigned long vtkNotUsed(eid), void* vtkNotUsed(calldata)) { this->Modified(); }
Initialize UserBounds, used in GetBounds.
BUG: Initialize UserBounds, used in GetBounds. Change-Id: Id69a252ddab397cbef204de76ebda9b462d59bd6
C++
bsd-3-clause
msmolens/VTK,hendradarwin/VTK,aashish24/VTK-old,keithroe/vtkoptix,sumedhasingla/VTK,biddisco/VTK,keithroe/vtkoptix,mspark93/VTK,candy7393/VTK,candy7393/VTK,cjh1/VTK,sumedhasingla/VTK,johnkit/vtk-dev,jmerkow/VTK,jmerkow/VTK,jmerkow/VTK,gram526/VTK,collects/VTK,msmolens/VTK,SimVascular/VTK,cjh1/VTK,spthaolt/VTK,SimVascular/VTK,keithroe/vtkoptix,jmerkow/VTK,biddisco/VTK,demarle/VTK,candy7393/VTK,johnkit/vtk-dev,mspark93/VTK,spthaolt/VTK,gram526/VTK,gram526/VTK,collects/VTK,spthaolt/VTK,sankhesh/VTK,mspark93/VTK,hendradarwin/VTK,SimVascular/VTK,berendkleinhaneveld/VTK,johnkit/vtk-dev,cjh1/VTK,SimVascular/VTK,hendradarwin/VTK,johnkit/vtk-dev,sankhesh/VTK,berendkleinhaneveld/VTK,jmerkow/VTK,jmerkow/VTK,demarle/VTK,gram526/VTK,mspark93/VTK,cjh1/VTK,demarle/VTK,aashish24/VTK-old,biddisco/VTK,msmolens/VTK,sankhesh/VTK,biddisco/VTK,msmolens/VTK,demarle/VTK,cjh1/VTK,mspark93/VTK,sankhesh/VTK,ashray/VTK-EVM,berendkleinhaneveld/VTK,sumedhasingla/VTK,ashray/VTK-EVM,collects/VTK,sumedhasingla/VTK,johnkit/vtk-dev,msmolens/VTK,SimVascular/VTK,ashray/VTK-EVM,sankhesh/VTK,sumedhasingla/VTK,spthaolt/VTK,keithroe/vtkoptix,mspark93/VTK,aashish24/VTK-old,collects/VTK,cjh1/VTK,aashish24/VTK-old,keithroe/vtkoptix,berendkleinhaneveld/VTK,msmolens/VTK,berendkleinhaneveld/VTK,gram526/VTK,demarle/VTK,hendradarwin/VTK,candy7393/VTK,gram526/VTK,SimVascular/VTK,gram526/VTK,ashray/VTK-EVM,collects/VTK,candy7393/VTK,keithroe/vtkoptix,biddisco/VTK,ashray/VTK-EVM,biddisco/VTK,sumedhasingla/VTK,aashish24/VTK-old,jmerkow/VTK,johnkit/vtk-dev,berendkleinhaneveld/VTK,demarle/VTK,keithroe/vtkoptix,ashray/VTK-EVM,biddisco/VTK,keithroe/vtkoptix,sumedhasingla/VTK,candy7393/VTK,sankhesh/VTK,ashray/VTK-EVM,mspark93/VTK,berendkleinhaneveld/VTK,mspark93/VTK,SimVascular/VTK,jmerkow/VTK,candy7393/VTK,spthaolt/VTK,ashray/VTK-EVM,spthaolt/VTK,sumedhasingla/VTK,spthaolt/VTK,gram526/VTK,hendradarwin/VTK,johnkit/vtk-dev,sankhesh/VTK,SimVascular/VTK,candy7393/VTK,msmolens/VTK,collects/VTK,sankhesh/VTK,aashish24/VTK-old,demarle/VTK,demarle/VTK,hendradarwin/VTK,msmolens/VTK,hendradarwin/VTK
7724f942aa445c7b160e1e11e6483ba1b19d3048
library/iot_att/iot_att.cpp
library/iot_att/iot_att.cpp
/* AllThingsTalk - SmartLiving.io Arduino library */ #define DEBUG //turns on debugging in the IOT library. comment out this line to save memory. #include "iot_att.h" #include <Time.h> #define RETRYDELAY 5000 //the nr of milliseconds that we pause before retrying to create the connection #define ETHERNETDELAY 1000 //the nr of milliseconds that we pause to give the ethernet board time to start #define MQTTPORT 1883 #ifdef DEBUG char HTTPSERVTEXT[] = "connection HTTP Server"; char MQTTSERVTEXT[] = "connection MQTT Server"; char FAILED_RETRY[] = " failed,retrying"; char SUCCESTXT[] = " established"; #endif char _mac[18]; //create the object ATTDevice::ATTDevice(String deviceId, String clientId, String clientKey) { _deviceId = deviceId; _clientId = clientId; _clientKey = clientKey; } //connect with the http server bool ATTDevice::Connect(byte mac[], char httpServer[]) { _serverName = httpServer; //keep track of this value while working with the http server. if (Ethernet.begin(mac) == 0) // Initialize the Ethernet connection: { Serial.println(F("DHCP failed,end")); return false; //we failed to connect } String macStr = String(mac[0], HEX); for(int i = 1; i < 6; i++) //copy the mac address to a char buffer so we can use it later on to connect to mqtt. macStr += "-" + String(mac[i], HEX); macStr.toCharArray(_mac, 18); delay(ETHERNETDELAY); // give the Ethernet shield a second to initialize: #ifdef DEBUG Serial.println(_mac); Serial.println(F("connecting")); #endif while (!_client.connect(httpServer, 80)) // if you get a connection, report back via serial: { #ifdef DEBUG Serial.print(HTTPSERVTEXT); Serial.println(FAILED_RETRY); #endif delay(RETRYDELAY); } #ifdef DEBUG Serial.print(HTTPSERVTEXT); Serial.println(SUCCESTXT); #endif return true; //we have created a connection succesfully. } //create or update the specified asset. void ATTDevice::AddAsset(String name, String description, bool isActuator, String type) { // form a JSON-formatted string: String jsonString = "{\"name\":\"" + name + "\",\"description\":\"" + description + "\",\"is\":\""; if(isActuator) jsonString += "actuator"; else jsonString += "sensor"; jsonString += "\",\"profile\": { \"type\":\"" + type + "\" }, \"deviceId\":\"" + _deviceId + "\" }"; // Make a HTTP request: _client.println(F("POST /api/asset?idFromName=true HTTP/1.1")); _client.print(F("Host: ")); _client.println(_serverName); _client.println(F("Content-Type: application/json")); _client.print(F("Auth-ClientKey: "));_client.println(_clientKey); _client.print(F("Auth-ClientId: "));_client.println(_clientId); _client.print("Content-Length: "); _client.println(jsonString.length()); _client.println(); _client.println(jsonString); _client.println(); Serial.println(jsonString); //show it on the screen delay(ETHERNETDELAY); GetHTTPResult(); //get the response fromm the server and show it. } //connect with the http server and broker void ATTDevice::Subscribe(PubSubClient& mqttclient) { _mqttclient = &mqttclient; _serverName = NULL; //no longer need this reference. #ifdef DEBUG Serial.println(F("Stopping HTTP")); #endif _client.flush(); _client.stop(); //delay(RETRYDELAY); //give the ethernet card a little time to stop properly before working with mqtt. while (!_mqttclient->connect(_mac)) { #ifdef DEBUG Serial.print(MQTTSERVTEXT); Serial.println(FAILED_RETRY); #endif delay(RETRYDELAY); } #ifdef DEBUG Serial.print(MQTTSERVTEXT); Serial.println(SUCCESTXT); #endif MqttSubscribe(); } //check for any new mqtt messages. void ATTDevice::Process() { _mqttclient->loop(); } //send a data value to the cloud server for the sensor with the specified id. void ATTDevice::Send(String value, String sensorId) { unsigned long timeNow = (unsigned long)now(); String pubString = String(timeNow) + "|" + value; int length = pubString.length() + 1; char message_buff[length]; pubString.toCharArray(message_buff, length); #ifdef DEBUG //don't need to write all of this if not debugging. Serial.print(F("time = ")); Serial.println(timeNow); Serial.print(F("Publish to ")); Serial.print(sensorId); Serial.print(" : "); #endif Serial.println(pubString); //this value is still useful and generated anyway, so no extra cost. String Mqttstring = "/f/" + _clientId + "/s/" + _deviceId + "/" + sensorId; length = Mqttstring.length() + 1; char Mqttstring_buff[length]; Mqttstring.toCharArray(Mqttstring_buff, length); _mqttclient->publish(Mqttstring_buff, message_buff); delay(100); //give some time to the ethernet shield so it can process everything. } //subscribe to the mqtt topic so we can receive data from the server. void ATTDevice::MqttSubscribe() { String MqttString = "/m/"+_clientId+"/#"; char Mqttstring_buff[MqttString.length()+1]; MqttString.toCharArray(Mqttstring_buff, MqttString.length()+1); _mqttclient->subscribe(Mqttstring_buff); Mqttstring_buff[1] = 's'; //change from /m/ClientId/# to /s/ClientId/# _mqttclient->subscribe(Mqttstring_buff); #ifdef DEBUG Serial.println(F("MQTT Subscribed...")); #endif } void ATTDevice::GetHTTPResult() { // If there's incoming data from the net connection, send it out the serial port // This is for debugging purposes only if(_client.available()){ while (_client.available()) { char c = _client.read(); Serial.print(c); } Serial.println(); } }
/* AllThingsTalk - SmartLiving.io Arduino library */ #define DEBUG //turns on debugging in the IOT library. comment out this line to save memory. #include "iot_att.h" #include <Time.h> #define RETRYDELAY 5000 //the nr of milliseconds that we pause before retrying to create the connection #define ETHERNETDELAY 1000 //the nr of milliseconds that we pause to give the ethernet board time to start #define MQTTPORT 1883 #ifdef DEBUG char HTTPSERVTEXT[] = "connection HTTP Server"; char MQTTSERVTEXT[] = "connection MQTT Server"; char FAILED_RETRY[] = " failed,retrying"; char SUCCESTXT[] = " established"; #endif char _mac[18]; //create the object ATTDevice::ATTDevice(String deviceId, String clientId, String clientKey) { _deviceId = deviceId; _clientId = clientId; _clientKey = clientKey; } //connect with the http server bool ATTDevice::Connect(byte mac[], char httpServer[]) { _serverName = httpServer; //keep track of this value while working with the http server. if (Ethernet.begin(mac) == 0) // Initialize the Ethernet connection: { Serial.println(F("DHCP failed,end")); return false; //we failed to connect } String macStr = String(mac[0], HEX); for(int i = 1; i < 6; i++) //copy the mac address to a char buffer so we can use it later on to connect to mqtt. macStr += "-" + String(mac[i], HEX); macStr.toCharArray(_mac, 18); delay(ETHERNETDELAY); // give the Ethernet shield a second to initialize: #ifdef DEBUG Serial.println(_mac); Serial.println(F("connecting")); #endif while (!_client.connect(httpServer, 80)) // if you get a connection, report back via serial: { #ifdef DEBUG Serial.print(HTTPSERVTEXT); Serial.println(FAILED_RETRY); #endif delay(RETRYDELAY); } #ifdef DEBUG Serial.print(HTTPSERVTEXT); Serial.println(SUCCESTXT); #endif return true; //we have created a connection succesfully. } //create or update the specified asset. void ATTDevice::AddAsset(String name, String description, bool isActuator, String type) { // form a JSON-formatted string: String jsonString = "{\"name\":\"" + name + "\",\"description\":\"" + description + "\",\"is\":\""; if(isActuator) jsonString += "actuator"; else jsonString += "sensor"; jsonString += "\",\"profile\": { \"type\":\"" + type + "\" }, \"deviceId\":\"" + _deviceId + "\" }"; // Make a HTTP request: _client.println(F("POST /api/asset?idFromName=true HTTP/1.1")); _client.print(F("Host: ")); _client.println(_serverName); _client.println(F("Content-Type: application/json")); _client.print(F("Auth-ClientKey: "));_client.println(_clientKey); _client.print(F("Auth-ClientId: "));_client.println(_clientId); _client.print("Content-Length: "); _client.println(jsonString.length()); _client.println(); _client.println(jsonString); _client.println(); Serial.println(jsonString); //show it on the screen delay(ETHERNETDELAY); GetHTTPResult(); //get the response fromm the server and show it. } //connect with the http server and broker void ATTDevice::Subscribe(PubSubClient& mqttclient) { _mqttclient = &mqttclient; _serverName = NULL; //no longer need this reference. #ifdef DEBUG Serial.println(F("Stopping HTTP")); #endif _client.flush(); _client.stop(); //delay(RETRYDELAY); //give the ethernet card a little time to stop properly before working with mqtt. while (!_mqttclient->connect(_mac)) { #ifdef DEBUG Serial.print(MQTTSERVTEXT); Serial.println(FAILED_RETRY); #endif delay(RETRYDELAY); } #ifdef DEBUG Serial.print(MQTTSERVTEXT); Serial.println(SUCCESTXT); #endif MqttSubscribe(); } //check for any new mqtt messages. void ATTDevice::Process() { _mqttclient->loop(); } //send a data value to the cloud server for the sensor with the specified id. void ATTDevice::Send(String value, String sensorId) { unsigned long timeNow = (unsigned long)now(); String pubString = String(timeNow) + "|" + value; int length = pubString.length() + 1; char message_buff[length]; pubString.toCharArray(message_buff, length); #ifdef DEBUG //don't need to write all of this if not debugging. Serial.print(F("time = ")); Serial.println(timeNow); Serial.print(F("Publish to ")); Serial.print(sensorId); Serial.print(" : "); #endif Serial.println(pubString); //this value is still useful and generated anyway, so no extra cost. String Mqttstring = "/f/" + _clientId + "/s/" + _deviceId + sensorId; length = Mqttstring.length() + 1; char Mqttstring_buff[length]; Mqttstring.toCharArray(Mqttstring_buff, length); _mqttclient->publish(Mqttstring_buff, message_buff); delay(100); //give some time to the ethernet shield so it can process everything. } //subscribe to the mqtt topic so we can receive data from the server. void ATTDevice::MqttSubscribe() { String MqttString = "/m/"+_clientId+"/#"; char Mqttstring_buff[MqttString.length()+1]; MqttString.toCharArray(Mqttstring_buff, MqttString.length()+1); _mqttclient->subscribe(Mqttstring_buff); Mqttstring_buff[1] = 's'; //change from /m/ClientId/# to /s/ClientId/# _mqttclient->subscribe(Mqttstring_buff); #ifdef DEBUG Serial.println(F("MQTT Subscribed...")); #endif } void ATTDevice::GetHTTPResult() { // If there's incoming data from the net connection, send it out the serial port // This is for debugging purposes only if(_client.available()){ while (_client.available()) { char c = _client.read(); Serial.print(c); } Serial.println(); } }
fix in mqtt publish topic
fix in mqtt publish topic according to new api
C++
apache-2.0
allthingstalk/arduino-client
883deb055c874ff835120d5419773414bcbb8aba
clipp/view.cpp
clipp/view.cpp
/***************************************************************************** * Licensed to Qualys, Inc. (QUALYS) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * QUALYS 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. ****************************************************************************/ /** * @file * @brief IronBee --- CLIPP View Consumer Implementation * * @author Christopher Alfeld <[email protected]> */ #include "ironbee_config_auto.h" #include "view.hpp" #include <boost/foreach.hpp> #include <boost/function.hpp> #include <boost/format.hpp> #ifdef HAVE_MODP #include <modp_burl.h> #endif using namespace std; namespace IronBee { namespace CLIPP { struct ViewConsumer::State { boost::function<void(const Input::input_p&)> viewer; }; namespace { bool is_not_printable(char c) { return (c < 32 || c > 126) && (c != 10) && (c != 13); } void output_with_escapes(const char* b, const char* e) { const char* i = b; while (i < e) { const char* j = find_if(i, e, &is_not_printable); if (j == e) { cout.write(i, e - i); i = e; } else { if (j > i) { cout.write(i, j - i); i = j; } // Workaround for boost::format bug. int value = *i; cout << (boost::format("[%02x]") % (value & 0xff)); ++i; } } } using namespace Input; struct ViewDelegate : public Delegate { //! Output ConnectionEvent. static void connection_event(const ConnectionEvent& event) { cout << event.local_ip << ":" << event.local_port << " <--> " << event.remote_ip << ":" << event.remote_port ; } //! Output DataEvent. static void data_event(const DataEvent& event) { output_with_escapes( event.data.data, event.data.data + event.data.length ); } //! Output HeaderEven& eventt static void header_event(const HeaderEvent& event) { BOOST_FOREACH(const header_t& header, event.headers) { cout << header.first << ": " << header.second << endl; } } //! CONNECTION_OPENED void connection_opened(const ConnectionEvent& event) { cout << "=== CONNECTION_OPENED: "; connection_event(event); cout << " ===" << endl; } //! CONNECTION_CLOSED void connection_closed(const NullEvent& event) { cout << "=== CONNECTION_CLOSED ===" << endl; } //! CONNECTION_DATA_IN void connection_data_in(const DataEvent& event) { cout << "=== CONNECTION_DATA_IN ===" << endl; data_event(event); cout << endl; } //! CONNECTION_DATA_OUT void connection_data_out(const DataEvent& event) { cout << "=== CONNECTION_DATA_OUT ===" << endl; data_event(event); cout << endl; } //! REQUEST_STARTED void request_started(const RequestEvent& event) { cout << "=== REQUEST_STARTED: " << event.method << " " << event.uri << " " << event.uri << " ===" << endl; if (event.raw.data) { cout << "RAW: " << event.raw << endl; } urldecode("DECODED RAW: ", event.raw.data, event.raw.length); urldecode("DECODED URI: ", event.uri.data, event.uri.length); } //! REQUEST_HEADER void request_header(const HeaderEvent& event) { cout << "=== REQUEST_HEADER ===" << endl; header_event(event); } //! REQUEST HEADER FINISHED void request_header_finished(const NullEvent& event) { cout << "=== REQUEST_HEADER_FINISHED ===" << endl; } //! REQUEST_BODY void request_body(const DataEvent& event) { cout << "=== REQUEST_BODY ===" << endl; data_event(event); cout << endl; } //! REQUEST_FINISHED void request_finished(const NullEvent& event) { cout << "=== REQUEST_FINISHED ===" << endl; } //! RESPONSE_STARTED void response_started(const ResponseEvent& event) { cout << "=== RESPONSE_STARTED " << event.protocol << " " << event.status << " " << event.message << " ===" << endl; if (event.raw.data) { cout << event.raw << endl; } } //! RESPONSE_HEADER void response_header(const HeaderEvent& event) { cout << "=== RESPONSE HEADER ===" << endl; header_event(event); } //! RESPONSE HEADER FINISHED void response_header_finished(const NullEvent& event) { cout << "=== RESPONSE_HEADER_FINISHED ===" << endl; } //! RESPONSE_BODY void response_body(const DataEvent& event) { cout << "=== RESPONSE BODY ===" << endl; data_event(event); cout << endl; } //! RESPONSE_FINISHED void response_finished(const NullEvent& event) { cout << "=== RESPONSE FINISHED ===" << endl; } private: void urldecode(const char* prefix, const char* data, size_t length) { #ifdef HAVE_MODP if (! data) { return; } string decoded = modp::url_decode(data, length); if ( decoded.length() != length || ! equal(decoded.begin(), decoded.end(), data) ) { cout << prefix << decoded << endl; } #endif } }; void view_full(const input_p& input) { if (input->id.empty()) { cout << "---- No ID Provided ----" << endl; } else { cout << "---- " << input->id << " ----" << endl; } ViewDelegate viewer; input->connection.dispatch(viewer); } void view_id(const input_p& input) { if (input->id.empty()) { cout << "---- No ID Provided ----" << endl; } else { cout << "---- " << input->id << " ----" << endl; } } void view_summary(const input_p& input) { string id("NO ID"); if (! input->id.empty()) { id = input->id; } size_t num_txs = input->connection.transactions.size(); if (input->connection.pre_transaction_events.empty()) { // no IP information. cout << boost::format("%36s NO CONNECTION INFO %5d") % id % num_txs << endl; } const ConnectionEvent& connection_event = dynamic_cast<ConnectionEvent&>( *input->connection.pre_transaction_events.front() ); cout << boost::format("%-40s %22s <-> %-22s %5d txs") % id % (boost::format("%s:%d") % connection_event.local_ip % connection_event.local_port ) % (boost::format("%s:%d") % connection_event.remote_ip % connection_event.remote_port ) % num_txs << endl; } } ViewConsumer::ViewConsumer(const std::string& arg) : m_state(new State()) { if (arg == "id") { m_state->viewer = view_id; } else if (arg == "summary") { m_state->viewer = view_summary; } else if (arg.empty()) { m_state->viewer = view_full; } else { throw runtime_error("Unknown View argument: " + arg); } } bool ViewConsumer::operator()(const input_p& input) { if ( ! input ) { return true; } m_state->viewer(input); return true; } ViewModifier::ViewModifier(const std::string& arg) : m_consumer(arg) { // nop } bool ViewModifier::operator()(input_p& input) { return m_consumer(input); } } // CLIPP } // IronBee
/***************************************************************************** * Licensed to Qualys, Inc. (QUALYS) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * QUALYS 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. ****************************************************************************/ /** * @file * @brief IronBee --- CLIPP View Consumer Implementation * * @author Christopher Alfeld <[email protected]> */ #include "ironbee_config_auto.h" #include "view.hpp" #include <boost/foreach.hpp> #include <boost/function.hpp> #include <boost/format.hpp> #ifdef HAVE_MODP #include <modp_burl.h> #endif using namespace std; namespace IronBee { namespace CLIPP { struct ViewConsumer::State { boost::function<void(const Input::input_p&)> viewer; }; namespace { bool is_not_printable(char c) { return (c < 32 || c > 126) && (c != 10) && (c != 13); } void output_with_escapes(const char* b, const char* e) { const char* i = b; while (i < e) { const char* j = find_if(i, e, &is_not_printable); if (j == e) { cout.write(i, e - i); i = e; } else { if (j > i) { cout.write(i, j - i); i = j; } // Workaround for boost::format bug. int value = *i; cout << (boost::format("[%02x]") % (value & 0xff)); ++i; } } } using namespace Input; struct ViewDelegate : public Delegate { //! Output ConnectionEvent. static void connection_event(const ConnectionEvent& event) { cout << event.local_ip << ":" << event.local_port << " <--> " << event.remote_ip << ":" << event.remote_port ; } //! Output DataEvent. static void data_event(const DataEvent& event) { output_with_escapes( event.data.data, event.data.data + event.data.length ); } //! Output HeaderEven& eventt static void header_event(const HeaderEvent& event) { BOOST_FOREACH(const header_t& header, event.headers) { cout << header.first << ": " << header.second << endl; } } //! CONNECTION_OPENED void connection_opened(const ConnectionEvent& event) { cout << "=== CONNECTION_OPENED: "; connection_event(event); cout << " ===" << endl; } //! CONNECTION_CLOSED void connection_closed(const NullEvent& event) { cout << "=== CONNECTION_CLOSED ===" << endl; } //! CONNECTION_DATA_IN void connection_data_in(const DataEvent& event) { cout << "=== CONNECTION_DATA_IN ===" << endl; data_event(event); cout << endl; } //! CONNECTION_DATA_OUT void connection_data_out(const DataEvent& event) { cout << "=== CONNECTION_DATA_OUT ===" << endl; data_event(event); cout << endl; } //! REQUEST_STARTED void request_started(const RequestEvent& event) { cout << "=== REQUEST_STARTED: " << event.method << " " << event.uri << " " << event.protocol << " ===" << endl; if (event.raw.data) { cout << "RAW: " << event.raw << endl; } urldecode("DECODED RAW: ", event.raw.data, event.raw.length); urldecode("DECODED URI: ", event.uri.data, event.uri.length); } //! REQUEST_HEADER void request_header(const HeaderEvent& event) { cout << "=== REQUEST_HEADER ===" << endl; header_event(event); } //! REQUEST HEADER FINISHED void request_header_finished(const NullEvent& event) { cout << "=== REQUEST_HEADER_FINISHED ===" << endl; } //! REQUEST_BODY void request_body(const DataEvent& event) { cout << "=== REQUEST_BODY ===" << endl; data_event(event); cout << endl; } //! REQUEST_FINISHED void request_finished(const NullEvent& event) { cout << "=== REQUEST_FINISHED ===" << endl; } //! RESPONSE_STARTED void response_started(const ResponseEvent& event) { cout << "=== RESPONSE_STARTED " << event.protocol << " " << event.status << " " << event.message << " ===" << endl; if (event.raw.data) { cout << event.raw << endl; } } //! RESPONSE_HEADER void response_header(const HeaderEvent& event) { cout << "=== RESPONSE HEADER ===" << endl; header_event(event); } //! RESPONSE HEADER FINISHED void response_header_finished(const NullEvent& event) { cout << "=== RESPONSE_HEADER_FINISHED ===" << endl; } //! RESPONSE_BODY void response_body(const DataEvent& event) { cout << "=== RESPONSE BODY ===" << endl; data_event(event); cout << endl; } //! RESPONSE_FINISHED void response_finished(const NullEvent& event) { cout << "=== RESPONSE FINISHED ===" << endl; } private: void urldecode(const char* prefix, const char* data, size_t length) { #ifdef HAVE_MODP if (! data) { return; } string decoded = modp::url_decode(data, length); if ( decoded.length() != length || ! equal(decoded.begin(), decoded.end(), data) ) { cout << prefix << decoded << endl; } #endif } }; void view_full(const input_p& input) { if (input->id.empty()) { cout << "---- No ID Provided ----" << endl; } else { cout << "---- " << input->id << " ----" << endl; } ViewDelegate viewer; input->connection.dispatch(viewer); } void view_id(const input_p& input) { if (input->id.empty()) { cout << "---- No ID Provided ----" << endl; } else { cout << "---- " << input->id << " ----" << endl; } } void view_summary(const input_p& input) { string id("NO ID"); if (! input->id.empty()) { id = input->id; } size_t num_txs = input->connection.transactions.size(); if (input->connection.pre_transaction_events.empty()) { // no IP information. cout << boost::format("%36s NO CONNECTION INFO %5d") % id % num_txs << endl; } const ConnectionEvent& connection_event = dynamic_cast<ConnectionEvent&>( *input->connection.pre_transaction_events.front() ); cout << boost::format("%-40s %22s <-> %-22s %5d txs") % id % (boost::format("%s:%d") % connection_event.local_ip % connection_event.local_port ) % (boost::format("%s:%d") % connection_event.remote_ip % connection_event.remote_port ) % num_txs << endl; } } ViewConsumer::ViewConsumer(const std::string& arg) : m_state(new State()) { if (arg == "id") { m_state->viewer = view_id; } else if (arg == "summary") { m_state->viewer = view_summary; } else if (arg.empty()) { m_state->viewer = view_full; } else { throw runtime_error("Unknown View argument: " + arg); } } bool ViewConsumer::operator()(const input_p& input) { if ( ! input ) { return true; } m_state->viewer(input); return true; } ViewModifier::ViewModifier(const std::string& arg) : m_consumer(arg) { // nop } bool ViewModifier::operator()(input_p& input) { return m_consumer(input); } } // CLIPP } // IronBee
Fix display of request protocol when using @view.
clipp: Fix display of request protocol when using @view.
C++
apache-2.0
ironbee/ironbee,ironbee/ironbee,ironbee/ironbee,b1v1r/ironbee,b1v1r/ironbee,ironbee/ironbee,b1v1r/ironbee,ironbee/ironbee,ironbee/ironbee,ironbee/ironbee,ironbee/ironbee,b1v1r/ironbee,ironbee/ironbee,b1v1r/ironbee,b1v1r/ironbee,b1v1r/ironbee,ironbee/ironbee,b1v1r/ironbee,ironbee/ironbee,b1v1r/ironbee,b1v1r/ironbee,b1v1r/ironbee,ironbee/ironbee,b1v1r/ironbee
8ca8caa25d4db46ef1f03d4ec9cf0225fede77bf
clustering.hpp
clustering.hpp
#pragma once #include <boost/program_options.hpp> #include "config.hpp"
#pragma once
clean up
clean up
C++
bsd-2-clause
lettis/Clustering,lettis/Clustering,lettis/Clustering,lettis/Clustering,lettis/Clustering
4b53e27622fe51585a1e6b07796a2ddcd389ef22
src/util/ot/naor-pinkas.cpp
src/util/ot/naor-pinkas.cpp
#include "naor-pinkas.h" void NaorPinkas::Receiver(uint32_t nSndVals, uint32_t nOTs, CBitVector& choices, CSocket& socket, uint8_t* ret) { fe* PK0 = m_cPKCrypto->get_fe(); fe** PK_sigma = (fe**) malloc(sizeof(fe*) * nOTs); fe** pDec = (fe**) malloc(sizeof(fe*) * nOTs); fe** pC = (fe**) malloc(sizeof(fe*) * nSndVals); fe* g = m_cPKCrypto->get_generator(); num** pK = (num**) malloc(sizeof(num*) * nOTs); uint8_t* retPtr; uint32_t u, k, choice, hash_bytes, fe_bytes; hash_bytes = m_cCrypto->get_hash_bytes(); fe_bytes = m_cPKCrypto->fe_byte_size(); brickexp *bg, *bc; bg = m_cPKCrypto->get_brick(g); //BrickInit(&bg, g, m_fParams); uint8_t* pBuf = (uint8_t*) malloc(sizeof(uint8_t) * nOTs * fe_bytes); uint32_t nBufSize = nSndVals * fe_bytes; //calculate the generator of the group for (k = 0; k < nOTs; k++) { PK_sigma[k] = m_cPKCrypto->get_fe();// FieldElementInit(PK_sigma[k]); pK[k] = m_cPKCrypto->get_rnd_num(); //FieldElementInit(pK[k]); //pK[k]->//GetRandomNumber(pK[k], m_fParams.secparam, m_fParams);/ bg->pow(PK_sigma[k], pK[k]);//BrickPowerMod(&bg, PK_sigma[k], pK[k]); } socket.Receive(pBuf, nBufSize); uint8_t* pBufIdx = pBuf; for (u = 0; u < nSndVals; u++) { pC[u] = m_cPKCrypto->get_fe();//FieldElementInit(pC[u]); pC[u]->import_from_bytes(pBufIdx);//ByteToFieldElement(pC + u, m_fParams.elebytelen, pBufIdx); pBufIdx += fe_bytes; } bc = m_cPKCrypto->get_brick(pC[0]);//BrickInit(&bc, pC[0], m_fParams); //==================================================== // N-P receiver: send pk0 pBufIdx = pBuf; for (k = 0; k < nOTs; k++) { choice = choices.GetBit((int32_t) k); if (choice != 0) { PK0->set_div(pC[choice], PK_sigma[k]);//FieldElementDiv(PK0, pC[choice], PK_sigma[k], m_fParams);//PK0 = pC[choice]; } else { PK0->set(PK_sigma[k]);//FieldElementSet(PK0, PK_sigma[k]);//PK0 = PK_sigma[k]; } //cout << "PK0: " << PK0 << ", PK_sigma: " << PK_sigma[k] << ", choice: " << choice << ", pC[choice: " << pC[choice] << endl; PK0->export_to_bytes(pBufIdx);//FieldElementToByte(pBufIdx, m_fParams.elebytelen, PK0); pBufIdx += fe_bytes;//m_fParams.elebytelen; } socket.Send(pBuf, nOTs * m_cPKCrypto->fe_byte_size()); free(pBuf); pBuf = (uint8_t*) malloc(sizeof(uint8_t) * fe_bytes);//new uint8_t[m_fParams.elebytelen]; retPtr = ret; for (k = 0; k < nOTs; k++) { pDec[k] = m_cPKCrypto->get_fe();//FieldElementInit(pDec[k]); bc->pow(pDec[k], pK[k]);//BrickPowerMod(&bc, pDec[k], pK[k]); pDec[k]->export_to_bytes(pBuf);//FieldElementToByte(pBuf, m_fParams.elebytelen, pDec[k]); hashReturn(retPtr, hash_bytes, pBuf, fe_bytes, k); retPtr += hash_bytes;//SHA1_BYTES; } delete bc;//BrickDelete(&bc); delete bg;//BrickDelete(&bg); delete [] pBuf; //TODO delete all field elements and numbers free(PK_sigma); free(pDec); free(pC); free(pK); } void NaorPinkas::Sender(uint32_t nSndVals, uint32_t nOTs, CSocket& socket, uint8_t* ret) { num *alpha, *PKr, *tmp; fe **pCr, **pC, *fetmp, *PK0r, *g, **pPK0; uint8_t* pBuf, *pBufIdx; uint32_t hash_bytes, fe_bytes, nBufSize, u, k; hash_bytes = m_cCrypto->get_hash_bytes(); fe_bytes = m_cPKCrypto->fe_byte_size(); alpha = m_cPKCrypto->get_rnd_num(); PKr = m_cPKCrypto->get_num(); pCr = (fe**) malloc(sizeof(fe*) * nSndVals); pC = (fe**) malloc(sizeof(fe*) * nSndVals); fetmp = m_cPKCrypto->get_fe(); PK0r = m_cPKCrypto->get_fe(); pC[0] = m_cPKCrypto->get_fe(); g = m_cPKCrypto->get_generator(); /*FieldElementInit(alpha); FieldElementInit(fetmp); FieldElementInit(pC[0]); FieldElementInit(PK0r); FieldElementInit(tmp);*/ //random C1 //GetRandomNumber(alpha, m_fParams.secparam, m_fParams);//alpha = rand(m_nSecParam, 2);//TODO pC[0]->set_pow(g, alpha);//FieldElementPow(pC[0], g, alpha, m_fParams); //random C(i+1) for (u = 1; u < nSndVals; u++) { pC[u] = m_cPKCrypto->get_fe();//FieldElementInit(pC[u]); tmp = m_cPKCrypto->get_rnd_num(); //GetRandomNumber(tmp, m_fParams.secparam, m_fParams);//alpha = rand(m_nSecParam, 2); //TODO pC[u]->set_pow(g, tmp);//FieldElementPow(pC[u], g, tmp, m_fParams); } //==================================================== // Export the generated C_1-C_nSndVals to a uint8_t vector and send them to the receiver nBufSize = nSndVals * fe_bytes; pBuf = (uint8_t*) malloc(nBufSize); pBufIdx = pBuf; for (u = 0; u < nSndVals; u++) { pC[u]->export_to_bytes(pBufIdx);//FieldElementToByte(pBufIdx, m_fParams.elebytelen, pC[u]); pBufIdx += fe_bytes;//m_fParams.elebytelen; } socket.Send(pBuf, nBufSize); //==================================================== // compute C^R for (u = 1; u < nSndVals; u++) { pCr[u] = m_cPKCrypto->get_fe();//FieldElementInit(pCr[u]); pCr[u]->set_pow(pC[u], alpha);//FieldElementPow(pCr[u], pC[u], alpha, m_fParams); } //==================================================== free(pBuf); // N-P sender: receive pk0 nBufSize = fe_bytes * nOTs; pBuf = (uint8_t*) malloc(nBufSize); socket.Receive(pBuf, nBufSize); pBufIdx = pBuf; pPK0 = (fe**) malloc(sizeof(fe*) * nOTs); for (k = 0; k < nOTs; k++) { pPK0[k] = m_cPKCrypto->get_fe(); //FieldElementInit(pPK0[k]); pPK0[k]->import_from_bytes(pBufIdx); //ByteToFieldElement(pPK0 + k, m_fParams.elebytelen, pBufIdx); pBufIdx += fe_bytes; } //==================================================== // Write all nOTs * nSndVals possible values to ret //free(pBuf); TODO fix and uncomment pBuf = (uint8_t*) malloc(sizeof(uint8_t) * fe_bytes * nSndVals); uint8_t* retPtr = ret; fetmp = m_cPKCrypto->get_fe(); for (k = 0; k < nOTs; k++) { pBufIdx = pBuf; for (u = 0; u < nSndVals; u++) { if (u == 0) { // pk0^r PK0r->set_pow(pPK0[k], alpha);//FieldElementPow(PK0r, pPK0[k], alpha, m_fParams); PK0r->export_to_bytes(pBufIdx);//FieldElementToByte(pBufIdx, m_fParams.elebytelen, PK0r); } else { // pk^r fetmp->set_div(pCr[u], PK0r);//FieldElementDiv(fetmp, pCr[u], PK0r, m_fParams); fetmp->export_to_bytes(pBufIdx);//FieldElementToByte(pBufIdx, m_fParams.elebytelen, fetmp); } hashReturn(retPtr, hash_bytes, pBufIdx, fe_bytes, k); pBufIdx += fe_bytes; retPtr += hash_bytes; } } //free(pBuf); free(pCr); free(pC); }
#include "naor-pinkas.h" void NaorPinkas::Receiver(uint32_t nSndVals, uint32_t nOTs, CBitVector& choices, CSocket& socket, uint8_t* ret) { fe* PK0 = m_cPKCrypto->get_fe(); fe** PK_sigma = (fe**) malloc(sizeof(fe*) * nOTs); fe** pDec = (fe**) malloc(sizeof(fe*) * nOTs); fe** pC = (fe**) malloc(sizeof(fe*) * nSndVals); fe* g = m_cPKCrypto->get_generator(); num** pK = (num**) malloc(sizeof(num*) * nOTs); uint8_t* retPtr; uint32_t u, k, choice, hash_bytes, fe_bytes; hash_bytes = m_cCrypto->get_hash_bytes(); fe_bytes = m_cPKCrypto->fe_byte_size(); brickexp *bg, *bc; bg = m_cPKCrypto->get_brick(g); //BrickInit(&bg, g, m_fParams); uint8_t* pBuf = (uint8_t*) malloc(sizeof(uint8_t) * nOTs * fe_bytes); uint32_t nBufSize = nSndVals * fe_bytes; //calculate the generator of the group for (k = 0; k < nOTs; k++) { PK_sigma[k] = m_cPKCrypto->get_fe();// FieldElementInit(PK_sigma[k]); pK[k] = m_cPKCrypto->get_rnd_num(); //FieldElementInit(pK[k]); //pK[k]->//GetRandomNumber(pK[k], m_fParams.secparam, m_fParams);/ bg->pow(PK_sigma[k], pK[k]);//BrickPowerMod(&bg, PK_sigma[k], pK[k]); } socket.Receive(pBuf, nBufSize); uint8_t* pBufIdx = pBuf; for (u = 0; u < nSndVals; u++) { pC[u] = m_cPKCrypto->get_fe();//FieldElementInit(pC[u]); pC[u]->import_from_bytes(pBufIdx);//ByteToFieldElement(pC + u, m_fParams.elebytelen, pBufIdx); pBufIdx += fe_bytes; } bc = m_cPKCrypto->get_brick(pC[0]);//BrickInit(&bc, pC[0], m_fParams); //==================================================== // N-P receiver: send pk0 pBufIdx = pBuf; for (k = 0; k < nOTs; k++) { choice = choices.GetBit((int32_t) k); if (choice != 0) { PK0->set_div(pC[choice], PK_sigma[k]);//FieldElementDiv(PK0, pC[choice], PK_sigma[k], m_fParams);//PK0 = pC[choice]; } else { PK0->set(PK_sigma[k]);//FieldElementSet(PK0, PK_sigma[k]);//PK0 = PK_sigma[k]; } //cout << "PK0: " << PK0 << ", PK_sigma: " << PK_sigma[k] << ", choice: " << choice << ", pC[choice: " << pC[choice] << endl; PK0->export_to_bytes(pBufIdx);//FieldElementToByte(pBufIdx, m_fParams.elebytelen, PK0); pBufIdx += fe_bytes;//m_fParams.elebytelen; } socket.Send(pBuf, nOTs * m_cPKCrypto->fe_byte_size()); free(pBuf); pBuf = (uint8_t*) malloc(sizeof(uint8_t) * fe_bytes);//new uint8_t[m_fParams.elebytelen]; retPtr = ret; for (k = 0; k < nOTs; k++) { pDec[k] = m_cPKCrypto->get_fe();//FieldElementInit(pDec[k]); bc->pow(pDec[k], pK[k]);//BrickPowerMod(&bc, pDec[k], pK[k]); pDec[k]->export_to_bytes(pBuf);//FieldElementToByte(pBuf, m_fParams.elebytelen, pDec[k]); hashReturn(retPtr, hash_bytes, pBuf, fe_bytes, k); retPtr += hash_bytes;//SHA1_BYTES; } delete bc;//BrickDelete(&bc); delete bg;//BrickDelete(&bg); free(pBuf); //TODO delete all field elements and numbers free(PK_sigma); free(pDec); free(pC); free(pK); } void NaorPinkas::Sender(uint32_t nSndVals, uint32_t nOTs, CSocket& socket, uint8_t* ret) { num *alpha, *PKr, *tmp; fe **pCr, **pC, *fetmp, *PK0r, *g, **pPK0; uint8_t* pBuf, *pBufIdx; uint32_t hash_bytes, fe_bytes, nBufSize, u, k; hash_bytes = m_cCrypto->get_hash_bytes(); fe_bytes = m_cPKCrypto->fe_byte_size(); alpha = m_cPKCrypto->get_rnd_num(); PKr = m_cPKCrypto->get_num(); pCr = (fe**) malloc(sizeof(fe*) * nSndVals); pC = (fe**) malloc(sizeof(fe*) * nSndVals); fetmp = m_cPKCrypto->get_fe(); PK0r = m_cPKCrypto->get_fe(); pC[0] = m_cPKCrypto->get_fe(); g = m_cPKCrypto->get_generator(); /*FieldElementInit(alpha); FieldElementInit(fetmp); FieldElementInit(pC[0]); FieldElementInit(PK0r); FieldElementInit(tmp);*/ //random C1 //GetRandomNumber(alpha, m_fParams.secparam, m_fParams);//alpha = rand(m_nSecParam, 2);//TODO pC[0]->set_pow(g, alpha);//FieldElementPow(pC[0], g, alpha, m_fParams); //random C(i+1) for (u = 1; u < nSndVals; u++) { pC[u] = m_cPKCrypto->get_fe();//FieldElementInit(pC[u]); tmp = m_cPKCrypto->get_rnd_num(); //GetRandomNumber(tmp, m_fParams.secparam, m_fParams);//alpha = rand(m_nSecParam, 2); //TODO pC[u]->set_pow(g, tmp);//FieldElementPow(pC[u], g, tmp, m_fParams); } //==================================================== // Export the generated C_1-C_nSndVals to a uint8_t vector and send them to the receiver nBufSize = nSndVals * fe_bytes; pBuf = (uint8_t*) malloc(nBufSize); pBufIdx = pBuf; for (u = 0; u < nSndVals; u++) { pC[u]->export_to_bytes(pBufIdx);//FieldElementToByte(pBufIdx, m_fParams.elebytelen, pC[u]); pBufIdx += fe_bytes;//m_fParams.elebytelen; } socket.Send(pBuf, nBufSize); //==================================================== // compute C^R for (u = 1; u < nSndVals; u++) { pCr[u] = m_cPKCrypto->get_fe();//FieldElementInit(pCr[u]); pCr[u]->set_pow(pC[u], alpha);//FieldElementPow(pCr[u], pC[u], alpha, m_fParams); } //==================================================== free(pBuf); // N-P sender: receive pk0 nBufSize = fe_bytes * nOTs; pBuf = (uint8_t*) malloc(nBufSize); socket.Receive(pBuf, nBufSize); pBufIdx = pBuf; pPK0 = (fe**) malloc(sizeof(fe*) * nOTs); for (k = 0; k < nOTs; k++) { pPK0[k] = m_cPKCrypto->get_fe(); //FieldElementInit(pPK0[k]); pPK0[k]->import_from_bytes(pBufIdx); //ByteToFieldElement(pPK0 + k, m_fParams.elebytelen, pBufIdx); pBufIdx += fe_bytes; } //==================================================== // Write all nOTs * nSndVals possible values to ret //free(pBuf); TODO fix and uncomment pBuf = (uint8_t*) malloc(sizeof(uint8_t) * fe_bytes * nSndVals); uint8_t* retPtr = ret; fetmp = m_cPKCrypto->get_fe(); for (k = 0; k < nOTs; k++) { pBufIdx = pBuf; for (u = 0; u < nSndVals; u++) { if (u == 0) { // pk0^r PK0r->set_pow(pPK0[k], alpha);//FieldElementPow(PK0r, pPK0[k], alpha, m_fParams); PK0r->export_to_bytes(pBufIdx);//FieldElementToByte(pBufIdx, m_fParams.elebytelen, PK0r); } else { // pk^r fetmp->set_div(pCr[u], PK0r);//FieldElementDiv(fetmp, pCr[u], PK0r, m_fParams); fetmp->export_to_bytes(pBufIdx);//FieldElementToByte(pBufIdx, m_fParams.elebytelen, fetmp); } hashReturn(retPtr, hash_bytes, pBufIdx, fe_bytes, k); pBufIdx += fe_bytes; retPtr += hash_bytes; } } free(pBuf); free(pCr); free(pC); }
correct de-allocation of memory
correct de-allocation of memory
C++
agpl-3.0
encryptogroup/PSI,encryptogroup/PSI,encryptogroup/PSI