<commit_before>// Copyright 2016 Yahoo Inc. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.

#include <cppunit/extensions/HelperMacros.h>
#include <vespa/document/serialization/vespadocumentdeserializer.h>
#include <vespa/document/serialization/vespadocumentserializer.h>
#include <vespa/vespalib/objects/nbostream.h>
#include <vespa/vespalib/testkit/test_kit.h>
#include <vespa/document/bucket/bucketidfactory.h>
#include <vespa/document/base/documentid.h>
#include <vespa/document/datatype/documenttype.h>
#include <vespa/vespalib/util/md5.h>

using document::VespaDocumentDeserializer;
using document::VespaDocumentSerializer;
using vespalib::nbostream;

namespace document {

struct DocumentIdTest : public CppUnit::TestFixture {
    void generateJavaComplianceFile();
    void testOutput();
    void testEqualityOperator();
    void testCopying();
    void testParseId();
    void checkNtnuGlobalId();
    void testDocGlobalId();
    void freestandingLocationFromGroupNameFuncMatchesIdLocation();

    CPPUNIT_TEST_SUITE(DocumentIdTest);
    CPPUNIT_TEST(testEqualityOperator);
    CPPUNIT_TEST(testOutput);
    CPPUNIT_TEST(testCopying);
    CPPUNIT_TEST(generateJavaComplianceFile);
    CPPUNIT_TEST(testParseId);
    CPPUNIT_TEST(checkNtnuGlobalId);
    CPPUNIT_TEST(testDocGlobalId);
    CPPUNIT_TEST(freestandingLocationFromGroupNameFuncMatchesIdLocation);
    CPPUNIT_TEST_SUITE_END();

};

CPPUNIT_TEST_SUITE_REGISTRATION(DocumentIdTest);

namespace {
    void writeGlobalIdBucketId(std::ostream& out, const std::string& id) {
        BucketIdFactory factory;
        out << id << " - " << document::DocumentId(id).getGlobalId()
            << " - " << factory.getBucketId(document::DocumentId(id)).toString()
            << "\n";
    }
}

void DocumentIdTest::generateJavaComplianceFile()
{
    {  // Generate file with globalids and bucket ID of various document ids,
       // which java will use to ensure equal implementations.
        std::ostringstream ost;
        writeGlobalIdBucketId(ost, "doc:ns:specific");
        writeGlobalIdBucketId(ost, "doc:another:specific");
        writeGlobalIdBucketId(ost, "doc:ns:another");
        writeGlobalIdBucketId(ost, "userdoc:ns:100:specific");
        writeGlobalIdBucketId(ost, "userdoc:np:100:another");
        writeGlobalIdBucketId(ost, "userdoc:ns:101:specific");
        writeGlobalIdBucketId(ost, "groupdoc:ns:agroup:specific");
        writeGlobalIdBucketId(ost, "groupdoc:np:agroup:another");
        writeGlobalIdBucketId(ost, "groupdoc:ns:another:specific");
        for (uint32_t i=0; i<20; ++i) {
            std::ostringstream ost2;
            ost2 << i;
            writeGlobalIdBucketId(ost, "doc:ns:"+ost2.str());
        }
        writeGlobalIdBucketId(ost, "id:ns:type::specific");
        writeGlobalIdBucketId(ost, "id:another:type::specific");
        writeGlobalIdBucketId(ost, "id:ns:type::another");
        writeGlobalIdBucketId(ost, "id:ns:type:n=100:specific");
        writeGlobalIdBucketId(ost, "id:np:type:n=100:another");
        writeGlobalIdBucketId(ost, "id:ns:type:n=101:specific");
        writeGlobalIdBucketId(ost, "id:ns:type:g=agroup:specific");
        writeGlobalIdBucketId(ost, "id:np:type:g=agroup:another");
        writeGlobalIdBucketId(ost, "id:ns:type:g=another:specific");
        FastOS_File file;
        CPPUNIT_ASSERT(file.OpenWriteOnlyTruncate(TEST_PATH("cpp-globalidbucketids.txt").c_str()));
        std::string content(ost.str());
        CPPUNIT_ASSERT(file.CheckedWrite(content.c_str(), content.size()));
        CPPUNIT_ASSERT(file.Close());
    }
}

void DocumentIdTest::testOutput()
{
    DocumentId id(DocIdString("crawler", "http://www.yahoo.com"));

    std::ostringstream ost;
    ost << id;
    std::string expected("doc:crawler:http://www.yahoo.com");
    CPPUNIT_ASSERT_EQUAL(expected, ost.str());

    CPPUNIT_ASSERT_EQUAL(vespalib::string(expected), id.toString());

    expected = "DocumentId(id = doc:crawler:http://www.yahoo.com, "
                          "gid(0x928baffb39cf32004542fb60))";
    CPPUNIT_ASSERT_EQUAL(expected, static_cast<Printable&>(id).toString(true));
}

namespace {
    template<class T>
    std::string getNotEqualMessage(const T& t1, const T& t2) {
        std::ostringstream ost;
        ost << "Expected instances to be different. This was not the case:\n"
            << t1 << "\n" << t2 << "\n";
        return ost.str();
    }
}

void DocumentIdTest::testEqualityOperator()
{
    std::string uri(DocIdString("crawler", "http://www.yahoo.com").toString());

    DocumentId id1(uri);
    DocumentId id2(uri);
    DocumentId id3("doc:crawler:http://www.yahoo.no/");

    CPPUNIT_ASSERT_EQUAL(id1, id2);
    CPPUNIT_ASSERT_MESSAGE(getNotEqualMessage(id1, id3), !(id1 == id3));
}

void DocumentIdTest::testCopying()
{
    std::string uri(DocIdString("crawler", "http://www.yahoo.com/").toString());

    DocumentId id1(uri);
    DocumentId id2(id1);
    DocumentId id3("doc:ns:foo");
    id3 = id2;

    CPPUNIT_ASSERT_EQUAL(id1, id2);
    CPPUNIT_ASSERT_EQUAL(id1, id3);
}

void
DocumentIdTest::testParseId()
{
    // Moved to base/documentid_test.cpp
}

void
DocumentIdTest::checkNtnuGlobalId()
{
    DocumentId id("doc:crawler:http://www.ntnu.no/");
    CPPUNIT_ASSERT_EQUAL(vespalib::string("gid(0xb8863740be14221c0ac77896)"),
                         id.getGlobalId().toString());
}

void
DocumentIdTest::testDocGlobalId()
{
        // Test that location of doc scheme documents are set correctly, such
        // that the location is the first bytes of the original GID.
    std::string id("doc:crawler:http://www.ntnu.no/");
    DocumentId did(id);

    unsigned char key[16];
    fastc_md5sum(reinterpret_cast<const unsigned char*>(id.c_str()),
                 id.size(), key);

    CPPUNIT_ASSERT_EQUAL(GlobalId(key), did.getGlobalId());
}

void
DocumentIdTest::freestandingLocationFromGroupNameFuncMatchesIdLocation()
{
    CPPUNIT_ASSERT_EQUAL(
            DocumentId("id::foo:g=zoid:bar").getScheme().getLocation(),
            GroupDocIdString::locationFromGroupName("zoid"));
    CPPUNIT_ASSERT_EQUAL(
            DocumentId("id::bar:g=doink:baz").getScheme().getLocation(),
            GroupDocIdString::locationFromGroupName("doink"));
}

} // document
<commit_msg>Add missing include<commit_after>// Copyright 2016 Yahoo Inc. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.

#include <cppunit/extensions/HelperMacros.h>
#include <vespa/document/serialization/vespadocumentdeserializer.h>
#include <vespa/document/serialization/vespadocumentserializer.h>
#include <vespa/vespalib/objects/nbostream.h>
#include <vespa/vespalib/testkit/test_kit.h>
#include <vespa/document/bucket/bucketidfactory.h>
#include <vespa/document/base/documentid.h>
#include <vespa/document/datatype/documenttype.h>
#include <vespa/vespalib/util/md5.h>
#include <vespa/fastos/file.h>

using document::VespaDocumentDeserializer;
using document::VespaDocumentSerializer;
using vespalib::nbostream;

namespace document {

struct DocumentIdTest : public CppUnit::TestFixture {
    void generateJavaComplianceFile();
    void testOutput();
    void testEqualityOperator();
    void testCopying();
    void testParseId();
    void checkNtnuGlobalId();
    void testDocGlobalId();
    void freestandingLocationFromGroupNameFuncMatchesIdLocation();

    CPPUNIT_TEST_SUITE(DocumentIdTest);
    CPPUNIT_TEST(testEqualityOperator);
    CPPUNIT_TEST(testOutput);
    CPPUNIT_TEST(testCopying);
    CPPUNIT_TEST(generateJavaComplianceFile);
    CPPUNIT_TEST(testParseId);
    CPPUNIT_TEST(checkNtnuGlobalId);
    CPPUNIT_TEST(testDocGlobalId);
    CPPUNIT_TEST(freestandingLocationFromGroupNameFuncMatchesIdLocation);
    CPPUNIT_TEST_SUITE_END();

};

CPPUNIT_TEST_SUITE_REGISTRATION(DocumentIdTest);

namespace {
    void writeGlobalIdBucketId(std::ostream& out, const std::string& id) {
        BucketIdFactory factory;
        out << id << " - " << document::DocumentId(id).getGlobalId()
            << " - " << factory.getBucketId(document::DocumentId(id)).toString()
            << "\n";
    }
}

void DocumentIdTest::generateJavaComplianceFile()
{
    {  // Generate file with globalids and bucket ID of various document ids,
       // which java will use to ensure equal implementations.
        std::ostringstream ost;
        writeGlobalIdBucketId(ost, "doc:ns:specific");
        writeGlobalIdBucketId(ost, "doc:another:specific");
        writeGlobalIdBucketId(ost, "doc:ns:another");
        writeGlobalIdBucketId(ost, "userdoc:ns:100:specific");
        writeGlobalIdBucketId(ost, "userdoc:np:100:another");
        writeGlobalIdBucketId(ost, "userdoc:ns:101:specific");
        writeGlobalIdBucketId(ost, "groupdoc:ns:agroup:specific");
        writeGlobalIdBucketId(ost, "groupdoc:np:agroup:another");
        writeGlobalIdBucketId(ost, "groupdoc:ns:another:specific");
        for (uint32_t i=0; i<20; ++i) {
            std::ostringstream ost2;
            ost2 << i;
            writeGlobalIdBucketId(ost, "doc:ns:"+ost2.str());
        }
        writeGlobalIdBucketId(ost, "id:ns:type::specific");
        writeGlobalIdBucketId(ost, "id:another:type::specific");
        writeGlobalIdBucketId(ost, "id:ns:type::another");
        writeGlobalIdBucketId(ost, "id:ns:type:n=100:specific");
        writeGlobalIdBucketId(ost, "id:np:type:n=100:another");
        writeGlobalIdBucketId(ost, "id:ns:type:n=101:specific");
        writeGlobalIdBucketId(ost, "id:ns:type:g=agroup:specific");
        writeGlobalIdBucketId(ost, "id:np:type:g=agroup:another");
        writeGlobalIdBucketId(ost, "id:ns:type:g=another:specific");
        FastOS_File file;
        CPPUNIT_ASSERT(file.OpenWriteOnlyTruncate(TEST_PATH("cpp-globalidbucketids.txt").c_str()));
        std::string content(ost.str());
        CPPUNIT_ASSERT(file.CheckedWrite(content.c_str(), content.size()));
        CPPUNIT_ASSERT(file.Close());
    }
}

void DocumentIdTest::testOutput()
{
    DocumentId id(DocIdString("crawler", "http://www.yahoo.com"));

    std::ostringstream ost;
    ost << id;
    std::string expected("doc:crawler:http://www.yahoo.com");
    CPPUNIT_ASSERT_EQUAL(expected, ost.str());

    CPPUNIT_ASSERT_EQUAL(vespalib::string(expected), id.toString());

    expected = "DocumentId(id = doc:crawler:http://www.yahoo.com, "
                          "gid(0x928baffb39cf32004542fb60))";
    CPPUNIT_ASSERT_EQUAL(expected, static_cast<Printable&>(id).toString(true));
}

namespace {
    template<class T>
    std::string getNotEqualMessage(const T& t1, const T& t2) {
        std::ostringstream ost;
        ost << "Expected instances to be different. This was not the case:\n"
            << t1 << "\n" << t2 << "\n";
        return ost.str();
    }
}

void DocumentIdTest::testEqualityOperator()
{
    std::string uri(DocIdString("crawler", "http://www.yahoo.com").toString());

    DocumentId id1(uri);
    DocumentId id2(uri);
    DocumentId id3("doc:crawler:http://www.yahoo.no/");

    CPPUNIT_ASSERT_EQUAL(id1, id2);
    CPPUNIT_ASSERT_MESSAGE(getNotEqualMessage(id1, id3), !(id1 == id3));
}

void DocumentIdTest::testCopying()
{
    std::string uri(DocIdString("crawler", "http://www.yahoo.com/").toString());

    DocumentId id1(uri);
    DocumentId id2(id1);
    DocumentId id3("doc:ns:foo");
    id3 = id2;

    CPPUNIT_ASSERT_EQUAL(id1, id2);
    CPPUNIT_ASSERT_EQUAL(id1, id3);
}

void
DocumentIdTest::testParseId()
{
    // Moved to base/documentid_test.cpp
}

void
DocumentIdTest::checkNtnuGlobalId()
{
    DocumentId id("doc:crawler:http://www.ntnu.no/");
    CPPUNIT_ASSERT_EQUAL(vespalib::string("gid(0xb8863740be14221c0ac77896)"),
                         id.getGlobalId().toString());
}

void
DocumentIdTest::testDocGlobalId()
{
        // Test that location of doc scheme documents are set correctly, such
        // that the location is the first bytes of the original GID.
    std::string id("doc:crawler:http://www.ntnu.no/");
    DocumentId did(id);

    unsigned char key[16];
    fastc_md5sum(reinterpret_cast<const unsigned char*>(id.c_str()),
                 id.size(), key);

    CPPUNIT_ASSERT_EQUAL(GlobalId(key), did.getGlobalId());
}

void
DocumentIdTest::freestandingLocationFromGroupNameFuncMatchesIdLocation()
{
    CPPUNIT_ASSERT_EQUAL(
            DocumentId("id::foo:g=zoid:bar").getScheme().getLocation(),
            GroupDocIdString::locationFromGroupName("zoid"));
    CPPUNIT_ASSERT_EQUAL(
            DocumentId("id::bar:g=doink:baz").getScheme().getLocation(),
            GroupDocIdString::locationFromGroupName("doink"));
}

} // document
<|endoftext|>


<commit_before>/****************************************************************************
**
** Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies).
** Contact: Qt Software Information (qt-info@nokia.com)
**
** This file is part of the examples of the Qt Toolkit.
**
** $QT_BEGIN_LICENSE:LGPL$
** No Commercial Usage
** This file contains pre-release code and may not be distributed.
** You may use this file in accordance with the terms and conditions
** contained in the either Technology Preview License Agreement or the
** Beta Release License Agreement.
**
** 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.0, included in the file LGPL_EXCEPTION.txt in this
** package.
**
** GNU General Public License Usage
** Alternatively, this file may be used under the terms of the GNU
** General Public License version 3.0 as published by the Free Software
** Foundation and appearing in the file LICENSE.GPL included in the
** packaging of this file.  Please review the following information to
** ensure the GNU General Public License version 3.0 requirements will be
** met: http://www.gnu.org/copyleft/gpl.html.
**
** If you are unsure which license is appropriate for your use, please
** contact the sales department at qt-sales@nokia.com.
** $QT_END_LICENSE$
**
****************************************************************************/

#include <QtGui>

#include <codeeditor.h>

//![constructor]

CodeEditor::CodeEditor(QWidget *parent) : QPlainTextEdit(parent)
{
    lineNumberArea = new LineNumberArea(this);

    connect(this, SIGNAL(blockCountChanged(int)), this, SLOT(updateLineNumberAreaWidth(int)));
    connect(this, SIGNAL(updateRequest(const QRect &, int)), this, SLOT(updateLineNumberArea(const QRect &, int)));
    connect(this, SIGNAL(cursorPositionChanged()), this, SLOT(highlightCurrentLine()));

    updateLineNumberAreaWidth(0);
    highlightCurrentLine();
}

//![constructor]

//![extraAreaWidth]

int CodeEditor::lineNumberAreaWidth()
{
    int digits = 1;
    int max = qMax(1, blockCount());
    while (max >= 10) {
        max /= 10;
        ++digits;
    }

    int space = 3 + fontMetrics().width(QLatin1Char('9')) * digits;

    return space;
}

//![extraAreaWidth]

//![slotUpdateExtraAreaWidth]

void CodeEditor::updateLineNumberAreaWidth(int /* newBlockCount */)
{
    setViewportMargins(lineNumberAreaWidth(), 0, 0, 0);
}

//![slotUpdateExtraAreaWidth]

//![slotUpdateRequest]

void CodeEditor::updateLineNumberArea(const QRect &rect, int dy)
{
    if (dy)
        lineNumberArea->scroll(0, dy);
    else
        lineNumberArea->update(0, rect.y(), lineNumberArea->width(), rect.height());

    if (rect.contains(viewport()->rect()))
        updateLineNumberAreaWidth(0);
}

//![slotUpdateRequest]

//![resizeEvent]

void CodeEditor::resizeEvent(QResizeEvent *e)
{
    QPlainTextEdit::resizeEvent(e);

    QRect cr = contentsRect();
    lineNumberArea->setGeometry(QRect(cr.left(), cr.top(), lineNumberAreaWidth(), cr.height()));
}

//![resizeEvent]

//![cursorPositionChanged]

void CodeEditor::highlightCurrentLine()
{
    QList<QTextEdit::ExtraSelection> extraSelections;

    if (!isReadOnly()) {
        QTextEdit::ExtraSelection selection;

        QColor lineColor = QColor(Qt::yellow).lighter(160);

        selection.format.setBackground(lineColor);
        selection.format.setProperty(QTextFormat::FullWidthSelection, true);
        selection.cursor = textCursor();
        selection.cursor.clearSelection();
        extraSelections.append(selection);
    }

    setExtraSelections(extraSelections);
}

//![cursorPositionChanged]

//![extraAreaPaintEvent_0]

void CodeEditor::lineNumberAreaPaintEvent(QPaintEvent *event)
{
    QPainter painter(lineNumberArea);
    painter.fillRect(event->rect(), Qt::lightGray);

//![extraAreaPaintEvent_0]

//![extraAreaPaintEvent_1]
    QTextBlock block = firstVisibleBlock();
    int blockNumber = block.blockNumber();
    int top = (int) blockBoundingGeometry(block).translated(contentOffset()).top();
    int bottom = top + (int) blockBoundingRect(block).height();
//![extraAreaPaintEvent_1]

//![extraAreaPaintEvent_2]
    while (block.isValid() && top <= event->rect().bottom()) {
        if (block.isVisible() && bottom >= event->rect().top()) {
            QString number = QString::number(blockNumber + 1);
            painter.setPen(Qt::black);
            painter.drawText(0, top, lineNumberArea->width(), fontMetrics().height(),
                             Qt::AlignRight, number);
        }

        block = block.next();
        top = bottom;
        bottom = top + (int) blockBoundingRect(block).height();
        ++blockNumber;
    }
}
//![extraAreaPaintEvent_2]

<commit_msg>Make the codeeditor example compile on Windows.<commit_after>/****************************************************************************
**
** Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies).
** Contact: Qt Software Information (qt-info@nokia.com)
**
** This file is part of the examples of the Qt Toolkit.
**
** $QT_BEGIN_LICENSE:LGPL$
** No Commercial Usage
** This file contains pre-release code and may not be distributed.
** You may use this file in accordance with the terms and conditions
** contained in the either Technology Preview License Agreement or the
** Beta Release License Agreement.
**
** 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.0, included in the file LGPL_EXCEPTION.txt in this
** package.
**
** GNU General Public License Usage
** Alternatively, this file may be used under the terms of the GNU
** General Public License version 3.0 as published by the Free Software
** Foundation and appearing in the file LICENSE.GPL included in the
** packaging of this file.  Please review the following information to
** ensure the GNU General Public License version 3.0 requirements will be
** met: http://www.gnu.org/copyleft/gpl.html.
**
** If you are unsure which license is appropriate for your use, please
** contact the sales department at qt-sales@nokia.com.
** $QT_END_LICENSE$
**
****************************************************************************/

#include <QtGui>

#include "codeeditor.h"

//![constructor]

CodeEditor::CodeEditor(QWidget *parent) : QPlainTextEdit(parent)
{
    lineNumberArea = new LineNumberArea(this);

    connect(this, SIGNAL(blockCountChanged(int)), this, SLOT(updateLineNumberAreaWidth(int)));
    connect(this, SIGNAL(updateRequest(const QRect &, int)), this, SLOT(updateLineNumberArea(const QRect &, int)));
    connect(this, SIGNAL(cursorPositionChanged()), this, SLOT(highlightCurrentLine()));

    updateLineNumberAreaWidth(0);
    highlightCurrentLine();
}

//![constructor]

//![extraAreaWidth]

int CodeEditor::lineNumberAreaWidth()
{
    int digits = 1;
    int max = qMax(1, blockCount());
    while (max >= 10) {
        max /= 10;
        ++digits;
    }

    int space = 3 + fontMetrics().width(QLatin1Char('9')) * digits;

    return space;
}

//![extraAreaWidth]

//![slotUpdateExtraAreaWidth]

void CodeEditor::updateLineNumberAreaWidth(int /* newBlockCount */)
{
    setViewportMargins(lineNumberAreaWidth(), 0, 0, 0);
}

//![slotUpdateExtraAreaWidth]

//![slotUpdateRequest]

void CodeEditor::updateLineNumberArea(const QRect &rect, int dy)
{
    if (dy)
        lineNumberArea->scroll(0, dy);
    else
        lineNumberArea->update(0, rect.y(), lineNumberArea->width(), rect.height());

    if (rect.contains(viewport()->rect()))
        updateLineNumberAreaWidth(0);
}

//![slotUpdateRequest]

//![resizeEvent]

void CodeEditor::resizeEvent(QResizeEvent *e)
{
    QPlainTextEdit::resizeEvent(e);

    QRect cr = contentsRect();
    lineNumberArea->setGeometry(QRect(cr.left(), cr.top(), lineNumberAreaWidth(), cr.height()));
}

//![resizeEvent]

//![cursorPositionChanged]

void CodeEditor::highlightCurrentLine()
{
    QList<QTextEdit::ExtraSelection> extraSelections;

    if (!isReadOnly()) {
        QTextEdit::ExtraSelection selection;

        QColor lineColor = QColor(Qt::yellow).lighter(160);

        selection.format.setBackground(lineColor);
        selection.format.setProperty(QTextFormat::FullWidthSelection, true);
        selection.cursor = textCursor();
        selection.cursor.clearSelection();
        extraSelections.append(selection);
    }

    setExtraSelections(extraSelections);
}

//![cursorPositionChanged]

//![extraAreaPaintEvent_0]

void CodeEditor::lineNumberAreaPaintEvent(QPaintEvent *event)
{
    QPainter painter(lineNumberArea);
    painter.fillRect(event->rect(), Qt::lightGray);

//![extraAreaPaintEvent_0]

//![extraAreaPaintEvent_1]
    QTextBlock block = firstVisibleBlock();
    int blockNumber = block.blockNumber();
    int top = (int) blockBoundingGeometry(block).translated(contentOffset()).top();
    int bottom = top + (int) blockBoundingRect(block).height();
//![extraAreaPaintEvent_1]

//![extraAreaPaintEvent_2]
    while (block.isValid() && top <= event->rect().bottom()) {
        if (block.isVisible() && bottom >= event->rect().top()) {
            QString number = QString::number(blockNumber + 1);
            painter.setPen(Qt::black);
            painter.drawText(0, top, lineNumberArea->width(), fontMetrics().height(),
                             Qt::AlignRight, number);
        }

        block = block.next();
        top = bottom;
        bottom = top + (int) blockBoundingRect(block).height();
        ++blockNumber;
    }
}
//![extraAreaPaintEvent_2]

<|endoftext|>


<commit_before>/****************************************************************************
**
** Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies).
** Contact: Qt Software Information (qt-info@nokia.com)
**
** This file is part of the examples of the Qt Toolkit.
**
** $QT_BEGIN_LICENSE:LGPL$
** No Commercial Usage
** This file contains pre-release code and may not be distributed.
** You may use this file in accordance with the terms and conditions
** contained in the either Technology Preview License Agreement or the
** Beta Release License Agreement.
**
** 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.0, included in the file LGPL_EXCEPTION.txt in this
** package.
**
** GNU General Public License Usage
** Alternatively, this file may be used under the terms of the GNU
** General Public License version 3.0 as published by the Free Software
** Foundation and appearing in the file LICENSE.GPL included in the
** packaging of this file.  Please review the following information to
** ensure the GNU General Public License version 3.0 requirements will be
** met: http://www.gnu.org/copyleft/gpl.html.
**
** If you are unsure which license is appropriate for your use, please
** contact the sales department at qt-sales@nokia.com.
** $QT_END_LICENSE$
**
****************************************************************************/

#include <QtGui>

#include "mainwindow.h"
#include "stylesheeteditor.h"

MainWindow::MainWindow()
{
    ui.setupUi(this);

    ui.nameLabel->setProperty("class", "mandatory QLabel");

    styleSheetEditor = new StyleSheetEditor(this);

    statusBar()->addWidget(new QLabel(tr("Ready")));

    connect(ui.exitAction, SIGNAL(triggered()), qApp, SLOT(quit()));
    connect(ui.aboutQtAction, SIGNAL(triggered()), qApp, SLOT(aboutQt()));
}

void MainWindow::on_editStyleAction_triggered()
{
    styleSheetEditor->show();
    styleSheetEditor->activateWindow();
}

void MainWindow::on_aboutAction_triggered()
{
    QMessageBox::about(this, tr("About Style sheet"),
        tr("The Style Sheet example shows how widgets can be styled "
           "using Qt "
           "Style Sheets. Click File|Edit Style Sheet to pop up the "
           "style editor, and either choose an existing style sheet or design "
           "your own."));
}
<commit_msg>Changed stylesheets example to create softkeystack. This commit should probably be reverted before merging to master<commit_after>/****************************************************************************
**
** Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies).
** Contact: Qt Software Information (qt-info@nokia.com)
**
** This file is part of the examples of the Qt Toolkit.
**
** $QT_BEGIN_LICENSE:LGPL$
** No Commercial Usage
** This file contains pre-release code and may not be distributed.
** You may use this file in accordance with the terms and conditions
** contained in the either Technology Preview License Agreement or the
** Beta Release License Agreement.
**
** 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.0, included in the file LGPL_EXCEPTION.txt in this
** package.
**
** GNU General Public License Usage
** Alternatively, this file may be used under the terms of the GNU
** General Public License version 3.0 as published by the Free Software
** Foundation and appearing in the file LICENSE.GPL included in the
** packaging of this file.  Please review the following information to
** ensure the GNU General Public License version 3.0 requirements will be
** met: http://www.gnu.org/copyleft/gpl.html.
**
** If you are unsure which license is appropriate for your use, please
** contact the sales department at qt-sales@nokia.com.
** $QT_END_LICENSE$
**
****************************************************************************/

#include <QtGui>

#include "mainwindow.h"
#include "stylesheeteditor.h"

MainWindow::MainWindow()
{
    QSoftKeyStack* stack = new QSoftKeyStack(this);
    setSoftKeyStack(stack);

    ui.setupUi(this);

    ui.nameLabel->setProperty("class", "mandatory QLabel");

    styleSheetEditor = new StyleSheetEditor(this);

    statusBar()->addWidget(new QLabel(tr("Ready")));

    connect(ui.exitAction, SIGNAL(triggered()), qApp, SLOT(quit()));
    connect(ui.aboutQtAction, SIGNAL(triggered()), qApp, SLOT(aboutQt()));
}

void MainWindow::on_editStyleAction_triggered()
{
    styleSheetEditor->show();
    styleSheetEditor->activateWindow();
}

void MainWindow::on_aboutAction_triggered()
{
    QMessageBox::about(this, tr("About Style sheet"),
        tr("The Style Sheet example shows how widgets can be styled "
           "using Qt "
           "Style Sheets. Click File|Edit Style Sheet to pop up the "
           "style editor, and either choose an existing style sheet or design "
           "your own."));
}
<|endoftext|>


<commit_before>/*
// Copyright (c) 2018 Intel Corporation
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//      http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
*/

#include "channelcommands.hpp"

#include "apphandler.hpp"
#include "channel_layer.hpp"

#include <phosphor-logging/log.hpp>
#include <regex>

using namespace phosphor::logging;

namespace ipmi
{

/** @struct SetChannelAccessReq
 *
 *  Structure for set channel access request command (refer spec sec 22.22)
 */
struct SetChannelAccessReq
{
#if BYTE_ORDER == LITTLE_ENDIAN
    uint8_t chNum : 4;
    uint8_t reserved_1 : 4;
    uint8_t accessMode : 3;
    uint8_t usrAuthDisabled : 1;
    uint8_t msgAuthDisabled : 1;
    uint8_t alertDisabled : 1;
    uint8_t accessSetMode : 2;
    uint8_t privLimit : 4;
    uint8_t reserved_2 : 2;
    uint8_t privSetMode : 2;
#endif
#if BYTE_ORDER == BIG_ENDIAN
    uint8_t reserved_1 : 4;
    uint8_t chNum : 4;
    uint8_t accessSetMode : 2;
    uint8_t alertDisabled : 1;
    uint8_t msgAuthDisabled : 1;
    uint8_t usrAuthDisabled : 1;
    uint8_t accessMode : 3;
    uint8_t privSetMode : 2;
    uint8_t reserved_2 : 2;
    uint8_t privLimit : 4;
#endif

} __attribute__((packed));

/** @struct GetChannelAccessReq
 *
 *  Structure for get channel access request command (refer spec sec 22.23)
 */
struct GetChannelAccessReq
{
#if BYTE_ORDER == LITTLE_ENDIAN
    uint8_t chNum : 4;
    uint8_t reserved_1 : 4;
    uint8_t reserved_2 : 6;
    uint8_t accessSetMode : 2;
#endif
#if BYTE_ORDER == BIG_ENDIAN
    uint8_t reserved_1 : 4;
    uint8_t chNum : 4;
    uint8_t accessSetMode : 2;
    uint8_t reserved_2 : 6;
#endif
} __attribute__((packed));

/** @struct GetChannelAccessResp
 *
 *  Structure for get channel access response command (refer spec sec 22.23)
 */
struct GetChannelAccessResp
{
#if BYTE_ORDER == LITTLE_ENDIAN
    uint8_t accessMode : 3;
    uint8_t usrAuthDisabled : 1;
    uint8_t msgAuthDisabled : 1;
    uint8_t alertDisabled : 1;
    uint8_t reserved_1 : 2;
    uint8_t privLimit : 4;
    uint8_t reserved_2 : 4;
#endif
#if BYTE_ORDER == BIG_ENDIAN
    uint8_t reserved_1 : 2;
    uint8_t alertDisabled : 1;
    uint8_t msgAuthDisabled : 1;
    uint8_t usrAuthDisabled : 1;
    uint8_t accessMode : 3;
    uint8_t reserved_2 : 4;
    uint8_t privLimit : 4;
#endif
} __attribute__((packed));

/** @struct GetChannelInfoReq
 *
 *  Structure for get channel info request command (refer spec sec 22.24)
 */
struct GetChannelInfoReq
{
#if BYTE_ORDER == LITTLE_ENDIAN
    uint8_t chNum : 4;
    uint8_t reserved_1 : 4;
#endif
#if BYTE_ORDER == BIG_ENDIAN
    uint8_t reserved_1 : 4;
    uint8_t chNum : 4;
#endif
} __attribute__((packed));

/** @struct GetChannelInfoResp
 *
 *  Structure for get channel info response command (refer spec sec 22.24)
 */
struct GetChannelInfoResp
{
#if BYTE_ORDER == LITTLE_ENDIAN
    uint8_t chNum : 4;
    uint8_t reserved_1 : 4;
    uint8_t mediumType : 7;
    uint8_t reserved_2 : 1;
    uint8_t msgProtType : 5;
    uint8_t reserved_3 : 3;
    uint8_t actSessCount : 6;
    uint8_t sessType : 2;
#endif
#if BYTE_ORDER == BIG_ENDIAN
    uint8_t reserved_1 : 4;
    uint8_t chNum : 4;
    uint8_t reserved_2 : 1;
    uint8_t mediumType : 7;
    uint8_t reserved_3 : 3;
    uint8_t msgProtType : 5;
    uint8_t sessType : 2;
    uint8_t actSessCount : 6;
#endif
    uint8_t vendorId[3];
    uint8_t auxChInfo[2];
} __attribute__((packed));

ipmi_ret_t ipmiSetChannelAccess(ipmi_netfn_t netfn, ipmi_cmd_t cmd,
                                ipmi_request_t request,
                                ipmi_response_t response,
                                ipmi_data_len_t data_len,
                                ipmi_context_t context)
{
    const SetChannelAccessReq* req = static_cast<SetChannelAccessReq*>(request);
    size_t reqLength = *data_len;

    *data_len = 0;

    if (reqLength != sizeof(*req))
    {
        log<level::DEBUG>("Set channel access - Invalid Length");
        return IPMI_CC_REQ_DATA_LEN_INVALID;
    }

    uint8_t chNum = convertCurrentChannelNum(req->chNum);
    if (!isValidChannel(chNum))
    {
        log<level::DEBUG>("Set channel access - Parameter out of range");
        return IPMI_CC_INVALID_FIELD_REQUEST;
    }

    if (EChannelSessSupported::none == getChannelSessionSupport(chNum))
    {
        log<level::DEBUG>("Set channel access - No support on channel");
        return IPMI_CC_ACTION_NOT_SUPPORTED_FOR_CHANNEL;
    }

    ChannelAccess chActData;
    ChannelAccess chNVData;
    uint8_t setActFlag = 0;
    uint8_t setNVFlag = 0;
    ipmi_ret_t compCode = IPMI_CC_OK;

    switch (req->accessSetMode)
    {
        case doNotSet:
            // Do nothing
            break;
        case nvData:
            chNVData.accessMode = req->accessMode;
            chNVData.userAuthDisabled = req->usrAuthDisabled;
            chNVData.perMsgAuthDisabled = req->msgAuthDisabled;
            chNVData.alertingDisabled = req->alertDisabled;
            setNVFlag |= (setAccessMode | setUserAuthEnabled |
                          setMsgAuthEnabled | setAlertingEnabled);
            break;
        case activeData:
            chActData.accessMode = req->accessMode;
            chActData.userAuthDisabled = req->usrAuthDisabled;
            chActData.perMsgAuthDisabled = req->msgAuthDisabled;
            chActData.alertingDisabled = req->alertDisabled;
            setActFlag |= (setAccessMode | setUserAuthEnabled |
                           setMsgAuthEnabled | setAlertingEnabled);
            break;
        case reserved:
        default:
            log<level::DEBUG>("Set channel access - Invalid access set mode");
            return IPMI_CC_INVALID_FIELD_REQUEST;
    }

    switch (req->privSetMode)
    {
        case doNotSet:
            // Do nothing
            break;
        case nvData:
            chNVData.privLimit = req->privLimit;
            setNVFlag |= setPrivLimit;
            break;
        case activeData:
            chActData.privLimit = req->privLimit;
            setActFlag |= setPrivLimit;
            break;
        case reserved:
        default:
            log<level::DEBUG>("Set channel access - Invalid access priv mode");
            return IPMI_CC_INVALID_FIELD_REQUEST;
    }

    if (setNVFlag != 0)
    {
        compCode = setChannelAccessPersistData(chNum, chNVData, setNVFlag);
        if (compCode != IPMI_CC_OK)
        {
            log<level::DEBUG>("Set channel access - Failed to set access data");
            return compCode;
        }
    }

    if (setActFlag != 0)
    {
        compCode = setChannelAccessData(chNum, chActData, setActFlag);
        if (compCode != IPMI_CC_OK)
        {
            log<level::DEBUG>("Set channel access - Failed to set access data");
            return compCode;
        }
    }

    return IPMI_CC_OK;
}

ipmi_ret_t ipmiGetChannelAccess(ipmi_netfn_t netfn, ipmi_cmd_t cmd,
                                ipmi_request_t request,
                                ipmi_response_t response,
                                ipmi_data_len_t data_len,
                                ipmi_context_t context)
{
    const GetChannelAccessReq* req = static_cast<GetChannelAccessReq*>(request);
    size_t reqLength = *data_len;

    *data_len = 0;

    if (reqLength != sizeof(*req))
    {
        log<level::DEBUG>("Get channel access - Invalid Length");
        return IPMI_CC_REQ_DATA_LEN_INVALID;
    }

    uint8_t chNum = convertCurrentChannelNum(req->chNum);
    if (!isValidChannel(chNum))
    {
        log<level::DEBUG>("Get channel access - Parameter out of range");
        return IPMI_CC_INVALID_FIELD_REQUEST;
    }

    if ((req->accessSetMode == doNotSet) || (req->accessSetMode == reserved))
    {
        log<level::DEBUG>("Get channel access - Invalid Access mode");
        return IPMI_CC_INVALID_FIELD_REQUEST;
    }

    if (EChannelSessSupported::none == getChannelSessionSupport(chNum))
    {
        log<level::DEBUG>("Get channel access - No support on channel");
        return IPMI_CC_ACTION_NOT_SUPPORTED_FOR_CHANNEL;
    }

    GetChannelAccessResp* resp = static_cast<GetChannelAccessResp*>(response);

    std::fill(reinterpret_cast<uint8_t*>(resp),
              reinterpret_cast<uint8_t*>(resp) + sizeof(*resp), 0);

    ChannelAccess chAccess;
    ipmi_ret_t compCode = IPMI_CC_OK;

    if (req->accessSetMode == nvData)
    {
        compCode = getChannelAccessPersistData(chNum, chAccess);
    }
    else if (req->accessSetMode == activeData)
    {
        compCode = getChannelAccessData(chNum, chAccess);
    }

    if (compCode != IPMI_CC_OK)
    {
        return compCode;
    }

    resp->accessMode = chAccess.accessMode;
    resp->usrAuthDisabled = chAccess.userAuthDisabled;
    resp->msgAuthDisabled = chAccess.perMsgAuthDisabled;
    resp->alertDisabled = chAccess.alertingDisabled;
    resp->privLimit = chAccess.privLimit;

    *data_len = sizeof(*resp);
    return IPMI_CC_OK;
}

ipmi_ret_t ipmiGetChannelInfo(ipmi_netfn_t netfn, ipmi_cmd_t cmd,
                              ipmi_request_t request, ipmi_response_t response,
                              ipmi_data_len_t data_len, ipmi_context_t context)
{
    const GetChannelInfoReq* req = static_cast<GetChannelInfoReq*>(request);
    size_t reqLength = *data_len;

    *data_len = 0;

    if (reqLength != sizeof(*req))
    {
        log<level::DEBUG>("Get channel info - Invalid Length");
        return IPMI_CC_REQ_DATA_LEN_INVALID;
    }

    uint8_t chNum = convertCurrentChannelNum(req->chNum);
    if (!isValidChannel(chNum))
    {
        log<level::DEBUG>("Get channel info - Parameter out of range");
        return IPMI_CC_INVALID_FIELD_REQUEST;
    }

    // Check the existance of device for session-less channels.
    if ((EChannelSessSupported::none != getChannelSessionSupport(chNum)) &&
        (!(doesDeviceExist(chNum))))
    {
        log<level::DEBUG>("Get channel info - Device not exist");
        return IPMI_CC_PARM_OUT_OF_RANGE;
    }

    GetChannelInfoResp* resp = static_cast<GetChannelInfoResp*>(response);

    std::fill(reinterpret_cast<uint8_t*>(resp),
              reinterpret_cast<uint8_t*>(resp) + sizeof(*resp), 0);

    ChannelInfo chInfo;
    ipmi_ret_t compCode = getChannelInfo(chNum, chInfo);
    if (compCode != IPMI_CC_OK)
    {
        return compCode;
    }

    resp->chNum = chNum;
    resp->mediumType = chInfo.mediumType;
    resp->msgProtType = chInfo.protocolType;
    resp->actSessCount = getChannelActiveSessions(chNum);
    resp->sessType = chInfo.sessionSupported;

    // IPMI Spec: The IPMI Enterprise Number is: 7154 (decimal)
    resp->vendorId[0] = 0xF2;
    resp->vendorId[1] = 0x1B;
    resp->vendorId[2] = 0x00;

    // Auxiliary Channel info  - byte 1:2
    // TODO: For System Interface(0xF) and OEM channel types, this needs
    // to be changed acoordingly.
    // All other channel types, its reverved
    resp->auxChInfo[0] = 0x00;
    resp->auxChInfo[1] = 0x00;

    *data_len = sizeof(*resp);

    return IPMI_CC_OK;
}

void registerChannelFunctions() __attribute__((constructor));
void registerChannelFunctions()
{
    ipmiChannelInit();

    ipmi_register_callback(NETFUN_APP, IPMI_CMD_SET_CHANNEL_ACCESS, NULL,
                           ipmiSetChannelAccess, PRIVILEGE_ADMIN);

    ipmi_register_callback(NETFUN_APP, IPMI_CMD_GET_CHANNEL_ACCESS, NULL,
                           ipmiGetChannelAccess, PRIVILEGE_USER);

    ipmi_register_callback(NETFUN_APP, IPMI_CMD_GET_CHANNEL_INFO, NULL,
                           ipmiGetChannelInfo, PRIVILEGE_USER);
    return;
}

} // namespace ipmi
<commit_msg>Fix: Check reserved fields in channel cmds request<commit_after>/*
// Copyright (c) 2018 Intel Corporation
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//      http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
*/

#include "channelcommands.hpp"

#include "apphandler.hpp"
#include "channel_layer.hpp"

#include <phosphor-logging/log.hpp>
#include <regex>

using namespace phosphor::logging;

namespace ipmi
{

/** @struct SetChannelAccessReq
 *
 *  Structure for set channel access request command (refer spec sec 22.22)
 */
struct SetChannelAccessReq
{
#if BYTE_ORDER == LITTLE_ENDIAN
    uint8_t chNum : 4;
    uint8_t reserved_1 : 4;
    uint8_t accessMode : 3;
    uint8_t usrAuthDisabled : 1;
    uint8_t msgAuthDisabled : 1;
    uint8_t alertDisabled : 1;
    uint8_t accessSetMode : 2;
    uint8_t privLimit : 4;
    uint8_t reserved_2 : 2;
    uint8_t privSetMode : 2;
#endif
#if BYTE_ORDER == BIG_ENDIAN
    uint8_t reserved_1 : 4;
    uint8_t chNum : 4;
    uint8_t accessSetMode : 2;
    uint8_t alertDisabled : 1;
    uint8_t msgAuthDisabled : 1;
    uint8_t usrAuthDisabled : 1;
    uint8_t accessMode : 3;
    uint8_t privSetMode : 2;
    uint8_t reserved_2 : 2;
    uint8_t privLimit : 4;
#endif

} __attribute__((packed));

/** @struct GetChannelAccessReq
 *
 *  Structure for get channel access request command (refer spec sec 22.23)
 */
struct GetChannelAccessReq
{
#if BYTE_ORDER == LITTLE_ENDIAN
    uint8_t chNum : 4;
    uint8_t reserved_1 : 4;
    uint8_t reserved_2 : 6;
    uint8_t accessSetMode : 2;
#endif
#if BYTE_ORDER == BIG_ENDIAN
    uint8_t reserved_1 : 4;
    uint8_t chNum : 4;
    uint8_t accessSetMode : 2;
    uint8_t reserved_2 : 6;
#endif
} __attribute__((packed));

/** @struct GetChannelAccessResp
 *
 *  Structure for get channel access response command (refer spec sec 22.23)
 */
struct GetChannelAccessResp
{
#if BYTE_ORDER == LITTLE_ENDIAN
    uint8_t accessMode : 3;
    uint8_t usrAuthDisabled : 1;
    uint8_t msgAuthDisabled : 1;
    uint8_t alertDisabled : 1;
    uint8_t reserved_1 : 2;
    uint8_t privLimit : 4;
    uint8_t reserved_2 : 4;
#endif
#if BYTE_ORDER == BIG_ENDIAN
    uint8_t reserved_1 : 2;
    uint8_t alertDisabled : 1;
    uint8_t msgAuthDisabled : 1;
    uint8_t usrAuthDisabled : 1;
    uint8_t accessMode : 3;
    uint8_t reserved_2 : 4;
    uint8_t privLimit : 4;
#endif
} __attribute__((packed));

/** @struct GetChannelInfoReq
 *
 *  Structure for get channel info request command (refer spec sec 22.24)
 */
struct GetChannelInfoReq
{
#if BYTE_ORDER == LITTLE_ENDIAN
    uint8_t chNum : 4;
    uint8_t reserved_1 : 4;
#endif
#if BYTE_ORDER == BIG_ENDIAN
    uint8_t reserved_1 : 4;
    uint8_t chNum : 4;
#endif
} __attribute__((packed));

/** @struct GetChannelInfoResp
 *
 *  Structure for get channel info response command (refer spec sec 22.24)
 */
struct GetChannelInfoResp
{
#if BYTE_ORDER == LITTLE_ENDIAN
    uint8_t chNum : 4;
    uint8_t reserved_1 : 4;
    uint8_t mediumType : 7;
    uint8_t reserved_2 : 1;
    uint8_t msgProtType : 5;
    uint8_t reserved_3 : 3;
    uint8_t actSessCount : 6;
    uint8_t sessType : 2;
#endif
#if BYTE_ORDER == BIG_ENDIAN
    uint8_t reserved_1 : 4;
    uint8_t chNum : 4;
    uint8_t reserved_2 : 1;
    uint8_t mediumType : 7;
    uint8_t reserved_3 : 3;
    uint8_t msgProtType : 5;
    uint8_t sessType : 2;
    uint8_t actSessCount : 6;
#endif
    uint8_t vendorId[3];
    uint8_t auxChInfo[2];
} __attribute__((packed));

ipmi_ret_t ipmiSetChannelAccess(ipmi_netfn_t netfn, ipmi_cmd_t cmd,
                                ipmi_request_t request,
                                ipmi_response_t response,
                                ipmi_data_len_t data_len,
                                ipmi_context_t context)
{
    const SetChannelAccessReq* req = static_cast<SetChannelAccessReq*>(request);
    size_t reqLength = *data_len;

    *data_len = 0;

    if (reqLength != sizeof(*req))
    {
        log<level::DEBUG>("Set channel access - Invalid Length");
        return IPMI_CC_REQ_DATA_LEN_INVALID;
    }

    uint8_t chNum = convertCurrentChannelNum(req->chNum);
    if (!isValidChannel(chNum) || req->reserved_1 != 0 || req->reserved_2 != 0)
    {
        log<level::DEBUG>("Set channel access - Invalid field in request");
        return IPMI_CC_INVALID_FIELD_REQUEST;
    }

    if (EChannelSessSupported::none == getChannelSessionSupport(chNum))
    {
        log<level::DEBUG>("Set channel access - No support on channel");
        return IPMI_CC_ACTION_NOT_SUPPORTED_FOR_CHANNEL;
    }

    ChannelAccess chActData;
    ChannelAccess chNVData;
    uint8_t setActFlag = 0;
    uint8_t setNVFlag = 0;
    ipmi_ret_t compCode = IPMI_CC_OK;

    switch (req->accessSetMode)
    {
        case doNotSet:
            // Do nothing
            break;
        case nvData:
            chNVData.accessMode = req->accessMode;
            chNVData.userAuthDisabled = req->usrAuthDisabled;
            chNVData.perMsgAuthDisabled = req->msgAuthDisabled;
            chNVData.alertingDisabled = req->alertDisabled;
            setNVFlag |= (setAccessMode | setUserAuthEnabled |
                          setMsgAuthEnabled | setAlertingEnabled);
            break;
        case activeData:
            chActData.accessMode = req->accessMode;
            chActData.userAuthDisabled = req->usrAuthDisabled;
            chActData.perMsgAuthDisabled = req->msgAuthDisabled;
            chActData.alertingDisabled = req->alertDisabled;
            setActFlag |= (setAccessMode | setUserAuthEnabled |
                           setMsgAuthEnabled | setAlertingEnabled);
            break;
        case reserved:
        default:
            log<level::DEBUG>("Set channel access - Invalid access set mode");
            return IPMI_CC_INVALID_FIELD_REQUEST;
    }

    switch (req->privSetMode)
    {
        case doNotSet:
            // Do nothing
            break;
        case nvData:
            chNVData.privLimit = req->privLimit;
            setNVFlag |= setPrivLimit;
            break;
        case activeData:
            chActData.privLimit = req->privLimit;
            setActFlag |= setPrivLimit;
            break;
        case reserved:
        default:
            log<level::DEBUG>("Set channel access - Invalid access priv mode");
            return IPMI_CC_INVALID_FIELD_REQUEST;
    }

    if (setNVFlag != 0)
    {
        compCode = setChannelAccessPersistData(chNum, chNVData, setNVFlag);
        if (compCode != IPMI_CC_OK)
        {
            log<level::DEBUG>("Set channel access - Failed to set access data");
            return compCode;
        }
    }

    if (setActFlag != 0)
    {
        compCode = setChannelAccessData(chNum, chActData, setActFlag);
        if (compCode != IPMI_CC_OK)
        {
            log<level::DEBUG>("Set channel access - Failed to set access data");
            return compCode;
        }
    }

    return IPMI_CC_OK;
}

ipmi_ret_t ipmiGetChannelAccess(ipmi_netfn_t netfn, ipmi_cmd_t cmd,
                                ipmi_request_t request,
                                ipmi_response_t response,
                                ipmi_data_len_t data_len,
                                ipmi_context_t context)
{
    const GetChannelAccessReq* req = static_cast<GetChannelAccessReq*>(request);
    size_t reqLength = *data_len;

    *data_len = 0;

    if (reqLength != sizeof(*req))
    {
        log<level::DEBUG>("Get channel access - Invalid Length");
        return IPMI_CC_REQ_DATA_LEN_INVALID;
    }

    uint8_t chNum = convertCurrentChannelNum(req->chNum);
    if (!isValidChannel(chNum) || req->reserved_1 != 0 || req->reserved_2 != 0)
    {
        log<level::DEBUG>("Get channel access - Invalid field in request");
        return IPMI_CC_INVALID_FIELD_REQUEST;
    }

    if ((req->accessSetMode == doNotSet) || (req->accessSetMode == reserved))
    {
        log<level::DEBUG>("Get channel access - Invalid Access mode");
        return IPMI_CC_INVALID_FIELD_REQUEST;
    }

    if (EChannelSessSupported::none == getChannelSessionSupport(chNum))
    {
        log<level::DEBUG>("Get channel access - No support on channel");
        return IPMI_CC_ACTION_NOT_SUPPORTED_FOR_CHANNEL;
    }

    GetChannelAccessResp* resp = static_cast<GetChannelAccessResp*>(response);

    std::fill(reinterpret_cast<uint8_t*>(resp),
              reinterpret_cast<uint8_t*>(resp) + sizeof(*resp), 0);

    ChannelAccess chAccess;
    ipmi_ret_t compCode = IPMI_CC_OK;

    if (req->accessSetMode == nvData)
    {
        compCode = getChannelAccessPersistData(chNum, chAccess);
    }
    else if (req->accessSetMode == activeData)
    {
        compCode = getChannelAccessData(chNum, chAccess);
    }

    if (compCode != IPMI_CC_OK)
    {
        return compCode;
    }

    resp->accessMode = chAccess.accessMode;
    resp->usrAuthDisabled = chAccess.userAuthDisabled;
    resp->msgAuthDisabled = chAccess.perMsgAuthDisabled;
    resp->alertDisabled = chAccess.alertingDisabled;
    resp->privLimit = chAccess.privLimit;

    *data_len = sizeof(*resp);
    return IPMI_CC_OK;
}

ipmi_ret_t ipmiGetChannelInfo(ipmi_netfn_t netfn, ipmi_cmd_t cmd,
                              ipmi_request_t request, ipmi_response_t response,
                              ipmi_data_len_t data_len, ipmi_context_t context)
{
    const GetChannelInfoReq* req = static_cast<GetChannelInfoReq*>(request);
    size_t reqLength = *data_len;

    *data_len = 0;

    if (reqLength != sizeof(*req))
    {
        log<level::DEBUG>("Get channel info - Invalid Length");
        return IPMI_CC_REQ_DATA_LEN_INVALID;
    }

    uint8_t chNum = convertCurrentChannelNum(req->chNum);
    if (!isValidChannel(chNum) || req->reserved_1 != 0)
    {
        log<level::DEBUG>("Get channel info - Invalid field in request");
        return IPMI_CC_INVALID_FIELD_REQUEST;
    }

    // Check the existance of device for session-less channels.
    if ((EChannelSessSupported::none != getChannelSessionSupport(chNum)) &&
        (!(doesDeviceExist(chNum))))
    {
        log<level::DEBUG>("Get channel info - Device not exist");
        return IPMI_CC_PARM_OUT_OF_RANGE;
    }

    GetChannelInfoResp* resp = static_cast<GetChannelInfoResp*>(response);

    std::fill(reinterpret_cast<uint8_t*>(resp),
              reinterpret_cast<uint8_t*>(resp) + sizeof(*resp), 0);

    ChannelInfo chInfo;
    ipmi_ret_t compCode = getChannelInfo(chNum, chInfo);
    if (compCode != IPMI_CC_OK)
    {
        return compCode;
    }

    resp->chNum = chNum;
    resp->mediumType = chInfo.mediumType;
    resp->msgProtType = chInfo.protocolType;
    resp->actSessCount = getChannelActiveSessions(chNum);
    resp->sessType = chInfo.sessionSupported;

    // IPMI Spec: The IPMI Enterprise Number is: 7154 (decimal)
    resp->vendorId[0] = 0xF2;
    resp->vendorId[1] = 0x1B;
    resp->vendorId[2] = 0x00;

    // Auxiliary Channel info  - byte 1:2
    // TODO: For System Interface(0xF) and OEM channel types, this needs
    // to be changed acoordingly.
    // All other channel types, its reverved
    resp->auxChInfo[0] = 0x00;
    resp->auxChInfo[1] = 0x00;

    *data_len = sizeof(*resp);

    return IPMI_CC_OK;
}

void registerChannelFunctions() __attribute__((constructor));
void registerChannelFunctions()
{
    ipmiChannelInit();

    ipmi_register_callback(NETFUN_APP, IPMI_CMD_SET_CHANNEL_ACCESS, NULL,
                           ipmiSetChannelAccess, PRIVILEGE_ADMIN);

    ipmi_register_callback(NETFUN_APP, IPMI_CMD_GET_CHANNEL_ACCESS, NULL,
                           ipmiGetChannelAccess, PRIVILEGE_USER);

    ipmi_register_callback(NETFUN_APP, IPMI_CMD_GET_CHANNEL_INFO, NULL,
                           ipmiGetChannelInfo, PRIVILEGE_USER);
    return;
}

} // namespace ipmi
<|endoftext|>


<commit_before>// Copyright (c) 2018 Kari Karvonen, OH1KK

#include "ext.h"	// all calls to the extension interface begin with "ext_", e.g. ext_register()

#include "kiwi.h"
#include "cfg.h"
#include "str.h"

#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include <math.h>
#include <strings.h>
#include <sys/types.h>
#include <sys/wait.h>

//#define ANT_SWITCH_DEBUG_MSG	true
#define ANT_SWITCH_DEBUG_MSG	false

// rx_chan is the receiver channel number we've been assigned, 0..RX_CHAN
// We need this so the extension can support multiple users, each with their own ant_switch[] data structure.

struct ant_switch_t {
	u1_t rx_chan;
};

// Can't use RX_CHANS since 8-channel mode was introduced.
// But also can't use the new MAX_RX_CHANS because of the backward compatibility issue.
// So just define our own plausible maximum.
#define ANT_SW_MAX_RX_CHANS    32
static ant_switch_t ant_switch[ANT_SW_MAX_RX_CHANS];

char * ant_switch_queryantennas() {
	char *cmd, *reply;
	static char selected_antennas[256];
	int n;
	asprintf(&cmd, "/root/extensions/ant_switch/frontend/ant-switch-frontend s");
	reply = non_blocking_cmd(cmd, NULL);
	n = sscanf(kstr_sp(reply), "Selected antennas: %250s", selected_antennas);
	free(cmd);
	//printf("frontend: s n=%d reply=<%s>\n", n, kstr_sp(reply));
	if (!n) printf("ant_switch_queryantenna BAD STATUS? <%s>\n", kstr_sp(reply));
	kstr_free(reply);
	return(selected_antennas);
}

int ant_switch_setantenna(char* antenna) {
    char *cmd, *reply;
	int status;
	int n;
    asprintf(&cmd, "/root/extensions/ant_switch/frontend/ant-switch-frontend %s", antenna);
	//printf("frontend: %s\n", antenna);
	reply = non_blocking_cmd(cmd,NULL);
	free(cmd);
	kstr_free(reply);
	return(0);
}

int ant_switch_toggleantenna(char* antenna) {
    char *cmd, *reply;
	int status;
	int n;
    asprintf(&cmd, "/root/extensions/ant_switch/frontend/ant-switch-frontend t%s", antenna);
	//printf("frontend: t%s\n", antenna);
	reply = non_blocking_cmd(cmd, NULL);
	free(cmd);
	kstr_free(reply);
	return(0);
}

int ant_switch_validate_cmd(char *cmd) {
    int is_valid_cmd = false;
    if (strcmp(cmd, "1") == 0) is_valid_cmd=true;
    if (strcmp(cmd, "2") == 0) is_valid_cmd=true;
    if (strcmp(cmd, "3") == 0) is_valid_cmd=true;
    if (strcmp(cmd, "4") == 0) is_valid_cmd=true;
    if (strcmp(cmd, "5") == 0) is_valid_cmd=true;
    if (strcmp(cmd, "6") == 0) is_valid_cmd=true;
    if (strcmp(cmd, "7") == 0) is_valid_cmd=true;
    if (strcmp(cmd, "8") == 0) is_valid_cmd=true;
    if (strcmp(cmd, "g") == 0) is_valid_cmd=true;
    return(is_valid_cmd);
}

bool ant_switch_read_denyswitching() {
    bool error;
    char cfgparam[26]="ant_switch.denyswitching\0";
    int result = cfg_int(cfgparam, &error, CFG_OPTIONAL);
    // error handling: if deny parameter is not defined, or it is 0, then switching is allowed
    if (result == 1) return true; else return false;
}

bool ant_switch_read_denymixing() {
    bool error;
    char cfgparam[26]="ant_switch.denymixing\0";
    int result = cfg_int(cfgparam, &error, CFG_OPTIONAL);
    // error handling: if deny parameter is not defined, or it is 0, then mixing is allowed
    if (result == 1) return true; else return false;
}

bool ant_switch_read_denymultiuser() {
    bool error;
    char cfgparam[26]="ant_switch.denymultiuser\0";
    int result = cfg_int(cfgparam, &error, CFG_OPTIONAL);
    // error handling: if deny parameter is not defined, or it is 0, then switching is allowed
    if (result == 1) {
        // option is set. Now check if more than 1 user online rx_util.cpp current_nusers variable
        if (current_nusers > 1) return true; else return false;
    } else {
        return false;
    }
}

bool ant_switch_msgs(char *msg, int rx_chan)
{
	ant_switch_t *e = &ant_switch[rx_chan];
	int n=0;
	char antenna[256];

	//printf("### ant_switch_msgs RX%d <%s>\n", rx_chan, msg);

	if (strcmp(msg, "SET ext_server_init") == 0) {
		e->rx_chan = rx_chan;	// remember our receiver channel number
		ext_send_msg(e->rx_chan, ANT_SWITCH_DEBUG_MSG, "EXT ready");
		return true;
	}

    n = sscanf(msg, "SET Antenna=%s", antenna);
    if (n == 1) {
        printf("ant_switch: RX%d %s\n", rx_chan, msg);
        if (ant_switch_read_denyswitching()==true || ant_switch_read_denymultiuser()==true) {
            ext_send_msg(e->rx_chan, ANT_SWITCH_DEBUG_MSG, "EXT AntennaDenySwitching=1");
            return true;
        } else {
            ext_send_msg(e->rx_chan, ANT_SWITCH_DEBUG_MSG, "EXT AntennaDenySwitching=0");
        }

        // FIXME: or toggle antenna if antenna mixing is allowed
        if (ant_switch_validate_cmd(antenna)) {
            if (ant_switch_read_denymixing() == 1) {
                ant_switch_setantenna(antenna);
            } else {
                ant_switch_toggleantenna(antenna);
            }
        } else {
            ext_send_msg(e->rx_chan, ANT_SWITCH_DEBUG_MSG, "Command not valid SET Antenna=%s",antenna);
        }

        return true;
    }

    if (strcmp(msg, "GET Antenna") == 0) {
        char *selected_antennas = ant_switch_queryantennas();
        ext_send_msg(e->rx_chan, ANT_SWITCH_DEBUG_MSG, "EXT Antenna=%s", selected_antennas);

        if (ant_switch_read_denyswitching()==true || ant_switch_read_denymultiuser()==true) {
            ext_send_msg(e->rx_chan, ANT_SWITCH_DEBUG_MSG, "EXT AntennaDenySwitching=1");
        } else {
            ext_send_msg(e->rx_chan, ANT_SWITCH_DEBUG_MSG, "EXT AntennaDenySwitching=0");
        }

        if (ant_switch_read_denymixing()==true) {
            ext_send_msg(e->rx_chan, ANT_SWITCH_DEBUG_MSG, "EXT AntennaDenyMixing=1");
        } else {
            ext_send_msg(e->rx_chan, ANT_SWITCH_DEBUG_MSG, "EXT AntennaDenyMixing=0");
        }

        return true;
    }

    return false;
}

void ant_switch_close(int rx_chan)
{
    // do nothing
}

void ant_switch_main();

ext_t ant_switch_ext = {
	"ant_switch",
	ant_switch_main,
	ant_switch_close,
	ant_switch_msgs,
};

void ant_switch_main()
{
	ext_register(&ant_switch_ext);
}
<commit_msg>a new way to handle thunderstorm mode<commit_after>// Copyright (c) 2018-2019 Kari Karvonen, OH1KK

#include "ext.h"	// all calls to the extension interface begin with "ext_", e.g. ext_register()

#include "kiwi.h"
#include "cfg.h"
#include "str.h"

#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include <math.h>
#include <strings.h>
#include <sys/types.h>
#include <sys/wait.h>

//#define ANT_SWITCH_DEBUG_MSG	true
#define ANT_SWITCH_DEBUG_MSG	false

// rx_chan is the receiver channel number we've been assigned, 0..RX_CHAN
// We need this so the extension can support multiple users, each with their own ant_switch[] data structure.

struct ant_switch_t {
	u1_t rx_chan;
};

// Can't use RX_CHANS since 8-channel mode was introduced.
// But also can't use the new MAX_RX_CHANS because of the backward compatibility issue.
// So just define our own plausible maximum.
#define ANT_SW_MAX_RX_CHANS    32
static ant_switch_t ant_switch[ANT_SW_MAX_RX_CHANS];

char * ant_switch_queryantennas() {
	char *cmd, *reply;
	static char selected_antennas[256];
	int n;
	asprintf(&cmd, "/root/extensions/ant_switch/frontend/ant-switch-frontend s");
	reply = non_blocking_cmd(cmd, NULL);
	n = sscanf(kstr_sp(reply), "Selected antennas: %250s", selected_antennas);
	free(cmd);
	//printf("frontend: s n=%d reply=<%s>\n", n, kstr_sp(reply));
	if (!n) printf("ant_switch_queryantenna BAD STATUS? <%s>\n", kstr_sp(reply));
	kstr_free(reply);
	return(selected_antennas);
}

int ant_switch_setantenna(char* antenna) {
    char *cmd, *reply;
	int status;
	int n;
    asprintf(&cmd, "/root/extensions/ant_switch/frontend/ant-switch-frontend %s", antenna);
	//printf("frontend: %s\n", antenna);
	reply = non_blocking_cmd(cmd,NULL);
	free(cmd);
	kstr_free(reply);
	return(0);
}

int ant_switch_toggleantenna(char* antenna) {
    char *cmd, *reply;
	int status;
	int n;
    asprintf(&cmd, "/root/extensions/ant_switch/frontend/ant-switch-frontend t%s", antenna);
	//printf("frontend: t%s\n", antenna);
	reply = non_blocking_cmd(cmd, NULL);
	free(cmd);
	kstr_free(reply);
	return(0);
}

int ant_switch_validate_cmd(char *cmd) {
    int is_valid_cmd = false;
    if (strcmp(cmd, "1") == 0) is_valid_cmd=true;
    if (strcmp(cmd, "2") == 0) is_valid_cmd=true;
    if (strcmp(cmd, "3") == 0) is_valid_cmd=true;
    if (strcmp(cmd, "4") == 0) is_valid_cmd=true;
    if (strcmp(cmd, "5") == 0) is_valid_cmd=true;
    if (strcmp(cmd, "6") == 0) is_valid_cmd=true;
    if (strcmp(cmd, "7") == 0) is_valid_cmd=true;
    if (strcmp(cmd, "8") == 0) is_valid_cmd=true;
    if (strcmp(cmd, "g") == 0) is_valid_cmd=true;
    return(is_valid_cmd);
}

bool ant_switch_read_denyswitching() {
    bool error;
    char cfgparam[26]="ant_switch.denyswitching\0";
    int result = cfg_int(cfgparam, &error, CFG_OPTIONAL);
    // error handling: if deny parameter is not defined, or it is 0, then switching is allowed
    if (result == 1) return true; else return false;
}

bool ant_switch_read_denymixing() {
    bool error;
    char cfgparam[26]="ant_switch.denymixing\0";
    int result = cfg_int(cfgparam, &error, CFG_OPTIONAL);
    // error handling: if deny parameter is not defined, or it is 0, then mixing is allowed
    if (result == 1) return true; else return false;
}

bool ant_switch_read_denymultiuser() {
    bool error;
    char cfgparam[26]="ant_switch.denymultiuser\0";
    int result = cfg_int(cfgparam, &error, CFG_OPTIONAL);
    // error handling: if deny parameter is not defined, or it is 0, then switching is allowed
    if (result == 1) {
        // option is set. Now check if more than 1 user online rx_util.cpp current_nusers variable
        if (current_nusers > 1) return true; else return false;
    } else {
        return false;
    }
}

bool ant_switch_read_thunderstorm() {
    bool error;
    char cfgparam[26]="ant_switch.thunderstorm\0";
    int result = cfg_int(cfgparam, &error, CFG_OPTIONAL);
    // error handling: if deny parameter is not defined, or it is 0, then mixing is allowed
    if (result == 1) return true; else return false;
}

bool ant_switch_msgs(char *msg, int rx_chan)
{
	ant_switch_t *e = &ant_switch[rx_chan];
	int n=0;
	char antenna[256];

	//printf("### ant_switch_msgs RX%d <%s>\n", rx_chan, msg);

	if (strcmp(msg, "SET ext_server_init") == 0) {
		e->rx_chan = rx_chan;	// remember our receiver channel number
		ext_send_msg(e->rx_chan, ANT_SWITCH_DEBUG_MSG, "EXT ready");
		return true;
	}

    n = sscanf(msg, "SET Antenna=%s", antenna);
    if (n == 1) {
        printf("ant_switch: RX%d %s\n", rx_chan, msg);
        if (ant_switch_read_thunderstorm()==true || ant_switch_read_denyswitching()==true || ant_switch_read_denymultiuser()==true) {
            ext_send_msg(e->rx_chan, ANT_SWITCH_DEBUG_MSG, "EXT AntennaDenySwitching=1");
            return true;
        } else {
            ext_send_msg(e->rx_chan, ANT_SWITCH_DEBUG_MSG, "EXT AntennaDenySwitching=0");
        }

        // FIXME: or toggle antenna if antenna mixing is allowed
        if (ant_switch_validate_cmd(antenna)) {
            if (ant_switch_read_denymixing() == 1) {
                ant_switch_setantenna(antenna);
            } else {
                ant_switch_toggleantenna(antenna);
            }
        } else {
            ext_send_msg(e->rx_chan, ANT_SWITCH_DEBUG_MSG, "Command not valid SET Antenna=%s",antenna);
        }

        return true;
    }

    if (strcmp(msg, "GET Antenna") == 0) {
        char *selected_antennas = ant_switch_queryantennas();
        ext_send_msg(e->rx_chan, ANT_SWITCH_DEBUG_MSG, "EXT Antenna=%s", selected_antennas);

        if (ant_switch_read_denyswitching()==true || ant_switch_read_denymultiuser()==true) {
            ext_send_msg(e->rx_chan, ANT_SWITCH_DEBUG_MSG, "EXT AntennaDenySwitching=1");
        } else {
            ext_send_msg(e->rx_chan, ANT_SWITCH_DEBUG_MSG, "EXT AntennaDenySwitching=0");
        }

        if (ant_switch_read_denymixing()==true) {
            ext_send_msg(e->rx_chan, ANT_SWITCH_DEBUG_MSG, "EXT AntennaDenyMixing=1");
        } else {
            ext_send_msg(e->rx_chan, ANT_SWITCH_DEBUG_MSG, "EXT AntennaDenyMixing=0");
        }
        if (ant_switch_read_thunderstorm()==true) {
            ext_send_msg(e->rx_chan, ANT_SWITCH_DEBUG_MSG, "EXT Thunderstorm=1");
            // also ground antenna if not grounded
            if (strcmp(selected_antennas, "g")!=0)  {
                char* groundall=(char*)"g\0";
                ant_switch_setantenna(groundall);
                ext_send_msg(e->rx_chan, ANT_SWITCH_DEBUG_MSG, "EXT Antenna=g");
            }
            return true;
        } else {
                ext_send_msg(e->rx_chan, ANT_SWITCH_DEBUG_MSG, "EXT Thunderstorm=0");
        }
        return true;
    }
    return false;
}

void ant_switch_close(int rx_chan)
{
    // do nothing
}

void ant_switch_main();

ext_t ant_switch_ext = {
	"ant_switch",
	ant_switch_main,
	ant_switch_close,
	ant_switch_msgs,
};

void ant_switch_main()
{
	ext_register(&ant_switch_ext);
}
<|endoftext|>


<commit_before><commit_msg>INTEGRATION: CWS oasisbf2 (1.13.78); FILE MERGED 2004/11/17 18:49:42 dvo 1.13.78.2: #i31024# prevent headings with outline num-rules from being written as lists 2004/11/04 15:19:02 dvo 1.13.78.1: #i31024# prevent headings with outline num-rules from being written as lists<commit_after><|endoftext|>


<commit_before>#include "TopLibraryPanel.h"

#include <easycomplex.h>
#include <easytext.h>

namespace eui
{

TopLibraryPanel::TopLibraryPanel(wxWindow* parent)
	: wxPanel(parent)
{
	InitLayout();
	EnableUILibrary(true);
}

void TopLibraryPanel::EnableUILibrary(bool enable)
{
	wxSizer* sizer = GetSizer();
	if (enable) {
		sizer->Show((size_t)0);
		sizer->Hide((size_t)1);
	} else {
		sizer->Show((size_t)1);
		sizer->Hide((size_t)0);
	}
}

void TopLibraryPanel::Clear()
{
	m_library_ui->Clear();
	m_library_raw->Clear();
}

void TopLibraryPanel::InitLayout()
{
	wxSizer* sizer = new wxBoxSizer(wxVERTICAL);

	m_library_ui = new d2d::LibraryPanel(this);
	sizer->Add(m_library_ui, 1, wxEXPAND);

	m_library_raw = new d2d::LibraryPanel(this);
	wxWindow* nb = m_library_raw->GetNotebook();
	m_library_raw->AddPage(new d2d::LibraryImagePage(nb));
	m_library_raw->AddPage(new ecomplex::LibraryPage(nb));
//	m_library_raw->AddPage(new etext::LibraryPage(nb));
	m_library_raw->AddPage(new d2d::LibraryFontBlankPage(nb));
	sizer->Add(m_library_raw, 1, wxEXPAND);

	SetSizer(sizer);

	Layout();
}

}<commit_msg>[CHANGED] 替换ui的text library<commit_after>#include "TopLibraryPanel.h"

#include <easycomplex.h>
#include <easytext.h>

namespace eui
{

TopLibraryPanel::TopLibraryPanel(wxWindow* parent)
	: wxPanel(parent)
{
	InitLayout();
	EnableUILibrary(true);
}

void TopLibraryPanel::EnableUILibrary(bool enable)
{
	wxSizer* sizer = GetSizer();
	if (enable) {
		sizer->Show((size_t)0);
		sizer->Hide((size_t)1);
	} else {
		sizer->Show((size_t)1);
		sizer->Hide((size_t)0);
	}
}

void TopLibraryPanel::Clear()
{
	m_library_ui->Clear();
	m_library_raw->Clear();
}

void TopLibraryPanel::InitLayout()
{
	wxSizer* sizer = new wxBoxSizer(wxVERTICAL);

	m_library_ui = new d2d::LibraryPanel(this);
	sizer->Add(m_library_ui, 1, wxEXPAND);

	m_library_raw = new d2d::LibraryPanel(this);
	wxWindow* nb = m_library_raw->GetNotebook();
	m_library_raw->AddPage(new d2d::LibraryImagePage(nb));
	m_library_raw->AddPage(new ecomplex::LibraryPage(nb));
	m_library_raw->AddPage(new etext::LibraryPage(nb));
//	m_library_raw->AddPage(new d2d::LibraryFontBlankPage(nb));
	sizer->Add(m_library_raw, 1, wxEXPAND);

	SetSizer(sizer);

	Layout();
}

}<|endoftext|>


<commit_before>/*********************************************************************
* Software License Agreement (BSD License)
*
*  Copyright 2016-2017 Davide Faconti
*  All rights reserved.
*
*  Redistribution and use in source and binary forms, with or without
*  modification, are permitted provided that the following conditions
*  are met:
*
*   * Redistributions of source code must retain the above copyright
*     notice, this list of conditions and the following disclaimer.
*   * Redistributions in binary form must reproduce the above
*     copyright notice, this list of conditions and the following
*     disclaimer in the documentation and/or other materials provided
*     with the distribution.
*   * Neither the name of Willow Garage, Inc. nor the names of its
*     contributors may be used to endorse or promote products derived
*     from this software without specific prior written permission.
*
*  THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
*  "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
*  LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
*  FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
*  COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
*  INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
*  BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
*  LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
*  CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
*  LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
*  ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
*  POSSIBILITY OF SUCH DAMAGE.
* *******************************************************************/

#ifndef VARIANT_IMPL_H
#define VARIANT_IMPL_H

#include <type_traits>
#include <limits>
#include <iostream>
#include "ros_type_introspection/builtin_types.hpp"
#include "ros_type_introspection/details/exceptions.hpp"

namespace RosIntrospection
{

namespace details{

template <typename T>
using Invoke = typename T::type;

template <typename BoolCondition>
using EnableIf = Invoke<std::enable_if<BoolCondition::value> >;

template <typename T>
struct is_integer : std::integral_constant<bool, std::is_integral<T>::value
        && !std::is_same<T, bool>::value
        && !std::is_same<T, char>::value>
{};

template <typename From, typename To>
struct is_same_type : std::integral_constant<bool, std::is_same<From, To>::value>
{};

template <typename From, typename To>
struct is_safe_integer_conversion
        : std::integral_constant<bool, is_integer<From>::value
        && is_integer<To>::value
        && sizeof(From) <= sizeof(To)
&& std::is_signed<From>::value == std::is_signed<To>::value>
{};

template <typename From, typename To>
struct float_conversion
        : std::integral_constant<bool, std::is_floating_point<From>::value
        && std::is_floating_point<To>::value >
{};

template <typename From, typename To>
struct unsigned_to_smaller_conversion
        : std::integral_constant<bool, is_integer<From>::value
        && is_integer<To>::value
        && (sizeof(From) > sizeof(To))
&& !std::is_signed<From>::value
&& !std::is_signed<To>::value >
{};

template <typename From, typename To>
struct signed_to_smaller_conversion
        : std::integral_constant<bool, is_integer<From>::value
        && is_integer<To>::value
        && (sizeof(From) > sizeof(To))
&& std::is_signed<From>::value
&& std::is_signed<To>::value >
{};

//---------------------------
template <typename From, typename To>
struct signed_to_smaller_unsigned_conversion
        : std::integral_constant<bool, is_integer<From>::value
        && is_integer<To>::value
        && sizeof(From) >= sizeof(To)
&& std::is_signed<From>::value
&& !std::is_signed<To>::value >
{};

template <typename From, typename To>
struct signed_to_larger_unsigned_conversion
        : std::integral_constant<bool, is_integer<From>::value
        && is_integer<To>::value
        && sizeof(From) < sizeof(To)
&& std::is_signed<From>::value
&& !std::is_signed<To>::value >
{};

template <typename From, typename To>
struct unsigned_to_smaller_signed_conversion
        : std::integral_constant<bool, is_integer<From>::value
        && is_integer<To>::value
        && (sizeof(From) >= sizeof(To))
&& !std::is_signed<From>::value
&& std::is_signed<To>::value >
{};

template <typename From, typename To>
struct unsigned_to_larger_signed_conversion
        : std::integral_constant<bool, is_integer<From>::value
        && is_integer<To>::value
        && sizeof(From) < sizeof(To)
&& !std::is_signed<From>::value
&& std::is_signed<To>::value >
{};

template <typename From, typename To>
struct floating_to_signed_conversion
        : std::integral_constant<bool, std::is_floating_point<From>::value
        && is_integer<To>::value
        && std::is_signed<To>::value >
{};

template <typename From, typename To>
struct floating_to_unsigned_conversion
        : std::integral_constant<bool, std::is_floating_point<From>::value
        && is_integer<To>::value
        && !std::is_signed<To>::value >
{};

template <typename From, typename To>
struct integer_to_floating_conversion
        : std::integral_constant<bool, is_integer<From>::value
        && std::is_floating_point<To>::value >
{};

template <typename From, typename To>
inline void checkUpperLimit(const From& from)
{
    if ((sizeof(To) < sizeof(From)) &&
        (from > static_cast<From>(std::numeric_limits<To>::max()))) {
        throw RangeException("Value too large.");
    }
    else if (static_cast<To>(from) > std::numeric_limits<To>::max()) {
        throw RangeException("Value too large.");
    }
}

template <typename From, typename To>
inline void checkUpperLimitFloat(const From& from)
{
  if (from > std::numeric_limits<To>::max()){
    throw RangeException("Value too large.");
  }
}

template <typename From, typename To>
inline void checkLowerLimitFloat(const From& from)
{
    if (from < -std::numeric_limits<To>::max()){
        throw RangeException("Value too small.");
    }
}

template <typename From, typename To>
inline void checkLowerLimit(const From& from)
{
  if (from < std::numeric_limits<To>::min()){
    throw RangeException("Value too small.");
  }
}

template <typename From, typename To>
inline void checkTruncation(const From& from)
{
  if( from != static_cast<From>(static_cast<To>( from))){
    throw RangeException("Floating point truncated");
  }
}

//----------------------- Implementation ----------------------------------------------

template<typename SRC,typename DST,
         typename details::EnableIf< details::is_same_type<SRC, DST>>* = nullptr >
inline void convert_impl( const SRC& from, DST& target )
{
    //std::cout << "is_same_type" << std::endl;
    target = from;
}

template<typename SRC,typename DST,
         typename details::EnableIf< details::is_safe_integer_conversion<SRC, DST>>* = nullptr >
inline void convert_impl( const SRC& from, DST& target )
{
    //std::cout << "is_safe_integer_conversion" << std::endl;
    target = static_cast<DST>( from);
}

template<typename SRC,typename DST,
         typename details::EnableIf< details::float_conversion<SRC, DST>>* = nullptr >
inline void convert_impl( const SRC& from, DST& target )
{
    //std::cout << "float_conversion" << std::endl;
    checkTruncation<SRC,DST>(from);
    target = static_cast<DST>( from );
}

template<typename SRC,typename DST,
         typename details::EnableIf< details::unsigned_to_smaller_conversion<SRC, DST>>* = nullptr  >
inline void convert_impl( const SRC& from, DST& target )
{
    //std::cout << "unsigned_to_smaller_conversion" << std::endl;

    checkUpperLimit<SRC,DST>(from);
    target = static_cast<DST>( from);
}

template<typename SRC,typename DST,
         typename details::EnableIf< details::signed_to_smaller_conversion<SRC, DST>>* = nullptr  >
inline void convert_impl( const SRC& from, DST& target )
{
    //std::cout << "signed_to_smaller_conversion" << std::endl;
    checkLowerLimit<SRC,DST>(from);
    checkUpperLimit<SRC,DST>(from);
    target = static_cast<DST>( from);
}

template<typename SRC,typename DST,
         typename details::EnableIf< details::signed_to_smaller_unsigned_conversion<SRC, DST>>* = nullptr  >
inline void convert_impl( const SRC& from, DST& target )
{
    //std::cout << "signed_to_smaller_unsigned_conversion" << std::endl;
    if (from < 0 )
        throw RangeException("Value is negative and can't be converted to signed");

    checkUpperLimit<SRC,DST>(from);

    target = static_cast<DST>( from);
}

template<typename SRC,typename DST,
         typename details::EnableIf< details::signed_to_larger_unsigned_conversion<SRC, DST>>* = nullptr   >
inline void convert_impl( const SRC& from, DST& target )
{
    //std::cout << "signed_to_larger_unsigned_conversion" << std::endl;

    if ( from < 0 )
        throw RangeException("Value is negative and can't be converted to signed");

    target = static_cast<DST>( from);
}

template<typename SRC,typename DST,
         typename details::EnableIf< details::unsigned_to_larger_signed_conversion<SRC, DST>>* = nullptr   >
inline void convert_impl( const SRC& from, DST& target )
{
    //std::cout << "unsigned_to_larger_signed_conversion" << std::endl;
    target = static_cast<DST>( from);
}

template<typename SRC,typename DST,
         typename details::EnableIf< details::unsigned_to_smaller_signed_conversion<SRC, DST>>* = nullptr   >
inline void convert_impl( const SRC& from, DST& target )
{
    //std::cout << "unsigned_to_smaller_signed_conversion" << std::endl;

    checkUpperLimit<SRC,DST>(from);
    target = static_cast<DST>( from);
}

template<typename SRC,typename DST,
         typename details::EnableIf< details::floating_to_signed_conversion<SRC, DST>>* = nullptr   >
inline void convert_impl( const SRC& from, DST& target )
{
    //std::cout << "floating_to_signed_conversion" << std::endl;

    checkLowerLimitFloat<SRC,DST>(from);
    checkLowerLimitFloat<SRC,DST>(from);

    if( from != static_cast<SRC>(static_cast<DST>( from)))
        throw RangeException("Floating point truncated");

    target = static_cast<DST>( from);
}

template<typename SRC,typename DST,
         typename details::EnableIf< details::floating_to_unsigned_conversion<SRC, DST>>* = nullptr   >
inline void convert_impl( const SRC& from, DST& target )
{
    //std::cout << "floating_to_unsigned_conversion" << std::endl;
    if ( from < 0 )
        throw RangeException("Value is negative and can't be converted to signed");

    checkLowerLimitFloat<SRC,DST>(from);

    if( from != static_cast<SRC>(static_cast<DST>( from)))
        throw RangeException("Floating point truncated");

    target = static_cast<DST>( from);
}

template<typename SRC,typename DST,
         typename details::EnableIf< details::integer_to_floating_conversion<SRC, DST>>* = nullptr >
inline void convert_impl( const SRC& from, DST& target )
{
    //std::cout << "floating_to_unsigned_conversion" << std::endl;

    checkTruncation<SRC,DST>(from);
    target = static_cast<DST>( from);
}

} //end namespace details

} //end namespace

#endif // VARIANT_H

<commit_msg>fix compilation issue<commit_after>/*********************************************************************
* Software License Agreement (BSD License)
*
*  Copyright 2016-2017 Davide Faconti
*  All rights reserved.
*
*  Redistribution and use in source and binary forms, with or without
*  modification, are permitted provided that the following conditions
*  are met:
*
*   * Redistributions of source code must retain the above copyright
*     notice, this list of conditions and the following disclaimer.
*   * Redistributions in binary form must reproduce the above
*     copyright notice, this list of conditions and the following
*     disclaimer in the documentation and/or other materials provided
*     with the distribution.
*   * Neither the name of Willow Garage, Inc. nor the names of its
*     contributors may be used to endorse or promote products derived
*     from this software without specific prior written permission.
*
*  THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
*  "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
*  LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
*  FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
*  COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
*  INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
*  BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
*  LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
*  CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
*  LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
*  ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
*  POSSIBILITY OF SUCH DAMAGE.
* *******************************************************************/

#ifndef VARIANT_IMPL_H
#define VARIANT_IMPL_H

#include <type_traits>
#include <limits>
#include <iostream>
#include "ros_type_introspection/builtin_types.hpp"
#include "ros_type_introspection/details/exceptions.hpp"

namespace RosIntrospection
{

namespace details{

template <typename T>
using Invoke = typename T::type;

template <typename BoolCondition>
using EnableIf = Invoke<std::enable_if<BoolCondition::value> >;

template <typename T>
struct is_integer : std::integral_constant<bool, std::is_integral<T>::value
        && !std::is_same<T, bool>::value
        && !std::is_same<T, char>::value>
{};

template <typename From, typename To>
struct is_same_real : std::integral_constant<bool,
    std::is_same<From, To>::value
    && std::is_floating_point<To>::value >
{};

template <typename From, typename To>
struct is_safe_integer_conversion
        : std::integral_constant<bool, is_integer<From>::value
        && is_integer<To>::value
        && sizeof(From) <= sizeof(To)
&& std::is_signed<From>::value == std::is_signed<To>::value>
{};

template <typename From, typename To>
struct float_conversion
        : std::integral_constant<bool, std::is_floating_point<From>::value
        && std::is_floating_point<To>::value >
{};

template <typename From, typename To>
struct unsigned_to_smaller_conversion
        : std::integral_constant<bool, is_integer<From>::value
        && is_integer<To>::value
        && (sizeof(From) > sizeof(To))
&& !std::is_signed<From>::value
&& !std::is_signed<To>::value >
{};

template <typename From, typename To>
struct signed_to_smaller_conversion
        : std::integral_constant<bool, is_integer<From>::value
        && is_integer<To>::value
        && (sizeof(From) > sizeof(To))
&& std::is_signed<From>::value
&& std::is_signed<To>::value >
{};

//---------------------------
template <typename From, typename To>
struct signed_to_smaller_unsigned_conversion
        : std::integral_constant<bool, is_integer<From>::value
        && is_integer<To>::value
        && sizeof(From) >= sizeof(To)
&& std::is_signed<From>::value
&& !std::is_signed<To>::value >
{};

template <typename From, typename To>
struct signed_to_larger_unsigned_conversion
        : std::integral_constant<bool, is_integer<From>::value
        && is_integer<To>::value
        && sizeof(From) < sizeof(To)
&& std::is_signed<From>::value
&& !std::is_signed<To>::value >
{};

template <typename From, typename To>
struct unsigned_to_smaller_signed_conversion
        : std::integral_constant<bool, is_integer<From>::value
        && is_integer<To>::value
        && (sizeof(From) >= sizeof(To))
&& !std::is_signed<From>::value
&& std::is_signed<To>::value >
{};

template <typename From, typename To>
struct unsigned_to_larger_signed_conversion
        : std::integral_constant<bool, is_integer<From>::value
        && is_integer<To>::value
        && sizeof(From) < sizeof(To)
&& !std::is_signed<From>::value
&& std::is_signed<To>::value >
{};

template <typename From, typename To>
struct floating_to_signed_conversion
        : std::integral_constant<bool, std::is_floating_point<From>::value
        && is_integer<To>::value
        && std::is_signed<To>::value >
{};

template <typename From, typename To>
struct floating_to_unsigned_conversion
        : std::integral_constant<bool, std::is_floating_point<From>::value
        && is_integer<To>::value
        && !std::is_signed<To>::value >
{};

template <typename From, typename To>
struct integer_to_floating_conversion
        : std::integral_constant<bool, is_integer<From>::value
        && std::is_floating_point<To>::value >
{};

template <typename From, typename To>
inline void checkUpperLimit(const From& from)
{
    if ((sizeof(To) < sizeof(From)) &&
        (from > static_cast<From>(std::numeric_limits<To>::max()))) {
        throw RangeException("Value too large.");
    }
    else if (static_cast<To>(from) > std::numeric_limits<To>::max()) {
        throw RangeException("Value too large.");
    }
}

template <typename From, typename To>
inline void checkUpperLimitFloat(const From& from)
{
  if (from > std::numeric_limits<To>::max()){
    throw RangeException("Value too large.");
  }
}

template <typename From, typename To>
inline void checkLowerLimitFloat(const From& from)
{
    if (from < -std::numeric_limits<To>::max()){
        throw RangeException("Value too small.");
    }
}

template <typename From, typename To>
inline void checkLowerLimit(const From& from)
{
  if (from < std::numeric_limits<To>::min()){
    throw RangeException("Value too small.");
  }
}

template <typename From, typename To>
inline void checkTruncation(const From& from)
{
  if( from != static_cast<From>(static_cast<To>( from))){
    throw RangeException("Floating point truncated");
  }
}

//----------------------- Implementation ----------------------------------------------

template<typename SRC,typename DST,
         typename details::EnableIf< details::is_same_real<SRC, DST>>* = nullptr >
inline void convert_impl( const SRC& from, DST& target )
{
    target = from;
}

template<typename SRC,typename DST,
         typename details::EnableIf< details::is_safe_integer_conversion<SRC, DST>>* = nullptr >
inline void convert_impl( const SRC& from, DST& target )
{
    //std::cout << "is_safe_integer_conversion" << std::endl;
    target = static_cast<DST>( from);
}

template<typename SRC,typename DST,
         typename details::EnableIf< details::float_conversion<SRC, DST>>* = nullptr >
inline void convert_impl( const SRC& from, DST& target )
{
    //std::cout << "float_conversion" << std::endl;
    checkTruncation<SRC,DST>(from);
    target = static_cast<DST>( from );
}

template<typename SRC,typename DST,
         typename details::EnableIf< details::unsigned_to_smaller_conversion<SRC, DST>>* = nullptr  >
inline void convert_impl( const SRC& from, DST& target )
{
    //std::cout << "unsigned_to_smaller_conversion" << std::endl;

    checkUpperLimit<SRC,DST>(from);
    target = static_cast<DST>( from);
}

template<typename SRC,typename DST,
         typename details::EnableIf< details::signed_to_smaller_conversion<SRC, DST>>* = nullptr  >
inline void convert_impl( const SRC& from, DST& target )
{
    //std::cout << "signed_to_smaller_conversion" << std::endl;
    checkLowerLimit<SRC,DST>(from);
    checkUpperLimit<SRC,DST>(from);
    target = static_cast<DST>( from);
}

template<typename SRC,typename DST,
         typename details::EnableIf< details::signed_to_smaller_unsigned_conversion<SRC, DST>>* = nullptr  >
inline void convert_impl( const SRC& from, DST& target )
{
    //std::cout << "signed_to_smaller_unsigned_conversion" << std::endl;
    if (from < 0 )
        throw RangeException("Value is negative and can't be converted to signed");

    checkUpperLimit<SRC,DST>(from);

    target = static_cast<DST>( from);
}

template<typename SRC,typename DST,
         typename details::EnableIf< details::signed_to_larger_unsigned_conversion<SRC, DST>>* = nullptr   >
inline void convert_impl( const SRC& from, DST& target )
{
    //std::cout << "signed_to_larger_unsigned_conversion" << std::endl;

    if ( from < 0 )
        throw RangeException("Value is negative and can't be converted to signed");

    target = static_cast<DST>( from);
}

template<typename SRC,typename DST,
         typename details::EnableIf< details::unsigned_to_larger_signed_conversion<SRC, DST>>* = nullptr   >
inline void convert_impl( const SRC& from, DST& target )
{
    //std::cout << "unsigned_to_larger_signed_conversion" << std::endl;
    target = static_cast<DST>( from);
}

template<typename SRC,typename DST,
         typename details::EnableIf< details::unsigned_to_smaller_signed_conversion<SRC, DST>>* = nullptr   >
inline void convert_impl( const SRC& from, DST& target )
{
    //std::cout << "unsigned_to_smaller_signed_conversion" << std::endl;

    checkUpperLimit<SRC,DST>(from);
    target = static_cast<DST>( from);
}

template<typename SRC,typename DST,
         typename details::EnableIf< details::floating_to_signed_conversion<SRC, DST>>* = nullptr   >
inline void convert_impl( const SRC& from, DST& target )
{
    //std::cout << "floating_to_signed_conversion" << std::endl;

    checkLowerLimitFloat<SRC,DST>(from);
    checkLowerLimitFloat<SRC,DST>(from);

    if( from != static_cast<SRC>(static_cast<DST>( from)))
        throw RangeException("Floating point truncated");

    target = static_cast<DST>( from);
}

template<typename SRC,typename DST,
         typename details::EnableIf< details::floating_to_unsigned_conversion<SRC, DST>>* = nullptr   >
inline void convert_impl( const SRC& from, DST& target )
{
    //std::cout << "floating_to_unsigned_conversion" << std::endl;
    if ( from < 0 )
        throw RangeException("Value is negative and can't be converted to signed");

    checkLowerLimitFloat<SRC,DST>(from);

    if( from != static_cast<SRC>(static_cast<DST>( from)))
        throw RangeException("Floating point truncated");

    target = static_cast<DST>( from);
}

template<typename SRC,typename DST,
         typename details::EnableIf< details::integer_to_floating_conversion<SRC, DST>>* = nullptr >
inline void convert_impl( const SRC& from, DST& target )
{
    //std::cout << "floating_to_unsigned_conversion" << std::endl;

    checkTruncation<SRC,DST>(from);
    target = static_cast<DST>( from);
}

} //end namespace details

} //end namespace

#endif // VARIANT_H

<|endoftext|>


<commit_before><commit_msg>Select best adapter (by dedicated video memory) for DX12 device creation<commit_after><|endoftext|>


<commit_before><commit_msg>Add additional chipunits in chiplet check logic<commit_after><|endoftext|>


<commit_before><commit_msg>INTEGRATION: CWS ooo19126 (1.5.348); FILE MERGED 2005/09/05 13:06:37 rt 1.5.348.1: #i54170# Change license header: remove SISSL<commit_after><|endoftext|>


<commit_before><commit_msg>Add `size` method to binary tree<commit_after><|endoftext|>