<commit_before>/**************************************************************************
** This file is part of LiteIDE
**
** Copyright (c) 2011-2019 visualfc. 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.
**
** In addition, as a special exception,  that plugins developed for LiteIDE,
** are allowed to remain closed sourced and can be distributed under any license .
** These rights are included in the file LGPL_EXCEPTION.txt in this package.
**
**************************************************************************/
// Module: quickopenwidget.cpp
// Creator: visualfc <visualfc@gmail.com>

#include "quickopenwidget.h"
#include "liteapi/liteids.h"
#include <QVBoxLayout>
#include <QComboBox>
#include <QTreeView>
#include <QFocusEvent>
#include <QHeaderView>
#include <QDebug>
#include <QApplication>
#include <QToolBar>

//lite_memory_check_begin
#if defined(WIN32) && defined(_MSC_VER) &&  defined(_DEBUG)
     #define _CRTDBG_MAP_ALLOC
     #include <stdlib.h>
     #include <crtdbg.h>
     #define DEBUG_NEW new( _NORMAL_BLOCK, __FILE__, __LINE__ )
     #define new DEBUG_NEW
#endif
//lite_memory_check_end

QuickOpenWidget::QuickOpenWidget(LiteApi::IApplication *app, QWidget *parent) :
    QWidget(parent, Qt::Popup),// Qt::ToolTip | Qt::WindowStaysOnTopHint),
    m_liteApp(app)
{
    //this->setFocusPolicy(Qt::NoFocus);
    m_edit = new Utils::FilterLineEdit(300);
    m_view = new QTreeView;
    m_view->setHeaderHidden(true);
    m_view->setTextElideMode(Qt::ElideLeft);
#if QT_VERSION >= 0x050000
    m_view->header()->setSectionResizeMode(QHeaderView::ResizeToContents);
#else
    m_view->header()->setResizeMode(QHeaderView::ResizeToContents);
#endif
    m_view->setEditTriggers(QAbstractItemView::NoEditTriggers);

    m_wrap = true;

    m_tmpToolBar = 0;

    m_layout = new QVBoxLayout;
    m_layout->setMargin(0);
    m_layout->setSpacing(0);
    m_layout->addWidget(m_edit);
    m_layout->addWidget(m_view);

    this->setMinimumWidth(600);
    this->setMinimumHeight(300);

    this->setLayout(m_layout);

    connect(m_edit,SIGNAL(filterChanged(QString)),this,SIGNAL(filterChanged(QString)));

    m_edit->installEventFilter(this);
}

void QuickOpenWidget::setModel(QAbstractItemModel *model,const QModelIndex &rootIndex)
{
    m_view->setModel(model);
    m_view->setRootIndex(rootIndex);
}

QLineEdit *QuickOpenWidget::editor()
{
    return m_edit;
}

QTreeView *QuickOpenWidget::view()
{
    return m_view;
}

void QuickOpenWidget::setTempToolBar(QToolBar *toolBar)
{
    if (m_tmpToolBar) {
        m_layout->removeWidget(m_tmpToolBar);
        m_tmpToolBar->hide();
    }
    m_tmpToolBar = toolBar;
    if (toolBar == 0) {
        return;
    }
    m_tmpToolBar->show();
    m_layout->insertWidget(0,m_tmpToolBar);
}

void QuickOpenWidget::hideEvent(QHideEvent *e)
{
    emit hideWidget();
    if (m_tmpToolBar) {
        m_layout->removeWidget(m_tmpToolBar);
        m_tmpToolBar->hide();
    }
    m_tmpToolBar = 0;
    QWidget::hideEvent(e);
}

void QuickOpenWidget::closeWidget()
{
    if (m_tmpToolBar) {
        m_layout->removeWidget(m_tmpToolBar);
    }
    m_tmpToolBar = 0;
    QWidget::close();
}

void QuickOpenWidget::showView(QPoint *pos)
{
    if (pos == 0) {
        QPoint pt(0,0);
        this->move(m_liteApp->editorManager()->widget()->mapToGlobal(pt));
    } else {
        this->move(pos->x(),pos->y());
    }
    m_edit->setFocus();
    this->show();
}

bool QuickOpenWidget::eventFilter(QObject *o, QEvent *e)
{
    if (e->type() == QEvent::KeyPress) {
        QKeyEvent *ke = static_cast<QKeyEvent *>(e);
        QAbstractItemModel *model = m_view->model();
        if (!model) {
            return false;
        }

        const int key = ke->key();
        switch (key) {
        case Qt::Key_Up: {
            QModelIndex index = m_view->indexAbove(m_view->currentIndex());
            if (!index.isValid()) {
                index = model->index(model->rowCount(m_view->rootIndex())-1,0,m_view->rootIndex());
            }

            m_view->setCurrentIndex(index);
            emit indexChanage(index);
            return true;
        }
        case Qt::Key_Down: {
            QModelIndex index = m_view->indexBelow(m_view->currentIndex());
            if (!index.isValid()) {
                index = model->index(0,0,m_view->rootIndex());
            }
            m_view->setCurrentIndex(index);
            emit indexChanage(index);
            return true;
        }
        case Qt::Key_Return: {
            QModelIndex index = m_view->currentIndex();
            if (model->hasChildren(index)) {
                m_view->setExpanded(index,!m_view->isExpanded(index));
            } else {
                emit indexEnter(index);
            }
            return true;
        }
        }
    } else if (e->type() == QEvent::FocusOut) {
        if (QWidget::focusWidget() == m_view ) {
            m_edit->setFocus();
        }
        return true;
    }
    return QWidget::eventFilter(o,e);
}
<commit_msg>quickopen: filter disable key_return check<commit_after>/**************************************************************************
** This file is part of LiteIDE
**
** Copyright (c) 2011-2019 visualfc. 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.
**
** In addition, as a special exception,  that plugins developed for LiteIDE,
** are allowed to remain closed sourced and can be distributed under any license .
** These rights are included in the file LGPL_EXCEPTION.txt in this package.
**
**************************************************************************/
// Module: quickopenwidget.cpp
// Creator: visualfc <visualfc@gmail.com>

#include "quickopenwidget.h"
#include "liteapi/liteids.h"
#include <QVBoxLayout>
#include <QComboBox>
#include <QTreeView>
#include <QFocusEvent>
#include <QHeaderView>
#include <QDebug>
#include <QApplication>
#include <QToolBar>

//lite_memory_check_begin
#if defined(WIN32) && defined(_MSC_VER) &&  defined(_DEBUG)
     #define _CRTDBG_MAP_ALLOC
     #include <stdlib.h>
     #include <crtdbg.h>
     #define DEBUG_NEW new( _NORMAL_BLOCK, __FILE__, __LINE__ )
     #define new DEBUG_NEW
#endif
//lite_memory_check_end

QuickOpenWidget::QuickOpenWidget(LiteApi::IApplication *app, QWidget *parent) :
    QWidget(parent, Qt::Popup),// Qt::ToolTip | Qt::WindowStaysOnTopHint),
    m_liteApp(app)
{
    //this->setFocusPolicy(Qt::NoFocus);
    m_edit = new Utils::FilterLineEdit(300);
    m_view = new QTreeView;
    m_view->setHeaderHidden(true);
    m_view->setTextElideMode(Qt::ElideLeft);
#if QT_VERSION >= 0x050000
    m_view->header()->setSectionResizeMode(QHeaderView::ResizeToContents);
#else
    m_view->header()->setResizeMode(QHeaderView::ResizeToContents);
#endif
    m_view->setEditTriggers(QAbstractItemView::NoEditTriggers);

    m_wrap = true;

    m_tmpToolBar = 0;

    m_layout = new QVBoxLayout;
    m_layout->setMargin(0);
    m_layout->setSpacing(0);
    m_layout->addWidget(m_edit);
    m_layout->addWidget(m_view);

    this->setMinimumWidth(600);
    this->setMinimumHeight(300);

    this->setLayout(m_layout);

    connect(m_edit,SIGNAL(filterChanged(QString)),this,SIGNAL(filterChanged(QString)));

    m_edit->installEventFilter(this);
}

void QuickOpenWidget::setModel(QAbstractItemModel *model,const QModelIndex &rootIndex)
{
    m_view->setModel(model);
    m_view->setRootIndex(rootIndex);
}

QLineEdit *QuickOpenWidget::editor()
{
    return m_edit;
}

QTreeView *QuickOpenWidget::view()
{
    return m_view;
}

void QuickOpenWidget::setTempToolBar(QToolBar *toolBar)
{
    if (m_tmpToolBar) {
        m_layout->removeWidget(m_tmpToolBar);
        m_tmpToolBar->hide();
    }
    m_tmpToolBar = toolBar;
    if (toolBar == 0) {
        return;
    }
    m_tmpToolBar->show();
    m_layout->insertWidget(0,m_tmpToolBar);
}

void QuickOpenWidget::hideEvent(QHideEvent *e)
{
    emit hideWidget();
    if (m_tmpToolBar) {
        m_layout->removeWidget(m_tmpToolBar);
        m_tmpToolBar->hide();
    }
    m_tmpToolBar = 0;
    QWidget::hideEvent(e);
}

void QuickOpenWidget::closeWidget()
{
    if (m_tmpToolBar) {
        m_layout->removeWidget(m_tmpToolBar);
    }
    m_tmpToolBar = 0;
    QWidget::close();
}

void QuickOpenWidget::showView(QPoint *pos)
{
    if (pos == 0) {
        QPoint pt(0,0);
        this->move(m_liteApp->editorManager()->widget()->mapToGlobal(pt));
    } else {
        this->move(pos->x(),pos->y());
    }
    m_edit->setFocus();
    this->show();
}

bool QuickOpenWidget::eventFilter(QObject *o, QEvent *e)
{
    if (e->type() == QEvent::KeyPress) {
        QKeyEvent *ke = static_cast<QKeyEvent *>(e);
        QAbstractItemModel *model = m_view->model();
        if (!model) {
            return false;
        }

        const int key = ke->key();
        switch (key) {
        case Qt::Key_Up: {
            QModelIndex index = m_view->indexAbove(m_view->currentIndex());
            if (!index.isValid()) {
                index = model->index(model->rowCount(m_view->rootIndex())-1,0,m_view->rootIndex());
            }

            m_view->setCurrentIndex(index);
            emit indexChanage(index);
            return true;
        }
        case Qt::Key_Down: {
            QModelIndex index = m_view->indexBelow(m_view->currentIndex());
            if (!index.isValid()) {
                index = model->index(0,0,m_view->rootIndex());
            }
            m_view->setCurrentIndex(index);
            emit indexChanage(index);
            return true;
        }
//        case Qt::Key_Return: {
//            QModelIndex index = m_view->currentIndex();
//            if (model->hasChildren(index)) {
//                m_view->setExpanded(index,!m_view->isExpanded(index));
//            } else {
//                emit indexEnter(index);
//            }
//            return true;
//        }
        }
    } else if (e->type() == QEvent::FocusOut) {
        if (QWidget::focusWidget() == m_view ) {
            m_edit->setFocus();
        }
        return true;
    }
    return QWidget::eventFilter(o,e);
}
<|endoftext|>


<commit_before>/*************************************************************************
 *
 *  $RCSfile: ManifestImport.cxx,v $
 *
 *  $Revision: 1.4 $
 *
 *  last change: $Author: mtg $ $Date: 2001-05-17 13:03:42 $
 *
 *  The Contents of this file are made available subject to the terms of
 *  either of the following licenses
 *
 *         - GNU Lesser General Public License Version 2.1
 *         - Sun Industry Standards Source License Version 1.1
 *
 *  Sun Microsystems Inc., October, 2000
 *
 *  GNU Lesser General Public License Version 2.1
 *  =============================================
 *  Copyright 2000 by Sun Microsystems, Inc.
 *  901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *  This library is free software; you can redistribute it and/or
 *  modify it under the terms of the GNU Lesser General Public
 *  License version 2.1, as published by the Free Software Foundation.
 *
 *  This library is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *  Lesser General Public License for more details.
 *
 *  You should have received a copy of the GNU Lesser General Public
 *  License along with this library; if not, write to the Free Software
 *  Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *  MA  02111-1307  USA
 *
 *
 *  Sun Industry Standards Source License Version 1.1
 *  =================================================
 *  The contents of this file are subject to the Sun Industry Standards
 *  Source License Version 1.1 (the "License"); You may not use this file
 *  except in compliance with the License. You may obtain a copy of the
 *  License at http://www.openoffice.org/license.html.
 *
 *  Software provided under this License is provided on an "AS IS" basis,
 *  WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
 *  WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
 *  MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
 *  See the License for the specific provisions governing your rights and
 *  obligations concerning the Software.
 *
 *  The Initial Developer of the Original Code is: Sun Microsystems, Inc.
 *
 *  Copyright: 2000 by Sun Microsystems, Inc.
 *
 *  All Rights Reserved.
 *
 *  Contributor(s): Martin Gallwey (gallwey@sun.com)
 *
 *
 ************************************************************************/

#ifndef _MANIFEST_IMPORT_HXX
#include <ManifestImport.hxx>
#endif
#ifndef _MANIFEST_DEFINES_HXX
#include <ManifestDefines.hxx>
#endif
#ifndef _BASE64_CODEC_HXX_
#include <Base64Codec.hxx>
#endif
using namespace com::sun::star::uno;
using namespace com::sun::star::beans;
using namespace com::sun::star;
using namespace rtl;
using namespace std;

ManifestImport::ManifestImport( vector < Sequence < PropertyValue > > & rNewManVector )
: rManVector ( rNewManVector )
, nNumProperty (0)
, bIgnoreEncryptData    ( sal_False )

, sFileEntryElement     ( RTL_CONSTASCII_USTRINGPARAM ( ELEMENT_FILE_ENTRY ) )
, sManifestElement      ( RTL_CONSTASCII_USTRINGPARAM ( ELEMENT_MANIFEST ) )
, sEncryptionDataElement( RTL_CONSTASCII_USTRINGPARAM ( ELEMENT_ENCRYPTION_DATA ) )
, sAlgorithmElement ( RTL_CONSTASCII_USTRINGPARAM ( ELEMENT_ALGORITHM ) )
, sKeyDerivationElement( RTL_CONSTASCII_USTRINGPARAM ( ELEMENT_KEY_DERIVATION ) )

, sCdataAttribute       ( RTL_CONSTASCII_USTRINGPARAM ( ATTRIBUTE_CDATA ) )
, sMediaTypeAttribute   ( RTL_CONSTASCII_USTRINGPARAM ( ATTRIBUTE_MEDIA_TYPE ) )
, sFullPathAttribute    ( RTL_CONSTASCII_USTRINGPARAM ( ATTRIBUTE_FULL_PATH ) )
, sSizeAttribute        ( RTL_CONSTASCII_USTRINGPARAM ( ATTRIBUTE_SIZE ) )
, sSaltAttribute        ( RTL_CONSTASCII_USTRINGPARAM ( ATTRIBUTE_SALT ) )
, sInitialisationVectorAttribute ( RTL_CONSTASCII_USTRINGPARAM ( ATTRIBUTE_INITIALISATION_VECTOR ) )
, sIterationCountAttribute ( RTL_CONSTASCII_USTRINGPARAM ( ATTRIBUTE_ITERATION_COUNT ) )
, sAlgorithmNameAttribute   ( RTL_CONSTASCII_USTRINGPARAM ( ATTRIBUTE_ALGORITHM_NAME ) )
, sKeyDerivationNameAttribute   ( RTL_CONSTASCII_USTRINGPARAM ( ATTRIBUTE_KEY_DERIVATION_NAME ) )

, sFullPathProperty             ( RTL_CONSTASCII_USTRINGPARAM ( "FullPath" ) )
, sMediaTypeProperty            ( RTL_CONSTASCII_USTRINGPARAM ( "MediaType" ) )
, sIterationCountProperty       ( RTL_CONSTASCII_USTRINGPARAM ( "IterationCount" ) )
, sSaltProperty                 ( RTL_CONSTASCII_USTRINGPARAM ( "Salt" ) )
, sInitialisationVectorProperty ( RTL_CONSTASCII_USTRINGPARAM ( "InitialisationVector" ) )
, sSizeProperty                 ( RTL_CONSTASCII_USTRINGPARAM ( "Size" ) )

, sWhiteSpace               ( RTL_CONSTASCII_USTRINGPARAM ( " " ) )
, sBlowfish                 ( RTL_CONSTASCII_USTRINGPARAM ( "Blowfish CFB" ) )
, sPBKDF2                   ( RTL_CONSTASCII_USTRINGPARAM ( "PBKDF2" ) )
{
}
ManifestImport::~ManifestImport (void )
{
}
void SAL_CALL ManifestImport::startDocument(  )
        throw(xml::sax::SAXException, uno::RuntimeException)
{
}
void SAL_CALL ManifestImport::endDocument(  )
        throw(xml::sax::SAXException, uno::RuntimeException)
{
}
void SAL_CALL ManifestImport::startElement( const OUString& aName, const uno::Reference< xml::sax::XAttributeList >& xAttribs )
        throw(xml::sax::SAXException, uno::RuntimeException)
{
    if (aName == sFileEntryElement)
    {
        aStack.push( e_FileEntry );
        aSequence.realloc ( 6 ); // Can have at most 6 entries (currently, will realloc to actual number in endElement)
        aSequence[nNumProperty].Name = sMediaTypeProperty;
        aSequence[nNumProperty++].Value <<= xAttribs->getValueByName( sMediaTypeAttribute );
        aSequence[nNumProperty].Name = sFullPathProperty;
        aSequence[nNumProperty++].Value <<= xAttribs->getValueByName( sFullPathAttribute );

        OUString sSize = xAttribs->getValueByName ( sSizeAttribute );
        if (sSize.getLength())
        {
            sal_Int32 nSize;
            nSize = sSize.toInt32();
            aSequence[nNumProperty].Name = sSizeProperty;
            aSequence[nNumProperty++].Value <<= nSize;
        }
    }
    else if (!aStack.empty())
    {
        if (aStack.top() == e_FileEntry && aName == sEncryptionDataElement)
        {
            // If this element exists, then this stream is encrypted and we need
            // to store the initialisation vector, salt and iteration count used
            aStack.push (e_EncryptionData );
        }
        else if (aStack.top() == e_EncryptionData && aName == sAlgorithmElement)
        {
            aStack.push (e_Algorithm);
            OUString aString = xAttribs->getValueByName ( sAlgorithmNameAttribute );
            if (aString == sBlowfish && !bIgnoreEncryptData)
            {
                aString = xAttribs->getValueByName ( sInitialisationVectorAttribute );
                Sequence < sal_uInt8 > aDecodeBuffer;
                Base64Codec::decodeBase64 (aDecodeBuffer, aString);
                aSequence[nNumProperty].Name = sInitialisationVectorProperty;
                aSequence[nNumProperty++].Value <<= aDecodeBuffer;
            }
            else
                // If we don't recognise the algorithm, then the key derivation info
                // is useless to us
                bIgnoreEncryptData = sal_True;
        }
        else if (aStack.top() == e_EncryptionData && aName == sKeyDerivationElement)
        {
            aStack.push (e_KeyDerivation);
            OUString aString = xAttribs->getValueByName ( sKeyDerivationNameAttribute );
            if ( aString == sPBKDF2 && !bIgnoreEncryptData )
            {
                aString = xAttribs->getValueByName ( sSaltAttribute );
                Sequence < sal_uInt8 > aDecodeBuffer;
                Base64Codec::decodeBase64 (aDecodeBuffer, aString);
                aSequence[nNumProperty].Name = sSaltProperty;
                aSequence[nNumProperty++].Value <<= aDecodeBuffer;

                aString = xAttribs->getValueByName ( sIterationCountAttribute );
                aSequence[nNumProperty].Name = sIterationCountProperty;
                aSequence[nNumProperty++].Value <<= aString.toInt32();
            }
            else
                // If we don't recognise the key derivation technique, then the
                // algorithm info is useless to us
                bIgnoreEncryptData = sal_True;
        }
    }
}
void SAL_CALL ManifestImport::endElement( const OUString& aName )
    throw(xml::sax::SAXException, uno::RuntimeException)
{
    if ( !aStack.empty() )
    {
        if (aStack.top() == e_FileEntry)
        {
            aSequence.realloc ( nNumProperty );
            bIgnoreEncryptData = sal_False;
            rManVector.push_back ( aSequence );
            nNumProperty = 0;
        }
        aStack.pop();
    }
}
void SAL_CALL ManifestImport::characters( const OUString& aChars )
        throw(xml::sax::SAXException, uno::RuntimeException)
{
}
void SAL_CALL ManifestImport::ignorableWhitespace( const OUString& aWhitespaces )
        throw(xml::sax::SAXException, uno::RuntimeException)
{
}
void SAL_CALL ManifestImport::processingInstruction( const OUString& aTarget, const OUString& aData )
        throw(xml::sax::SAXException, uno::RuntimeException)
{
}
void SAL_CALL ManifestImport::setDocumentLocator( const uno::Reference< xml::sax::XLocator >& xLocator )
        throw(xml::sax::SAXException, uno::RuntimeException)
{
}

<commit_msg>#90699# import MD5 of unencrypted stream<commit_after>/*************************************************************************
 *
 *  $RCSfile: ManifestImport.cxx,v $
 *
 *  $Revision: 1.5 $
 *
 *  last change: $Author: mtg $ $Date: 2001-09-05 19:23:48 $
 *
 *  The Contents of this file are made available subject to the terms of
 *  either of the following licenses
 *
 *         - GNU Lesser General Public License Version 2.1
 *         - Sun Industry Standards Source License Version 1.1
 *
 *  Sun Microsystems Inc., October, 2000
 *
 *  GNU Lesser General Public License Version 2.1
 *  =============================================
 *  Copyright 2000 by Sun Microsystems, Inc.
 *  901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *  This library is free software; you can redistribute it and/or
 *  modify it under the terms of the GNU Lesser General Public
 *  License version 2.1, as published by the Free Software Foundation.
 *
 *  This library is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *  Lesser General Public License for more details.
 *
 *  You should have received a copy of the GNU Lesser General Public
 *  License along with this library; if not, write to the Free Software
 *  Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *  MA  02111-1307  USA
 *
 *
 *  Sun Industry Standards Source License Version 1.1
 *  =================================================
 *  The contents of this file are subject to the Sun Industry Standards
 *  Source License Version 1.1 (the "License"); You may not use this file
 *  except in compliance with the License. You may obtain a copy of the
 *  License at http://www.openoffice.org/license.html.
 *
 *  Software provided under this License is provided on an "AS IS" basis,
 *  WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
 *  WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
 *  MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
 *  See the License for the specific provisions governing your rights and
 *  obligations concerning the Software.
 *
 *  The Initial Developer of the Original Code is: Sun Microsystems, Inc.
 *
 *  Copyright: 2000 by Sun Microsystems, Inc.
 *
 *  All Rights Reserved.
 *
 *  Contributor(s): Martin Gallwey (gallwey@sun.com)
 *
 *
 ************************************************************************/

#ifndef _MANIFEST_IMPORT_HXX
#include <ManifestImport.hxx>
#endif
#ifndef _MANIFEST_DEFINES_HXX
#include <ManifestDefines.hxx>
#endif
#ifndef _BASE64_CODEC_HXX_
#include <Base64Codec.hxx>
#endif
using namespace com::sun::star::uno;
using namespace com::sun::star::beans;
using namespace com::sun::star;
using namespace rtl;
using namespace std;

ManifestImport::ManifestImport( vector < Sequence < PropertyValue > > & rNewManVector )
: rManVector ( rNewManVector )
, nNumProperty (0)
, bIgnoreEncryptData    ( sal_False )

, sFileEntryElement     ( RTL_CONSTASCII_USTRINGPARAM ( ELEMENT_FILE_ENTRY ) )
, sManifestElement      ( RTL_CONSTASCII_USTRINGPARAM ( ELEMENT_MANIFEST ) )
, sEncryptionDataElement( RTL_CONSTASCII_USTRINGPARAM ( ELEMENT_ENCRYPTION_DATA ) )
, sAlgorithmElement ( RTL_CONSTASCII_USTRINGPARAM ( ELEMENT_ALGORITHM ) )
, sKeyDerivationElement( RTL_CONSTASCII_USTRINGPARAM ( ELEMENT_KEY_DERIVATION ) )

, sCdataAttribute               ( RTL_CONSTASCII_USTRINGPARAM ( ATTRIBUTE_CDATA ) )
, sMediaTypeAttribute           ( RTL_CONSTASCII_USTRINGPARAM ( ATTRIBUTE_MEDIA_TYPE ) )
, sFullPathAttribute            ( RTL_CONSTASCII_USTRINGPARAM ( ATTRIBUTE_FULL_PATH ) )
, sSizeAttribute                ( RTL_CONSTASCII_USTRINGPARAM ( ATTRIBUTE_SIZE ) )
, sSaltAttribute                ( RTL_CONSTASCII_USTRINGPARAM ( ATTRIBUTE_SALT ) )
, sInitialisationVectorAttribute ( RTL_CONSTASCII_USTRINGPARAM ( ATTRIBUTE_INITIALISATION_VECTOR ) )
, sIterationCountAttribute      ( RTL_CONSTASCII_USTRINGPARAM ( ATTRIBUTE_ITERATION_COUNT ) )
, sAlgorithmNameAttribute       ( RTL_CONSTASCII_USTRINGPARAM ( ATTRIBUTE_ALGORITHM_NAME ) )
, sKeyDerivationNameAttribute   ( RTL_CONSTASCII_USTRINGPARAM ( ATTRIBUTE_KEY_DERIVATION_NAME ) )
, sChecksumTypeAttribute        ( RTL_CONSTASCII_USTRINGPARAM ( ATTRIBUTE_CHECKSUM_TYPE ) )
, sChecksumAttribute            ( RTL_CONSTASCII_USTRINGPARAM ( ATTRIBUTE_CHECKSUM ) )

, sFullPathProperty             ( RTL_CONSTASCII_USTRINGPARAM ( "FullPath" ) )
, sMediaTypeProperty            ( RTL_CONSTASCII_USTRINGPARAM ( "MediaType" ) )
, sIterationCountProperty       ( RTL_CONSTASCII_USTRINGPARAM ( "IterationCount" ) )
, sSaltProperty                 ( RTL_CONSTASCII_USTRINGPARAM ( "Salt" ) )
, sInitialisationVectorProperty ( RTL_CONSTASCII_USTRINGPARAM ( "InitialisationVector" ) )
, sSizeProperty                 ( RTL_CONSTASCII_USTRINGPARAM ( "Size" ) )
, sDigestProperty               ( RTL_CONSTASCII_USTRINGPARAM ( "Digest" ) )

, sWhiteSpace                   ( RTL_CONSTASCII_USTRINGPARAM ( " " ) )
, sBlowfish                     ( RTL_CONSTASCII_USTRINGPARAM ( "Blowfish CFB" ) )
, sPBKDF2                       ( RTL_CONSTASCII_USTRINGPARAM ( "PBKDF2" ) )
, sMD5                          ( RTL_CONSTASCII_USTRINGPARAM ( "MD5" ) )
{
}
ManifestImport::~ManifestImport (void )
{
}
void SAL_CALL ManifestImport::startDocument(  )
        throw(xml::sax::SAXException, uno::RuntimeException)
{
}
void SAL_CALL ManifestImport::endDocument(  )
        throw(xml::sax::SAXException, uno::RuntimeException)
{
}
void SAL_CALL ManifestImport::startElement( const OUString& aName, const uno::Reference< xml::sax::XAttributeList >& xAttribs )
        throw(xml::sax::SAXException, uno::RuntimeException)
{
    if (aName == sFileEntryElement)
    {
        aStack.push( e_FileEntry );
        aSequence.realloc ( 7 ); // Can have at most 6 entries (currently, will realloc to actual number in endElement)

        // Put full-path property first for MBA
        aSequence[nNumProperty].Name = sFullPathProperty;
        aSequence[nNumProperty++].Value <<= xAttribs->getValueByName( sFullPathAttribute );
        aSequence[nNumProperty].Name = sMediaTypeProperty;
        aSequence[nNumProperty++].Value <<= xAttribs->getValueByName( sMediaTypeAttribute );

        OUString sSize = xAttribs->getValueByName ( sSizeAttribute );
        if (sSize.getLength())
        {
            sal_Int32 nSize;
            nSize = sSize.toInt32();
            aSequence[nNumProperty].Name = sSizeProperty;
            aSequence[nNumProperty++].Value <<= nSize;
        }
    }
    else if (!aStack.empty())
    {
        if (aStack.top() == e_FileEntry && aName == sEncryptionDataElement)
        {
            // If this element exists, then this stream is encrypted and we need
            // to store the initialisation vector, salt and iteration count used
            aStack.push (e_EncryptionData );
            OUString aString = xAttribs->getValueByName ( sChecksumTypeAttribute );
            if (aString == sMD5 && !bIgnoreEncryptData)
            {
                aString = xAttribs->getValueByName ( sChecksumAttribute );
                Sequence < sal_uInt8 > aDecodeBuffer;
                Base64Codec::decodeBase64 (aDecodeBuffer, aString);
                aSequence[nNumProperty].Name = sDigestProperty;
                aSequence[nNumProperty++].Value <<= aDecodeBuffer;
            }
        }
        else if (aStack.top() == e_EncryptionData && aName == sAlgorithmElement)
        {
            aStack.push (e_Algorithm);
            OUString aString = xAttribs->getValueByName ( sAlgorithmNameAttribute );
            if (aString == sBlowfish && !bIgnoreEncryptData)
            {
                aString = xAttribs->getValueByName ( sInitialisationVectorAttribute );
                Sequence < sal_uInt8 > aDecodeBuffer;
                Base64Codec::decodeBase64 (aDecodeBuffer, aString);
                aSequence[nNumProperty].Name = sInitialisationVectorProperty;
                aSequence[nNumProperty++].Value <<= aDecodeBuffer;
            }
            else
                // If we don't recognise the algorithm, then the key derivation info
                // is useless to us
                bIgnoreEncryptData = sal_True;
        }
        else if (aStack.top() == e_EncryptionData && aName == sKeyDerivationElement)
        {
            aStack.push (e_KeyDerivation);
            OUString aString = xAttribs->getValueByName ( sKeyDerivationNameAttribute );
            if ( aString == sPBKDF2 && !bIgnoreEncryptData )
            {
                aString = xAttribs->getValueByName ( sSaltAttribute );
                Sequence < sal_uInt8 > aDecodeBuffer;
                Base64Codec::decodeBase64 (aDecodeBuffer, aString);
                aSequence[nNumProperty].Name = sSaltProperty;
                aSequence[nNumProperty++].Value <<= aDecodeBuffer;

                aString = xAttribs->getValueByName ( sIterationCountAttribute );
                aSequence[nNumProperty].Name = sIterationCountProperty;
                aSequence[nNumProperty++].Value <<= aString.toInt32();
            }
            else
                // If we don't recognise the key derivation technique, then the
                // algorithm info is useless to us
                bIgnoreEncryptData = sal_True;
        }
    }
}
void SAL_CALL ManifestImport::endElement( const OUString& aName )
    throw(xml::sax::SAXException, uno::RuntimeException)
{
    if ( !aStack.empty() )
    {
        if (aStack.top() == e_FileEntry)
        {
            aSequence.realloc ( nNumProperty );
            bIgnoreEncryptData = sal_False;
            rManVector.push_back ( aSequence );
            nNumProperty = 0;
        }
        aStack.pop();
    }
}
void SAL_CALL ManifestImport::characters( const OUString& aChars )
        throw(xml::sax::SAXException, uno::RuntimeException)
{
}
void SAL_CALL ManifestImport::ignorableWhitespace( const OUString& aWhitespaces )
        throw(xml::sax::SAXException, uno::RuntimeException)
{
}
void SAL_CALL ManifestImport::processingInstruction( const OUString& aTarget, const OUString& aData )
        throw(xml::sax::SAXException, uno::RuntimeException)
{
}
void SAL_CALL ManifestImport::setDocumentLocator( const uno::Reference< xml::sax::XLocator >& xLocator )
        throw(xml::sax::SAXException, uno::RuntimeException)
{
}

<|endoftext|>


<commit_before>/****************************************************************************
 * Copyright (c) 2012-2017 by the DataTransferKit authors                   *
 * All rights reserved.                                                     *
 *                                                                          *
 * This file is part of the DataTransferKit library. DataTransferKit is     *
 * distributed under a BSD 3-clause license. For the licensing terms see    *
 * the LICENSE file in the top-level directory.                             *
 ****************************************************************************/

#ifndef DTK_LINEAR_BVH_DECL_HPP
#define DTK_LINEAR_BVH_DECL_HPP

#include <Kokkos_ArithTraits.hpp>
#include <Kokkos_Array.hpp>
#include <Kokkos_View.hpp>

#include <DTK_DetailsAlgorithms.hpp>
#include <DTK_DetailsBox.hpp>
#include <DTK_DetailsNode.hpp>
#include <DTK_DetailsPredicate.hpp>

#include "DTK_ConfigDefs.hpp"

namespace DataTransferKit
{
namespace Details
{
template <typename NO>
struct TreeTraversal;
}

/**
 * Bounding Volume Hierarchy.
 */
template <typename NO>
struct BVH
{
  public:
    using DeviceType = typename NO::device_type;

  public:
    BVH( Kokkos::View<Box const *, DeviceType> bounding_boxes );

    template <typename Query>
    void query( Kokkos::View<Query *, DeviceType> queries,
                Kokkos::View<int *, DeviceType> &indices,
                Kokkos::View<int *, DeviceType> &offset ) const;

  private:
    friend struct Details::TreeTraversal<NO>;

    Kokkos::View<Node *, DeviceType> _leaf_nodes;
    Kokkos::View<Node *, DeviceType> _internal_nodes;
    /*
     * Array of indices that sort the boxes used to construct the hierarchy.
     * The leaf nodes are ordered so we need these to identify objects that
     * meet a predicate.
     */
    Kokkos::View<int *, DeviceType> _indices;
};

template <typename NO>
template <typename Query>
void BVH<NO>::query( Kokkos::View<Query *, DeviceType> queries,
                     Kokkos::View<int *, DeviceType> &indices,
                     Kokkos::View<int *, DeviceType> &offset ) const
{
    using ExecutionSpace = typename DeviceType::execution_space;

    namespace details = DataTransferKit::Details;

    int const n_queries = queries.extent( 0 );

    // Initialize view
    // [ 0 0 0 .... 0 0 ]
    //                ^
    //                N
    Kokkos::resize( offset, n_queries + 1 );
    Kokkos::parallel_for(
        "query(): initialize offset (set all entries to zero)",
        Kokkos::RangePolicy<ExecutionSpace>( 0, n_queries + 1 ),
        KOKKOS_LAMBDA( int i ) { offset[i] = 0; } );
    Kokkos::fence();

    // Make a copy of *this. We need this to put is on the device. Otherwise,
    // it will throw illegal address error in the paralle_for loops below.
    BVH<NO> bvh = *this;

    // Say we found exactly two object for each query:
    // [ 2 2 2 .... 2 0 ]
    //   ^            ^
    //   0th          Nth element in the view
    Kokkos::parallel_for(
        "query(): first pass at the search count the number of indices",
        Kokkos::RangePolicy<ExecutionSpace>( 0, n_queries ),
        KOKKOS_LAMBDA( int i ) {
            offset( i ) = details::TreeTraversal<NO>::query(
                bvh, queries( i ), []( int index ) {} );
        } );
    Kokkos::fence();

    // Then we would get:
    // [ 0 2 4 .... 2N-2 2N ]
    //                    ^
    //                    N
    Kokkos::parallel_scan(
        "query(): compute offset",
        Kokkos::RangePolicy<ExecutionSpace>( 0, n_queries + 1 ),
        KOKKOS_LAMBDA( int i, int &update, bool final_pass ) {
            int const offset_i = offset( i );
            if ( final_pass )
                offset( i ) = update;
            update += offset_i;
        } );
    Kokkos::fence();

    // Let us extract the last element in the view which is the total count of
    // objects which where found to meet the query predicates:
    //
    // [ 2N ]
    auto total_count = Kokkos::subview( offset, n_queries );
    auto total_count_host = Kokkos::create_mirror_view( total_count );
    // We allocate the memory and fill
    //
    // [ A0 A1 B0 B1 C0 C1 ... X0 X1 ]
    //   ^     ^     ^         ^     ^
    //   0     2     4         2N-2  2N
    Kokkos::deep_copy( total_count_host, total_count );
    Kokkos::resize( indices, total_count( 0 ) );
    Kokkos::parallel_for(
        "second_pass", Kokkos::RangePolicy<ExecutionSpace>( 0, n_queries ),
        KOKKOS_LAMBDA( int i ) {
            int count = 0;
            details::TreeTraversal<NO>::query(
                bvh, queries( i ), [indices, offset, i, &count]( int index ) {
                    indices( offset( i ) + count++ ) = index;
                } );
        } );
    Kokkos::fence();
}

} // end namespace DataTransferKit

#endif
<commit_msg>Fix comment in BVH declaration to be picked up by Doxygen<commit_after>/****************************************************************************
 * Copyright (c) 2012-2017 by the DataTransferKit authors                   *
 * All rights reserved.                                                     *
 *                                                                          *
 * This file is part of the DataTransferKit library. DataTransferKit is     *
 * distributed under a BSD 3-clause license. For the licensing terms see    *
 * the LICENSE file in the top-level directory.                             *
 ****************************************************************************/

#ifndef DTK_LINEAR_BVH_DECL_HPP
#define DTK_LINEAR_BVH_DECL_HPP

#include <Kokkos_ArithTraits.hpp>
#include <Kokkos_Array.hpp>
#include <Kokkos_View.hpp>

#include <DTK_DetailsAlgorithms.hpp>
#include <DTK_DetailsBox.hpp>
#include <DTK_DetailsNode.hpp>
#include <DTK_DetailsPredicate.hpp>

#include "DTK_ConfigDefs.hpp"

namespace DataTransferKit
{
namespace Details
{
template <typename NO>
struct TreeTraversal;
}

/**
 * Bounding Volume Hierarchy.
 */
template <typename NO>
struct BVH
{
  public:
    using DeviceType = typename NO::device_type;

  public:
    BVH( Kokkos::View<Box const *, DeviceType> bounding_boxes );

    template <typename Query>
    void query( Kokkos::View<Query *, DeviceType> queries,
                Kokkos::View<int *, DeviceType> &indices,
                Kokkos::View<int *, DeviceType> &offset ) const;

  private:
    friend struct Details::TreeTraversal<NO>;

    Kokkos::View<Node *, DeviceType> _leaf_nodes;
    Kokkos::View<Node *, DeviceType> _internal_nodes;
    /**
     * Array of indices that sort the boxes used to construct the hierarchy.
     * The leaf nodes are ordered so we need these to identify objects that
     * meet a predicate.
     */
    Kokkos::View<int *, DeviceType> _indices;
};

template <typename NO>
template <typename Query>
void BVH<NO>::query( Kokkos::View<Query *, DeviceType> queries,
                     Kokkos::View<int *, DeviceType> &indices,
                     Kokkos::View<int *, DeviceType> &offset ) const
{
    using ExecutionSpace = typename DeviceType::execution_space;

    namespace details = DataTransferKit::Details;

    int const n_queries = queries.extent( 0 );

    // Initialize view
    // [ 0 0 0 .... 0 0 ]
    //                ^
    //                N
    Kokkos::resize( offset, n_queries + 1 );
    Kokkos::parallel_for(
        "query(): initialize offset (set all entries to zero)",
        Kokkos::RangePolicy<ExecutionSpace>( 0, n_queries + 1 ),
        KOKKOS_LAMBDA( int i ) { offset[i] = 0; } );
    Kokkos::fence();

    // Make a copy of *this. We need this to put is on the device. Otherwise,
    // it will throw illegal address error in the paralle_for loops below.
    BVH<NO> bvh = *this;

    // Say we found exactly two object for each query:
    // [ 2 2 2 .... 2 0 ]
    //   ^            ^
    //   0th          Nth element in the view
    Kokkos::parallel_for(
        "query(): first pass at the search count the number of indices",
        Kokkos::RangePolicy<ExecutionSpace>( 0, n_queries ),
        KOKKOS_LAMBDA( int i ) {
            offset( i ) = details::TreeTraversal<NO>::query(
                bvh, queries( i ), []( int index ) {} );
        } );
    Kokkos::fence();

    // Then we would get:
    // [ 0 2 4 .... 2N-2 2N ]
    //                    ^
    //                    N
    Kokkos::parallel_scan(
        "query(): compute offset",
        Kokkos::RangePolicy<ExecutionSpace>( 0, n_queries + 1 ),
        KOKKOS_LAMBDA( int i, int &update, bool final_pass ) {
            int const offset_i = offset( i );
            if ( final_pass )
                offset( i ) = update;
            update += offset_i;
        } );
    Kokkos::fence();

    // Let us extract the last element in the view which is the total count of
    // objects which where found to meet the query predicates:
    //
    // [ 2N ]
    auto total_count = Kokkos::subview( offset, n_queries );
    auto total_count_host = Kokkos::create_mirror_view( total_count );
    // We allocate the memory and fill
    //
    // [ A0 A1 B0 B1 C0 C1 ... X0 X1 ]
    //   ^     ^     ^         ^     ^
    //   0     2     4         2N-2  2N
    Kokkos::deep_copy( total_count_host, total_count );
    Kokkos::resize( indices, total_count( 0 ) );
    Kokkos::parallel_for(
        "second_pass", Kokkos::RangePolicy<ExecutionSpace>( 0, n_queries ),
        KOKKOS_LAMBDA( int i ) {
            int count = 0;
            details::TreeTraversal<NO>::query(
                bvh, queries( i ), [indices, offset, i, &count]( int index ) {
                    indices( offset( i ) + count++ ) = index;
                } );
        } );
    Kokkos::fence();
}

} // end namespace DataTransferKit

#endif
<|endoftext|>


<commit_before>/*************************************************************************
 *
 *  $RCSfile: interact.cxx,v $
 *
 *  $Revision: 1.7 $
 *
 *  last change: $Author: obo $ $Date: 2004-06-01 09:03:13 $
 *
 *  The Contents of this file are made available subject to the terms of
 *  either of the following licenses
 *
 *         - GNU Lesser General Public License Version 2.1
 *         - Sun Industry Standards Source License Version 1.1
 *
 *  Sun Microsystems Inc., October, 2000
 *
 *  GNU Lesser General Public License Version 2.1
 *  =============================================
 *  Copyright 2000 by Sun Microsystems, Inc.
 *  901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *  This library is free software; you can redistribute it and/or
 *  modify it under the terms of the GNU Lesser General Public
 *  License version 2.1, as published by the Free Software Foundation.
 *
 *  This library is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *  Lesser General Public License for more details.
 *
 *  You should have received a copy of the GNU Lesser General Public
 *  License along with this library; if not, write to the Free Software
 *  Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *  MA  02111-1307  USA
 *
 *
 *  Sun Industry Standards Source License Version 1.1
 *  =================================================
 *  The contents of this file are subject to the Sun Industry Standards
 *  Source License Version 1.1 (the "License"); You may not use this file
 *  except in compliance with the License. You may obtain a copy of the
 *  License at http://www.openoffice.org/license.html.
 *
 *  Software provided under this License is provided on an "AS IS" basis,
 *  WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
 *  WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
 *  MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
 *  See the License for the specific provisions governing your rights and
 *  obligations concerning the Software.
 *
 *  The Initial Developer of the Original Code is: Sun Microsystems, Inc.
 *
 *  Copyright: 2000 by Sun Microsystems, Inc.
 *
 *  All Rights Reserved.
 *
 *  Contributor(s): _______________________________________
 *
 *
 ************************************************************************/

#include "interact.hxx"

#include "com/sun/star/java/JavaDisabledException.hpp"
#include "com/sun/star/java/JavaVMCreationFailureException.hpp"
#include "com/sun/star/task/XInteractionAbort.hpp"
#include "com/sun/star/task/XInteractionRetry.hpp"
#include "com/sun/star/task/XInteractionContinuation.hpp"
#include "cppuhelper/implbase1.hxx"
#include "osl/mutex.hxx"

namespace css = com::sun::star;

using stoc_javavm::InteractionRequest;

namespace {

class AbortContinuation:
    public cppu::WeakImplHelper1< css::task::XInteractionAbort >
{
public:
    inline AbortContinuation() {}

    virtual inline void SAL_CALL select() throw (css::uno::RuntimeException) {}

private:
    AbortContinuation(AbortContinuation &); // not implemented
    void operator =(AbortContinuation); // not implemented

    virtual inline ~AbortContinuation() {}
};

}

class InteractionRequest::RetryContinuation:
    public cppu::WeakImplHelper1< css::task::XInteractionRetry >
{
public:
    inline RetryContinuation(): m_bSelected(false) {}

    virtual void SAL_CALL select() throw (css::uno::RuntimeException);

    bool isSelected() const;

private:
    RetryContinuation(RetryContinuation &); // not implemented
    void operator =(RetryContinuation); // not implemented

    virtual inline ~RetryContinuation() {}

    mutable osl::Mutex m_aMutex;
    bool m_bSelected;
};

void SAL_CALL InteractionRequest::RetryContinuation::select()
    throw (css::uno::RuntimeException)
{
    osl::MutexGuard aGuard(m_aMutex);
    m_bSelected = true;
}

bool InteractionRequest::RetryContinuation::isSelected() const
{
    osl::MutexGuard aGuard(m_aMutex);
    return m_bSelected;
}

InteractionRequest::InteractionRequest(css::uno::Any const & rRequest):
    m_aRequest(rRequest)
{
    m_aContinuations.realloc(2);
    m_xRetryContinuation = new RetryContinuation;
    m_aContinuations[0] = new AbortContinuation;
    m_aContinuations[1] = m_xRetryContinuation.get();
}

css::uno::Any SAL_CALL InteractionRequest::getRequest()
    throw (css::uno::RuntimeException)
{
    return m_aRequest;
}

css::uno::Sequence< css::uno::Reference< css::task::XInteractionContinuation > >
SAL_CALL InteractionRequest::getContinuations()
    throw (css::uno::RuntimeException)
{
    return m_aContinuations;
}

bool InteractionRequest::retry() const
{
    return m_xRetryContinuation.is() && m_xRetryContinuation->isSelected();
}

InteractionRequest::~InteractionRequest()
{}
<commit_msg>INTEGRATION: CWS ooo19126 (1.7.58); FILE MERGED 2005/09/05 17:10:54 rt 1.7.58.1: #i54170# Change license header: remove SISSL<commit_after>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: interact.cxx,v $
 *
 *  $Revision: 1.8 $
 *
 *  last change: $Author: rt $ $Date: 2005-09-08 07:58:16 $
 *
 *  The Contents of this file are made available subject to
 *  the terms of GNU Lesser General Public License Version 2.1.
 *
 *
 *    GNU Lesser General Public License Version 2.1
 *    =============================================
 *    Copyright 2005 by Sun Microsystems, Inc.
 *    901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *    This library is free software; you can redistribute it and/or
 *    modify it under the terms of the GNU Lesser General Public
 *    License version 2.1, as published by the Free Software Foundation.
 *
 *    This library is distributed in the hope that it will be useful,
 *    but WITHOUT ANY WARRANTY; without even the implied warranty of
 *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *    Lesser General Public License for more details.
 *
 *    You should have received a copy of the GNU Lesser General Public
 *    License along with this library; if not, write to the Free Software
 *    Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *    MA  02111-1307  USA
 *
 ************************************************************************/

#include "interact.hxx"

#include "com/sun/star/java/JavaDisabledException.hpp"
#include "com/sun/star/java/JavaVMCreationFailureException.hpp"
#include "com/sun/star/task/XInteractionAbort.hpp"
#include "com/sun/star/task/XInteractionRetry.hpp"
#include "com/sun/star/task/XInteractionContinuation.hpp"
#include "cppuhelper/implbase1.hxx"
#include "osl/mutex.hxx"

namespace css = com::sun::star;

using stoc_javavm::InteractionRequest;

namespace {

class AbortContinuation:
    public cppu::WeakImplHelper1< css::task::XInteractionAbort >
{
public:
    inline AbortContinuation() {}

    virtual inline void SAL_CALL select() throw (css::uno::RuntimeException) {}

private:
    AbortContinuation(AbortContinuation &); // not implemented
    void operator =(AbortContinuation); // not implemented

    virtual inline ~AbortContinuation() {}
};

}

class InteractionRequest::RetryContinuation:
    public cppu::WeakImplHelper1< css::task::XInteractionRetry >
{
public:
    inline RetryContinuation(): m_bSelected(false) {}

    virtual void SAL_CALL select() throw (css::uno::RuntimeException);

    bool isSelected() const;

private:
    RetryContinuation(RetryContinuation &); // not implemented
    void operator =(RetryContinuation); // not implemented

    virtual inline ~RetryContinuation() {}

    mutable osl::Mutex m_aMutex;
    bool m_bSelected;
};

void SAL_CALL InteractionRequest::RetryContinuation::select()
    throw (css::uno::RuntimeException)
{
    osl::MutexGuard aGuard(m_aMutex);
    m_bSelected = true;
}

bool InteractionRequest::RetryContinuation::isSelected() const
{
    osl::MutexGuard aGuard(m_aMutex);
    return m_bSelected;
}

InteractionRequest::InteractionRequest(css::uno::Any const & rRequest):
    m_aRequest(rRequest)
{
    m_aContinuations.realloc(2);
    m_xRetryContinuation = new RetryContinuation;
    m_aContinuations[0] = new AbortContinuation;
    m_aContinuations[1] = m_xRetryContinuation.get();
}

css::uno::Any SAL_CALL InteractionRequest::getRequest()
    throw (css::uno::RuntimeException)
{
    return m_aRequest;
}

css::uno::Sequence< css::uno::Reference< css::task::XInteractionContinuation > >
SAL_CALL InteractionRequest::getContinuations()
    throw (css::uno::RuntimeException)
{
    return m_aContinuations;
}

bool InteractionRequest::retry() const
{
    return m_xRetryContinuation.is() && m_xRetryContinuation->isSelected();
}

InteractionRequest::~InteractionRequest()
{}
<|endoftext|>


<commit_before>/*
	This file is part of cpp-ethereum.

	cpp-ethereum is free software: you can redistribute it and/or modify
	it under the terms of the GNU General Public License as published by
	the Free Software Foundation, either version 3 of the License, or
	(at your option) any later version.

	cpp-ethereum is distributed in the hope that it will be useful,
	but WITHOUT ANY WARRANTY; without even the implied warranty of
	MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
	GNU General Public License for more details.

	You should have received a copy of the GNU General Public License
	along with cpp-ethereum.  If not, see <http://www.gnu.org/licenses/>.
*/
/**
 * @author Christian <c@ethdev.com>
 * @author Gav Wood <g@ethdev.com>
 * @date 2014
 * Full-stack compiler that converts a source code string to bytecode.
 */

#include <boost/algorithm/string.hpp>
#include <libsolidity/AST.h>
#include <libsolidity/Scanner.h>
#include <libsolidity/Parser.h>
#include <libsolidity/GlobalContext.h>
#include <libsolidity/NameAndTypeResolver.h>
#include <libsolidity/Compiler.h>
#include <libsolidity/CompilerStack.h>
#include <libsolidity/InterfaceHandler.h>

#include <libdevcrypto/SHA3.h>

using namespace std;

namespace dev
{
namespace solidity
{

const map<string, string> StandardSources = map<string, string>{
	{"coin", R"(import "CoinReg";import "Config";import "configUser";contract coin is configUser{function coin(bytes3 name, uint denom) {CoinReg(Config(configAddr()).lookup(3)).register(name, denom);}})"},
	{"Coin", R"(contract Coin{function isApprovedFor(address _target,address _proxy)constant returns(bool _r){}function isApproved(address _proxy)constant returns(bool _r){}function sendCoinFrom(address _from,uint256 _val,address _to){}function coinBalanceOf(address _a)constant returns(uint256 _r){}function sendCoin(uint256 _val,address _to){}function coinBalance()constant returns(uint256 _r){}function approve(address _a){}})"},
	{"CoinReg", R"(contract CoinReg{function count()constant returns(uint256 r){}function info(uint256 i)constant returns(address addr,bytes3 name,uint256 denom){}function register(bytes3 name,uint256 denom){}function unregister(){}})"},
	{"configUser", R"(contract configUser{function configAddr()constant returns(address a){ return 0xc6d9d2cd449a754c494264e1809c50e34d64562b;}})"},
	{"Config", R"(contract Config{function lookup(uint256 service)constant returns(address a){}function kill(){}function unregister(uint256 id){}function register(uint256 id,address service){}})"},
	{"mortal", R"(import "owned";contract mortal is owned {function kill() { if (msg.sender == owner) suicide(owner); }})"},
	{"named", R"(import "Config";import "NameReg";import "configUser";contract named is configUser {function named(bytes32 name) {NameReg(Config(configAddr()).lookup(1)).register(name);}})"},
	{"NameReg", R"(contract NameReg{function register(bytes32 name){}function addressOf(bytes32 name)constant returns(address addr){}function unregister(){}function nameOf(address addr)constant returns(bytes32 name){}})"},
	{"owned", R"(contract owned{function owned(){owner = msg.sender;}modifier onlyowner(){if(msg.sender==owner)_}address owner;})"},
	{"service", R"(import "Config";import "configUser";contract service is configUser{function service(uint _n){Config(configAddr()).register(_n, this);}})"},
	{"std", R"(import "owned";import "mortal";import "Config";import "configUser";import "NameReg";import "named";)"}
};

CompilerStack::CompilerStack(bool _addStandardSources):
	m_addStandardSources(_addStandardSources), m_parseSuccessful(false)
{
	if (m_addStandardSources)
		addSources(StandardSources, true); // add them as libraries
}

bool CompilerStack::addSource(string const& _name, string const& _content, bool _isLibrary)
{
	bool existed = m_sources.count(_name) != 0;
	reset(true);
	m_sources[_name].scanner = make_shared<Scanner>(CharStream(_content), _name);
	m_sources[_name].isLibrary = _isLibrary;
	return existed;
}

void CompilerStack::setSource(string const& _sourceCode)
{
	reset();
	addSource("", _sourceCode);
}

void CompilerStack::parse()
{
	for (auto& sourcePair: m_sources)
	{
		sourcePair.second.scanner->reset();
		sourcePair.second.ast = Parser().parse(sourcePair.second.scanner);
	}
	resolveImports();

	m_globalContext = make_shared<GlobalContext>();
	NameAndTypeResolver resolver(m_globalContext->getDeclarations());
	for (Source const* source: m_sourceOrder)
		resolver.registerDeclarations(*source->ast);
	for (Source const* source: m_sourceOrder)
		for (ASTPointer<ASTNode> const& node: source->ast->getNodes())
			if (ContractDefinition* contract = dynamic_cast<ContractDefinition*>(node.get()))
			{
				m_globalContext->setCurrentContract(*contract);
				resolver.updateDeclaration(*m_globalContext->getCurrentThis());
				resolver.updateDeclaration(*m_globalContext->getCurrentSuper());
				resolver.resolveNamesAndTypes(*contract);
				m_contracts[contract->getName()].contract = contract;
			}
	for (Source const* source: m_sourceOrder)
		for (ASTPointer<ASTNode> const& node: source->ast->getNodes())
			if (ContractDefinition* contract = dynamic_cast<ContractDefinition*>(node.get()))
			{
				m_globalContext->setCurrentContract(*contract);
				resolver.updateDeclaration(*m_globalContext->getCurrentThis());
				resolver.checkTypeRequirements(*contract);
				m_contracts[contract->getName()].contract = contract;
			}
	m_parseSuccessful = true;
}

void CompilerStack::parse(string const& _sourceCode)
{
	setSource(_sourceCode);
	parse();
}

vector<string> CompilerStack::getContractNames() const
{
	if (!m_parseSuccessful)
		BOOST_THROW_EXCEPTION(CompilerError() << errinfo_comment("Parsing was not successful."));
	vector<string> contractNames;
	for (auto const& contract: m_contracts)
		contractNames.push_back(contract.first);
	return contractNames;
}

void CompilerStack::compile(bool _optimize)
{
	if (!m_parseSuccessful)
		parse();

	map<ContractDefinition const*, bytes const*> contractBytecode;
	for (Source const* source: m_sourceOrder)
		for (ASTPointer<ASTNode> const& node: source->ast->getNodes())
			if (ContractDefinition* contract = dynamic_cast<ContractDefinition*>(node.get()))
			{
				if (!contract->isFullyImplemented())
					continue;
				shared_ptr<Compiler> compiler = make_shared<Compiler>(_optimize);
				compiler->compileContract(*contract, contractBytecode);
				Contract& compiledContract = m_contracts[contract->getName()];
				compiledContract.bytecode = compiler->getAssembledBytecode();
				compiledContract.runtimeBytecode = compiler->getRuntimeBytecode();
				compiledContract.compiler = move(compiler);
				contractBytecode[compiledContract.contract] = &compiledContract.bytecode;
			}
}

bytes const& CompilerStack::compile(string const& _sourceCode, bool _optimize)
{
	parse(_sourceCode);
	compile(_optimize);
	return getBytecode();
}

eth::AssemblyItems const* CompilerStack::getAssemblyItems(string const& _contractName) const
{
	Contract const& contract = getContract(_contractName);
	return contract.compiler ? &getContract(_contractName).compiler->getAssemblyItems() : nullptr;
}

eth::AssemblyItems const* CompilerStack::getRuntimeAssemblyItems(string const& _contractName) const
{
	Contract const& contract = getContract(_contractName);
	return contract.compiler ? &getContract(_contractName).compiler->getRuntimeAssemblyItems() : nullptr;
}

bytes const& CompilerStack::getBytecode(string const& _contractName) const
{
	return getContract(_contractName).bytecode;
}

bytes const& CompilerStack::getRuntimeBytecode(string const& _contractName) const
{
	return getContract(_contractName).runtimeBytecode;
}

dev::h256 CompilerStack::getContractCodeHash(string const& _contractName) const
{
	return dev::sha3(getRuntimeBytecode(_contractName));
}

void CompilerStack::streamAssembly(ostream& _outStream, string const& _contractName, StringMap _sourceCodes, bool _inJsonFormat) const
{
	Contract const& contract = getContract(_contractName);
	if (contract.compiler)
		contract(_contractName).compiler->streamAssembly(_outStream, _sourceCodes, _inJsonFormat);
	else
		_outStream << "Contract not fully implemented" << endl;
}

string const& CompilerStack::getInterface(string const& _contractName) const
{
	return getMetadata(_contractName, DocumentationType::ABIInterface);
}

string const& CompilerStack::getSolidityInterface(string const& _contractName) const
{
	return getMetadata(_contractName, DocumentationType::ABISolidityInterface);
}

string const& CompilerStack::getMetadata(string const& _contractName, DocumentationType _type) const
{
	if (!m_parseSuccessful)
		BOOST_THROW_EXCEPTION(CompilerError() << errinfo_comment("Parsing was not successful."));

	Contract const& contract = getContract(_contractName);

	std::unique_ptr<string const>* doc;
	switch (_type)
	{
	case DocumentationType::NatspecUser:
		doc = &contract.userDocumentation;
		break;
	case DocumentationType::NatspecDev:
		doc = &contract.devDocumentation;
		break;
	case DocumentationType::ABIInterface:
		doc = &contract.interface;
		break;
	case DocumentationType::ABISolidityInterface:
		doc = &contract.solidityInterface;
		break;
	default:
		BOOST_THROW_EXCEPTION(InternalCompilerError() << errinfo_comment("Illegal documentation type."));
	}
	if (!*doc)
		*doc = contract.interfaceHandler->getDocumentation(*contract.contract, _type);
	return *(*doc);
}

Scanner const& CompilerStack::getScanner(string const& _sourceName) const
{
	return *getSource(_sourceName).scanner;
}

SourceUnit const& CompilerStack::getAST(string const& _sourceName) const
{
	return *getSource(_sourceName).ast;
}

ContractDefinition const& CompilerStack::getContractDefinition(string const& _contractName) const
{
	return *getContract(_contractName).contract;
}

bytes CompilerStack::staticCompile(std::string const& _sourceCode, bool _optimize)
{
	CompilerStack stack;
	return stack.compile(_sourceCode, _optimize);
}

void CompilerStack::reset(bool _keepSources)
{
	m_parseSuccessful = false;
	if (_keepSources)
		for (auto sourcePair: m_sources)
			sourcePair.second.reset();
	else
	{
		m_sources.clear();
		if (m_addStandardSources)
			addSources(StandardSources);
	}
	m_globalContext.reset();
	m_sourceOrder.clear();
	m_contracts.clear();
}

void CompilerStack::resolveImports()
{
	// topological sorting (depth first search) of the import graph, cutting potential cycles
	vector<Source const*> sourceOrder;
	set<Source const*> sourcesSeen;

	function<void(Source const*)> toposort = [&](Source const* _source)
	{
		if (sourcesSeen.count(_source))
			return;
		sourcesSeen.insert(_source);
		for (ASTPointer<ASTNode> const& node: _source->ast->getNodes())
			if (ImportDirective const* import = dynamic_cast<ImportDirective*>(node.get()))
			{
				string const& id = import->getIdentifier();
				if (!m_sources.count(id))
					BOOST_THROW_EXCEPTION(ParserError()
										  << errinfo_sourceLocation(import->getLocation())
										  << errinfo_comment("Source not found."));
				toposort(&m_sources[id]);
			}
		sourceOrder.push_back(_source);
	};

	for (auto const& sourcePair: m_sources)
		if (!sourcePair.second.isLibrary)
			toposort(&sourcePair.second);

	swap(m_sourceOrder, sourceOrder);
}

std::string CompilerStack::defaultContractName() const
{
	return getContract("").contract->getName();
}

CompilerStack::Contract const& CompilerStack::getContract(string const& _contractName) const
{
	if (m_contracts.empty())
		BOOST_THROW_EXCEPTION(CompilerError() << errinfo_comment("No compiled contracts found."));
	string contractName = _contractName;
	if (_contractName.empty())
		// try to find some user-supplied contract
		for (auto const& it: m_sources)
			if (!StandardSources.count(it.first))
				for (ASTPointer<ASTNode> const& node: it.second.ast->getNodes())
					if (auto contract = dynamic_cast<ContractDefinition const*>(node.get()))
						contractName = contract->getName();
	auto it = m_contracts.find(contractName);
	if (it == m_contracts.end())
		BOOST_THROW_EXCEPTION(CompilerError() << errinfo_comment("Contract " + _contractName + " not found."));
	return it->second;
}

CompilerStack::Source const& CompilerStack::getSource(string const& _sourceName) const
{
	auto it = m_sources.find(_sourceName);
	if (it == m_sources.end())
		BOOST_THROW_EXCEPTION(CompilerError() << errinfo_comment("Given source file not found."));
	return it->second;
}

CompilerStack::Contract::Contract(): interfaceHandler(make_shared<InterfaceHandler>()) {}

}
}
<commit_msg>removed unused parameter from streamAsmJson<commit_after>/*
	This file is part of cpp-ethereum.

	cpp-ethereum is free software: you can redistribute it and/or modify
	it under the terms of the GNU General Public License as published by
	the Free Software Foundation, either version 3 of the License, or
	(at your option) any later version.

	cpp-ethereum is distributed in the hope that it will be useful,
	but WITHOUT ANY WARRANTY; without even the implied warranty of
	MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
	GNU General Public License for more details.

	You should have received a copy of the GNU General Public License
	along with cpp-ethereum.  If not, see <http://www.gnu.org/licenses/>.
*/
/**
 * @author Christian <c@ethdev.com>
 * @author Gav Wood <g@ethdev.com>
 * @date 2014
 * Full-stack compiler that converts a source code string to bytecode.
 */

#include <boost/algorithm/string.hpp>
#include <libsolidity/AST.h>
#include <libsolidity/Scanner.h>
#include <libsolidity/Parser.h>
#include <libsolidity/GlobalContext.h>
#include <libsolidity/NameAndTypeResolver.h>
#include <libsolidity/Compiler.h>
#include <libsolidity/CompilerStack.h>
#include <libsolidity/InterfaceHandler.h>

#include <libdevcrypto/SHA3.h>

using namespace std;

namespace dev
{
namespace solidity
{

const map<string, string> StandardSources = map<string, string>{
	{"coin", R"(import "CoinReg";import "Config";import "configUser";contract coin is configUser{function coin(bytes3 name, uint denom) {CoinReg(Config(configAddr()).lookup(3)).register(name, denom);}})"},
	{"Coin", R"(contract Coin{function isApprovedFor(address _target,address _proxy)constant returns(bool _r){}function isApproved(address _proxy)constant returns(bool _r){}function sendCoinFrom(address _from,uint256 _val,address _to){}function coinBalanceOf(address _a)constant returns(uint256 _r){}function sendCoin(uint256 _val,address _to){}function coinBalance()constant returns(uint256 _r){}function approve(address _a){}})"},
	{"CoinReg", R"(contract CoinReg{function count()constant returns(uint256 r){}function info(uint256 i)constant returns(address addr,bytes3 name,uint256 denom){}function register(bytes3 name,uint256 denom){}function unregister(){}})"},
	{"configUser", R"(contract configUser{function configAddr()constant returns(address a){ return 0xc6d9d2cd449a754c494264e1809c50e34d64562b;}})"},
	{"Config", R"(contract Config{function lookup(uint256 service)constant returns(address a){}function kill(){}function unregister(uint256 id){}function register(uint256 id,address service){}})"},
	{"mortal", R"(import "owned";contract mortal is owned {function kill() { if (msg.sender == owner) suicide(owner); }})"},
	{"named", R"(import "Config";import "NameReg";import "configUser";contract named is configUser {function named(bytes32 name) {NameReg(Config(configAddr()).lookup(1)).register(name);}})"},
	{"NameReg", R"(contract NameReg{function register(bytes32 name){}function addressOf(bytes32 name)constant returns(address addr){}function unregister(){}function nameOf(address addr)constant returns(bytes32 name){}})"},
	{"owned", R"(contract owned{function owned(){owner = msg.sender;}modifier onlyowner(){if(msg.sender==owner)_}address owner;})"},
	{"service", R"(import "Config";import "configUser";contract service is configUser{function service(uint _n){Config(configAddr()).register(_n, this);}})"},
	{"std", R"(import "owned";import "mortal";import "Config";import "configUser";import "NameReg";import "named";)"}
};

CompilerStack::CompilerStack(bool _addStandardSources):
	m_addStandardSources(_addStandardSources), m_parseSuccessful(false)
{
	if (m_addStandardSources)
		addSources(StandardSources, true); // add them as libraries
}

bool CompilerStack::addSource(string const& _name, string const& _content, bool _isLibrary)
{
	bool existed = m_sources.count(_name) != 0;
	reset(true);
	m_sources[_name].scanner = make_shared<Scanner>(CharStream(_content), _name);
	m_sources[_name].isLibrary = _isLibrary;
	return existed;
}

void CompilerStack::setSource(string const& _sourceCode)
{
	reset();
	addSource("", _sourceCode);
}

void CompilerStack::parse()
{
	for (auto& sourcePair: m_sources)
	{
		sourcePair.second.scanner->reset();
		sourcePair.second.ast = Parser().parse(sourcePair.second.scanner);
	}
	resolveImports();

	m_globalContext = make_shared<GlobalContext>();
	NameAndTypeResolver resolver(m_globalContext->getDeclarations());
	for (Source const* source: m_sourceOrder)
		resolver.registerDeclarations(*source->ast);
	for (Source const* source: m_sourceOrder)
		for (ASTPointer<ASTNode> const& node: source->ast->getNodes())
			if (ContractDefinition* contract = dynamic_cast<ContractDefinition*>(node.get()))
			{
				m_globalContext->setCurrentContract(*contract);
				resolver.updateDeclaration(*m_globalContext->getCurrentThis());
				resolver.updateDeclaration(*m_globalContext->getCurrentSuper());
				resolver.resolveNamesAndTypes(*contract);
				m_contracts[contract->getName()].contract = contract;
			}
	for (Source const* source: m_sourceOrder)
		for (ASTPointer<ASTNode> const& node: source->ast->getNodes())
			if (ContractDefinition* contract = dynamic_cast<ContractDefinition*>(node.get()))
			{
				m_globalContext->setCurrentContract(*contract);
				resolver.updateDeclaration(*m_globalContext->getCurrentThis());
				resolver.checkTypeRequirements(*contract);
				m_contracts[contract->getName()].contract = contract;
			}
	m_parseSuccessful = true;
}

void CompilerStack::parse(string const& _sourceCode)
{
	setSource(_sourceCode);
	parse();
}

vector<string> CompilerStack::getContractNames() const
{
	if (!m_parseSuccessful)
		BOOST_THROW_EXCEPTION(CompilerError() << errinfo_comment("Parsing was not successful."));
	vector<string> contractNames;
	for (auto const& contract: m_contracts)
		contractNames.push_back(contract.first);
	return contractNames;
}

void CompilerStack::compile(bool _optimize)
{
	if (!m_parseSuccessful)
		parse();

	map<ContractDefinition const*, bytes const*> contractBytecode;
	for (Source const* source: m_sourceOrder)
		for (ASTPointer<ASTNode> const& node: source->ast->getNodes())
			if (ContractDefinition* contract = dynamic_cast<ContractDefinition*>(node.get()))
			{
				if (!contract->isFullyImplemented())
					continue;
				shared_ptr<Compiler> compiler = make_shared<Compiler>(_optimize);
				compiler->compileContract(*contract, contractBytecode);
				Contract& compiledContract = m_contracts[contract->getName()];
				compiledContract.bytecode = compiler->getAssembledBytecode();
				compiledContract.runtimeBytecode = compiler->getRuntimeBytecode();
				compiledContract.compiler = move(compiler);
				contractBytecode[compiledContract.contract] = &compiledContract.bytecode;
			}
}

bytes const& CompilerStack::compile(string const& _sourceCode, bool _optimize)
{
	parse(_sourceCode);
	compile(_optimize);
	return getBytecode();
}

eth::AssemblyItems const* CompilerStack::getAssemblyItems(string const& _contractName) const
{
	Contract const& contract = getContract(_contractName);
	return contract.compiler ? &getContract(_contractName).compiler->getAssemblyItems() : nullptr;
}

eth::AssemblyItems const* CompilerStack::getRuntimeAssemblyItems(string const& _contractName) const
{
	Contract const& contract = getContract(_contractName);
	return contract.compiler ? &getContract(_contractName).compiler->getRuntimeAssemblyItems() : nullptr;
}

bytes const& CompilerStack::getBytecode(string const& _contractName) const
{
	return getContract(_contractName).bytecode;
}

bytes const& CompilerStack::getRuntimeBytecode(string const& _contractName) const
{
	return getContract(_contractName).runtimeBytecode;
}

dev::h256 CompilerStack::getContractCodeHash(string const& _contractName) const
{
	return dev::sha3(getRuntimeBytecode(_contractName));
}

void CompilerStack::streamAssembly(ostream& _outStream, string const& _contractName, StringMap _sourceCodes, bool _inJsonFormat) const
{
	Contract const& contract = getContract(_contractName);
	if (contract.compiler)
		contract.compiler->streamAssembly(_outStream, _sourceCodes, _inJsonFormat);
	else
		_outStream << "Contract not fully implemented" << endl;
}

string const& CompilerStack::getInterface(string const& _contractName) const
{
	return getMetadata(_contractName, DocumentationType::ABIInterface);
}

string const& CompilerStack::getSolidityInterface(string const& _contractName) const
{
	return getMetadata(_contractName, DocumentationType::ABISolidityInterface);
}

string const& CompilerStack::getMetadata(string const& _contractName, DocumentationType _type) const
{
	if (!m_parseSuccessful)
		BOOST_THROW_EXCEPTION(CompilerError() << errinfo_comment("Parsing was not successful."));

	Contract const& contract = getContract(_contractName);

	std::unique_ptr<string const>* doc;
	switch (_type)
	{
	case DocumentationType::NatspecUser:
		doc = &contract.userDocumentation;
		break;
	case DocumentationType::NatspecDev:
		doc = &contract.devDocumentation;
		break;
	case DocumentationType::ABIInterface:
		doc = &contract.interface;
		break;
	case DocumentationType::ABISolidityInterface:
		doc = &contract.solidityInterface;
		break;
	default:
		BOOST_THROW_EXCEPTION(InternalCompilerError() << errinfo_comment("Illegal documentation type."));
	}
	if (!*doc)
		*doc = contract.interfaceHandler->getDocumentation(*contract.contract, _type);
	return *(*doc);
}

Scanner const& CompilerStack::getScanner(string const& _sourceName) const
{
	return *getSource(_sourceName).scanner;
}

SourceUnit const& CompilerStack::getAST(string const& _sourceName) const
{
	return *getSource(_sourceName).ast;
}

ContractDefinition const& CompilerStack::getContractDefinition(string const& _contractName) const
{
	return *getContract(_contractName).contract;
}

bytes CompilerStack::staticCompile(std::string const& _sourceCode, bool _optimize)
{
	CompilerStack stack;
	return stack.compile(_sourceCode, _optimize);
}

void CompilerStack::reset(bool _keepSources)
{
	m_parseSuccessful = false;
	if (_keepSources)
		for (auto sourcePair: m_sources)
			sourcePair.second.reset();
	else
	{
		m_sources.clear();
		if (m_addStandardSources)
			addSources(StandardSources);
	}
	m_globalContext.reset();
	m_sourceOrder.clear();
	m_contracts.clear();
}

void CompilerStack::resolveImports()
{
	// topological sorting (depth first search) of the import graph, cutting potential cycles
	vector<Source const*> sourceOrder;
	set<Source const*> sourcesSeen;

	function<void(Source const*)> toposort = [&](Source const* _source)
	{
		if (sourcesSeen.count(_source))
			return;
		sourcesSeen.insert(_source);
		for (ASTPointer<ASTNode> const& node: _source->ast->getNodes())
			if (ImportDirective const* import = dynamic_cast<ImportDirective*>(node.get()))
			{
				string const& id = import->getIdentifier();
				if (!m_sources.count(id))
					BOOST_THROW_EXCEPTION(ParserError()
										  << errinfo_sourceLocation(import->getLocation())
										  << errinfo_comment("Source not found."));
				toposort(&m_sources[id]);
			}
		sourceOrder.push_back(_source);
	};

	for (auto const& sourcePair: m_sources)
		if (!sourcePair.second.isLibrary)
			toposort(&sourcePair.second);

	swap(m_sourceOrder, sourceOrder);
}

std::string CompilerStack::defaultContractName() const
{
	return getContract("").contract->getName();
}

CompilerStack::Contract const& CompilerStack::getContract(string const& _contractName) const
{
	if (m_contracts.empty())
		BOOST_THROW_EXCEPTION(CompilerError() << errinfo_comment("No compiled contracts found."));
	string contractName = _contractName;
	if (_contractName.empty())
		// try to find some user-supplied contract
		for (auto const& it: m_sources)
			if (!StandardSources.count(it.first))
				for (ASTPointer<ASTNode> const& node: it.second.ast->getNodes())
					if (auto contract = dynamic_cast<ContractDefinition const*>(node.get()))
						contractName = contract->getName();
	auto it = m_contracts.find(contractName);
	if (it == m_contracts.end())
		BOOST_THROW_EXCEPTION(CompilerError() << errinfo_comment("Contract " + _contractName + " not found."));
	return it->second;
}

CompilerStack::Source const& CompilerStack::getSource(string const& _sourceName) const
{
	auto it = m_sources.find(_sourceName);
	if (it == m_sources.end())
		BOOST_THROW_EXCEPTION(CompilerError() << errinfo_comment("Given source file not found."));
	return it->second;
}

CompilerStack::Contract::Contract(): interfaceHandler(make_shared<InterfaceHandler>()) {}

}
}
<|endoftext|>


<commit_before>/*
 *  CompoundAgent.cpp
 *  openc2e
 *
 *  Created by Alyssa Milburn on Tue May 25 2004.
 *  Copyright (c) 2004 Alyssa Milburn. 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 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.
 *
 */

#include "CompoundAgent.h"
#include "openc2e.h"
#include "c16Image.h"
#include <algorithm> // sort

void CompoundAgent::render(SDLBackend *renderer, int xoffset, int yoffset) {
	// todo: we're ignoring zorder here..
	for (std::vector<CompoundPart *>::iterator i = parts.begin(); i != parts.end(); i++) {
		(*i)->render(renderer, xoffset + (int)x, yoffset + (int)y);
	}

	if (displaycore) {
		// draw core
		int xoff = xoffset + x;
		int yoff = yoffset + y;
		renderer->renderLine(xoff + (getWidth() / 2), yoff, xoff + getWidth(), yoff + (getHeight() / 2), 0xFF0000CC);
		renderer->renderLine(xoff + getWidth(), yoff + (getHeight() / 2), xoff + (getWidth() / 2), yoff + getHeight(), 0xFF0000CC);
		renderer->renderLine(xoff + (getWidth() / 2), yoff + getHeight(), xoff, yoff + (getHeight() / 2), 0xFF0000CC);
		renderer->renderLine(xoff, yoff + (getHeight() / 2), xoff + (getWidth() / 2), yoff, 0xFF0000CC);
	}
}

void CompoundAgent::addPart(CompoundPart *p) {
	assert(!part(p->id)); // todo: handle better

	// todo: we should prbly insert at the right place, not call sort
	parts.push_back(p);
	std::sort(parts.begin(), parts.end());
}

void CompoundAgent::delPart(unsigned int id) {
	for (std::vector<CompoundPart *>::iterator x = parts.begin(); x != parts.end(); x++) {
		if ((*x)->id == id) { delete *x; parts.erase(x); return; }
	}

	throw "oops"; // TODO: handle this exception properly
}

CompoundPart *CompoundAgent::part(unsigned int id) {
	for (std::vector<CompoundPart *>::iterator x = parts.begin(); x != parts.end(); x++) {
		if ((*x)->id == id) return *x;
	}
	return 0;
}

void CompoundPart::render(SDLBackend *renderer, int xoffset, int yoffset) {
	renderer->render(getSprite(), getCurrentSprite(), xoffset + x, yoffset + y);
}

CompoundAgent::CompoundAgent(unsigned char _family, unsigned char _genus, unsigned short _species, unsigned int plane,
				std::string spritefile, unsigned int firstimage, unsigned int imagecount) :
				Agent(_family, _genus, _species, plane), width(0), height(0) {
	// TODO: we ignore image count acos it sucks
	CompoundPart *p = new DullPart(0, spritefile, firstimage, 0, 0, 0);
	addPart(p);
	width = p->getWidth();
	height = p->getHeight();
}

CompoundAgent::~CompoundAgent() {
	for (std::vector<CompoundPart *>::iterator x = parts.begin(); x != parts.end(); x++) {
		delete *x;
	}
}

CompoundPart::CompoundPart(unsigned int _id, std::string spritefile, unsigned int fimg,
						unsigned int _x, unsigned int _y, unsigned int _z) {
	id = _id;
	firstimg = fimg;
	x = _x;
	y = _y;
	zorder = _z;
	sprite = gallery.getImage(spritefile);
	caos_assert(sprite);
	pose = 0;
}

DullPart::DullPart(unsigned int _id, std::string spritefile, unsigned int fimg, unsigned int _x, unsigned int _y,
			 unsigned int _z) : CompoundPart(_id, spritefile, fimg, _x, _y, _z) {
}

ButtonPart::ButtonPart(unsigned int _id, std::string spritefile, unsigned int fimg, unsigned int _x, unsigned int _y,
						   unsigned int _z, const bytestring &animhover, int msgid, int option) : CompoundPart(_id, spritefile, fimg, _x, _y, _z) {
	// TODO: store animhover, msgid and option
}

FixedTextPart::FixedTextPart(unsigned int _id, std::string spritefile, unsigned int fimg, unsigned int _x, unsigned int _y,
		                                  unsigned int _z, std::string fontsprite) : TextPart(_id, spritefile, fimg, _x, _y, _z) {
	// TODO: load fontsprite
}

TextEntryPart::TextEntryPart(unsigned int _id, std::string spritefile, unsigned int fimg, unsigned int _x, unsigned int _y,
		                                  unsigned int _z, unsigned int msgid, std::string fontsprite) : TextPart(_id, spritefile, fimg, _x, _y, _z) {
	// TODO: load fontsprite, msgid
}

// TODO: combine identical code from SimpleAgent/CompoundAgent
// TODO: implement set/getAttributes for Vehicle/Creature(?)
void CompoundAgent::setAttributes(unsigned int attr) {
	carryable = (attr & 1);
	mouseable = (attr & 2);
	activateable = (attr & 4);
	invisible = (attr & 16);
	floatable = (attr & 32);
	suffercollisions = (attr & 64);
	sufferphysics = (attr & 128);
	camerashy = (attr & 256);
	rotatable = (attr & 1024);
	presence = (attr & 2048);
}

unsigned int CompoundAgent::getAttributes() {
	unsigned int a = (carryable ? 1 : 0);
	a += (mouseable ? 2: 0);
	a += (activateable ? 4: 0);
	a += (invisible ? 16: 0);
	a += (floatable ? 32: 0);
	a += (suffercollisions ? 64: 0);
	a += (sufferphysics ? 128: 0);
	a += (camerashy ? 256: 0);
	a += (rotatable ? 1024: 0);
	return a + (presence ? 2048: 0);
}

void CompoundAgent::tick() {
	Agent::tick();

	for (std::vector<CompoundPart *>::iterator x = parts.begin(); x != parts.end(); x++) {
		(*x)->tick();
	}
}

void CompoundPart::tick() {
	if (!animation.empty()) {
		unsigned int f = frameno + 1;
		if (f == animation.size()) return;
		if (animation[f] == 255) {
			if (f == (animation.size() - 1)) f = 0;
			else f = animation[f + 1];
		}
		setFrameNo(f);
	}
}

/* vim: set noet: */
<commit_msg>whoops, CompoundAgent should start with null ATTR<commit_after>/*
 *  CompoundAgent.cpp
 *  openc2e
 *
 *  Created by Alyssa Milburn on Tue May 25 2004.
 *  Copyright (c) 2004 Alyssa Milburn. 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 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.
 *
 */

#include "CompoundAgent.h"
#include "openc2e.h"
#include "c16Image.h"
#include <algorithm> // sort

void CompoundAgent::render(SDLBackend *renderer, int xoffset, int yoffset) {
	// todo: we're ignoring zorder here..
	for (std::vector<CompoundPart *>::iterator i = parts.begin(); i != parts.end(); i++) {
		(*i)->render(renderer, xoffset + (int)x, yoffset + (int)y);
	}

	if (displaycore) {
		// draw core
		int xoff = xoffset + x;
		int yoff = yoffset + y;
		renderer->renderLine(xoff + (getWidth() / 2), yoff, xoff + getWidth(), yoff + (getHeight() / 2), 0xFF0000CC);
		renderer->renderLine(xoff + getWidth(), yoff + (getHeight() / 2), xoff + (getWidth() / 2), yoff + getHeight(), 0xFF0000CC);
		renderer->renderLine(xoff + (getWidth() / 2), yoff + getHeight(), xoff, yoff + (getHeight() / 2), 0xFF0000CC);
		renderer->renderLine(xoff, yoff + (getHeight() / 2), xoff + (getWidth() / 2), yoff, 0xFF0000CC);
	}
}

void CompoundAgent::addPart(CompoundPart *p) {
	assert(!part(p->id)); // todo: handle better

	// todo: we should prbly insert at the right place, not call sort
	parts.push_back(p);
	std::sort(parts.begin(), parts.end());
}

void CompoundAgent::delPart(unsigned int id) {
	for (std::vector<CompoundPart *>::iterator x = parts.begin(); x != parts.end(); x++) {
		if ((*x)->id == id) { delete *x; parts.erase(x); return; }
	}

	throw "oops"; // TODO: handle this exception properly
}

CompoundPart *CompoundAgent::part(unsigned int id) {
	for (std::vector<CompoundPart *>::iterator x = parts.begin(); x != parts.end(); x++) {
		if ((*x)->id == id) return *x;
	}
	return 0;
}

void CompoundPart::render(SDLBackend *renderer, int xoffset, int yoffset) {
	renderer->render(getSprite(), getCurrentSprite(), xoffset + x, yoffset + y);
}

CompoundAgent::CompoundAgent(unsigned char _family, unsigned char _genus, unsigned short _species, unsigned int plane,
				std::string spritefile, unsigned int firstimage, unsigned int imagecount) :
				Agent(_family, _genus, _species, plane), width(0), height(0) {
	setAttributes(0);
	// TODO: we ignore image count acos it sucks
	CompoundPart *p = new DullPart(0, spritefile, firstimage, 0, 0, 0);
	addPart(p);
	width = p->getWidth();
	height = p->getHeight();
}

CompoundAgent::~CompoundAgent() {
	for (std::vector<CompoundPart *>::iterator x = parts.begin(); x != parts.end(); x++) {
		delete *x;
	}
}

CompoundPart::CompoundPart(unsigned int _id, std::string spritefile, unsigned int fimg,
						unsigned int _x, unsigned int _y, unsigned int _z) {
	id = _id;
	firstimg = fimg;
	x = _x;
	y = _y;
	zorder = _z;
	sprite = gallery.getImage(spritefile);
	caos_assert(sprite);
	pose = 0;
}

DullPart::DullPart(unsigned int _id, std::string spritefile, unsigned int fimg, unsigned int _x, unsigned int _y,
			 unsigned int _z) : CompoundPart(_id, spritefile, fimg, _x, _y, _z) {
}

ButtonPart::ButtonPart(unsigned int _id, std::string spritefile, unsigned int fimg, unsigned int _x, unsigned int _y,
						   unsigned int _z, const bytestring &animhover, int msgid, int option) : CompoundPart(_id, spritefile, fimg, _x, _y, _z) {
	// TODO: store animhover, msgid and option
}

FixedTextPart::FixedTextPart(unsigned int _id, std::string spritefile, unsigned int fimg, unsigned int _x, unsigned int _y,
		                                  unsigned int _z, std::string fontsprite) : TextPart(_id, spritefile, fimg, _x, _y, _z) {
	// TODO: load fontsprite
}

TextEntryPart::TextEntryPart(unsigned int _id, std::string spritefile, unsigned int fimg, unsigned int _x, unsigned int _y,
		                                  unsigned int _z, unsigned int msgid, std::string fontsprite) : TextPart(_id, spritefile, fimg, _x, _y, _z) {
	// TODO: load fontsprite, msgid
}

// TODO: combine identical code from SimpleAgent/CompoundAgent
// TODO: implement set/getAttributes for Vehicle/Creature(?)
void CompoundAgent::setAttributes(unsigned int attr) {
	carryable = (attr & 1);
	mouseable = (attr & 2);
	activateable = (attr & 4);
	invisible = (attr & 16);
	floatable = (attr & 32);
	suffercollisions = (attr & 64);
	sufferphysics = (attr & 128);
	camerashy = (attr & 256);
	rotatable = (attr & 1024);
	presence = (attr & 2048);
}

unsigned int CompoundAgent::getAttributes() {
	unsigned int a = (carryable ? 1 : 0);
	a += (mouseable ? 2: 0);
	a += (activateable ? 4: 0);
	a += (invisible ? 16: 0);
	a += (floatable ? 32: 0);
	a += (suffercollisions ? 64: 0);
	a += (sufferphysics ? 128: 0);
	a += (camerashy ? 256: 0);
	a += (rotatable ? 1024: 0);
	return a + (presence ? 2048: 0);
}

void CompoundAgent::tick() {
	Agent::tick();

	for (std::vector<CompoundPart *>::iterator x = parts.begin(); x != parts.end(); x++) {
		(*x)->tick();
	}
}

void CompoundPart::tick() {
	if (!animation.empty()) {
		unsigned int f = frameno + 1;
		if (f == animation.size()) return;
		if (animation[f] == 255) {
			if (f == (animation.size() - 1)) f = 0;
			else f = animation[f + 1];
		}
		setFrameNo(f);
	}
}

/* vim: set noet: */
<|endoftext|>