<commit_before>/*******************************************************************************

Licensed to the OpenCOR team under one or more contributor license agreements.
See the NOTICE.txt file distributed with this work for additional information
regarding copyright ownership. The OpenCOR team licenses this file to you under
the Apache License, Version 2.0 (the "License"); you may not use this file
except in compliance with the License. You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software distributed
under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
CONDITIONS OF ANY KIND, either express or implied. See the License for the
specific language governing permissions and limitations under the License.

*******************************************************************************/

//==============================================================================
// GUI utilities
//==============================================================================

#include "corecliutils.h"
#include "commonwidget.h"
#include "coresettings.h"
#include "coreguiutils.h"
#include "settings.h"

//==============================================================================

#include <Qt>

//==============================================================================

#include <QAction>
#include <QApplication>
#include <QBuffer>
#include <QColor>
#include <QDate>
#include <QFileDialog>
#include <QFileInfo>
#include <QFont>
#include <QFrame>
#include <QIODevice>
#include <QLabel>
#include <QMenu>
#include <QMessageBox>
#include <QPalette>
#include <QSettings>
#include <QSizePolicy>
#include <QStackedWidget>

//==============================================================================

namespace OpenCOR {
namespace Core {

//==============================================================================

#include "coreguiutils.cpp.inl"

//==============================================================================

QString allFilters(const QString &pFilters)
{
    return  QObject::tr("All Files")
           +" (*"
#ifdef Q_OS_WIN
           +".*"
#endif
           +")"
           +(pFilters.isEmpty()?QString():";;"+pFilters);
}

//==============================================================================

QString getOpenFileName(const QString &pCaption, const QString &pFilters)
{
    // Retrieve and return one open file name

    QString res = QFileDialog::getOpenFileName(qApp->activeWindow(),
                                               pCaption, activeDirectory(),
                                               allFilters(pFilters));

    if (res.size())
        // We have retrieved a file name, so keep track of the folder in which
        // it is

        setActiveDirectory(QFileInfo(res).path());

    // Return the file name

    return res;
}

//==============================================================================

QStringList getOpenFileNames(const QString &pCaption, const QString &pFilters)
{
    // Retrieve and return one or several open file names

    QStringList res = QFileDialog::getOpenFileNames(qApp->activeWindow(),
                                                    pCaption, activeDirectory(),
                                                    allFilters(pFilters));

    if (res.count())
        // We have retrieved at least one file name, so keep track of the folder
        // in which it is
        // Note #1: we use the last open file name to determine the folder that
        //          is to be remembered since on Windows 7, at least, it's
        //          possible to search for files from within the file dialog
        //          box, and the last file name should be the one we are most
        //          'interested' in...
        // Note #2: this doesn't, unfortunately, address the case where the user
        //          goes to a directory and then closes the file dialog box
        //          without selecting any open file name. There might be a way
        //          to get it to work, but that would involve using the exec()
        //          method rather than the static getOpenFilesNames() method,
        //          which would result in a non-native looking file dialog box
        //          (on Windows 7 at least), so it's not an option
        //          unfortunately...

        setActiveDirectory(QFileInfo(res[res.count()-1]).path());

    // Return the file name(s)

    return res;
}

//==============================================================================

QString getSaveFileName(const QString &pCaption, const QString &pFileName,
                        const QString &pFilters)
{
    // Retrieve and return a save file name

    QString res = QDir::toNativeSeparators(QFileDialog::getSaveFileName(qApp->activeWindow(),
                                                                        pCaption,
                                                                        pFileName.isEmpty()?
                                                                            activeDirectory():
                                                                            pFileName,
                                                                        allFilters(pFilters), 0,
                                                                        QFileDialog::DontConfirmOverwrite));

    // Make sure that we have got a save file name

    if (!res.isEmpty()) {
        // Make sure that the save file name is not the same as our given one

        if (!res.compare(pFileName)) {
            QMessageBox::warning(qApp->activeWindow(), pCaption,
                                 QObject::tr("Please choose a different file name."));

            return QString();
        }

        // Update our active directory

        QFileInfo resInfo = res;

        setActiveDirectory(resInfo.path());

        // Check whether the save file already exists

        if (resInfo.exists())
            // The save file already exists, so ask whether we want to overwrite
            // it

            if (QMessageBox::question(qApp->activeWindow(), pCaption,
                                      QObject::tr("<strong>%1</strong> already exists. Do you want to overwrite it?").arg(res),
                                      QMessageBox::Yes|QMessageBox::No,
                                      QMessageBox::Yes) == QMessageBox::No )
                return QString();
    }

    // Everything went fine,so return the save file name

    return res;
}

//==============================================================================

void setFocusTo(QWidget *pWidget)
{
    // Give the focus to pWidget, but then revert the focus back to whoever had
    // it before, if needed

    if (!pWidget)
        return;

    QWidget *focusedWidget = qApp->activeWindow()?
                                 qApp->activeWindow()->focusWidget():
                                 0;

    if (   !focusedWidget
        || (pWidget->parentWidget() == focusedWidget->parentWidget())) {
        // Either there is no currently focused widget or the currently focused
        // widget and the one to which we want to set the focus share the same
        // parent, so set the focus to the given widget

        pWidget->setFocus();
    }
}

//==============================================================================

QMenu * newMenu(const QString &pName, QWidget *pParent)
{
    // Create and return a menu

    QMenu *res = new QMenu(pParent);

    res->setObjectName("menu"+pName.left(1).toUpper()+pName.right(pName.size()-1));

    return res;
}

//==============================================================================

QMenu * newMenu(const QIcon &pIcon, QWidget *pParent)
{
    // Create and return a menu

    QMenu *res = new QMenu(pParent);

    res->menuAction()->setIcon(pIcon);

    return res;
}

//==============================================================================

QAction * newAction(const bool &pCheckable, const QIcon &pIcon,
                    const QKeySequence &pKeySequence, QWidget *pParent)
{
    // Create and return an action

    QAction *res = new QAction(pParent);

    res->setCheckable(pCheckable);
    res->setIcon(pIcon);
    res->setShortcut(pKeySequence);

    return res;
}

//==============================================================================

QAction * newAction(const bool &pCheckable, const QKeySequence &pKeySequence,
                    QWidget *pParent)
{
    // Create and return an action

    QAction *res = new QAction(pParent);

    res->setCheckable(pCheckable);
    res->setShortcut(pKeySequence);

    return res;
}

//==============================================================================

QAction * newAction(const bool &pCheckable, QWidget *pParent)
{
    // Create and return an action

    QAction *res = new QAction(pParent);

    res->setCheckable(pCheckable);

    return res;
}

//==============================================================================

QAction * newAction(const QIcon &pIcon,
                    const QList<QKeySequence> &pKeySequences, QWidget *pParent)
{
    // Create and return an action

    QAction *res = new QAction(pParent);

    res->setIcon(pIcon);
    res->setShortcuts(pKeySequences);

    return res;
}

//==============================================================================

QAction * newAction(const QIcon &pIcon, const QKeySequence &pKeySequence,
                    QWidget *pParent)
{
    // Create and return an action

    QAction *res = new QAction(pParent);

    res->setIcon(pIcon);
    res->setShortcut(pKeySequence);

    return res;
}

//==============================================================================

QAction * newAction(const QIcon &pIcon, QWidget *pParent)
{
    // Create and return an action

    QAction *res = new QAction(pParent);

    res->setIcon(pIcon);

    return res;
}

//==============================================================================

QAction * newAction(const QKeySequence &pKeySequence, QWidget *pParent)
{
    // Create and return an action

    QAction *res = new QAction(pParent);

    res->setShortcut(pKeySequence);

    return res;
}

//==============================================================================

QAction * newAction(const QKeySequence::StandardKey &pStandardKey,
                    QWidget *pParent)
{
    // Create and return an action

    QAction *res = new QAction(pParent);

    res->setShortcut(pStandardKey);

    return res;
}

//==============================================================================

QFrame * newLineWidget(const bool &pHorizontal, const QColor &pColor,
                       QWidget *pParent)
{
    // Create and return a 'real' line widget, i.e. one which is 1 pixel wide,
    // using a QFrame widget

    QFrame *res = new QFrame(pParent);

    res->setStyleSheet(QString("QFrame {"
                               "    border: 1px solid rgb(%1, %2, %3);"
                               "}").arg(QString::number(pColor.red()),
                                        QString::number(pColor.green()),
                                        QString::number(pColor.blue())));

    if (pHorizontal) {
        res->setSizePolicy(QSizePolicy::Preferred, QSizePolicy::Fixed);
        res->setFixedHeight(1);
    } else {
        res->setSizePolicy(QSizePolicy::Fixed, QSizePolicy::Preferred);
        res->setFixedWidth(1);
    }

    return res;
}

//==============================================================================

QFrame * newLineWidget(const bool &pHorizontal, QWidget *pParent)
{
    // Create and return a 'real' horizontal line widget

    return newLineWidget(pHorizontal, borderColor(), pParent);
}

//==============================================================================

QFrame * newLineWidget(const QColor &pColor, QWidget *pParent)
{
    // Create and return a 'real' horizontal line widget

    return newLineWidget(true, pColor, pParent);
}

//==============================================================================

QFrame * newLineWidget(QWidget *pParent)
{
    // Create and return a 'real' horizontal line widget

    return newLineWidget(true, borderColor(), pParent);
}

//==============================================================================

QString iconDataUri(const QString &pIcon, const int &pWidth, const int &pHeight,
                    const QIcon::Mode &pMode)
{
    // Convert an icon, which resource name is given, to a data URI, after
    // having resized it, if requested

    QIcon icon(pIcon);

    if (icon.isNull())
        return QString();

    QByteArray data;
    QBuffer buffer(&data);
    QSize iconSize = icon.availableSizes().first();

    buffer.open(QIODevice::WriteOnly);
    icon.pixmap((pWidth == -1)?iconSize.width():pWidth,
                (pHeight == -1)?iconSize.height():pHeight,
                pMode).save(&buffer, "PNG");

    return QString("data:image/png;base64,%1").arg(QString(data.toBase64()));
}

//==============================================================================

void showEnableWidget(QWidget *pWidget, const bool &pVisible,
                      const bool &pEnabled)
{
    // Show/enable or hide/disable the given widget

    pWidget->setVisible(pVisible);
    pWidget->setEnabled(pVisible && pEnabled);
}

//==============================================================================

QColor lockedColor(const QColor &pColor)
{
    // Return the resulting locked version of the given colour

    int r = pColor.red();
    int g = pColor.green();
    int b = pColor.blue();

    static const int lr = 255;
    static const int lg = 0;
    static const int lb = 0;

    static const double alpha = 0.05;
    static const double oneMinusAlpha = 1.0-alpha;

    return QColor(alpha*lr+oneMinusAlpha*r,
                  alpha*lg+oneMinusAlpha*g,
                  alpha*lb+oneMinusAlpha*b);
}

//==============================================================================

}   // namespace Core
}   // namespace OpenCOR

//==============================================================================
// End of file
//==============================================================================
<commit_msg>"All Files" option should be last in list of file filters.<commit_after>/*******************************************************************************

Licensed to the OpenCOR team under one or more contributor license agreements.
See the NOTICE.txt file distributed with this work for additional information
regarding copyright ownership. The OpenCOR team licenses this file to you under
the Apache License, Version 2.0 (the "License"); you may not use this file
except in compliance with the License. You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software distributed
under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
CONDITIONS OF ANY KIND, either express or implied. See the License for the
specific language governing permissions and limitations under the License.

*******************************************************************************/

//==============================================================================
// GUI utilities
//==============================================================================

#include "corecliutils.h"
#include "commonwidget.h"
#include "coresettings.h"
#include "coreguiutils.h"
#include "settings.h"

//==============================================================================

#include <Qt>

//==============================================================================

#include <QAction>
#include <QApplication>
#include <QBuffer>
#include <QColor>
#include <QDate>
#include <QFileDialog>
#include <QFileInfo>
#include <QFont>
#include <QFrame>
#include <QIODevice>
#include <QLabel>
#include <QMenu>
#include <QMessageBox>
#include <QPalette>
#include <QSettings>
#include <QSizePolicy>
#include <QStackedWidget>

//==============================================================================

namespace OpenCOR {
namespace Core {

//==============================================================================

#include "coreguiutils.cpp.inl"

//==============================================================================

QString allFilters(const QString &pFilters)
{
    return (pFilters.isEmpty()?QString():pFilters+";;")
           + QObject::tr("All Files")
           +" (*"
#ifdef Q_OS_WIN
           +".*"
#endif
           +")";
}

//==============================================================================

QString getOpenFileName(const QString &pCaption, const QString &pFilters)
{
    // Retrieve and return one open file name

    QString res = QFileDialog::getOpenFileName(qApp->activeWindow(),
                                               pCaption, activeDirectory(),
                                               allFilters(pFilters));

    if (res.size())
        // We have retrieved a file name, so keep track of the folder in which
        // it is

        setActiveDirectory(QFileInfo(res).path());

    // Return the file name

    return res;
}

//==============================================================================

QStringList getOpenFileNames(const QString &pCaption, const QString &pFilters)
{
    // Retrieve and return one or several open file names

    QStringList res = QFileDialog::getOpenFileNames(qApp->activeWindow(),
                                                    pCaption, activeDirectory(),
                                                    allFilters(pFilters));

    if (res.count())
        // We have retrieved at least one file name, so keep track of the folder
        // in which it is
        // Note #1: we use the last open file name to determine the folder that
        //          is to be remembered since on Windows 7, at least, it's
        //          possible to search for files from within the file dialog
        //          box, and the last file name should be the one we are most
        //          'interested' in...
        // Note #2: this doesn't, unfortunately, address the case where the user
        //          goes to a directory and then closes the file dialog box
        //          without selecting any open file name. There might be a way
        //          to get it to work, but that would involve using the exec()
        //          method rather than the static getOpenFilesNames() method,
        //          which would result in a non-native looking file dialog box
        //          (on Windows 7 at least), so it's not an option
        //          unfortunately...

        setActiveDirectory(QFileInfo(res[res.count()-1]).path());

    // Return the file name(s)

    return res;
}

//==============================================================================

QString getSaveFileName(const QString &pCaption, const QString &pFileName,
                        const QString &pFilters)
{
    // Retrieve and return a save file name

    QString res = QDir::toNativeSeparators(QFileDialog::getSaveFileName(qApp->activeWindow(),
                                                                        pCaption,
                                                                        pFileName.isEmpty()?
                                                                            activeDirectory():
                                                                            pFileName,
                                                                        allFilters(pFilters), 0,
                                                                        QFileDialog::DontConfirmOverwrite));

    // Make sure that we have got a save file name

    if (!res.isEmpty()) {
        // Make sure that the save file name is not the same as our given one

        if (!res.compare(pFileName)) {
            QMessageBox::warning(qApp->activeWindow(), pCaption,
                                 QObject::tr("Please choose a different file name."));

            return QString();
        }

        // Update our active directory

        QFileInfo resInfo = res;

        setActiveDirectory(resInfo.path());

        // Check whether the save file already exists

        if (resInfo.exists())
            // The save file already exists, so ask whether we want to overwrite
            // it

            if (QMessageBox::question(qApp->activeWindow(), pCaption,
                                      QObject::tr("<strong>%1</strong> already exists. Do you want to overwrite it?").arg(res),
                                      QMessageBox::Yes|QMessageBox::No,
                                      QMessageBox::Yes) == QMessageBox::No )
                return QString();
    }

    // Everything went fine,so return the save file name

    return res;
}

//==============================================================================

void setFocusTo(QWidget *pWidget)
{
    // Give the focus to pWidget, but then revert the focus back to whoever had
    // it before, if needed

    if (!pWidget)
        return;

    QWidget *focusedWidget = qApp->activeWindow()?
                                 qApp->activeWindow()->focusWidget():
                                 0;

    if (   !focusedWidget
        || (pWidget->parentWidget() == focusedWidget->parentWidget())) {
        // Either there is no currently focused widget or the currently focused
        // widget and the one to which we want to set the focus share the same
        // parent, so set the focus to the given widget

        pWidget->setFocus();
    }
}

//==============================================================================

QMenu * newMenu(const QString &pName, QWidget *pParent)
{
    // Create and return a menu

    QMenu *res = new QMenu(pParent);

    res->setObjectName("menu"+pName.left(1).toUpper()+pName.right(pName.size()-1));

    return res;
}

//==============================================================================

QMenu * newMenu(const QIcon &pIcon, QWidget *pParent)
{
    // Create and return a menu

    QMenu *res = new QMenu(pParent);

    res->menuAction()->setIcon(pIcon);

    return res;
}

//==============================================================================

QAction * newAction(const bool &pCheckable, const QIcon &pIcon,
                    const QKeySequence &pKeySequence, QWidget *pParent)
{
    // Create and return an action

    QAction *res = new QAction(pParent);

    res->setCheckable(pCheckable);
    res->setIcon(pIcon);
    res->setShortcut(pKeySequence);

    return res;
}

//==============================================================================

QAction * newAction(const bool &pCheckable, const QKeySequence &pKeySequence,
                    QWidget *pParent)
{
    // Create and return an action

    QAction *res = new QAction(pParent);

    res->setCheckable(pCheckable);
    res->setShortcut(pKeySequence);

    return res;
}

//==============================================================================

QAction * newAction(const bool &pCheckable, QWidget *pParent)
{
    // Create and return an action

    QAction *res = new QAction(pParent);

    res->setCheckable(pCheckable);

    return res;
}

//==============================================================================

QAction * newAction(const QIcon &pIcon,
                    const QList<QKeySequence> &pKeySequences, QWidget *pParent)
{
    // Create and return an action

    QAction *res = new QAction(pParent);

    res->setIcon(pIcon);
    res->setShortcuts(pKeySequences);

    return res;
}

//==============================================================================

QAction * newAction(const QIcon &pIcon, const QKeySequence &pKeySequence,
                    QWidget *pParent)
{
    // Create and return an action

    QAction *res = new QAction(pParent);

    res->setIcon(pIcon);
    res->setShortcut(pKeySequence);

    return res;
}

//==============================================================================

QAction * newAction(const QIcon &pIcon, QWidget *pParent)
{
    // Create and return an action

    QAction *res = new QAction(pParent);

    res->setIcon(pIcon);

    return res;
}

//==============================================================================

QAction * newAction(const QKeySequence &pKeySequence, QWidget *pParent)
{
    // Create and return an action

    QAction *res = new QAction(pParent);

    res->setShortcut(pKeySequence);

    return res;
}

//==============================================================================

QAction * newAction(const QKeySequence::StandardKey &pStandardKey,
                    QWidget *pParent)
{
    // Create and return an action

    QAction *res = new QAction(pParent);

    res->setShortcut(pStandardKey);

    return res;
}

//==============================================================================

QFrame * newLineWidget(const bool &pHorizontal, const QColor &pColor,
                       QWidget *pParent)
{
    // Create and return a 'real' line widget, i.e. one which is 1 pixel wide,
    // using a QFrame widget

    QFrame *res = new QFrame(pParent);

    res->setStyleSheet(QString("QFrame {"
                               "    border: 1px solid rgb(%1, %2, %3);"
                               "}").arg(QString::number(pColor.red()),
                                        QString::number(pColor.green()),
                                        QString::number(pColor.blue())));

    if (pHorizontal) {
        res->setSizePolicy(QSizePolicy::Preferred, QSizePolicy::Fixed);
        res->setFixedHeight(1);
    } else {
        res->setSizePolicy(QSizePolicy::Fixed, QSizePolicy::Preferred);
        res->setFixedWidth(1);
    }

    return res;
}

//==============================================================================

QFrame * newLineWidget(const bool &pHorizontal, QWidget *pParent)
{
    // Create and return a 'real' horizontal line widget

    return newLineWidget(pHorizontal, borderColor(), pParent);
}

//==============================================================================

QFrame * newLineWidget(const QColor &pColor, QWidget *pParent)
{
    // Create and return a 'real' horizontal line widget

    return newLineWidget(true, pColor, pParent);
}

//==============================================================================

QFrame * newLineWidget(QWidget *pParent)
{
    // Create and return a 'real' horizontal line widget

    return newLineWidget(true, borderColor(), pParent);
}

//==============================================================================

QString iconDataUri(const QString &pIcon, const int &pWidth, const int &pHeight,
                    const QIcon::Mode &pMode)
{
    // Convert an icon, which resource name is given, to a data URI, after
    // having resized it, if requested

    QIcon icon(pIcon);

    if (icon.isNull())
        return QString();

    QByteArray data;
    QBuffer buffer(&data);
    QSize iconSize = icon.availableSizes().first();

    buffer.open(QIODevice::WriteOnly);
    icon.pixmap((pWidth == -1)?iconSize.width():pWidth,
                (pHeight == -1)?iconSize.height():pHeight,
                pMode).save(&buffer, "PNG");

    return QString("data:image/png;base64,%1").arg(QString(data.toBase64()));
}

//==============================================================================

void showEnableWidget(QWidget *pWidget, const bool &pVisible,
                      const bool &pEnabled)
{
    // Show/enable or hide/disable the given widget

    pWidget->setVisible(pVisible);
    pWidget->setEnabled(pVisible && pEnabled);
}

//==============================================================================

QColor lockedColor(const QColor &pColor)
{
    // Return the resulting locked version of the given colour

    int r = pColor.red();
    int g = pColor.green();
    int b = pColor.blue();

    static const int lr = 255;
    static const int lg = 0;
    static const int lb = 0;

    static const double alpha = 0.05;
    static const double oneMinusAlpha = 1.0-alpha;

    return QColor(alpha*lr+oneMinusAlpha*r,
                  alpha*lg+oneMinusAlpha*g,
                  alpha*lb+oneMinusAlpha*b);
}

//==============================================================================

}   // namespace Core
}   // namespace OpenCOR

//==============================================================================
// End of file
//==============================================================================
<|endoftext|>


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

#ifndef _SEINITIALIZERIMPL_HXX
#define _SEINITIALIZERIMPL_HXX

#ifndef _COM_SUN_STAR_XML_CRYPTO_XXMLSECURITYCONTEXT_HPP_
#include <com/sun/star/xml/crypto/XXMLSecurityContext.hpp>
#endif
#ifndef _COM_SUN_STAR_XML_CRYPTO_SEINITIALIZER_HPP_
#include <com/sun/star/xml/crypto/XSEInitializer.hpp>
#endif
#ifndef _COM_SUN_STAR_LANG_XUNOTUNNEL_HPP_
#include <com/sun/star/lang/XUnoTunnel.hpp>
#endif
#ifndef _COM_SUN_STAR_LANG_XSERVICEINFO_HPP_
#include <com/sun/star/lang/XServiceInfo.hpp>
#endif
#ifndef _COM_SUN_STAR_LANG_XMULTISERVICEFACTORY_HPP_
#include <com/sun/star/lang/XMultiServiceFactory.hpp>
#endif
#ifndef _CPPUHELPER_IMPLBASE2_HXX_
#include <cppuhelper/implbase2.hxx>
#endif

#include <libxml/tree.h>

class SEInitializer_MSCryptImpl : public cppu::WeakImplHelper2
<
    com::sun::star::xml::crypto::XSEInitializer,
    com::sun::star::lang::XServiceInfo
>
/****** SEInitializer_MSCryptImpl.hxx/CLASS SEInitializer_MSCryptImpl ***********
 *
 *   NAME
 *  SEInitializer_MSCryptImpl -- Class to initialize a Security Context
 *  instance
 *
 *   FUNCTION
 *  Use this class to initialize a XmlSec based Security Context
 *  instance. After this instance is used up, use this class to free this
 *  instance.
 *
 *   HISTORY
 *  05.01.2004 -    Interface supported: XSEInitializer, XSEInitializer
 *
 *   AUTHOR
 *  Michael Mi
 *  Email: michael.mi@sun.com
 ******************************************************************************/
{
private:
    com::sun::star::uno::Reference< com::sun::star::lang::XMultiServiceFactory > mxMSF;

public:
    SEInitializer_MSCryptImpl(const com::sun::star::uno::Reference< com::sun::star::lang::XMultiServiceFactory > &rxMSF);
    virtual ~SEInitializer_MSCryptImpl();

    /* XSEInitializer */
    virtual com::sun::star::uno::Reference<
        com::sun::star::xml::crypto::XXMLSecurityContext >
        SAL_CALL createSecurityContext( const rtl::OUString& certDB )
        throw (com::sun::star::uno::RuntimeException);

    virtual void SAL_CALL freeSecurityContext( const com::sun::star::uno::Reference<
        com::sun::star::xml::crypto::XXMLSecurityContext >& securityContext )
        throw (com::sun::star::uno::RuntimeException);

    /* XServiceInfo */
    virtual rtl::OUString SAL_CALL getImplementationName(  )
        throw (com::sun::star::uno::RuntimeException);

    virtual sal_Bool SAL_CALL supportsService( const rtl::OUString& ServiceName )
        throw (com::sun::star::uno::RuntimeException);

    virtual com::sun::star::uno::Sequence< rtl::OUString > SAL_CALL getSupportedServiceNames(  )
        throw (com::sun::star::uno::RuntimeException);
};

rtl::OUString SEInitializer_MSCryptImpl_getImplementationName()
    throw ( com::sun::star::uno::RuntimeException );

sal_Bool SAL_CALL SEInitializer_MSCryptImpl_supportsService( const rtl::OUString& ServiceName )
    throw ( com::sun::star::uno::RuntimeException );

com::sun::star::uno::Sequence< rtl::OUString > SAL_CALL SEInitializer_MSCryptImpl_getSupportedServiceNames(  )
    throw ( com::sun::star::uno::RuntimeException );

com::sun::star::uno::Reference< com::sun::star::uno::XInterface >
SAL_CALL SEInitializer_MSCryptImpl_createInstance( const com::sun::star::uno::Reference< com::sun::star::lang::XMultiServiceFactory > & rSMgr)
    throw ( com::sun::star::uno::Exception );

#endif

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

#ifndef _SEINITIALIZERIMPL_HXX
#define _SEINITIALIZERIMPL_HXX

#ifndef _COM_SUN_STAR_XML_CRYPTO_XXMLSECURITYCONTEXT_HPP_
#include <com/sun/star/xml/crypto/XXMLSecurityContext.hpp>
#endif
#ifndef _COM_SUN_STAR_XML_CRYPTO_SEINITIALIZER_HPP_
#include <com/sun/star/xml/crypto/XSEInitializer.hpp>
#endif
#ifndef _COM_SUN_STAR_LANG_XUNOTUNNEL_HPP_
#include <com/sun/star/lang/XUnoTunnel.hpp>
#endif
#ifndef _COM_SUN_STAR_LANG_XSERVICEINFO_HPP_
#include <com/sun/star/lang/XServiceInfo.hpp>
#endif
#ifndef _COM_SUN_STAR_LANG_XMULTISERVICEFACTORY_HPP_
#include <com/sun/star/lang/XMultiServiceFactory.hpp>
#endif
#ifndef _CPPUHELPER_IMPLBASE2_HXX_
#include <cppuhelper/implbase2.hxx>
#endif

#include <libxml/tree.h>

class SEInitializer_MSCryptImpl : public cppu::WeakImplHelper2
<
    com::sun::star::xml::crypto::XSEInitializer,
    com::sun::star::lang::XServiceInfo
>
/****** SEInitializer_MSCryptImpl.hxx/CLASS SEInitializer_MSCryptImpl ***********
 *
 *   NAME
 *  SEInitializer_MSCryptImpl -- Class to initialize a Security Context
 *  instance
 *
 *   FUNCTION
 *  Use this class to initialize a XmlSec based Security Context
 *  instance. After this instance is used up, use this class to free this
 *  instance.
 *
 *   HISTORY
 *  05.01.2004 -    Interface supported: XSEInitializer, XSEInitializer
 *
 *   AUTHOR
 *  Michael Mi
 *  Email: michael.mi@sun.com
 ******************************************************************************/
{
private:
    com::sun::star::uno::Reference< com::sun::star::lang::XMultiServiceFactory > mxMSF;

public:
    SEInitializer_MSCryptImpl(const com::sun::star::uno::Reference< com::sun::star::lang::XMultiServiceFactory > &rxMSF);
    virtual ~SEInitializer_MSCryptImpl();

    /* XSEInitializer */
    virtual com::sun::star::uno::Reference<
        com::sun::star::xml::crypto::XXMLSecurityContext >
        SAL_CALL createSecurityContext( const rtl::OUString& certDB )
        throw (com::sun::star::uno::RuntimeException);

    virtual void SAL_CALL freeSecurityContext( const com::sun::star::uno::Reference<
        com::sun::star::xml::crypto::XXMLSecurityContext >& securityContext )
        throw (com::sun::star::uno::RuntimeException);

    /* XServiceInfo */
    virtual rtl::OUString SAL_CALL getImplementationName(  )
        throw (com::sun::star::uno::RuntimeException);

    virtual sal_Bool SAL_CALL supportsService( const rtl::OUString& ServiceName )
        throw (com::sun::star::uno::RuntimeException);

    virtual com::sun::star::uno::Sequence< rtl::OUString > SAL_CALL getSupportedServiceNames(  )
        throw (com::sun::star::uno::RuntimeException);
};

rtl::OUString SEInitializer_MSCryptImpl_getImplementationName()
    throw ( com::sun::star::uno::RuntimeException );

sal_Bool SAL_CALL SEInitializer_MSCryptImpl_supportsService( const rtl::OUString& ServiceName )
    throw ( com::sun::star::uno::RuntimeException );

com::sun::star::uno::Sequence< rtl::OUString > SAL_CALL SEInitializer_MSCryptImpl_getSupportedServiceNames(  )
    throw ( com::sun::star::uno::RuntimeException );

com::sun::star::uno::Reference< com::sun::star::uno::XInterface >
SAL_CALL SEInitializer_MSCryptImpl_createInstance( const com::sun::star::uno::Reference< com::sun::star::lang::XMultiServiceFactory > & rSMgr)
    throw ( com::sun::star::uno::Exception );

#endif

<|endoftext|>


<commit_before>/****************************************************************************
**
** Copyright (C) 2011 Nokia Corporation and/or its subsidiary(-ies).
** All rights reserved.
** Contact: Nokia Corporation (qt-info@nokia.com)
**
** This file is part of the plugins of the Qt Toolkit.
**
** $QT_BEGIN_LICENSE:LGPL$
** GNU Lesser General Public License Usage
** This file may be used under the terms of the GNU Lesser General Public
** License version 2.1 as published by the Free Software Foundation and
** appearing in the file LICENSE.LGPL included in the packaging of this
** file. Please review the following information to ensure the GNU Lesser
** General Public License version 2.1 requirements will be met:
** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, Nokia gives you certain additional
** rights. These rights are described in the Nokia Qt LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
** 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.
**
** Other Usage
** Alternatively, this file may be used in accordance with the terms and
** conditions contained in a signed written agreement between you and Nokia.
**
**
**
**
**
** $QT_END_LICENSE$
**
****************************************************************************/

#include "qwaylandclipboard.h"
#include "qwaylanddisplay.h"
#include "qwaylandinputdevice.h"
#include "qwaylandmime.h"
#include <QtGui/QPlatformNativeInterface>
#include <QtGui/QApplication>
#include <QtCore/QMimeData>
#include <QtCore/QStringList>
#include <QtCore/QFile>
#include <QtCore/QtDebug>
#include <QtGui/private/qdnd_p.h>

static QWaylandClipboard *clipboard = 0;

class QWaylandClipboardMimeData : public QInternalMimeData
{
public:
    void clearAll();
    void setFormats(const QStringList &formatList);
    bool hasFormat_sys(const QString &mimeType) const;
    QStringList formats_sys() const;
    QVariant retrieveData_sys(const QString &mimeType, QVariant::Type type) const;
private:
    QStringList mFormatList;
};

void QWaylandClipboardMimeData::clearAll()
{
    clear();
    mFormatList.clear();
}

void QWaylandClipboardMimeData::setFormats(const QStringList &formatList)
{
    mFormatList = formatList;
}

bool QWaylandClipboardMimeData::hasFormat_sys(const QString &mimeType) const
{
    return formats().contains(mimeType);
}

QStringList QWaylandClipboardMimeData::formats_sys() const
{
    return mFormatList;
}

QVariant QWaylandClipboardMimeData::retrieveData_sys(const QString &mimeType, QVariant::Type type) const
{
    return clipboard->retrieveData(mimeType, type);
}

class QWaylandSelection
{
public:
    QWaylandSelection(QWaylandDisplay *display, QMimeData *data);
    ~QWaylandSelection();

    static uint32_t getTime();
    static void send(void *data, struct wl_selection *selection, const char *mime_type, int fd);
    static void cancelled(void *data, struct wl_selection *selection);
    static const struct wl_selection_listener selectionListener;

    QMimeData *mMimeData;
    struct wl_selection *mSelection;
};

const struct wl_selection_listener QWaylandSelection::selectionListener = {
    QWaylandSelection::send,
    QWaylandSelection::cancelled
};

uint32_t QWaylandSelection::getTime()
{
    struct timeval tv;
    gettimeofday(&tv, 0);
    return tv.tv_sec * 1000 + tv.tv_usec / 1000;
}

QWaylandSelection::QWaylandSelection(QWaylandDisplay *display, QMimeData *data)
    : mMimeData(data), mSelection(0)
{
    struct wl_shell *shell = display->wl_shell();
    mSelection = wl_shell_create_selection(shell);
    wl_selection_add_listener(mSelection, &selectionListener, this);
    foreach (const QString &format, data->formats())
        wl_selection_offer(mSelection, format.toLatin1().constData());
    wl_selection_activate(mSelection,
                          display->inputDevices().at(0)->wl_input_device(),
                          getTime());
}

QWaylandSelection::~QWaylandSelection()
{
    if (mSelection) {
        clipboard->unregisterSelection(this);
        wl_selection_destroy(mSelection);
    }
    delete mMimeData;
}

void QWaylandSelection::send(void *data,
                             struct wl_selection *selection,
                             const char *mime_type,
                             int fd)
{
    Q_UNUSED(selection);
    QWaylandSelection *self = static_cast<QWaylandSelection *>(data);
    QString mimeType = QString::fromLatin1(mime_type);
    QByteArray content = QWaylandMimeHelper::getByteArray(self->mMimeData, mimeType);
    if (!content.isEmpty()) {
        QFile f;
        if (f.open(fd, QIODevice::WriteOnly))
            f.write(content);
    }
    close(fd);
}

void QWaylandSelection::cancelled(void *data, struct wl_selection *selection)
{
    Q_UNUSED(selection);
    delete static_cast<QWaylandSelection *>(data);
}

QWaylandClipboard *QWaylandClipboard::instance(QWaylandDisplay *display)
{
    if (!clipboard)
        clipboard = new QWaylandClipboard(display);
    return clipboard;
}

QWaylandClipboard::QWaylandClipboard(QWaylandDisplay *display)
    : mDisplay(display), mMimeDataIn(0), mOffer(0)
{
}

QWaylandClipboard::~QWaylandClipboard()
{
    if (mOffer)
        wl_selection_offer_destroy(mOffer);
    delete mMimeDataIn;
    qDeleteAll(mSelections);
}

void QWaylandClipboard::unregisterSelection(QWaylandSelection *selection)
{
    mSelections.removeOne(selection);
}

void QWaylandClipboard::syncCallback(void *data)
{
    *static_cast<bool *>(data) = true;
}

void QWaylandClipboard::forceRoundtrip(struct wl_display *display)
{
    bool done = false;
    wl_display_sync_callback(display, syncCallback, &done);
    wl_display_iterate(display, WL_DISPLAY_WRITABLE);
    while (!done)
        wl_display_iterate(display, WL_DISPLAY_READABLE);
}

QVariant QWaylandClipboard::retrieveData(const QString &mimeType, QVariant::Type type) const
{
    Q_UNUSED(type);
    if (mOfferedMimeTypes.isEmpty() || !mOffer)
        return QVariant();
    int pipefd[2];
    if (pipe(pipefd) == -1) {
        qWarning("QWaylandClipboard: pipe() failed");
        return QVariant();
    }
    QByteArray mimeTypeBa = mimeType.toLatin1();
    wl_selection_offer_receive(mOffer, mimeTypeBa.constData(), pipefd[1]);
    QByteArray content;
    forceRoundtrip(mDisplay->wl_display());
    char buf[256];
    int n;
    close(pipefd[1]);
    while ((n = read(pipefd[0], &buf, sizeof buf)) > 0)
        content.append(buf, n);
    close(pipefd[0]);
    return content;
}

QMimeData *QWaylandClipboard::mimeData(QClipboard::Mode mode)
{
    Q_ASSERT(mode == QClipboard::Clipboard);
    if (!mSelections.isEmpty())
        return mSelections.last()->mMimeData;
    if (!mMimeDataIn)
        mMimeDataIn = new QWaylandClipboardMimeData;
    mMimeDataIn->clearAll();
    if (!mOfferedMimeTypes.isEmpty() && mOffer)
        mMimeDataIn->setFormats(mOfferedMimeTypes);
    return mMimeDataIn;
}

void QWaylandClipboard::setMimeData(QMimeData *data, QClipboard::Mode mode)
{
    Q_ASSERT(mode == QClipboard::Clipboard);
    if (!mDisplay->inputDevices().isEmpty()) {
        if (!data)
            data = new QMimeData;
        mSelections.append(new QWaylandSelection(mDisplay, data));
    } else {
        qWarning("QWaylandClipboard::setMimeData: No input devices");
    }
}

bool QWaylandClipboard::supportsMode(QClipboard::Mode mode) const
{
    return mode == QClipboard::Clipboard;
}

const struct wl_selection_offer_listener QWaylandClipboard::selectionOfferListener = {
    QWaylandClipboard::offer,
    QWaylandClipboard::keyboardFocus
};

void QWaylandClipboard::createSelectionOffer(uint32_t id)
{
    mOfferedMimeTypes.clear();
    if (mOffer)
        wl_selection_offer_destroy(mOffer);
    mOffer = 0;
    struct wl_selection_offer *offer = wl_selection_offer_create(mDisplay->wl_display(), id, 1);
    wl_selection_offer_add_listener(offer, &selectionOfferListener, this);
}

void QWaylandClipboard::offer(void *data,
                              struct wl_selection_offer *selection_offer,
                              const char *type)
{
    Q_UNUSED(data);
    Q_UNUSED(selection_offer);
    clipboard->mOfferedMimeTypes.append(QString::fromLatin1(type));
}

void QWaylandClipboard::keyboardFocus(void *data,
                                      struct wl_selection_offer *selection_offer,
                                      wl_input_device *input_device)
{
    Q_UNUSED(data);
    if (!input_device) {
        wl_selection_offer_destroy(selection_offer);
        clipboard->mOffer = 0;
        return;
    }
    clipboard->mOffer = selection_offer;
    if (clipboard->mSelections.isEmpty())
        QMetaObject::invokeMethod(&clipboard->mEmitter, "emitChanged", Qt::QueuedConnection);
}

void QWaylandClipboardSignalEmitter::emitChanged()
{
    clipboard->emitChanged(QClipboard::Clipboard);
}
<commit_msg>Handle EINTR gracefully in Wayland clipboard.<commit_after>/****************************************************************************
**
** Copyright (C) 2011 Nokia Corporation and/or its subsidiary(-ies).
** All rights reserved.
** Contact: Nokia Corporation (qt-info@nokia.com)
**
** This file is part of the plugins of the Qt Toolkit.
**
** $QT_BEGIN_LICENSE:LGPL$
** GNU Lesser General Public License Usage
** This file may be used under the terms of the GNU Lesser General Public
** License version 2.1 as published by the Free Software Foundation and
** appearing in the file LICENSE.LGPL included in the packaging of this
** file. Please review the following information to ensure the GNU Lesser
** General Public License version 2.1 requirements will be met:
** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, Nokia gives you certain additional
** rights. These rights are described in the Nokia Qt LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
** 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.
**
** Other Usage
** Alternatively, this file may be used in accordance with the terms and
** conditions contained in a signed written agreement between you and Nokia.
**
**
**
**
**
** $QT_END_LICENSE$
**
****************************************************************************/

#include "qwaylandclipboard.h"
#include "qwaylanddisplay.h"
#include "qwaylandinputdevice.h"
#include "qwaylandmime.h"
#include <QtGui/QPlatformNativeInterface>
#include <QtGui/QApplication>
#include <QtCore/QMimeData>
#include <QtCore/QStringList>
#include <QtCore/QFile>
#include <QtCore/QtDebug>
#include <QtGui/private/qdnd_p.h>
#include <QtCore/private/qcore_unix_p.h> // for QT_READ

static QWaylandClipboard *clipboard = 0;

class QWaylandClipboardMimeData : public QInternalMimeData
{
public:
    void clearAll();
    void setFormats(const QStringList &formatList);
    bool hasFormat_sys(const QString &mimeType) const;
    QStringList formats_sys() const;
    QVariant retrieveData_sys(const QString &mimeType, QVariant::Type type) const;
private:
    QStringList mFormatList;
};

void QWaylandClipboardMimeData::clearAll()
{
    clear();
    mFormatList.clear();
}

void QWaylandClipboardMimeData::setFormats(const QStringList &formatList)
{
    mFormatList = formatList;
}

bool QWaylandClipboardMimeData::hasFormat_sys(const QString &mimeType) const
{
    return formats().contains(mimeType);
}

QStringList QWaylandClipboardMimeData::formats_sys() const
{
    return mFormatList;
}

QVariant QWaylandClipboardMimeData::retrieveData_sys(const QString &mimeType, QVariant::Type type) const
{
    return clipboard->retrieveData(mimeType, type);
}

class QWaylandSelection
{
public:
    QWaylandSelection(QWaylandDisplay *display, QMimeData *data);
    ~QWaylandSelection();

    static uint32_t getTime();
    static void send(void *data, struct wl_selection *selection, const char *mime_type, int fd);
    static void cancelled(void *data, struct wl_selection *selection);
    static const struct wl_selection_listener selectionListener;

    QMimeData *mMimeData;
    struct wl_selection *mSelection;
};

const struct wl_selection_listener QWaylandSelection::selectionListener = {
    QWaylandSelection::send,
    QWaylandSelection::cancelled
};

uint32_t QWaylandSelection::getTime()
{
    struct timeval tv;
    gettimeofday(&tv, 0);
    return tv.tv_sec * 1000 + tv.tv_usec / 1000;
}

QWaylandSelection::QWaylandSelection(QWaylandDisplay *display, QMimeData *data)
    : mMimeData(data), mSelection(0)
{
    struct wl_shell *shell = display->wl_shell();
    mSelection = wl_shell_create_selection(shell);
    wl_selection_add_listener(mSelection, &selectionListener, this);
    foreach (const QString &format, data->formats())
        wl_selection_offer(mSelection, format.toLatin1().constData());
    wl_selection_activate(mSelection,
                          display->inputDevices().at(0)->wl_input_device(),
                          getTime());
}

QWaylandSelection::~QWaylandSelection()
{
    if (mSelection) {
        clipboard->unregisterSelection(this);
        wl_selection_destroy(mSelection);
    }
    delete mMimeData;
}

void QWaylandSelection::send(void *data,
                             struct wl_selection *selection,
                             const char *mime_type,
                             int fd)
{
    Q_UNUSED(selection);
    QWaylandSelection *self = static_cast<QWaylandSelection *>(data);
    QString mimeType = QString::fromLatin1(mime_type);
    QByteArray content = QWaylandMimeHelper::getByteArray(self->mMimeData, mimeType);
    if (!content.isEmpty()) {
        QFile f;
        if (f.open(fd, QIODevice::WriteOnly))
            f.write(content);
    }
    close(fd);
}

void QWaylandSelection::cancelled(void *data, struct wl_selection *selection)
{
    Q_UNUSED(selection);
    delete static_cast<QWaylandSelection *>(data);
}

QWaylandClipboard *QWaylandClipboard::instance(QWaylandDisplay *display)
{
    if (!clipboard)
        clipboard = new QWaylandClipboard(display);
    return clipboard;
}

QWaylandClipboard::QWaylandClipboard(QWaylandDisplay *display)
    : mDisplay(display), mMimeDataIn(0), mOffer(0)
{
}

QWaylandClipboard::~QWaylandClipboard()
{
    if (mOffer)
        wl_selection_offer_destroy(mOffer);
    delete mMimeDataIn;
    qDeleteAll(mSelections);
}

void QWaylandClipboard::unregisterSelection(QWaylandSelection *selection)
{
    mSelections.removeOne(selection);
}

void QWaylandClipboard::syncCallback(void *data)
{
    *static_cast<bool *>(data) = true;
}

void QWaylandClipboard::forceRoundtrip(struct wl_display *display)
{
    bool done = false;
    wl_display_sync_callback(display, syncCallback, &done);
    wl_display_iterate(display, WL_DISPLAY_WRITABLE);
    while (!done)
        wl_display_iterate(display, WL_DISPLAY_READABLE);
}

QVariant QWaylandClipboard::retrieveData(const QString &mimeType, QVariant::Type type) const
{
    Q_UNUSED(type);
    if (mOfferedMimeTypes.isEmpty() || !mOffer)
        return QVariant();
    int pipefd[2];
    if (pipe(pipefd) == -1) {
        qWarning("QWaylandClipboard: pipe() failed");
        return QVariant();
    }
    QByteArray mimeTypeBa = mimeType.toLatin1();
    wl_selection_offer_receive(mOffer, mimeTypeBa.constData(), pipefd[1]);
    QByteArray content;
    forceRoundtrip(mDisplay->wl_display());
    char buf[256];
    int n;
    close(pipefd[1]);
    while ((n = QT_READ(pipefd[0], &buf, sizeof buf)) > 0)
        content.append(buf, n);
    close(pipefd[0]);
    return content;
}

QMimeData *QWaylandClipboard::mimeData(QClipboard::Mode mode)
{
    Q_ASSERT(mode == QClipboard::Clipboard);
    if (!mSelections.isEmpty())
        return mSelections.last()->mMimeData;
    if (!mMimeDataIn)
        mMimeDataIn = new QWaylandClipboardMimeData;
    mMimeDataIn->clearAll();
    if (!mOfferedMimeTypes.isEmpty() && mOffer)
        mMimeDataIn->setFormats(mOfferedMimeTypes);
    return mMimeDataIn;
}

void QWaylandClipboard::setMimeData(QMimeData *data, QClipboard::Mode mode)
{
    Q_ASSERT(mode == QClipboard::Clipboard);
    if (!mDisplay->inputDevices().isEmpty()) {
        if (!data)
            data = new QMimeData;
        mSelections.append(new QWaylandSelection(mDisplay, data));
    } else {
        qWarning("QWaylandClipboard::setMimeData: No input devices");
    }
}

bool QWaylandClipboard::supportsMode(QClipboard::Mode mode) const
{
    return mode == QClipboard::Clipboard;
}

const struct wl_selection_offer_listener QWaylandClipboard::selectionOfferListener = {
    QWaylandClipboard::offer,
    QWaylandClipboard::keyboardFocus
};

void QWaylandClipboard::createSelectionOffer(uint32_t id)
{
    mOfferedMimeTypes.clear();
    if (mOffer)
        wl_selection_offer_destroy(mOffer);
    mOffer = 0;
    struct wl_selection_offer *offer = wl_selection_offer_create(mDisplay->wl_display(), id, 1);
    wl_selection_offer_add_listener(offer, &selectionOfferListener, this);
}

void QWaylandClipboard::offer(void *data,
                              struct wl_selection_offer *selection_offer,
                              const char *type)
{
    Q_UNUSED(data);
    Q_UNUSED(selection_offer);
    clipboard->mOfferedMimeTypes.append(QString::fromLatin1(type));
}

void QWaylandClipboard::keyboardFocus(void *data,
                                      struct wl_selection_offer *selection_offer,
                                      wl_input_device *input_device)
{
    Q_UNUSED(data);
    if (!input_device) {
        wl_selection_offer_destroy(selection_offer);
        clipboard->mOffer = 0;
        return;
    }
    clipboard->mOffer = selection_offer;
    if (clipboard->mSelections.isEmpty())
        QMetaObject::invokeMethod(&clipboard->mEmitter, "emitChanged", Qt::QueuedConnection);
}

void QWaylandClipboardSignalEmitter::emitChanged()
{
    clipboard->emitChanged(QClipboard::Clipboard);
}
<|endoftext|>


<commit_before>//
// This file is part of the Marble Virtual Globe.
//
// This program is free software licensed under the GNU LGPL. You can
// find a copy of this license in LICENSE.txt in the top directory of
// the source code.
//
// Copyright 2011      Dennis Nienhüser <earthwings@gentoo.org>
//

#include "OsmDatabase.h"
#include "OsmRegion.h"
#include "MarbleDebug.h"
#include "MarbleMath.h"
#include "MarbleLocale.h"
#include "DatabaseQuery.h"

#include <QtCore/QFile>
#include <QtCore/QDataStream>
#include <QtCore/QStringList>
#include <QtCore/QRegExp>
#include <QtCore/QVariant>
#include <QtCore/QTime>

#include <QtSql/QSqlDatabase>
#include <QtSql/QSqlQuery>
#include <QtSql/QSqlError>

namespace Marble {

OsmDatabase::OsmDatabase()
{
    m_database = QSqlDatabase::addDatabase( "QSQLITE" );
}

void OsmDatabase::addFile( const QString &fileName )
{
    m_databases << fileName;
}

QList<OsmPlacemark> OsmDatabase::find( MarbleModel* model, const QString &searchTerm )
{
    if ( m_databases.isEmpty() ) {
        return QList<OsmPlacemark>();
    }

    DatabaseQuery userQuery( model, searchTerm );

    QString queryString;

    queryString = " SELECT regions.name,"
            " places.name, places.number,"
            " places.category, places.lon, places.lat"
            " FROM regions, places";

    if ( userQuery.queryType() == DatabaseQuery::CategorySearch ) {
        queryString += " WHERE regions.id = places.region AND places.category = %1";
        queryString = queryString.arg( (qint32) userQuery.category() );
        if ( userQuery.resultFormat() == DatabaseQuery::DistanceFormat && userQuery.region().isEmpty() ) {
            queryString += " ORDER BY ((places.lat-%1)*(places.lat-%1)+(places.lon-%2)*(places.lon-%2))";
            GeoDataCoordinates position = userQuery.position();
            queryString = queryString.arg( position.latitude( GeoDataCoordinates::Degree ), 0, 'f', 8 )
                    .arg( position.longitude( GeoDataCoordinates::Degree ), 0, 'f', 8 );
        } else {
            queryString += " AND regions.name LIKE '%" + userQuery.region() + "%'";
        }
    } else if ( userQuery.queryType() == DatabaseQuery::BroadSearch ) {
        queryString += " WHERE regions.id = places.region"
                " AND places.name " + wildcardQuery( searchTerm );
    } else {
        queryString += " WHERE regions.id = places.region"
                "   AND places.name " + wildcardQuery( userQuery.street() );
        if ( !userQuery.houseNumber().isEmpty() ) {
            queryString += " AND places.number " + wildcardQuery( userQuery.houseNumber() );
        }
        queryString += " AND regions.name LIKE '%" + userQuery.region() + "%'";
    }

    queryString += " LIMIT 50;";

    QList<OsmPlacemark> result;
    QTime timer;
    timer.start();
    foreach( const QString &databaseFile, m_databases ) {
        /** @todo: sort/filter results from several databases */

        m_database.setDatabaseName( databaseFile );
        if ( !m_database.open() ) {
            mDebug() << "Failed to connect to database " << databaseFile;
        }

        QSqlQuery query;
        query.setForwardOnly( true );
        if ( !query.exec( queryString ) ) {
            mDebug() << "Failed to execute query: " << query.lastError();
            return result;
        }

        while ( query.next() ) {
            OsmPlacemark placemark;
            if ( userQuery.resultFormat() == DatabaseQuery::DistanceFormat ) {
                GeoDataCoordinates coordinates( query.value(4).toFloat(), query.value(5).toFloat(), 0.0, GeoDataCoordinates::Degree );
                placemark.setAdditionalInformation( formatDistance( coordinates, userQuery.position() ) );
            } else {
                placemark.setAdditionalInformation( query.value( 0 ).toString() );
            }
            placemark.setName( query.value(1).toString() );
            placemark.setHouseNumber( query.value(2).toString() );
            placemark.setCategory( (OsmPlacemark::OsmCategory) query.value(3).toInt() );
            placemark.setLongitude( query.value(4).toFloat() );
            placemark.setLatitude( query.value(5).toFloat() );
            result.push_back( placemark );
        }
    }

    mDebug() << "Offline OSM search query took " << timer.elapsed() << " ms. Query: " << queryString;
    return result;
}

QString OsmDatabase::formatDistance( const GeoDataCoordinates &a, const GeoDataCoordinates &b ) const
{
    qreal distance = EARTH_RADIUS * distanceSphere( a, b);

    int precision = 0;
    QString distanceUnit = "m";

    if ( MarbleGlobal::getInstance()->locale()->distanceUnit() == Marble::MilesFeet ) {
        precision = 1;
        distanceUnit = "mi";
        distance *= METER2KM;
        distance *= KM2MI;
    } else {
        if ( distance >= 1000 ) {
            distance /= 1000;
            distanceUnit = "km";
            precision = 1;
        } else if ( distance >= 200 ) {
            distance = 50 * qRound( distance / 50 );
        } else if ( distance >= 100 ) {
            distance = 25 * qRound( distance / 25 );
        } else {
            distance = 10 * qRound( distance / 10 );
        }
    }

    QString const fuzzyDistance = QString( "%1 %2" ).arg( distance, 0, 'f', precision ).arg( distanceUnit );

    int direction = 180 + bearing( a, b ) * RAD2DEG;

    QString heading = QObject::tr( "north" );
    if ( direction > 337 ) {
        heading = QObject::tr( "north" );
    } else if ( direction > 292 ) {
        heading = QObject::tr( "north-west" );
    } else if ( direction > 247 ) {
        heading = QObject::tr( "west" );
    } else if ( direction > 202 ) {
        heading = QObject::tr( "south-west" );
    } else if ( direction > 157 ) {
        heading = QObject::tr( "south" );
    } else if ( direction > 112 ) {
        heading = QObject::tr( "south-east" );
    } else if ( direction > 67 ) {
        heading = QObject::tr( "east" );
    } else if ( direction > 22 ) {
        heading = QObject::tr( "north-east" );
    }

    return fuzzyDistance + " " + heading;
}

qreal OsmDatabase::bearing( const GeoDataCoordinates &a, const GeoDataCoordinates &b ) const
{
    qreal delta = b.longitude() - a.longitude();
    qreal lat1 = a.latitude();
    qreal lat2 = b.latitude();
    return fmod( atan2( sin ( delta ) * cos ( lat2 ),
                       cos( lat1 ) * sin( lat2 ) - sin( lat1 ) * cos( lat2 ) * cos ( delta ) ), 2 * M_PI );
}

QString OsmDatabase::wildcardQuery( const QString &term ) const
{
    QString result = term;
    if ( term.contains( '*' ) ) {
        return " LIKE '" + result.replace( '*', '%' ) + "'";
    } else {
        return " = '" + result + "'";
    }
}

}
<commit_msg>Don't show house numbers if the user didn't search for them.<commit_after>//
// This file is part of the Marble Virtual Globe.
//
// This program is free software licensed under the GNU LGPL. You can
// find a copy of this license in LICENSE.txt in the top directory of
// the source code.
//
// Copyright 2011      Dennis Nienhüser <earthwings@gentoo.org>
//

#include "OsmDatabase.h"
#include "OsmRegion.h"
#include "MarbleDebug.h"
#include "MarbleMath.h"
#include "MarbleLocale.h"
#include "DatabaseQuery.h"

#include <QtCore/QFile>
#include <QtCore/QDataStream>
#include <QtCore/QStringList>
#include <QtCore/QRegExp>
#include <QtCore/QVariant>
#include <QtCore/QTime>

#include <QtSql/QSqlDatabase>
#include <QtSql/QSqlQuery>
#include <QtSql/QSqlError>

namespace Marble {

OsmDatabase::OsmDatabase()
{
    m_database = QSqlDatabase::addDatabase( "QSQLITE" );
}

void OsmDatabase::addFile( const QString &fileName )
{
    m_databases << fileName;
}

QList<OsmPlacemark> OsmDatabase::find( MarbleModel* model, const QString &searchTerm )
{
    if ( m_databases.isEmpty() ) {
        return QList<OsmPlacemark>();
    }

    DatabaseQuery userQuery( model, searchTerm );

    QString queryString;

    queryString = " SELECT regions.name,"
            " places.name, places.number,"
            " places.category, places.lon, places.lat"
            " FROM regions, places";

    if ( userQuery.queryType() == DatabaseQuery::CategorySearch ) {
        queryString += " WHERE regions.id = places.region AND places.category = %1";
        queryString = queryString.arg( (qint32) userQuery.category() );
        if ( userQuery.resultFormat() == DatabaseQuery::DistanceFormat && userQuery.region().isEmpty() ) {
            queryString += " ORDER BY ((places.lat-%1)*(places.lat-%1)+(places.lon-%2)*(places.lon-%2))";
            GeoDataCoordinates position = userQuery.position();
            queryString = queryString.arg( position.latitude( GeoDataCoordinates::Degree ), 0, 'f', 8 )
                    .arg( position.longitude( GeoDataCoordinates::Degree ), 0, 'f', 8 );
        } else {
            queryString += " AND regions.name LIKE '%" + userQuery.region() + "%'";
        }
    } else if ( userQuery.queryType() == DatabaseQuery::BroadSearch ) {
        queryString += " WHERE regions.id = places.region"
                " AND places.name " + wildcardQuery( searchTerm );
    } else {
        queryString += " WHERE regions.id = places.region"
                "   AND places.name " + wildcardQuery( userQuery.street() );
        if ( !userQuery.houseNumber().isEmpty() ) {
            queryString += " AND places.number " + wildcardQuery( userQuery.houseNumber() );
        } else {
            queryString += "AND places.number IS NULL";
        }
        queryString += " AND regions.name LIKE '%" + userQuery.region() + "%'";
    }

    queryString += " LIMIT 50;";

    QList<OsmPlacemark> result;
    QTime timer;
    timer.start();
    foreach( const QString &databaseFile, m_databases ) {
        /** @todo: sort/filter results from several databases */

        m_database.setDatabaseName( databaseFile );
        if ( !m_database.open() ) {
            mDebug() << "Failed to connect to database " << databaseFile;
        }

        QSqlQuery query;
        query.setForwardOnly( true );
        if ( !query.exec( queryString ) ) {
            mDebug() << "Failed to execute query: " << query.lastError();
            return result;
        }

        while ( query.next() ) {
            OsmPlacemark placemark;
            if ( userQuery.resultFormat() == DatabaseQuery::DistanceFormat ) {
                GeoDataCoordinates coordinates( query.value(4).toFloat(), query.value(5).toFloat(), 0.0, GeoDataCoordinates::Degree );
                placemark.setAdditionalInformation( formatDistance( coordinates, userQuery.position() ) );
            } else {
                placemark.setAdditionalInformation( query.value( 0 ).toString() );
            }
            placemark.setName( query.value(1).toString() );
            placemark.setHouseNumber( query.value(2).toString() );
            placemark.setCategory( (OsmPlacemark::OsmCategory) query.value(3).toInt() );
            placemark.setLongitude( query.value(4).toFloat() );
            placemark.setLatitude( query.value(5).toFloat() );
            result.push_back( placemark );
        }
    }

    qDebug() << "Offline OSM search query took " << timer.elapsed() << " ms. Query: " << queryString;
    return result;
}

QString OsmDatabase::formatDistance( const GeoDataCoordinates &a, const GeoDataCoordinates &b ) const
{
    qreal distance = EARTH_RADIUS * distanceSphere( a, b);

    int precision = 0;
    QString distanceUnit = "m";

    if ( MarbleGlobal::getInstance()->locale()->distanceUnit() == Marble::MilesFeet ) {
        precision = 1;
        distanceUnit = "mi";
        distance *= METER2KM;
        distance *= KM2MI;
    } else {
        if ( distance >= 1000 ) {
            distance /= 1000;
            distanceUnit = "km";
            precision = 1;
        } else if ( distance >= 200 ) {
            distance = 50 * qRound( distance / 50 );
        } else if ( distance >= 100 ) {
            distance = 25 * qRound( distance / 25 );
        } else {
            distance = 10 * qRound( distance / 10 );
        }
    }

    QString const fuzzyDistance = QString( "%1 %2" ).arg( distance, 0, 'f', precision ).arg( distanceUnit );

    int direction = 180 + bearing( a, b ) * RAD2DEG;

    QString heading = QObject::tr( "north" );
    if ( direction > 337 ) {
        heading = QObject::tr( "north" );
    } else if ( direction > 292 ) {
        heading = QObject::tr( "north-west" );
    } else if ( direction > 247 ) {
        heading = QObject::tr( "west" );
    } else if ( direction > 202 ) {
        heading = QObject::tr( "south-west" );
    } else if ( direction > 157 ) {
        heading = QObject::tr( "south" );
    } else if ( direction > 112 ) {
        heading = QObject::tr( "south-east" );
    } else if ( direction > 67 ) {
        heading = QObject::tr( "east" );
    } else if ( direction > 22 ) {
        heading = QObject::tr( "north-east" );
    }

    return fuzzyDistance + " " + heading;
}

qreal OsmDatabase::bearing( const GeoDataCoordinates &a, const GeoDataCoordinates &b ) const
{
    qreal delta = b.longitude() - a.longitude();
    qreal lat1 = a.latitude();
    qreal lat2 = b.latitude();
    return fmod( atan2( sin ( delta ) * cos ( lat2 ),
                       cos( lat1 ) * sin( lat2 ) - sin( lat1 ) * cos( lat2 ) * cos ( delta ) ), 2 * M_PI );
}

QString OsmDatabase::wildcardQuery( const QString &term ) const
{
    QString result = term;
    if ( term.contains( '*' ) ) {
        return " LIKE '" + result.replace( '*', '%' ) + "'";
    } else {
        return " = '" + result + "'";
    }
}

}
<|endoftext|>