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

#include "ToolPanel.hxx"

#include "TaskPaneFocusManager.hxx"
#include "TitleBar.hxx"
#include "TitledControl.hxx"
#include "ControlContainer.hxx"
#include "TaskPaneViewShell.hxx"
#include "taskpane/TaskPaneControlFactory.hxx"

#ifndef _SV_DECOVIEW_HXX
#include <vcl/decoview.hxx>
#endif
#ifndef _SV_MENU_HXX
#include <vcl/menu.hxx>
#endif

namespace sd { namespace toolpanel {

/** Use WB_DIALOGCONTROL as argument for the Control constructor to
    let VCL handle focus traveling.  In addition the control
    descriptors have to use WB_TABSTOP.
*/
ToolPanel::ToolPanel (
    Window* pParentWindow,
    TaskPaneViewShell& rViewShell)
    : Control (pParentWindow, WB_DIALOGCONTROL),
      mrViewShell(rViewShell),
      TreeNode (NULL),
      mbRearrangeActive(false)
{
    SetBackground (Wallpaper ());
    SetAccessibleName (String::CreateFromAscii("Task Pane"));
    SetAccessibleDescription (String::CreateFromAscii("Impress task pane"));
}

ToolPanel::~ToolPanel (void)
{
}

sal_uInt32 ToolPanel::AddControl (
    ::std::auto_ptr<ControlFactory> pControlFactory,
    const String& rTitle,
    ULONG nHelpId)
{
    TitledControl* pTitledControl = new TitledControl (
        this,
        pControlFactory,
        rTitle,
        TitleBar::TBT_CONTROL_TITLE);
    ::std::auto_ptr<TreeNode> pChild (pTitledControl);

    // Get the (grand) parent window which is focus-wise our parent.
    Window* pParent = GetParent();
    if (pParent != NULL)
        pParent = pParent->GetParent();

    if (pParent != NULL)
    {
        // Add a down link only for the first control so that when entering
        // the sub tool panel the focus is set to the first control.
        if (mpControlContainer->GetControlCount() == 1)
            FocusManager::Instance().RegisterLink (pParent, pChild->GetWindow());
        else
            FocusManager::Instance().RegisterUpLink (pChild->GetWindow(), pParent);
    }

    pTitledControl->GetTitleBar()->SetHelpId(nHelpId);

    return mpControlContainer->AddControl (pChild);
}

void ToolPanel::ListHasChanged (void)
{
    mpControlContainer->ListHasChanged ();
    Rearrange ();
}

void ToolPanel::Resize (void)
{
    Control::Resize();
    Rearrange ();
}

void ToolPanel::RequestResize (void)
{
    Invalidate();
    Rearrange ();
}

/** Subtract the space for the title bars from the available space and
    give the remaining space to the active control.
*/
void ToolPanel::Rearrange (void)
{
    // Prevent recursive calls.
    if ( ! mbRearrangeActive && mpControlContainer->GetVisibleControlCount()>0)
    {
        mbRearrangeActive = true;

        SetBackground (Wallpaper ());

        // Make the area that is covered by the children a little bit
        // smaller so that a frame is visible arround them.
        Rectangle aAvailableArea (Point(0,0), GetOutputSizePixel());

        int nWidth = aAvailableArea.GetWidth();
        sal_uInt32 nControlCount (mpControlContainer->GetControlCount());
        sal_uInt32 nActiveControlIndex (
            mpControlContainer->GetActiveControlIndex());

        // Place title bars of controls above the active control and thereby
        // determine the top of the active control.
        sal_uInt32 nIndex;
        for (nIndex=mpControlContainer->GetFirstIndex();
             nIndex<nActiveControlIndex;
             nIndex=mpControlContainer->GetNextIndex(nIndex))
        {
            TreeNode* pChild = mpControlContainer->GetControl(nIndex);
            if (pChild != NULL)
            {
                sal_uInt32 nHeight = pChild->GetPreferredHeight (nWidth);
                pChild->GetWindow()->SetPosSizePixel (
                    aAvailableArea.TopLeft(),
                    Size(nWidth, nHeight));
                aAvailableArea.Top() += nHeight;
            }
        }

        // Place title bars of controls below the active control and thereby
        // determine the bottom of the active control.
        for (nIndex=mpControlContainer->GetLastIndex();
             nIndex<nControlCount && nIndex!=nActiveControlIndex;
             nIndex=mpControlContainer->GetPreviousIndex(nIndex))
        {
            TreeNode* pChild = mpControlContainer->GetControl(nIndex);
            if (pChild != NULL)
            {
                sal_uInt32 nHeight = pChild->GetPreferredHeight (nWidth);
                pChild->GetWindow()->SetPosSizePixel (
                    Point(aAvailableArea.Left(),
                        aAvailableArea.Bottom()-nHeight+1),
                        Size(nWidth, nHeight));
                aAvailableArea.Bottom() -= nHeight;
            }
        }

        // Finally place the active control.
        TreeNode* pChild = mpControlContainer->GetControl(nActiveControlIndex);
        if (pChild != NULL)
            pChild->GetWindow()->SetPosSizePixel (
                aAvailableArea.TopLeft(),
                aAvailableArea.GetSize());

        mbRearrangeActive = false;
    }
    else
        SetBackground (
            Application::GetSettings().GetStyleSettings().GetDialogColor());
}

Size ToolPanel::GetPreferredSize (void)
{
    return Size(300,300);
}

sal_Int32 ToolPanel::GetPreferredWidth (sal_Int32 nHeight)
{
    return 300;
}

sal_Int32 ToolPanel::GetPreferredHeight (sal_Int32 nWidth)
{
    return 300;
}

bool ToolPanel::IsResizable (void)
{
    return true;
}

::Window* ToolPanel::GetWindow (void)
{
    return this;
}

TaskPaneShellManager* ToolPanel::GetShellManager (void)
{
    return &mrViewShell.GetSubShellManager();
}

} } // end of namespace ::sd::toolpanel
<commit_msg>INTEGRATION: CWS impress51 (1.6.46); FILE MERGED 2005/06/06 12:18:25 af 1.6.46.3: #i50190# Adaption to changes in TaskPaneFocusManager.  Focus is cycled through children on KEY_UP/DOWN. 2005/05/19 09:37:21 af 1.6.46.2: #i48247# Renamed TreeNode::{Get,Create}Accessible() to {Get,Create}AccessibleObject(). 2005/05/04 15:02:44 af 1.6.46.1: #i48247# Added CreateAccessible() method.<commit_after>/*************************************************************************
 *
 *  $RCSfile: ToolPanel.cxx,v $
 *
 *  $Revision: 1.7 $
 *
 *  last change: $Author: kz $ $Date: 2005-07-14 10:23:39 $
 *
 *  The Contents of this file are made available subject to the terms of
 *  either of the following licenses
 *
 *         - GNU Lesser General Public License Version 2.1
 *         - Sun Industry Standards Source License Version 1.1
 *
 *  Sun Microsystems Inc., October, 2000
 *
 *  GNU Lesser General Public License Version 2.1
 *  =============================================
 *  Copyright 2000 by Sun Microsystems, Inc.
 *  901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *  This library is free software; you can redistribute it and/or
 *  modify it under the terms of the GNU Lesser General Public
 *  License version 2.1, as published by the Free Software Foundation.
 *
 *  This library is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *  Lesser General Public License for more details.
 *
 *  You should have received a copy of the GNU Lesser General Public
 *  License along with this library; if not, write to the Free Software
 *  Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *  MA  02111-1307  USA
 *
 *
 *  Sun Industry Standards Source License Version 1.1
 *  =================================================
 *  The contents of this file are subject to the Sun Industry Standards
 *  Source License Version 1.1 (the "License"); You may not use this file
 *  except in compliance with the License. You may obtain a copy of the
 *  License at http://www.openoffice.org/license.html.
 *
 *  Software provided under this License is provided on an "AS IS" basis,
 *  WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
 *  WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
 *  MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
 *  See the License for the specific provisions governing your rights and
 *  obligations concerning the Software.
 *
 *  The Initial Developer of the Original Code is: Sun Microsystems, Inc.
 *
 *  Copyright: 2000 by Sun Microsystems, Inc.
 *
 *  All Rights Reserved.
 *
 *  Contributor(s): _______________________________________
 *
 *
 ************************************************************************/

#include "taskpane/ToolPanel.hxx"

#include "TaskPaneFocusManager.hxx"
#include "taskpane/TitleBar.hxx"
#include "taskpane/TitledControl.hxx"
#include "taskpane/ControlContainer.hxx"
#include "TaskPaneViewShell.hxx"
#include "taskpane/TaskPaneControlFactory.hxx"
#include "AccessibleTaskPane.hxx"

#include "strings.hrc"
#include "sdresid.hxx"

#ifndef _SV_DECOVIEW_HXX
#include <vcl/decoview.hxx>
#endif
#ifndef _SV_MENU_HXX
#include <vcl/menu.hxx>
#endif

namespace sd { namespace toolpanel {

/** Use WB_DIALOGCONTROL as argument for the Control constructor to
    let VCL handle focus traveling.  In addition the control
    descriptors have to use WB_TABSTOP.
*/
ToolPanel::ToolPanel (
    Window* pParentWindow,
    TaskPaneViewShell& rViewShell)
    : Control (pParentWindow, WB_DIALOGCONTROL),
      mrViewShell(rViewShell),
      TreeNode (NULL),
      mbRearrangeActive(false)
{
    SetBackground (Wallpaper ());
}

ToolPanel::~ToolPanel (void)
{
}

sal_uInt32 ToolPanel::AddControl (
    ::std::auto_ptr<ControlFactory> pControlFactory,
    const String& rTitle,
    ULONG nHelpId)
{
    TitledControl* pTitledControl = new TitledControl (
        this,
        pControlFactory,
        rTitle,
        TitleBar::TBT_CONTROL_TITLE);
    ::std::auto_ptr<TreeNode> pChild (pTitledControl);

    // Get the (grand) parent window which is focus-wise our parent.
    Window* pParent = GetParent();
    if (pParent != NULL)
        pParent = pParent->GetParent();

    FocusManager& rFocusManager (FocusManager::Instance());
    int nControlCount (mpControlContainer->GetControlCount());

    // Add a link up from every control to the parent.  A down link is added
    // only for the first control so that when entering the sub tool panel
    // the focus is set to the first control.
    if (pParent != NULL)
    {
        if (nControlCount == 1)
            rFocusManager.RegisterDownLink(pParent, pChild->GetWindow());
        rFocusManager.RegisterUpLink(pChild->GetWindow(), pParent);
    }

    // Replace the old links for cycling between first and last child by
    // current ones.
    if (nControlCount > 0)
    {
        ::Window* pFirst = mpControlContainer->GetControl(0)->GetWindow();
        ::Window* pLast = mpControlContainer->GetControl(nControlCount-1)->GetWindow();
        rFocusManager.RemoveLinks(pFirst,pLast);
        rFocusManager.RemoveLinks(pLast,pFirst);

        rFocusManager.RegisterLink(pFirst,pChild->GetWindow(), KEY_UP);
        rFocusManager.RegisterLink(pChild->GetWindow(),pFirst, KEY_DOWN);
    }

    pTitledControl->GetTitleBar()->SetHelpId(nHelpId);

    return mpControlContainer->AddControl (pChild);
}

void ToolPanel::ListHasChanged (void)
{
    mpControlContainer->ListHasChanged ();
    Rearrange ();
}

void ToolPanel::Resize (void)
{
    Control::Resize();
    Rearrange ();
}

void ToolPanel::RequestResize (void)
{
    Invalidate();
    Rearrange ();
}

/** Subtract the space for the title bars from the available space and
    give the remaining space to the active control.
*/
void ToolPanel::Rearrange (void)
{
    // Prevent recursive calls.
    if ( ! mbRearrangeActive && mpControlContainer->GetVisibleControlCount()>0)
    {
        mbRearrangeActive = true;

        SetBackground (Wallpaper ());

        // Make the area that is covered by the children a little bit
        // smaller so that a frame is visible arround them.
        Rectangle aAvailableArea (Point(0,0), GetOutputSizePixel());

        int nWidth = aAvailableArea.GetWidth();
        sal_uInt32 nControlCount (mpControlContainer->GetControlCount());
        sal_uInt32 nActiveControlIndex (
            mpControlContainer->GetActiveControlIndex());

        // Place title bars of controls above the active control and thereby
        // determine the top of the active control.
        sal_uInt32 nIndex;
        for (nIndex=mpControlContainer->GetFirstIndex();
             nIndex<nActiveControlIndex;
             nIndex=mpControlContainer->GetNextIndex(nIndex))
        {
            TreeNode* pChild = mpControlContainer->GetControl(nIndex);
            if (pChild != NULL)
            {
                sal_uInt32 nHeight = pChild->GetPreferredHeight (nWidth);
                pChild->GetWindow()->SetPosSizePixel (
                    aAvailableArea.TopLeft(),
                    Size(nWidth, nHeight));
                aAvailableArea.Top() += nHeight;
            }
        }

        // Place title bars of controls below the active control and thereby
        // determine the bottom of the active control.
        for (nIndex=mpControlContainer->GetLastIndex();
             nIndex<nControlCount && nIndex!=nActiveControlIndex;
             nIndex=mpControlContainer->GetPreviousIndex(nIndex))
        {
            TreeNode* pChild = mpControlContainer->GetControl(nIndex);
            if (pChild != NULL)
            {
                sal_uInt32 nHeight = pChild->GetPreferredHeight (nWidth);
                pChild->GetWindow()->SetPosSizePixel (
                    Point(aAvailableArea.Left(),
                        aAvailableArea.Bottom()-nHeight+1),
                        Size(nWidth, nHeight));
                aAvailableArea.Bottom() -= nHeight;
            }
        }

        // Finally place the active control.
        TreeNode* pChild = mpControlContainer->GetControl(nActiveControlIndex);
        if (pChild != NULL)
            pChild->GetWindow()->SetPosSizePixel (
                aAvailableArea.TopLeft(),
                aAvailableArea.GetSize());

        mbRearrangeActive = false;
    }
    else
        SetBackground (
            Application::GetSettings().GetStyleSettings().GetDialogColor());
}

Size ToolPanel::GetPreferredSize (void)
{
    return Size(300,300);
}

sal_Int32 ToolPanel::GetPreferredWidth (sal_Int32 nHeight)
{
    return 300;
}

sal_Int32 ToolPanel::GetPreferredHeight (sal_Int32 nWidth)
{
    return 300;
}

bool ToolPanel::IsResizable (void)
{
    return true;
}

::Window* ToolPanel::GetWindow (void)
{
    return this;
}

TaskPaneShellManager* ToolPanel::GetShellManager (void)
{
    return &mrViewShell.GetSubShellManager();
}

::com::sun::star::uno::Reference<
    ::com::sun::star::accessibility::XAccessible> ToolPanel::CreateAccessibleObject (
        const ::com::sun::star::uno::Reference<
        ::com::sun::star::accessibility::XAccessible>& rxParent)
{
    return new ::accessibility::AccessibleTaskPane (
        rxParent,
        String(SdResId(STR_RIGHT_PANE_TITLE)),
        String(SdResId(STR_RIGHT_PANE_TITLE)),
        *this);
}

} } // end of namespace ::sd::toolpanel
<|endoftext|>


<commit_before>/// \file urbi/umessage.hxx

#include <urbi/uvalue.hh>

namespace urbi
{

  template <typename T>
  inline
  int
  getValue(UMessage* m, T& val)
  {
    int res = 0;
    if ((res = (m && m->type == MESSAGE_DATA)))
      val = *m->value;
    delete m;
    return res;
  }

  template <>
  inline
  int
  getValue<double>(UMessage* m, double& val)
  {
    int res = 0;
    if ((res = (m && m->type == MESSAGE_DATA && m->value->type == DATA_DOUBLE)))
      val = (double) *m->value;
    delete m;
    return res;
  }

  inline
  UMessage::operator urbi::UValue& ()
  {
    return *value;
  }

  inline
  std::ostream&
  operator<<(std::ostream& o, const UMessage& m)
  {
    return m.print(o);
  };

} // namespace urbi
<commit_msg>UMessage: improve getValue.<commit_after>/// \file urbi/umessage.hxx

#include <urbi/uvalue.hh>

namespace urbi
{

  template <typename T>
  inline
  int
  getValue(UMessage* m, T& val)
  {
    int res = 0;
    if ((res = (m && m->type == MESSAGE_DATA)))
      val = (T) *m->value;
    delete m;
    return res;
  }

  template <>
  inline
  int
  getValue<double>(UMessage* m, double& val)
  {
    int res = 0;
    if ((res = (m && m->type == MESSAGE_DATA && m->value->type == DATA_DOUBLE)))
      val = (double) *m->value;
    delete m;
    return res;
  }

  inline
  UMessage::operator urbi::UValue& ()
  {
    return *value;
  }

  inline
  std::ostream&
  operator<<(std::ostream& o, const UMessage& m)
  {
    return m.print(o);
  };

} // namespace urbi
<|endoftext|>


<commit_before>#include "manipulatetoolview.h"
#include "manipulatetoolcontroller.h"
#include <QMouseEvent>
#include "terrainview.h"
#include "session.h"
#include "terrain.h"
#include "terrainedit.h"

ManipulateToolView::ManipulateToolView(ManipulateMode mode, Session *session, TerrainView *view) :
    session(session),
    view(view),
    mode(mode),
    hover(false),
    otherActive(false),
    active(false),
    cursor(Qt::SizeVerCursor)
{
    connect(view, SIGNAL(clientMousePressed(QMouseEvent*)), SLOT(clientMousePressed(QMouseEvent*)));
    connect(view, SIGNAL(clientMouseReleased(QMouseEvent*)), SLOT(clientMouseReleased(QMouseEvent*)));
    connect(view, SIGNAL(clientMouseMoved(QMouseEvent*)), SLOT(clientMouseMoved(QMouseEvent*)));
    connect(view, SIGNAL(terrainPaint(TerrainViewDrawingContext*)), SLOT(terrainPaint(TerrainViewDrawingContext*)));

    highlightImage = QImage(8, 8, QImage::Format_RGB32);
    std::memset(highlightImage.bits(), 0, 8 * 8 * 4);
    for (int i = 0; i < 8; ++i) {
        uint col = 0xff00;
        highlightImage.setPixel(i, 0, col);
        highlightImage.setPixel(i, highlightImage.height() - 1, col);
        highlightImage.setPixel(0, i, col);
        highlightImage.setPixel(highlightImage.width() - 1, i, col);
    }
}

ManipulateToolView::~ManipulateToolView()
{

}

void ManipulateToolView::clientMousePressed(QMouseEvent *e)
{
    if (e->isAccepted()) {
        otherActive = true;
        return;
    }
    if (e->button() == Qt::LeftButton && hover) {
        edit = session->beginEdit();
        if (edit) {
            active = true;
            dragStartY = e->y();
            dragStartHeight = session->terrain()->landform(pos.x(), pos.y());
            if (mode == ManipulateMode::Landform)
                view->addCursorOverride(&cursor);
        }
        e->accept();
    }
}

void ManipulateToolView::clientMouseReleased(QMouseEvent *e)
{
    if (active && e->button() == Qt::LeftButton) {
        active = false;
        session->endEdit();
        e->accept();
        if (mode == ManipulateMode::Landform)
            view->removeCursorOverride(&cursor);
    }
    if (e->buttons() == 0) {
        otherActive = false;
    }
    clientMouseMoved(e);
}

void ManipulateToolView::clientMouseMoved(QMouseEvent *e)
{
    if (active && mode == ManipulateMode::Landform) {
        float height = dragStartHeight + (e->y() - dragStartY) * .07f;
        height = Terrain::quantizeOne(height);

        edit->beginEdit(QRect(pos.x(), pos.y(), 1, 1), session->terrain().data());
        session->terrain()->landform(pos.x(), pos.y()) = height;
        edit->endEdit(session->terrain().data());
    } else {
        hover = false;
        if (e->x() >= 0 && e->y() >= 0 && e->x() < view->width() && e->y() < view->height()) {
            pos = view->rayCast(e->pos());
            auto t = session->terrain();
            if (pos.x() >= 0 && pos.y() >= 0 && pos.x() < t->size().width() && pos.y() < t->size().height())
                hover = true;
        }
        if (active && mode == ManipulateMode::Color) {
            // set color
            if (hover) {
                edit->beginEdit(QRect(pos.x(), pos.y(), 1, 1), session->terrain().data());
                session->terrain()->color(pos.x(), pos.y()) = session->primaryColor();
                edit->endEdit(session->terrain().data());
            }
        }
    }
    view->update();
}

void ManipulateToolView::terrainPaint(TerrainViewDrawingContext *ctx)
{
    if (hover) {
        ctx->projectBitmap(highlightImage, QPointF(pos.x() + .05f, pos.y() + .05f), QSizeF(.9f, .9f), true);
    }
}

<commit_msg>Made "paint" tool better<commit_after>#include "manipulatetoolview.h"
#include "manipulatetoolcontroller.h"
#include <QMouseEvent>
#include "terrainview.h"
#include "session.h"
#include "terrain.h"
#include "terrainedit.h"

ManipulateToolView::ManipulateToolView(ManipulateMode mode, Session *session, TerrainView *view) :
    session(session),
    view(view),
    mode(mode),
    hover(false),
    otherActive(false),
    active(false),
    cursor(Qt::SizeVerCursor)
{
    connect(view, SIGNAL(clientMousePressed(QMouseEvent*)), SLOT(clientMousePressed(QMouseEvent*)));
    connect(view, SIGNAL(clientMouseReleased(QMouseEvent*)), SLOT(clientMouseReleased(QMouseEvent*)));
    connect(view, SIGNAL(clientMouseMoved(QMouseEvent*)), SLOT(clientMouseMoved(QMouseEvent*)));
    connect(view, SIGNAL(terrainPaint(TerrainViewDrawingContext*)), SLOT(terrainPaint(TerrainViewDrawingContext*)));

    highlightImage = QImage(8, 8, QImage::Format_RGB32);
    std::memset(highlightImage.bits(), 0, 8 * 8 * 4);
    for (int i = 0; i < 8; ++i) {
        uint col = 0xff00;
        highlightImage.setPixel(i, 0, col);
        highlightImage.setPixel(i, highlightImage.height() - 1, col);
        highlightImage.setPixel(0, i, col);
        highlightImage.setPixel(highlightImage.width() - 1, i, col);
    }
}

ManipulateToolView::~ManipulateToolView()
{

}

void ManipulateToolView::clientMousePressed(QMouseEvent *e)
{
    if (e->isAccepted()) {
        otherActive = true;
        return;
    }
    if (e->button() == Qt::LeftButton && hover) {
        edit = session->beginEdit();
        if (edit) {
            active = true;
            dragStartY = e->y();
            dragStartHeight = session->terrain()->landform(pos.x(), pos.y());
            if (mode == ManipulateMode::Landform)
                view->addCursorOverride(&cursor);
            clientMouseMoved(e);
        }
        e->accept();
    }
}

void ManipulateToolView::clientMouseReleased(QMouseEvent *e)
{
    if (active && e->button() == Qt::LeftButton) {
        active = false;
        session->endEdit();
        e->accept();
        if (mode == ManipulateMode::Landform)
            view->removeCursorOverride(&cursor);
    }
    if (e->buttons() == 0) {
        otherActive = false;
    }
    clientMouseMoved(e);
}

void ManipulateToolView::clientMouseMoved(QMouseEvent *e)
{
    if (active && mode == ManipulateMode::Landform) {
        float height = dragStartHeight + (e->y() - dragStartY) * .07f;
        height = Terrain::quantizeOne(height);

        edit->beginEdit(QRect(pos.x(), pos.y(), 1, 1), session->terrain().data());
        session->terrain()->landform(pos.x(), pos.y()) = height;
        edit->endEdit(session->terrain().data());
    } else {
        hover = false;
        if (e->x() >= 0 && e->y() >= 0 && e->x() < view->width() && e->y() < view->height()) {
            pos = view->rayCast(e->pos());
            auto t = session->terrain();
            if (pos.x() >= 0 && pos.y() >= 0 && pos.x() < t->size().width() && pos.y() < t->size().height())
                hover = true;
        }
        if (active && mode == ManipulateMode::Color) {
            // set color
            if (hover) {
                edit->beginEdit(QRect(pos.x(), pos.y(), 1, 1), session->terrain().data());
                session->terrain()->color(pos.x(), pos.y()) = session->primaryColor();
                edit->endEdit(session->terrain().data());
            }
        }
    }
    view->update();
}

void ManipulateToolView::terrainPaint(TerrainViewDrawingContext *ctx)
{
    if (hover) {
        ctx->projectBitmap(highlightImage, QPointF(pos.x() + .05f, pos.y() + .05f), QSizeF(.9f, .9f), true);
    }
}

<|endoftext|>


<commit_before>#include "objectives/noisy/fitness-noise/FitnessNoiseSource.hpp"
#include <vector>

FitnessNoiseSource::FitnessNoiseSource() {}

Fitness FitnessNoiseSource::noisify(
	Fitness cleanFitness,
	std::function<double(double)> noisemaker
) {
	std::vector<double> components = cleanFitness.getComponents();
	for (unsigned int i = 0; i < components.size(); i++)
		components[i] = noisemaker(components[i]);
	return Fitness(components);
}
<commit_msg>[FitnessNoiseSource]: Updated to use FitnessSource<commit_after>#include "objectives/noisy/fitness-noise/FitnessNoiseSource.hpp"
#include <vector>

FitnessNoiseSource::FitnessNoiseSource() {}

Fitness FitnessNoiseSource::noisify(
	Fitness cleanFitness,
	std::function<double(double)> noisemaker
) {
	std::vector<FitnessPair> components = cleanFitness.getComponents();
	for (unsigned int i = 0; i < components.size(); i++)
		components[i] = std::make_tuple(
			noisemaker(std::get<0>(components[i])),
			std::get<1>(components[i])
		);
	return Fitness(components);
}
<|endoftext|>


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

#include "ui/app_list/app_list_folder_item.h"

#include "base/guid.h"
#include "ui/app_list/app_list_constants.h"
#include "ui/app_list/app_list_item_list.h"
#include "ui/app_list/folder_image_source.h"
#include "ui/gfx/geometry/rect.h"

namespace app_list {

AppListFolderItem::AppListFolderItem(const std::string& id,
                                     FolderType folder_type)
    : AppListItem(id),
      folder_type_(folder_type),
      item_list_(new AppListItemList) {
  item_list_->AddObserver(this);
}

AppListFolderItem::~AppListFolderItem() {
  for (size_t i = 0; i < top_items_.size(); ++i)
    top_items_[i]->RemoveObserver(this);
  item_list_->RemoveObserver(this);
}

void AppListFolderItem::UpdateIcon() {
  FolderImageSource::Icons top_icons;
  for (size_t i = 0; i < top_items_.size(); ++i)
    top_icons.push_back(top_items_[i]->icon());

  const gfx::Size icon_size = gfx::Size(kGridIconDimension, kGridIconDimension);
  gfx::ImageSkia icon = gfx::ImageSkia(
      new FolderImageSource(top_icons, icon_size),
      icon_size);
  SetIcon(icon, false);
}

const gfx::ImageSkia& AppListFolderItem::GetTopIcon(size_t item_index) {
  DCHECK(item_index <= top_items_.size());
  return top_items_[item_index]->icon();
}

gfx::Rect AppListFolderItem::GetTargetIconRectInFolderForItem(
    AppListItem* item,
    const gfx::Rect& folder_icon_bounds) {
  for (size_t i = 0; i < top_items_.size(); ++i) {
    if (item->id() == top_items_[i]->id()) {
      std::vector<gfx::Rect> rects =
          FolderImageSource::GetTopIconsBounds(folder_icon_bounds);
      return rects[i];
    }
  }

  gfx::Rect target_rect(folder_icon_bounds);
  target_rect.ClampToCenteredSize(FolderImageSource::ItemIconSize());
  return target_rect;
}

void AppListFolderItem::Activate(int event_flags) {
  // Folder handling is implemented by the View, so do nothing.
}

// static
const char AppListFolderItem::kItemType[] = "FolderItem";

const char* AppListFolderItem::GetItemType() const {
  return AppListFolderItem::kItemType;
}

ui::MenuModel* AppListFolderItem::GetContextMenuModel() {
  // TODO(stevenjb/jennyz): Implement.
  return NULL;
}

AppListItem* AppListFolderItem::FindChildItem(const std::string& id) {
  return item_list_->FindItem(id);
}

size_t AppListFolderItem::ChildItemCount() const {
  return item_list_->item_count();
}

void AppListFolderItem::OnExtensionPreferenceChanged() {
  for (size_t i = 0; i < item_list_->item_count(); ++i)
    item_list_->item_at(i)->OnExtensionPreferenceChanged();
}

bool AppListFolderItem::CompareForTest(const AppListItem* other) const {
  if (!AppListItem::CompareForTest(other))
    return false;
  const AppListFolderItem* other_folder =
      static_cast<const AppListFolderItem*>(other);
  if (other_folder->item_list()->item_count() != item_list_->item_count())
    return false;
  for (size_t i = 0; i < item_list_->item_count(); ++i) {
    if (!item_list()->item_at(i)->CompareForTest(
            other_folder->item_list()->item_at(i)))
      return false;
  }
  return true;
}

std::string AppListFolderItem::GenerateId() {
  return base::GenerateGUID();
}

void AppListFolderItem::ItemIconChanged() {
  UpdateIcon();
}

void AppListFolderItem::OnListItemAdded(size_t index,
                                        AppListItem* item) {
  if (index <= kNumFolderTopItems)
    UpdateTopItems();
}

void AppListFolderItem::OnListItemRemoved(size_t index,
                                          AppListItem* item) {
  if (index <= kNumFolderTopItems)
    UpdateTopItems();
}

void AppListFolderItem::OnListItemMoved(size_t from_index,
                                        size_t to_index,
                                        AppListItem* item) {
  if (from_index <= kNumFolderTopItems || to_index <= kNumFolderTopItems)
    UpdateTopItems();
}

void AppListFolderItem::UpdateTopItems() {
  for (size_t i = 0; i < top_items_.size(); ++i)
    top_items_[i]->RemoveObserver(this);
  top_items_.clear();

  for (size_t i = 0;
       i < kNumFolderTopItems && i < item_list_->item_count(); ++i) {
    AppListItem* item = item_list_->item_at(i);
    item->AddObserver(this);
    top_items_.push_back(item);
  }
  UpdateIcon();
}

}  // namespace app_list
<commit_msg>App list folder icons: Fixed off-by-one error.<commit_after>// Copyright 2013 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "ui/app_list/app_list_folder_item.h"

#include "base/guid.h"
#include "ui/app_list/app_list_constants.h"
#include "ui/app_list/app_list_item_list.h"
#include "ui/app_list/folder_image_source.h"
#include "ui/gfx/geometry/rect.h"

namespace app_list {

AppListFolderItem::AppListFolderItem(const std::string& id,
                                     FolderType folder_type)
    : AppListItem(id),
      folder_type_(folder_type),
      item_list_(new AppListItemList) {
  item_list_->AddObserver(this);
}

AppListFolderItem::~AppListFolderItem() {
  for (size_t i = 0; i < top_items_.size(); ++i)
    top_items_[i]->RemoveObserver(this);
  item_list_->RemoveObserver(this);
}

void AppListFolderItem::UpdateIcon() {
  FolderImageSource::Icons top_icons;
  for (size_t i = 0; i < top_items_.size(); ++i)
    top_icons.push_back(top_items_[i]->icon());

  const gfx::Size icon_size = gfx::Size(kGridIconDimension, kGridIconDimension);
  gfx::ImageSkia icon = gfx::ImageSkia(
      new FolderImageSource(top_icons, icon_size),
      icon_size);
  SetIcon(icon, false);
}

const gfx::ImageSkia& AppListFolderItem::GetTopIcon(size_t item_index) {
  CHECK_LT(item_index, top_items_.size());
  return top_items_[item_index]->icon();
}

gfx::Rect AppListFolderItem::GetTargetIconRectInFolderForItem(
    AppListItem* item,
    const gfx::Rect& folder_icon_bounds) {
  for (size_t i = 0; i < top_items_.size(); ++i) {
    if (item->id() == top_items_[i]->id()) {
      std::vector<gfx::Rect> rects =
          FolderImageSource::GetTopIconsBounds(folder_icon_bounds);
      return rects[i];
    }
  }

  gfx::Rect target_rect(folder_icon_bounds);
  target_rect.ClampToCenteredSize(FolderImageSource::ItemIconSize());
  return target_rect;
}

void AppListFolderItem::Activate(int event_flags) {
  // Folder handling is implemented by the View, so do nothing.
}

// static
const char AppListFolderItem::kItemType[] = "FolderItem";

const char* AppListFolderItem::GetItemType() const {
  return AppListFolderItem::kItemType;
}

ui::MenuModel* AppListFolderItem::GetContextMenuModel() {
  // TODO(stevenjb/jennyz): Implement.
  return NULL;
}

AppListItem* AppListFolderItem::FindChildItem(const std::string& id) {
  return item_list_->FindItem(id);
}

size_t AppListFolderItem::ChildItemCount() const {
  return item_list_->item_count();
}

void AppListFolderItem::OnExtensionPreferenceChanged() {
  for (size_t i = 0; i < item_list_->item_count(); ++i)
    item_list_->item_at(i)->OnExtensionPreferenceChanged();
}

bool AppListFolderItem::CompareForTest(const AppListItem* other) const {
  if (!AppListItem::CompareForTest(other))
    return false;
  const AppListFolderItem* other_folder =
      static_cast<const AppListFolderItem*>(other);
  if (other_folder->item_list()->item_count() != item_list_->item_count())
    return false;
  for (size_t i = 0; i < item_list_->item_count(); ++i) {
    if (!item_list()->item_at(i)->CompareForTest(
            other_folder->item_list()->item_at(i)))
      return false;
  }
  return true;
}

std::string AppListFolderItem::GenerateId() {
  return base::GenerateGUID();
}

void AppListFolderItem::ItemIconChanged() {
  UpdateIcon();
}

void AppListFolderItem::OnListItemAdded(size_t index,
                                        AppListItem* item) {
  if (index < kNumFolderTopItems)
    UpdateTopItems();
}

void AppListFolderItem::OnListItemRemoved(size_t index,
                                          AppListItem* item) {
  if (index < kNumFolderTopItems)
    UpdateTopItems();
}

void AppListFolderItem::OnListItemMoved(size_t from_index,
                                        size_t to_index,
                                        AppListItem* item) {
  if (from_index < kNumFolderTopItems || to_index < kNumFolderTopItems)
    UpdateTopItems();
}

void AppListFolderItem::UpdateTopItems() {
  for (size_t i = 0; i < top_items_.size(); ++i)
    top_items_[i]->RemoveObserver(this);
  top_items_.clear();

  for (size_t i = 0;
       i < kNumFolderTopItems && i < item_list_->item_count(); ++i) {
    AppListItem* item = item_list_->item_at(i);
    item->AddObserver(this);
    top_items_.push_back(item);
  }
  UpdateIcon();
}

}  // namespace app_list
<|endoftext|>


<commit_before>/****************************************************************************
**
** Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies).
** All rights reserved.
** Contact: Nokia Corporation (qt-info@nokia.com)
**
** This file is part of the Qt Creator.
**
** $QT_BEGIN_LICENSE:LGPL$
** No Commercial Usage
** This file contains pre-release code and may not be distributed.
** You may use this file in accordance with the terms and conditions
** contained in the Technology Preview License Agreement accompanying
** this package.
**
** GNU Lesser General Public License Usage
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 as published by the Free Software
** Foundation and appearing in the file LICENSE.LGPL included in the
** packaging of this file.  Please review the following information to
** ensure the GNU Lesser General Public License version 2.1 requirements
** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, Nokia gives you certain additional
** rights.  These rights are described in the Nokia Qt LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
** If you have questions regarding the use of this file, please contact
** Nokia at qt-info@nokia.com.
**
** $QT_END_LICENSE$
**
****************************************************************************/

#include "maemosshrunner.h"

#include "maemodeploystep.h"
#include "maemodeviceconfigurations.h"
#include "maemoglobal.h"
#include "maemoremotemounter.h"
#include "maemoremotemountsmodel.h"
#include "maemorunconfiguration.h"

#include <coreplugin/ssh/sshconnection.h>
#include <coreplugin/ssh/sshremoteprocess.h>

#include <QtCore/QFileInfo>

using namespace Core;

namespace Qt4ProjectManager {
namespace Internal {

MaemoSshRunner::MaemoSshRunner(QObject *parent,
    MaemoRunConfiguration *runConfig, bool debugging)
    : QObject(parent), m_runConfig(runConfig),
      m_mounter(new MaemoRemoteMounter(this)),
      m_devConfig(runConfig->deviceConfig()), m_shuttingDown(false),
      m_debugging(debugging)
{
    m_procsToKill
        << QFileInfo(m_runConfig->localExecutableFilePath()).fileName()
        << QLatin1String("utfs-client");
    if (debugging)
        m_procsToKill << QLatin1String("gdbserver");
    connect(m_mounter, SIGNAL(mounted()), this, SLOT(handleMounted()));
    connect(m_mounter, SIGNAL(unmounted()), this, SLOT(handleUnmounted()));
    connect(m_mounter, SIGNAL(error(QString)), this,
        SLOT(handleMounterError(QString)));
    connect(m_mounter, SIGNAL(reportProgress(QString)), this,
        SIGNAL(reportProgress(QString)));
    connect(m_mounter, SIGNAL(debugOutput(QString)), this,
        SIGNAL(mountDebugOutput(QString)));
}

MaemoSshRunner::~MaemoSshRunner() {}

void MaemoSshRunner::setConnection(const QSharedPointer<Core::SshConnection> &connection)
{
    m_connection = connection;
}

void MaemoSshRunner::start()
{
    // Should not happen.
    if (m_shuttingDown) {
        emit error(tr("Cannot start deployment, as the clean-up from the last time has not finished yet."));
        return;
    }

    m_stop = false;
    m_exitStatus = -1;
    if (m_connection)
        disconnect(m_connection.data(), 0, this, 0);
    bool reUse = isConnectionUsable();
    if (!reUse)
        m_connection = m_runConfig->deployStep()->sshConnection();
    reUse = isConnectionUsable();
    if (!reUse)
        m_connection = SshConnection::create();
    connect(m_connection.data(), SIGNAL(connected()), this,
        SLOT(handleConnected()));
    connect(m_connection.data(), SIGNAL(error(SshError)), this,
        SLOT(handleConnectionFailure()));
    if (reUse) {
        handleConnected();
    } else {
        emit reportProgress(tr("Connecting to device..."));
        m_connection->connectToHost(m_devConfig.server);
    }
}

void MaemoSshRunner::stop()
{
    if (m_shuttingDown)
        return;

    m_stop = true;
    m_mounter->stop();
    if (m_cleaner)
        disconnect(m_cleaner.data(), 0, this, 0);
    cleanup(false);
}

void MaemoSshRunner::handleConnected()
{
    if (m_stop)
        return;

    cleanup(true);
}

void MaemoSshRunner::handleConnectionFailure()
{
    emit error(tr("Could not connect to host: %1")
        .arg(m_connection->errorString()));
}

void MaemoSshRunner::cleanup(bool initialCleanup)
{
    if (!isConnectionUsable())
        return;

    emit reportProgress(tr("Killing remote process(es)..."));
    m_shuttingDown = !initialCleanup;
    QString niceKill;
    QString brutalKill;
    foreach (const QString &proc, m_procsToKill) {
        niceKill += QString::fromLocal8Bit("pkill %1\\$;").arg(proc);
        brutalKill += QString::fromLocal8Bit("pkill -9 %1\\$;").arg(proc);
    }
    QString remoteCall = niceKill + QLatin1String("sleep 1; ") + brutalKill;
    remoteCall.remove(remoteCall.count() - 1, 1); // Get rid of trailing semicolon.

    m_cleaner = m_connection->createRemoteProcess(remoteCall.toUtf8());
    connect(m_cleaner.data(), SIGNAL(closed(int)), this,
        SLOT(handleCleanupFinished(int)));
    m_cleaner->start();
}

void MaemoSshRunner::handleCleanupFinished(int exitStatus)
{
    Q_ASSERT(exitStatus == SshRemoteProcess::FailedToStart
        || exitStatus == SshRemoteProcess::KilledBySignal
        || exitStatus == SshRemoteProcess::ExitedNormally);

    if (m_shuttingDown) {
        m_unmountState = ShutdownUnmount;
        m_mounter->unmount();
        return;
    }

    if (m_stop)
        return;

    if (exitStatus != SshRemoteProcess::ExitedNormally) {
        emit error(tr("Initial cleanup failed: %1")
            .arg(m_cleaner->errorString()));
    } else {
        m_mounter->setConnection(m_connection);
        m_unmountState = InitialUnmount;
        m_mounter->unmount();
    }
}

void MaemoSshRunner::handleUnmounted()
{
    switch (m_unmountState) {
    case InitialUnmount: {
        if (m_stop)
            return;
        m_mounter->resetMountSpecifications();
        MaemoPortList portList = m_devConfig.freePorts();
        if (m_debugging) { // gdbserver and QML inspector need one port each.
            if (m_runConfig->useCppDebugger() && !m_runConfig->useRemoteGdb())
                portList.getNext();
            if (m_runConfig->useQmlDebugger())
                portList.getNext();
        }
        m_mounter->setToolchain(m_runConfig->toolchain());
        m_mounter->setPortList(portList);
        const MaemoRemoteMountsModel * const remoteMounts
            = m_runConfig->remoteMounts();
        for (int i = 0; i < remoteMounts->mountSpecificationCount(); ++i) {
            if (!addMountSpecification(remoteMounts->mountSpecificationAt(i)))
                return;
        }
        if (m_debugging && m_runConfig->useRemoteGdb()) {
            if (!addMountSpecification(MaemoMountSpecification(
                m_runConfig->localDirToMountForRemoteGdb(),
                MaemoGlobal::remoteProjectSourcesMountPoint())))
                return;
        }
        m_unmountState = PreMountUnmount;
        m_mounter->unmount();
        break;
    }
    case PreMountUnmount:
        if (m_stop)
            return;
        m_mounter->mount();
        break;
    case ShutdownUnmount:
        Q_ASSERT(m_shuttingDown);
        m_mounter->resetMountSpecifications();
        m_shuttingDown = false;
        if (m_exitStatus == SshRemoteProcess::ExitedNormally) {
            emit remoteProcessFinished(m_runner->exitCode());
        } else if (m_exitStatus == -1) {
            emit remoteProcessFinished(-1);
        } else {
            emit error(tr("Error running remote process: %1")
                .arg(m_runner->errorString()));
        }
        m_exitStatus = -1;
        break;
    }
}

void MaemoSshRunner::handleMounted()
{
    if (!m_stop)
        emit readyForExecution();
}

void MaemoSshRunner::handleMounterError(const QString &errorMsg)
{
    if (m_shuttingDown)
        m_shuttingDown = false;
    emit error(errorMsg);
}

void MaemoSshRunner::startExecution(const QByteArray &remoteCall)
{
    if (m_runConfig->remoteExecutableFilePath().isEmpty()) {
        emit error(tr("Cannot run: No remote executable set."));
        return;
    }

    m_runner = m_connection->createRemoteProcess(remoteCall);
    connect(m_runner.data(), SIGNAL(started()), this,
        SIGNAL(remoteProcessStarted()));
    connect(m_runner.data(), SIGNAL(closed(int)), this,
        SLOT(handleRemoteProcessFinished(int)));
    connect(m_runner.data(), SIGNAL(outputAvailable(QByteArray)), this,
        SIGNAL(remoteOutput(QByteArray)));
    connect(m_runner.data(), SIGNAL(errorOutputAvailable(QByteArray)), this,
        SIGNAL(remoteErrorOutput(QByteArray)));
    m_runner->start();
}

void MaemoSshRunner::handleRemoteProcessFinished(int exitStatus)
{
    Q_ASSERT(exitStatus == SshRemoteProcess::FailedToStart
        || exitStatus == SshRemoteProcess::KilledBySignal
        || exitStatus == SshRemoteProcess::ExitedNormally);

    m_exitStatus = exitStatus;
    cleanup(false);
}

bool MaemoSshRunner::addMountSpecification(const MaemoMountSpecification &mountSpec)
{
    if (!m_mounter->addMountSpecification(mountSpec, false)) {
        emit error(tr("The device does not have enough free ports "
            "for this run configuration."));
        return false;
    }
    return true;
}

bool MaemoSshRunner::isConnectionUsable() const
{
    return m_connection && m_connection->state() == SshConnection::Connected
        && m_connection->connectionParameters() == m_devConfig.server;
}

} // namespace Internal
} // namespace Qt4ProjectManager

<commit_msg>Maemo: Use tighter regular expression for pkill.<commit_after>/****************************************************************************
**
** Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies).
** All rights reserved.
** Contact: Nokia Corporation (qt-info@nokia.com)
**
** This file is part of the Qt Creator.
**
** $QT_BEGIN_LICENSE:LGPL$
** No Commercial Usage
** This file contains pre-release code and may not be distributed.
** You may use this file in accordance with the terms and conditions
** contained in the Technology Preview License Agreement accompanying
** this package.
**
** GNU Lesser General Public License Usage
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 as published by the Free Software
** Foundation and appearing in the file LICENSE.LGPL included in the
** packaging of this file.  Please review the following information to
** ensure the GNU Lesser General Public License version 2.1 requirements
** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, Nokia gives you certain additional
** rights.  These rights are described in the Nokia Qt LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
** If you have questions regarding the use of this file, please contact
** Nokia at qt-info@nokia.com.
**
** $QT_END_LICENSE$
**
****************************************************************************/

#include "maemosshrunner.h"

#include "maemodeploystep.h"
#include "maemodeviceconfigurations.h"
#include "maemoglobal.h"
#include "maemoremotemounter.h"
#include "maemoremotemountsmodel.h"
#include "maemorunconfiguration.h"

#include <coreplugin/ssh/sshconnection.h>
#include <coreplugin/ssh/sshremoteprocess.h>

#include <QtCore/QFileInfo>

using namespace Core;

namespace Qt4ProjectManager {
namespace Internal {

MaemoSshRunner::MaemoSshRunner(QObject *parent,
    MaemoRunConfiguration *runConfig, bool debugging)
    : QObject(parent), m_runConfig(runConfig),
      m_mounter(new MaemoRemoteMounter(this)),
      m_devConfig(runConfig->deviceConfig()), m_shuttingDown(false),
      m_debugging(debugging)
{
    m_procsToKill
        << QFileInfo(m_runConfig->localExecutableFilePath()).fileName()
        << QLatin1String("utfs-client");
    if (debugging)
        m_procsToKill << QLatin1String("gdbserver");
    connect(m_mounter, SIGNAL(mounted()), this, SLOT(handleMounted()));
    connect(m_mounter, SIGNAL(unmounted()), this, SLOT(handleUnmounted()));
    connect(m_mounter, SIGNAL(error(QString)), this,
        SLOT(handleMounterError(QString)));
    connect(m_mounter, SIGNAL(reportProgress(QString)), this,
        SIGNAL(reportProgress(QString)));
    connect(m_mounter, SIGNAL(debugOutput(QString)), this,
        SIGNAL(mountDebugOutput(QString)));
}

MaemoSshRunner::~MaemoSshRunner() {}

void MaemoSshRunner::setConnection(const QSharedPointer<Core::SshConnection> &connection)
{
    m_connection = connection;
}

void MaemoSshRunner::start()
{
    // Should not happen.
    if (m_shuttingDown) {
        emit error(tr("Cannot start deployment, as the clean-up from the last time has not finished yet."));
        return;
    }

    m_stop = false;
    m_exitStatus = -1;
    if (m_connection)
        disconnect(m_connection.data(), 0, this, 0);
    bool reUse = isConnectionUsable();
    if (!reUse)
        m_connection = m_runConfig->deployStep()->sshConnection();
    reUse = isConnectionUsable();
    if (!reUse)
        m_connection = SshConnection::create();
    connect(m_connection.data(), SIGNAL(connected()), this,
        SLOT(handleConnected()));
    connect(m_connection.data(), SIGNAL(error(SshError)), this,
        SLOT(handleConnectionFailure()));
    if (reUse) {
        handleConnected();
    } else {
        emit reportProgress(tr("Connecting to device..."));
        m_connection->connectToHost(m_devConfig.server);
    }
}

void MaemoSshRunner::stop()
{
    if (m_shuttingDown)
        return;

    m_stop = true;
    m_mounter->stop();
    if (m_cleaner)
        disconnect(m_cleaner.data(), 0, this, 0);
    cleanup(false);
}

void MaemoSshRunner::handleConnected()
{
    if (m_stop)
        return;

    cleanup(true);
}

void MaemoSshRunner::handleConnectionFailure()
{
    emit error(tr("Could not connect to host: %1")
        .arg(m_connection->errorString()));
}

void MaemoSshRunner::cleanup(bool initialCleanup)
{
    if (!isConnectionUsable())
        return;

    emit reportProgress(tr("Killing remote process(es)..."));
    m_shuttingDown = !initialCleanup;

    // pkill behaves differently on Fremantle and Harmattan.
    const char *const killTemplate = "pkill -%2 '^%1$'; pkill -%2 '/%1$';";

    QString niceKill;
    QString brutalKill;
    foreach (const QString &proc, m_procsToKill) {
        niceKill += QString::fromLocal8Bit(killTemplate).arg(proc).arg("SIGTERM");
        brutalKill += QString::fromLocal8Bit(killTemplate).arg(proc).arg("SIGKILL");
    }
    QString remoteCall = niceKill + QLatin1String("sleep 1; ") + brutalKill;
    remoteCall.remove(remoteCall.count() - 1, 1); // Get rid of trailing semicolon.

    m_cleaner = m_connection->createRemoteProcess(remoteCall.toUtf8());
    connect(m_cleaner.data(), SIGNAL(closed(int)), this,
        SLOT(handleCleanupFinished(int)));
    m_cleaner->start();
}

void MaemoSshRunner::handleCleanupFinished(int exitStatus)
{
    Q_ASSERT(exitStatus == SshRemoteProcess::FailedToStart
        || exitStatus == SshRemoteProcess::KilledBySignal
        || exitStatus == SshRemoteProcess::ExitedNormally);

    if (m_shuttingDown) {
        m_unmountState = ShutdownUnmount;
        m_mounter->unmount();
        return;
    }

    if (m_stop)
        return;

    if (exitStatus != SshRemoteProcess::ExitedNormally) {
        emit error(tr("Initial cleanup failed: %1")
            .arg(m_cleaner->errorString()));
    } else {
        m_mounter->setConnection(m_connection);
        m_unmountState = InitialUnmount;
        m_mounter->unmount();
    }
}

void MaemoSshRunner::handleUnmounted()
{
    switch (m_unmountState) {
    case InitialUnmount: {
        if (m_stop)
            return;
        m_mounter->resetMountSpecifications();
        MaemoPortList portList = m_devConfig.freePorts();
        if (m_debugging) { // gdbserver and QML inspector need one port each.
            if (m_runConfig->useCppDebugger() && !m_runConfig->useRemoteGdb())
                portList.getNext();
            if (m_runConfig->useQmlDebugger())
                portList.getNext();
        }
        m_mounter->setToolchain(m_runConfig->toolchain());
        m_mounter->setPortList(portList);
        const MaemoRemoteMountsModel * const remoteMounts
            = m_runConfig->remoteMounts();
        for (int i = 0; i < remoteMounts->mountSpecificationCount(); ++i) {
            if (!addMountSpecification(remoteMounts->mountSpecificationAt(i)))
                return;
        }
        if (m_debugging && m_runConfig->useRemoteGdb()) {
            if (!addMountSpecification(MaemoMountSpecification(
                m_runConfig->localDirToMountForRemoteGdb(),
                MaemoGlobal::remoteProjectSourcesMountPoint())))
                return;
        }
        m_unmountState = PreMountUnmount;
        m_mounter->unmount();
        break;
    }
    case PreMountUnmount:
        if (m_stop)
            return;
        m_mounter->mount();
        break;
    case ShutdownUnmount:
        Q_ASSERT(m_shuttingDown);
        m_mounter->resetMountSpecifications();
        m_shuttingDown = false;
        if (m_exitStatus == SshRemoteProcess::ExitedNormally) {
            emit remoteProcessFinished(m_runner->exitCode());
        } else if (m_exitStatus == -1) {
            emit remoteProcessFinished(-1);
        } else {
            emit error(tr("Error running remote process: %1")
                .arg(m_runner->errorString()));
        }
        m_exitStatus = -1;
        break;
    }
}

void MaemoSshRunner::handleMounted()
{
    if (!m_stop)
        emit readyForExecution();
}

void MaemoSshRunner::handleMounterError(const QString &errorMsg)
{
    if (m_shuttingDown)
        m_shuttingDown = false;
    emit error(errorMsg);
}

void MaemoSshRunner::startExecution(const QByteArray &remoteCall)
{
    if (m_runConfig->remoteExecutableFilePath().isEmpty()) {
        emit error(tr("Cannot run: No remote executable set."));
        return;
    }

    m_runner = m_connection->createRemoteProcess(remoteCall);
    connect(m_runner.data(), SIGNAL(started()), this,
        SIGNAL(remoteProcessStarted()));
    connect(m_runner.data(), SIGNAL(closed(int)), this,
        SLOT(handleRemoteProcessFinished(int)));
    connect(m_runner.data(), SIGNAL(outputAvailable(QByteArray)), this,
        SIGNAL(remoteOutput(QByteArray)));
    connect(m_runner.data(), SIGNAL(errorOutputAvailable(QByteArray)), this,
        SIGNAL(remoteErrorOutput(QByteArray)));
    m_runner->start();
}

void MaemoSshRunner::handleRemoteProcessFinished(int exitStatus)
{
    Q_ASSERT(exitStatus == SshRemoteProcess::FailedToStart
        || exitStatus == SshRemoteProcess::KilledBySignal
        || exitStatus == SshRemoteProcess::ExitedNormally);

    m_exitStatus = exitStatus;
    cleanup(false);
}

bool MaemoSshRunner::addMountSpecification(const MaemoMountSpecification &mountSpec)
{
    if (!m_mounter->addMountSpecification(mountSpec, false)) {
        emit error(tr("The device does not have enough free ports "
            "for this run configuration."));
        return false;
    }
    return true;
}

bool MaemoSshRunner::isConnectionUsable() const
{
    return m_connection && m_connection->state() == SshConnection::Connected
        && m_connection->connectionParameters() == m_devConfig.server;
}

} // namespace Internal
} // namespace Qt4ProjectManager

<|endoftext|>


<commit_before>#include "SurfaceCollection.hpp"
#include <map>

namespace Slic3r {

SurfaceCollection::operator Polygons() const
{
    Polygons polygons;
    for (Surfaces::const_iterator surface = this->surfaces.begin(); surface != this->surfaces.end(); ++surface) {
        Polygons surface_p = surface->expolygon;
        polygons.insert(polygons.end(), surface_p.begin(), surface_p.end());
    }
    return polygons;
}

SurfaceCollection::operator ExPolygons() const
{
    ExPolygons expp;
    expp.reserve(this->surfaces.size());
    for (Surfaces::const_iterator surface = this->surfaces.begin(); surface != this->surfaces.end(); ++surface) {
        expp.push_back(surface->expolygon);
    }
    return expp;
}

void
SurfaceCollection::simplify(double tolerance)
{
    Surfaces ss;
    for (Surfaces::const_iterator it_s = this->surfaces.begin(); it_s != this->surfaces.end(); ++it_s) {
        ExPolygons expp;
        it_s->expolygon.simplify(tolerance, &expp);
        for (ExPolygons::const_iterator it_e = expp.begin(); it_e != expp.end(); ++it_e) {
            Surface s = *it_s;
            s.expolygon = *it_e;
            ss.push_back(s);
        }
    }
    this->surfaces = ss;
}

/* group surfaces by common properties */
void
SurfaceCollection::group(std::vector<SurfacesConstPtr> *retval) const
{
    for (Surfaces::const_iterator it = this->surfaces.begin(); it != this->surfaces.end(); ++it) {
        // find a group with the same properties
        SurfacesConstPtr* group = NULL;
        for (std::vector<SurfacesConstPtr>::iterator git = retval->begin(); git != retval->end(); ++git) {
            const Surface* gkey = git->front();
            if (   gkey->surface_type      == it->surface_type
                && gkey->thickness         == it->thickness
                && gkey->thickness_layers  == it->thickness_layers
                && gkey->bridge_angle      == it->bridge_angle) {
                group = &*git;
                break;
            }
        }

        // if no group with these properties exists, add one
        if (group == NULL) {
            retval->resize(retval->size() + 1);
            group = &retval->back();
        }

        // append surface to group
        group->push_back(&*it);
    }
}

template <class T>
bool
SurfaceCollection::any_internal_contains(const T &item) const
{
    for (Surfaces::const_iterator surface = this->surfaces.begin(); surface != this->surfaces.end(); ++surface) {
        if (surface->is_internal() && surface->expolygon.contains(item)) return true;
    }
    return false;
}
template bool SurfaceCollection::any_internal_contains<Polyline>(const Polyline &item) const;

template <class T>
bool
SurfaceCollection::any_bottom_contains(const T &item) const
{
    for (Surfaces::const_iterator surface = this->surfaces.begin(); surface != this->surfaces.end(); ++surface) {
        if (surface->is_bottom() && surface->expolygon.contains(item)) return true;
    }
    return false;
}
template bool SurfaceCollection::any_bottom_contains<Polyline>(const Polyline &item) const;

SurfacesPtr
SurfaceCollection::filter_by_type(SurfaceType type)
{
    SurfacesPtr ss;
    for (Surfaces::iterator surface = this->surfaces.begin(); surface != this->surfaces.end(); ++surface) {
        if (surface->surface_type == type) ss.push_back(&*surface);
    }
    return ss;
}

SurfacesPtr
SurfaceCollection::filter_by_type(std::initializer_list<SurfaceType> types)
{
    size_t n {0};
    SurfacesPtr ss;
    for (const auto& t : types) {
        n |= t;
    }
    for (Surfaces::iterator surface = this->surfaces.begin(); surface != this->surfaces.end(); ++surface) {
        if (surface->surface_type & n == surface->surface_type) ss.push_back(&*surface);
    }
    return ss;
}
void
SurfaceCollection::filter_by_type(SurfaceType type, Polygons* polygons)
{
    for (Surfaces::iterator surface = this->surfaces.begin(); surface != this->surfaces.end(); ++surface) {
        if (surface->surface_type == type)
            append_to(*polygons, (Polygons)surface->expolygon);
    }
}

void
SurfaceCollection::append(const SurfaceCollection &coll)
{
    this->append(coll.surfaces);
}

void
SurfaceCollection::append(const Surfaces &surfaces)
{
    append_to(this->surfaces, surfaces);
}

void
SurfaceCollection::append(const ExPolygons &src, const Surface &templ)
{
    this->surfaces.reserve(this->surfaces.size() + src.size());
    for (ExPolygons::const_iterator it = src.begin(); it != src.end(); ++ it) {
        this->surfaces.push_back(templ);
        this->surfaces.back().expolygon = *it;
    }
}

void
SurfaceCollection::append(const ExPolygons &src, SurfaceType surfaceType)
{
    this->surfaces.reserve(this->surfaces.size() + src.size());
    for (ExPolygons::const_iterator it = src.begin(); it != src.end(); ++ it)
        this->surfaces.push_back(Surface(surfaceType, *it));
}

size_t
SurfaceCollection::polygons_count() const
{
    size_t count = 0;
    for (Surfaces::const_iterator it = this->surfaces.begin(); it != this->surfaces.end(); ++ it)
        count += 1 + it->expolygon.holes.size();
    return count;
}
void
SurfaceCollection::remove_type(const SurfaceType type)
{
    // Use stl remove_if to remove
    auto ptr = std::remove_if(surfaces.begin(), surfaces.end(),[type] (Surface& s) { return s.surface_type == type; });
    surfaces.erase(ptr, surfaces.cend());
}

void
SurfaceCollection::remove_types(const SurfaceType *types, size_t ntypes)
{
    for (size_t i = 0; i < ntypes; ++i)
        this->remove_type(types[i]);
}

void
SurfaceCollection::remove_types(std::initializer_list<SurfaceType> types) {
    for (const auto& t : types) {
        this->remove_type(t);
    }
}

void
SurfaceCollection::keep_type(const SurfaceType type)
{
    // Use stl remove_if to remove
    auto ptr = std::remove_if(surfaces.begin(), surfaces.end(),[type] (const Surface& s) { return s.surface_type != type; });
    surfaces.erase(ptr, surfaces.cend());
}

void
SurfaceCollection::keep_types(const SurfaceType *types, size_t ntypes)
{
    size_t n {0};
    for (size_t i = 0; i < ntypes; ++i)
        n |= types[i]; // form bitmask.
    // Use stl remove_if to remove
    auto ptr = std::remove_if(surfaces.begin(), surfaces.end(),[n] (const Surface& s) { return s.surface_type & n != s.surface_type; });
    surfaces.erase(ptr, surfaces.cend());
}

void
SurfaceCollection::keep_types(std::initializer_list<SurfaceType> types) {
    for (const auto& t : types) {
        this->keep_type(t);
    }
}
/* group surfaces by common properties */
void
SurfaceCollection::group(std::vector<SurfacesPtr> *retval)
{
    for (Surfaces::iterator it = this->surfaces.begin(); it != this->surfaces.end(); ++it) {
        // find a group with the same properties
        SurfacesPtr* group = NULL;
        for (std::vector<SurfacesPtr>::iterator git = retval->begin(); git != retval->end(); ++git)
            if (! git->empty() && surfaces_could_merge(*git->front(), *it)) {
                group = &*git;
                break;
            }
        // if no group with these properties exists, add one
        if (group == NULL) {
            retval->resize(retval->size() + 1);
            group = &retval->back();
        }
        // append surface to group
        group->push_back(&*it);
    }
}

} // namespace Slic3r
<commit_msg>Added parens to declare intent and quiet compiler warnings.<commit_after>#include "SurfaceCollection.hpp"
#include <map>

namespace Slic3r {

SurfaceCollection::operator Polygons() const
{
    Polygons polygons;
    for (Surfaces::const_iterator surface = this->surfaces.begin(); surface != this->surfaces.end(); ++surface) {
        Polygons surface_p = surface->expolygon;
        polygons.insert(polygons.end(), surface_p.begin(), surface_p.end());
    }
    return polygons;
}

SurfaceCollection::operator ExPolygons() const
{
    ExPolygons expp;
    expp.reserve(this->surfaces.size());
    for (Surfaces::const_iterator surface = this->surfaces.begin(); surface != this->surfaces.end(); ++surface) {
        expp.push_back(surface->expolygon);
    }
    return expp;
}

void
SurfaceCollection::simplify(double tolerance)
{
    Surfaces ss;
    for (Surfaces::const_iterator it_s = this->surfaces.begin(); it_s != this->surfaces.end(); ++it_s) {
        ExPolygons expp;
        it_s->expolygon.simplify(tolerance, &expp);
        for (ExPolygons::const_iterator it_e = expp.begin(); it_e != expp.end(); ++it_e) {
            Surface s = *it_s;
            s.expolygon = *it_e;
            ss.push_back(s);
        }
    }
    this->surfaces = ss;
}

/* group surfaces by common properties */
void
SurfaceCollection::group(std::vector<SurfacesConstPtr> *retval) const
{
    for (Surfaces::const_iterator it = this->surfaces.begin(); it != this->surfaces.end(); ++it) {
        // find a group with the same properties
        SurfacesConstPtr* group = NULL;
        for (std::vector<SurfacesConstPtr>::iterator git = retval->begin(); git != retval->end(); ++git) {
            const Surface* gkey = git->front();
            if (   gkey->surface_type      == it->surface_type
                && gkey->thickness         == it->thickness
                && gkey->thickness_layers  == it->thickness_layers
                && gkey->bridge_angle      == it->bridge_angle) {
                group = &*git;
                break;
            }
        }

        // if no group with these properties exists, add one
        if (group == NULL) {
            retval->resize(retval->size() + 1);
            group = &retval->back();
        }

        // append surface to group
        group->push_back(&*it);
    }
}

template <class T>
bool
SurfaceCollection::any_internal_contains(const T &item) const
{
    for (Surfaces::const_iterator surface = this->surfaces.begin(); surface != this->surfaces.end(); ++surface) {
        if (surface->is_internal() && surface->expolygon.contains(item)) return true;
    }
    return false;
}
template bool SurfaceCollection::any_internal_contains<Polyline>(const Polyline &item) const;

template <class T>
bool
SurfaceCollection::any_bottom_contains(const T &item) const
{
    for (Surfaces::const_iterator surface = this->surfaces.begin(); surface != this->surfaces.end(); ++surface) {
        if (surface->is_bottom() && surface->expolygon.contains(item)) return true;
    }
    return false;
}
template bool SurfaceCollection::any_bottom_contains<Polyline>(const Polyline &item) const;

SurfacesPtr
SurfaceCollection::filter_by_type(SurfaceType type)
{
    SurfacesPtr ss;
    for (Surfaces::iterator surface = this->surfaces.begin(); surface != this->surfaces.end(); ++surface) {
        if (surface->surface_type == type) ss.push_back(&*surface);
    }
    return ss;
}

SurfacesPtr
SurfaceCollection::filter_by_type(std::initializer_list<SurfaceType> types)
{
    size_t n {0};
    SurfacesPtr ss;
    for (const auto& t : types) {
        n |= t;
    }
    for (Surfaces::iterator surface = this->surfaces.begin(); surface != this->surfaces.end(); ++surface) {
        if ((surface->surface_type & n) == surface->surface_type) ss.push_back(&*surface);
    }
    return ss;
}
void
SurfaceCollection::filter_by_type(SurfaceType type, Polygons* polygons)
{
    for (Surfaces::iterator surface = this->surfaces.begin(); surface != this->surfaces.end(); ++surface) {
        if (surface->surface_type == type)
            append_to(*polygons, (Polygons)surface->expolygon);
    }
}

void
SurfaceCollection::append(const SurfaceCollection &coll)
{
    this->append(coll.surfaces);
}

void
SurfaceCollection::append(const Surfaces &surfaces)
{
    append_to(this->surfaces, surfaces);
}

void
SurfaceCollection::append(const ExPolygons &src, const Surface &templ)
{
    this->surfaces.reserve(this->surfaces.size() + src.size());
    for (ExPolygons::const_iterator it = src.begin(); it != src.end(); ++ it) {
        this->surfaces.push_back(templ);
        this->surfaces.back().expolygon = *it;
    }
}

void
SurfaceCollection::append(const ExPolygons &src, SurfaceType surfaceType)
{
    this->surfaces.reserve(this->surfaces.size() + src.size());
    for (ExPolygons::const_iterator it = src.begin(); it != src.end(); ++ it)
        this->surfaces.push_back(Surface(surfaceType, *it));
}

size_t
SurfaceCollection::polygons_count() const
{
    size_t count = 0;
    for (Surfaces::const_iterator it = this->surfaces.begin(); it != this->surfaces.end(); ++ it)
        count += 1 + it->expolygon.holes.size();
    return count;
}
void
SurfaceCollection::remove_type(const SurfaceType type)
{
    // Use stl remove_if to remove
    auto ptr = std::remove_if(surfaces.begin(), surfaces.end(),[type] (Surface& s) { return s.surface_type == type; });
    surfaces.erase(ptr, surfaces.cend());
}

void
SurfaceCollection::remove_types(const SurfaceType *types, size_t ntypes)
{
    for (size_t i = 0; i < ntypes; ++i)
        this->remove_type(types[i]);
}

void
SurfaceCollection::remove_types(std::initializer_list<SurfaceType> types) {
    for (const auto& t : types) {
        this->remove_type(t);
    }
}

void
SurfaceCollection::keep_type(const SurfaceType type)
{
    // Use stl remove_if to remove
    auto ptr = std::remove_if(surfaces.begin(), surfaces.end(),[type] (const Surface& s) { return s.surface_type != type; });
    surfaces.erase(ptr, surfaces.cend());
}

void
SurfaceCollection::keep_types(const SurfaceType *types, size_t ntypes)
{
    size_t n {0};
    for (size_t i = 0; i < ntypes; ++i)
        n |= types[i]; // form bitmask.
    // Use stl remove_if to remove
    auto ptr = std::remove_if(surfaces.begin(), surfaces.end(),[n] (const Surface& s) { return (s.surface_type & n) != s.surface_type; });
    surfaces.erase(ptr, surfaces.cend());
}

void
SurfaceCollection::keep_types(std::initializer_list<SurfaceType> types) {
    for (const auto& t : types) {
        this->keep_type(t);
    }
}
/* group surfaces by common properties */
void
SurfaceCollection::group(std::vector<SurfacesPtr> *retval)
{
    for (Surfaces::iterator it = this->surfaces.begin(); it != this->surfaces.end(); ++it) {
        // find a group with the same properties
        SurfacesPtr* group = NULL;
        for (std::vector<SurfacesPtr>::iterator git = retval->begin(); git != retval->end(); ++git)
            if (! git->empty() && surfaces_could_merge(*git->front(), *it)) {
                group = &*git;
                break;
            }
        // if no group with these properties exists, add one
        if (group == NULL) {
            retval->resize(retval->size() + 1);
            group = &retval->back();
        }
        // append surface to group
        group->push_back(&*it);
    }
}

} // namespace Slic3r
<|endoftext|>


<commit_before>#include "gtest/gtest.h"
#include "maze.h"

TEST (Direction, ClearDirectionData_AllNorth)
{
  location_t loc = {5, 6};
  SetDirection (loc, SOUTH);
  MazeClearDirectionData();
  for (loc.row = 0; loc.row < MAZE_ROWS; loc.row++) {
    for (loc.col = 0; loc.col < MAZE_COLS; loc.col++) {
      EXPECT_EQ (NORTH, MazeGetDirection (loc));
    }
  }
}

TEST (Direction, MazeGetDirection_defaultValue_getNORTH)
{
  location_t loc = Home();
  EXPECT_EQ (NORTH, MazeGetDirection (loc));
}

TEST (Direction, MazeSetDirection_ReturnSetValue)
{
  location_t loc = {3, 4};
  direction_t dir = EAST;
  EXPECT_EQ (NORTH, MazeGetDirection (loc));
  SetDirection (loc, dir);
  EXPECT_EQ (dir, MazeGetDirection (loc));
}

TEST (Direction, DirectionGetLeftFrom)
{
  EXPECT_EQ (WEST, LeftFrom (NORTH));
  EXPECT_EQ (SOUTH, LeftFrom (WEST));
  EXPECT_EQ (EAST, LeftFrom (SOUTH));
  EXPECT_EQ (NORTH, LeftFrom (EAST));
}

TEST (Direction, DirectionGetRightFrom)
{
  EXPECT_EQ (EAST, RightFrom (NORTH));
  EXPECT_EQ (SOUTH, RightFrom (EAST));
  EXPECT_EQ (WEST, RightFrom (SOUTH));
  EXPECT_EQ (NORTH, RightFrom (WEST));
}

TEST (Direction, Behind)
{
  EXPECT_EQ (SOUTH, Behind (NORTH));
  EXPECT_EQ (WEST, Behind (EAST));
  EXPECT_EQ (NORTH, Behind (SOUTH));
  EXPECT_EQ (EAST, Behind (WEST));
}

<commit_msg>updated  direction tests to cope with INVALID directions<commit_after>#include "gtest/gtest.h"
#include "maze.h"

TEST (Direction, ClearDirectionData_AllNorth)
{
  location_t loc = {5, 6};
  SetDirection (loc, SOUTH);
  MazeClearDirectionData();
  for (loc.row = 0; loc.row < MAZE_ROWS; loc.row++) {
    for (loc.col = 0; loc.col < MAZE_COLS; loc.col++) {
      EXPECT_EQ (INVALID, MazeGetDirection (loc));
    }
  }
}

TEST (Direction, MazeGetDirection_defaultValue_getNORTH)
{
  location_t loc = Home();
  EXPECT_EQ (INVALID, MazeGetDirection (loc));
}

TEST (Direction, MazeSetDirection_ReturnSetValue)
{
  location_t loc = {3, 4};
  direction_t dir = EAST;
  EXPECT_EQ (INVALID, MazeGetDirection (loc));
  SetDirection (loc, dir);
  EXPECT_EQ (dir, MazeGetDirection (loc));
}

TEST (Direction, DirectionGetLeftFrom)
{
  EXPECT_EQ (WEST, LeftFrom (NORTH));
  EXPECT_EQ (SOUTH, LeftFrom (WEST));
  EXPECT_EQ (EAST, LeftFrom (SOUTH));
  EXPECT_EQ (NORTH, LeftFrom (EAST));
}

TEST (Direction, DirectionGetRightFrom)
{
  EXPECT_EQ (EAST, RightFrom (NORTH));
  EXPECT_EQ (SOUTH, RightFrom (EAST));
  EXPECT_EQ (WEST, RightFrom (SOUTH));
  EXPECT_EQ (NORTH, RightFrom (WEST));
}

TEST (Direction, Behind)
{
  EXPECT_EQ (SOUTH, Behind (NORTH));
  EXPECT_EQ (WEST, Behind (EAST));
  EXPECT_EQ (NORTH, Behind (SOUTH));
  EXPECT_EQ (EAST, Behind (WEST));
}

<|endoftext|>


<commit_before>//This is a testing version of the BDT training code
//Author: Zhaoyuan "Maxwell" Cui
//Physics department, Unversity of Arizona

#include "iostream"
#include "fstream"

#include "TFile.h"
#include "TTree.h"
#include "TString.h"
#include "TSystem.h"
#include "TROOT.h"

#include "TMVA/Factory.h"
#include "TMVA/Tools.h"
#include "TMVA/TMVAGui.h"

int bdt_vlq()
{
  //Load the library
  TMVA::Tools::Instance();

  std::cout<<std::endl;
  std::cout<<"==>Start BDT"<<std::endl;

  TString outputFileName("BDT_VLQ_data.root");
  TFile *outputFile=TFile::Open(outputFileName, "RECREATE");

  //Register TMVA Factory
  TMVA::Factory *factory=new TMVA::Factory("BDT_VLQ", outputFile,
					   "V:!Silent:Color:DrawProgressBar:AnalysisType=Classification");

  //Read training data
  //
  TString fSig="../normalization/BBS_sig.root";
  TString fBkg_VV="../normalization/VV.root";
  TString fBkg_VVV="../normalization/VVV.root";
  TString fBkg_ttW_np2="../normalization/ttW_np2_bkg.root";
  TString fBkg_ttW_np1="../normalization/ttW_np1_bkg.root";
  TString fBkg_ttW_np0="../normalization/ttW_np0_bkg.root";
  TString fBkg_ttH="../normalization/ttH.root";

  std::ifstream inputFile("datafiles.txt");
  std::string fileName;

  while(std::getline(inputFile,fileName))
    {
      TFile *inputBg=TFile::Open(fileName);
    }

  //---
  // TFile *inputSig=TFile::Open(fSig);
  // TFile *inputVV=TFile::Open(fBkg_VV);
  // TFile *inputVVV=TFile::Open(fBkg_VVV);
  // TFile *inputNP2=TFile::Open(fBkg_ttW_np2);
  // TFile *inputNP1=TFile::Open(fBkg_ttW_np1);
  // TFile *inputNP0=TFile::Open(fBkg_ttW_np0);
  // TFile *inputttH=TFile::Open(fBkg_ttH);

  TTree *signal=(TTree*)inputSig->Get("nominal_Loose");
  TTree *vv=(TTree*)inputVV->Get("nominal_Loose");
  TTree *vvv=(TTree*)inputVVV->Get("nominal_Loose");
  TTree *ttW_np2=(TTree*)inputNP2->Get("nominal_Loose");
  TTree *ttW_np1=(TTree*)inputNP1->Get("nominal_Loose");
  TTree *ttW_np0=(TTree*)inputNP0->Get("nominal_Loose");
  TTree *ttH=(TTree*)inputttH->Get("nominal_Loose");

  std::cout<<"File operation done"<<std::endl;

  //Add variables that will be used for MVA training
  factory->AddVariable("mu",'F');
  factory->AddVariable("el_pt.[0]",'F');
  factory->AddVariable("mu_pt.[0]",'F');
  factory->AddVariable("jet_pt.[0]",'F');
  factory->AddVariable("met_met",'F');
  factory->AddVariable("met_phi",'F');
  factory->AddVariable("SSee_2016",'I');
  factory->AddVariable("SSem_2016",'I');
  factory->AddVariable("SSmm_2016",'I');
  factory->AddVariable("eee_2016",'I');
  factory->AddVariable("eem_2016",'I');
  factory->AddVariable("emm_2016",'I');
  factory->AddVariable("mmm_2016",'I');
  factory->AddVariable("lep_pt.[0]",'I');
  factory->AddVariable("ht",'F');
  factory->AddVariable("met_sumet",'F');
  factory->AddVariable("bj",'I');

  std::cout<<" --- BDT_VLQ\tUsing input file: "
	   <<"\n\t"
	   <<inputSig->GetName()<<"\n\t"
	   <<inputVV->GetName()<<"\n\t"
	   <<inputVVV->GetName()<<"\n\t"
	   <<inputNP2->GetName()<<"\n\t"
	   <<inputNP1->GetName()<<"\n\t"
	   <<inputNP0->GetName()<<"\n\t"
	   <<inputttH->GetName()<<std::endl;

  //Global event weights per tree
  Double_t signalWeight=1.0;
  Double_t vvWeight=1.0;
  Double_t vvvWeight=1.0;
  Double_t ttW_np2Weight=1.0;
  Double_t ttW_np1Weight=1.0;
  Double_t ttW_np0Weight=1.0;
  Double_t ttHWeight=1.0;

  // factory->AddSignalTree(signal,signalWeight);
  // factory->AddBackgroundTree(vv,vvWeight);
  // factory->AddBackgroundTree(vvv,vvvWeight);
  // factory->AddBackgroundTree(ttW_np2,ttW_np2Weight);
  // factory->AddBackgroundTree(ttW_np1,ttW_np2Weight);
  // factory->AddBackgroundTree(ttW_np0,ttW_np2Weight);
  // factory->AddBackgroundTree(ttH,ttHWeight);

  // factory->SetWeightExpression("evtWeight");

  //Apply additional cuts on the signal and background samples
  TCut mycut="";
  factory->PrepareTrainingAndTestTree(mycut,"SplitMode=random:!V:NormMode=None");

  // --- Book MVA method
  //
  //Boosted Decision Tree

  //TString Option="!H:!V:NTrees=400:MaxDepth=10:MinNodeSize=5%:nCuts=20:NegWeightTreatment=IgnoreNegWeightsInTraining:SeparationType=GiniIndex:BoostType=AdaBoost:VarTransform=Decorrelate";

  //TString Option="!H:!V:BoostType=AdaBoost:AdaBoostBeta=0.5:UseBaggedBoost:BaggedSampleFraction=0.5:SeparationType=GiniIndex";

  TString Option="!H:!V:NTrees=400:MinNodeSize=5%:MaxDepth=3:BoostType=AdaBoost:SeparationType=GiniIndex:nCuts=20:VarTransform=Decorrelate";

  factory->BookMethod( TMVA::Types::kBDT, "BDT",
		       Option);

  factory->TrainAllMethods();
  factory->TestAllMethods();
  factory->EvaluateAllMethods();

  outputFile->Close();

  std::cout << "==> Wrote root file: " << outputFile->GetName() << std::endl;
  std::cout << "==> TMVAClassification is done!" << std::endl;

  delete factory;

  //Launch the GUI for the root macros
  if (!gROOT->IsBatch())
    TMVA::TMVAGui(outputFileName);

  return 0;
}

int main()
{
  return bdt_vlq();
}
<commit_msg>update input method<commit_after>//This is a testing version of the BDT training code
//Author: Zhaoyuan "Maxwell" Cui
//Physics department, Unversity of Arizona

#include "iostream"
#include "fstream"

#include "TFile.h"
#include "TTree.h"
#include "TString.h"
#include "TSystem.h"
#include "TROOT.h"

#include "TMVA/Factory.h"
#include "TMVA/Tools.h"
#include "TMVA/TMVAGui.h"

int bdt_vlq()
{
  //Load the library
  TMVA::Tools::Instance();

  std::cout<<std::endl;
  std::cout<<"==>Start BDT"<<std::endl;

  TString outputFileName("BDT_VLQ_data.root");
  TFile *outputFile=TFile::Open(outputFileName, "RECREATE");

  //Register TMVA Factory
  TMVA::Factory *factory=new TMVA::Factory("BDT_VLQ", outputFile,
					   "V:!Silent:Color:DrawProgressBar:AnalysisType=Classification");

  //Read training data
  //
  TString fSig;
  TString fBkg;
  TString prefix="normalized_";

  std::ifstream inputFile("datafiles.txt");
  std::string fileName;

  TFile *inputBg=new TFile[10];
  TTree *bgTree=new TTree[10];

  Int_t counter=0;

  while(std::getline(inputFile,fileName))
    {
      fileName=prefix+fileName;
      inputBg[counter]=new TFile::Open(fileName);
      bgTree[counter]=(TTree*)inputBg[counter]->Get("nominal_Loose");
      counter++;
    }

  //---
  // TFile *inputSig=TFile::Open(fSig);
  // TFile *inputVV=TFile::Open(fBkg_VV);
  // TFile *inputVVV=TFile::Open(fBkg_VVV);
  // TFile *inputNP2=TFile::Open(fBkg_ttW_np2);
  // TFile *inputNP1=TFile::Open(fBkg_ttW_np1);
  // TFile *inputNP0=TFile::Open(fBkg_ttW_np0);
  // TFile *inputttH=TFile::Open(fBkg_ttH);

  // TTree *signal=(TTree*)inputSig->Get("nominal_Loose");
  // TTree *vv=(TTree*)inputVV->Get("nominal_Loose");
  // TTree *vvv=(TTree*)inputVVV->Get("nominal_Loose");
  // TTree *ttW_np2=(TTree*)inputNP2->Get("nominal_Loose");
  // TTree *ttW_np1=(TTree*)inputNP1->Get("nominal_Loose");
  // TTree *ttW_np0=(TTree*)inputNP0->Get("nominal_Loose");
  // TTree *ttH=(TTree*)inputttH->Get("nominal_Loose");

  std::cout<<"File operation done"<<std::endl;

  //Add variables that will be used for MVA training
  factory->AddVariable("mu",'F');
  factory->AddVariable("el_pt.[0]",'F');
  factory->AddVariable("mu_pt.[0]",'F');
  factory->AddVariable("jet_pt.[0]",'F');
  factory->AddVariable("met_met",'F');
  factory->AddVariable("met_phi",'F');
  factory->AddVariable("SSee_2016",'I');
  factory->AddVariable("SSem_2016",'I');
  factory->AddVariable("SSmm_2016",'I');
  factory->AddVariable("eee_2016",'I');
  factory->AddVariable("eem_2016",'I');
  factory->AddVariable("emm_2016",'I');
  factory->AddVariable("mmm_2016",'I');
  factory->AddVariable("lep_pt.[0]",'I');
  factory->AddVariable("ht",'F');
  factory->AddVariable("met_sumet",'F');
  factory->AddVariable("bjet",'I');

  for(Int_t n=0;n<10;n++)
    {
      std::cout<<" --- BDT_VLQ\tUsing input file: "
	       <<"\n\t"
	       <<inputBg[n]->GetName()<<"\n\t"
	       <<std::endl;
    }

  //Global event weights per tree
  // Double_t signalWeight=1.0;
  // Double_t vvWeight=1.0;
  // Double_t vvvWeight=1.0;
  // Double_t ttW_np2Weight=1.0;
  // Double_t ttW_np1Weight=1.0;
  // Double_t ttW_np0Weight=1.0;
  // Double_t ttHWeight=1.0;

  // factory->AddSignalTree(signal,signalWeight);
  // factory->AddBackgroundTree(vv,vvWeight);
  // factory->AddBackgroundTree(vvv,vvvWeight);
  // factory->AddBackgroundTree(ttW_np2,ttW_np2Weight);
  // factory->AddBackgroundTree(ttW_np1,ttW_np2Weight);
  // factory->AddBackgroundTree(ttW_np0,ttW_np2Weight);
  // factory->AddBackgroundTree(ttH,ttHWeight);

  factory->SetWeightExpression("evtWeight");

  //Apply additional cuts on the signal and background samples
  TCut mycut="";
  factory->PrepareTrainingAndTestTree(mycut,"SplitMode=random:!V:NormMode=None");

  // --- Book MVA method
  //
  //Boosted Decision Tree

  //TString Option="!H:!V:NTrees=400:MaxDepth=10:MinNodeSize=5%:nCuts=20:NegWeightTreatment=IgnoreNegWeightsInTraining:SeparationType=GiniIndex:BoostType=AdaBoost:VarTransform=Decorrelate";

  //TString Option="!H:!V:BoostType=AdaBoost:AdaBoostBeta=0.5:UseBaggedBoost:BaggedSampleFraction=0.5:SeparationType=GiniIndex";

  TString Option="!H:!V:NTrees=400:MinNodeSize=5%:MaxDepth=3:BoostType=AdaBoost:SeparationType=GiniIndex:nCuts=20:VarTransform=Decorrelate";

  factory->BookMethod( TMVA::Types::kBDT, "BDT",
		       Option);

  factory->TrainAllMethods();
  factory->TestAllMethods();
  factory->EvaluateAllMethods();

  outputFile->Close();

  std::cout << "==> Wrote root file: " << outputFile->GetName() << std::endl;
  std::cout << "==> TMVAClassification is done!" << std::endl;

  delete factory;

  //Launch the GUI for the root macros
  if (!gROOT->IsBatch())
    TMVA::TMVAGui(outputFileName);

  return 0;
}

int main()
{
  return bdt_vlq();
}
<|endoftext|>


<commit_before>#include <boost/test/unit_test.hpp>

//#include "clotho/powerset/powerset.hpp"
#include "clotho/powerset/variable_subset.hpp"

struct test_element {
    double k, v;

    test_element( double _k = 0., double _v = 0.) : k (_k), v(_v) {}
    test_element( const test_element & t ) : k(t.k), v(t.v) {}

    friend bool operator==( const test_element & lhs, const test_element & rhs );
    friend bool operator!=( const test_element & lhs, const test_element & rhs );
};

inline bool operator==( const test_element & lhs, const test_element & rhs ) {
    return ( lhs.k == rhs.k && lhs.v == rhs.v);
}

inline bool operator!=( const test_element & lhs, const test_element & rhs ) {
    return ( lhs.k != rhs.k && lhs.v != rhs.v);
}

namespace clotho {
namespace powersets {

template <>
struct element_key_of< test_element > {
    typedef double key_type;

    inline key_type operator()( const test_element & t ) { return t.k; }
};

template< class Block >
struct block_map< test_element, Block > {
    typedef test_element    element_type;
    typedef Block           size_type;

    static const unsigned int bits_per_block = sizeof(size_type) * 8;

    inline size_type operator()( const element_type & elem ) {
        assert( 0. < elem.k && elem.k < 1. );

        return elem.k * bits_per_block;
    }
};

}   // namespace powersets
}   // namespace clotho

typedef clotho::powersets::variable_subset< test_element > subset_type;
typedef typename subset_type::powerset_type powerset_type;

BOOST_AUTO_TEST_SUITE( test_powerset )

BOOST_AUTO_TEST_CASE( create_powerset ) {

    powerset_type ps;

    typename powerset_type::block_map_type bmap;

    double k = 0.5;
    test_element te( k, 2.0 );

    typename powerset_type::element_index_type idx = ps.find_or_create(te);

    BOOST_REQUIRE_MESSAGE( idx == bmap(te), "Unexpected index returned" );
}

BOOST_AUTO_TEST_SUITE_END()
<commit_msg>added basic unit tests<commit_after>#include <boost/test/unit_test.hpp>

//#include "clotho/powerset/powerset.hpp"
#include "clotho/powerset/variable_subset.hpp"

struct test_element {
    double k, v;

    test_element( double _k = 0., double _v = 0.) : k (_k), v(_v) {}
    test_element( const test_element & t ) : k(t.k), v(t.v) {}

    friend bool operator==( const test_element & lhs, const test_element & rhs );
    friend bool operator!=( const test_element & lhs, const test_element & rhs );
};

inline bool operator==( const test_element & lhs, const test_element & rhs ) {
    return ( lhs.k == rhs.k && lhs.v == rhs.v);
}

inline bool operator!=( const test_element & lhs, const test_element & rhs ) {
    return ( lhs.k != rhs.k && lhs.v != rhs.v);
}

namespace clotho {
namespace powersets {

template <>
struct element_key_of< test_element > {
    typedef double key_type;

    inline key_type operator()( const test_element & t ) { return t.k; }
};

template< class Block >
struct block_map< test_element, Block > {
    typedef test_element    element_type;
    typedef Block           size_type;

    static const unsigned int bits_per_block = sizeof(size_type) * 8;

    inline size_type operator()( const element_type & elem ) {
        assert( 0. <= elem.k && elem.k < 1. );

        return elem.k * bits_per_block;
    }
};

}   // namespace powersets
}   // namespace clotho

typedef clotho::powersets::variable_subset< test_element > subset_type;
typedef typename subset_type::powerset_type powerset_type;
typedef powerset_type::block_map_type bmap;

BOOST_AUTO_TEST_SUITE( test_powerset )

BOOST_AUTO_TEST_CASE( create_powerset_simple) {

    powerset_type ps;

    double k = 0.75;
    test_element te( k, 2.0 );

    typename powerset_type::element_index_type idx = ps.find_or_create(te);
    BOOST_REQUIRE_MESSAGE( idx == bmap()(te), "Unexpected index returned" );
    BOOST_REQUIRE_MESSAGE( ps.size() == 1, "Unexpected size" );
    BOOST_REQUIRE_MESSAGE( ps.variable_allocated_size() == bmap::bits_per_block, "Unexpected variable space: " << ps.variable_allocated_size() );

}

BOOST_AUTO_TEST_CASE( create_powerset_width ) {
    powerset_type ps;

    BOOST_REQUIRE_MESSAGE( ps.empty(), "Unexpected size" );
    for( unsigned int i = 0; i < bmap::bits_per_block; ++i ) {
        double v = (double) i;
        double k = v / (double) bmap::bits_per_block;
        test_element te(k, 1.0);

        typename powerset_type::element_index_type idx = ps.find_or_create(te);

        BOOST_REQUIRE_MESSAGE( idx == i, "Unexpected index " << idx << " returned for " << i << "(" << k << ")" );
    }

    BOOST_REQUIRE_MESSAGE( ps.size() == bmap::bits_per_block, "Unexpected size" );
}

BOOST_AUTO_TEST_SUITE_END()
<|endoftext|>


<commit_before>//===- unittests/ADT/IListIteratorTest.cpp - ilist_iterator unit tests ----===//
//
//                     The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//

#include "llvm/ADT/simple_ilist.h"
#include "gtest/gtest.h"

using namespace llvm;

namespace {

struct Node : ilist_node<Node> {};

TEST(IListIteratorTest, DefaultConstructor) {
  simple_ilist<Node>::iterator I;
  simple_ilist<Node>::reverse_iterator RI;
  simple_ilist<Node>::const_iterator CI;
  simple_ilist<Node>::const_reverse_iterator CRI;
  EXPECT_EQ(nullptr, I.getNodePtr());
  EXPECT_EQ(nullptr, CI.getNodePtr());
  EXPECT_EQ(nullptr, RI.getNodePtr());
  EXPECT_EQ(nullptr, CRI.getNodePtr());
  EXPECT_EQ(I, I);
  EXPECT_EQ(I, CI);
  EXPECT_EQ(CI, I);
  EXPECT_EQ(CI, CI);
  EXPECT_EQ(RI, RI);
  EXPECT_EQ(RI, CRI);
  EXPECT_EQ(CRI, RI);
  EXPECT_EQ(CRI, CRI);
  EXPECT_EQ(I, RI.getReverse());
  EXPECT_EQ(RI, I.getReverse());
}

TEST(IListIteratorTest, Empty) {
  simple_ilist<Node> L;

  // Check iterators of L.
  EXPECT_EQ(L.begin(), L.end());
  EXPECT_EQ(L.rbegin(), L.rend());

  // Reverse of end should be rend (since the sentinel sits on both sides).
  EXPECT_EQ(L.end(), L.rend().getReverse());
  EXPECT_EQ(L.rend(), L.end().getReverse());

  // Iterators shouldn't match default constructors.
  simple_ilist<Node>::iterator I;
  simple_ilist<Node>::reverse_iterator RI;
  EXPECT_NE(I, L.begin());
  EXPECT_NE(I, L.end());
  EXPECT_NE(RI, L.rbegin());
  EXPECT_NE(RI, L.rend());
}

TEST(IListIteratorTest, OneNodeList) {
  simple_ilist<Node> L;
  Node A;
  L.insert(L.end(), A);

  // Check address of reference.
  EXPECT_EQ(&A, &*L.begin());
  EXPECT_EQ(&A, &*L.rbegin());

  // Check that the handle matches.
  EXPECT_EQ(L.rbegin().getNodePtr(), L.begin().getNodePtr());

  // Check iteration.
  EXPECT_EQ(L.end(), ++L.begin());
  EXPECT_EQ(L.begin(), --L.end());
  EXPECT_EQ(L.rend(), ++L.rbegin());
  EXPECT_EQ(L.rbegin(), --L.rend());

  // Check conversions.
  EXPECT_EQ(L.rbegin(), L.begin().getReverse());
  EXPECT_EQ(L.begin(), L.rbegin().getReverse());
}

TEST(IListIteratorTest, TwoNodeList) {
  simple_ilist<Node> L;
  Node A, B;
  L.insert(L.end(), A);
  L.insert(L.end(), B);

  // Check order.
  EXPECT_EQ(&A, &*L.begin());
  EXPECT_EQ(&B, &*++L.begin());
  EXPECT_EQ(L.end(), ++++L.begin());
  EXPECT_EQ(&B, &*L.rbegin());
  EXPECT_EQ(&A, &*++L.rbegin());
  EXPECT_EQ(L.rend(), ++++L.rbegin());

  // Check conversions.
  EXPECT_EQ(++L.rbegin(), L.begin().getReverse());
  EXPECT_EQ(L.rbegin(), (++L.begin()).getReverse());
  EXPECT_EQ(++L.begin(), L.rbegin().getReverse());
  EXPECT_EQ(L.begin(), (++L.rbegin()).getReverse());
}

TEST(IListIteratorTest, CheckEraseForward) {
  simple_ilist<Node> L;
  Node A, B;
  L.insert(L.end(), A);
  L.insert(L.end(), B);

  // Erase nodes.
  auto I = L.begin();
  EXPECT_EQ(&A, &*I);
  L.remove(*I++);
  EXPECT_EQ(&B, &*I);
  L.remove(*I++);
  EXPECT_EQ(L.end(), I);
}

TEST(IListIteratorTest, CheckEraseReverse) {
  simple_ilist<Node> L;
  Node A, B;
  L.insert(L.end(), A);
  L.insert(L.end(), B);

  // Erase nodes.
  auto RI = L.rbegin();
  EXPECT_EQ(&B, &*RI);
  L.remove(*RI++);
  EXPECT_EQ(&A, &*RI);
  L.remove(*RI++);
  EXPECT_EQ(L.rend(), RI);
}

TEST(IListIteratorTest, ReverseConstructor) {
  simple_ilist<Node> L;
  const simple_ilist<Node> &CL = L;
  Node A, B;
  L.insert(L.end(), A);
  L.insert(L.end(), B);

  // Save typing.
  typedef simple_ilist<Node>::iterator iterator;
  typedef simple_ilist<Node>::reverse_iterator reverse_iterator;
  typedef simple_ilist<Node>::const_iterator const_iterator;
  typedef simple_ilist<Node>::const_reverse_iterator const_reverse_iterator;

  // Check conversion values.
  EXPECT_EQ(L.begin(), iterator(L.rend()));
  EXPECT_EQ(++L.begin(), iterator(++L.rbegin()));
  EXPECT_EQ(L.end(), iterator(L.rbegin()));
  EXPECT_EQ(L.rbegin(), reverse_iterator(L.end()));
  EXPECT_EQ(++L.rbegin(), reverse_iterator(++L.begin()));
  EXPECT_EQ(L.rend(), reverse_iterator(L.begin()));

  // Check const iterator constructors.
  EXPECT_EQ(CL.begin(), const_iterator(L.rend()));
  EXPECT_EQ(CL.begin(), const_iterator(CL.rend()));
  EXPECT_EQ(CL.rbegin(), const_reverse_iterator(L.end()));
  EXPECT_EQ(CL.rbegin(), const_reverse_iterator(CL.end()));

  // Confirm lack of implicit conversions.
  static_assert(std::is_convertible<iterator, reverse_iterator>::value,
                "unexpected implicit conversion");
  static_assert(std::is_convertible<reverse_iterator, iterator>::value,
                "unexpected implicit conversion");
  static_assert(
      std::is_convertible<const_iterator, const_reverse_iterator>::value,
      "unexpected implicit conversion");
  static_assert(
      std::is_convertible<const_reverse_iterator, const_iterator>::value,
      "unexpected implicit conversion");
}

} // end namespace
<commit_msg>Fix some missing negations in the traits checking from r294349<commit_after>//===- unittests/ADT/IListIteratorTest.cpp - ilist_iterator unit tests ----===//
//
//                     The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//

#include "llvm/ADT/simple_ilist.h"
#include "gtest/gtest.h"

using namespace llvm;

namespace {

struct Node : ilist_node<Node> {};

TEST(IListIteratorTest, DefaultConstructor) {
  simple_ilist<Node>::iterator I;
  simple_ilist<Node>::reverse_iterator RI;
  simple_ilist<Node>::const_iterator CI;
  simple_ilist<Node>::const_reverse_iterator CRI;
  EXPECT_EQ(nullptr, I.getNodePtr());
  EXPECT_EQ(nullptr, CI.getNodePtr());
  EXPECT_EQ(nullptr, RI.getNodePtr());
  EXPECT_EQ(nullptr, CRI.getNodePtr());
  EXPECT_EQ(I, I);
  EXPECT_EQ(I, CI);
  EXPECT_EQ(CI, I);
  EXPECT_EQ(CI, CI);
  EXPECT_EQ(RI, RI);
  EXPECT_EQ(RI, CRI);
  EXPECT_EQ(CRI, RI);
  EXPECT_EQ(CRI, CRI);
  EXPECT_EQ(I, RI.getReverse());
  EXPECT_EQ(RI, I.getReverse());
}

TEST(IListIteratorTest, Empty) {
  simple_ilist<Node> L;

  // Check iterators of L.
  EXPECT_EQ(L.begin(), L.end());
  EXPECT_EQ(L.rbegin(), L.rend());

  // Reverse of end should be rend (since the sentinel sits on both sides).
  EXPECT_EQ(L.end(), L.rend().getReverse());
  EXPECT_EQ(L.rend(), L.end().getReverse());

  // Iterators shouldn't match default constructors.
  simple_ilist<Node>::iterator I;
  simple_ilist<Node>::reverse_iterator RI;
  EXPECT_NE(I, L.begin());
  EXPECT_NE(I, L.end());
  EXPECT_NE(RI, L.rbegin());
  EXPECT_NE(RI, L.rend());
}

TEST(IListIteratorTest, OneNodeList) {
  simple_ilist<Node> L;
  Node A;
  L.insert(L.end(), A);

  // Check address of reference.
  EXPECT_EQ(&A, &*L.begin());
  EXPECT_EQ(&A, &*L.rbegin());

  // Check that the handle matches.
  EXPECT_EQ(L.rbegin().getNodePtr(), L.begin().getNodePtr());

  // Check iteration.
  EXPECT_EQ(L.end(), ++L.begin());
  EXPECT_EQ(L.begin(), --L.end());
  EXPECT_EQ(L.rend(), ++L.rbegin());
  EXPECT_EQ(L.rbegin(), --L.rend());

  // Check conversions.
  EXPECT_EQ(L.rbegin(), L.begin().getReverse());
  EXPECT_EQ(L.begin(), L.rbegin().getReverse());
}

TEST(IListIteratorTest, TwoNodeList) {
  simple_ilist<Node> L;
  Node A, B;
  L.insert(L.end(), A);
  L.insert(L.end(), B);

  // Check order.
  EXPECT_EQ(&A, &*L.begin());
  EXPECT_EQ(&B, &*++L.begin());
  EXPECT_EQ(L.end(), ++++L.begin());
  EXPECT_EQ(&B, &*L.rbegin());
  EXPECT_EQ(&A, &*++L.rbegin());
  EXPECT_EQ(L.rend(), ++++L.rbegin());

  // Check conversions.
  EXPECT_EQ(++L.rbegin(), L.begin().getReverse());
  EXPECT_EQ(L.rbegin(), (++L.begin()).getReverse());
  EXPECT_EQ(++L.begin(), L.rbegin().getReverse());
  EXPECT_EQ(L.begin(), (++L.rbegin()).getReverse());
}

TEST(IListIteratorTest, CheckEraseForward) {
  simple_ilist<Node> L;
  Node A, B;
  L.insert(L.end(), A);
  L.insert(L.end(), B);

  // Erase nodes.
  auto I = L.begin();
  EXPECT_EQ(&A, &*I);
  L.remove(*I++);
  EXPECT_EQ(&B, &*I);
  L.remove(*I++);
  EXPECT_EQ(L.end(), I);
}

TEST(IListIteratorTest, CheckEraseReverse) {
  simple_ilist<Node> L;
  Node A, B;
  L.insert(L.end(), A);
  L.insert(L.end(), B);

  // Erase nodes.
  auto RI = L.rbegin();
  EXPECT_EQ(&B, &*RI);
  L.remove(*RI++);
  EXPECT_EQ(&A, &*RI);
  L.remove(*RI++);
  EXPECT_EQ(L.rend(), RI);
}

TEST(IListIteratorTest, ReverseConstructor) {
  simple_ilist<Node> L;
  const simple_ilist<Node> &CL = L;
  Node A, B;
  L.insert(L.end(), A);
  L.insert(L.end(), B);

  // Save typing.
  typedef simple_ilist<Node>::iterator iterator;
  typedef simple_ilist<Node>::reverse_iterator reverse_iterator;
  typedef simple_ilist<Node>::const_iterator const_iterator;
  typedef simple_ilist<Node>::const_reverse_iterator const_reverse_iterator;

  // Check conversion values.
  EXPECT_EQ(L.begin(), iterator(L.rend()));
  EXPECT_EQ(++L.begin(), iterator(++L.rbegin()));
  EXPECT_EQ(L.end(), iterator(L.rbegin()));
  EXPECT_EQ(L.rbegin(), reverse_iterator(L.end()));
  EXPECT_EQ(++L.rbegin(), reverse_iterator(++L.begin()));
  EXPECT_EQ(L.rend(), reverse_iterator(L.begin()));

  // Check const iterator constructors.
  EXPECT_EQ(CL.begin(), const_iterator(L.rend()));
  EXPECT_EQ(CL.begin(), const_iterator(CL.rend()));
  EXPECT_EQ(CL.rbegin(), const_reverse_iterator(L.end()));
  EXPECT_EQ(CL.rbegin(), const_reverse_iterator(CL.end()));

  // Confirm lack of implicit conversions.
  static_assert(!std::is_convertible<iterator, reverse_iterator>::value,
                "unexpected implicit conversion");
  static_assert(!std::is_convertible<reverse_iterator, iterator>::value,
                "unexpected implicit conversion");
  static_assert(
      !std::is_convertible<const_iterator, const_reverse_iterator>::value,
      "unexpected implicit conversion");
  static_assert(
      !std::is_convertible<const_reverse_iterator, const_iterator>::value,
      "unexpected implicit conversion");
}

} // end namespace
<|endoftext|>