<commit_before>// This file is part of the "x0" project, http://github.com/christianparpart/x0>
//   (c) 2009-2017 Christian Parpart <christian@parpart.family>
//
// Licensed under the MIT License (the "License"); you may not use this
// file except in compliance with the License. You may obtain a copy of
// the License at: http://opensource.org/licenses/MIT

#include <xzero/io/OutputStream.h>
#include <xzero/RuntimeError.h>

namespace xzero {

int OutputStream::write(const std::string& data) {
  return write(data.data(), data.size());
}

int OutputStream::printf(const char* fmt, ...) {
  char buf[8192];

  va_list args;
  va_start(args, fmt);
  int pos = vsnprintf(buf, sizeof(buf), fmt, args);
  va_end(args);

  if (pos < 0) {
    RAISE_ERRNO(errno);
  }

  if (static_cast<size_t>(pos) < sizeof(buf)) {
    write(buf, pos);
  } else {
    RAISE_ERRNO(errno);
  }

  return pos;
}

} // namespace xzero
<commit_msg>[xzero] OutputStream: adds missing include<commit_after>// This file is part of the "x0" project, http://github.com/christianparpart/x0>
//   (c) 2009-2017 Christian Parpart <christian@parpart.family>
//
// Licensed under the MIT License (the "License"); you may not use this
// file except in compliance with the License. You may obtain a copy of
// the License at: http://opensource.org/licenses/MIT

#include <xzero/io/OutputStream.h>
#include <xzero/RuntimeError.h>
#include <stdarg.h>

namespace xzero {

int OutputStream::write(const std::string& data) {
  return write(data.data(), data.size());
}

int OutputStream::printf(const char* fmt, ...) {
  char buf[8192];

  va_list args;
  va_start(args, fmt);
  int pos = vsnprintf(buf, sizeof(buf), fmt, args);
  va_end(args);

  if (pos < 0) {
    RAISE_ERRNO(errno);
  }

  if (static_cast<size_t>(pos) < sizeof(buf)) {
    write(buf, pos);
  } else {
    RAISE_ERRNO(errno);
  }

  return pos;
}

} // namespace xzero
<|endoftext|>


<commit_before>/*************************************************************************
 *
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
 *
 * Copyright 2008 by Sun Microsystems, Inc.
 *
 * OpenOffice.org - a multi-platform office productivity suite
 *
 * This file is part of OpenOffice.org.
 *
 * OpenOffice.org is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Lesser General Public License version 3
 * only, as published by the Free Software Foundation.
 *
 * OpenOffice.org 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 version 3 for more details
 * (a copy is included in the LICENSE file that accompanied this code).
 *
 * You should have received a copy of the GNU Lesser General Public License
 * version 3 along with OpenOffice.org.  If not, see
 * <http://www.openoffice.org/license.html>
 * for a copy of the LGPLv3 License.
 *
 ************************************************************************/

#include "vcl/oldprintadaptor.hxx"
#include "vcl/gdimtf.hxx"

#include "com/sun/star/awt/Size.hpp"

#include <vector>

namespace vcl
{
    struct AdaptorPage
    {
        GDIMetaFile                     maPage;
        com::sun::star::awt::Size       maPageSize;
    };

    struct ImplOldStyleAdaptorData
    {
        std::vector< AdaptorPage >  maPages;
    };
}

using namespace vcl;
using namespace cppu;
using namespace com::sun::star;
using namespace com::sun::star::uno;
using namespace com::sun::star::beans;

OldStylePrintAdaptor::OldStylePrintAdaptor( const boost::shared_ptr< Printer >& i_pPrinter )
    : PrinterListener( i_pPrinter )
    , mpData( new ImplOldStyleAdaptorData() )
{
}

OldStylePrintAdaptor::~OldStylePrintAdaptor()
{
}

void OldStylePrintAdaptor::StartPage()
{
    Size aPaperSize( getPrinter()->PixelToLogic( getPrinter()->GetPaperSizePixel(), MapMode( MAP_100TH_MM ) ) );
    mpData->maPages.push_back( AdaptorPage() );
    mpData->maPages.back().maPageSize.Width = aPaperSize.getWidth();
    mpData->maPages.back().maPageSize.Height = aPaperSize.getHeight();
    getPrinter()->SetConnectMetaFile( &mpData->maPages.back().maPage );
}

void OldStylePrintAdaptor::EndPage()
{
    getPrinter()->SetConnectMetaFile( NULL );
    mpData->maPages.back().maPage.WindStart();
}

int  OldStylePrintAdaptor::getPageCount() const
{
    return int(mpData->maPages.size());
}

Sequence< PropertyValue > OldStylePrintAdaptor::getPageParameters( int i_nPage ) const
{
    Sequence< PropertyValue > aRet( 1 );
    aRet[0].Name = rtl::OUString( RTL_CONSTASCII_USTRINGPARAM("PageSize") );
    if( i_nPage < int(mpData->maPages.size() ) )
        aRet[0].Value = makeAny( mpData->maPages[i_nPage].maPageSize );
    else
    {
        awt::Size aEmpty( 0, 0  );
        aRet[0].Value = makeAny( aEmpty );
    }
    return aRet;
}

void OldStylePrintAdaptor::printPage( int i_nPage ) const
{
    if( i_nPage < int(mpData->maPages.size()) )
   {
       mpData->maPages[ i_nPage ].maPage.WindStart();
       mpData->maPages[ i_nPage ].maPage.Play( getPrinter().get() );
   }
}

<commit_msg>add missing precompiled header<commit_after>/*************************************************************************
 *
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
 *
 * Copyright 2008 by Sun Microsystems, Inc.
 *
 * OpenOffice.org - a multi-platform office productivity suite
 *
 * This file is part of OpenOffice.org.
 *
 * OpenOffice.org is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Lesser General Public License version 3
 * only, as published by the Free Software Foundation.
 *
 * OpenOffice.org 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 version 3 for more details
 * (a copy is included in the LICENSE file that accompanied this code).
 *
 * You should have received a copy of the GNU Lesser General Public License
 * version 3 along with OpenOffice.org.  If not, see
 * <http://www.openoffice.org/license.html>
 * for a copy of the LGPLv3 License.
 *
 ************************************************************************/

#include "precompiled_vcl.hxx"

#include "vcl/oldprintadaptor.hxx"
#include "vcl/gdimtf.hxx"

#include "com/sun/star/awt/Size.hpp"

#include <vector>

namespace vcl
{
    struct AdaptorPage
    {
        GDIMetaFile                     maPage;
        com::sun::star::awt::Size       maPageSize;
    };

    struct ImplOldStyleAdaptorData
    {
        std::vector< AdaptorPage >  maPages;
    };
}

using namespace vcl;
using namespace cppu;
using namespace com::sun::star;
using namespace com::sun::star::uno;
using namespace com::sun::star::beans;

OldStylePrintAdaptor::OldStylePrintAdaptor( const boost::shared_ptr< Printer >& i_pPrinter )
    : PrinterListener( i_pPrinter )
    , mpData( new ImplOldStyleAdaptorData() )
{
}

OldStylePrintAdaptor::~OldStylePrintAdaptor()
{
}

void OldStylePrintAdaptor::StartPage()
{
    Size aPaperSize( getPrinter()->PixelToLogic( getPrinter()->GetPaperSizePixel(), MapMode( MAP_100TH_MM ) ) );
    mpData->maPages.push_back( AdaptorPage() );
    mpData->maPages.back().maPageSize.Width = aPaperSize.getWidth();
    mpData->maPages.back().maPageSize.Height = aPaperSize.getHeight();
    getPrinter()->SetConnectMetaFile( &mpData->maPages.back().maPage );
}

void OldStylePrintAdaptor::EndPage()
{
    getPrinter()->SetConnectMetaFile( NULL );
    mpData->maPages.back().maPage.WindStart();
}

int  OldStylePrintAdaptor::getPageCount() const
{
    return int(mpData->maPages.size());
}

Sequence< PropertyValue > OldStylePrintAdaptor::getPageParameters( int i_nPage ) const
{
    Sequence< PropertyValue > aRet( 1 );
    aRet[0].Name = rtl::OUString( RTL_CONSTASCII_USTRINGPARAM("PageSize") );
    if( i_nPage < int(mpData->maPages.size() ) )
        aRet[0].Value = makeAny( mpData->maPages[i_nPage].maPageSize );
    else
    {
        awt::Size aEmpty( 0, 0  );
        aRet[0].Value = makeAny( aEmpty );
    }
    return aRet;
}

void OldStylePrintAdaptor::printPage( int i_nPage ) const
{
    if( i_nPage < int(mpData->maPages.size()) )
   {
       mpData->maPages[ i_nPage ].maPage.WindStart();
       mpData->maPages[ i_nPage ].maPage.Play( getPrinter().get() );
   }
}

<|endoftext|>


<commit_before>/*************************************************************************
 *
 *  $RCSfile: taskpanelist.cxx,v $
 *
 *  $Revision: 1.8 $
 *
 *  last change: $Author: hr $ $Date: 2002-03-19 10:51: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): _______________________________________
 *
 *
 ************************************************************************/
#ifndef _SV_SVDATA_HXX
#include <svdata.hxx>
#endif
#ifndef _RCID_H
#include <rcid.h>
#endif
#ifndef _SV_DOCKWIN_HXX
#include <dockwin.hxx>
#endif

#include <taskpanelist.hxx>
#include <functional>
#include <algorithm>

// can't have static linkage because SUNPRO 5.2 complains
Point ImplTaskPaneListGetPos( const Window *w )
{
    Point pos;
    if( w->ImplIsDockingWindow() )
    {
        pos = ((DockingWindow*)w)->GetPosPixel();
        Window *pF = ((DockingWindow*)w)->GetFloatingWindow();
        if( pF )
            pos = pF->OutputToAbsoluteScreenPixel( pF->ScreenToOutputPixel( pos ) );
        else
            pos = w->OutputToAbsoluteScreenPixel( pos );
    }
    else
        pos = w->OutputToAbsoluteScreenPixel( w->GetPosPixel() );

    return pos;
}

// compares window pos left-to-right
struct LTRSort : public ::std::binary_function< const Window*, const Window*, bool >
{
    bool operator()( const Window* w1, const Window* w2 ) const
    {
        Point pos1(ImplTaskPaneListGetPos( w1 ));
        Point pos2(ImplTaskPaneListGetPos( w2 ));

        if( pos1.X() == pos2.X() )
            return ( pos1.Y() < pos2.Y() );
        else
            return ( pos1.X() < pos2.X() );
    }
};
struct LTRSortBackward : public ::std::binary_function< const Window*, const Window*, bool >
{
    bool operator()( const Window* w2, const Window* w1 ) const
    {
        Point pos1(ImplTaskPaneListGetPos( w1 ));
        Point pos2(ImplTaskPaneListGetPos( w2 ));

        if( pos1.X() == pos2.X() )
            return ( pos1.Y() < pos2.Y() );
        else
            return ( pos1.X() < pos2.X() );
    }
};

// --------------------------------------------------

TaskPaneList::TaskPaneList()
{
}

TaskPaneList::~TaskPaneList()
{
}

// --------------------------------------------------

void TaskPaneList::AddWindow( Window *pWindow )
{
    bool bDockingWindow=false;
    bool bToolbox=false;
    bool bDialog=false;
    bool bUnknown=false;

    if( pWindow )
    {
        if( pWindow->GetType() == RSC_DOCKINGWINDOW )
            bDockingWindow = true;
        else if( pWindow->GetType() == RSC_TOOLBOX )
            bToolbox = true;
        else if( pWindow->IsDialog() )
            bDialog = true;
        else
            bUnknown = true;

        ::std::vector< Window* >::iterator p;
        p = ::std::find( mTaskPanes.begin(), mTaskPanes.end(), pWindow );

        // avoid duplicates
        if( p == mTaskPanes.end() ) // not found
            mTaskPanes.push_back( pWindow );
    }
}

// --------------------------------------------------

void TaskPaneList::RemoveWindow( Window *pWindow )
{
    ::std::vector< Window* >::iterator p;
    p = ::std::find( mTaskPanes.begin(), mTaskPanes.end(), pWindow );
    if( p != mTaskPanes.end() )
        mTaskPanes.erase( p );
}

// --------------------------------------------------

BOOL TaskPaneList::HandleKeyEvent( KeyEvent aKeyEvent )
{
    BOOL bFloatsOnly = FALSE;
    BOOL bFocusInList = FALSE;
    KeyCode aKeyCode = aKeyEvent.GetKeyCode();
    BOOL bForward = !aKeyCode.IsShift();
    if( ( aKeyCode.IsMod1() && aKeyCode.GetCode() == KEY_TAB )  // Ctrl-TAB
        || ( bFloatsOnly = ( aKeyCode.GetCode()) == KEY_F6 )    // F6
        )
    {
        // is the focus in the list ?
        BOOL bHasFocus = FALSE;
        ::std::vector< Window* >::iterator p = mTaskPanes.begin();
        while( p != mTaskPanes.end() )
        {
            Window *pWin = *p;
            if( (*p)->HasChildPathFocus( TRUE ) )
            {
                // F6 works only in floaters
                if( bFloatsOnly && (*p)->GetType() != RSC_DOCKINGWINDOW && !(*p)->IsDialog() )
                    return FALSE;

                bFocusInList = TRUE;
                // activate next task pane
                Window *pNextWin = bFloatsOnly ? FindNextFloat( *p, bForward ) : FindNextPane( *p, bForward );
                if( pNextWin != pWin )
                {
                    ImplGetSVData()->maWinData.mbNoSaveFocus = TRUE;
                    pNextWin->GrabFocus();
                    ImplGetSVData()->maWinData.mbNoSaveFocus = FALSE;
                }
                else
                {
                    // we did not find another taskpane, so
                    // put focus back into document: use frame win of topmost parent
                    while( pWin )
                    {
                        if( !pWin->GetParent() )
                        {
                            pWin->ImplGetFrameWindow()->GetWindow( WINDOW_CLIENT )->GrabFocus();
                            break;
                        }
                        pWin = pWin->GetParent();
                    }
                }

                return TRUE;
            }
            else
                p++;
        }

        // the focus is not in the list: activate first float if F6 was pressed
        if( !bFocusInList && bFloatsOnly )
        {
            Window *pWin = FindNextFloat( NULL, bForward );
            if( pWin )
            {
                pWin->GrabFocus();
                return TRUE;
            }
        }
    }

    return FALSE;
}

// --------------------------------------------------

//  returns next valid pane
Window* TaskPaneList::FindNextPane( Window *pWindow, BOOL bForward )
{
    if( bForward )
        ::std::stable_sort( mTaskPanes.begin(), mTaskPanes.end(), LTRSort() );
    else
        ::std::stable_sort( mTaskPanes.begin(), mTaskPanes.end(), LTRSortBackward() );

    ::std::vector< Window* >::iterator p = mTaskPanes.begin();
    while( p != mTaskPanes.end() )
    {
        if( *p == pWindow )
        {
            unsigned n = mTaskPanes.size();
            while( --n )
            {
                if( ++p == mTaskPanes.end() )
                    p = mTaskPanes.begin();
                if( (*p)->IsVisible() )
                    return *p;
            }
            break;
        }
        else
            ++p;
    }

    return pWindow; // nothing found
}

// --------------------------------------------------

// returns first valid float if pWindow==0, otherwise returns next valid float
Window* TaskPaneList::FindNextFloat( Window *pWindow, BOOL bForward )
{
    if( bForward )
        ::std::stable_sort( mTaskPanes.begin(), mTaskPanes.end(), LTRSort() );
    else
        ::std::stable_sort( mTaskPanes.begin(), mTaskPanes.end(), LTRSortBackward() );

    ::std::vector< Window* >::iterator p = mTaskPanes.begin();
    while( p != mTaskPanes.end() )
    {
        if( !pWindow || *p == pWindow )
        {
            while( p != mTaskPanes.end() )
            {
                if( pWindow )   // increment before test
                    ++p;
                if( p == mTaskPanes.end() )
                    return pWindow; // do not wrap, send focus back to document at end of list
                if( (*p)->IsVisible() && ( (*p)->GetType() == RSC_DOCKINGWINDOW || (*p)->IsDialog() ) )
                    return *p;
                if( !pWindow )  // increment after test, otherwise first element is skipped
                    ++p;
            }
            break;
        }
        else
            ++p;
    }

    return pWindow; // nothing found
}

// --------------------------------------------------

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

#include <taskpanelist.hxx>
#include <functional>
#include <algorithm>

// can't have static linkage because SUNPRO 5.2 complains
Point ImplTaskPaneListGetPos( const Window *w )
{
    Point pos;
    if( w->ImplIsDockingWindow() )
    {
        pos = ((DockingWindow*)w)->GetPosPixel();
        Window *pF = ((DockingWindow*)w)->GetFloatingWindow();
        if( pF )
            pos = pF->OutputToAbsoluteScreenPixel( pF->ScreenToOutputPixel( pos ) );
        else
            pos = w->OutputToAbsoluteScreenPixel( pos );
    }
    else
        pos = w->OutputToAbsoluteScreenPixel( w->GetPosPixel() );

    return pos;
}

// compares window pos left-to-right
struct LTRSort : public ::std::binary_function< const Window*, const Window*, bool >
{
    bool operator()( const Window* w1, const Window* w2 ) const
    {
        Point pos1(ImplTaskPaneListGetPos( w1 ));
        Point pos2(ImplTaskPaneListGetPos( w2 ));

        if( pos1.X() == pos2.X() )
            return ( pos1.Y() < pos2.Y() );
        else
            return ( pos1.X() < pos2.X() );
    }
};
struct LTRSortBackward : public ::std::binary_function< const Window*, const Window*, bool >
{
    bool operator()( const Window* w2, const Window* w1 ) const
    {
        Point pos1(ImplTaskPaneListGetPos( w1 ));
        Point pos2(ImplTaskPaneListGetPos( w2 ));

        if( pos1.X() == pos2.X() )
            return ( pos1.Y() < pos2.Y() );
        else
            return ( pos1.X() < pos2.X() );
    }
};

// --------------------------------------------------

TaskPaneList::TaskPaneList()
{
}

TaskPaneList::~TaskPaneList()
{
}

// --------------------------------------------------

void TaskPaneList::AddWindow( Window *pWindow )
{
    bool bDockingWindow=false;
    bool bToolbox=false;
    bool bDialog=false;
    bool bUnknown=false;

    if( pWindow )
    {
        if( pWindow->GetType() == RSC_DOCKINGWINDOW )
            bDockingWindow = true;
        else if( pWindow->GetType() == RSC_TOOLBOX )
            bToolbox = true;
        else if( pWindow->IsDialog() )
            bDialog = true;
        else
            bUnknown = true;

        ::std::vector< Window* >::iterator p;
        p = ::std::find( mTaskPanes.begin(), mTaskPanes.end(), pWindow );

        // avoid duplicates
        if( p == mTaskPanes.end() ) // not found
            mTaskPanes.push_back( pWindow );
    }
}

// --------------------------------------------------

void TaskPaneList::RemoveWindow( Window *pWindow )
{
    ::std::vector< Window* >::iterator p;
    p = ::std::find( mTaskPanes.begin(), mTaskPanes.end(), pWindow );
    if( p != mTaskPanes.end() )
        mTaskPanes.erase( p );
}

// --------------------------------------------------

BOOL TaskPaneList::HandleKeyEvent( KeyEvent aKeyEvent )
{
    // F6 cycles through everything and works always
    // Ctrl-TAB cycles through Menubar, Toolbars and Floatingwindows only and is
    // only active if one of those items has the focus
    BOOL bF6 = FALSE;
    BOOL bFocusInList = FALSE;
    KeyCode aKeyCode = aKeyEvent.GetKeyCode();
    BOOL bForward = !aKeyCode.IsShift();
    if( ( aKeyCode.IsMod1() && aKeyCode.GetCode() == KEY_TAB )  // Ctrl-TAB
        || ( bF6 = ( aKeyCode.GetCode()) == KEY_F6 )    // F6
        )
    {
        // is the focus in the list ?
        BOOL bHasFocus = FALSE;
        ::std::vector< Window* >::iterator p = mTaskPanes.begin();
        while( p != mTaskPanes.end() )
        {
            Window *pWin = *p;
            if( (*p)->HasChildPathFocus( TRUE ) )
            {
                bFocusInList = TRUE;

                // Ctrl-TAB works not in Dialogs
                if( !bF6 && (*p)->IsDialog() )
                    return FALSE;

                // activate next task pane
                Window *pNextWin = bF6 ?  FindNextFloat( *p, bForward ) : FindNextPane( *p, bForward );
                if( pNextWin != pWin )
                {
                    ImplGetSVData()->maWinData.mbNoSaveFocus = TRUE;
                    pNextWin->GrabFocus();
                    ImplGetSVData()->maWinData.mbNoSaveFocus = FALSE;
                }
                else
                {
                    // we did not find another taskpane, so
                    // put focus back into document: use frame win of topmost parent
                    while( pWin )
                    {
                        if( !pWin->GetParent() )
                        {
                            pWin->ImplGetFrameWindow()->GetWindow( WINDOW_CLIENT )->GrabFocus();
                            break;
                        }
                        pWin = pWin->GetParent();
                    }
                }

                return TRUE;
            }
            else
                p++;
        }

        // the focus is not in the list: activate first float if F6 was pressed
        if( !bFocusInList && bF6 )
        {
            Window *pWin = FindNextFloat( NULL, bForward );
            if( pWin )
            {
                pWin->GrabFocus();
                return TRUE;
            }
        }
    }

    return FALSE;
}

// --------------------------------------------------

//  returns next valid pane
Window* TaskPaneList::FindNextPane( Window *pWindow, BOOL bForward )
{
    if( bForward )
        ::std::stable_sort( mTaskPanes.begin(), mTaskPanes.end(), LTRSort() );
    else
        ::std::stable_sort( mTaskPanes.begin(), mTaskPanes.end(), LTRSortBackward() );

    ::std::vector< Window* >::iterator p = mTaskPanes.begin();
    while( p != mTaskPanes.end() )
    {
        if( *p == pWindow )
        {
            unsigned n = mTaskPanes.size();
            while( --n )
            {
                if( ++p == mTaskPanes.end() )
                    p = mTaskPanes.begin();
                if( (*p)->IsVisible() && !(*p)->IsDialog() )
                    return *p;
            }
            break;
        }
        else
            ++p;
    }

    return pWindow; // nothing found
}

// --------------------------------------------------

// returns first valid item (regardless of type) if pWindow==0, otherwise returns next valid float
Window* TaskPaneList::FindNextFloat( Window *pWindow, BOOL bForward )
{
    if( bForward )
        ::std::stable_sort( mTaskPanes.begin(), mTaskPanes.end(), LTRSort() );
    else
        ::std::stable_sort( mTaskPanes.begin(), mTaskPanes.end(), LTRSortBackward() );

    ::std::vector< Window* >::iterator p = mTaskPanes.begin();
    while( p != mTaskPanes.end() )
    {
        if( !pWindow || *p == pWindow )
        {
            while( p != mTaskPanes.end() )
            {
                if( pWindow )   // increment before test
                    ++p;
                if( p == mTaskPanes.end() )
                    return pWindow; // do not wrap, send focus back to document at end of list
                if( (*p)->IsVisible() /*&& ( (*p)->GetType() == RSC_DOCKINGWINDOW || (*p)->IsDialog() )*/ )
                    return *p;
                if( !pWindow )  // increment after test, otherwise first element is skipped
                    ++p;
            }
            break;
        }
        else
            ++p;
    }

    return pWindow; // nothing found
}

// --------------------------------------------------

<|endoftext|>


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

#ifndef _TARGETLISTENER_HXX_
#define _TARGETLISTENER_HXX_

#include <windows.h>
#include <cppuhelper/implbase1.hxx>
#include <com/sun/star/datatransfer/dnd/XDropTargetListener.hpp>
#include <com/sun/star/datatransfer/dnd/DropTargetDropEvent.hpp>
#include <com/sun/star/datatransfer/dnd/DropTargetDragEvent.hpp>
#include <com/sun/star/datatransfer/dnd/DropTargetDragEnterEvent.hpp>

using namespace ::com::sun::star::datatransfer;
using namespace ::com::sun::star::datatransfer::dnd;
using namespace ::cppu;
using namespace ::com::sun::star::uno;
using namespace ::com::sun::star::lang;

class DropTargetListener: public WeakImplHelper1<XDropTargetListener>
{
    // this is a window where droped data are shown as text (only text)
    HWND m_hEdit;
public:
    DropTargetListener( HWND hEdit);
    ~DropTargetListener();

    virtual void SAL_CALL disposing( const EventObject& Source )
        throw(RuntimeException);

    virtual void SAL_CALL drop( const DropTargetDropEvent& dtde )
        throw(RuntimeException);
    virtual void SAL_CALL dragEnter( const DropTargetDragEnterEvent& dtde )
        throw(RuntimeException);
    virtual void SAL_CALL dragExit( const DropTargetEvent& dte )
        throw(RuntimeException);
    virtual void SAL_CALL dragOver( const DropTargetDragEvent& dtde )
        throw(RuntimeException);
    virtual void SAL_CALL dropActionChanged( const DropTargetDragEvent& dtde )
        throw(RuntimeException);
};

#endif
<commit_msg>INTEGRATION: CWS warnings01 (1.4.4); FILE MERGED 2006/03/09 20:32:32 pl 1.4.4.1: #i55991# removed warnings for windows platform<commit_after>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: targetlistener.hxx,v $
 *
 *  $Revision: 1.5 $
 *
 *  last change: $Author: hr $ $Date: 2006-06-20 06:09:01 $
 *
 *  The Contents of this file are made available subject to
 *  the terms of GNU Lesser General Public License Version 2.1.
 *
 *
 *    GNU Lesser General Public License Version 2.1
 *    =============================================
 *    Copyright 2005 by Sun Microsystems, Inc.
 *    901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *    This library is free software; you can redistribute it and/or
 *    modify it under the terms of the GNU Lesser General Public
 *    License version 2.1, as published by the Free Software Foundation.
 *
 *    This library is distributed in the hope that it will be useful,
 *    but WITHOUT ANY WARRANTY; without even the implied warranty of
 *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *    Lesser General Public License for more details.
 *
 *    You should have received a copy of the GNU Lesser General Public
 *    License along with this library; if not, write to the Free Software
 *    Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *    MA  02111-1307  USA
 *
 ************************************************************************/

#ifndef _TARGETLISTENER_HXX_
#define _TARGETLISTENER_HXX_

#if defined _MSC_VER
#pragma warning(push,1)
#endif
#include <windows.h>
#if defined _MSC_VER
#pragma warning(pop)
#endif
#include <cppuhelper/implbase1.hxx>
#include <com/sun/star/datatransfer/dnd/XDropTargetListener.hpp>
#include <com/sun/star/datatransfer/dnd/DropTargetDropEvent.hpp>
#include <com/sun/star/datatransfer/dnd/DropTargetDragEvent.hpp>
#include <com/sun/star/datatransfer/dnd/DropTargetDragEnterEvent.hpp>

using namespace ::com::sun::star::datatransfer;
using namespace ::com::sun::star::datatransfer::dnd;
using namespace ::cppu;
using namespace ::com::sun::star::uno;
using namespace ::com::sun::star::lang;

class DropTargetListener: public WeakImplHelper1<XDropTargetListener>
{
    // this is a window where droped data are shown as text (only text)
    HWND m_hEdit;
public:
    DropTargetListener( HWND hEdit);
    ~DropTargetListener();

    virtual void SAL_CALL disposing( const EventObject& Source )
        throw(RuntimeException);

    virtual void SAL_CALL drop( const DropTargetDropEvent& dtde )
        throw(RuntimeException);
    virtual void SAL_CALL dragEnter( const DropTargetDragEnterEvent& dtde )
        throw(RuntimeException);
    virtual void SAL_CALL dragExit( const DropTargetEvent& dte )
        throw(RuntimeException);
    virtual void SAL_CALL dragOver( const DropTargetDragEvent& dtde )
        throw(RuntimeException);
    virtual void SAL_CALL dropActionChanged( const DropTargetDragEvent& dtde )
        throw(RuntimeException);
};

#endif
<|endoftext|>


<commit_before>#include "SharedMesh.hh"

#include "Parsers/Parsers.hh"

#include <assert.h>

namespace	Resources
{

SharedMesh::SharedMesh(void)
{
}

SharedMesh::~SharedMesh(void)
{
}

bool	SharedMesh::load(std::string const &path)
{
	if (loadObj(path, _geometry) == false)
		return (false);
	_buffer.init(_geometry.vertices.size(), &_geometry.indices[0]);
	_buffer.addAttribute(OpenGLTools::Attribute(sizeof(float) * 4, 4, GL_FLOAT));
	_buffer.addAttribute(OpenGLTools::Attribute(sizeof(float) * 4, 4, GL_FLOAT));
	_buffer.addAttribute(OpenGLTools::Attribute(sizeof(float) * 4, 4, GL_FLOAT));
	_buffer.addAttribute(OpenGLTools::Attribute(sizeof(float) * 2, 2, GL_FLOAT));
	assert(_geometry.vertices.size() > 0 && "Cannot create mesh without vertices.");
	_buffer.setBuffer(0, reinterpret_cast<byte *>(&_geometry.vertices[0].x));
	if (_geometry.colors.size())
	  _buffer.setBuffer(1, reinterpret_cast<byte *>(&_geometry.colors[0].x));
	if (_geometry.normals.size())
	  _buffer.setBuffer(2, reinterpret_cast<byte *>(&_geometry.normals[0].x));
	if (_geometry.uvs.size())
	  _buffer.setBuffer(3, reinterpret_cast<byte *>(&_geometry.uvs[0].x));
	return (true);
}

void		SharedMesh::draw() const
{
	_buffer.draw(GL_TRIANGLES);
}

OpenGLTools::VertexBuffer	&SharedMesh::getBuffer()
{
	return (_buffer);
}

}<commit_msg>Obj loader fixed<commit_after>#include "SharedMesh.hh"

#include "Parsers/Parsers.hh"

#include <assert.h>

namespace	Resources
{

SharedMesh::SharedMesh(void)
{
}

SharedMesh::~SharedMesh(void)
{
}

bool	SharedMesh::load(std::string const &path)
{
	if (loadObj(path, _geometry) == false)
		return (false);
	_buffer.init(_geometry.indices.size(), &_geometry.indices[0]);
	_buffer.addAttribute(OpenGLTools::Attribute(sizeof(float) * 4, 4, GL_FLOAT));
	_buffer.addAttribute(OpenGLTools::Attribute(sizeof(float) * 4, 4, GL_FLOAT));
	_buffer.addAttribute(OpenGLTools::Attribute(sizeof(float) * 4, 4, GL_FLOAT));
	_buffer.addAttribute(OpenGLTools::Attribute(sizeof(float) * 2, 2, GL_FLOAT));
	assert(_geometry.vertices.size() > 0 && "Cannot create mesh without vertices.");
	_buffer.setBuffer(0, reinterpret_cast<byte *>(&_geometry.vertices[0].x));
	if (_geometry.colors.size())
	  _buffer.setBuffer(1, reinterpret_cast<byte *>(&_geometry.colors[0].x));
	if (_geometry.normals.size())
	  _buffer.setBuffer(2, reinterpret_cast<byte *>(&_geometry.normals[0].x));
	if (_geometry.uvs.size())
	  _buffer.setBuffer(3, reinterpret_cast<byte *>(&_geometry.uvs[0].x));
	return (true);
}

void		SharedMesh::draw() const
{
	_buffer.draw(GL_TRIANGLES);
}

OpenGLTools::VertexBuffer	&SharedMesh::getBuffer()
{
	return (_buffer);
}

}<|endoftext|>


<commit_before>/**
 * @file test-template-1.cpp
 * @author Giovanni Curiel (giovannicuriel@gmail.com)
 * @brief Test for template
 * @version 0.1
 * @date 2021-10-23
 *
 * @copyright Copyright (c) 2021
 */

#include <iostream>
#include <list>

bool isEven(u_int32_t n) { return n % 2 == 1;}

struct Point {
    int x;
    int y;
    bool operator==(const Point& other) const {
        return x == other.x && y == other.y;
    }
};

enum ProjectionSide {
    TO_THE_LEFT,
    TO_THE_RIGHT,
    NO_PROJECTION
};

struct Edge {
    Point p1;
    Point p2;
    bool isWithinYRange(const Point & p) const {
        return (p.y >= p1.y && p.y <= p2.y) || (p.y <= p1.y && p.y >= p2.y);
    }
};

struct FirstOrderFunction {
    double m;
    double a;
    FirstOrderFunction(const Edge & e) {
        m = (e.p2.y - e.p1.y) / double (e.p2.x - e.p1.x);
        a =  e.p1.y - m * e.p1.x;
    }
    double f(int x) const {
        return a + m * x;
    }
    bool isAbove(const Point & p) const {
        return f(p.x) > p.y;
    }
    bool isBelow(const Point & p) const {
        return !isAbove(p);
    }
};

struct Vertex : public Point {
    Vertex(int x, int y) : Point({x, y}) {}
    Vertex(const Point & p) : Point(p) {}
};

bool hasProjectionOnEdge(const Point & point, const Edge & edge, ProjectionSide side) {
    auto edgeFunction = FirstOrderFunction(edge);
    switch (side) {
        case NO_PROJECTION:
            return !edge.isWithinYRange(point);
        case TO_THE_LEFT:
            return edge.isWithinYRange(point) && edgeFunction.isAbove(point);
        case TO_THE_RIGHT:
            return edge.isWithinYRange(point) && edgeFunction.isBelow(point);
    }
    return false;
}

struct Polygon {
    const std::list<Edge> edges;

    Polygon(const std::list<Vertex> & p) :
        edges(buildEdgesFrom(p)
    ) {}

    static std::list<Edge> buildEdgesFrom(const std::list<Vertex> & vertices) {
        std::list<Edge> edges;
        edges.clear();
        Vertex const * firstVertex = nullptr;
        Vertex const * secondVertex = nullptr;
        for (auto & vertex: vertices) {
            firstVertex = &vertex;
            if (secondVertex) {
                edges.push_back({*secondVertex, *firstVertex});
            }
            secondVertex = firstVertex;
        }
        // Last edge
        edges.push_back((Edge){vertices.back(), vertices.front()});
        return edges;
    }

    bool contains(const Point & point) const {
        u_int32_t cross = 0;
        for (auto & edge: edges) {
            if (hasProjectionOnEdge(point, edge, TO_THE_LEFT)) {
                cross++;
            }
        }
        return isEven(cross);
    }
};

std::ostream & operator<<(std::ostream & os, const Point & p) {
    os << "(" << p.x << ", " << p.y << ")";
    return os;
}

std::ostream & operator<<(std::ostream & os, const Edge & e) {
    os << "Edge: " << e.p1 << " - " << e.p2;
    return os;
};

int main(void) {
    Polygon polygon = Polygon (
        {
            {1, 1},
            {11, 3},
            {14, 14},
            {3, 11}
        }
    );
    std::list<Point> points = {
        { 0, 0 },
        { 2, 0 },
        { 5, 0 },
        { 13, 0 },
        { 15, 0 },
        { 0,  2 },
        { 2,  2 },
        { 5,  2 },
        { 10, 2 },
        { 13, 2 },
        { 15, 2 },
        { 0,  5 },
        { 2,  5 },
        { 5,  5 },
        { 13, 5 },
        { 15, 5 },
        { 0,  13 },
        { 2,  13 },
        { 5,  13 },
        { 13, 13 },
        { 15, 13 },
        { 0,  15 },
        { 2,  15 },
        { 5,  15 },
        { 13, 15 },
        { 15, 15 },
    };
    for (auto & point: points) {
        auto state = (polygon.contains(point) ? "" : "not ");
        std::cout << "Point " << point << " is " << state << "inside the polygon" << std::endl;
    }
    return 0;
}
<commit_msg>fix: fixing a tidybit on c++ polygon algorithm<commit_after>/**
 * @file test-template-1.cpp
 * @author Giovanni Curiel (giovannicuriel@gmail.com)
 * @brief Test for template
 * @version 0.1
 * @date 2021-10-23
 *
 * @copyright Copyright (c) 2021
 */

#include <iostream>
#include <list>

bool isEven(u_int32_t n) { return n % 2 == 1;}

struct Point {
    int x;
    int y;
    bool operator==(const Point& other) const {
        return x == other.x && y == other.y;
    }
};

enum ProjectionSide {
    TO_THE_LEFT,
    TO_THE_RIGHT,
    NO_PROJECTION
};

struct Edge {
    Point p1;
    Point p2;
    bool isWithinYRange(const Point & p) const {
        return (p.y >= p1.y && p.y <= p2.y) || (p.y <= p1.y && p.y >= p2.y);
    }
};

struct FirstOrderFunction {
    double m;
    double a;
    FirstOrderFunction(const Edge & e) {
        m = (e.p2.y - e.p1.y) / double (e.p2.x - e.p1.x);
        a =  e.p1.y - m * e.p1.x;
    }
    double f(int x) const {
        return a + m * x;
    }
    bool isAbove(const Point & p) const {
        return f(p.x) >= p.y;
    }
    bool isBelow(const Point & p) const {
        return f(p.x) <= p.y;
    }
};

struct Vertex : public Point {
    Vertex(int x, int y) : Point({x, y}) {}
    Vertex(const Point & p) : Point(p) {}
};

bool hasProjectionOnEdge(const Point & point, const Edge & edge, ProjectionSide side) {
    auto edgeFunction = FirstOrderFunction(edge);
    switch (side) {
        case NO_PROJECTION:
            return !edge.isWithinYRange(point);
        case TO_THE_LEFT:
            return edge.isWithinYRange(point) && edgeFunction.isAbove(point);
        case TO_THE_RIGHT:
            return edge.isWithinYRange(point) && edgeFunction.isBelow(point);
    }
    return false;
}

struct Polygon {
    const std::list<Edge> edges;

    Polygon(const std::list<Vertex> & p) :
        edges(buildEdgesFrom(p)
    ) {}

    static std::list<Edge> buildEdgesFrom(const std::list<Vertex> & vertices) {
        std::list<Edge> edges;
        edges.clear();
        Vertex const * firstVertex = nullptr;
        Vertex const * secondVertex = nullptr;
        for (auto & vertex: vertices) {
            firstVertex = &vertex;
            if (secondVertex) {
                edges.push_back({*secondVertex, *firstVertex});
            }
            secondVertex = firstVertex;
        }
        // Last edge
        edges.push_back((Edge){vertices.back(), vertices.front()});
        return edges;
    }

    bool contains(const Point & point) const {
        u_int32_t cross = 0;
        for (auto & edge: edges) {
            if (hasProjectionOnEdge(point, edge, TO_THE_LEFT)) {
                cross++;
            }
        }
        return isEven(cross);
    }
};

std::ostream & operator<<(std::ostream & os, const Point & p) {
    os << "(" << p.x << ", " << p.y << ")";
    return os;
}

std::ostream & operator<<(std::ostream & os, const Edge & e) {
    os << "Edge: " << e.p1 << " - " << e.p2;
    return os;
};

int main(void) {
    Polygon polygon = Polygon (
        {
            {1, 1},
            {11, 3},
            {14, 14},
            {3, 11}
        }
    );
    std::list<Point> points = {
        { 0, 0 },
        { 11, 3 },
        { 2, 6 },
        { 2, 0 },
        { 5, 0 },
        { 13, 0 },
        { 15, 0 },
        { 0,  2 },
        { 2,  2 },
        { 5,  2 },
        { 10, 2 },
        { 13, 2 },
        { 15, 2 },
        { 0,  5 },
        { 2,  5 },
        { 5,  5 },
        { 13, 5 },
        { 15, 5 },
        { 0,  13 },
        { 2,  13 },
        { 5,  13 },
        { 13, 13 },
        { 15, 13 },
        { 0,  15 },
        { 2,  15 },
        { 5,  15 },
        { 13, 15 },
        { 15, 15 },
    };
    for (auto & point: points) {
        auto state = (polygon.contains(point) ? "" : "not ");
        std::cout << "Point " << point << " is " << state << "inside the polygon" << std::endl;
    }
    return 0;
}
<|endoftext|>


<commit_before>#ifndef VIENNAGRID_SEGMENTED_MESH_HPP
#define VIENNAGRID_SEGMENTED_MESH_HPP

#include "viennagrid/mesh/mesh.hpp"
#include "viennagrid/mesh/segmentation.hpp"

namespace viennagrid
{

  template<typename MeshT, typename SegmentationT>
  struct segmented_mesh
  {
    typedef MeshT mesh_type;
    typedef SegmentationT segmentation_type;

    mesh_type mesh;
    segmentation_type segmentation;
  };

  template<typename WrappedMeshConfig, typename WrappedSegmentationConfig>
  struct segmented_mesh< viennagrid::mesh<WrappedMeshConfig>, viennagrid::segmentation<WrappedSegmentationConfig> >
  {
    typedef viennagrid::mesh<WrappedMeshConfig> mesh_type;
    typedef viennagrid::segmentation<WrappedSegmentationConfig> segmentation_type;

    segmented_mesh() : segmentation(mesh) {}

    mesh_type mesh;
    segmentation_type segmentation;
  };

}

#endif
<commit_msg>segmented_mesh.hpp: added initialization of segmentation in constructor<commit_after>#ifndef VIENNAGRID_SEGMENTED_MESH_HPP
#define VIENNAGRID_SEGMENTED_MESH_HPP

#include "viennagrid/mesh/mesh.hpp"
#include "viennagrid/mesh/segmentation.hpp"

namespace viennagrid
{

  template<typename MeshT, typename SegmentationT>
  struct segmented_mesh
  {
    typedef MeshT mesh_type;
    typedef SegmentationT segmentation_type;

    segmented_mesh() : segmentation(mesh) {}

    mesh_type mesh;
    segmentation_type segmentation;
  };

  template<typename WrappedMeshConfig, typename WrappedSegmentationConfig>
  struct segmented_mesh< viennagrid::mesh<WrappedMeshConfig>, viennagrid::segmentation<WrappedSegmentationConfig> >
  {
    typedef viennagrid::mesh<WrappedMeshConfig> mesh_type;
    typedef viennagrid::segmentation<WrappedSegmentationConfig> segmentation_type;

    segmented_mesh() : segmentation(mesh) {}

    mesh_type mesh;
    segmentation_type segmentation;
  };

}

#endif
<|endoftext|>


<commit_before>/* Copyright 2018 The TensorFlow Authors. All Rights Reserved.

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

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

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

#include "tensorflow/core/distributed_runtime/cancellable_call.h"
#include "tensorflow/core/distributed_runtime/device_resolver_distributed.h"
#include "tensorflow/core/distributed_runtime/worker_cache.h"
#include "tensorflow/core/protobuf/config.pb.h"

namespace tensorflow {
namespace {

class CompleteGroupCall : public CancellableCall {
 public:
  CompleteGroupCall(const CollGroupParams& group, const string& device_name,
                    CancellationManager* cancel_mgr,
                    const string& remote_worker, WorkerCacheInterface* wc)
      : CancellableCall(cancel_mgr, remote_worker, wc) {
    req_.set_group_key(group.group_key);
    req_.set_group_size(group.group_size);
    req_.set_device_type(group.device_type.type_string());
    req_.add_device_name(device_name);
  }
  ~CompleteGroupCall() override {}

  void IssueCall(const StatusCallback& done) override {
    wi_->CompleteGroupAsync(&opts_, &req_, &resp_, done);
  }

  CompleteGroupRequest req_;
  CompleteGroupResponse resp_;
};

class CompleteInstanceCall : public CancellableCall {
 public:
  CompleteInstanceCall(const CollGroupParams& group,
                       const CollInstanceParams& instance,
                       const string& node_name, const string& device_name,
                       bool is_source, CancellationManager* cancel_mgr,
                       const string& remote_worker, WorkerCacheInterface* wc)
      : CancellableCall(cancel_mgr, remote_worker, wc) {
    req_.set_name(node_name);
    req_.set_type(instance.type);
    req_.set_data_type(instance.data_type);
    instance.shape.AsProto(req_.mutable_shape());
    req_.set_group_key(group.group_key);
    req_.set_group_size(group.group_size);
    req_.set_instance_key(instance.instance_key);
    req_.set_device_type(group.device_type.type_string());
    for (int32 offset : instance.impl_details.subdiv_offsets) {
      req_.add_subdiv_offset(offset);
    }
    req_.set_device(device_name);
    req_.set_is_source(is_source);
  }

  ~CompleteInstanceCall() override {}

  void IssueCall(const StatusCallback& done) override {
    wi_->CompleteInstanceAsync(&opts_, &req_, &resp_, done);
  }

  CompleteInstanceRequest req_;
  CompleteInstanceResponse resp_;
};

}  // namespace

CollectiveParamResolverDistributed::CollectiveParamResolverDistributed(
    const ConfigProto& config, const DeviceMgr* dev_mgr,
    DeviceResolverDistributed* dev_resolver, WorkerCacheInterface* worker_cache,
    const string& task_name)
    : CollectiveParamResolverLocal(dev_mgr, dev_resolver, task_name),
      worker_cache_(worker_cache),
      group_leader_(task_name == config.experimental().collective_group_leader()
                        ? ""
                        : config.experimental().collective_group_leader()) {}

void CollectiveParamResolverDistributed::CompleteParamsAsync(
    const string& device, CollectiveParams* cp, CancellationManager* cancel_mgr,
    const StatusCallback& done) {
  CompleteGroupDistributed(device, cp, cancel_mgr,
                           [this, device, cp, cancel_mgr, done](
                               const Status& s, const GroupRec* gr) {
                             if (s.ok()) {
                               CompleteInstanceDistributed(device, gr, cp,
                                                           cancel_mgr, done);
                             } else {
                               done(s);
                             }
                           });
}

void CollectiveParamResolverDistributed::CompleteGroupAsync(
    const CompleteGroupRequest* request, CompleteGroupResponse* response,
    CancellationManager* cancel_mgr, const StatusCallback& done) {
  CollectiveParams cp;
  cp.group.group_key = request->group_key();
  cp.group.group_size = request->group_size();
  cp.group.device_type = DeviceType(request->device_type());
  for (const string& dn : request->device_name()) {
    cp.instance.device_names.push_back(dn);
  }
  CompleteGroupDistributed(
      cp.instance.device_names[0], &cp, cancel_mgr,
      [this, response, done](const Status& s, const GroupRec* gr) {
        if (s.ok()) {
          mutex_lock l(gr->mu);
          response->set_group_key(gr->group.group_key);
          response->set_group_size(gr->group.group_size);
          response->set_device_type(gr->group.device_type.type_string());
          response->set_num_tasks(gr->task_set.size());
          for (const string& dn : gr->device_list) {
            response->add_device_name(dn);
          }
          for (const string& tn : gr->task_list) {
            response->add_task_name(tn);
          }
        } else {
          LOG(ERROR) << "Bad status from CompleteGroupDistributed: " << s;
        }
        done(s);
      });
}

void CollectiveParamResolverDistributed::CompleteInstanceAsync(
    const CompleteInstanceRequest* request, CompleteInstanceResponse* response,
    CancellationManager* cancel_mgr, const StatusCallback& done) {
  CollectiveParams* cp = new CollectiveParams;
  cp->name = request->name();
  cp->group.group_key = request->group_key();
  cp->group.group_size = request->group_size();
  cp->group.device_type = DeviceType(request->device_type());
  cp->instance.type = CollectiveType(request->type());
  cp->instance.instance_key = request->instance_key();
  cp->instance.data_type = request->data_type();
  cp->instance.shape = TensorShape(request->shape());
  for (int32 offset : request->subdiv_offset()) {
    cp->instance.impl_details.subdiv_offsets.push_back(offset);
  }
  VLOG(1) << "New cp " << cp << " for device " << request->device() << " : "
          << cp->ToString();
  StatusCallback done_and_cleanup = [this, cp, done](const Status& s) {
    done(s);
    delete cp;
  };
  // Start by completing the group.
  CompleteGroupDistributed(
      request->device(), cp, cancel_mgr,
      [this, cp, request, response, cancel_mgr, done_and_cleanup](
          const Status& cg_status, const GroupRec* gr) {
        if (cg_status.ok()) {
          // Then complete the instance.
          CompleteInstanceDistributed(
              request->device(), gr, cp, cancel_mgr,
              [this, gr, cp, response,
               done_and_cleanup](const Status& ci_status) {
                if (ci_status.ok()) {
                  // Now source_rank should be known, so
                  // retrieve it.
                  FindInstanceRec(
                      gr, cp,
                      [this, gr, cp, response, done_and_cleanup](
                          const Status& fi_status, InstanceRec* ir) {
                        if (fi_status.ok()) {
                          mutex_lock l(ir->out_mu);
                          ir->WaitForOutMu(l);
                          response->set_instance_key(cp->instance.instance_key);
                          response->set_source_rank(ir->source_rank);
                          done_and_cleanup(fi_status);
                        } else {
                          done_and_cleanup(fi_status);
                        }
                      });
                } else {
                  done_and_cleanup(ci_status);
                }
              });
        } else {
          done_and_cleanup(cg_status);
        }
      });
}

bool CollectiveParamResolverDistributed::GroupIsCached(int32 group_key) {
  mutex_lock l(group_mu_);
  const auto& it = group_table_.find(group_key);
  return it != group_table_.end();
}

Status CollectiveParamResolverDistributed::UpdateGroupCache(
    const CompleteGroupResponse& resp) {
  // Build a new record from resp.
  std::unique_ptr<GroupRec> gr(new GroupRec);
  mutex_lock grl(gr->mu);
  gr->group.device_type = DeviceType(resp.device_type());
  gr->group.group_key = resp.group_key();
  gr->group.group_size = resp.group_size();
  gr->group.num_tasks = resp.num_tasks();
  if (resp.device_name_size() != gr->group.group_size) {
    return errors::Internal(
        "CompleteGroupResponse group_size doesn't match device_name list");
  }
  for (const string& dn : resp.device_name()) {
    gr->device_set.insert(dn);
    gr->device_list.push_back(dn);
  }
  if (resp.task_name_size() != gr->group.group_size) {
    return errors::Internal(
        "CompleteGroupResponse group_size doesn't match task_name list");
  }
  for (const string& tn : resp.task_name()) {
    gr->task_list.push_back(tn);
    gr->task_set.insert(tn);
  }
  CHECK_EQ(gr->task_set.size(), gr->group.num_tasks);
  {
    // Group membership should never change. Once a record is in group_table_
    // it never gets removed.
    mutex_lock l(group_mu_);
    auto it = group_table_.find(gr->group.group_key);
    if (it == group_table_.end()) {
      group_table_[gr->group.group_key] = std::move(gr);
    }
  }
  return Status::OK();
}

void CollectiveParamResolverDistributed::CompleteGroupDistributed(
    const string& device, CollectiveParams* cp, CancellationManager* cancel_mgr,
    const GroupRecCallback& done) {
  VLOG(1) << "CompleteGroupDistributed group_key=" << cp->group.group_key
          << " dev: " << device << " is_leader=" << (group_leader_.empty());
  if (group_leader_.empty()) {
    // This is the group leader, so resolution is local.
    return CompleteGroupLocal(device, cp, done);
  } else if (!GroupIsCached(cp->group.group_key)) {
    // Need to update Group cache from the leader.
    CompleteGroupCall* call = new CompleteGroupCall(
        cp->group, device, cancel_mgr, group_leader_, worker_cache_);
    call->Start([this, device, cp, call, done](const Status& s) {
      if (s.ok()) {
        Status status = UpdateGroupCache(call->resp_);
        if (status.ok()) {
          CompleteGroupLocal(device, cp, done);
        } else {
          done(status, nullptr);
        }
      } else {
        done(s, nullptr);
      }
      delete call;
    });
    return;
  } else {
    return CompleteGroupLocal(device, cp, done);
  }
}

bool CollectiveParamResolverDistributed::InstanceIsCached(int32 instance_key) {
  mutex_lock l(instance_mu_);
  const auto& it = instance_table_.find(instance_key);
  return it != instance_table_.end();
}

void CollectiveParamResolverDistributed::UpdateInstanceCache(
    const GroupRec* gr, CollectiveParams* cp,
    const CompleteInstanceResponse& resp, const StatusCallback& done) {
  Notification note;
  InstanceRec* ir = nullptr;
  int32 source_rank = resp.source_rank();

  auto continue_with_ir = [this, cp, &ir, source_rank, done](const Status& s) {
    if (!s.ok()) {
      done(s);
      return;
    }
    Status status;
    do {
      mutex_lock l(ir->out_mu);
      ir->WaitForOutMu(l);
      if (ir->source_rank != source_rank) {
        if (ir->source_rank >= 0) {
          ir->status = errors::Internal(
              "UpdateInstanceCache: CompleteInstanceResponse for instance ",
              cp->instance.instance_key, " gives source_rank=", source_rank,
              " but cache already holds value=", ir->source_rank);
          status = ir->status;
          break;
        }
        ir->source_rank = source_rank;
      }
      if (ir->known_count < cp->group.group_size) {
        ir->known_count = cp->group.group_size;
        if (ir->known.size() != cp->group.group_size) {
          ir->status = errors::Internal(
              "UpdateInstanceCache:: CompleteInstanceResponse for instance ",
              cp->instance.instance_key, " has known.size()=", ir->known.size(),
              " < group_size=", cp->group.group_size);
          status = ir->status;
          break;
        }
        for (int i = 0; i < ir->known.size(); ++i) {
          ir->known[i] = true;
        }
      }
      status = ir->status;
    } while (false);
    // Callback outside of lock.
    done(status);
  };

  FindInstanceRec(
      gr, cp, [this, &ir, continue_with_ir](const Status s, InstanceRec* irec) {
        ir = irec;
        continue_with_ir(s);
      });
}

void CollectiveParamResolverDistributed::CompleteInstanceDistributed(
    const string& device, const GroupRec* gr, CollectiveParams* cp,
    CancellationManager* cancel_mgr, const StatusCallback& done) {
  if (group_leader_.empty()) {
    // This is the group leader so resolution is local.
    return CompleteInstanceLocal(device, gr, cp, cp->is_source, done);
  } else if (InstanceIsCached(cp->instance.instance_key)) {
    return CompleteInstanceLocal(device, gr, cp, cp->is_source, done);
  } else {
    CompleteInstanceCall* call = new CompleteInstanceCall(
        cp->group, cp->instance, cp->name, device, cp->is_source, cancel_mgr,
        group_leader_, worker_cache_);
    call->Start([this, device, gr, cp, call, done](const Status& s) {
      if (s.ok()) {
        UpdateInstanceCache(
            gr, cp, call->resp_, [this, device, gr, cp, done](const Status& s) {
              if (!s.ok()) {
                done(s);
              } else {
                CompleteInstanceLocal(device, gr, cp, cp->is_source, done);
              }
            });
      } else {
        done(s);
      }
      delete call;
    });
    return;
  }
}

}  // namespace tensorflow
<commit_msg>Do not capture variables that may be destroyed before callback finishes.<commit_after>/* Copyright 2018 The TensorFlow Authors. All Rights Reserved.

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

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

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

#include "tensorflow/core/distributed_runtime/cancellable_call.h"
#include "tensorflow/core/distributed_runtime/device_resolver_distributed.h"
#include "tensorflow/core/distributed_runtime/worker_cache.h"
#include "tensorflow/core/protobuf/config.pb.h"

namespace tensorflow {
namespace {

class CompleteGroupCall : public CancellableCall {
 public:
  CompleteGroupCall(const CollGroupParams& group, const string& device_name,
                    CancellationManager* cancel_mgr,
                    const string& remote_worker, WorkerCacheInterface* wc)
      : CancellableCall(cancel_mgr, remote_worker, wc) {
    req_.set_group_key(group.group_key);
    req_.set_group_size(group.group_size);
    req_.set_device_type(group.device_type.type_string());
    req_.add_device_name(device_name);
  }
  ~CompleteGroupCall() override {}

  void IssueCall(const StatusCallback& done) override {
    wi_->CompleteGroupAsync(&opts_, &req_, &resp_, done);
  }

  CompleteGroupRequest req_;
  CompleteGroupResponse resp_;
};

class CompleteInstanceCall : public CancellableCall {
 public:
  CompleteInstanceCall(const CollGroupParams& group,
                       const CollInstanceParams& instance,
                       const string& node_name, const string& device_name,
                       bool is_source, CancellationManager* cancel_mgr,
                       const string& remote_worker, WorkerCacheInterface* wc)
      : CancellableCall(cancel_mgr, remote_worker, wc) {
    req_.set_name(node_name);
    req_.set_type(instance.type);
    req_.set_data_type(instance.data_type);
    instance.shape.AsProto(req_.mutable_shape());
    req_.set_group_key(group.group_key);
    req_.set_group_size(group.group_size);
    req_.set_instance_key(instance.instance_key);
    req_.set_device_type(group.device_type.type_string());
    for (int32 offset : instance.impl_details.subdiv_offsets) {
      req_.add_subdiv_offset(offset);
    }
    req_.set_device(device_name);
    req_.set_is_source(is_source);
  }

  ~CompleteInstanceCall() override {}

  void IssueCall(const StatusCallback& done) override {
    wi_->CompleteInstanceAsync(&opts_, &req_, &resp_, done);
  }

  CompleteInstanceRequest req_;
  CompleteInstanceResponse resp_;
};

}  // namespace

CollectiveParamResolverDistributed::CollectiveParamResolverDistributed(
    const ConfigProto& config, const DeviceMgr* dev_mgr,
    DeviceResolverDistributed* dev_resolver, WorkerCacheInterface* worker_cache,
    const string& task_name)
    : CollectiveParamResolverLocal(dev_mgr, dev_resolver, task_name),
      worker_cache_(worker_cache),
      group_leader_(task_name == config.experimental().collective_group_leader()
                        ? ""
                        : config.experimental().collective_group_leader()) {}

void CollectiveParamResolverDistributed::CompleteParamsAsync(
    const string& device, CollectiveParams* cp, CancellationManager* cancel_mgr,
    const StatusCallback& done) {
  CompleteGroupDistributed(device, cp, cancel_mgr,
                           [this, device, cp, cancel_mgr, done](
                               const Status& s, const GroupRec* gr) {
                             if (s.ok()) {
                               CompleteInstanceDistributed(device, gr, cp,
                                                           cancel_mgr, done);
                             } else {
                               done(s);
                             }
                           });
}

void CollectiveParamResolverDistributed::CompleteGroupAsync(
    const CompleteGroupRequest* request, CompleteGroupResponse* response,
    CancellationManager* cancel_mgr, const StatusCallback& done) {
  CollectiveParams cp;
  cp.group.group_key = request->group_key();
  cp.group.group_size = request->group_size();
  cp.group.device_type = DeviceType(request->device_type());
  for (const string& dn : request->device_name()) {
    cp.instance.device_names.push_back(dn);
  }
  CompleteGroupDistributed(
      cp.instance.device_names[0], &cp, cancel_mgr,
      [this, response, done](const Status& s, const GroupRec* gr) {
        if (s.ok()) {
          mutex_lock l(gr->mu);
          response->set_group_key(gr->group.group_key);
          response->set_group_size(gr->group.group_size);
          response->set_device_type(gr->group.device_type.type_string());
          response->set_num_tasks(gr->task_set.size());
          for (const string& dn : gr->device_list) {
            response->add_device_name(dn);
          }
          for (const string& tn : gr->task_list) {
            response->add_task_name(tn);
          }
        } else {
          LOG(ERROR) << "Bad status from CompleteGroupDistributed: " << s;
        }
        done(s);
      });
}

void CollectiveParamResolverDistributed::CompleteInstanceAsync(
    const CompleteInstanceRequest* request, CompleteInstanceResponse* response,
    CancellationManager* cancel_mgr, const StatusCallback& done) {
  CollectiveParams* cp = new CollectiveParams;
  cp->name = request->name();
  cp->group.group_key = request->group_key();
  cp->group.group_size = request->group_size();
  cp->group.device_type = DeviceType(request->device_type());
  cp->instance.type = CollectiveType(request->type());
  cp->instance.instance_key = request->instance_key();
  cp->instance.data_type = request->data_type();
  cp->instance.shape = TensorShape(request->shape());
  for (int32 offset : request->subdiv_offset()) {
    cp->instance.impl_details.subdiv_offsets.push_back(offset);
  }
  string* device = new string(request->device());
  VLOG(1) << "New cp " << cp << " for device " << *device << " : "
          << cp->ToString();
  StatusCallback done_and_cleanup = [this, cp, device, done](const Status& s) {
    done(s);
    delete cp;
    delete device;
  };
  // Start by completing the group.
  CompleteGroupDistributed(
      *device, cp, cancel_mgr,
      [this, cp, device, response, cancel_mgr, done_and_cleanup](
          const Status& cg_status, const GroupRec* gr) {
        if (cg_status.ok()) {
          // Then complete the instance.
          CompleteInstanceDistributed(
              *device, gr, cp, cancel_mgr,
              [this, gr, cp, response,
               done_and_cleanup](const Status& ci_status) {
                if (ci_status.ok()) {
                  // Now source_rank should be known, so
                  // retrieve it.
                  FindInstanceRec(
                      gr, cp,
                      [this, gr, cp, response, done_and_cleanup](
                          const Status& fi_status, InstanceRec* ir) {
                        if (fi_status.ok()) {
                          mutex_lock l(ir->out_mu);
                          ir->WaitForOutMu(l);
                          response->set_instance_key(cp->instance.instance_key);
                          response->set_source_rank(ir->source_rank);
                          done_and_cleanup(fi_status);
                        } else {
                          done_and_cleanup(fi_status);
                        }
                      });
                } else {
                  done_and_cleanup(ci_status);
                }
              });
        } else {
          done_and_cleanup(cg_status);
        }
      });
}

bool CollectiveParamResolverDistributed::GroupIsCached(int32 group_key) {
  mutex_lock l(group_mu_);
  const auto& it = group_table_.find(group_key);
  return it != group_table_.end();
}

Status CollectiveParamResolverDistributed::UpdateGroupCache(
    const CompleteGroupResponse& resp) {
  // Build a new record from resp.
  std::unique_ptr<GroupRec> gr(new GroupRec);
  mutex_lock grl(gr->mu);
  gr->group.device_type = DeviceType(resp.device_type());
  gr->group.group_key = resp.group_key();
  gr->group.group_size = resp.group_size();
  gr->group.num_tasks = resp.num_tasks();
  if (resp.device_name_size() != gr->group.group_size) {
    return errors::Internal(
        "CompleteGroupResponse group_size doesn't match device_name list");
  }
  for (const string& dn : resp.device_name()) {
    gr->device_set.insert(dn);
    gr->device_list.push_back(dn);
  }
  if (resp.task_name_size() != gr->group.group_size) {
    return errors::Internal(
        "CompleteGroupResponse group_size doesn't match task_name list");
  }
  for (const string& tn : resp.task_name()) {
    gr->task_list.push_back(tn);
    gr->task_set.insert(tn);
  }
  CHECK_EQ(gr->task_set.size(), gr->group.num_tasks);
  {
    // Group membership should never change. Once a record is in group_table_
    // it never gets removed.
    mutex_lock l(group_mu_);
    auto it = group_table_.find(gr->group.group_key);
    if (it == group_table_.end()) {
      group_table_[gr->group.group_key] = std::move(gr);
    }
  }
  return Status::OK();
}

void CollectiveParamResolverDistributed::CompleteGroupDistributed(
    const string& device, CollectiveParams* cp, CancellationManager* cancel_mgr,
    const GroupRecCallback& done) {
  VLOG(1) << "CompleteGroupDistributed group_key=" << cp->group.group_key
          << " dev: " << device << " is_leader=" << (group_leader_.empty());
  if (group_leader_.empty()) {
    // This is the group leader, so resolution is local.
    return CompleteGroupLocal(device, cp, done);
  } else if (!GroupIsCached(cp->group.group_key)) {
    // Need to update Group cache from the leader.
    CompleteGroupCall* call = new CompleteGroupCall(
        cp->group, device, cancel_mgr, group_leader_, worker_cache_);
    call->Start([this, device, cp, call, done](const Status& s) {
      if (s.ok()) {
        Status status = UpdateGroupCache(call->resp_);
        if (status.ok()) {
          CompleteGroupLocal(device, cp, done);
        } else {
          done(status, nullptr);
        }
      } else {
        done(s, nullptr);
      }
      delete call;
    });
    return;
  } else {
    return CompleteGroupLocal(device, cp, done);
  }
}

bool CollectiveParamResolverDistributed::InstanceIsCached(int32 instance_key) {
  mutex_lock l(instance_mu_);
  const auto& it = instance_table_.find(instance_key);
  return it != instance_table_.end();
}

void CollectiveParamResolverDistributed::UpdateInstanceCache(
    const GroupRec* gr, CollectiveParams* cp,
    const CompleteInstanceResponse& resp, const StatusCallback& done) {
  using InstanceRecPointer = InstanceRec*;
  InstanceRecPointer* irp = new InstanceRecPointer(nullptr);
  int32 source_rank = resp.source_rank();

  auto continue_with_ir = [this, cp, irp, source_rank, done](const Status& s) {
    if (!s.ok()) {
      done(s);
      delete irp;
      return;
    }
    Status status;
    InstanceRec* ir = *irp;
    do {
      mutex_lock l(ir->out_mu);
      ir->WaitForOutMu(l);
      if (ir->source_rank != source_rank) {
        if (ir->source_rank >= 0) {
          ir->status = errors::Internal(
              "UpdateInstanceCache: CompleteInstanceResponse for instance ",
              cp->instance.instance_key, " gives source_rank=", source_rank,
              " but cache already holds value=", ir->source_rank);
          status = ir->status;
          break;
        }
        ir->source_rank = source_rank;
      }
      if (ir->known_count < cp->group.group_size) {
        ir->known_count = cp->group.group_size;
        if (ir->known.size() != cp->group.group_size) {
          ir->status = errors::Internal(
              "UpdateInstanceCache:: CompleteInstanceResponse for instance ",
              cp->instance.instance_key, " has known.size()=", ir->known.size(),
              " < group_size=", cp->group.group_size);
          status = ir->status;
          break;
        }
        for (int i = 0; i < ir->known.size(); ++i) {
          ir->known[i] = true;
        }
      }
      status = ir->status;
    } while (false);
    // Callback outside of lock.
    done(status);
    delete irp;
  };

  FindInstanceRec(
      gr, cp, [this, irp, continue_with_ir](const Status s, InstanceRec* irec) {
        *irp = irec;
        continue_with_ir(s);
      });
}

void CollectiveParamResolverDistributed::CompleteInstanceDistributed(
    const string& device, const GroupRec* gr, CollectiveParams* cp,
    CancellationManager* cancel_mgr, const StatusCallback& done) {
  if (group_leader_.empty()) {
    // This is the group leader so resolution is local.
    return CompleteInstanceLocal(device, gr, cp, cp->is_source, done);
  } else if (InstanceIsCached(cp->instance.instance_key)) {
    return CompleteInstanceLocal(device, gr, cp, cp->is_source, done);
  } else {
    CompleteInstanceCall* call = new CompleteInstanceCall(
        cp->group, cp->instance, cp->name, device, cp->is_source, cancel_mgr,
        group_leader_, worker_cache_);
    call->Start([this, device, gr, cp, call, done](const Status& s) {
      if (s.ok()) {
        UpdateInstanceCache(
            gr, cp, call->resp_, [this, device, gr, cp, done](const Status& s) {
              if (!s.ok()) {
                done(s);
              } else {
                CompleteInstanceLocal(device, gr, cp, cp->is_source, done);
              }
            });
      } else {
        done(s);
      }
      delete call;
    });
    return;
  }
}

}  // namespace tensorflow
<|endoftext|>


<commit_before>/* This file is part of Ingen.
 * Copyright (C) 2007-2009 Dave Robillard <http://drobilla.net>
 *
 * Ingen is free software; you can redistribute it and/or modify it under the
 * terms of the GNU General Public License as published by the Free Software
 * Foundation; either version 2 of the License, or (at your option) any later
 * version.
 *
 * Ingen is distributed in the hope that it will be useful, but HAVEOUT ANY
 * WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
 * FOR A PARTICULAR PURPOSE.  See the GNU General Public License for details.
 *
 * You should have received a copy of the GNU General Public License along
 * with this program; if not, write to the Free Software Foundation, Inc.,
 * 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
 */

#include "ingen-config.h"
#include "raul/SharedPtr.hpp"
#include "module/Module.hpp"
#include "module/World.hpp"
#ifdef HAVE_LIBLO
#include "OSCEngineSender.hpp"
#endif
#ifdef HAVE_SOUP
#include "HTTPEngineSender.hpp"
#endif

using namespace Ingen;

#ifdef HAVE_LIBLO
SharedPtr<Ingen::Shared::EngineInterface>
new_osc_interface(Ingen::Shared::World* world, const std::string& url)
{
	Client::OSCEngineSender* oes = Client::OSCEngineSender::create(url);
	oes->attach(rand(), true);
	return SharedPtr<Shared::EngineInterface>(oes);
}
#endif

#ifdef HAVE_SOUP
SharedPtr<Ingen::Shared::EngineInterface>
new_http_interface(Ingen::Shared::World* world, const std::string& url)
{
	Client::HTTPEngineSender* hes = new Client::HTTPEngineSender(world, url);
	hes->attach(rand(), true);
	return SharedPtr<Shared::EngineInterface>(hes);
}
#endif

struct IngenClientModule : public Ingen::Shared::Module {
	void load(Ingen::Shared::World* world) {
		world->add_interface_factory("osc.udp", &new_osc_interface);
		world->add_interface_factory("osc.tcp", &new_osc_interface);
		world->add_interface_factory("http",    &new_http_interface);
	}
};

static IngenClientModule* module = NULL;

extern "C" {

Ingen::Shared::Module*
ingen_module_load() {
	if (!module)
		module = new IngenClientModule();

	return module;
}

} // extern "C"

<commit_msg>Fix compilation without liblo and/or without libsoup.<commit_after>/* This file is part of Ingen.
 * Copyright (C) 2007-2009 Dave Robillard <http://drobilla.net>
 *
 * Ingen is free software; you can redistribute it and/or modify it under the
 * terms of the GNU General Public License as published by the Free Software
 * Foundation; either version 2 of the License, or (at your option) any later
 * version.
 *
 * Ingen is distributed in the hope that it will be useful, but HAVEOUT ANY
 * WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
 * FOR A PARTICULAR PURPOSE.  See the GNU General Public License for details.
 *
 * You should have received a copy of the GNU General Public License along
 * with this program; if not, write to the Free Software Foundation, Inc.,
 * 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
 */

#include "ingen-config.h"
#include "raul/SharedPtr.hpp"
#include "module/Module.hpp"
#include "module/World.hpp"
#ifdef HAVE_LIBLO
#include "OSCEngineSender.hpp"
#endif
#ifdef HAVE_SOUP
#include "HTTPEngineSender.hpp"
#endif

using namespace Ingen;

#ifdef HAVE_LIBLO
SharedPtr<Ingen::Shared::EngineInterface>
new_osc_interface(Ingen::Shared::World* world, const std::string& url)
{
	Client::OSCEngineSender* oes = Client::OSCEngineSender::create(url);
	oes->attach(rand(), true);
	return SharedPtr<Shared::EngineInterface>(oes);
}
#endif

#ifdef HAVE_SOUP
SharedPtr<Ingen::Shared::EngineInterface>
new_http_interface(Ingen::Shared::World* world, const std::string& url)
{
	Client::HTTPEngineSender* hes = new Client::HTTPEngineSender(world, url);
	hes->attach(rand(), true);
	return SharedPtr<Shared::EngineInterface>(hes);
}
#endif

struct IngenClientModule : public Ingen::Shared::Module {
	void load(Ingen::Shared::World* world) {
#ifdef HAVE_LIBLO
		world->add_interface_factory("osc.udp", &new_osc_interface);
		world->add_interface_factory("osc.tcp", &new_osc_interface);
#endif
#ifdef HAVE_SOUP
		world->add_interface_factory("http",    &new_http_interface);
#endif
	}
};

static IngenClientModule* module = NULL;

extern "C" {

Ingen::Shared::Module*
ingen_module_load() {
	if (!module)
		module = new IngenClientModule();

	return module;
}

} // extern "C"

<|endoftext|>


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

The Medical Imaging Interaction Toolkit (MITK)

Copyright (c) German Cancer Research Center,
Division of Medical and Biological Informatics.
All rights reserved.

This software is distributed WITHOUT ANY WARRANTY; without
even the implied warranty of MERCHANTABILITY or FITNESS FOR
A PARTICULAR PURPOSE.

See LICENSE.txt or http://www.mitk.org for details.

===================================================================*/
#include <mitkContourModelMapper3D.h>

#include <vtkPoints.h>
#include <vtkCellArray.h>
#include <vtkProperty.h>

mitk::ContourModelMapper3D::ContourModelMapper3D()
{
}

mitk::ContourModelMapper3D::~ContourModelMapper3D()
{
}

const mitk::ContourModel* mitk::ContourModelMapper3D::GetInput( void )
{
  //convient way to get the data from the dataNode
  return static_cast< const mitk::ContourModel * >( this->GetData() );
}

vtkProp* mitk::ContourModelMapper3D::GetVtkProp(mitk::BaseRenderer* renderer)
{
  //return the actor corresponding to the renderer
  return m_LSH.GetLocalStorage(renderer)->m_Actor;
}

void mitk::ContourModelMapper3D::MitkRenderOverlay(BaseRenderer* renderer)
{
  if ( this->IsVisible(renderer)==false )
    return;
  if ( this->GetVtkProp(renderer)->GetVisibility() )
  {
    this->GetVtkProp(renderer)->RenderOverlay(renderer->GetVtkRenderer());
  }
}

void mitk::ContourModelMapper3D::MitkRenderOpaqueGeometry(BaseRenderer* renderer)
{
  if ( this->IsVisible( renderer )==false )
    return;
  if ( this->GetVtkProp(renderer)->GetVisibility() )
  {
    this->GetVtkProp(renderer)->RenderOpaqueGeometry( renderer->GetVtkRenderer() );
  }
}

void mitk::ContourModelMapper3D::MitkRenderTranslucentGeometry(BaseRenderer* renderer)
{
  if ( this->IsVisible(renderer)==false )
    return;
  if ( this->GetVtkProp(renderer)->GetVisibility() )
  {
    this->GetVtkProp(renderer)->RenderTranslucentPolygonalGeometry(renderer->GetVtkRenderer());
  }
}

void mitk::ContourModelMapper3D::MitkRenderVolumetricGeometry(BaseRenderer* renderer)
{
  if(IsVisible(renderer)==false)
    return;
  if ( GetVtkProp(renderer)->GetVisibility() )
  {
    this->GetVtkProp(renderer)->RenderVolumetricGeometry(renderer->GetVtkRenderer());
  }
}

void mitk::ContourModelMapper3D::GenerateDataForRenderer( mitk::BaseRenderer *renderer )
{
  /* First convert the contourModel to vtkPolyData, then tube filter it and
   * set it input for our mapper
   */

  LocalStorage *localStorage = m_LSH.GetLocalStorage(renderer);

  mitk::ContourModel* inputContour  = static_cast< mitk::ContourModel* >( this->GetData() );

  localStorage->m_OutlinePolyData = this->CreateVtkPolyDataFromContour(inputContour);

  this->ApplyContourProperties(renderer);

  //tube filter the polyData
  localStorage->m_TubeFilter->SetInput(localStorage->m_OutlinePolyData);
  localStorage->m_TubeFilter->SetRadius(0.2);
  localStorage->m_TubeFilter->Update();
  localStorage->m_Mapper->SetInput(localStorage->m_TubeFilter->GetOutput());

}

void mitk::ContourModelMapper3D::Update(mitk::BaseRenderer* renderer)
{
  if ( !this->IsVisible( renderer ) )
  {
    return;
  }

  mitk::ContourModel* data  = static_cast< mitk::ContourModel*>( this->GetData() );
  if ( data == NULL )
  {
    return;
  }

  // Calculate time step of the input data for the specified renderer (integer value)
  this->CalculateTimeStep( renderer );

  // Check if time step is valid
  const TimeSlicedGeometry *dataTimeGeometry = data->GetTimeSlicedGeometry();
  if ( ( dataTimeGeometry == NULL )
    || ( dataTimeGeometry->GetTimeSteps() == 0 )
    || ( !dataTimeGeometry->IsValidTime( this->GetTimestep() ) ) )
  {
    return;
  }

  const DataNode *node = this->GetDataNode();
  data->UpdateOutputInformation();
  LocalStorage *localStorage = m_LSH.GetLocalStorage(renderer);

  //check if something important has changed and we need to rerender
  if ( (localStorage->m_LastUpdateTime < node->GetMTime()) //was the node modified?
    || (localStorage->m_LastUpdateTime < data->GetPipelineMTime()) //Was the data modified?
    || (localStorage->m_LastUpdateTime < renderer->GetCurrentWorldGeometry2DUpdateTime()) //was the geometry modified?
    || (localStorage->m_LastUpdateTime < renderer->GetCurrentWorldGeometry2D()->GetMTime())
    || (localStorage->m_LastUpdateTime < node->GetPropertyList()->GetMTime()) //was a property modified?
    || (localStorage->m_LastUpdateTime < node->GetPropertyList(renderer)->GetMTime()) )
  {
    this->GenerateDataForRenderer( renderer );
  }

  // since we have checked that nothing important has changed, we can set
  // m_LastUpdateTime to the current time
  localStorage->m_LastUpdateTime.Modified();
}

vtkSmartPointer<vtkPolyData> mitk::ContourModelMapper3D::CreateVtkPolyDataFromContour(mitk::ContourModel* inputContour)
{
  //the points to draw
  vtkSmartPointer<vtkPoints> points = vtkSmartPointer<vtkPoints>::New();
  //the lines to connect the points
  vtkSmartPointer<vtkCellArray> lines = vtkSmartPointer<vtkCellArray>::New();

  //iterate over the control points
  mitk::ContourModel::VertexIterator current = inputContour->IteratorBegin();
  mitk::ContourModel::VertexIterator next = inputContour->IteratorBegin();
  next++;

  mitk::ContourModel::VertexIterator end = inputContour->IteratorEnd();

  while(next != end)
  {
    mitk::ContourModel::VertexType* currentControlPoint = *current;
    mitk::ContourModel::VertexType* nextControlPoint = *next;

    vtkIdType p1 = points->InsertNextPoint(currentControlPoint->Coordinates[0], currentControlPoint->Coordinates[1], currentControlPoint->Coordinates[2]);
    vtkIdType p2 = points->InsertNextPoint(nextControlPoint->Coordinates[0], nextControlPoint->Coordinates[1], nextControlPoint->Coordinates[2]);
    //add the line between both contorlPoints
    lines->InsertNextCell(2);
    lines->InsertCellPoint(p1);
    lines->InsertCellPoint(p2);

    current++;
    next++;
  }

  if(inputContour->IsClosed())
  {
    // If the contour is closed add a line from the last to the first control point
    mitk::ContourModel::VertexType* firstControlPoint = *(inputContour->IteratorBegin());
    mitk::ContourModel::VertexType* lastControlPoint = *(--(inputContour->IteratorEnd()));
    vtkIdType p2 = points->InsertNextPoint(lastControlPoint->Coordinates[0], lastControlPoint->Coordinates[1], lastControlPoint->Coordinates[2]);
    vtkIdType p1 = points->InsertNextPoint(firstControlPoint->Coordinates[0], firstControlPoint->Coordinates[1], firstControlPoint->Coordinates[2]);

    //add the line to the cellArray
    lines->InsertNextCell(2);
    lines->InsertCellPoint(p1);
    lines->InsertCellPoint(p2);
  }

  // Create a polydata to store everything in
  vtkSmartPointer<vtkPolyData> polyData = vtkSmartPointer<vtkPolyData>::New();
  // Add the points to the dataset
  polyData->SetPoints(points);
  // Add the lines to the dataset
  polyData->SetLines(lines);

  return polyData;
}

void mitk::ContourModelMapper3D::ApplyContourProperties(mitk::BaseRenderer* renderer)
{
  LocalStorage *localStorage = m_LSH.GetLocalStorage(renderer);

  float binaryOutlineWidth(1.0);
  if (this->GetDataNode()->GetFloatProperty( "contour width", binaryOutlineWidth, renderer ))
  {
    localStorage->m_Actor->GetProperty()->SetLineWidth(binaryOutlineWidth);
  }

  localStorage->m_Actor->GetProperty()->SetColor(0.9, 1.0, 0.1);
}

/*+++++++++++++++++++ LocalStorage part +++++++++++++++++++++++++*/

mitk::ContourModelMapper3D::LocalStorage* mitk::ContourModelMapper3D::GetLocalStorage(mitk::BaseRenderer* renderer)
{
  return m_LSH.GetLocalStorage(renderer);
}

mitk::ContourModelMapper3D::LocalStorage::LocalStorage()
{
  m_Mapper = vtkSmartPointer<vtkPolyDataMapper>::New();
  m_Actor = vtkSmartPointer<vtkActor>::New();
  m_OutlinePolyData = vtkSmartPointer<vtkPolyData>::New();
  m_TubeFilter = vtkSmartPointer<vtkTubeFilter>::New();

  //set the mapper for the actor
  m_Actor->SetMapper(m_Mapper);
}

void mitk::ContourModelMapper3D::SetDefaultProperties(mitk::DataNode* node, mitk::BaseRenderer* renderer, bool overwrite)
{
  node->AddProperty( "color", ColorProperty::New(1.0,0.0,0.0), renderer, overwrite );
  node->AddProperty( "contour width", mitk::FloatProperty::New( 1.0 ), renderer, overwrite );

  Superclass::SetDefaultProperties(node, renderer, overwrite);
}<commit_msg>support timesteps in 3d<commit_after>/*===================================================================

The Medical Imaging Interaction Toolkit (MITK)

Copyright (c) German Cancer Research Center,
Division of Medical and Biological Informatics.
All rights reserved.

This software is distributed WITHOUT ANY WARRANTY; without
even the implied warranty of MERCHANTABILITY or FITNESS FOR
A PARTICULAR PURPOSE.

See LICENSE.txt or http://www.mitk.org for details.

===================================================================*/
#include <mitkContourModelMapper3D.h>

#include <vtkPoints.h>
#include <vtkCellArray.h>
#include <vtkProperty.h>

mitk::ContourModelMapper3D::ContourModelMapper3D()
{
}

mitk::ContourModelMapper3D::~ContourModelMapper3D()
{
}

const mitk::ContourModel* mitk::ContourModelMapper3D::GetInput( void )
{
  //convient way to get the data from the dataNode
  return static_cast< const mitk::ContourModel * >( this->GetData() );
}

vtkProp* mitk::ContourModelMapper3D::GetVtkProp(mitk::BaseRenderer* renderer)
{
  //return the actor corresponding to the renderer
  return m_LSH.GetLocalStorage(renderer)->m_Actor;
}

void mitk::ContourModelMapper3D::MitkRenderOverlay(BaseRenderer* renderer)
{
  if ( this->IsVisible(renderer)==false )
    return;
  if ( this->GetVtkProp(renderer)->GetVisibility() )
  {
    this->GetVtkProp(renderer)->RenderOverlay(renderer->GetVtkRenderer());
  }
}

void mitk::ContourModelMapper3D::MitkRenderOpaqueGeometry(BaseRenderer* renderer)
{
  if ( this->IsVisible( renderer )==false )
    return;
  if ( this->GetVtkProp(renderer)->GetVisibility() )
  {
    this->GetVtkProp(renderer)->RenderOpaqueGeometry( renderer->GetVtkRenderer() );
  }
}

void mitk::ContourModelMapper3D::MitkRenderTranslucentGeometry(BaseRenderer* renderer)
{
  if ( this->IsVisible(renderer)==false )
    return;
  if ( this->GetVtkProp(renderer)->GetVisibility() )
  {
    this->GetVtkProp(renderer)->RenderTranslucentPolygonalGeometry(renderer->GetVtkRenderer());
  }
}

void mitk::ContourModelMapper3D::MitkRenderVolumetricGeometry(BaseRenderer* renderer)
{
  if(IsVisible(renderer)==false)
    return;
  if ( GetVtkProp(renderer)->GetVisibility() )
  {
    this->GetVtkProp(renderer)->RenderVolumetricGeometry(renderer->GetVtkRenderer());
  }
}

void mitk::ContourModelMapper3D::GenerateDataForRenderer( mitk::BaseRenderer *renderer )
{
  /* First convert the contourModel to vtkPolyData, then tube filter it and
   * set it input for our mapper
   */

  LocalStorage *localStorage = m_LSH.GetLocalStorage(renderer);

  mitk::ContourModel* inputContour  = static_cast< mitk::ContourModel* >( this->GetData() );

  localStorage->m_OutlinePolyData = this->CreateVtkPolyDataFromContour(inputContour);

  this->ApplyContourProperties(renderer);

  //tube filter the polyData
  localStorage->m_TubeFilter->SetInput(localStorage->m_OutlinePolyData);
  localStorage->m_TubeFilter->SetRadius(0.2);
  localStorage->m_TubeFilter->Update();
  localStorage->m_Mapper->SetInput(localStorage->m_TubeFilter->GetOutput());

}

void mitk::ContourModelMapper3D::Update(mitk::BaseRenderer* renderer)
{
  if ( !this->IsVisible( renderer ) )
  {
    return;
  }

  mitk::ContourModel* data  = static_cast< mitk::ContourModel*>( this->GetData() );
  if ( data == NULL )
  {
    return;
  }

  // Calculate time step of the input data for the specified renderer (integer value)
  this->CalculateTimeStep( renderer );

  // Check if time step is valid
  const TimeSlicedGeometry *dataTimeGeometry = data->GetTimeSlicedGeometry();
  if ( ( dataTimeGeometry == NULL )
    || ( dataTimeGeometry->GetTimeSteps() == 0 )
    || ( !dataTimeGeometry->IsValidTime( renderer->GetTimeStep() ) ) )
  {
    //clear the rendered polydata
    localStorage->m_Mapper->SetInput(vtkSmartPointer<vtkPolyData>::New());
    return;
  }

  const DataNode *node = this->GetDataNode();
  data->UpdateOutputInformation();
  LocalStorage *localStorage = m_LSH.GetLocalStorage(renderer);

  //check if something important has changed and we need to rerender
  if ( (localStorage->m_LastUpdateTime < node->GetMTime()) //was the node modified?
    || (localStorage->m_LastUpdateTime < data->GetPipelineMTime()) //Was the data modified?
    || (localStorage->m_LastUpdateTime < renderer->GetCurrentWorldGeometry2DUpdateTime()) //was the geometry modified?
    || (localStorage->m_LastUpdateTime < renderer->GetCurrentWorldGeometry2D()->GetMTime())
    || (localStorage->m_LastUpdateTime < node->GetPropertyList()->GetMTime()) //was a property modified?
    || (localStorage->m_LastUpdateTime < node->GetPropertyList(renderer)->GetMTime()) )
  {
    this->GenerateDataForRenderer( renderer );
  }

  // since we have checked that nothing important has changed, we can set
  // m_LastUpdateTime to the current time
  localStorage->m_LastUpdateTime.Modified();
}

vtkSmartPointer<vtkPolyData> mitk::ContourModelMapper3D::CreateVtkPolyDataFromContour(mitk::ContourModel* inputContour)
{
  unsigned int timestep = this->GetTimestep();

  //the points to draw
  vtkSmartPointer<vtkPoints> points = vtkSmartPointer<vtkPoints>::New();
  //the lines to connect the points
  vtkSmartPointer<vtkCellArray> lines = vtkSmartPointer<vtkCellArray>::New();

  //iterate over the control points
  mitk::ContourModel::VertexIterator current = inputContour->IteratorBegin(timestep);
  mitk::ContourModel::VertexIterator next = inputContour->IteratorBegin(timestep);
  next++;

  mitk::ContourModel::VertexIterator end = inputContour->IteratorEnd(timestep);

  while(next != end)
  {
    mitk::ContourModel::VertexType* currentControlPoint = *current;
    mitk::ContourModel::VertexType* nextControlPoint = *next;

    vtkIdType p1 = points->InsertNextPoint(currentControlPoint->Coordinates[0], currentControlPoint->Coordinates[1], currentControlPoint->Coordinates[2]);
    vtkIdType p2 = points->InsertNextPoint(nextControlPoint->Coordinates[0], nextControlPoint->Coordinates[1], nextControlPoint->Coordinates[2]);
    //add the line between both contorlPoints
    lines->InsertNextCell(2);
    lines->InsertCellPoint(p1);
    lines->InsertCellPoint(p2);

    current++;
    next++;
  }

  if(inputContour->IsClosed(timestep))
  {
    // If the contour is closed add a line from the last to the first control point
    mitk::ContourModel::VertexType* firstControlPoint = *(inputContour->IteratorBegin(timestep));
    mitk::ContourModel::VertexType* lastControlPoint = *(--(inputContour->IteratorEnd(timestep)));
    vtkIdType p2 = points->InsertNextPoint(lastControlPoint->Coordinates[0], lastControlPoint->Coordinates[1], lastControlPoint->Coordinates[2]);
    vtkIdType p1 = points->InsertNextPoint(firstControlPoint->Coordinates[0], firstControlPoint->Coordinates[1], firstControlPoint->Coordinates[2]);

    //add the line to the cellArray
    lines->InsertNextCell(2);
    lines->InsertCellPoint(p1);
    lines->InsertCellPoint(p2);
  }

  // Create a polydata to store everything in
  vtkSmartPointer<vtkPolyData> polyData = vtkSmartPointer<vtkPolyData>::New();
  // Add the points to the dataset
  polyData->SetPoints(points);
  // Add the lines to the dataset
  polyData->SetLines(lines);

  return polyData;
}

void mitk::ContourModelMapper3D::ApplyContourProperties(mitk::BaseRenderer* renderer)
{
  LocalStorage *localStorage = m_LSH.GetLocalStorage(renderer);

  float binaryOutlineWidth(1.0);
  if (this->GetDataNode()->GetFloatProperty( "contour width", binaryOutlineWidth, renderer ))
  {
    localStorage->m_Actor->GetProperty()->SetLineWidth(binaryOutlineWidth);
  }

  localStorage->m_Actor->GetProperty()->SetColor(0.9, 1.0, 0.1);
}

/*+++++++++++++++++++ LocalStorage part +++++++++++++++++++++++++*/

mitk::ContourModelMapper3D::LocalStorage* mitk::ContourModelMapper3D::GetLocalStorage(mitk::BaseRenderer* renderer)
{
  return m_LSH.GetLocalStorage(renderer);
}

mitk::ContourModelMapper3D::LocalStorage::LocalStorage()
{
  m_Mapper = vtkSmartPointer<vtkPolyDataMapper>::New();
  m_Actor = vtkSmartPointer<vtkActor>::New();
  m_OutlinePolyData = vtkSmartPointer<vtkPolyData>::New();
  m_TubeFilter = vtkSmartPointer<vtkTubeFilter>::New();

  //set the mapper for the actor
  m_Actor->SetMapper(m_Mapper);
}

void mitk::ContourModelMapper3D::SetDefaultProperties(mitk::DataNode* node, mitk::BaseRenderer* renderer, bool overwrite)
{
  node->AddProperty( "color", ColorProperty::New(1.0,0.0,0.0), renderer, overwrite );
  node->AddProperty( "contour width", mitk::FloatProperty::New( 1.0 ), renderer, overwrite );

  Superclass::SetDefaultProperties(node, renderer, overwrite);
}<|endoftext|>