<commit_before>/****************************************************************************
**
** Copyright (C) 2013 Digia Plc and/or its subsidiary(-ies).
** Contact: http://www.qt-project.org/legal
**
** This file is part of Qt Creator.
**
** Commercial License Usage
** Licensees holding valid commercial Qt licenses may use this file in
** accordance with the commercial license agreement provided with the
** Software or, alternatively, in accordance with the terms contained in
** a written agreement between you and Digia.  For licensing terms and
** conditions see http://qt.digia.com/licensing.  For further information
** use the contact form at http://qt.digia.com/contact-us.
**
** GNU Lesser General Public License Usage
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 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, Digia gives you certain additional
** rights.  These rights are described in the Digia Qt LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
****************************************************************************/

#include "movetool.h"

#include "formeditorscene.h"
#include "formeditorview.h"
#include "formeditorwidget.h"

#include "resizehandleitem.h"

#include <QApplication>
#include <QGraphicsSceneMouseEvent>
#include <QAction>
#include <QDebug>

namespace QmlDesigner {

MoveTool::MoveTool(FormEditorView *editorView)
    : AbstractFormEditorTool(editorView),
    m_moveManipulator(editorView->scene()->manipulatorLayerItem(), editorView),
    m_selectionIndicator(editorView->scene()->manipulatorLayerItem()),
    m_resizeIndicator(editorView->scene()->manipulatorLayerItem()),
    m_anchorIndicator(editorView->scene()->manipulatorLayerItem()),
    m_bindingIndicator(editorView->scene()->manipulatorLayerItem())
{
    m_selectionIndicator.setCursor(Qt::SizeAllCursor);
}

MoveTool::~MoveTool()
{

}

void MoveTool::clear()
{
    m_moveManipulator.clear();
    m_movingItems.clear();
    m_selectionIndicator.clear();
    m_resizeIndicator.clear();
    m_anchorIndicator.clear();
    m_bindingIndicator.clear();

    AbstractFormEditorTool::clear();
}

void MoveTool::mousePressEvent(const QList<QGraphicsItem*> &itemList,
                                            QGraphicsSceneMouseEvent *event)
{
    if (event->button() == Qt::LeftButton) {
        if (itemList.isEmpty())
            return;
        m_movingItems = movingItems(items());
        if (m_movingItems.isEmpty())
            return;

        m_moveManipulator.setItems(m_movingItems);
        m_moveManipulator.begin(event->scenePos());
    }

    AbstractFormEditorTool::mousePressEvent(itemList, event);
}

void MoveTool::mouseMoveEvent(const QList<QGraphicsItem*> &itemList,
                                           QGraphicsSceneMouseEvent *event)
{
    if (m_moveManipulator.isActive()) {
        if (m_movingItems.isEmpty())
            return;

        //    m_selectionIndicator.hide();
        m_resizeIndicator.hide();
        m_anchorIndicator.hide();
        m_bindingIndicator.hide();

        FormEditorItem *containerItem = containerFormEditorItem(itemList, m_movingItems);
        if (containerItem && view()->currentState().isBaseState()) {
            if (containerItem != m_movingItems.first()->parentItem()
                    && event->modifiers().testFlag(Qt::ShiftModifier)) {
                m_moveManipulator.reparentTo(containerItem);
            }
        }

        m_moveManipulator.update(event->scenePos(), generateUseSnapping(event->modifiers()));
    }
}

void MoveTool::hoverMoveEvent(const QList<QGraphicsItem*> &itemList,
                        QGraphicsSceneMouseEvent * /*event*/)
{
    if (itemList.isEmpty()) {
        view()->changeToSelectionTool();
        return;
    }

    ResizeHandleItem* resizeHandle = ResizeHandleItem::fromGraphicsItem(itemList.first());
    if (resizeHandle) {
        view()->changeToResizeTool();
        return;
    }

    if (!topSelectedItemIsMovable(itemList)) {
        view()->changeToSelectionTool();
        return;
    }
}

void MoveTool::keyPressEvent(QKeyEvent *event)
{
    switch (event->key()) {
        case Qt::Key_Shift:
        case Qt::Key_Alt:
        case Qt::Key_Control:
        case Qt::Key_AltGr:
            event->setAccepted(false);
            return;
    }

    double moveStep = 1.0;

    if (event->modifiers().testFlag(Qt::ShiftModifier))
        moveStep = 10.0;

    if (!event->isAutoRepeat()) {
        QList<FormEditorItem*> movableItems(movingItems(items()));
        if (movableItems.isEmpty())
            return;

        m_moveManipulator.setItems(movableItems);
//        m_selectionIndicator.hide();
        m_resizeIndicator.hide();
        m_anchorIndicator.hide();
        m_bindingIndicator.hide();
        m_moveManipulator.beginRewriterTransaction();
    }

    switch (event->key()) {
        case Qt::Key_Left: m_moveManipulator.moveBy(-moveStep, 0.0); break;
        case Qt::Key_Right: m_moveManipulator.moveBy(moveStep, 0.0); break;
        case Qt::Key_Up: m_moveManipulator.moveBy(0.0, -moveStep); break;
        case Qt::Key_Down: m_moveManipulator.moveBy(0.0, moveStep); break;
    }

    if (event->key() == Qt::Key_Escape && !m_movingItems.isEmpty()) {
       event->accept();
       view()->changeToSelectionTool();
    }
}

void MoveTool::keyReleaseEvent(QKeyEvent *keyEvent)
{
    switch (keyEvent->key()) {
        case Qt::Key_Shift:
        case Qt::Key_Alt:
        case Qt::Key_Control:
        case Qt::Key_AltGr:
            keyEvent->setAccepted(false);
            return;
    }

    if (!keyEvent->isAutoRepeat()) {
        m_moveManipulator.beginRewriterTransaction();
        m_moveManipulator.clear();
//        m_selectionIndicator.show();
        m_resizeIndicator.show();
        m_anchorIndicator.show();
        m_bindingIndicator.show();
    }
}

void  MoveTool::dragLeaveEvent(QGraphicsSceneDragDropEvent * /*event*/)
{

}

void  MoveTool::dragMoveEvent(QGraphicsSceneDragDropEvent * /*event*/)
{

}

void MoveTool::mouseReleaseEvent(const QList<QGraphicsItem*> &itemList,
                                 QGraphicsSceneMouseEvent *event)
{
    if (m_moveManipulator.isActive()) {
        if (m_movingItems.isEmpty())
            return;

        m_moveManipulator.end(generateUseSnapping(event->modifiers()));

        m_selectionIndicator.show();
        m_resizeIndicator.show();
        m_anchorIndicator.show();
        m_bindingIndicator.show();
        m_movingItems.clear();
    }

    AbstractFormEditorTool::mouseReleaseEvent(itemList, event);
}

void MoveTool::mouseDoubleClickEvent(const QList<QGraphicsItem*> &itemList, QGraphicsSceneMouseEvent *event)
{
    AbstractFormEditorTool::mouseDoubleClickEvent(itemList, event);
}

void MoveTool::itemsAboutToRemoved(const QList<FormEditorItem*> &removedItemList)
{
    foreach (FormEditorItem* removedItem, removedItemList)
        m_movingItems.removeOne(removedItem);
}

void MoveTool::selectedItemsChanged(const QList<FormEditorItem*> &itemList)
{
    m_selectionIndicator.setItems(movingItems(itemList));
    m_resizeIndicator.setItems(itemList);
    m_anchorIndicator.setItems(itemList);
    m_bindingIndicator.setItems(itemList);
    updateMoveManipulator();
}

void MoveTool::instancesCompleted(const QList<FormEditorItem*> & /*itemList*/)
{
}

void  MoveTool::instancesParentChanged(const QList<FormEditorItem *> &itemList)
{
    m_moveManipulator.synchronizeInstanceParent(itemList);
}

void MoveTool::instancePropertyChange(const QList<QPair<ModelNode, PropertyName> > & /*propertyList*/)
{
}

bool MoveTool::haveSameParent(const QList<FormEditorItem*> &itemList)
{
    if (itemList.isEmpty())
        return false;

    QGraphicsItem *firstParent = itemList.first()->parentItem();
    foreach (FormEditorItem* item, itemList)
    {
        if (firstParent != item->parentItem())
            return false;
    }

    return true;
}

bool MoveTool::isAncestorOfAllItems(FormEditorItem* maybeAncestorItem,
                                    const QList<FormEditorItem*> &itemList)
{
    foreach (FormEditorItem* item, itemList)
    {
        if (!maybeAncestorItem->isAncestorOf(item) && item != maybeAncestorItem)
            return false;
    }

    return true;
}

FormEditorItem* MoveTool::ancestorIfOtherItemsAreChild(const QList<FormEditorItem*> &itemList)
{
    if (itemList.isEmpty())
        return 0;

    foreach (FormEditorItem* item, itemList)
    {
        if (isAncestorOfAllItems(item, itemList))
            return item;
    }

    return 0;
}

void MoveTool::updateMoveManipulator()
{
    if (m_moveManipulator.isActive())
        return;
}

void MoveTool::beginWithPoint(const QPointF &beginPoint)
{
    m_movingItems = movingItems(items());
    if (m_movingItems.isEmpty())
        return;

    m_moveManipulator.setItems(m_movingItems);
    m_moveManipulator.begin(beginPoint);
}

static bool isNotAncestorOfItemInList(FormEditorItem *formEditorItem, const QList<FormEditorItem*> &itemList)
{
    foreach (FormEditorItem *item, itemList) {
        if (item
            && item->qmlItemNode().isValid()
            && item->qmlItemNode().isAncestorOf(formEditorItem->qmlItemNode()))
            return false;
    }

    return true;
}

FormEditorItem* MoveTool::containerFormEditorItem(const QList<QGraphicsItem*> &itemUnderMouseList,
                                        const QList<FormEditorItem*> &selectedItemList)
{
    Q_ASSERT(!selectedItemList.isEmpty());

    foreach (QGraphicsItem* item, itemUnderMouseList) {
        FormEditorItem *formEditorItem = FormEditorItem::fromQGraphicsItem(item);
        if (formEditorItem
           && !selectedItemList.contains(formEditorItem)
           && isNotAncestorOfItemInList(formEditorItem, selectedItemList))
                return formEditorItem;

    }

    return 0;
}

QList<FormEditorItem*> movalbeItems(const QList<FormEditorItem*> &itemList)
{
    QList<FormEditorItem*> filteredItemList(itemList);

    QMutableListIterator<FormEditorItem*> listIterator(filteredItemList);
    while (listIterator.hasNext()) {
        FormEditorItem *item = listIterator.next();
        if (!item->qmlItemNode().isValid()
                || !item->qmlItemNode().instanceIsMovable()
                || !item->qmlItemNode().modelIsMovable()
                || item->qmlItemNode().instanceIsInLayoutable())
            listIterator.remove();
    }

    return filteredItemList;
}

QList<FormEditorItem*> MoveTool::movingItems(const QList<FormEditorItem*> &selectedItemList)
{
    QList<FormEditorItem*> filteredItemList = movalbeItems(selectedItemList);

    FormEditorItem* ancestorItem = ancestorIfOtherItemsAreChild(filteredItemList);

    if (ancestorItem != 0 && ancestorItem->qmlItemNode().isRootNode()) {
//        view()->changeToSelectionTool();
        return QList<FormEditorItem*>();
    }

    if (ancestorItem != 0 && ancestorItem->parentItem() != 0)  {
        QList<FormEditorItem*> ancestorItemList;
        ancestorItemList.append(ancestorItem);
        return ancestorItemList;
    }

    if (!haveSameParent(filteredItemList)) {
//        view()->changeToSelectionTool();
        return QList<FormEditorItem*>();
    }

    return filteredItemList;
}

void MoveTool::formEditorItemsChanged(const QList<FormEditorItem*> &itemList)
{
    m_selectionIndicator.updateItems(itemList);
    m_resizeIndicator.updateItems(itemList);
    m_anchorIndicator.updateItems(itemList);
    m_bindingIndicator.updateItems(itemList);
}

}
<commit_msg>QmlDesigner.FormEditor: using FormEditorItem::isContainer in MoveTool<commit_after>/****************************************************************************
**
** Copyright (C) 2013 Digia Plc and/or its subsidiary(-ies).
** Contact: http://www.qt-project.org/legal
**
** This file is part of Qt Creator.
**
** Commercial License Usage
** Licensees holding valid commercial Qt licenses may use this file in
** accordance with the commercial license agreement provided with the
** Software or, alternatively, in accordance with the terms contained in
** a written agreement between you and Digia.  For licensing terms and
** conditions see http://qt.digia.com/licensing.  For further information
** use the contact form at http://qt.digia.com/contact-us.
**
** GNU Lesser General Public License Usage
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 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, Digia gives you certain additional
** rights.  These rights are described in the Digia Qt LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
****************************************************************************/

#include "movetool.h"

#include "formeditorscene.h"
#include "formeditorview.h"
#include "formeditorwidget.h"

#include "resizehandleitem.h"

#include <QApplication>
#include <QGraphicsSceneMouseEvent>
#include <QAction>
#include <QDebug>

namespace QmlDesigner {

MoveTool::MoveTool(FormEditorView *editorView)
    : AbstractFormEditorTool(editorView),
    m_moveManipulator(editorView->scene()->manipulatorLayerItem(), editorView),
    m_selectionIndicator(editorView->scene()->manipulatorLayerItem()),
    m_resizeIndicator(editorView->scene()->manipulatorLayerItem()),
    m_anchorIndicator(editorView->scene()->manipulatorLayerItem()),
    m_bindingIndicator(editorView->scene()->manipulatorLayerItem())
{
    m_selectionIndicator.setCursor(Qt::SizeAllCursor);
}

MoveTool::~MoveTool()
{

}

void MoveTool::clear()
{
    m_moveManipulator.clear();
    m_movingItems.clear();
    m_selectionIndicator.clear();
    m_resizeIndicator.clear();
    m_anchorIndicator.clear();
    m_bindingIndicator.clear();

    AbstractFormEditorTool::clear();
}

void MoveTool::mousePressEvent(const QList<QGraphicsItem*> &itemList,
                                            QGraphicsSceneMouseEvent *event)
{
    if (event->button() == Qt::LeftButton) {
        if (itemList.isEmpty())
            return;
        m_movingItems = movingItems(items());
        if (m_movingItems.isEmpty())
            return;

        m_moveManipulator.setItems(m_movingItems);
        m_moveManipulator.begin(event->scenePos());
    }

    AbstractFormEditorTool::mousePressEvent(itemList, event);
}

void MoveTool::mouseMoveEvent(const QList<QGraphicsItem*> &itemList,
                                           QGraphicsSceneMouseEvent *event)
{
    if (m_moveManipulator.isActive()) {
        if (m_movingItems.isEmpty())
            return;

        //    m_selectionIndicator.hide();
        m_resizeIndicator.hide();
        m_anchorIndicator.hide();
        m_bindingIndicator.hide();

        FormEditorItem *containerItem = containerFormEditorItem(itemList, m_movingItems);
        if (containerItem && view()->currentState().isBaseState()) {
            if (containerItem != m_movingItems.first()->parentItem()
                    && event->modifiers().testFlag(Qt::ShiftModifier)) {
                m_moveManipulator.reparentTo(containerItem);
            }
        }

        m_moveManipulator.update(event->scenePos(), generateUseSnapping(event->modifiers()));
    }
}

void MoveTool::hoverMoveEvent(const QList<QGraphicsItem*> &itemList,
                        QGraphicsSceneMouseEvent * /*event*/)
{
    if (itemList.isEmpty()) {
        view()->changeToSelectionTool();
        return;
    }

    ResizeHandleItem* resizeHandle = ResizeHandleItem::fromGraphicsItem(itemList.first());
    if (resizeHandle) {
        view()->changeToResizeTool();
        return;
    }

    if (!topSelectedItemIsMovable(itemList)) {
        view()->changeToSelectionTool();
        return;
    }
}

void MoveTool::keyPressEvent(QKeyEvent *event)
{
    switch (event->key()) {
        case Qt::Key_Shift:
        case Qt::Key_Alt:
        case Qt::Key_Control:
        case Qt::Key_AltGr:
            event->setAccepted(false);
            return;
    }

    double moveStep = 1.0;

    if (event->modifiers().testFlag(Qt::ShiftModifier))
        moveStep = 10.0;

    if (!event->isAutoRepeat()) {
        QList<FormEditorItem*> movableItems(movingItems(items()));
        if (movableItems.isEmpty())
            return;

        m_moveManipulator.setItems(movableItems);
//        m_selectionIndicator.hide();
        m_resizeIndicator.hide();
        m_anchorIndicator.hide();
        m_bindingIndicator.hide();
        m_moveManipulator.beginRewriterTransaction();
    }

    switch (event->key()) {
        case Qt::Key_Left: m_moveManipulator.moveBy(-moveStep, 0.0); break;
        case Qt::Key_Right: m_moveManipulator.moveBy(moveStep, 0.0); break;
        case Qt::Key_Up: m_moveManipulator.moveBy(0.0, -moveStep); break;
        case Qt::Key_Down: m_moveManipulator.moveBy(0.0, moveStep); break;
    }

    if (event->key() == Qt::Key_Escape && !m_movingItems.isEmpty()) {
       event->accept();
       view()->changeToSelectionTool();
    }
}

void MoveTool::keyReleaseEvent(QKeyEvent *keyEvent)
{
    switch (keyEvent->key()) {
        case Qt::Key_Shift:
        case Qt::Key_Alt:
        case Qt::Key_Control:
        case Qt::Key_AltGr:
            keyEvent->setAccepted(false);
            return;
    }

    if (!keyEvent->isAutoRepeat()) {
        m_moveManipulator.beginRewriterTransaction();
        m_moveManipulator.clear();
//        m_selectionIndicator.show();
        m_resizeIndicator.show();
        m_anchorIndicator.show();
        m_bindingIndicator.show();
    }
}

void  MoveTool::dragLeaveEvent(QGraphicsSceneDragDropEvent * /*event*/)
{

}

void  MoveTool::dragMoveEvent(QGraphicsSceneDragDropEvent * /*event*/)
{

}

void MoveTool::mouseReleaseEvent(const QList<QGraphicsItem*> &itemList,
                                 QGraphicsSceneMouseEvent *event)
{
    if (m_moveManipulator.isActive()) {
        if (m_movingItems.isEmpty())
            return;

        m_moveManipulator.end(generateUseSnapping(event->modifiers()));

        m_selectionIndicator.show();
        m_resizeIndicator.show();
        m_anchorIndicator.show();
        m_bindingIndicator.show();
        m_movingItems.clear();
    }

    AbstractFormEditorTool::mouseReleaseEvent(itemList, event);
}

void MoveTool::mouseDoubleClickEvent(const QList<QGraphicsItem*> &itemList, QGraphicsSceneMouseEvent *event)
{
    AbstractFormEditorTool::mouseDoubleClickEvent(itemList, event);
}

void MoveTool::itemsAboutToRemoved(const QList<FormEditorItem*> &removedItemList)
{
    foreach (FormEditorItem* removedItem, removedItemList)
        m_movingItems.removeOne(removedItem);
}

void MoveTool::selectedItemsChanged(const QList<FormEditorItem*> &itemList)
{
    m_selectionIndicator.setItems(movingItems(itemList));
    m_resizeIndicator.setItems(itemList);
    m_anchorIndicator.setItems(itemList);
    m_bindingIndicator.setItems(itemList);
    updateMoveManipulator();
}

void MoveTool::instancesCompleted(const QList<FormEditorItem*> & /*itemList*/)
{
}

void  MoveTool::instancesParentChanged(const QList<FormEditorItem *> &itemList)
{
    m_moveManipulator.synchronizeInstanceParent(itemList);
}

void MoveTool::instancePropertyChange(const QList<QPair<ModelNode, PropertyName> > & /*propertyList*/)
{
}

bool MoveTool::haveSameParent(const QList<FormEditorItem*> &itemList)
{
    if (itemList.isEmpty())
        return false;

    QGraphicsItem *firstParent = itemList.first()->parentItem();
    foreach (FormEditorItem* item, itemList)
    {
        if (firstParent != item->parentItem())
            return false;
    }

    return true;
}

bool MoveTool::isAncestorOfAllItems(FormEditorItem* maybeAncestorItem,
                                    const QList<FormEditorItem*> &itemList)
{
    foreach (FormEditorItem* item, itemList)
    {
        if (!maybeAncestorItem->isAncestorOf(item) && item != maybeAncestorItem)
            return false;
    }

    return true;
}

FormEditorItem* MoveTool::ancestorIfOtherItemsAreChild(const QList<FormEditorItem*> &itemList)
{
    if (itemList.isEmpty())
        return 0;

    foreach (FormEditorItem* item, itemList)
    {
        if (isAncestorOfAllItems(item, itemList))
            return item;
    }

    return 0;
}

void MoveTool::updateMoveManipulator()
{
    if (m_moveManipulator.isActive())
        return;
}

void MoveTool::beginWithPoint(const QPointF &beginPoint)
{
    m_movingItems = movingItems(items());
    if (m_movingItems.isEmpty())
        return;

    m_moveManipulator.setItems(m_movingItems);
    m_moveManipulator.begin(beginPoint);
}

static bool isNotAncestorOfItemInList(FormEditorItem *formEditorItem, const QList<FormEditorItem*> &itemList)
{
    foreach (FormEditorItem *item, itemList) {
        if (item
            && item->qmlItemNode().isValid()
            && item->qmlItemNode().isAncestorOf(formEditorItem->qmlItemNode()))
            return false;
    }

    return true;
}

FormEditorItem* MoveTool::containerFormEditorItem(const QList<QGraphicsItem*> &itemUnderMouseList,
                                        const QList<FormEditorItem*> &selectedItemList)
{
    Q_ASSERT(!selectedItemList.isEmpty());

    foreach (QGraphicsItem* item, itemUnderMouseList) {
        FormEditorItem *formEditorItem = FormEditorItem::fromQGraphicsItem(item);
        if (formEditorItem
           && !selectedItemList.contains(formEditorItem)
           && isNotAncestorOfItemInList(formEditorItem, selectedItemList)
           && formEditorItem->isContainer())
                return formEditorItem;

    }

    return 0;
}

QList<FormEditorItem*> movalbeItems(const QList<FormEditorItem*> &itemList)
{
    QList<FormEditorItem*> filteredItemList(itemList);

    QMutableListIterator<FormEditorItem*> listIterator(filteredItemList);
    while (listIterator.hasNext()) {
        FormEditorItem *item = listIterator.next();
        if (!item->qmlItemNode().isValid()
                || !item->qmlItemNode().instanceIsMovable()
                || !item->qmlItemNode().modelIsMovable()
                || item->qmlItemNode().instanceIsInLayoutable())
            listIterator.remove();
    }

    return filteredItemList;
}

QList<FormEditorItem*> MoveTool::movingItems(const QList<FormEditorItem*> &selectedItemList)
{
    QList<FormEditorItem*> filteredItemList = movalbeItems(selectedItemList);

    FormEditorItem* ancestorItem = ancestorIfOtherItemsAreChild(filteredItemList);

    if (ancestorItem != 0 && ancestorItem->qmlItemNode().isRootNode()) {
//        view()->changeToSelectionTool();
        return QList<FormEditorItem*>();
    }

    if (ancestorItem != 0 && ancestorItem->parentItem() != 0)  {
        QList<FormEditorItem*> ancestorItemList;
        ancestorItemList.append(ancestorItem);
        return ancestorItemList;
    }

    if (!haveSameParent(filteredItemList)) {
//        view()->changeToSelectionTool();
        return QList<FormEditorItem*>();
    }

    return filteredItemList;
}

void MoveTool::formEditorItemsChanged(const QList<FormEditorItem*> &itemList)
{
    m_selectionIndicator.updateItems(itemList);
    m_resizeIndicator.updateItems(itemList);
    m_anchorIndicator.updateItems(itemList);
    m_bindingIndicator.updateItems(itemList);
}

}
<|endoftext|>


<commit_before>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: SlsPageObjectViewContact.cxx,v $
 *
 *  $Revision: 1.6 $
 *
 *  last change: $Author: ihi $ $Date: 2006-11-14 14:36:35 $
 *
 *  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
 *
 ************************************************************************/

// MARKER(update_precomp.py): autogen include statement, do not remove
#include "precompiled_sd.hxx"

#include "view/SlsPageObjectViewContact.hxx"

#include "model/SlsPageDescriptor.hxx"
#include "controller/SlsPageObjectFactory.hxx"

#include <svx/svdopage.hxx>

#ifndef _TOOLS_DEBUG_HXX
#include <tools/debug.hxx>
#endif

using namespace ::sdr::contact;

namespace sd { namespace slidesorter { namespace view {

PageObjectViewContact::PageObjectViewContact (
    SdrPageObj& rPageObj,
    model::PageDescriptor& rDescriptor)
    : ViewContactOfPageObj (rPageObj),
      mbIsValid(true),
      mrDescriptor(rDescriptor)
{
}

PageObjectViewContact::~PageObjectViewContact (void)
{
}

ViewObjectContact&
    PageObjectViewContact::CreateObjectSpecificViewObjectContact(
        ObjectContact& rObjectContact)
{
    ViewObjectContact* pResult
        = mrDescriptor.GetPageObjectFactory().CreateViewObjectContact (
            rObjectContact,
            *this);
    DBG_ASSERT (pResult!=NULL,
        "PageObjectViewContact::CreateObjectSpecificViewObjectContact() was not able to create object.");
    return *pResult;
}

const SdrPage* PageObjectViewContact::GetPage (void) const
{
    if (mbIsValid)
        return GetReferencedPage();
    else
        return NULL;
}

void PageObjectViewContact::CalcPaintRectangle (void)
{
    ViewContactOfPageObj::CalcPaintRectangle();
    if (mbIsValid)
    {
        maPageObjectBoundingBox = maPaintRectangle;
        SvBorder aBorder (mrDescriptor.GetModelBorder());
        maPaintRectangle.Left() -= aBorder.Left();
        maPaintRectangle.Right() += aBorder.Right();
        maPaintRectangle.Top() -= aBorder.Top();
        maPaintRectangle.Bottom() += aBorder.Bottom();
    }
}

Rectangle PageObjectViewContact::GetPageRectangle (void)
{
    return GetPageObj().GetCurrentBoundRect();
}

Rectangle PageObjectViewContact::GetPageObjectBoundingBox (void) const
{
    return maPageObjectBoundingBox;
}

SdrPageObj& PageObjectViewContact::GetPageObject (void) const
{
    return ViewContactOfPageObj::GetPageObj();
}

void PageObjectViewContact::PrepareDelete (void)
{
    mbIsValid = false;
}

} } } // end of namespace ::sd::slidesorter::view
<commit_msg>INTEGRATION: CWS components1 (1.4.148); FILE MERGED 2006/11/21 16:23:20 af 1.4.148.3: RESYNC: (1.5-1.6); FILE MERGED 2006/09/25 17:26:33 af 1.4.148.2: RESYNC: (1.4-1.5); FILE MERGED 2006/08/22 11:49:35 af 1.4.148.1: #i68075# Added ActionChanged() method.<commit_after>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: SlsPageObjectViewContact.cxx,v $
 *
 *  $Revision: 1.7 $
 *
 *  last change: $Author: rt $ $Date: 2007-04-03 16:19:16 $
 *
 *  The Contents of this file are made available subject to
 *  the terms of GNU Lesser General Public License Version 2.1.
 *
 *
 *    GNU Lesser General Public License Version 2.1
 *    =============================================
 *    Copyright 2005 by Sun Microsystems, Inc.
 *    901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *    This library is free software; you can redistribute it and/or
 *    modify it under the terms of the GNU Lesser General Public
 *    License version 2.1, as published by the Free Software Foundation.
 *
 *    This library is distributed in the hope that it will be useful,
 *    but WITHOUT ANY WARRANTY; without even the implied warranty of
 *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *    Lesser General Public License for more details.
 *
 *    You should have received a copy of the GNU Lesser General Public
 *    License along with this library; if not, write to the Free Software
 *    Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *    MA  02111-1307  USA
 *
 ************************************************************************/

// MARKER(update_precomp.py): autogen include statement, do not remove
#include "precompiled_sd.hxx"

#include "view/SlsPageObjectViewContact.hxx"

#include "model/SlsPageDescriptor.hxx"
#include "controller/SlsPageObjectFactory.hxx"

#include <svx/svdopage.hxx>

#ifndef _TOOLS_DEBUG_HXX
#include <tools/debug.hxx>
#endif

using namespace ::sdr::contact;

namespace sd { namespace slidesorter { namespace view {

PageObjectViewContact::PageObjectViewContact (
    SdrPageObj& rPageObj,
    model::PageDescriptor& rDescriptor)
    : ViewContactOfPageObj (rPageObj),
      mbIsValid(true),
      mrDescriptor(rDescriptor)
{
}

PageObjectViewContact::~PageObjectViewContact (void)
{
}

ViewObjectContact&
    PageObjectViewContact::CreateObjectSpecificViewObjectContact(
        ObjectContact& rObjectContact)
{
    ViewObjectContact* pResult
        = mrDescriptor.GetPageObjectFactory().CreateViewObjectContact (
            rObjectContact,
            *this);
    DBG_ASSERT (pResult!=NULL,
        "PageObjectViewContact::CreateObjectSpecificViewObjectContact() was not able to create object.");
    return *pResult;
}

const SdrPage* PageObjectViewContact::GetPage (void) const
{
    if (mbIsValid)
        return GetReferencedPage();
    else
        return NULL;
}

void PageObjectViewContact::CalcPaintRectangle (void)
{
    ViewContactOfPageObj::CalcPaintRectangle();
    if (mbIsValid)
    {
        maPageObjectBoundingBox = maPaintRectangle;
        SvBorder aBorder (mrDescriptor.GetModelBorder());
        maPaintRectangle.Left() -= aBorder.Left();
        maPaintRectangle.Right() += aBorder.Right();
        maPaintRectangle.Top() -= aBorder.Top();
        maPaintRectangle.Bottom() += aBorder.Bottom();
    }
}

Rectangle PageObjectViewContact::GetPageRectangle (void)
{
    return GetPageObj().GetCurrentBoundRect();
}

void PageObjectViewContact::ActionChanged (void)
{
    ViewContactOfPageObj::ActionChanged();
}

Rectangle PageObjectViewContact::GetPageObjectBoundingBox (void) const
{
    return maPageObjectBoundingBox;
}

SdrPageObj& PageObjectViewContact::GetPageObject (void) const
{
    return ViewContactOfPageObj::GetPageObj();
}

void PageObjectViewContact::PrepareDelete (void)
{
    mbIsValid = false;
}

} } } // end of namespace ::sd::slidesorter::view
<|endoftext|>


<commit_before>// ******************************************************************************************
// * This project is licensed under the GNU Affero GPL v3. Copyright © 2014 A3Wasteland.com *
// ******************************************************************************************
#include "player_sys.sqf"

class playerSettings {

	idd = playersys_DIALOG;
	movingEnable = true;
	enableSimulation = true;
	onLoad = "[] execVM 'client\systems\playerMenu\item_list.sqf'";

	class controlsBackground {

		class MainBG : w_RscPicture {
			idc = -1;
			colorText[] = {1, 1, 1, 1};
			colorBackground[] = {0,0,0,0};
			text = "#(argb,8,8,3)color(0,0,0,0.6)";
			moving = true;
			x = 0.0; y = 0.1;
			w = .745; h = 0.65;
		};

		class TopBar: w_RscPicture
		{
			idc = -1;
			colorText[] = {1, 1, 1, 1};
			colorBackground[] = {0,0,0,0};
			text = "#(argb,8,8,3)color(0.45,0.005,0,1)";

			x = 0;
			y = 0.1;
			w = 0.745;
			h = 0.05;
		};

		class MainTitle : w_RscText {
			idc = -1;
			text = "Player Menu";
			sizeEx = 0.04;
			shadow = 2;
			x = 0.260; y = 0.1;
			w = 0.3; h = 0.05;
		};

		class waterIcon : w_RscPicture {
			idc = -1;
			text = "client\icons\energydrink.paa";
			x = 0.022; y = 0.2;
			w = 0.04 / (4/3); h = 0.04;
		};

		class foodIcon : w_RscPicture {
			idc = -1;
			text = "client\icons\cannedfood.paa";
			x = 0.022; y = 0.26;
			w = 0.04 / (4/3); h = 0.04;
		};

		class moneyIcon : w_RscPicture {
			idc = -1;
			text = "client\icons\money.paa";
			x = 0.022; y = 0.32;
			w = 0.04 / (4/3); h = 0.04;
		};

		class serverLogo : w_RscPicture {
			idc = -1;
			text = "mapconfig\logo.paa";
			x = 0.225; y = 0.20;
			w = 0.32 / (4/3); h = 0.32;
		};

		class waterText : w_RscText {
			idc = water_text;
			text = "";
			sizeEx = 0.03;
			x = 0.06; y = 0.193;
			w = 0.3; h = 0.05;
		};

		class foodText : w_RscText {
			idc = food_text;
			sizeEx = 0.03;
			text = "";
			x = 0.06; y = 0.254;
			w = 0.3; h = 0.05;
		};

		class moneyText : w_RscText {
			idc = money_text;
			text = "";
			sizeEx = 0.03;
			x = 0.06; y = 0.313;
			w = 0.3; h = 0.05;
		};

		class distanceText : w_RscText {
			idc = view_range_text;
			text = "View range:";
			sizeEx = 0.025;
			x = 0.03; y = 0.40;
			w = 0.3; h = 0.02;
		};

		class uptimeText : w_RscText {
			idc = uptime_text;
			text = "";
			sizeEx = 0.030;
			x = 0.52; y = 0.69;
			w = 0.225; h = 0.03;
		};
	};

	class controls {

		class itemList : w_Rsclist {
			idc = item_list;
			x = 0.49; y = 0.185;
			w = 0.235; h = 0.325;
		};

		class DropButton : w_RscButton {
			idc = -1;
			text = "Drop";
			onButtonClick = "[1] execVM 'client\systems\playerMenu\itemfnc.sqf'";
			x = 0.610; y = 0.525;
			w = 0.116; h = 0.033 * safezoneH;
		};

		class UseButton : w_RscButton {
			idc = -1;
			text = "Use";
			onButtonClick = "[0] execVM 'client\systems\playerMenu\itemfnc.sqf'";
			x = 0.489; y = 0.525;
			w = 0.116; h = 0.033 * safezoneH;
		};

		class moneyInput: w_RscCombo {
			idc = money_value;
			x = 0.610; y = 0.618;
			w = .116; h = .030;
		};

		class DropcButton : w_RscButton {
			idc = -1;
			text = "Drop";
			onButtonClick = "[] execVM 'client\systems\playerMenu\dropMoney.sqf'";
			x = 0.489; y = 0.60;
			w = 0.116; h = 0.033 * safezoneH;
		};

		class CloseButton : w_RscButton {
			idc = close_button;
			text = "Close";
			onButtonClick = "[] execVM 'client\systems\playerMenu\closePlayerMenu.sqf'";
			x = 0.02; y = 0.66;
			w = 0.125; h = 0.033 * safezoneH;
		};

		class GroupsButton : w_RscButton {
			idc = groupButton;
			text = "Group Management";
			onButtonClick = "[] execVM 'client\systems\groups\loadGroupManagement.sqf'";
			x = 0.158; y = 0.66;
			w = 0.225; h = 0.033 * safezoneH;
		};

		class btnDistanceNear : w_RscButton {
			idc = -1;
			text = "Low";
			onButtonClick = "setViewDistance 1000; setObjectViewDistance 1200; setTerrainGrid 27;";
			x = 0.02; y = 0.43;
			w = 0.125; h = 0.033 * safezoneH;
		};

		class btnDistanceMedium : w_RscButton {
			idc = -1;
			text = "Medium";
			onButtonClick = "setViewDistance 1500; setObjectViewDistance 1500; setTerrainGrid 25;";
			x = 0.02; y = 0.5;
			w = 0.125; h = 0.033 * safezoneH;
		};

		class btnDistanceFar : w_RscButton {
			idc = -1;
			text = "High";
			onButtonClick = "setViewDistance 2500; setObjectViewDistance 2500; setTerrainGrid 12.5;";
			x = 0.02; y = 0.57;
			w = 0.125; h = 0.033 * safezoneH;
		};

		class TOParmaInfoButton : w_RscButton { //btnDistanceEffects
			idc = -1;
			text = "Server Info";
			onButtonClick = "[] execVM 'addons\TOParmaInfo\loadTOParmaInfo.sqf'";
			x = 0.158; y = 0.57;
			w = 0.225; h = 0.033 * safezoneH;
		};

	};
};

<commit_msg>Testing<commit_after>// ******************************************************************************************
// * This project is licensed under the GNU Affero GPL v3. Copyright © 2014 A3Wasteland.com *
// ******************************************************************************************
#include "player_sys.sqf"

class playerSettings {

	idd = playersys_DIALOG;
	movingEnable = true;
	enableSimulation = true;
	onLoad = "[] execVM 'client\systems\playerMenu\item_list.sqf'";

	class controlsBackground {

		class MainBG : w_RscPicture {
			idc = -1;
			colorText[] = {1, 1, 1, 1};
			colorBackground[] = {0,0,0,0};
			text = "#(argb,8,8,3)color(0,0,0,0.6)";
			moving = true;
			x = 0.0; y = 0.1;
			w = .745; h = 0.65;
		};

		class TopBar: w_RscPicture
		{
			idc = -1;
			colorText[] = {1, 1, 1, 1};
			colorBackground[] = {0,0,0,0};
			text = "#(argb,8,8,3)color(0.45,0.005,0,1)";

			x = 0;
			y = 0.1;
			w = 0.745;
			h = 0.05;
		};

		class MainTitle : w_RscText {
			idc = -1;
			text = "Player Menu";
			sizeEx = 0.04;
			shadow = 2;
			x = 0.260; y = 0.1;
			w = 0.3; h = 0.05;
		};

		class waterIcon : w_RscPicture {
			idc = -1;
			text = "client\icons\energydrink.paa";
			x = 0.022; y = 0.2;
			w = 0.04 / (4/3); h = 0.04;
		};

		class foodIcon : w_RscPicture {
			idc = -1;
			text = "client\icons\cannedfood.paa";
			x = 0.022; y = 0.26;
			w = 0.04 / (4/3); h = 0.04;
		};

		class moneyIcon : w_RscPicture {
			idc = -1;
			text = "client\icons\money.paa";
			x = 0.022; y = 0.32;
			w = 0.04 / (4/3); h = 0.04;
		};

		class serverLogo : w_RscPicture {
			idc = -1;
			text = "mapconfig\logo.paa";
			x = 0.225; y = 0.20;
			w = 0.32 / (4/3); h = 0.32;
		};

		class waterText : w_RscText {
			idc = water_text;
			text = "";
			sizeEx = 0.03;
			x = 0.06; y = 0.193;
			w = 0.3; h = 0.05;
		};

		class foodText : w_RscText {
			idc = food_text;
			sizeEx = 0.03;
			text = "";
			x = 0.06; y = 0.254;
			w = 0.3; h = 0.05;
		};

		class moneyText : w_RscText {
			idc = money_text;
			text = "";
			sizeEx = 0.03;
			x = 0.06; y = 0.313;
			w = 0.3; h = 0.05;
		};

		class distanceText : w_RscText {
			idc = view_range_text;
			text = "View range:";
			sizeEx = 0.025;
			x = 0.03; y = 0.40;
			w = 0.3; h = 0.02;
		};

		class uptimeText : w_RscText {
			idc = uptime_text;
			text = "";
			sizeEx = 0.030;
			x = 0.52; y = 0.69;
			w = 0.225; h = 0.03;
		};
	};

	class controls {

		class itemList : w_Rsclist {
			idc = item_list;
			x = 0.49; y = 0.185;
			w = 0.235; h = 0.325;
		};

		class DropButton : w_RscButton {
			idc = -1;
			text = "Drop";
			onButtonClick = "[1] execVM 'client\systems\playerMenu\itemfnc.sqf'";
			x = 0.610; y = 0.525;
			w = 0.116; h = 0.033 * safezoneH;
		};

		class UseButton : w_RscButton {
			idc = -1;
			text = "Use";
			onButtonClick = "[0] execVM 'client\systems\playerMenu\itemfnc.sqf'";
			x = 0.489; y = 0.525;
			w = 0.116; h = 0.033 * safezoneH;
		};

		class moneyInput: w_RscCombo {
			idc = money_value;
			x = 0.610; y = 0.618;
			w = .116; h = .030;
		};

		class DropcButton : w_RscButton {
			idc = -1;
			text = "Drop";
			onButtonClick = "[] execVM 'client\systems\playerMenu\dropMoney.sqf'";
			x = 0.489; y = 0.60;
			w = 0.116; h = 0.033 * safezoneH;
		};

		class CloseButton : w_RscButton {
			idc = close_button;
			text = "Close";
			onButtonClick = "[] execVM 'client\systems\playerMenu\closePlayerMenu.sqf'";
			x = 0.02; y = 0.66;
			w = 0.125; h = 0.033 * safezoneH;
		};

		class GroupsButton : w_RscButton {
			idc = groupButton;
			text = "Group Management";
			onButtonClick = "[] execVM 'client\systems\groups\loadGroupManagement.sqf'";
			x = 0.158; y = 0.66;
			w = 0.225; h = 0.033 * safezoneH;
		};

		class btnDistanceNear : w_RscButton {
			idc = -1;
			text = "Low";
			onButtonClick = "setViewDistance 1000; setObjectViewDistance 1200; setTerrainGrid 27;";
			x = 0.02; y = 0.43;
			w = 0.125; h = 0.033 * safezoneH;
		};

		class btnDistanceMedium : w_RscButton {
			idc = -1;
			text = "Medium";
			onButtonClick = "setViewDistance 1500; setObjectViewDistance 1500; setTerrainGrid 25;";
			x = 0.02; y = 0.5;
			w = 0.125; h = 0.033 * safezoneH;
		};

		class btnDistanceFar : w_RscButton {
			idc = -1;
			text = "High";
			onButtonClick = "setViewDistance 2500; setObjectViewDistance 2500; setTerrainGrid 12.5;";
			x = 0.02; y = 0.57;
			w = 0.125; h = 0.033 * safezoneH;
		};

		class TOParmaInfoButton : w_RscButton { //btnDistanceEffects
			idc = -1;
			text = "Server Info";
			onButtonClick = "[] execVM 'addons\TOParmaInfo\loadTOParmaInfo.sqf'";
			x = 0.158; y = 0.57;
			w = 0.225; h = 0.033 * safezoneH;
		};

		/* class showStat : w_RscButton {
			idc = -1;
			text = "Show Stats";
			onButtonClick = "[] execVM 'addons\statusBar\statusbar.sqf'";
			x = 0.158; y = 0.5;
			w = 0.225; h = 0.033 * safezoneH;
		}; */

	};
};

<|endoftext|>


<commit_before>/** Copyright (C) 2015 Ultimaker - Released under terms of the AGPLv3 License */
#include "polygon.h"

#include "linearAlg2D.h" // pointLiesOnTheRightOfLine

#include "../debug.h"

namespace cura
{

bool PolygonRef::shorterThan(int64_t check_length) const
{
    const PolygonRef& polygon = *this;
    const Point* p0 = &polygon.back();
    for (const Point& p1 : polygon)
    {
        check_length += vSize(*p0 - p1);
        if (check_length >= check_length)
        {
            return false;
        }
        p0 = &p1;
    }
    return true;
}

bool PolygonRef::inside(Point p, bool border_result)
{
    PolygonRef thiss = *this;
    if (size() < 1)
    {
        return false;
    }

    int crossings = 0;
    Point p0 = back();
    for(unsigned int n=0; n<size(); n++)
    {
        Point p1 = thiss[n];
        // no tests unless the segment p0-p1 is at least partly at, or to right of, p.X
        short comp = LinearAlg2D::pointLiesOnTheRightOfLine(p, p0, p1);
        if (comp == 1)
        {
            crossings++;
        }
        else if (comp == 0)
        {
            return border_result;
        }
        p0 = p1;
    }
    return (crossings % 2) == 1;
}

bool Polygons::inside(Point p, bool border_result) const
{
    const Polygons& thiss = *this;
    if (size() < 1)
    {
        return false;
    }

    int crossings = 0;
    for (const ClipperLib::Path& poly : thiss)
    {
        Point p0 = poly.back();
        for (const Point& p1 : poly)
        {
            short comp = LinearAlg2D::pointLiesOnTheRightOfLine(p, p0, p1);
            if (comp == 1)
            {
                crossings++;
            }
            else if (comp == 0)
            {
                return border_result;
            }
            p0 = p1;
        }
    }
    return (crossings % 2) == 1;
}

unsigned int Polygons::findInside(Point p, bool border_result)
{
    Polygons& thiss = *this;
    if (size() < 1)
    {
        return false;
    }

    int64_t min_x[size()];
    std::fill_n(min_x, size(), std::numeric_limits<int64_t>::max());  // initialize with int.max
    int crossings[size()];
    std::fill_n(crossings, size(), 0);  // initialize with zeros

    for (unsigned int poly_idx = 0; poly_idx < size(); poly_idx++)
    {
        PolygonRef poly = thiss[poly_idx];
        Point p0 = poly.back();
        for(Point& p1 : poly)
        {
            short comp = LinearAlg2D::pointLiesOnTheRightOfLine(p, p0, p1);
            if (comp == 1)
            {
                crossings[poly_idx]++;
                int64_t x;
                if (p1.Y == p0.Y)
                {
                    x = p0.X;
                }
                else
                {
                    x = p0.X + (p1.X-p0.X) * (p.Y-p0.Y) / (p1.Y-p0.Y);
                }
                if (x < min_x[poly_idx])
                {
                    min_x[poly_idx] = x;
                }
            }
            else if (border_result && comp == 0)
            {
                return poly_idx;
            }
            p0 = p1;
        }
    }

    int64_t min_x_uneven = std::numeric_limits<int64_t>::max();
    unsigned int ret = NO_INDEX;
    unsigned int n_unevens = 0;
    for (unsigned int array_idx = 0; array_idx < size(); array_idx++)
    {
        if (crossings[array_idx] % 2 == 1)
        {
            n_unevens++;
            if (min_x[array_idx] < min_x_uneven)
            {
                min_x_uneven = min_x[array_idx];
                ret = array_idx;
            }
        }
    }
    if (n_unevens % 2 == 0) { ret = NO_INDEX; }
    return ret;
}

void PolygonRef::simplify(int smallest_line_segment_squared, int allowed_error_distance_squared){
    PolygonRef& thiss = *this;

    if (size() <= 2)
    {
        clear();
        return;
    }

    { // remove segments smaller than allowed_error_distance
    // this is neccesary in order to avoid the case where a long segment is followed by a lot of small segments would get simplified to a long segment going to the wrong end point
    //  .......                _                 _______
    // |                      /                 |
    // |     would become    /    instead of    |
    // |                    /                   |
        Point* last = &thiss.back();
        unsigned int writing_idx = 0;
        for (unsigned int poly_idx = 0; poly_idx < size(); poly_idx++)
        {
            Point& here = thiss[poly_idx];
            if (vSize2(*last - here) < smallest_line_segment_squared)
            {
                // don't add the point
            }
            else
            {
                thiss[writing_idx] = here;
                writing_idx++;
                last = &here;
            }
        }
        path->erase(path->begin() + writing_idx , path->end());
    }

    if (size() < 3)
    {
        clear();
        return;
    }

    Point* last = &thiss[0];
    unsigned int writing_idx = 1;
    for (unsigned int poly_idx = 1; poly_idx < size(); poly_idx++)
    {
        Point& here = thiss[poly_idx];
        if ( vSize2(here-*last) < allowed_error_distance_squared )
        {
            // don't add the point to the result
            continue;
        }
        Point& next = thiss[(poly_idx+1) % size()];
        char here_is_beyond_line = 0;
        int64_t error2 = LinearAlg2D::getDist2FromLineSegment(*last, here, next, &here_is_beyond_line);
        if (here_is_beyond_line == 0 && error2 < allowed_error_distance_squared)
        {// don't add the point to the result
        } else
        {
            thiss[writing_idx] = here;
            writing_idx++;
            last = &here;
        }
    }
    path->erase(path->begin() + writing_idx , path->end());

    if (size() < 3)
    {
        clear();
        return;
    }

    { // handle the line segments spanning the vector end and begin
        Point* last = &thiss.back();
        Point& here = thiss[0];
        if ( vSize2(here-*last) < allowed_error_distance_squared )
        {
            remove(0);
        }
        Point& next = thiss[1];
        int64_t error2 = LinearAlg2D::getDist2FromLineSegment(*last, here, next);
        if (error2 < allowed_error_distance_squared)
        {
            remove(0);
        } else
        {
            // leave it in
        }
    }

    if (size() < 3)
    {
        clear();
        return;
    }
}

std::vector<PolygonsPart> Polygons::splitIntoParts(bool unionAll) const
{
    std::vector<PolygonsPart> ret;
    ClipperLib::Clipper clipper(clipper_init);
    ClipperLib::PolyTree resultPolyTree;
    clipper.AddPaths(paths, ClipperLib::ptSubject, true);
    if (unionAll)
        clipper.Execute(ClipperLib::ctUnion, resultPolyTree, ClipperLib::pftNonZero, ClipperLib::pftNonZero);
    else
        clipper.Execute(ClipperLib::ctUnion, resultPolyTree);

    splitIntoParts_processPolyTreeNode(&resultPolyTree, ret);
    return ret;
}

void Polygons::splitIntoParts_processPolyTreeNode(ClipperLib::PolyNode* node, std::vector<PolygonsPart>& ret) const
{
    for(int n=0; n<node->ChildCount(); n++)
    {
        ClipperLib::PolyNode* child = node->Childs[n];
        PolygonsPart part;
        part.add(child->Contour);
        for(int i=0; i<child->ChildCount(); i++)
        {
            part.add(child->Childs[i]->Contour);
            splitIntoParts_processPolyTreeNode(child->Childs[i], ret);
        }
        ret.push_back(part);
    }
}

unsigned int PartsView::getPartContaining(unsigned int poly_idx, unsigned int* boundary_poly_idx)
{
    PartsView& partsView = *this;
    for (unsigned int part_idx_now = 0; part_idx_now < partsView.size(); part_idx_now++)
    {
        std::vector<unsigned int>& partView = partsView[part_idx_now];
        if (partView.size() == 0) { continue; }
        std::vector<unsigned int>::iterator result = std::find(partView.begin(), partView.end(), poly_idx);
        if (result != partView.end())
        {
            if (boundary_poly_idx) { *boundary_poly_idx = partView[0]; }
            return part_idx_now;
        }
    }
    return NO_INDEX;
}

PolygonsPart PartsView::assemblePart(unsigned int part_idx)
{
    PartsView& partsView = *this;
    PolygonsPart ret;
    if (part_idx != NO_INDEX)
    {
        for (unsigned int poly_idx_ff : partsView[part_idx])
        {
            ret.add(polygons[poly_idx_ff]);
        }
    }
    return ret;
}

PolygonsPart PartsView::assemblePartContaining(unsigned int poly_idx, unsigned int* boundary_poly_idx)
{
    PolygonsPart ret;
    unsigned int part_idx = getPartContaining(poly_idx, boundary_poly_idx);
    if (part_idx != NO_INDEX)
    {
        return assemblePart(part_idx);
    }
    return ret;
}

PartsView Polygons::splitIntoPartsView(bool unionAll)
{
    Polygons reordered;
    PartsView partsView(*this);
    ClipperLib::Clipper clipper(clipper_init);
    ClipperLib::PolyTree resultPolyTree;
    clipper.AddPaths(paths, ClipperLib::ptSubject, true);
    if (unionAll)
        clipper.Execute(ClipperLib::ctUnion, resultPolyTree, ClipperLib::pftNonZero, ClipperLib::pftNonZero);
    else
        clipper.Execute(ClipperLib::ctUnion, resultPolyTree);

    splitIntoPartsView_processPolyTreeNode(partsView, reordered, &resultPolyTree);

    (*this) = reordered;
    return partsView;
}

void Polygons::splitIntoPartsView_processPolyTreeNode(PartsView& partsView, Polygons& reordered, ClipperLib::PolyNode* node) const
{
    for(int n=0; n<node->ChildCount(); n++)
    {
        ClipperLib::PolyNode* child = node->Childs[n];
        partsView.emplace_back();
        unsigned int pos = partsView.size() - 1;
        partsView[pos].push_back(reordered.size());
        reordered.add(child->Contour);
        for(int i = 0; i < child->ChildCount(); i++)
        {
            partsView[pos].push_back(reordered.size());
            reordered.add(child->Childs[i]->Contour);
            splitIntoPartsView_processPolyTreeNode(partsView, reordered, child->Childs[i]);
        }
    }
}

}//namespace cura
<commit_msg>Compare in PolygonRef::shorterThan is strange.<commit_after>/** Copyright (C) 2015 Ultimaker - Released under terms of the AGPLv3 License */
#include "polygon.h"

#include "linearAlg2D.h" // pointLiesOnTheRightOfLine

#include "../debug.h"

namespace cura
{

bool PolygonRef::shorterThan(int64_t check_length) const
{
    const PolygonRef& polygon = *this;
    const Point* p0 = &polygon.back();
    int64_t length = 0;
    for (const Point& p1 : polygon)
    {
        length += vSize(*p0 - p1);
        if (length >= check_length)
        {
            return false;
        }
        p0 = &p1;
    }
    return true;
}

bool PolygonRef::inside(Point p, bool border_result)
{
    PolygonRef thiss = *this;
    if (size() < 1)
    {
        return false;
    }

    int crossings = 0;
    Point p0 = back();
    for(unsigned int n=0; n<size(); n++)
    {
        Point p1 = thiss[n];
        // no tests unless the segment p0-p1 is at least partly at, or to right of, p.X
        short comp = LinearAlg2D::pointLiesOnTheRightOfLine(p, p0, p1);
        if (comp == 1)
        {
            crossings++;
        }
        else if (comp == 0)
        {
            return border_result;
        }
        p0 = p1;
    }
    return (crossings % 2) == 1;
}

bool Polygons::inside(Point p, bool border_result) const
{
    const Polygons& thiss = *this;
    if (size() < 1)
    {
        return false;
    }

    int crossings = 0;
    for (const ClipperLib::Path& poly : thiss)
    {
        Point p0 = poly.back();
        for (const Point& p1 : poly)
        {
            short comp = LinearAlg2D::pointLiesOnTheRightOfLine(p, p0, p1);
            if (comp == 1)
            {
                crossings++;
            }
            else if (comp == 0)
            {
                return border_result;
            }
            p0 = p1;
        }
    }
    return (crossings % 2) == 1;
}

unsigned int Polygons::findInside(Point p, bool border_result)
{
    Polygons& thiss = *this;
    if (size() < 1)
    {
        return false;
    }

    int64_t min_x[size()];
    std::fill_n(min_x, size(), std::numeric_limits<int64_t>::max());  // initialize with int.max
    int crossings[size()];
    std::fill_n(crossings, size(), 0);  // initialize with zeros

    for (unsigned int poly_idx = 0; poly_idx < size(); poly_idx++)
    {
        PolygonRef poly = thiss[poly_idx];
        Point p0 = poly.back();
        for(Point& p1 : poly)
        {
            short comp = LinearAlg2D::pointLiesOnTheRightOfLine(p, p0, p1);
            if (comp == 1)
            {
                crossings[poly_idx]++;
                int64_t x;
                if (p1.Y == p0.Y)
                {
                    x = p0.X;
                }
                else
                {
                    x = p0.X + (p1.X-p0.X) * (p.Y-p0.Y) / (p1.Y-p0.Y);
                }
                if (x < min_x[poly_idx])
                {
                    min_x[poly_idx] = x;
                }
            }
            else if (border_result && comp == 0)
            {
                return poly_idx;
            }
            p0 = p1;
        }
    }

    int64_t min_x_uneven = std::numeric_limits<int64_t>::max();
    unsigned int ret = NO_INDEX;
    unsigned int n_unevens = 0;
    for (unsigned int array_idx = 0; array_idx < size(); array_idx++)
    {
        if (crossings[array_idx] % 2 == 1)
        {
            n_unevens++;
            if (min_x[array_idx] < min_x_uneven)
            {
                min_x_uneven = min_x[array_idx];
                ret = array_idx;
            }
        }
    }
    if (n_unevens % 2 == 0) { ret = NO_INDEX; }
    return ret;
}

void PolygonRef::simplify(int smallest_line_segment_squared, int allowed_error_distance_squared){
    PolygonRef& thiss = *this;

    if (size() <= 2)
    {
        clear();
        return;
    }

    { // remove segments smaller than allowed_error_distance
    // this is neccesary in order to avoid the case where a long segment is followed by a lot of small segments would get simplified to a long segment going to the wrong end point
    //  .......                _                 _______
    // |                      /                 |
    // |     would become    /    instead of    |
    // |                    /                   |
        Point* last = &thiss.back();
        unsigned int writing_idx = 0;
        for (unsigned int poly_idx = 0; poly_idx < size(); poly_idx++)
        {
            Point& here = thiss[poly_idx];
            if (vSize2(*last - here) < smallest_line_segment_squared)
            {
                // don't add the point
            }
            else
            {
                thiss[writing_idx] = here;
                writing_idx++;
                last = &here;
            }
        }
        path->erase(path->begin() + writing_idx , path->end());
    }

    if (size() < 3)
    {
        clear();
        return;
    }

    Point* last = &thiss[0];
    unsigned int writing_idx = 1;
    for (unsigned int poly_idx = 1; poly_idx < size(); poly_idx++)
    {
        Point& here = thiss[poly_idx];
        if ( vSize2(here-*last) < allowed_error_distance_squared )
        {
            // don't add the point to the result
            continue;
        }
        Point& next = thiss[(poly_idx+1) % size()];
        char here_is_beyond_line = 0;
        int64_t error2 = LinearAlg2D::getDist2FromLineSegment(*last, here, next, &here_is_beyond_line);
        if (here_is_beyond_line == 0 && error2 < allowed_error_distance_squared)
        {// don't add the point to the result
        } else
        {
            thiss[writing_idx] = here;
            writing_idx++;
            last = &here;
        }
    }
    path->erase(path->begin() + writing_idx , path->end());

    if (size() < 3)
    {
        clear();
        return;
    }

    { // handle the line segments spanning the vector end and begin
        Point* last = &thiss.back();
        Point& here = thiss[0];
        if ( vSize2(here-*last) < allowed_error_distance_squared )
        {
            remove(0);
        }
        Point& next = thiss[1];
        int64_t error2 = LinearAlg2D::getDist2FromLineSegment(*last, here, next);
        if (error2 < allowed_error_distance_squared)
        {
            remove(0);
        } else
        {
            // leave it in
        }
    }

    if (size() < 3)
    {
        clear();
        return;
    }
}

std::vector<PolygonsPart> Polygons::splitIntoParts(bool unionAll) const
{
    std::vector<PolygonsPart> ret;
    ClipperLib::Clipper clipper(clipper_init);
    ClipperLib::PolyTree resultPolyTree;
    clipper.AddPaths(paths, ClipperLib::ptSubject, true);
    if (unionAll)
        clipper.Execute(ClipperLib::ctUnion, resultPolyTree, ClipperLib::pftNonZero, ClipperLib::pftNonZero);
    else
        clipper.Execute(ClipperLib::ctUnion, resultPolyTree);

    splitIntoParts_processPolyTreeNode(&resultPolyTree, ret);
    return ret;
}

void Polygons::splitIntoParts_processPolyTreeNode(ClipperLib::PolyNode* node, std::vector<PolygonsPart>& ret) const
{
    for(int n=0; n<node->ChildCount(); n++)
    {
        ClipperLib::PolyNode* child = node->Childs[n];
        PolygonsPart part;
        part.add(child->Contour);
        for(int i=0; i<child->ChildCount(); i++)
        {
            part.add(child->Childs[i]->Contour);
            splitIntoParts_processPolyTreeNode(child->Childs[i], ret);
        }
        ret.push_back(part);
    }
}

unsigned int PartsView::getPartContaining(unsigned int poly_idx, unsigned int* boundary_poly_idx)
{
    PartsView& partsView = *this;
    for (unsigned int part_idx_now = 0; part_idx_now < partsView.size(); part_idx_now++)
    {
        std::vector<unsigned int>& partView = partsView[part_idx_now];
        if (partView.size() == 0) { continue; }
        std::vector<unsigned int>::iterator result = std::find(partView.begin(), partView.end(), poly_idx);
        if (result != partView.end())
        {
            if (boundary_poly_idx) { *boundary_poly_idx = partView[0]; }
            return part_idx_now;
        }
    }
    return NO_INDEX;
}

PolygonsPart PartsView::assemblePart(unsigned int part_idx)
{
    PartsView& partsView = *this;
    PolygonsPart ret;
    if (part_idx != NO_INDEX)
    {
        for (unsigned int poly_idx_ff : partsView[part_idx])
        {
            ret.add(polygons[poly_idx_ff]);
        }
    }
    return ret;
}

PolygonsPart PartsView::assemblePartContaining(unsigned int poly_idx, unsigned int* boundary_poly_idx)
{
    PolygonsPart ret;
    unsigned int part_idx = getPartContaining(poly_idx, boundary_poly_idx);
    if (part_idx != NO_INDEX)
    {
        return assemblePart(part_idx);
    }
    return ret;
}

PartsView Polygons::splitIntoPartsView(bool unionAll)
{
    Polygons reordered;
    PartsView partsView(*this);
    ClipperLib::Clipper clipper(clipper_init);
    ClipperLib::PolyTree resultPolyTree;
    clipper.AddPaths(paths, ClipperLib::ptSubject, true);
    if (unionAll)
        clipper.Execute(ClipperLib::ctUnion, resultPolyTree, ClipperLib::pftNonZero, ClipperLib::pftNonZero);
    else
        clipper.Execute(ClipperLib::ctUnion, resultPolyTree);

    splitIntoPartsView_processPolyTreeNode(partsView, reordered, &resultPolyTree);

    (*this) = reordered;
    return partsView;
}

void Polygons::splitIntoPartsView_processPolyTreeNode(PartsView& partsView, Polygons& reordered, ClipperLib::PolyNode* node) const
{
    for(int n=0; n<node->ChildCount(); n++)
    {
        ClipperLib::PolyNode* child = node->Childs[n];
        partsView.emplace_back();
        unsigned int pos = partsView.size() - 1;
        partsView[pos].push_back(reordered.size());
        reordered.add(child->Contour);
        for(int i = 0; i < child->ChildCount(); i++)
        {
            partsView[pos].push_back(reordered.size());
            reordered.add(child->Childs[i]->Contour);
            splitIntoPartsView_processPolyTreeNode(partsView, reordered, child->Childs[i]);
        }
    }
}

}//namespace cura
<|endoftext|>


<commit_before>/*
  Usage: seq_sample N IN.fastq OUT.fastq

  Samples N reads from IN.fastq and writes them to OUT.fastq without
  duplicates.
 */

#include <fstream>
#include <iostream>
#include <set>

#include <seqan/basic.h>
#include <seqan/file.h>
#include <seqan/misc/misc_random.h>
#include <seqan/sequence.h>
#include <seqan/store.h>

using namespace seqan;

template <
	typename TStream,
	typename TSeq >
void dumpWrapped(
	TStream &out,
	TSeq &seq)
{
	unsigned size = length(seq);
	unsigned i;
	for (i = 0; i + 60 < size; i += 60)
		out << infix(seq, i, i + 60) << std::endl;
	out << infix(seq, i, size) << std::endl;
}

template <typename TStream, typename TStringSetSpec, typename TStringSetSpec2>
void write(TStream & stream,
           StringSet<String<Dna5Q>, TStringSetSpec> const & sequences,
           StringSet<CharString, TStringSetSpec2> const & seqIds,
           Fastq const &) {
    typedef StringSet<String<Dna5Q>, TStringSetSpec> TStringSet;
    typedef typename Position<TStringSet>::Type TPosition;

    CharString qualBuffer;
    for (TPosition i = 0; i < length(sequences); ++i) {
        stream << "@" << seqIds[i] << std::endl;
        stream << sequences[i] << std::endl;
        stream << "+" << seqIds[i] << std::endl;
        resize(qualBuffer, length(sequences[i]), Exact());
        for (TPosition j = 0; j < length(sequences[i]); ++j) {
            qualBuffer[j] = getQualityValue(sequences[i][j]) + '!';
        }
        stream << qualBuffer << std::endl;
    }
}

int main(int argc, char **argv) {
    if (argc != 4) {
        std::cerr << "ERROR: Wrong number of parameters!" << std::endl;
        std::cerr << "USAGE: seq_sample N IN.fastq OUT.fastq" << std::endl;
        return 1;
    }

    // TODO(holtgrew): Actually, we want to seed this!
//     const unsigned SEED = 42;
    mtRandInit();

    unsigned n = atoi(argv[1]);

    // Load reads using the fragment store.
    FragmentStore<> fragStore;
    if (!loadReads(fragStore, argv[2])) return 1;

    // The factor 10 is arbitrarily chosen to make sure the generation
    // is sufficiently fast.
    if (length(fragStore.readSeqStore) < 10 * n) {
        std::cerr << "Number of reads in file should be >= 10*n" << std::endl;
        return 1;
    }

    // Randomly build the resulting string set.
    // Pick ids to select.
    std::set<unsigned> selectedIds;
    while (length(selectedIds) < n) {
        unsigned x = mtRand() % length(fragStore.readSeqStore);
        selectedIds.insert(x);
    }
    // Actually build result.
    StringSet<String<Dna5Q> > resultSeqs;
    reserve(resultSeqs, n);
    StringSet<CharString> resultIds;
    reserve(resultIds, n);
    for (std::set<unsigned>::const_iterator it = selectedIds.begin(); it != selectedIds.end(); ++it) {
        appendValue(resultSeqs, fragStore.readSeqStore[*it]);
        appendValue(resultIds, fragStore.readNameStore[*it]);
    }

    // Write out the result.
    if (CharString("-") == argv[3]) {
        write(std::cout, resultSeqs, resultIds, Fastq());
    } else {
        std::fstream fstrm(argv[3], std::ios_base::out);
        if (not fstrm.is_open()) {
            std::cerr << "Could not open out file \"" << argv[3] << "\"" << std::endl;
            return 1;
        }
        write(fstrm, resultSeqs, resultIds, Fastq());
    }

    return 0;
}
<commit_msg>New seq_sample app.<commit_after>/*
  Usage: seq_sample N IN.fastq OUT.fastq
         seq_sample N IN.1.fastq IN.2.fastq OUT.1.fastq OUT.2.fastq

  Samples N reads from IN.fastq and writes them to OUT.fastq without
  duplicates, alternatively from mate-paired reads.
 */

#include <fstream>
#include <iostream>
#include <set>

#include <seqan/basic.h>
#include <seqan/file.h>
#include <seqan/misc/misc_random.h>
#include <seqan/sequence.h>
#include <seqan/store.h>

using namespace seqan;

template <typename TStream, typename TStringSetSpec, typename TStringSetSpec2>
void write(TStream & stream,
           StringSet<String<Dna5Q>, TStringSetSpec> const & sequences,
           StringSet<CharString, TStringSetSpec2> const & seqIds,
           Fastq const &) {
    typedef StringSet<String<Dna5Q>, TStringSetSpec> TStringSet;
    typedef typename Position<TStringSet>::Type TPosition;

    CharString qualBuffer;
    for (TPosition i = 0; i < length(sequences); ++i) {
        stream << "@" << seqIds[i] << std::endl;
        stream << sequences[i] << std::endl;
        stream << "+" << seqIds[i] << std::endl;
        resize(qualBuffer, length(sequences[i]), Exact());
        for (TPosition j = 0; j < length(sequences[i]); ++j) {
            qualBuffer[j] = getQualityValue(sequences[i][j]) + '!';
        }
        stream << qualBuffer << std::endl;
    }
}

int main(int argc, char **argv) {
    if (argc != 4 && argc != 6) {
        std::cerr << "ERROR: Wrong number of parameters!" << std::endl;
        std::cerr << "USAGE: seq_sample N IN.fastq OUT.fastq" << std::endl;
        std::cerr << "       seq_sample N IN.1.fastq IN.2.fastq OUT.1.fastq OUT.2.fastq" << std::endl;
        return 1;
    }

    // TODO(holtgrew): Actually, we want to seed this!
    const unsigned SEED = 42;
    mtRandInit(SEED);

    unsigned n = atoi(argv[1]);

    // Load reads using the fragment store.
    FragmentStore<> fragStore;
    bool hasMatePairs = (argc == 6);
    unsigned matePairFactor = hasMatePairs ? 2 : 1;
    if (!hasMatePairs) {
        if (!loadReads(fragStore, argv[2])) return 1;
    } else {
        if (!loadReads(fragStore, argv[2], argv[3])) return 1;
    }
    unsigned matePairCount = length(fragStore.readSeqStore) / matePairFactor;

    // The factor 10 is arbitrarily chosen to make sure the generation
    // is sufficiently fast.
    if (matePairCount < 10 * n) {
        std::cerr << "Number of reads/mate pairs in file/s should be >= 10*n" << std::endl;
        return 1;
    }

    // Randomly build the resulting string set.
    // Pick ids to select.
    std::set<unsigned> selectedIds;
    while (length(selectedIds) < n) {
        unsigned x = mtRand() % matePairCount;
        selectedIds.insert(x);
    }
    // Actually build result.
    StringSet<String<Dna5Q> > resultSeqsL, resultSeqsR;
    StringSet<CharString> resultIdsL, resultIdsR;
    reserve(resultSeqsL, n);
    reserve(resultIdsL, n);
    if (hasMatePairs) {
        reserve(resultIdsR, n);
        reserve(resultSeqsR, n);
    }
    for (std::set<unsigned>::const_iterator it = selectedIds.begin(); it != selectedIds.end(); ++it) {
        if (!hasMatePairs) {
            appendValue(resultSeqsL, fragStore.readSeqStore[*it]);
            appendValue(resultIdsL, fragStore.readNameStore[*it]);
        } else {
            appendValue(resultSeqsL, fragStore.readSeqStore[2 * (*it)]);
            appendValue(resultIdsL, fragStore.readNameStore[2 * (*it)]);
            appendValue(resultSeqsR, fragStore.readSeqStore[2 * (*it) + 1]);
            appendValue(resultIdsR, fragStore.readNameStore[2 * (*it) + 1]);
        }
    }

    // Write out the result.
    if (!hasMatePairs) {
        if (CharString("-") == argv[3]) {
            write(std::cout, resultSeqsL, resultIdsL, Fastq());
        } else {
            std::fstream fstrm(argv[3], std::ios_base::out);
            if (not fstrm.is_open()) {
                std::cerr << "Could not open out file \"" << argv[3] << "\"" << std::endl;
                return 1;
            }
            write(fstrm, resultSeqsL, resultIdsL, Fastq());
        }
    } else {
        if (CharString("-") == argv[4]) {
            write(std::cout, resultSeqsL, resultIdsL, Fastq());
        } else {
            std::fstream fstrm(argv[4], std::ios_base::out);
            if (not fstrm.is_open()) {
                std::cerr << "Could not open out file \"" << argv[4] << "\"" << std::endl;
                return 1;
            }
            write(fstrm, resultSeqsL, resultIdsL, Fastq());
        }
        if (CharString("-") == argv[5]) {
            write(std::cout, resultSeqsR, resultIdsR, Fastq());
        } else {
            std::fstream fstrm(argv[5], std::ios_base::out);
            if (not fstrm.is_open()) {
                std::cerr << "Could not open out file \"" << argv[5] << "\"" << std::endl;
                return 1;
            }
            write(fstrm, resultSeqsR, resultIdsR, Fastq());
        }
    }

    return 0;
}
<|endoftext|>


<commit_before>#include <mantella_bits/samplesSelection/bestNeighbourhoodSamplesSelection.hpp>

namespace mant {
  void BestNeighbourhoodSamplesSelection::selectImplementation() {
    arma::Col<double> bestParameter;
    double bestObjectiveValue = std::numeric_limits<double>::infinity();
    for (const auto& sample : samples_) {
      if(sample.second < bestObjectiveValue) {
        bestParameter = sample.first;
        bestObjectiveValue = sample.second;
      }
    }

    arma::Col<double> distances(samples_.size());
    arma::uword n = 0;
    for (const auto& sample : samples_) {
      distances(++n) = arma::norm(bestParameter - sample.first);
    }

    for (const auto& i : static_cast<arma::Col<arma::uword>>(static_cast<arma::Col<arma::uword>>(arma::sort_index(distances)).head(numberOfSelectedSamples_))) {
      const auto& selectedSample = std::next(std::begin(samples_), i);
      selectedSamples_.insert({selectedSample->first, selectedSample->second});
    }
  }

  std::string BestNeighbourhoodSamplesSelection::toString() const {
    return "nearest_to_best_samples_selection";
  }
}<commit_msg>Fixed toString<commit_after>#include <mantella_bits/samplesSelection/bestNeighbourhoodSamplesSelection.hpp>

namespace mant {
  void BestNeighbourhoodSamplesSelection::selectImplementation() {
    arma::Col<double> bestParameter;
    double bestObjectiveValue = std::numeric_limits<double>::infinity();
    for (const auto& sample : samples_) {
      if(sample.second < bestObjectiveValue) {
        bestParameter = sample.first;
        bestObjectiveValue = sample.second;
      }
    }

    arma::Col<double> distances(samples_.size());
    arma::uword n = 0;
    for (const auto& sample : samples_) {
      distances(++n) = arma::norm(bestParameter - sample.first);
    }

    for (const auto& i : static_cast<arma::Col<arma::uword>>(static_cast<arma::Col<arma::uword>>(arma::sort_index(distances)).head(numberOfSelectedSamples_))) {
      const auto& selectedSample = std::next(std::begin(samples_), i);
      selectedSamples_.insert({selectedSample->first, selectedSample->second});
    }
  }

  std::string BestNeighbourhoodSamplesSelection::toString() const {
    return "best_neighbourhood_samples_selection";
  }
}<|endoftext|>


<commit_before>#ifndef VG_VARIANT_ADDER_HPP
#define VG_VARIANT_ADDER_HPP

/** \file
 * variant_adder.hpp: defines a tool class used for adding variants from VCF
 * files into existing graphs.
 */

#include "vcf_buffer.hpp"
#include "path_index.hpp"
#include "vg.hpp"
#include "progressive.hpp"
#include "name_mapper.hpp"
#include "graph_synchronizer.hpp"

namespace vg {

using namespace std;

/**
 * A tool class for adding variants to a VG graph. Integrated NameMapper
 * provides name translation for the VCF contigs.
 */
class VariantAdder : public NameMapper, public Progressive {

public:

    /**
     * Make a new VariantAdder to add variants to the given graph. Modifies the
     * graph in place.
     */
    VariantAdder(VG& graph);

    /**
     * Add in the variants from the given non-null VCF file. The file must be
     * freshly opened. The variants in the file must be sorted.
     *
     * May be called from multiple threads. Synchronizes internally on the
     * graph.
     */
    void add_variants(vcflib::VariantCallFile* vcf);

    /// How wide of a range in bases should we look for nearby variants in?
    size_t variant_range = 50;

    /// How much additional context should we try and add outside the radius of
    /// our group of variants we actually find?
    size_t flank_range = 20;

    /// Should we accept and ignore VCF contigs that we can't find in the graph?
    bool ignore_missing_contigs = false;

protected:
    /// The graph we are modifying
    VG& graph;

    /// We keep a GraphSynchronizer so we can have multiple threads working on
    /// different parts of the same graph.
    GraphSynchronizer sync;

    /// We cache the set of valid path names, so we can detect/skip missing ones
    /// without locking the graph.
    set<string> path_names;

    /**
     * Get all the unique combinations of variant alts represented by actual
     * haplotypes. Arbitrarily phases unphased variants.
     *
     * Can (and should) take a WindowedVcfBuffer that owns the variants, and
     * from which cached pre-parsed genotypes can be extracted.
     *
     * Returns a set of vectors or one number per variant, giving the alt number
     * (starting with 0 for reference) that appears on the haplotype.
     *
     * TODO: ought to just take a collection of pre-barsed genotypes, but in an
     * efficient way (a vector of pointers to vectors of sample genotypes?)
     */
    set<vector<int>> get_unique_haplotypes(const vector<vcflib::Variant*>& variants, WindowedVcfBuffer* cache = nullptr) const;

    /**
     * Convert a haplotype on a list of variants into a string. The string will
     * run from the start of the first variant through the end of the last
     * variant.
     */
    string haplotype_to_string(const vector<int>& haplotype, const vector<vcflib::Variant*>& variants);

    /**
     * Get the radius of the variant around its center: the amount of sequence
     * that needs to be pulled out to make sure you have the ref and all the
     * alts, if they exist. This is just going to be twice the longest of the
     * ref and the alts.
     */
    static size_t get_radius(const vcflib::Variant& variant);

    /**
     * Get the center position of the given variant.
     */
    static size_t get_center(const vcflib::Variant& variant);

    /**
     * Get the center and radius around that center needed to extract everything
     * that might be involved in a group of variants.
     */
    static pair<size_t, size_t> get_center_and_radius(const vector<vcflib::Variant*>& variants);

};

}

#endif

<commit_msg>Up context<commit_after>#ifndef VG_VARIANT_ADDER_HPP
#define VG_VARIANT_ADDER_HPP

/** \file
 * variant_adder.hpp: defines a tool class used for adding variants from VCF
 * files into existing graphs.
 */

#include "vcf_buffer.hpp"
#include "path_index.hpp"
#include "vg.hpp"
#include "progressive.hpp"
#include "name_mapper.hpp"
#include "graph_synchronizer.hpp"

namespace vg {

using namespace std;

/**
 * A tool class for adding variants to a VG graph. Integrated NameMapper
 * provides name translation for the VCF contigs.
 */
class VariantAdder : public NameMapper, public Progressive {

public:

    /**
     * Make a new VariantAdder to add variants to the given graph. Modifies the
     * graph in place.
     */
    VariantAdder(VG& graph);

    /**
     * Add in the variants from the given non-null VCF file. The file must be
     * freshly opened. The variants in the file must be sorted.
     *
     * May be called from multiple threads. Synchronizes internally on the
     * graph.
     */
    void add_variants(vcflib::VariantCallFile* vcf);

    /// How wide of a range in bases should we look for nearby variants in?
    size_t variant_range = 50;

    /// How much additional context should we try and add outside the radius of
    /// our group of variants we actually find?
    size_t flank_range = 100;

    /// Should we accept and ignore VCF contigs that we can't find in the graph?
    bool ignore_missing_contigs = false;

protected:
    /// The graph we are modifying
    VG& graph;

    /// We keep a GraphSynchronizer so we can have multiple threads working on
    /// different parts of the same graph.
    GraphSynchronizer sync;

    /// We cache the set of valid path names, so we can detect/skip missing ones
    /// without locking the graph.
    set<string> path_names;

    /**
     * Get all the unique combinations of variant alts represented by actual
     * haplotypes. Arbitrarily phases unphased variants.
     *
     * Can (and should) take a WindowedVcfBuffer that owns the variants, and
     * from which cached pre-parsed genotypes can be extracted.
     *
     * Returns a set of vectors or one number per variant, giving the alt number
     * (starting with 0 for reference) that appears on the haplotype.
     *
     * TODO: ought to just take a collection of pre-barsed genotypes, but in an
     * efficient way (a vector of pointers to vectors of sample genotypes?)
     */
    set<vector<int>> get_unique_haplotypes(const vector<vcflib::Variant*>& variants, WindowedVcfBuffer* cache = nullptr) const;

    /**
     * Convert a haplotype on a list of variants into a string. The string will
     * run from the start of the first variant through the end of the last
     * variant.
     */
    string haplotype_to_string(const vector<int>& haplotype, const vector<vcflib::Variant*>& variants);

    /**
     * Get the radius of the variant around its center: the amount of sequence
     * that needs to be pulled out to make sure you have the ref and all the
     * alts, if they exist. This is just going to be twice the longest of the
     * ref and the alts.
     */
    static size_t get_radius(const vcflib::Variant& variant);

    /**
     * Get the center position of the given variant.
     */
    static size_t get_center(const vcflib::Variant& variant);

    /**
     * Get the center and radius around that center needed to extract everything
     * that might be involved in a group of variants.
     */
    static pair<size_t, size_t> get_center_and_radius(const vector<vcflib::Variant*>& variants);

};

}

#endif

<|endoftext|>


<commit_before>#ifndef DUNE_DETAILED_DISCRETIZATIONS_ASSEMBLER_SYSTEM_AFFINE_HH
#define DUNE_DETAILED_DISCRETIZATIONS_ASSEMBLER_SYSTEM_AFFINE_HH

// std includes
#include <vector>

// dune-common includes
#include <dune/common/dynmatrix.hh>
#include <dune/common/dynvector.hh>

namespace Dune {

namespace Detailed {

namespace Discretizations {

namespace Assembler {

namespace System {

template <class AnsatzFunctionSpaceImp, class TestFunctionSpaceImp = AnsatzFunctionSpaceImp>
class Constrained
{
public:
  typedef AnsatzFunctionSpaceImp AnsatzFunctionSpaceType;

  typedef TestFunctionSpaceImp TestFunctionSpaceType;

  typedef Constrained<AnsatzFunctionSpaceImp, TestFunctionSpaceImp> ThisType;

  //! constructor
  Constrained(const AnsatzFunctionSpaceType& ansatzSpace, const TestFunctionSpaceType& testSpace)
    : ansatzSpace_(ansatzSpace)
    , testSpace_(testSpace)
  {
  }

  //! constructor
  Constrained(const AnsatzFunctionSpaceType& ansatzSpace)
    : ansatzSpace_(ansatzSpace)
    , testSpace_(ansatzSpace)
  {
  }

  const AnsatzFunctionSpaceType& ansatzSpace()
  {
    return ansatzSpace_;
  }

  const TestFunctionSpaceType& testSpace()
  {
    return testSpace_;
  }

  template <class LocalMatrixAssemblerType, class MatrixType, class LocalVectorAssemblerType, class VectorType>
  void assemble(const LocalMatrixAssemblerType& localMatrixAssembler, MatrixType& systemMatrix,
                const LocalVectorAssemblerType& localVectorAssembler, VectorType& systemVector) const
  {
    assembleSystem(localMatrixAssembler, systemMatrix, localVectorAssembler, systemVector);
    applyConstraints(systemMatrix, systemVector);
  } // void assemble()

  template <class LocalMatrixAssemblerType, class MatrixType, class LocalVectorAssemblerType, class VectorType>
  void assembleSystem(const LocalMatrixAssemblerType& localMatrixAssembler, MatrixType& systemMatrix,
                      const LocalVectorAssemblerType& localVectorAssembler, VectorType& systemVector) const
  {
    // some types
    typedef typename AnsatzFunctionSpaceType::GridPartType GridPartType;
    typedef typename GridPartType::template Codim<0>::IteratorType EntityIteratorType;
    typedef typename GridPartType::template Codim<0>::EntityType EntityType;
    typedef typename AnsatzFunctionSpaceType::RangeFieldType RangeFieldType;
    typedef Dune::DynamicMatrix<RangeFieldType> LocalMatrixType;
    typedef Dune::DynamicVector<RangeFieldType> LocalVectorType;

    // common tmp storage for all entities
    std::vector<unsigned int> numberTmpMatrices = localMatrixAssembler.numTmpObjectsRequired();
    std::vector<LocalMatrixType> tmpLocalAssemblerMatrices(
        numberTmpMatrices[0],
        LocalMatrixType(ansatzSpace_.map().maxLocalSize(), testSpace_.map().maxLocalSize(), RangeFieldType(0.0)));
    std::vector<LocalMatrixType> tmpLocalOperatorMatrices(
        numberTmpMatrices[1],
        LocalMatrixType(ansatzSpace_.map().maxLocalSize(), testSpace_.map().maxLocalSize(), RangeFieldType(0.0)));
    std::vector<std::vector<LocalMatrixType>> tmpLocalMatricesContainer;
    tmpLocalMatricesContainer.push_back(tmpLocalAssemblerMatrices);
    tmpLocalMatricesContainer.push_back(tmpLocalOperatorMatrices);

    std::vector<unsigned int> numberTmpVectors = localVectorAssembler.numTmpObjectsRequired();
    std::vector<LocalVectorType> tmpLocalAssemblerVectors(
        numberTmpVectors[0], LocalVectorType(testSpace_.map().maxLocalSize(), RangeFieldType(0.0)));
    std::vector<LocalVectorType> tmpLocalFunctionalVectors(
        numberTmpVectors[1], LocalVectorType(testSpace_.map().maxLocalSize(), RangeFieldType(0.0)));
    std::vector<std::vector<LocalVectorType>> tmpLocalVectorsContainer;
    tmpLocalVectorsContainer.push_back(tmpLocalAssemblerVectors);
    tmpLocalVectorsContainer.push_back(tmpLocalFunctionalVectors);

    // walk the grid to assemble
    for (EntityIteratorType entityIterator = ansatzSpace_.gridPart().template begin<0>();
         entityIterator != ansatzSpace_.gridPart().template end<0>();
         ++entityIterator) {
      const EntityType& entity = *entityIterator;
      localMatrixAssembler.assembleLocal(ansatzSpace_, testSpace_, entity, systemMatrix, tmpLocalMatricesContainer);
      localVectorAssembler.assembleLocal(testSpace_, entity, systemVector, tmpLocalVectorsContainer);
    } // walk the grid to assemble
  } // void assembleSystem()

  template <class MatrixType, class VectorType>
  void applyConstraints(MatrixType& matrix, VectorType& vector) const
  {
    typedef typename AnsatzFunctionSpaceType::GridPartType GridPartType;
    typedef typename GridPartType::template Codim<0>::IteratorType EntityIteratorType;
    typedef typename GridPartType::template Codim<0>::EntityType EntityType;
    typedef typename AnsatzFunctionSpaceType::ConstraintsType ConstraintsType;
    typedef typename ConstraintsType::LocalConstraintsType LocalConstraintsType;
    // walk the grid to apply constraints
    const ConstraintsType& constraints = ansatzSpace_.constraints();
    for (EntityIteratorType entityIterator = ansatzSpace_.gridPart().template begin<0>();
         entityIterator != ansatzSpace_.gridPart().template end<0>();
         ++entityIterator) {
      const EntityType& entity                     = *entityIterator;
      const LocalConstraintsType& localConstraints = constraints.local(entity);
      applyLocalMatrixConstraints(localConstraints, matrix);
      applyLocalVectorConstraints(localConstraints, vector);

    } // walk the grid to apply constraints

  } // void applyConstraints()

private:
  ThisType& operator=(const ThisType&);
  Constrained(const ThisType&);

  template <class LocalConstraintsType, class MatrixType>
  void applyLocalMatrixConstraints(const LocalConstraintsType& localConstraints, MatrixType& matrix) const
  {
    for (unsigned int i = 0; i < localConstraints.rowDofsSize(); ++i) {
      for (unsigned int j = 0; j < localConstraints.columnDofsSize(); ++j) {
        matrix.set(localConstraints.rowDofs(i), localConstraints.columnDofs(j), localConstraints.localMatrix(i, j));
      }
    }
  } // end applyLocalMatrixConstraints

  template <class LocalConstraintsType, class VectorType>
  void applyLocalVectorConstraints(const LocalConstraintsType& localConstraints, VectorType& vector) const
  {
    for (unsigned int i = 0; i < localConstraints.rowDofsSize(); ++i) {
      vector.set(localConstraints.rowDofs(i), 0.0);
    }
  } // end applyLocalVectorConstraints

  const AnsatzFunctionSpaceType& ansatzSpace_;
  const TestFunctionSpaceType& testSpace_;
}; // end class Constrained

} // end namespace System

} // end namespace Assembler

} // namespace Discretizations

} // namespace Detailed

} // end namespace Dune

#endif // DUNE_DETAILED_DISCRETIZATIONS_ASSEMBLER_SYSTEM_AFFINE_HH
<commit_msg>[assembler.system.constrained] some cleanup<commit_after>#ifndef DUNE_DETAILED_DISCRETIZATIONS_ASSEMBLER_SYSTEM_AFFINE_HH
#define DUNE_DETAILED_DISCRETIZATIONS_ASSEMBLER_SYSTEM_AFFINE_HH

// std includes
#include <vector>

// dune-common includes
#include <dune/common/dynmatrix.hh>
#include <dune/common/dynvector.hh>

namespace Dune {

namespace Detailed {

namespace Discretizations {

namespace Assembler {

namespace System {

template <class AnsatzFunctionSpaceImp, class TestFunctionSpaceImp = AnsatzFunctionSpaceImp>
class Constrained
{
public:
  typedef AnsatzFunctionSpaceImp AnsatzFunctionSpaceType;

  typedef TestFunctionSpaceImp TestFunctionSpaceType;

  typedef Constrained<AnsatzFunctionSpaceImp, TestFunctionSpaceImp> ThisType;

  //! constructor
  Constrained(const AnsatzFunctionSpaceType& ansatzSpace, const TestFunctionSpaceType& testSpace)
    : ansatzSpace_(ansatzSpace)
    , testSpace_(testSpace)
  {
  }

  //! constructor
  Constrained(const AnsatzFunctionSpaceType& ansatzSpace)
    : ansatzSpace_(ansatzSpace)
    , testSpace_(ansatzSpace)
  {
  }

  const AnsatzFunctionSpaceType& ansatzSpace()
  {
    return ansatzSpace_;
  }

  const TestFunctionSpaceType& testSpace()
  {
    return testSpace_;
  }

  template <class LocalMatrixAssemblerType, class MatrixType, class LocalVectorAssemblerType, class VectorType>
  void assemble(const LocalMatrixAssemblerType& localMatrixAssembler, MatrixType& systemMatrix,
                const LocalVectorAssemblerType& localVectorAssembler, VectorType& systemVector) const
  {
    assembleSystem(localMatrixAssembler, systemMatrix, localVectorAssembler, systemVector);
    applyConstraints(systemMatrix, systemVector);
  } // void assemble()

  template <class LocalMatrixAssemblerType, class MatrixType, class LocalVectorAssemblerType, class VectorType>
  void assembleSystem(const LocalMatrixAssemblerType& localMatrixAssembler, MatrixType& systemMatrix,
                      const LocalVectorAssemblerType& localVectorAssembler, VectorType& systemVector) const
  {
    // some types
    typedef typename AnsatzFunctionSpaceType::GridPartType GridPartType;
    typedef typename GridPartType::template Codim<0>::IteratorType EntityIteratorType;
    typedef typename GridPartType::template Codim<0>::EntityType EntityType;
    typedef typename AnsatzFunctionSpaceType::RangeFieldType RangeFieldType;
    typedef Dune::DynamicMatrix<RangeFieldType> LocalMatrixType;
    typedef Dune::DynamicVector<RangeFieldType> LocalVectorType;

    // common tmp storage for all entities
    std::vector<unsigned int> numberTmpMatrices = localMatrixAssembler.numTmpObjectsRequired();
    std::vector<LocalMatrixType> tmpLocalAssemblerMatrices(
        numberTmpMatrices[0],
        LocalMatrixType(ansatzSpace_.map().maxLocalSize(), testSpace_.map().maxLocalSize(), RangeFieldType(0.0)));
    std::vector<LocalMatrixType> tmpLocalOperatorMatrices(
        numberTmpMatrices[1],
        LocalMatrixType(ansatzSpace_.map().maxLocalSize(), testSpace_.map().maxLocalSize(), RangeFieldType(0.0)));
    std::vector<std::vector<LocalMatrixType>> tmpLocalMatricesContainer;
    tmpLocalMatricesContainer.push_back(tmpLocalAssemblerMatrices);
    tmpLocalMatricesContainer.push_back(tmpLocalOperatorMatrices);

    std::vector<unsigned int> numberTmpVectors = localVectorAssembler.numTmpObjectsRequired();
    std::vector<LocalVectorType> tmpLocalAssemblerVectors(
        numberTmpVectors[0], LocalVectorType(testSpace_.map().maxLocalSize(), RangeFieldType(0.0)));
    std::vector<LocalVectorType> tmpLocalFunctionalVectors(
        numberTmpVectors[1], LocalVectorType(testSpace_.map().maxLocalSize(), RangeFieldType(0.0)));
    std::vector<std::vector<LocalVectorType>> tmpLocalVectorsContainer;
    tmpLocalVectorsContainer.push_back(tmpLocalAssemblerVectors);
    tmpLocalVectorsContainer.push_back(tmpLocalFunctionalVectors);

    // walk the grid to assemble
    for (EntityIteratorType entityIterator = ansatzSpace_.gridPart().template begin<0>();
         entityIterator != ansatzSpace_.gridPart().template end<0>();
         ++entityIterator) {
      const EntityType& entity = *entityIterator;
      localMatrixAssembler.assembleLocal(ansatzSpace_, testSpace_, entity, systemMatrix, tmpLocalMatricesContainer);
      localVectorAssembler.assembleLocal(testSpace_, entity, systemVector, tmpLocalVectorsContainer);
    } // walk the grid to assemble
  } // void assembleSystem()

  template <class MatrixType, class VectorType>
  void applyConstraints(MatrixType& matrix, VectorType& vector) const
  {
    typedef typename AnsatzFunctionSpaceType::GridPartType GridPartType;
    typedef typename GridPartType::template Codim<0>::IteratorType EntityIteratorType;
    typedef typename GridPartType::template Codim<0>::EntityType EntityType;
    typedef typename AnsatzFunctionSpaceType::ConstraintsType ConstraintsType;
    typedef typename ConstraintsType::LocalConstraintsType LocalConstraintsType;
    // walk the grid to apply constraints
    const ConstraintsType& constraints = ansatzSpace_.constraints();
    for (EntityIteratorType entityIterator = ansatzSpace_.gridPart().template begin<0>();
         entityIterator != ansatzSpace_.gridPart().template end<0>();
         ++entityIterator) {
      const EntityType& entity                     = *entityIterator;
      const LocalConstraintsType& localConstraints = constraints.local(entity);
      applyLocalMatrixConstraints(localConstraints, matrix);
      applyLocalVectorConstraints(localConstraints, vector);

    } // walk the grid to apply constraints

  } // void applyConstraints()

private:
  ThisType& operator=(const ThisType&);
  Constrained(const ThisType&);

  template <class LocalConstraintsType, class MatrixType>
  void applyLocalMatrixConstraints(const LocalConstraintsType& localConstraints, MatrixType& matrix) const
  {
    for (unsigned int i = 0; i < localConstraints.rowDofsSize(); ++i) {
      const unsigned int rowDof = localConstraints.rowDofs(i);
      for (unsigned int j = 0; j < localConstraints.columnDofsSize(); ++j) {
        matrix.set(rowDof, localConstraints.columnDofs(j), localConstraints.localMatrix(i, j));
      }
    }
  } // end applyLocalMatrixConstraints

  template <class LocalConstraintsType, class VectorType>
  void applyLocalVectorConstraints(const LocalConstraintsType& localConstraints, VectorType& vector) const
  {
    for (unsigned int i = 0; i < localConstraints.rowDofsSize(); ++i) {
      vector.set(localConstraints.rowDofs(i), 0.0);
    }
  } // end applyLocalVectorConstraints

  const AnsatzFunctionSpaceType& ansatzSpace_;
  const TestFunctionSpaceType& testSpace_;
}; // end class Constrained

} // end namespace System

} // end namespace Assembler

} // namespace Discretizations

} // namespace Detailed

} // end namespace Dune

#endif // DUNE_DETAILED_DISCRETIZATIONS_ASSEMBLER_SYSTEM_AFFINE_HH
<|endoftext|>