<commit_before>/*
    Copyright 2012 Sebastian Sauer <sebastian.sauer@kdab.com>

    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) version 3, or any
    later version accepted by the membership of KDE e.V. (or its
    successor approved by the membership of KDE e.V.), which shall
    act as a proxy defined in Section 6 of version 3 of the license.

    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, see <http://www.gnu.org/licenses/>.
*/

#include "accessibleproperties.h"

#include "qaccessibilityclient/accessibleobject.h"
#include "qaccessibilityclient/registry.h"

using namespace QAccessibleClient;

ObjectProperties::ObjectProperties(QObject *parent)
    : QStandardItemModel(parent)
{
}

ObjectProperties::~ObjectProperties()
{
}

void ObjectProperties::setAccessibleObject(const QAccessibleClient::AccessibleObject &acc)
{
    beginResetModel();

    clear();
    setColumnCount(2);
    setHorizontalHeaderLabels( QStringList() << QString("Property") << QString("Value") );

    if (!acc.isValid()) {
        endResetModel();
        return;
    }

    QAccessibleClient::AccessibleObject::Interfaces interfaces = acc.supportedInterfaces();
    if (interfaces.testFlag(QAccessibleClient::AccessibleObject::AccessibleInterface)) {
        QStandardItem *item = append(QString("Accessible"));
        append(QString("Name"), acc.name(), item);
        append(QString("Description"), acc.description(), item);
        append(QString("Role"), acc.roleName(), item);
        append(QString("LocalizedRole"), acc.localizedRoleName(), item);
        append(QString("Visible"), acc.isVisible(), item);
        append(QString("Default"), acc.isDefault(), item);
        append(QString("State"), stateString(acc), item);
        append(tr("Url"), acc.url(), item);
        AccessibleObject parent = acc.parent();
        if (parent.isValid())
            append(tr("Parent"), parent.url(), item);
        int childCount = acc.childCount();
        QStandardItem *children = append(QString("Children"), acc.childCount(), item);
        for (int i = 0; i < childCount; ++i) {
            AccessibleObject child = acc.child(i);
            if (!child.isValid()) {
                append(QLatin1String("Broken child"), QString::number(i), children);
            } else {
                append(child.name().isEmpty() ? tr("[%1]").arg(child.roleName()) : child.name(), child.url(), children);
            }
        }
        //GetAttributes
    }
    if (interfaces.testFlag(QAccessibleClient::AccessibleObject::ComponentInterface)) {
        QStandardItem *item = append(QString("Component"));
        append(QString("BoundingRect"), acc.boundingRect(), item);
        append(QString("Layer"), acc.layer(), item);
        append(QString("MDIZOrder"), acc.mdiZOrder(), item);
        append(QString("Alpha"), acc.alpha(), item);
    }
    if (interfaces.testFlag(QAccessibleClient::AccessibleObject::CollectionInterface)) {
        QStandardItem *item = append(QString("Collection"));
        Q_UNUSED(item);
    }
    if (interfaces.testFlag(QAccessibleClient::AccessibleObject::ApplicationInterface)) {
        QStandardItem *item = append(QString("Application"));
        append(QString("ToolkitName"), acc.appToolkitName(), item);
        append(QString("Version"), acc.appVersion(), item);
        append(QString("Id"), acc.appId(), item);
        append(QString("Locale"), acc.appLocale(), item);
        append(QString("BusAddress"), acc.appBusAddress(), item);
    }
    if (interfaces.testFlag(QAccessibleClient::AccessibleObject::DocumentInterface)) {
        QStandardItem *item = append(QString("Document"));
        Q_UNUSED(item);
        //GetLocale
        //GetAttributeValue
        //GetAttributes
    }

    if (interfaces.testFlag(QAccessibleClient::AccessibleObject::EditableTextInterface)) {
        QStandardItem *item = append(QString("EditableText"));
        Q_UNUSED(item);
    }
    if (interfaces.testFlag(QAccessibleClient::AccessibleObject::HyperlinkInterface)) {
        QStandardItem *item = append(QString("Hyperlink"));
        Q_UNUSED(item);
        /*
        <property name="NAnchors" type="n" access="read"/>
        <property name="StartIndex" type="i" access="read"/>
        <property name="EndIndex" type="i" access="read"/>
        <method name="GetObject">
            <arg direction="in" name="i" type="i"/>
            <arg direction="out" type="(so)"/>
            <annotation name="com.trolltech.QtDBus.QtTypeName.Out0" value="QSpiObjectReference"/>
        </method>
        0<method name="GetURI">
            <arg direction="in" name="i" type="i"/>
            <arg direction="out" type="s"/>
        </method>
        <method name="IsValid">
            <arg direction="out" type="b"/>
        </method>
        */
    }
    if (interfaces.testFlag(QAccessibleClient::AccessibleObject::HypertextInterface)) {
        QStandardItem *item = append(QString("Hypertext"));
        Q_UNUSED(item);
        /*
        <method name="GetNLinks">
            <arg direction="out" type="i"/>
        </method>
        <method name="GetLink">
            <arg direction="in" name="linkIndex" type="i"/>
            <arg direction="out" type="(so)"/>
            <annotation name="com.trolltech.QtDBus.QtTypeName.Out0" value="QSpiObjectReference"/>
        </method>
        <method name="GetLinkIndex">
            <arg direction="in" name="characterIndex" type="i"/>
            <arg direction="out" type="i"/>
        </method>
        */
    }
    if (interfaces.testFlag(QAccessibleClient::AccessibleObject::ImageInterface)) {
        QStandardItem *item = append(QString("Image"));
        append(QString("Description"), acc.imageDescription(), item);
        append(QString("Locale"), acc.imageLocale(), item);
        append(QString("Rect"), acc.imageRect(), item);
    }
    if (interfaces.testFlag(QAccessibleClient::AccessibleObject::SelectionInterface)) {
        QStandardItem *item = append(QString("Selection"));
        Q_FOREACH(const QAccessibleClient::AccessibleObject &s, acc.selection()) {
            append(s.name(), s.role(), item);
        }
    }
    if (interfaces.testFlag(QAccessibleClient::AccessibleObject::TableInterface)) {
        QStandardItem *item = append(QString("Table"));
        Q_UNUSED(item);
        /*
        <property name="NRows" type="i" access="read"/>
        <property name="NColumns" type="i" access="read"/>
        <property name="Caption" type="(so)" access="read">
            <annotation name="com.trolltech.QtDBus.QtTypeName" value="QSpiObjectReference"/>
        </property>
        <property name="Summary" type="(so)" access="read">
            <annotation name="com.trolltech.QtDBus.QtTypeName" value="QSpiObjectReference"/>
        </property>
        <property name="NSelectedRows" type="i" access="read"/>
        <property name="NSelectedColumns" type="i" access="read"/>
        <method name="GetRowDescription">
            <arg direction="in" name="row" type="i"/>
            <arg direction="out" type="s"/>
        </method>
        <method name="GetColumnDescription">
            <arg direction="in" name="column" type="i"/>
            <arg direction="out" type="s"/>
        </method>
        <method name="GetSelectedRows">
            <arg direction="out" type="ai"/>
            <annotation name="com.trolltech.QtDBus.QtTypeName.Out0" value="QSpiIntList"/>
        </method>
        <method name="GetSelectedColumns">
            <arg direction="out" type="ai"/>
            <annotation name="com.trolltech.QtDBus.QtTypeName.Out0" value="QSpiIntList"/>
        </method>
        */
    }
    if (interfaces.testFlag(QAccessibleClient::AccessibleObject::TextInterface)) {
        QStandardItem *item = append(QString("Text"));
        int offset = acc.caretOffset();
        append(QString("CaretOffset"), offset, item);
        append(QString("CharacterRect"), acc.characterRect(offset), item);
    }
    if (interfaces.testFlag(QAccessibleClient::AccessibleObject::ValueInterface)) {
        QStandardItem *item = append(QString("Value"));
        append(QString("Current"), acc.currentValue(), item);
        append(QString("Minimum"), acc.minimumValue(), item);
        append(QString("Maximum"), acc.maximumValue(), item);
        append(QString("Increment"), acc.minimumValueIncrement(), item);
    }
    if (interfaces.testFlag(QAccessibleClient::AccessibleObject::SocketInterface)) {
        QStandardItem *item = append(QString("Socket"));
        Q_UNUSED(item);
    }

    if (interfaces.testFlag(QAccessibleClient::AccessibleObject::EventKeyboardInterface)) {
        QStandardItem *item = append(QString("EventKeyboard"));
        Q_UNUSED(item);
    }
    if (interfaces.testFlag(QAccessibleClient::AccessibleObject::EventMouseInterface)) {
        QStandardItem *item = append(QString("EventMouse"));
        Q_UNUSED(item);
    }
    if (interfaces.testFlag(QAccessibleClient::AccessibleObject::EventObjectInterface)) {
        QStandardItem *item = append(QString("EventObject"));
        Q_UNUSED(item);
    }
    if (interfaces.testFlag(QAccessibleClient::AccessibleObject::EventWindowInterface)) {
        QStandardItem *item = append(QString("EventWindow"));
        Q_UNUSED(item);
    }
    if (interfaces.testFlag(QAccessibleClient::AccessibleObject::EventFocusInterface)) {
        QStandardItem *item = append(QString("EventFocus"));
        Q_UNUSED(item);
    }

    if (interfaces.testFlag(QAccessibleClient::AccessibleObject::ActionInterface)) {
        QStandardItem *item = append(QString("Action"));
        Q_FOREACH(const QSharedPointer<QAction> &a, acc.actions()) {
            QStandardItem *nameItem = new QStandardItem(a->text());
            QStandardItem *valueItem = new QStandardItem(a->whatsThis());
            item->appendRow(QList<QStandardItem*>() << nameItem << valueItem);
        }
    }

    endResetModel();
}

QStandardItem* ObjectProperties::append(const QString &name, const QVariant &value, QStandardItem *parentItem)
{
    if (!parentItem)
        parentItem = invisibleRootItem();
    QStandardItem *nameItem = new QStandardItem(name);
    QString text;
    switch (value.type()) {
        case QVariant::Point: {
            QPoint p = value.toPoint();
            text = QString("%1:%2").arg(p.x()).arg(p.y());
        } break;
        case QVariant::PointF: {
            QPointF p = value.toPointF();
            text = QString("%1:%2").arg(p.x()).arg(p.y());
        } break;
        case QVariant::Rect: {
            QRect r = value.toRect();
            text = QString("%1:%2 %3x%4").arg(r.left()).arg(r.top()).arg(r.width()).arg(r.height());
        } break;
        case QVariant::RectF: {
            QRectF r = value.toRectF();
            text = QString("%1:%2 %3x%4").arg(r.left()).arg(r.top()).arg(r.width()).arg(r.height());
        } break;
        default:
            text = value.toString();
            break;
    }
    QStandardItem *valueItem = new QStandardItem(text);
    parentItem->appendRow(QList<QStandardItem*>() << nameItem << valueItem);
    return nameItem;
}

QString ObjectProperties::stateString(const QAccessibleClient::AccessibleObject &acc)
{
    QStringList s;
    if (acc.isActive()) s << "Active";
    if (acc.isCheckable()) s << "Checkable";
    if (acc.isChecked()) s << "Checked";
    if (acc.isEditable()) s << "Editable";
    if (acc.isExpandable()) s << "Expandable";
    if (acc.isExpanded()) s << "Expanded";
    if (acc.isFocusable()) s << "Focusable";
    if (acc.isFocused()) s << "Focused";
    if (acc.isMultiLine()) s << "MultiLine";
    if (acc.isSelectable()) s << "Selectable";
    if (acc.isSelected()) s << "Selected";
    if (acc.isSensitive()) s << "Sensitive";
    if (acc.isSingleLine()) s << "SingleLine";
    return s.join(",");
}
<commit_msg>Display the TextInterface's caretCount and text in the properties docker<commit_after>/*
    Copyright 2012 Sebastian Sauer <sebastian.sauer@kdab.com>

    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) version 3, or any
    later version accepted by the membership of KDE e.V. (or its
    successor approved by the membership of KDE e.V.), which shall
    act as a proxy defined in Section 6 of version 3 of the license.

    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, see <http://www.gnu.org/licenses/>.
*/

#include "accessibleproperties.h"

#include "qaccessibilityclient/accessibleobject.h"
#include "qaccessibilityclient/registry.h"

using namespace QAccessibleClient;

ObjectProperties::ObjectProperties(QObject *parent)
    : QStandardItemModel(parent)
{
}

ObjectProperties::~ObjectProperties()
{
}

void ObjectProperties::setAccessibleObject(const QAccessibleClient::AccessibleObject &acc)
{
    beginResetModel();

    clear();
    setColumnCount(2);
    setHorizontalHeaderLabels( QStringList() << QString("Property") << QString("Value") );

    if (!acc.isValid()) {
        endResetModel();
        return;
    }

    QAccessibleClient::AccessibleObject::Interfaces interfaces = acc.supportedInterfaces();
    if (interfaces.testFlag(QAccessibleClient::AccessibleObject::AccessibleInterface)) {
        QStandardItem *item = append(QString("Accessible"));
        append(QString("Name"), acc.name(), item);
        append(QString("Description"), acc.description(), item);
        append(QString("Role"), acc.roleName(), item);
        append(QString("LocalizedRole"), acc.localizedRoleName(), item);
        append(QString("Visible"), acc.isVisible(), item);
        append(QString("Default"), acc.isDefault(), item);
        append(QString("State"), stateString(acc), item);
        append(tr("Url"), acc.url(), item);
        AccessibleObject parent = acc.parent();
        if (parent.isValid())
            append(tr("Parent"), parent.url(), item);
        int childCount = acc.childCount();
        QStandardItem *children = append(QString("Children"), acc.childCount(), item);
        for (int i = 0; i < childCount; ++i) {
            AccessibleObject child = acc.child(i);
            if (!child.isValid()) {
                append(QLatin1String("Broken child"), QString::number(i), children);
            } else {
                append(child.name().isEmpty() ? tr("[%1]").arg(child.roleName()) : child.name(), child.url(), children);
            }
        }
        //GetAttributes
    }
    if (interfaces.testFlag(QAccessibleClient::AccessibleObject::ComponentInterface)) {
        QStandardItem *item = append(QString("Component"));
        append(QString("BoundingRect"), acc.boundingRect(), item);
        append(QString("Layer"), acc.layer(), item);
        append(QString("MDIZOrder"), acc.mdiZOrder(), item);
        append(QString("Alpha"), acc.alpha(), item);
    }
    if (interfaces.testFlag(QAccessibleClient::AccessibleObject::CollectionInterface)) {
        QStandardItem *item = append(QString("Collection"));
        Q_UNUSED(item);
    }
    if (interfaces.testFlag(QAccessibleClient::AccessibleObject::ApplicationInterface)) {
        QStandardItem *item = append(QString("Application"));
        append(QString("ToolkitName"), acc.appToolkitName(), item);
        append(QString("Version"), acc.appVersion(), item);
        append(QString("Id"), acc.appId(), item);
        append(QString("Locale"), acc.appLocale(), item);
        append(QString("BusAddress"), acc.appBusAddress(), item);
    }
    if (interfaces.testFlag(QAccessibleClient::AccessibleObject::DocumentInterface)) {
        QStandardItem *item = append(QString("Document"));
        Q_UNUSED(item);
        //GetLocale
        //GetAttributeValue
        //GetAttributes
    }

    if (interfaces.testFlag(QAccessibleClient::AccessibleObject::EditableTextInterface)) {
        QStandardItem *item = append(QString("EditableText"));
        Q_UNUSED(item);
    }
    if (interfaces.testFlag(QAccessibleClient::AccessibleObject::HyperlinkInterface)) {
        QStandardItem *item = append(QString("Hyperlink"));
        Q_UNUSED(item);
        /*
        <property name="NAnchors" type="n" access="read"/>
        <property name="StartIndex" type="i" access="read"/>
        <property name="EndIndex" type="i" access="read"/>
        <method name="GetObject">
            <arg direction="in" name="i" type="i"/>
            <arg direction="out" type="(so)"/>
            <annotation name="com.trolltech.QtDBus.QtTypeName.Out0" value="QSpiObjectReference"/>
        </method>
        0<method name="GetURI">
            <arg direction="in" name="i" type="i"/>
            <arg direction="out" type="s"/>
        </method>
        <method name="IsValid">
            <arg direction="out" type="b"/>
        </method>
        */
    }
    if (interfaces.testFlag(QAccessibleClient::AccessibleObject::HypertextInterface)) {
        QStandardItem *item = append(QString("Hypertext"));
        Q_UNUSED(item);
        /*
        <method name="GetNLinks">
            <arg direction="out" type="i"/>
        </method>
        <method name="GetLink">
            <arg direction="in" name="linkIndex" type="i"/>
            <arg direction="out" type="(so)"/>
            <annotation name="com.trolltech.QtDBus.QtTypeName.Out0" value="QSpiObjectReference"/>
        </method>
        <method name="GetLinkIndex">
            <arg direction="in" name="characterIndex" type="i"/>
            <arg direction="out" type="i"/>
        </method>
        */
    }
    if (interfaces.testFlag(QAccessibleClient::AccessibleObject::ImageInterface)) {
        QStandardItem *item = append(QString("Image"));
        append(QString("Description"), acc.imageDescription(), item);
        append(QString("Locale"), acc.imageLocale(), item);
        append(QString("Rect"), acc.imageRect(), item);
    }
    if (interfaces.testFlag(QAccessibleClient::AccessibleObject::SelectionInterface)) {
        QStandardItem *item = append(QString("Selection"));
        Q_FOREACH(const QAccessibleClient::AccessibleObject &s, acc.selection()) {
            append(s.name(), s.role(), item);
        }
    }
    if (interfaces.testFlag(QAccessibleClient::AccessibleObject::TableInterface)) {
        QStandardItem *item = append(QString("Table"));
        Q_UNUSED(item);
        /*
        <property name="NRows" type="i" access="read"/>
        <property name="NColumns" type="i" access="read"/>
        <property name="Caption" type="(so)" access="read">
            <annotation name="com.trolltech.QtDBus.QtTypeName" value="QSpiObjectReference"/>
        </property>
        <property name="Summary" type="(so)" access="read">
            <annotation name="com.trolltech.QtDBus.QtTypeName" value="QSpiObjectReference"/>
        </property>
        <property name="NSelectedRows" type="i" access="read"/>
        <property name="NSelectedColumns" type="i" access="read"/>
        <method name="GetRowDescription">
            <arg direction="in" name="row" type="i"/>
            <arg direction="out" type="s"/>
        </method>
        <method name="GetColumnDescription">
            <arg direction="in" name="column" type="i"/>
            <arg direction="out" type="s"/>
        </method>
        <method name="GetSelectedRows">
            <arg direction="out" type="ai"/>
            <annotation name="com.trolltech.QtDBus.QtTypeName.Out0" value="QSpiIntList"/>
        </method>
        <method name="GetSelectedColumns">
            <arg direction="out" type="ai"/>
            <annotation name="com.trolltech.QtDBus.QtTypeName.Out0" value="QSpiIntList"/>
        </method>
        */
    }
    if (interfaces.testFlag(QAccessibleClient::AccessibleObject::TextInterface)) {
        QStandardItem *item = append(QString("Text"));
        int offset = acc.caretOffset();
        append(QString("CaretOffset"), offset, item);
        append(QString("CaretCount"), acc.caretCount(), item);
        append(QString("CharacterRect"), acc.characterRect(offset), item);
        append(QString("Text"), acc.text(), item);
    }
    if (interfaces.testFlag(QAccessibleClient::AccessibleObject::ValueInterface)) {
        QStandardItem *item = append(QString("Value"));
        append(QString("Current"), acc.currentValue(), item);
        append(QString("Minimum"), acc.minimumValue(), item);
        append(QString("Maximum"), acc.maximumValue(), item);
        append(QString("Increment"), acc.minimumValueIncrement(), item);
    }
    if (interfaces.testFlag(QAccessibleClient::AccessibleObject::SocketInterface)) {
        QStandardItem *item = append(QString("Socket"));
        Q_UNUSED(item);
    }

    if (interfaces.testFlag(QAccessibleClient::AccessibleObject::EventKeyboardInterface)) {
        QStandardItem *item = append(QString("EventKeyboard"));
        Q_UNUSED(item);
    }
    if (interfaces.testFlag(QAccessibleClient::AccessibleObject::EventMouseInterface)) {
        QStandardItem *item = append(QString("EventMouse"));
        Q_UNUSED(item);
    }
    if (interfaces.testFlag(QAccessibleClient::AccessibleObject::EventObjectInterface)) {
        QStandardItem *item = append(QString("EventObject"));
        Q_UNUSED(item);
    }
    if (interfaces.testFlag(QAccessibleClient::AccessibleObject::EventWindowInterface)) {
        QStandardItem *item = append(QString("EventWindow"));
        Q_UNUSED(item);
    }
    if (interfaces.testFlag(QAccessibleClient::AccessibleObject::EventFocusInterface)) {
        QStandardItem *item = append(QString("EventFocus"));
        Q_UNUSED(item);
    }

    if (interfaces.testFlag(QAccessibleClient::AccessibleObject::ActionInterface)) {
        QStandardItem *item = append(QString("Action"));
        Q_FOREACH(const QSharedPointer<QAction> &a, acc.actions()) {
            QStandardItem *nameItem = new QStandardItem(a->text());
            QStandardItem *valueItem = new QStandardItem(a->whatsThis());
            item->appendRow(QList<QStandardItem*>() << nameItem << valueItem);
        }
    }

    endResetModel();
}

QStandardItem* ObjectProperties::append(const QString &name, const QVariant &value, QStandardItem *parentItem)
{
    if (!parentItem)
        parentItem = invisibleRootItem();
    QStandardItem *nameItem = new QStandardItem(name);
    QString text;
    switch (value.type()) {
        case QVariant::Point: {
            QPoint p = value.toPoint();
            text = QString("%1:%2").arg(p.x()).arg(p.y());
        } break;
        case QVariant::PointF: {
            QPointF p = value.toPointF();
            text = QString("%1:%2").arg(p.x()).arg(p.y());
        } break;
        case QVariant::Rect: {
            QRect r = value.toRect();
            text = QString("%1:%2 %3x%4").arg(r.left()).arg(r.top()).arg(r.width()).arg(r.height());
        } break;
        case QVariant::RectF: {
            QRectF r = value.toRectF();
            text = QString("%1:%2 %3x%4").arg(r.left()).arg(r.top()).arg(r.width()).arg(r.height());
        } break;
        default:
            text = value.toString();
            break;
    }
    QStandardItem *valueItem = new QStandardItem(text);
    parentItem->appendRow(QList<QStandardItem*>() << nameItem << valueItem);
    return nameItem;
}

QString ObjectProperties::stateString(const QAccessibleClient::AccessibleObject &acc)
{
    QStringList s;
    if (acc.isActive()) s << "Active";
    if (acc.isCheckable()) s << "Checkable";
    if (acc.isChecked()) s << "Checked";
    if (acc.isEditable()) s << "Editable";
    if (acc.isExpandable()) s << "Expandable";
    if (acc.isExpanded()) s << "Expanded";
    if (acc.isFocusable()) s << "Focusable";
    if (acc.isFocused()) s << "Focused";
    if (acc.isMultiLine()) s << "MultiLine";
    if (acc.isSelectable()) s << "Selectable";
    if (acc.isSelected()) s << "Selected";
    if (acc.isSensitive()) s << "Sensitive";
    if (acc.isSingleLine()) s << "SingleLine";
    return s.join(",");
}
<|endoftext|>


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

#include <thrust/detail/config.h>
#include <thrust/find.h>
#include <thrust/reduce.h>

#include <thrust/tuple.h>
#include <thrust/extrema.h>
#include <thrust/iterator/counting_iterator.h>
#include <thrust/iterator/transform_iterator.h>
#include <thrust/iterator/zip_iterator.h>
#include <thrust/detail/internal_functional.h>

// Contributed by Erich Elsen

namespace thrust
{
namespace system
{
namespace detail
{
namespace generic
{

template<typename DerivedPolicy, typename InputIterator, typename T>
InputIterator find(thrust::execution_policy<DerivedPolicy> &exec,
                   InputIterator first,
                   InputIterator last,
                   const T& value)
{
  // XXX consider a placeholder expression here
  return thrust::find_if(exec, first, last, thrust::detail::equal_to_value<T>(value));
} // end find()

template<typename TupleType>
struct find_if_functor
{
    __host__ __device__
    TupleType operator()(const TupleType& lhs, const TupleType& rhs) const
    {
        // select the smallest index among true results
        if (thrust::get<0>(lhs) && thrust::get<0>(rhs))
            return TupleType(true, (thrust::min)(thrust::get<1>(lhs), thrust::get<1>(rhs)));
        else if (thrust::get<0>(lhs))
            return lhs;
        else
            return rhs;
    }
};

template<typename DerivedPolicy, typename InputIterator, typename Predicate>
InputIterator find_if(thrust::execution_policy<DerivedPolicy> &exec,
                      InputIterator first,
                      InputIterator last,
                      Predicate pred)
{
    typedef typename thrust::iterator_traits<InputIterator>::difference_type difference_type;
    typedef typename thrust::tuple<bool,difference_type> result_type;

    // empty sequence
    if (first == last)
        return last;

    const difference_type n = thrust::distance(first, last);

    // this implementation breaks up the sequence into separate intervals
    // in an attempt to early-out as soon as a value is found

    // TODO incorporate sizeof(InputType) into interval_threshold and round to multiple of 32
    const difference_type interval_threshold = 1 << 20;
    const difference_type interval_size = (std::min)(interval_threshold, n);

    // force transform_iterator output to bool
    typedef thrust::transform_iterator<Predicate, InputIterator, bool> XfrmIterator;
    typedef thrust::tuple<XfrmIterator, thrust::counting_iterator<difference_type> > IteratorTuple;
    typedef thrust::zip_iterator<IteratorTuple> ZipIterator;

    IteratorTuple iter_tuple = thrust::make_tuple(XfrmIterator(first, pred),
                                                  thrust::counting_iterator<difference_type>(0));

    ZipIterator begin = thrust::make_zip_iterator(iter_tuple);
    ZipIterator end   = begin + n;

    for(ZipIterator interval_begin = begin; interval_begin < end; interval_begin += interval_size)
    {
        ZipIterator interval_end = interval_begin + interval_size;
        if(end < interval_end)
        {
          interval_end = end;
        } // end if

        result_type result = thrust::reduce(exec,
                                            interval_begin, interval_end,
                                            result_type(false,interval_end - begin),
                                            find_if_functor<result_type>());

        // see if we found something
        if (thrust::get<0>(result))
        {
            return first + thrust::get<1>(result);
        }
    }

    //nothing was found if we reach here...
    return first + n;
}

template<typename DerivedPolicy, typename InputIterator, typename Predicate>
InputIterator find_if_not(thrust::execution_policy<DerivedPolicy> &exec,
                          InputIterator first,
                          InputIterator last,
                          Predicate pred)
{
    return thrust::find_if(exec, first, last, thrust::detail::not1(pred));
} // end find()

} // end namespace generic
} // end namespace detail
} // end namespace system
} // end namespace thrust

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

#include <thrust/detail/config.h>
#include <thrust/find.h>
#include <thrust/reduce.h>

#include <thrust/tuple.h>
#include <thrust/extrema.h>
#include <thrust/iterator/counting_iterator.h>
#include <thrust/iterator/transform_iterator.h>
#include <thrust/iterator/zip_iterator.h>
#include <thrust/detail/internal_functional.h>

// Contributed by Erich Elsen

namespace thrust
{
namespace system
{
namespace detail
{
namespace generic
{

template<typename DerivedPolicy, typename InputIterator, typename T>
InputIterator find(thrust::execution_policy<DerivedPolicy> &exec,
                   InputIterator first,
                   InputIterator last,
                   const T& value)
{
  // XXX consider a placeholder expression here
  return thrust::find_if(exec, first, last, thrust::detail::equal_to_value<T>(value));
} // end find()

template<typename TupleType>
struct find_if_functor
{
    __host__ __device__
    TupleType operator()(const TupleType& lhs, const TupleType& rhs) const
    {
        // select the smallest index among true results
        if (thrust::get<0>(lhs) && thrust::get<0>(rhs))
            return TupleType(true, (thrust::min)(thrust::get<1>(lhs), thrust::get<1>(rhs)));
        else if (thrust::get<0>(lhs))
            return lhs;
        else
            return rhs;
    }
};

template<typename DerivedPolicy, typename InputIterator, typename Predicate>
InputIterator find_if(thrust::execution_policy<DerivedPolicy> &exec,
                      InputIterator first,
                      InputIterator last,
                      Predicate pred)
{
    typedef typename thrust::iterator_traits<InputIterator>::difference_type difference_type;
    typedef typename thrust::tuple<bool,difference_type> result_type;

    // empty sequence
    if (first == last)
        return last;

    const difference_type n = thrust::distance(first, last);

    // this implementation breaks up the sequence into separate intervals
    // in an attempt to early-out as soon as a value is found

    // TODO incorporate sizeof(InputType) into interval_threshold and round to multiple of 32
    const difference_type interval_threshold = 1 << 20;
    const difference_type interval_size = (thrust::min)(interval_threshold, n);

    // force transform_iterator output to bool
    typedef thrust::transform_iterator<Predicate, InputIterator, bool> XfrmIterator;
    typedef thrust::tuple<XfrmIterator, thrust::counting_iterator<difference_type> > IteratorTuple;
    typedef thrust::zip_iterator<IteratorTuple> ZipIterator;

    IteratorTuple iter_tuple = thrust::make_tuple(XfrmIterator(first, pred),
                                                  thrust::counting_iterator<difference_type>(0));

    ZipIterator begin = thrust::make_zip_iterator(iter_tuple);
    ZipIterator end   = begin + n;

    for(ZipIterator interval_begin = begin; interval_begin < end; interval_begin += interval_size)
    {
        ZipIterator interval_end = interval_begin + interval_size;
        if(end < interval_end)
        {
          interval_end = end;
        } // end if

        result_type result = thrust::reduce(exec,
                                            interval_begin, interval_end,
                                            result_type(false,interval_end - begin),
                                            find_if_functor<result_type>());

        // see if we found something
        if (thrust::get<0>(result))
        {
            return first + thrust::get<1>(result);
        }
    }

    //nothing was found if we reach here...
    return first + n;
}

template<typename DerivedPolicy, typename InputIterator, typename Predicate>
InputIterator find_if_not(thrust::execution_policy<DerivedPolicy> &exec,
                          InputIterator first,
                          InputIterator last,
                          Predicate pred)
{
    return thrust::find_if(exec, first, last, thrust::detail::not1(pred));
} // end find()

} // end namespace generic
} // end namespace detail
} // end namespace system
} // end namespace thrust

<|endoftext|>


<commit_before>#include <stdio.h>
#include <stdlib.h>
#include <errno.h>
#include <unistd.h>

#include <getopt.h>
#include <string.h>

#include <bgzf.h>

#include <vector>
#include <string>

#define TILE_ASSEMBLY_TOOL "0.1.0"

#define DEFAULT_TILE_ASSEMBLY_FILE "assembly.00.hg19.fw.gz"

static struct option long_options[] = {
  {"help",                no_argument,        NULL, 'h'},
  {"version",             no_argument,        NULL, 'v'},
  {"verbose",             no_argument,        NULL, 'V'},
  {"input",               required_argument,  NULL, 'i'},
  {0,0,0,0}
};

typedef struct ta_opt_type {
  int show_header;
  int debug;
} ta_opt_t;

void show_version() {
  printf("Version: %s\n", TILE_ASSEMBLY_TOOL);
}

void show_help() {
  printf("Tile Assembly Tool\n");
  printf("\n");
  printf("usage:\n");
  printf("  tile-assembly <action> ...\n");
  printf("\n");
  printf("  [-v]        version\n");
  printf("  [-V]        verbose\n");
  printf("  [-i ifn]    input\n");
  printf("\n");
}

int split_tok_ch(std::vector< std::string > &tok_v, std::string &line, char field) {
  int i, j, k, n;
  std::string buf;

  n = (int)line.size();
  tok_v.clear();

  for (i=0; i<n; i++) {
    if (line[i]==field) {
      if (buf.size()>0) { tok_v.push_back(buf); }
      buf.clear();
      continue;
    }
    buf += line[i];
  }
  if (buf.size()>0) { tok_v.push_back(buf); }

  return 0;
}

int print_bgzf(const char *afn, long byte_offset, size_t byte_len) {
  int i, r;
  BGZF *bgzfp;
  char buf[1024];
  ssize_t sz=0;
  size_t buflen=1024, cur_len=0;

  if (!(bgzfp = bgzf_open(afn, "r"))) { return -1; }
  r = bgzf_index_load(bgzfp, afn, ".gzi");
  if (r<0) { goto cleanup_print_bgzf; }

  r = bgzf_useek(bgzfp, byte_offset, SEEK_SET);
  if (r<0) { goto cleanup_print_bgzf; }

  while (cur_len < byte_len) {
    if ((cur_len + buflen) <= byte_len ) {
      sz = bgzf_read(bgzfp, buf, sizeof(char)*buflen);
    } else {
      sz = bgzf_read(bgzfp, buf, sizeof(char)*(byte_len - cur_len));
    }
    if (sz<0) { r=-1; goto cleanup_print_bgzf; }
    for (i=0; i<sz; i++) { printf("%c", buf[i]); }
    cur_len += sz;
  }

  r=0;

cleanup_print_bgzf:
  bgzf_close(bgzfp);
  return r;
}

int tileassembly_index_info(const char *afn, const char *sfx, int tilepath, std::string &name, int *byte_offset, int *byte_len) {
  FILE *idx_fp;
  std::string idx_fn, line, field;
  std::vector< std::string > tok_v;
  int ch;
  const char *chp;
  char stilepath[32];

  snprintf(stilepath, 32, "%04x", tilepath);

  idx_fn = afn;
  idx_fn += sfx;
  if ((idx_fp = fopen(idx_fn.c_str(), "r"))==NULL) { return -1; }

  while (!feof(idx_fp)) {
    ch = fgetc(idx_fp);
    if ((ch=='\n') || (ch==EOF)) {
      if (line.size()==0) { continue; }

      split_tok_ch(tok_v, line, '\t');
      line.clear();

      if (tok_v.size()!=5) { continue; }

      name = tok_v[0];

      field = ":";
      field += stilepath;

      // tile path not found
      //
      if ((chp=strstr(tok_v[0].c_str(), field.c_str()))==NULL) {
        continue;
      }

      //printf("chp: %p %i %i\n", chp, (int)(tok_v[0].c_str() + tok_v[0].size() - chp), (int)field.size());

      if ((size_t)(tok_v[0].c_str() + tok_v[0].size() - chp) != field.size()) {
        continue;
      }

      *byte_offset = atoi(tok_v[2].c_str());
      *byte_len    = atoi(tok_v[1].c_str());

      fclose(idx_fp);

      return 0;
    }

    line += (char)ch;
  }

  fclose(idx_fp);

  return -1;
}

int print_tilepath(const char *afn, int tilepath, ta_opt_t *opt) {
  int r;
  FILE *idx_fp;
  std::string name;
  int ch;
  const char *chp;

  int byte_offset, byte_len;
  int print_header=0;

  print_header = opt->show_header;

  r = tileassembly_index_info(afn, ".fwi", tilepath, name, &byte_offset, &byte_len);
  if (r<0) { return r; }

  if (print_header) { printf(">%s\n", name.c_str()); }
  print_bgzf(afn, (long)byte_offset, (size_t)byte_len);
  return 0;
}

int tileassembly_end_pos(const char *afn, int tilepath, int *tilestep, int *ref_pos) {
  int i, r;
  BGZF *bgzfp;
  char buf[1024];
  ssize_t sz=0;
  size_t buflen=1024, cur_len=0;
  int byte_offset, byte_len;
  std::string name;
  std::string line;
  int char_count=0;
  int ch;
  std::vector< std::string > tok_v;

  int cur_tilestep=-1, cur_ref_pos=-1;

  r = tileassembly_index_info(afn, ".fwi", tilepath, name, &byte_offset, &byte_len);
  if (r<0) { return -1; }

  if (!(bgzfp = bgzf_open(afn, "r"))) { return -1; }
  r = bgzf_index_load(bgzfp, afn, ".gzi");
  if (r<0) { goto cleanup_print_bgzf; }

  r = bgzf_useek(bgzfp, byte_offset, SEEK_SET);
  if (r<0) { goto cleanup_print_bgzf; }

  r=-1;
  while ((ch=bgzf_getc(bgzfp))>=0) {
    char_count++;

    if ((ch<0) || (ch=='\n') || (char_count==byte_len)) {

      split_tok_ch(tok_v, line, '\t');
      line.clear();

      if (tok_v.size()!=2) { continue; }
      cur_tilestep = strtol(tok_v[0].c_str(), NULL, 16);
      cur_ref_pos = atoi(tok_v[1].c_str());
      r=0;
      continue;
    }

    if (char_count>=byte_len) { break; }

    line += (char)ch;
  }

  *tilestep = cur_tilestep;
  *ref_pos = cur_ref_pos;

cleanup_print_bgzf:
  bgzf_close(bgzfp);
  return r;
}

int print_range(const char *afn, int tilepath, ta_opt_t *opt) {
  int i, j, k, r;
  int prev_byte_offset, prev_byte_len;
  int byte_offset, byte_len;

  std::string tilepath_chrom, name, ref_name;
  std::vector< std::string > tok_v;

  int start_pos = 0;
  int show_header=0;

  int end_step, end_pos;

  show_header = opt->show_header;

  tileassembly_index_info(afn, ".fwi", tilepath, name, &byte_offset, &byte_len);
  split_tok_ch(tok_v, name, ':');
  if (tok_v.size()<3) { return -1; }

  ref_name = tok_v[0];
  tilepath_chrom = tok_v[1];

  if (tilepath>0) {
    tileassembly_index_info(afn, ".fwi", tilepath-1, name, &byte_offset, &byte_len);

    split_tok_ch(tok_v, name, ':');
    if (tok_v.size()<3) { return -1; }

    if (tok_v[1] != tilepath_chrom) { start_pos = 0; }
    else {
      r = tileassembly_end_pos(afn, tilepath-1, &k, &start_pos);
    }

  }

  r = tileassembly_end_pos(afn, tilepath, &end_step, &end_pos);

  if (show_header) {
    printf("#nstep\tbeg\tend\tchrom_name\tref_name\n");
  }
  printf("%i\t%i\t%i\t%s\t%s\n",
      end_step,
      start_pos,
      end_pos,
      tilepath_chrom.c_str(),
      ref_name.c_str() );

  return 0;
}

int main(int argc, char **argv ) {
  int i, j, k;
  int ch;
  int option_index;
  int verbose_flag = 0;
  int tilepath=-1;

  std::string assembly_fn, stilepath, action;

  ta_opt_t opt;

  char *chp;
  assembly_fn = DEFAULT_TILE_ASSEMBLY_FILE;

  opt.show_header = 0;
  opt.debug=0;

  chp = getenv("TILE_ASSEMBLY");
  if (chp) { assembly_fn = chp; }

  if (argc == 3) {
    action = argv[1];
    stilepath = argv[2];
  }

  else if (argc == 4) {
    action = argv[1];
    assembly_fn = argv[2];
    stilepath = argv[3];
  }

  else {
    show_help();
    exit(0);
  }

  tilepath = strtol(stilepath.c_str(), NULL, 16);

  /*
  while ((opt = getopt_long(argc-1, argv+1, "hvVi:", long_options, &option_index))!=-1) switch (opt) {
    case 0:
      fprintf(stderr, "sanity error, invalid option to parse, exiting\n");
      exit(-1);
      break;
    case 'v': show_version(); exit(0); break;
    case 'V': verbose_flag=1; break;
    case 'h':
    default: show_help(); exit(0); break;
  }
  */

  if (action == "tilepath") {
    print_tilepath(assembly_fn.c_str(), tilepath, &opt);
  }

  else if (action == "range") {
    opt.show_header=1;
    print_range(assembly_fn.c_str(), tilepath, &opt);
  }

  else {
    show_help();
    exit(0);
  }

}
<commit_msg>no issue #<commit_after>#include <stdio.h>
#include <stdlib.h>
#include <errno.h>
#include <unistd.h>

#include <getopt.h>
#include <string.h>

#include <bgzf.h>

#include <vector>
#include <string>

#define TILE_ASSEMBLY_TOOL "0.1.0"

#define DEFAULT_TILE_ASSEMBLY_FILE "assembly.00.hg19.fw.gz"

static struct option long_options[] = {
  {"help",                no_argument,        NULL, 'h'},
  {"version",             no_argument,        NULL, 'v'},
  {"verbose",             no_argument,        NULL, 'V'},
  {"input",               required_argument,  NULL, 'i'},
  {0,0,0,0}
};

typedef struct ta_opt_type {
  int show_header;
  int debug;
} ta_opt_t;

void show_version() {
  printf("Version: %s\n", TILE_ASSEMBLY_TOOL);
}

void show_help() {
  printf("\n");
  printf("Tile Assembly Tool\n");
  printf("\n");
  printf("usage:\n");
  printf("\n");
  //printf("  tile-assembly <action> ...\n");
  //printf("\n");
  printf("  tile-assembly tilepath [tile-assembly-file] <hex-tilepath>\n");
  printf("\n");
  printf("    show tile assembly information for tile path\n");
  printf("\n");
  printf("\n");
  printf("  tile-assembly range [tile-assembly-file] <hex-tilepath>\n");
  printf("\n");
  printf("    show tile assembly range for tile path\n");
  printf("\n");
  printf("\n");
  return;
  printf("  [-v]        version\n");
  printf("  [-V]        verbose\n");
  printf("  [-i ifn]    input\n");
  printf("\n");
}

int split_tok_ch(std::vector< std::string > &tok_v, std::string &line, char field) {
  int i, j, k, n;
  std::string buf;

  n = (int)line.size();
  tok_v.clear();

  for (i=0; i<n; i++) {
    if (line[i]==field) {
      if (buf.size()>0) { tok_v.push_back(buf); }
      buf.clear();
      continue;
    }
    buf += line[i];
  }
  if (buf.size()>0) { tok_v.push_back(buf); }

  return 0;
}

int print_bgzf(const char *afn, long byte_offset, size_t byte_len) {
  int i, r;
  BGZF *bgzfp;
  char buf[1024];
  ssize_t sz=0;
  size_t buflen=1024, cur_len=0;

  if (!(bgzfp = bgzf_open(afn, "r"))) { return -1; }
  r = bgzf_index_load(bgzfp, afn, ".gzi");
  if (r<0) { goto cleanup_print_bgzf; }

  r = bgzf_useek(bgzfp, byte_offset, SEEK_SET);
  if (r<0) { goto cleanup_print_bgzf; }

  while (cur_len < byte_len) {
    if ((cur_len + buflen) <= byte_len ) {
      sz = bgzf_read(bgzfp, buf, sizeof(char)*buflen);
    } else {
      sz = bgzf_read(bgzfp, buf, sizeof(char)*(byte_len - cur_len));
    }
    if (sz<0) { r=-1; goto cleanup_print_bgzf; }
    for (i=0; i<sz; i++) { printf("%c", buf[i]); }
    cur_len += sz;
  }

  r=0;

cleanup_print_bgzf:
  bgzf_close(bgzfp);
  return r;
}

int tileassembly_index_info(const char *afn, const char *sfx, int tilepath, std::string &name, int *byte_offset, int *byte_len) {
  FILE *idx_fp;
  std::string idx_fn, line, field;
  std::vector< std::string > tok_v;
  int ch;
  const char *chp;
  char stilepath[32];

  snprintf(stilepath, 32, "%04x", tilepath);

  idx_fn = afn;
  idx_fn += sfx;
  if ((idx_fp = fopen(idx_fn.c_str(), "r"))==NULL) { return -1; }

  while (!feof(idx_fp)) {
    ch = fgetc(idx_fp);
    if ((ch=='\n') || (ch==EOF)) {
      if (line.size()==0) { continue; }

      split_tok_ch(tok_v, line, '\t');
      line.clear();

      if (tok_v.size()!=5) { continue; }

      name = tok_v[0];

      field = ":";
      field += stilepath;

      // tile path not found
      //
      if ((chp=strstr(tok_v[0].c_str(), field.c_str()))==NULL) {
        continue;
      }

      //printf("chp: %p %i %i\n", chp, (int)(tok_v[0].c_str() + tok_v[0].size() - chp), (int)field.size());

      if ((size_t)(tok_v[0].c_str() + tok_v[0].size() - chp) != field.size()) {
        continue;
      }

      *byte_offset = atoi(tok_v[2].c_str());
      *byte_len    = atoi(tok_v[1].c_str());

      fclose(idx_fp);

      return 0;
    }

    line += (char)ch;
  }

  fclose(idx_fp);

  return -1;
}

int print_tilepath(const char *afn, int tilepath, ta_opt_t *opt) {
  int r;
  FILE *idx_fp;
  std::string name;
  int ch;
  const char *chp;

  int byte_offset, byte_len;
  int print_header=0;

  print_header = opt->show_header;

  r = tileassembly_index_info(afn, ".fwi", tilepath, name, &byte_offset, &byte_len);
  if (r<0) { return r; }

  if (print_header) { printf(">%s\n", name.c_str()); }
  print_bgzf(afn, (long)byte_offset, (size_t)byte_len);
  return 0;
}

int tileassembly_end_pos(const char *afn, int tilepath, int *tilestep, int *ref_pos) {
  int i, r;
  BGZF *bgzfp;
  char buf[1024];
  ssize_t sz=0;
  size_t buflen=1024, cur_len=0;
  int byte_offset, byte_len;
  std::string name;
  std::string line;
  int char_count=0;
  int ch;
  std::vector< std::string > tok_v;

  int cur_tilestep=-1, cur_ref_pos=-1;

  r = tileassembly_index_info(afn, ".fwi", tilepath, name, &byte_offset, &byte_len);
  if (r<0) { return -1; }

  if (!(bgzfp = bgzf_open(afn, "r"))) { return -1; }
  r = bgzf_index_load(bgzfp, afn, ".gzi");
  if (r<0) { goto cleanup_print_bgzf; }

  r = bgzf_useek(bgzfp, byte_offset, SEEK_SET);
  if (r<0) { goto cleanup_print_bgzf; }

  r=-1;
  while ((ch=bgzf_getc(bgzfp))>=0) {
    char_count++;

    if ((ch<0) || (ch=='\n') || (char_count==byte_len)) {

      split_tok_ch(tok_v, line, '\t');
      line.clear();

      if (tok_v.size()!=2) { continue; }
      cur_tilestep = strtol(tok_v[0].c_str(), NULL, 16);
      cur_ref_pos = atoi(tok_v[1].c_str());
      r=0;
      continue;
    }

    if (char_count>=byte_len) { break; }

    line += (char)ch;
  }

  *tilestep = cur_tilestep;
  *ref_pos = cur_ref_pos;

cleanup_print_bgzf:
  bgzf_close(bgzfp);
  return r;
}

int print_range(const char *afn, int tilepath, ta_opt_t *opt) {
  int i, j, k, r;
  int prev_byte_offset, prev_byte_len;
  int byte_offset, byte_len;

  std::string tilepath_chrom, name, ref_name;
  std::vector< std::string > tok_v;

  int start_pos = 0;
  int show_header=0;

  int end_step, end_pos;

  show_header = opt->show_header;

  tileassembly_index_info(afn, ".fwi", tilepath, name, &byte_offset, &byte_len);
  split_tok_ch(tok_v, name, ':');
  if (tok_v.size()<3) { return -1; }

  ref_name = tok_v[0];
  tilepath_chrom = tok_v[1];

  if (tilepath>0) {
    tileassembly_index_info(afn, ".fwi", tilepath-1, name, &byte_offset, &byte_len);

    split_tok_ch(tok_v, name, ':');
    if (tok_v.size()<3) { return -1; }

    if (tok_v[1] != tilepath_chrom) { start_pos = 0; }
    else {
      r = tileassembly_end_pos(afn, tilepath-1, &k, &start_pos);
    }

  }

  r = tileassembly_end_pos(afn, tilepath, &end_step, &end_pos);

  if (show_header) {
    printf("#nstep\tbeg\tend\tchrom_name\tref_name\n");
  }
  printf("%i\t%i\t%i\t%s\t%s\n",
      end_step,
      start_pos,
      end_pos,
      tilepath_chrom.c_str(),
      ref_name.c_str() );

  return 0;
}

int main(int argc, char **argv ) {
  int i, j, k;
  int ch;
  int option_index;
  int verbose_flag = 0;
  int tilepath=-1;

  std::string assembly_fn, stilepath, action;

  ta_opt_t opt;

  char *chp;
  assembly_fn = DEFAULT_TILE_ASSEMBLY_FILE;

  opt.show_header = 0;
  opt.debug=0;

  chp = getenv("TILE_ASSEMBLY");
  if (chp) { assembly_fn = chp; }

  if (argc == 3) {
    action = argv[1];
    stilepath = argv[2];
  }

  else if (argc == 4) {
    action = argv[1];
    assembly_fn = argv[2];
    stilepath = argv[3];
  }

  else {
    show_help();
    exit(0);
  }

  tilepath = strtol(stilepath.c_str(), NULL, 16);

  /*
  while ((opt = getopt_long(argc-1, argv+1, "hvVi:", long_options, &option_index))!=-1) switch (opt) {
    case 0:
      fprintf(stderr, "sanity error, invalid option to parse, exiting\n");
      exit(-1);
      break;
    case 'v': show_version(); exit(0); break;
    case 'V': verbose_flag=1; break;
    case 'h':
    default: show_help(); exit(0); break;
  }
  */

  if (action == "tilepath") {
    print_tilepath(assembly_fn.c_str(), tilepath, &opt);
  }

  else if (action == "range") {
    opt.show_header=1;
    print_range(assembly_fn.c_str(), tilepath, &opt);
  }

  else {
    show_help();
    exit(0);
  }

}
<|endoftext|>


<commit_before>//===----------------------- PartialDemangleTest.cpp ----------------------===//
//
//                     The LLVM Compiler Infrastructure
//
// This file is dual licensed under the MIT and the University of Illinois Open
// Source Licenses. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//

#include <cstdlib>
#include "llvm/Demangle/Demangle.h"
#include "gtest/gtest.h"

struct ChoppedName {
  const char *Mangled;
  const char *ContextName, *BaseName, *ReturnType, *Params;
};

static ChoppedName NamesToTest[] = {
  {"_Z1fv", "", "f", "", "()"},
  {"_ZN1a1b1cIiiiEEvm", "a::b", "c", "void", "(unsigned long)"},
  {"_ZZ5OuterIiEivEN5Inner12inner_memberEv",
   "int Outer<int>()::Inner", "inner_member", "", "()"},
  {"_Z1fIiEPFvvEv", "", "f", "void (*)()", "()"},
  {"_ZN1S1fIiEEvv", "S", "f", "void", "()"},

  // Call operator for a lambda in f().
  {"_ZZ1fvENK3$_0clEi", "f()::$_0", "operator()", "", "(int)"},

  // A call operator for a lambda in a lambda in f().
  {"_ZZZ1fvENK3$_0clEvENKUlvE_clEv",
   "f()::$_0::operator()() const::'lambda'()", "operator()", "", "()"},

  {"_ZZN1S1fEiiEd0_NKUlvE_clEv",
   "S::f(int, int)::'lambda'()", "operator()", "", "()"},

  {"_ZN1Scv7MuncherIJDpPT_EEIJFivEA_iEEEv",
   "S", "operator Muncher<int (*)(), int (*) []>", "", "()"},

  // Attributes.
  {"_ZN5test4IdE1fEUa9enable_ifIXeqfL0p_Li1EEXeqfL0p0_Li2EEEi",
   "test4<double>", "f", "", "(int)"},
  {"_ZN1SC2B8ctor_tagEv", "S", "S", "", "()"},
  {"_ZN1S1fB4MERPIiEEvv", "S", "f", "void", "()"},

  {"_ZNSsC1EmcRKSaIcE",
   "std::basic_string<char, std::char_traits<char>, std::allocator<char> >",
   "basic_string", "", "(unsigned long, char, std::allocator<char> const&)"},
  {"_ZNSsixEm", "std::string", "operator[]", "", "(unsigned long)"},
  {"_ZSt17__throw_bad_allocv", "std", "__throw_bad_alloc", "", "()"},

  {"_ZN1AI1BEC2Ev", "A<B>", "A", "", "()"},
  {"_ZN1AI1BED2Ev", "A<B>", "~A", "", "()"},
  {"_ZN1AI1BECI24BaseEi", "A<B>", "A", "", "(int)"},
  {"_ZNKR1AI1BE1fIiEEiv", "A<B>", "f", "int", "()"},

  {"_ZN1SIJicfEE3mfnIJjcdEEEvicfDpT_", "S<int, char, float>",
   "mfn", "void", "(int, char, float, unsigned int, char, double)"},
};

TEST(PartialDemangleTest, TestNameChopping) {
  size_t Size = 1;
  char *Buf = static_cast<char *>(std::malloc(Size));

  llvm::ItaniumPartialDemangler D;

  for (ChoppedName &N : NamesToTest) {
    EXPECT_FALSE(D.partialDemangle(N.Mangled));
    EXPECT_TRUE(D.isFunction());
    EXPECT_FALSE(D.isData());
    EXPECT_FALSE(D.isSpecialName());

    Buf = D.getFunctionDeclContextName(Buf, &Size);
    EXPECT_STREQ(Buf, N.ContextName);

    Buf = D.getFunctionBaseName(Buf, &Size);
    EXPECT_STREQ(Buf, N.BaseName);

    Buf = D.getFunctionReturnType(Buf, &Size);
    EXPECT_STREQ(Buf, N.ReturnType);

    Buf = D.getFunctionParameters(Buf, &Size);
    EXPECT_STREQ(Buf, N.Params);
  }

  std::free(Buf);
}

TEST(PartialDemangleTest, TestNameMeta) {
  llvm::ItaniumPartialDemangler Demangler;

  EXPECT_FALSE(Demangler.partialDemangle("_ZNK1f1gEv"));
  EXPECT_TRUE(Demangler.isFunction());
  EXPECT_TRUE(Demangler.hasFunctionQualifiers());
  EXPECT_FALSE(Demangler.isSpecialName());
  EXPECT_FALSE(Demangler.isData());

  EXPECT_FALSE(Demangler.partialDemangle("_Z1fv"));
  EXPECT_FALSE(Demangler.hasFunctionQualifiers());

  EXPECT_FALSE(Demangler.partialDemangle("_ZTV1S"));
  EXPECT_TRUE(Demangler.isSpecialName());
  EXPECT_FALSE(Demangler.isData());
  EXPECT_FALSE(Demangler.isFunction());

  EXPECT_FALSE(Demangler.partialDemangle("_ZN1aDC1a1b1cEE"));
  EXPECT_FALSE(Demangler.isFunction());
  EXPECT_FALSE(Demangler.isSpecialName());
  EXPECT_TRUE(Demangler.isData());
}

TEST(PartialDemanglerTest, TestCtorOrDtor) {
  static const char *Pos[] = {
      "_ZN1AC1Ev",        // A::A()
      "_ZN1AC1IiEET_",    // A::A<int>(int)
      "_ZN1AD2Ev",        // A::~A()
      "_ZN1BIiEC1IcEET_", // B<int>::B<char>(char)
      "_ZN1AC1B1TEv",     // A::A[abi:T]()
      "_ZNSt1AD2Ev",      // std::A::~A()
      "_ZN2ns1AD1Ev",      // ns::A::~A()
  };
  static const char *Neg[] = {
      "_Z1fv",
      "_ZN1A1gIiEEvT_", // void A::g<int>(int)
  };

  llvm::ItaniumPartialDemangler D;
  for (const char *N : Pos) {
    EXPECT_FALSE(D.partialDemangle(N));
    EXPECT_TRUE(D.isCtorOrDtor());
  }
  for (const char *N : Neg) {
    EXPECT_FALSE(D.partialDemangle(N));
    EXPECT_FALSE(D.isCtorOrDtor());
  }
}

TEST(PartialDemanglerTest, TestMisc) {
  llvm::ItaniumPartialDemangler D1, D2;

  EXPECT_FALSE(D1.partialDemangle("_Z1fv"));
  EXPECT_FALSE(D2.partialDemangle("_Z1g"));
  std::swap(D1, D2);
  EXPECT_FALSE(D1.isFunction());
  EXPECT_TRUE(D2.isFunction());

  EXPECT_TRUE(D1.partialDemangle("Not a mangled name!"));

}
<commit_msg>[Demangle] Add another test for ItaniumPartialDemangler<commit_after>//===----------------------- PartialDemangleTest.cpp ----------------------===//
//
//                     The LLVM Compiler Infrastructure
//
// This file is dual licensed under the MIT and the University of Illinois Open
// Source Licenses. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//

#include <cstdlib>
#include "llvm/Demangle/Demangle.h"
#include "gtest/gtest.h"

struct ChoppedName {
  const char *Mangled;
  const char *ContextName, *BaseName, *ReturnType, *Params;
};

static ChoppedName NamesToTest[] = {
  {"_Z1fv", "", "f", "", "()"},
  {"_ZN1a1b1cIiiiEEvm", "a::b", "c", "void", "(unsigned long)"},
  {"_ZZ5OuterIiEivEN5Inner12inner_memberEv",
   "int Outer<int>()::Inner", "inner_member", "", "()"},
  {"_Z1fIiEPFvvEv", "", "f", "void (*)()", "()"},
  {"_ZN1S1fIiEEvv", "S", "f", "void", "()"},

  // Call operator for a lambda in f().
  {"_ZZ1fvENK3$_0clEi", "f()::$_0", "operator()", "", "(int)"},

  // A call operator for a lambda in a lambda in f().
  {"_ZZZ1fvENK3$_0clEvENKUlvE_clEv",
   "f()::$_0::operator()() const::'lambda'()", "operator()", "", "()"},

  {"_ZZN1S1fEiiEd0_NKUlvE_clEv",
   "S::f(int, int)::'lambda'()", "operator()", "", "()"},

  {"_ZN1Scv7MuncherIJDpPT_EEIJFivEA_iEEEv",
   "S", "operator Muncher<int (*)(), int (*) []>", "", "()"},

  // Attributes.
  {"_ZN5test4IdE1fEUa9enable_ifIXeqfL0p_Li1EEXeqfL0p0_Li2EEEi",
   "test4<double>", "f", "", "(int)"},
  {"_ZN1SC2B8ctor_tagEv", "S", "S", "", "()"},
  {"_ZN1S1fB4MERPIiEEvv", "S", "f", "void", "()"},

  {"_ZNSsC1EmcRKSaIcE",
   "std::basic_string<char, std::char_traits<char>, std::allocator<char> >",
   "basic_string", "", "(unsigned long, char, std::allocator<char> const&)"},
  {"_ZNSsixEm", "std::string", "operator[]", "", "(unsigned long)"},
  {"_ZSt17__throw_bad_allocv", "std", "__throw_bad_alloc", "", "()"},

  {"_ZN1AI1BEC2Ev", "A<B>", "A", "", "()"},
  {"_ZN1AI1BED2Ev", "A<B>", "~A", "", "()"},
  {"_ZN1AI1BECI24BaseEi", "A<B>", "A", "", "(int)"},
  {"_ZNKR1AI1BE1fIiEEiv", "A<B>", "f", "int", "()"},

  {"_ZN1SIJicfEE3mfnIJjcdEEEvicfDpT_", "S<int, char, float>",
   "mfn", "void", "(int, char, float, unsigned int, char, double)"},
};

TEST(PartialDemangleTest, TestNameChopping) {
  size_t Size = 1;
  char *Buf = static_cast<char *>(std::malloc(Size));

  llvm::ItaniumPartialDemangler D;

  for (ChoppedName &N : NamesToTest) {
    EXPECT_FALSE(D.partialDemangle(N.Mangled));
    EXPECT_TRUE(D.isFunction());
    EXPECT_FALSE(D.isData());
    EXPECT_FALSE(D.isSpecialName());

    Buf = D.getFunctionDeclContextName(Buf, &Size);
    EXPECT_STREQ(Buf, N.ContextName);

    Buf = D.getFunctionBaseName(Buf, &Size);
    EXPECT_STREQ(Buf, N.BaseName);

    Buf = D.getFunctionReturnType(Buf, &Size);
    EXPECT_STREQ(Buf, N.ReturnType);

    Buf = D.getFunctionParameters(Buf, &Size);
    EXPECT_STREQ(Buf, N.Params);
  }

  std::free(Buf);
}

TEST(PartialDemangleTest, TestNameMeta) {
  llvm::ItaniumPartialDemangler Demangler;

  EXPECT_FALSE(Demangler.partialDemangle("_ZNK1f1gEv"));
  EXPECT_TRUE(Demangler.isFunction());
  EXPECT_TRUE(Demangler.hasFunctionQualifiers());
  EXPECT_FALSE(Demangler.isSpecialName());
  EXPECT_FALSE(Demangler.isData());

  EXPECT_FALSE(Demangler.partialDemangle("_Z1fv"));
  EXPECT_FALSE(Demangler.hasFunctionQualifiers());

  EXPECT_FALSE(Demangler.partialDemangle("_ZTV1S"));
  EXPECT_TRUE(Demangler.isSpecialName());
  EXPECT_FALSE(Demangler.isData());
  EXPECT_FALSE(Demangler.isFunction());

  EXPECT_FALSE(Demangler.partialDemangle("_ZN1aDC1a1b1cEE"));
  EXPECT_FALSE(Demangler.isFunction());
  EXPECT_FALSE(Demangler.isSpecialName());
  EXPECT_TRUE(Demangler.isData());
}

TEST(PartialDemanglerTest, TestCtorOrDtor) {
  static const char *Pos[] = {
      "_ZN1AC1Ev",        // A::A()
      "_ZN1AC1IiEET_",    // A::A<int>(int)
      "_ZN1AD2Ev",        // A::~A()
      "_ZN1BIiEC1IcEET_", // B<int>::B<char>(char)
      "_ZN1AC1B1TEv",     // A::A[abi:T]()
      "_ZNSt1AD2Ev",      // std::A::~A()
      "_ZN2ns1AD1Ev",      // ns::A::~A()
  };
  static const char *Neg[] = {
      "_Z1fv",
      "_ZN1A1gIiEEvT_", // void A::g<int>(int)
  };

  llvm::ItaniumPartialDemangler D;
  for (const char *N : Pos) {
    EXPECT_FALSE(D.partialDemangle(N));
    EXPECT_TRUE(D.isCtorOrDtor());
  }
  for (const char *N : Neg) {
    EXPECT_FALSE(D.partialDemangle(N));
    EXPECT_FALSE(D.isCtorOrDtor());
  }
}

TEST(PartialDemanglerTest, TestMisc) {
  llvm::ItaniumPartialDemangler D1, D2;

  EXPECT_FALSE(D1.partialDemangle("_Z1fv"));
  EXPECT_FALSE(D2.partialDemangle("_Z1g"));
  std::swap(D1, D2);
  EXPECT_FALSE(D1.isFunction());
  EXPECT_TRUE(D2.isFunction());

  EXPECT_TRUE(D1.partialDemangle("Not a mangled name!"));
}

TEST(PartialDemanglerTest, TestPrintCases) {
  llvm::ItaniumPartialDemangler D;

  const size_t OriginalSize = 4;
  char *Buf = static_cast<char *>(std::malloc(OriginalSize));
  const char *OriginalBuf = Buf;

  // Default success case: Result fits into the given buffer.
  // Res points to Buf. N returns string size including null termination.
  {
    EXPECT_FALSE(D.partialDemangle("_ZN1a1bEv"));

    size_t N = OriginalSize;
    char *Res = D.getFunctionDeclContextName(Buf, &N);
    EXPECT_STREQ("a", Res);
    EXPECT_EQ(OriginalBuf, Res);
    EXPECT_EQ(strlen(Res) + 1, N);
  }

  // Realloc success case: Result does not fit into the given buffer.
  // Res points to the new or extended buffer. N returns string size
  // including null termination. Buf was extended or freed.
  {
    EXPECT_FALSE(D.partialDemangle("_ZN1a1b1cIiiiEEvm"));

    size_t N = OriginalSize;
    char *Res = D.finishDemangle(Buf, &N);
    EXPECT_STREQ("void a::b::c<int, int, int>(unsigned long)", Res);
    EXPECT_EQ(strlen(Res) + 1, N);
    Buf = Res;
  }

  // Failure case: a::c is not a function.
  // Res is nullptr. N remains unchanged.
  {
    EXPECT_FALSE(D.partialDemangle("_ZN1a1cE"));

    size_t N = OriginalSize;
    char *Res = D.getFunctionName(Buf, &N);
    EXPECT_EQ(nullptr, Res);
    EXPECT_EQ(OriginalSize, N);
  }

  std::free(Buf);
}
<|endoftext|>


<commit_before><commit_msg>and back to normal distance constraints<commit_after><|endoftext|>


<commit_before><commit_msg>Construct two levels of dispatch when merging large number of vmethods<commit_after><|endoftext|>


<commit_before>// Copyright (c) 2011 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "build/build_config.h"

#if defined(OS_WIN)
#include <objbase.h>
#include <windows.h>
// Some directx includes can trigger deprecation warnings.
#pragma warning(disable:4995)
#include <dshow.h>
#endif

#include "base/command_line.h"
#include "base/message_loop.h"
#include "base/string_util.h"
#include "base/system_monitor/system_monitor.h"
#include "base/threading/platform_thread.h"
#include "content/common/child_process.h"
#include "content/common/hi_res_timer_manager.h"
#include "content/plugin/plugin_thread.h"
#include "content/public/common/content_switches.h"
#include "content/public/common/main_function_params.h"

#if defined(OS_WIN)
#include "base/win/scoped_comptr.h"
#include "content/common/injection_test_dll.h"
#include "sandbox/src/sandbox.h"
#elif defined(OS_POSIX) && !defined(OS_MACOSX)
#include "base/global_descriptors_posix.h"
#include "ipc/ipc_descriptors.h"
#endif

#if defined(OS_MACOSX)
// Removes our Carbon library interposing from the environment so that it
// doesn't carry into any processes that plugins might start.
void TrimInterposeEnvironment();

// Initializes the global Cocoa application object.
void InitializeChromeApplication();
#elif defined(OS_LINUX)
// Work around an unimplemented instruction in 64-bit Flash.
void WorkaroundFlashLAHF();
#endif

#if defined(OS_WIN)
// This function is provided so that the built-in flash can lock down the
// sandbox by calling DelayedLowerToken(0).
extern "C" DWORD __declspec(dllexport) __stdcall DelayedLowerToken(void* ts) {
  // s_ts is only set the first time the function is called, which happens
  // in PluginMain.
  static sandbox::TargetServices* s_ts =
      reinterpret_cast<sandbox::TargetServices*>(ts);
  if (ts)
    return 0;
  s_ts->LowerToken();
  return 1;
};

// Returns true if the plugin to be loaded is the internal flash.
bool IsPluginBuiltInFlash(const CommandLine& cmd_line) {
  FilePath path =  cmd_line.GetSwitchValuePath(switches::kPluginPath);
  return (path.BaseName() == FilePath(L"gcswf32.dll"));
}

// Before we lock down the flash sandbox, we need to activate
// the IME machinery. After lock down it seems it is unable
// to start. Note that we leak the IME context on purpose.
int PreloadIMEForFlash() {
  HIMC imc = ::ImmCreateContext();
  if (!imc)
    return 0;
  if (::ImmGetOpenStatus(imc))
    return 1;
  return 2;
}

#endif

// main() routine for running as the plugin process.
int PluginMain(const content::MainFunctionParams& parameters) {
  // The main thread of the plugin services UI.
#if defined(OS_MACOSX)
#if !defined(__LP64__)
  TrimInterposeEnvironment();
#endif
  InitializeChromeApplication();
#endif
  MessageLoop main_message_loop(MessageLoop::TYPE_UI);
  base::PlatformThread::SetName("CrPluginMain");

  base::SystemMonitor system_monitor;
  HighResolutionTimerManager high_resolution_timer_manager;

  const CommandLine& parsed_command_line = parameters.command_line;

#if defined(OS_LINUX)

#if defined(ARCH_CPU_64_BITS)
  WorkaroundFlashLAHF();
#endif

#elif defined(OS_WIN)
  sandbox::TargetServices* target_services =
      parameters.sandbox_info->target_services;

  CoInitialize(NULL);
  DVLOG(1) << "Started plugin with "
           << parsed_command_line.GetCommandLineString();

  HMODULE sandbox_test_module = NULL;
  bool no_sandbox = parsed_command_line.HasSwitch(switches::kNoSandbox);

  if (target_services && !no_sandbox) {
    // The command line might specify a test plugin to load.
    if (parsed_command_line.HasSwitch(switches::kTestSandbox)) {
      std::wstring test_plugin_name =
          parsed_command_line.GetSwitchValueNative(switches::kTestSandbox);
      sandbox_test_module = LoadLibrary(test_plugin_name.c_str());
      DCHECK(sandbox_test_module);
    }
  }
#endif
  if (parsed_command_line.HasSwitch(switches::kPluginStartupDialog)) {
    ChildProcess::WaitForDebugger("Plugin");
  }

  {
    ChildProcess plugin_process;
    plugin_process.set_main_thread(new PluginThread());
#if defined(OS_WIN)
    if (!no_sandbox && target_services) {
      // We are sandboxing the plugin. If it is a generic plug-in, we lock down
      // the sandbox right away, but if it is the built-in flash we let flash
      // start elevated and it will call DelayedLowerToken(0) when it's ready.
      if (IsPluginBuiltInFlash(parsed_command_line)) {
        DVLOG(1) << "Sandboxing flash";
        if (!PreloadIMEForFlash())
          DVLOG(1) << "IME preload failed";

        // Warm up the device enumerator for webcam and microphone.
        base::win::ScopedComPtr<ICreateDevEnum> device_enumerator;
        device_enumerator.CreateInstance(CLSID_SystemDeviceEnum);

        DelayedLowerToken(target_services);
      } else {
        target_services->LowerToken();
      }
    }
    if (sandbox_test_module) {
      RunPluginTests run_security_tests =
          reinterpret_cast<RunPluginTests>(GetProcAddress(sandbox_test_module,
                                                          kPluginTestCall));
      DCHECK(run_security_tests);
      if (run_security_tests) {
        int test_count = 0;
        DVLOG(1) << "Running plugin security tests";
        BOOL result = run_security_tests(&test_count);
        DCHECK(result) << "Test number " << test_count << " has failed.";
        // If we are in release mode, crash or debug the process.
        if (!result) {
          __debugbreak();
          _exit(1);
        }
      }

      FreeLibrary(sandbox_test_module);
    }
#endif

    MessageLoop::current()->Run();
  }

#if defined(OS_WIN)
  CoUninitialize();
#endif

  return 0;
}
<commit_msg>Fix how we warm up the device enumerator for Flash<commit_after>// Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "build/build_config.h"

#if defined(OS_WIN)
#include <objbase.h>
#include <windows.h>
// Some directx includes can trigger deprecation warnings.
#pragma warning(disable:4995)
#include <dshow.h>
#endif

#include "base/command_line.h"
#include "base/message_loop.h"
#include "base/string_util.h"
#include "base/system_monitor/system_monitor.h"
#include "base/threading/platform_thread.h"
#include "content/common/child_process.h"
#include "content/common/hi_res_timer_manager.h"
#include "content/plugin/plugin_thread.h"
#include "content/public/common/content_switches.h"
#include "content/public/common/main_function_params.h"

#if defined(OS_WIN)
#include "base/win/scoped_comptr.h"
#include "content/common/injection_test_dll.h"
#include "sandbox/src/sandbox.h"
#elif defined(OS_POSIX) && !defined(OS_MACOSX)
#include "base/global_descriptors_posix.h"
#include "ipc/ipc_descriptors.h"
#endif

#if defined(OS_MACOSX)
// Removes our Carbon library interposing from the environment so that it
// doesn't carry into any processes that plugins might start.
void TrimInterposeEnvironment();

// Initializes the global Cocoa application object.
void InitializeChromeApplication();
#elif defined(OS_LINUX)
// Work around an unimplemented instruction in 64-bit Flash.
void WorkaroundFlashLAHF();
#endif

#if defined(OS_WIN)
// This function is provided so that the built-in flash can lock down the
// sandbox by calling DelayedLowerToken(0).
extern "C" DWORD __declspec(dllexport) __stdcall DelayedLowerToken(void* ts) {
  // s_ts is only set the first time the function is called, which happens
  // in PluginMain.
  static sandbox::TargetServices* s_ts =
      reinterpret_cast<sandbox::TargetServices*>(ts);
  if (ts)
    return 0;
  s_ts->LowerToken();
  return 1;
};

// Returns true if the plugin to be loaded is the internal flash.
bool IsPluginBuiltInFlash(const CommandLine& cmd_line) {
  FilePath path =  cmd_line.GetSwitchValuePath(switches::kPluginPath);
  return (path.BaseName() == FilePath(L"gcswf32.dll"));
}

// Before we lock down the flash sandbox, we need to activate
// the IME machinery. After lock down it seems it is unable
// to start. Note that we leak the IME context on purpose.
int PreloadIMEForFlash() {
  HIMC imc = ::ImmCreateContext();
  if (!imc)
    return 0;
  if (::ImmGetOpenStatus(imc))
    return 1;
  return 2;
}

#endif

// main() routine for running as the plugin process.
int PluginMain(const content::MainFunctionParams& parameters) {
  // The main thread of the plugin services UI.
#if defined(OS_MACOSX)
#if !defined(__LP64__)
  TrimInterposeEnvironment();
#endif
  InitializeChromeApplication();
#endif
  MessageLoop main_message_loop(MessageLoop::TYPE_UI);
  base::PlatformThread::SetName("CrPluginMain");

  base::SystemMonitor system_monitor;
  HighResolutionTimerManager high_resolution_timer_manager;

  const CommandLine& parsed_command_line = parameters.command_line;

#if defined(OS_LINUX)

#if defined(ARCH_CPU_64_BITS)
  WorkaroundFlashLAHF();
#endif

#elif defined(OS_WIN)
  sandbox::TargetServices* target_services =
      parameters.sandbox_info->target_services;

  CoInitialize(NULL);
  DVLOG(1) << "Started plugin with "
           << parsed_command_line.GetCommandLineString();

  HMODULE sandbox_test_module = NULL;
  bool no_sandbox = parsed_command_line.HasSwitch(switches::kNoSandbox);

  if (target_services && !no_sandbox) {
    // The command line might specify a test plugin to load.
    if (parsed_command_line.HasSwitch(switches::kTestSandbox)) {
      std::wstring test_plugin_name =
          parsed_command_line.GetSwitchValueNative(switches::kTestSandbox);
      sandbox_test_module = LoadLibrary(test_plugin_name.c_str());
      DCHECK(sandbox_test_module);
    }
  }
#endif
  if (parsed_command_line.HasSwitch(switches::kPluginStartupDialog)) {
    ChildProcess::WaitForDebugger("Plugin");
  }

  {
    ChildProcess plugin_process;
    plugin_process.set_main_thread(new PluginThread());
#if defined(OS_WIN)
    if (!no_sandbox && target_services) {
      // We are sandboxing the plugin. If it is a generic plug-in, we lock down
      // the sandbox right away, but if it is the built-in flash we let flash
      // start elevated and it will call DelayedLowerToken(0) when it's ready.
      if (IsPluginBuiltInFlash(parsed_command_line)) {
        DVLOG(1) << "Sandboxing flash";
        if (!PreloadIMEForFlash())
          DVLOG(1) << "IME preload failed";

        // Warm up the device enumerator for webcam and microphone.
        base::win::ScopedComPtr<ICreateDevEnum> device_enumerator;
        device_enumerator.CreateInstance(CLSID_SystemDeviceEnum, NULL,
                                         CLSCTX_INPROC_SERVER |
                                         CLSCTX_INPROC_HANDLER);

        DelayedLowerToken(target_services);
      } else {
        target_services->LowerToken();
      }
    }
    if (sandbox_test_module) {
      RunPluginTests run_security_tests =
          reinterpret_cast<RunPluginTests>(GetProcAddress(sandbox_test_module,
                                                          kPluginTestCall));
      DCHECK(run_security_tests);
      if (run_security_tests) {
        int test_count = 0;
        DVLOG(1) << "Running plugin security tests";
        BOOL result = run_security_tests(&test_count);
        DCHECK(result) << "Test number " << test_count << " has failed.";
        // If we are in release mode, crash or debug the process.
        if (!result) {
          __debugbreak();
          _exit(1);
        }
      }

      FreeLibrary(sandbox_test_module);
    }
#endif

    MessageLoop::current()->Run();
  }

#if defined(OS_WIN)
  CoUninitialize();
#endif

  return 0;
}
<|endoftext|>


<commit_before>#include <str_const.h>
#include <ast.h>
void gets();
#include <iostream>

using namespace std::ast;

void test_str_const()
{
  constexpr str_const test("Hello!!");
  static_assert(test.size() == 7, "");
  static_assert(test[6] == '!', "");
  static_assert(test[7] == 0, "");
}

void test_ast_building()
{
  static constexpr ast_identifier id_test("test");
  static constexpr ast_identifier id_param1("param1");
  static constexpr ast_identifier id_param2("param2");
  static constexpr ast_identifier id_member1("member1");
  static constexpr ast_identifier id_member2("member2");

  //  examples
  //  int test;
  constexpr ast_var test_var1(builtin_types::type_int, id_test);
  static_assert(&builtin_types::type_int.name() != nullptr, "");
  static_assert(test_var1.name() == "test", "");
  static_assert(test_var1.type().name() == "int", "");

  //  const int test;
  static constexpr ast_qualified const_int(ast_type::Const, builtin_types::type_int);

  constexpr ast_var test_var2(const_int, id_test);
  static_assert(const_int.qualifiers() == ast_type::Const, "");
  static_assert(test_var2.type().kind() == kind_qualified, "");
  static_assert(get_as<ast_qualified>(test_var2.type()).qualifiers() == ast_type::Const, "");
  static_assert(test_var2.name() == "test", "");
  static_assert(test_var2.type().name() == "int", "");

  //  const int* test;
  static constexpr ast_pointer pointer_to_const_int(const_int);
  constexpr ast_var test_var3(pointer_to_const_int, id_test);
  static_assert(test_var3.name() == "test", "");

  //  int& test;
  static constexpr ast_reference int_reference(builtin_types::type_int);
  constexpr ast_var test_var4(int_reference, id_test);
  static_assert(test_var4.name() == "test", "");

  //  double test[2];
  static constexpr ast_string str_2("2");
  static constexpr ast_literal literal_2(builtin_types::type_int, str_2);
  static constexpr ast_array double_array_2(builtin_types::type_double, literal_2);
  constexpr ast_var test_var5(double_array_2, id_test);
  static_assert(test_var5.name() == "test", "");

  //  int** test;
  static constexpr ast_pointer pointer_to_int(builtin_types::type_int);
  static constexpr ast_pointer pointer_to_pointer_to_int(pointer_to_int);
  constexpr ast_var test_var6(pointer_to_pointer_to_int, id_test);
  static_assert(test_var6.name() == "test", "");

  // abstract function declaration
  // int (*)();
  static constexpr ast_product param_list_0;
  static constexpr ast_function abstract_int_funtion_param_0(param_list_0, builtin_types::type_int);
  static_assert(abstract_int_funtion_param_0.target().name() == "int", "");
  static_assert(abstract_int_funtion_param_0.source().elements().size() == 0, "");
  static_assert(abstract_int_funtion_param_0.throws().elements().size() == 0, "");
  static_assert(abstract_int_funtion_param_0.lang_linkage().language() == "C++", "");

  // abstract function declaration with 2 params
  // int (*)(char, double);
  static constexpr const ast_type* param_seq[] = { &builtin_types::type_char, &builtin_types::type_double };
  static constexpr ast_product param_list_2({ param_seq, 2});

  static constexpr ast_function abstract_int_funtion_param_2(param_list_2, builtin_types::type_int);
  static_assert(abstract_int_funtion_param_2.target().name() == "int", "");
  static_assert(abstract_int_funtion_param_2.source().elements().size() == 2, "");
  static_assert(abstract_int_funtion_param_2.source().elements()[0].name() == "char", "");
  static_assert(abstract_int_funtion_param_2.source().elements()[1].name() == "double", "");
  static_assert(abstract_int_funtion_param_2.throws().elements().size() == 0, "");
  static_assert(abstract_int_funtion_param_2.lang_linkage().language() == "C++", "");

  //  int test();
  //  static constexpr ast_parameter_list test_param_list_0({});
  static constexpr ast_mapping mappings_empty;

  static constexpr ast_fundecl int_funtion_param_0(id_test, abstract_int_funtion_param_0, mappings_empty);
  static_assert(int_funtion_param_0.parameters().size() == 0, "");
  static_assert(int_funtion_param_0.name() == "test", "");

  //  int test(char param1, double param2);
  static constexpr ast_parameter test_param_1(builtin_types::type_char, id_param1);
  static constexpr ast_parameter test_param_2(builtin_types::type_double, id_param2);
  static constexpr const ast_parameter* ast_parameters[] = { &test_param_1, &test_param_2 };
  static constexpr ast_parameter_list test_param_list_2({ast_parameters, 2});
  static constexpr ast_mapping mappings_param_2(test_param_list_2);

  static constexpr ast_fundecl int_funtion_param2(id_test, abstract_int_funtion_param_2, mappings_param_2);
  static_assert(int_funtion_param2.name() == "test", "");
  //static_assert(int_funtion_param2.type().name() == "int", ""); // TODO
  static_assert(int_funtion_param2.parameters().size() == 2, "");
  static_assert(int_funtion_param2.parameters()[0].name() == "param1", "");
  static_assert(int_funtion_param2.parameters()[0].type().name() == "char", "");
  static_assert(int_funtion_param2.parameters()[1].name() == "param2", "");
  static_assert(int_funtion_param2.parameters()[1].type().name() == "double", "");

  //  class test;
  static constexpr ast_class test_class_empty(id_test, {}, {});
  static_assert(test_class_empty.name() == "test", "");
  static_assert(test_class_empty.members().size() == 0, "");
  static_assert(test_class_empty.bases().size() == 0, "");

  //  class test
  //  {
  //    char member1;
  //    double member2;
  //  };
  static constexpr ast_var test_member1(builtin_types::type_char, id_member1);
  static constexpr ast_var test_member2(builtin_types::type_double, id_member2);
  static constexpr const ast_decl* test_class_members[] = { &test_member1, &test_member2 };

  static constexpr ast_class test_class(id_test, { test_class_members, 2 }, {});
  static_assert(test_class.name() == "test", "");
  static_assert(test_class.members().size() == 2, "");
  static_assert(test_class.members()[0].name() == "member1", "");
  static_assert(test_class.members()[0].type().name() == "char", "");
  static_assert(test_class.members()[1].name() == "member2", "");
  static_assert(test_class.members()[1].type().name() == "double", "");
  static_assert(test_class.bases().size() == 0, "");
}

int main()
{
  test_str_const();
  test_ast_building();

  return 0;
}
<commit_msg>Removed a wrong assert<commit_after>#include <str_const.h>
#include <ast.h>
void gets();
#include <iostream>

using namespace std::ast;

void test_str_const()
{
  constexpr str_const test("Hello!!");
  static_assert(test.size() == 7, "");
  static_assert(test[6] == '!', "");
  static_assert(test[7] == 0, "");
}

void test_ast_building()
{
  static constexpr ast_identifier id_test("test");
  static constexpr ast_identifier id_param1("param1");
  static constexpr ast_identifier id_param2("param2");
  static constexpr ast_identifier id_member1("member1");
  static constexpr ast_identifier id_member2("member2");

  //  examples
  //  int test;
  constexpr ast_var test_var1(builtin_types::type_int, id_test);
  static_assert(&builtin_types::type_int.name() != nullptr, "");
  static_assert(test_var1.name() == "test", "");
  static_assert(test_var1.type().name() == "int", "");

  //  const int test;
  static constexpr ast_qualified const_int(ast_type::Const, builtin_types::type_int);

  constexpr ast_var test_var2(const_int, id_test);
  static_assert(const_int.qualifiers() == ast_type::Const, "");
  static_assert(test_var2.type().kind() == kind_qualified, "");
  static_assert(get_as<ast_qualified>(test_var2.type()).qualifiers() == ast_type::Const, "");
  static_assert(test_var2.name() == "test", "");

  //  const int* test;
  static constexpr ast_pointer pointer_to_const_int(const_int);
  constexpr ast_var test_var3(pointer_to_const_int, id_test);
  static_assert(test_var3.name() == "test", "");

  //  int& test;
  static constexpr ast_reference int_reference(builtin_types::type_int);
  constexpr ast_var test_var4(int_reference, id_test);
  static_assert(test_var4.name() == "test", "");

  //  double test[2];
  static constexpr ast_string str_2("2");
  static constexpr ast_literal literal_2(builtin_types::type_int, str_2);
  static constexpr ast_array double_array_2(builtin_types::type_double, literal_2);
  constexpr ast_var test_var5(double_array_2, id_test);
  static_assert(test_var5.name() == "test", "");

  //  int** test;
  static constexpr ast_pointer pointer_to_int(builtin_types::type_int);
  static constexpr ast_pointer pointer_to_pointer_to_int(pointer_to_int);
  constexpr ast_var test_var6(pointer_to_pointer_to_int, id_test);
  static_assert(test_var6.name() == "test", "");

  // abstract function declaration
  // int (*)();
  static constexpr ast_product param_list_0;
  static constexpr ast_function abstract_int_funtion_param_0(param_list_0, builtin_types::type_int);
  static_assert(abstract_int_funtion_param_0.target().name() == "int", "");
  static_assert(abstract_int_funtion_param_0.source().elements().size() == 0, "");
  static_assert(abstract_int_funtion_param_0.throws().elements().size() == 0, "");
  static_assert(abstract_int_funtion_param_0.lang_linkage().language() == "C++", "");

  // abstract function declaration with 2 params
  // int (*)(char, double);
  static constexpr const ast_type* param_seq[] = { &builtin_types::type_char, &builtin_types::type_double };
  static constexpr ast_product param_list_2({ param_seq, 2});

  static constexpr ast_function abstract_int_funtion_param_2(param_list_2, builtin_types::type_int);
  static_assert(abstract_int_funtion_param_2.target().name() == "int", "");
  static_assert(abstract_int_funtion_param_2.source().elements().size() == 2, "");
  static_assert(abstract_int_funtion_param_2.source().elements()[0].name() == "char", "");
  static_assert(abstract_int_funtion_param_2.source().elements()[1].name() == "double", "");
  static_assert(abstract_int_funtion_param_2.throws().elements().size() == 0, "");
  static_assert(abstract_int_funtion_param_2.lang_linkage().language() == "C++", "");

  //  int test();
  //  static constexpr ast_parameter_list test_param_list_0({});
  static constexpr ast_mapping mappings_empty;

  static constexpr ast_fundecl int_funtion_param_0(id_test, abstract_int_funtion_param_0, mappings_empty);
  static_assert(int_funtion_param_0.parameters().size() == 0, "");
  static_assert(int_funtion_param_0.name() == "test", "");

  //  int test(char param1, double param2);
  static constexpr ast_parameter test_param_1(builtin_types::type_char, id_param1);
  static constexpr ast_parameter test_param_2(builtin_types::type_double, id_param2);
  static constexpr const ast_parameter* ast_parameters[] = { &test_param_1, &test_param_2 };
  static constexpr ast_parameter_list test_param_list_2({ast_parameters, 2});
  static constexpr ast_mapping mappings_param_2(test_param_list_2);

  static constexpr ast_fundecl int_funtion_param2(id_test, abstract_int_funtion_param_2, mappings_param_2);
  static_assert(int_funtion_param2.name() == "test", "");
  //static_assert(int_funtion_param2.type().name() == "int", ""); // TODO
  static_assert(int_funtion_param2.parameters().size() == 2, "");
  static_assert(int_funtion_param2.parameters()[0].name() == "param1", "");
  static_assert(int_funtion_param2.parameters()[0].type().name() == "char", "");
  static_assert(int_funtion_param2.parameters()[1].name() == "param2", "");
  static_assert(int_funtion_param2.parameters()[1].type().name() == "double", "");

  //  class test;
  static constexpr ast_class test_class_empty(id_test, {}, {});
  static_assert(test_class_empty.name() == "test", "");
  static_assert(test_class_empty.members().size() == 0, "");
  static_assert(test_class_empty.bases().size() == 0, "");

  //  class test
  //  {
  //    char member1;
  //    double member2;
  //  };
  static constexpr ast_var test_member1(builtin_types::type_char, id_member1);
  static constexpr ast_var test_member2(builtin_types::type_double, id_member2);
  static constexpr const ast_decl* test_class_members[] = { &test_member1, &test_member2 };

  static constexpr ast_class test_class(id_test, { test_class_members, 2 }, {});
  static_assert(test_class.name() == "test", "");
  static_assert(test_class.members().size() == 2, "");
  static_assert(test_class.members()[0].name() == "member1", "");
  static_assert(test_class.members()[0].type().name() == "char", "");
  static_assert(test_class.members()[1].name() == "member2", "");
  static_assert(test_class.members()[1].type().name() == "double", "");
  static_assert(test_class.bases().size() == 0, "");
}

int main()
{
  test_str_const();
  test_ast_building();

  return 0;
}
<|endoftext|>