<commit_before>/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
/*
 * This file is part of the LibreOffice project.
 *
 * This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/.
 */

#include <basegfx/polygon/b2dpolygon.hxx>
#include <drawinglayer/primitive2d/polygonprimitive2d.hxx>
#include <drawinglayer/primitive2d/polypolygonprimitive2d.hxx>
#include <drawinglayer/processor2d/baseprocessor2d.hxx>
#include <drawinglayer/processor2d/processorfromoutputdevice.hxx>
#include <sfx2/bindings.hxx>
#include <sfx2/dispatch.hxx>
#include <sfx2/infobar.hxx>
#include <sfx2/objsh.hxx>
#include <sfx2/sfx.hrc>
#include <sfx2/viewsh.hxx>
#include <vcl/svapp.hxx>
#include <vcl/settings.hxx>

using namespace std;
using namespace drawinglayer::geometry;
using namespace drawinglayer::processor2d;
using namespace drawinglayer::primitive2d;
using namespace drawinglayer::attribute;
using namespace drawinglayer::geometry;

namespace
{
    class SfxCloseButton : public PushButton
    {
        public:
            SfxCloseButton( vcl::Window* pParent ) : PushButton( pParent, 0 )
            {
            }

            virtual ~SfxCloseButton( ) { }

            virtual void Paint( const Rectangle& rRect ) SAL_OVERRIDE;
    };

    void SfxCloseButton::Paint( const Rectangle& )
    {
        const ViewInformation2D aNewViewInfos;
        const unique_ptr<BaseProcessor2D> pProcessor(
            createBaseProcessor2DFromOutputDevice(*this, aNewViewInfos));

        const Rectangle aRect(Point(0, 0), PixelToLogic(GetSizePixel()));

        Primitive2DSequence aSeq(2);

        basegfx::BColor aLightColor(1.0, 1.0, 191.0 / 255.0);
        basegfx::BColor aDarkColor(217.0 / 255.0, 217.0 / 255.0, 78.0 / 255.0);

        const StyleSettings& rSettings = Application::GetSettings().GetStyleSettings();
        if ( rSettings.GetHighContrastMode() )
        {
            aLightColor = rSettings.GetLightColor( ).getBColor( );
            aDarkColor = rSettings.GetDialogTextColor( ).getBColor( );

        }

        // Light background
        basegfx::B2DPolygon aPolygon;
        aPolygon.append( basegfx::B2DPoint( aRect.Left( ), aRect.Top( ) ) );
        aPolygon.append( basegfx::B2DPoint( aRect.Right( ), aRect.Top( ) ) );
        aPolygon.append( basegfx::B2DPoint( aRect.Right( ), aRect.Bottom( ) ) );
        aPolygon.append( basegfx::B2DPoint( aRect.Left( ), aRect.Bottom( ) ) );
        aPolygon.setClosed( true );
        PolyPolygonColorPrimitive2D* pBack = new PolyPolygonColorPrimitive2D(
                    basegfx::B2DPolyPolygon( aPolygon ), aLightColor );
        aSeq[0] = pBack;

        LineAttribute aLineAttribute(aDarkColor, 2.0);

        // Cross
        basegfx::B2DPolyPolygon aCross;
        basegfx::B2DPolygon aLine1;
        aLine1.append( basegfx::B2DPoint( aRect.Left(), aRect.Top( ) ) );
        aLine1.append( basegfx::B2DPoint( aRect.Right(), aRect.Bottom( ) ) );
        aCross.append( aLine1 );
        basegfx::B2DPolygon aLine2;
        aLine2.append( basegfx::B2DPoint( aRect.Right(), aRect.Top( ) ) );
        aLine2.append( basegfx::B2DPoint( aRect.Left(), aRect.Bottom( ) ) );
        aCross.append( aLine2 );

        PolyPolygonStrokePrimitive2D * pCross =
            new PolyPolygonStrokePrimitive2D(aCross, aLineAttribute, StrokeAttribute());

        aSeq[1] = pCross;

        pProcessor->process(aSeq);
    }
}

SfxInfoBarWindow::SfxInfoBarWindow( vcl::Window* pParent, const OUString& sId,
       const OUString& sMessage, vector<PushButton*> aButtons ) :
    Window(pParent, 0),
    m_sId(sId),
    m_pMessage(new FixedText(this, 0)),
    m_pCloseBtn(new SfxCloseButton(this)),
    m_aActionBtns()
{
    long nWidth = pParent->GetSizePixel().getWidth();
    SetPosSizePixel(Point(0, 0), Size(nWidth, 40));

    m_pMessage->SetText(sMessage);
    m_pMessage->SetBackground(Wallpaper(Color(255, 255, 191)));
    m_pMessage->Show();

    m_pCloseBtn->SetClickHdl(LINK(this, SfxInfoBarWindow, CloseHandler));
    m_pCloseBtn->Show();

    // Reparent the buttons and place them on the right of the bar
    vector<PushButton*>::iterator it;
    for (it = aButtons.begin(); it != aButtons.end(); ++it)
    {
        PushButton* pButton = *it;
        pButton->SetParent(this);
        pButton->Show();
        m_aActionBtns.push_back(pButton);
    }

    Resize();
}

SfxInfoBarWindow::~SfxInfoBarWindow()
{}

void SfxInfoBarWindow::Paint(const Rectangle& rPaintRect)
{
    const ViewInformation2D aNewViewInfos;
    const unique_ptr<BaseProcessor2D> pProcessor(
        createBaseProcessor2DFromOutputDevice(*this, aNewViewInfos));

    const Rectangle aRect(Point(0, 0), PixelToLogic(GetSizePixel()));

    Primitive2DSequence aSeq(2);

    basegfx::BColor aLightColor(1.0, 1.0, 191.0 / 255.0);
    basegfx::BColor aDarkColor(217.0 / 255.0, 217.0 / 255.0, 78.0 / 255.0);

    const StyleSettings& rSettings = Application::GetSettings().GetStyleSettings();
    if (rSettings.GetHighContrastMode())
    {
        aLightColor = rSettings.GetLightColor().getBColor();
        aDarkColor = rSettings.GetDialogTextColor().getBColor();
    }

    // Update the label background color
    m_pMessage->SetBackground(Wallpaper(Color(aLightColor)));

    // Light background
    basegfx::B2DPolygon aPolygon;
    aPolygon.append( basegfx::B2DPoint( aRect.Left( ), aRect.Top( ) ) );
    aPolygon.append( basegfx::B2DPoint( aRect.Right( ), aRect.Top( ) ) );
    aPolygon.append( basegfx::B2DPoint( aRect.Right( ), aRect.Bottom( ) ) );
    aPolygon.append( basegfx::B2DPoint( aRect.Left( ), aRect.Bottom( ) ) );
    aPolygon.setClosed(true);

    PolyPolygonColorPrimitive2D* pBack =
        new PolyPolygonColorPrimitive2D(basegfx::B2DPolyPolygon(aPolygon), aLightColor);
    aSeq[0] = pBack;

    LineAttribute aLineAttribute(aDarkColor, 1.0);

    // Bottom dark line
    basegfx::B2DPolygon aPolygonBottom;
    aPolygonBottom.append( basegfx::B2DPoint( aRect.Left(), aRect.Bottom( ) ) );
    aPolygonBottom.append( basegfx::B2DPoint( aRect.Right(), aRect.Bottom( ) ) );

    PolygonStrokePrimitive2D * pLineBottom =
            new PolygonStrokePrimitive2D (aPolygonBottom, aLineAttribute);

    aSeq[1] = pLineBottom;

    pProcessor->process(aSeq);

    Window::Paint(rPaintRect);
}

void SfxInfoBarWindow::Resize()
{
    long nWidth = GetSizePixel().getWidth();
    m_pCloseBtn->SetPosSizePixel(Point( nWidth - 25, 15), Size(10, 10));

    // Reparent the buttons and place them on the right of the bar
    long nX = m_pCloseBtn->GetPosPixel().getX() - 15;
    long nBtnGap = 5;
    boost::ptr_vector<PushButton>::iterator it;
    for (it = m_aActionBtns.begin(); it != m_aActionBtns.end(); ++it)
    {
        long nBtnWidth = it->GetSizePixel().getWidth();
        nX -= nBtnWidth;
        it->SetPosSizePixel(Point(nX, 5), Size(nBtnWidth, 30));
        nX -= nBtnGap;
    }

    m_pMessage->SetPosSizePixel(Point(10, 10), Size(nX - 20, 20));
}

IMPL_LINK_NOARG(SfxInfoBarWindow, CloseHandler)
{
    static_cast<SfxInfoBarContainerWindow*>(GetParent())->removeInfoBar(this);
    return 0;
}

SfxInfoBarContainerWindow::SfxInfoBarContainerWindow(SfxInfoBarContainerChild* pChildWin ) :
    Window(pChildWin->GetParent(), 0),
    m_pChildWin(pChildWin),
    m_pInfoBars()
{
}

SfxInfoBarContainerWindow::~SfxInfoBarContainerWindow()
{
}

void SfxInfoBarContainerWindow::appendInfoBar(const OUString& sId, const OUString& sMessage, vector<PushButton*> aButtons)
{
    Size aSize = GetSizePixel( );

    SfxInfoBarWindow* pInfoBar = new SfxInfoBarWindow(this, sId, sMessage, aButtons);
    pInfoBar->SetPosPixel(Point( 0, aSize.getHeight()));
    pInfoBar->Show();
    m_pInfoBars.push_back(pInfoBar);

    long nHeight = pInfoBar->GetSizePixel().getHeight();
    aSize.setHeight(aSize.getHeight() + nHeight);
    SetSizePixel(aSize);
}

SfxInfoBarWindow* SfxInfoBarContainerWindow::getInfoBar(const OUString& sId)
{
    boost::ptr_vector<SfxInfoBarWindow>::iterator it;
    for (it = m_pInfoBars.begin(); it != m_pInfoBars.end(); ++it)
    {
        if (it->getId() == sId)
            return &(*it);
    }
    return NULL;
}

void SfxInfoBarContainerWindow::removeInfoBar(SfxInfoBarWindow* pInfoBar)
{
    boost::ptr_vector<SfxInfoBarWindow>::iterator it;
    for (it = m_pInfoBars.begin(); it != m_pInfoBars.end(); ++it)
    {
        if (pInfoBar == &(*it))
        {
            m_pInfoBars.erase(it);
            break;
        }
    }

    long nY = 0;
    for (it = m_pInfoBars.begin(); it != m_pInfoBars.end(); ++it)
    {
        it->SetPosPixel( Point( 0, nY ) );
        nY += it->GetSizePixel( ).getHeight( );
    }

    Size aSize = GetSizePixel( );
    aSize.setHeight(nY);
    SetSizePixel(aSize);

    m_pChildWin->Update();
}

void SfxInfoBarContainerWindow::Resize()
{
    // Only need to change the width of the infobars
    long nWidth = GetSizePixel().getWidth();

    boost::ptr_vector<SfxInfoBarWindow>::iterator it;
    for (it = m_pInfoBars.begin(); it != m_pInfoBars.end(); ++it)
    {
        Size aSize = it->GetSizePixel();
        aSize.setWidth(nWidth);
        it->SetSizePixel(aSize);
        it->Resize();
    }
}

SFX_IMPL_POS_CHILDWINDOW_WITHID(SfxInfoBarContainerChild, SID_INFOBAR, SFX_OBJECTBAR_OBJECT);

SfxInfoBarContainerChild::SfxInfoBarContainerChild( vcl::Window* _pParent, sal_uInt16 nId, SfxBindings* pBindings, SfxChildWinInfo* ) :
    SfxChildWindow(_pParent, nId),
    m_pBindings(pBindings)
{
    pWindow = new SfxInfoBarContainerWindow(this);
    pWindow->SetPosSizePixel(Point(0, 0), Size(_pParent->GetSizePixel().getWidth(), 0));
    pWindow->Show();

    eChildAlignment = SFX_ALIGN_LOWESTTOP;
}

SfxInfoBarContainerChild::~SfxInfoBarContainerChild()
{
}

SfxChildWinInfo SfxInfoBarContainerChild::GetInfo() const
{
    SfxChildWinInfo aInfo = SfxChildWindow::GetInfo();
    return aInfo;
}

void SfxInfoBarContainerChild::Update()
{
    // Refresh the frame to take the infobars container height change into account
    const sal_uInt16 nId = GetChildWindowId();
    SfxViewFrame* pVFrame = m_pBindings->GetDispatcher()->GetFrame();
    pVFrame->ShowChildWindow(nId);

    // Give the focus to the document view
    pVFrame->GetWindow().GrabFocusToDocument();
}

/* vim:set shiftwidth=4 softtabstop=4 expandtab: */
<commit_msg>Further cleanup style in infobar, remove basegfx namespace in code<commit_after>/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
/*
 * This file is part of the LibreOffice project.
 *
 * This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/.
 */

#include <basegfx/polygon/b2dpolygon.hxx>
#include <drawinglayer/primitive2d/polygonprimitive2d.hxx>
#include <drawinglayer/primitive2d/polypolygonprimitive2d.hxx>
#include <drawinglayer/processor2d/baseprocessor2d.hxx>
#include <drawinglayer/processor2d/processorfromoutputdevice.hxx>
#include <sfx2/bindings.hxx>
#include <sfx2/dispatch.hxx>
#include <sfx2/infobar.hxx>
#include <sfx2/objsh.hxx>
#include <sfx2/sfx.hrc>
#include <sfx2/viewsh.hxx>
#include <vcl/svapp.hxx>
#include <vcl/settings.hxx>

using namespace std;
using namespace drawinglayer::geometry;
using namespace drawinglayer::processor2d;
using namespace drawinglayer::primitive2d;
using namespace drawinglayer::attribute;
using namespace drawinglayer::geometry;
using namespace basegfx;

namespace
{
    class SfxCloseButton : public PushButton
    {
        public:
            SfxCloseButton(vcl::Window* pParent) : PushButton(pParent, 0)
            {
            }

            virtual ~SfxCloseButton() {}

            virtual void Paint(const Rectangle& rRect) SAL_OVERRIDE;
    };

    void SfxCloseButton::Paint(const Rectangle&)
    {
        const ViewInformation2D aNewViewInfos;
        const unique_ptr<BaseProcessor2D> pProcessor(
            createBaseProcessor2DFromOutputDevice(*this, aNewViewInfos));

        const Rectangle aRect(Point(0, 0), PixelToLogic(GetSizePixel()));

        Primitive2DSequence aSeq(2);

        BColor aLightColor(1.0, 1.0, 191.0 / 255.0);
        BColor aDarkColor(217.0 / 255.0, 217.0 / 255.0, 78.0 / 255.0);

        const StyleSettings& rSettings = Application::GetSettings().GetStyleSettings();
        if (rSettings.GetHighContrastMode())
        {
            aLightColor = rSettings.GetLightColor().getBColor();
            aDarkColor = rSettings.GetDialogTextColor().getBColor();
        }

        // Light background
        B2DPolygon aPolygon;
        aPolygon.append(B2DPoint(aRect.Left(), aRect.Top()));
        aPolygon.append(B2DPoint(aRect.Right(), aRect.Top()));
        aPolygon.append(B2DPoint(aRect.Right(), aRect.Bottom()));
        aPolygon.append(B2DPoint(aRect.Left(), aRect.Bottom()));
        aPolygon.setClosed(true);

        PolyPolygonColorPrimitive2D* pBack =
            new PolyPolygonColorPrimitive2D(B2DPolyPolygon(aPolygon), aLightColor);
        aSeq[0] = pBack;

        LineAttribute aLineAttribute(aDarkColor, 2.0);

        // Cross
        B2DPolyPolygon aCross;

        B2DPolygon aLine1;
        aLine1.append(B2DPoint(aRect.Left(), aRect.Top()));
        aLine1.append(B2DPoint(aRect.Right(), aRect.Bottom()));
        aCross.append(aLine1);

        B2DPolygon aLine2;
        aLine2.append(B2DPoint(aRect.Right(), aRect.Top()));
        aLine2.append(B2DPoint(aRect.Left(), aRect.Bottom()));
        aCross.append(aLine2);

        PolyPolygonStrokePrimitive2D* pCross =
            new PolyPolygonStrokePrimitive2D(aCross, aLineAttribute, StrokeAttribute());

        aSeq[1] = pCross;

        pProcessor->process(aSeq);
    }
}

SfxInfoBarWindow::SfxInfoBarWindow(vcl::Window* pParent, const OUString& sId,
       const OUString& sMessage, vector<PushButton*> aButtons) :
    Window(pParent, 0),
    m_sId(sId),
    m_pMessage(new FixedText(this, 0)),
    m_pCloseBtn(new SfxCloseButton(this)),
    m_aActionBtns()
{
    long nWidth = pParent->GetSizePixel().getWidth();
    SetPosSizePixel(Point(0, 0), Size(nWidth, 40));

    m_pMessage->SetText(sMessage);
    m_pMessage->SetBackground(Wallpaper(Color(255, 255, 191)));
    m_pMessage->Show();

    m_pCloseBtn->SetClickHdl(LINK(this, SfxInfoBarWindow, CloseHandler));
    m_pCloseBtn->Show();

    // Reparent the buttons and place them on the right of the bar
    vector<PushButton*>::iterator it;
    for (it = aButtons.begin(); it != aButtons.end(); ++it)
    {
        PushButton* pButton = *it;
        pButton->SetParent(this);
        pButton->Show();
        m_aActionBtns.push_back(pButton);
    }

    Resize();
}

SfxInfoBarWindow::~SfxInfoBarWindow()
{}

void SfxInfoBarWindow::Paint(const Rectangle& rPaintRect)
{
    const ViewInformation2D aNewViewInfos;
    const unique_ptr<BaseProcessor2D> pProcessor(
        createBaseProcessor2DFromOutputDevice(*this, aNewViewInfos));

    const Rectangle aRect(Point(0, 0), PixelToLogic(GetSizePixel()));

    Primitive2DSequence aSeq(2);

    BColor aLightColor(1.0, 1.0, 191.0 / 255.0);
    BColor aDarkColor(217.0 / 255.0, 217.0 / 255.0, 78.0 / 255.0);

    const StyleSettings& rSettings = Application::GetSettings().GetStyleSettings();
    if (rSettings.GetHighContrastMode())
    {
        aLightColor = rSettings.GetLightColor().getBColor();
        aDarkColor = rSettings.GetDialogTextColor().getBColor();
    }

    // Update the label background color
    m_pMessage->SetBackground(Wallpaper(Color(aLightColor)));

    // Light background
    B2DPolygon aPolygon;
    aPolygon.append(B2DPoint(aRect.Left(), aRect.Top()));
    aPolygon.append(B2DPoint(aRect.Right(), aRect.Top()));
    aPolygon.append(B2DPoint(aRect.Right(), aRect.Bottom()));
    aPolygon.append(B2DPoint(aRect.Left(), aRect.Bottom()));
    aPolygon.setClosed(true);

    PolyPolygonColorPrimitive2D* pBack =
        new PolyPolygonColorPrimitive2D(B2DPolyPolygon(aPolygon), aLightColor);
    aSeq[0] = pBack;

    LineAttribute aLineAttribute(aDarkColor, 1.0);

    // Bottom dark line
    B2DPolygon aPolygonBottom;
    aPolygonBottom.append(B2DPoint(aRect.Left(), aRect.Bottom()));
    aPolygonBottom.append(B2DPoint(aRect.Right(), aRect.Bottom()));

    PolygonStrokePrimitive2D* pLineBottom =
            new PolygonStrokePrimitive2D (aPolygonBottom, aLineAttribute);

    aSeq[1] = pLineBottom;

    pProcessor->process(aSeq);

    Window::Paint(rPaintRect);
}

void SfxInfoBarWindow::Resize()
{
    long nWidth = GetSizePixel().getWidth();
    m_pCloseBtn->SetPosSizePixel(Point(nWidth - 25, 15), Size(10, 10));

    // Reparent the buttons and place them on the right of the bar
    long nX = m_pCloseBtn->GetPosPixel().getX() - 15;
    long nBtnGap = 5;
    boost::ptr_vector<PushButton>::iterator it;
    for (it = m_aActionBtns.begin(); it != m_aActionBtns.end(); ++it)
    {
        long nBtnWidth = it->GetSizePixel().getWidth();
        nX -= nBtnWidth;
        it->SetPosSizePixel(Point(nX, 5), Size(nBtnWidth, 30));
        nX -= nBtnGap;
    }

    m_pMessage->SetPosSizePixel(Point(10, 10), Size(nX - 20, 20));
}

IMPL_LINK_NOARG(SfxInfoBarWindow, CloseHandler)
{
    static_cast<SfxInfoBarContainerWindow*>(GetParent())->removeInfoBar(this);
    return 0;
}

SfxInfoBarContainerWindow::SfxInfoBarContainerWindow(SfxInfoBarContainerChild* pChildWin ) :
    Window(pChildWin->GetParent(), 0),
    m_pChildWin(pChildWin),
    m_pInfoBars()
{
}

SfxInfoBarContainerWindow::~SfxInfoBarContainerWindow()
{
}

void SfxInfoBarContainerWindow::appendInfoBar(const OUString& sId, const OUString& sMessage, vector<PushButton*> aButtons)
{
    Size aSize = GetSizePixel( );

    SfxInfoBarWindow* pInfoBar = new SfxInfoBarWindow(this, sId, sMessage, aButtons);
    pInfoBar->SetPosPixel(Point( 0, aSize.getHeight()));
    pInfoBar->Show();
    m_pInfoBars.push_back(pInfoBar);

    long nHeight = pInfoBar->GetSizePixel().getHeight();
    aSize.setHeight(aSize.getHeight() + nHeight);
    SetSizePixel(aSize);
}

SfxInfoBarWindow* SfxInfoBarContainerWindow::getInfoBar(const OUString& sId)
{
    boost::ptr_vector<SfxInfoBarWindow>::iterator it;
    for (it = m_pInfoBars.begin(); it != m_pInfoBars.end(); ++it)
    {
        if (it->getId() == sId)
            return &(*it);
    }
    return NULL;
}

void SfxInfoBarContainerWindow::removeInfoBar(SfxInfoBarWindow* pInfoBar)
{
    boost::ptr_vector<SfxInfoBarWindow>::iterator it;
    for (it = m_pInfoBars.begin(); it != m_pInfoBars.end(); ++it)
    {
        if (pInfoBar == &(*it))
        {
            m_pInfoBars.erase(it);
            break;
        }
    }

    long nY = 0;
    for (it = m_pInfoBars.begin(); it != m_pInfoBars.end(); ++it)
    {
        it->SetPosPixel(Point(0, nY));
        nY += it->GetSizePixel().getHeight();
    }

    Size aSize = GetSizePixel();
    aSize.setHeight(nY);
    SetSizePixel(aSize);

    m_pChildWin->Update();
}

void SfxInfoBarContainerWindow::Resize()
{
    // Only need to change the width of the infobars
    long nWidth = GetSizePixel().getWidth();

    boost::ptr_vector<SfxInfoBarWindow>::iterator it;
    for (it = m_pInfoBars.begin(); it != m_pInfoBars.end(); ++it)
    {
        Size aSize = it->GetSizePixel();
        aSize.setWidth(nWidth);
        it->SetSizePixel(aSize);
        it->Resize();
    }
}

SFX_IMPL_POS_CHILDWINDOW_WITHID(SfxInfoBarContainerChild, SID_INFOBAR, SFX_OBJECTBAR_OBJECT);

SfxInfoBarContainerChild::SfxInfoBarContainerChild( vcl::Window* _pParent, sal_uInt16 nId, SfxBindings* pBindings, SfxChildWinInfo* ) :
    SfxChildWindow(_pParent, nId),
    m_pBindings(pBindings)
{
    pWindow = new SfxInfoBarContainerWindow(this);
    pWindow->SetPosSizePixel(Point(0, 0), Size(_pParent->GetSizePixel().getWidth(), 0));
    pWindow->Show();

    eChildAlignment = SFX_ALIGN_LOWESTTOP;
}

SfxInfoBarContainerChild::~SfxInfoBarContainerChild()
{
}

SfxChildWinInfo SfxInfoBarContainerChild::GetInfo() const
{
    SfxChildWinInfo aInfo = SfxChildWindow::GetInfo();
    return aInfo;
}

void SfxInfoBarContainerChild::Update()
{
    // Refresh the frame to take the infobars container height change into account
    const sal_uInt16 nId = GetChildWindowId();
    SfxViewFrame* pVFrame = m_pBindings->GetDispatcher()->GetFrame();
    pVFrame->ShowChildWindow(nId);

    // Give the focus to the document view
    pVFrame->GetWindow().GrabFocusToDocument();
}

/* vim:set shiftwidth=4 softtabstop=4 expandtab: */
<|endoftext|>


<commit_before>/* LiteSQL - Common routines for backends
 *
 * The list of contributors at http://litesql.sf.net/
 *
 * See LICENSE for copyright information. */

#include <map>

#include "compatibility.hpp"
#include "litesql/backend.hpp"
#include "litesql/string.hpp"
#include "litesql/types.hpp"

#ifdef HAVE_LIBMYSQLCLIENT
#include "mysql.hpp"
#endif

#ifdef HAVE_LIBPQ
#include "postgresql.hpp"
#endif

#ifdef HAVE_LIBSQLITE3
#include "sqlite3.hpp"
#endif

#ifdef HAVE_ODBC
#include "odbc_backend.hpp"
#endif

#ifdef HAVE_OCILIB
#include "ocilib_backend.hpp"
#endif

using namespace litesql;
using namespace std;

string Backend::getCreateSequenceSQL(const string& name) const
{
    return "CREATE SEQUENCE " + name + " START 1 INCREMENT 1";
}

string Backend::getSeqSQL(const string& sname) const
{
    string ret="SELECT nextval('"+ sname + "');";
    return ret;
}

string Backend::groupInsert(Record tables, Records fields, Records values,
                   const string& sequence) const {
    string id = values[0][0];

    if (supportsSequences() && values[0][0] == "NULL") {
      Result * r = execute(getSeqSQL(sequence));
      id = r->records()[0][0];
      delete r;
    }
    for (int i = tables.size()-1; i >= 0; i--) {
      string fieldString = Split::join(fields[i],",");
        string valueString;
        if (!values[i].empty())
            values[i][0] = id;
        Split valueSplit(values[i]);
        for (size_t i2 = 0; i2 < valueSplit.size(); i2++)
            valueSplit[i2] = escapeSQL(valueSplit[i2]);
        valueString = valueSplit.join(",");
        string query = "INSERT INTO " + tables[i] + " (" + fieldString
            + ") VALUES (" + valueString + ");";
        delete execute(query);
        if (!supportsSequences() && id == "NULL")
            id = getInsertID();

    }
    return id;
}

Backend* Backend::getBackend(const string & backendType,const string& connInfo)
{
  Backend* backend;

#ifdef HAVE_LIBMYSQLCLIENT
  if (backendType == "mysql") {
    backend = new MySQL(connInfo);
  } else
#endif
#ifdef HAVE_LIBPQ
    if (backendType == "postgresql") {
      backend = new PostgreSQL(connInfo);
    } else
#endif
#ifdef HAVE_ODBC
      if (backendType == "odbc") {
        backend = new ODBCBackend(connInfo);
      } else
#endif
#ifdef HAVE_LIBSQLITE3
        if (backendType == "sqlite3") {
          backend = new SQLite3(connInfo);
        } else
#endif
#ifdef HAVE_OCILIB
        if (backendType == "oracle") {
          backend = new OCILib(connInfo);
        } else
#endif
        {
          backend = NULL;
        };
        return backend;
}
<commit_msg>added getSQLType(type) as a first step to get backend specific field types in future versions<commit_after>/* LiteSQL - Common routines for backends
 *
 * The list of contributors at http://litesql.sf.net/
 *
 * See LICENSE for copyright information. */

#include <map>

#include "compatibility.hpp"
#include "litesql/backend.hpp"
#include "litesql/string.hpp"
#include "litesql/types.hpp"

#ifdef HAVE_LIBMYSQLCLIENT
#include "mysql.hpp"
#endif

#ifdef HAVE_LIBPQ
#include "postgresql.hpp"
#endif

#ifdef HAVE_LIBSQLITE3
#include "sqlite3.hpp"
#endif

#ifdef HAVE_ODBC
#include "odbc_backend.hpp"
#endif

#ifdef HAVE_OCILIB
#include "ocilib_backend.hpp"
#endif

using namespace litesql;
using namespace std;

string Backend::getSQLType(AT_field_type fieldType) const
{
    switch(fieldType) {
    case A_field_type_integer: return "INTEGER";
    case A_field_type_bigint: return "BIGINT";
    case A_field_type_string: return "TEXT";
    case A_field_type_float: return "FLOAT";
    case A_field_type_double: return "DOUBLE";
    case A_field_type_boolean: return "INTEGER";
    case A_field_type_date: return "INTEGER";
    case A_field_type_time: return "INTEGER";
    case A_field_type_datetime: return "INTEGER";
    case A_field_type_blob: return "BLOB";
    default: return "";
    }
}

string Backend::getCreateSequenceSQL(const string& name) const
{
    return "CREATE SEQUENCE " + name + " START 1 INCREMENT 1";
}

string Backend::getSeqSQL(const string& sname) const
{
    string ret="SELECT nextval('"+ sname + "');";
    return ret;
}

string Backend::groupInsert(Record tables, Records fields, Records values,
                   const string& sequence) const {
    string id = values[0][0];

    if (supportsSequences() && values[0][0] == "NULL") {
      Result * r = execute(getSeqSQL(sequence));
      id = r->records()[0][0];
      delete r;
    }
    for (int i = tables.size()-1; i >= 0; i--) {
      string fieldString = Split::join(fields[i],",");
        string valueString;
        if (!values[i].empty())
            values[i][0] = id;
        Split valueSplit(values[i]);
        for (size_t i2 = 0; i2 < valueSplit.size(); i2++)
            valueSplit[i2] = escapeSQL(valueSplit[i2]);
        valueString = valueSplit.join(",");
        string query = "INSERT INTO " + tables[i] + " (" + fieldString
            + ") VALUES (" + valueString + ");";
        delete execute(query);
        if (!supportsSequences() && id == "NULL")
            id = getInsertID();

    }
    return id;
}

Backend* Backend::getBackend(const string & backendType,const string& connInfo)
{
  Backend* backend;

#ifdef HAVE_LIBMYSQLCLIENT
  if (backendType == "mysql") {
    backend = new MySQL(connInfo);
  } else
#endif
#ifdef HAVE_LIBPQ
    if (backendType == "postgresql") {
      backend = new PostgreSQL(connInfo);
    } else
#endif
#ifdef HAVE_ODBC
      if (backendType == "odbc") {
        backend = new ODBCBackend(connInfo);
      } else
#endif
#ifdef HAVE_LIBSQLITE3
        if (backendType == "sqlite3") {
          backend = new SQLite3(connInfo);
        } else
#endif
#ifdef HAVE_OCILIB
        if (backendType == "oracle") {
          backend = new OCILib(connInfo);
        } else
#endif
        {
          backend = NULL;
        };
        return backend;
}
<|endoftext|>


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

  Program:   Visualization Toolkit
  Module:    vtkCommunicator.cxx

  Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen
  All rights reserved.
  See Copyright.txt or http://www.kitware.com/Copyright.htm for details.

     This software is distributed WITHOUT ANY WARRANTY; without even
     the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
     PURPOSE.  See the above copyright notice for more information.

=========================================================================*/
#include "vtkCommunicator.h"

#include "vtkCharArray.h"
#include "vtkDataSetReader.h"
#include "vtkDataSetWriter.h"
#include "vtkDoubleArray.h"
#include "vtkFloatArray.h"
#include "vtkIdTypeArray.h"
#include "vtkImageClip.h"
#include "vtkIntArray.h"
#include "vtkStructuredPoints.h"
#include "vtkStructuredPointsReader.h"
#include "vtkStructuredPointsWriter.h"
#include "vtkUnsignedCharArray.h"
#include "vtkUnsignedLongArray.h"

vtkCxxRevisionMacro(vtkCommunicator, "1.26");

template <class T>
int SendDataArray(T* data, int length, int handle, int tag, vtkCommunicator *self)
{

  self->Send(data, length, handle, tag);

  return 1;
}

vtkCommunicator::vtkCommunicator()
{
  this->MarshalString = 0;
  this->MarshalStringLength = 0;
  this->MarshalDataLength = 0;
}

vtkCommunicator::~vtkCommunicator()
{
  this->DeleteAndSetMarshalString(0, 0);
}

int vtkCommunicator::UseCopy = 0;
void vtkCommunicator::SetUseCopy(int useCopy)
{
  vtkCommunicator::UseCopy = useCopy;
}

void vtkCommunicator::PrintSelf(ostream& os, vtkIndent indent)
{
  this->Superclass::PrintSelf(os, indent);
  os << indent << "Marshal string: ";
  if ( this->MarshalString )
    {
    os << this->MarshalString << endl;
    }
  else
    {
    os << "(None)" << endl;
    }
  os << indent << "Marshal string length: " << this->MarshalStringLength
     << endl;
  os << indent << "Marshal data length: " << this->MarshalDataLength
     << endl;
}

//----------------------------------------------------------------------------
// Internal method.  Assumes responsibility for deleting the string
void vtkCommunicator::DeleteAndSetMarshalString(char *str, int strLength)
{
  // delete any previous string
  if (this->MarshalString)
    {
    delete [] this->MarshalString;
    this->MarshalString = 0;
    this->MarshalStringLength = 0;
    this->MarshalDataLength = 0;
    }

  this->MarshalString = str;
  this->MarshalStringLength = strLength;
}

// Need to add better error checking
int vtkCommunicator::Send(vtkDataObject* data, int remoteHandle,
                          int tag)
{

  if (data == NULL)
    {
    this->MarshalDataLength = 0;
    this->Send( &this->MarshalDataLength, 1,
                remoteHandle, tag);
    return 1;
    }
  if (this->WriteObject(data))
    {
    this->Send( &this->MarshalDataLength, 1,
                remoteHandle, tag);
    // then send the string.

    this->Send( this->MarshalString, this->MarshalDataLength,
                remoteHandle, tag);

    return 1;
    }

  // could not marshal data
  return 0;
}

int vtkCommunicator::Send(vtkDataArray* data, int remoteHandle, int tag)
{

  int type = -1;
  if (data == NULL)
    {
      this->MarshalDataLength = 0;
      this->Send( &type, 1, remoteHandle, tag);
      return 1;
    }

  // send array type
  type = data->GetDataType();
  this->Send( &type, 1, remoteHandle, tag);

  // send array size
  vtkIdType size = data->GetSize();
  this->Send( &size, 1, remoteHandle, tag);

  // send number of components in array
  int numComponents = data->GetNumberOfComponents();
  this->Send( &numComponents, 1, remoteHandle, tag);

  const char* name = data->GetName();
  int len = 0;
  if (name)
    {
    len = static_cast<int>(strlen(name)) + 1;
    }

  // send length of name
  this->Send( &len, 1, remoteHandle, tag);

  if (len > 0)
    {
    // send name
    this->Send( const_cast<char*>(name), len, remoteHandle, tag);
    }

  // now send the raw array
  switch (type)
    {

    case VTK_CHAR:
      return SendDataArray(static_cast<char*>(data->GetVoidPointer(0)),
                          size, remoteHandle, tag, this);

    case VTK_UNSIGNED_CHAR:
      return SendDataArray(static_cast<unsigned char*>(data->GetVoidPointer(0)),
                          size, remoteHandle, tag, this);

    case VTK_INT:
      return SendDataArray(static_cast<int*>(data->GetVoidPointer(0)),
                          size, remoteHandle, tag, this);

    case VTK_UNSIGNED_LONG:
      return SendDataArray(static_cast<unsigned long*>(data->GetVoidPointer(0)),
                          size, remoteHandle, tag, this);

    case VTK_FLOAT:
      return SendDataArray(static_cast<float*>(data->GetVoidPointer(0)),
                          size, remoteHandle, tag, this);

    case VTK_DOUBLE:
      return SendDataArray(static_cast<double*>(data->GetVoidPointer(0)),
                          size, remoteHandle, tag, this);

    case VTK_ID_TYPE:
      return SendDataArray(static_cast<vtkIdType*>(data->GetVoidPointer(0)),
                          size, remoteHandle, tag, this);

    default:
      vtkErrorMacro(<<"Unsupported data type!");
      return 0; // could not marshal data

    }

}

int vtkCommunicator::Receive(vtkDataObject* data, int remoteHandle,
                             int tag)
{
  int dataLength;

  // First receive the data length.
  if (!this->Receive( &dataLength, 1, remoteHandle, tag))
    {
    vtkErrorMacro("Could not receive data!");
    return 0;
    }

  if (dataLength < 0)
    {
    vtkErrorMacro("Bad data length");
    return 0;
    }

  if (dataLength == 0)
    { // This indicates a NULL object was sent. Do nothing.
    return 1;
    }

  // if we cannot reuse the string, allocate a new one.
  if (dataLength > this->MarshalStringLength)
    {
    char *str = new char[dataLength + 10]; // maybe a little extra?
    this->DeleteAndSetMarshalString(str, dataLength + 10);
    }

  // Receive the string
  this->Receive(this->MarshalString, dataLength,
                remoteHandle, tag);
  this->MarshalDataLength = dataLength;

  this->ReadObject(data);

  // we should really look at status to determine success
  return 1;
}

int vtkCommunicator::Receive(vtkDataArray* data, int remoteHandle,
                             int tag)
{
  vtkIdType size;
  int type;
  int numComponents;
  int nameLength;

  char *c = 0;
  unsigned char *uc = 0;
  int *i = 0;
  unsigned long *ul = 0;
  float *f = 0;
  double *d = 0;
  vtkIdType *idt = 0;

  // First receive the data type.
  if (!this->Receive( &type, 1, remoteHandle, tag))
    {
    vtkErrorMacro("Could not receive data!");
    return 0;
    }

  if (type == -1)
    { // This indicates a NULL object was sent. Do nothing.
    return 1;
    }

  // Next receive the data length.
  if (!this->Receive( &size, 1, remoteHandle, tag))
    {
    vtkErrorMacro("Could not receive data!");
    return 0;
    }

  // Next receive the number of components.
  this->Receive( &numComponents, 1, remoteHandle, tag);

  // Next receive the length of the name.
  this->Receive( &nameLength, 1, remoteHandle, tag);

  if ( nameLength > 0 )
    {
    char *str = new char[nameLength];
    this->DeleteAndSetMarshalString(str, nameLength);

    // Receive the name
    this->Receive(this->MarshalString, nameLength, remoteHandle, tag);
    this->MarshalDataLength = nameLength;
    }

  if (size < 0)
    {
    vtkErrorMacro("Bad data length");
    return 0;
    }

  if (size == 0)
    { // This indicates a NULL object was sent. Do nothing.
    return 1;
    }

  // Receive the raw data array
  switch (type)
    {

    case VTK_CHAR:
      c = new char[size];
      this->Receive(c, size, remoteHandle, tag);
      static_cast<vtkCharArray*>(data)->SetArray(c, size, 0);
      break;

    case VTK_UNSIGNED_CHAR:
      uc = new unsigned char[size];
      this->Receive(uc, size, remoteHandle, tag);
      static_cast<vtkUnsignedCharArray*>(data)->SetArray(uc, size, 0);
      break;

    case VTK_INT:
      i = new int[size];
      this->Receive(i, size, remoteHandle, tag);
      static_cast<vtkIntArray*>(data)->SetArray(i, size, 0);
      break;

    case VTK_UNSIGNED_LONG:
      ul = new unsigned long[size];
      this->Receive(ul, size, remoteHandle, tag);
      static_cast<vtkUnsignedLongArray*>(data)->SetArray(ul, size, 0);
      break;

    case VTK_FLOAT:
      f = new float[size];
      this->Receive(f, size, remoteHandle, tag);
      static_cast<vtkFloatArray*>(data)->SetArray(f, size, 0);
      break;

    case VTK_DOUBLE:

      d = new double[size];
      this->Receive(d, size, remoteHandle, tag);
      static_cast<vtkDoubleArray*>(data)->SetArray(d, size, 0);
      break;

    case VTK_ID_TYPE:
      idt = new vtkIdType[size];
      this->Receive(idt, size, remoteHandle, tag);
      static_cast<vtkIdTypeArray*>(data)->SetArray(idt, size, 0);
      break;

    default:
      vtkErrorMacro(<<"Unsupported data type!");
      return 0; // could not marshal data

    }

  if (nameLength > 0)
    {
    data->SetName(this->MarshalString);
    }
  else
    {
    data->SetName(0);
    }
  data->SetNumberOfComponents(numComponents);

  return 1;

}

int vtkCommunicator::WriteObject(vtkDataObject *data)
{
  if (strcmp(data->GetClassName(), "vtkPolyData") == 0          ||
      strcmp(data->GetClassName(), "vtkUnstructuredGrid") == 0  ||
      strcmp(data->GetClassName(), "vtkStructuredGrid") == 0    ||
      strcmp(data->GetClassName(), "vtkRectilinearGrid") == 0   ||
      strcmp(data->GetClassName(), "vtkStructuredPoints") == 0)
    {
    return this->WriteDataSet((vtkDataSet*)data);
    }
  if (strcmp(data->GetClassName(), "vtkImageData") == 0)
    {
    return this->WriteImageData((vtkImageData*)data);
    }

  vtkErrorMacro("Cannot marshal object of type "
                << data->GetClassName());
  return 0;
}

int vtkCommunicator::ReadObject(vtkDataObject *data)
{
  if (strcmp(data->GetClassName(), "vtkPolyData") == 0          ||
      strcmp(data->GetClassName(), "vtkUnstructuredGrid") == 0  ||
      strcmp(data->GetClassName(), "vtkStructuredGrid") == 0    ||
      strcmp(data->GetClassName(), "vtkRectilinearGrid") == 0   ||
      strcmp(data->GetClassName(), "vtkStructuredPoints") == 0)
    {
    return this->ReadDataSet((vtkDataSet*)data);
    }
  if (strcmp(data->GetClassName(), "vtkImageData") == 0)
    {
    return this->ReadImageData((vtkImageData*)data);
    }

  vtkErrorMacro("Cannot marshal object of type "
                << data->GetClassName());

  return 1;
}

int vtkCommunicator::WriteImageData(vtkImageData *data)
{
  vtkImageClip *clip;
  vtkStructuredPointsWriter *writer;
  int size;

  // keep Update from propagating
  vtkImageData *tmp = vtkImageData::New();
  tmp->ShallowCopy(data);
  tmp->SetUpdateExtent(data->GetUpdateExtent());

  clip = vtkImageClip::New();
  clip->SetInput(tmp);
  clip->SetOutputWholeExtent(data->GetExtent());
  writer = vtkStructuredPointsWriter::New();
  writer->SetFileTypeToBinary();
  writer->WriteToOutputStringOn();
  writer->SetInput(clip->GetOutput());
  writer->Write();
  size = writer->GetOutputStringLength();

  this->DeleteAndSetMarshalString(writer->RegisterAndGetOutputString(), size);
  this->MarshalDataLength = size;
  clip->Delete();
  writer->Delete();
  tmp->Delete();

  return 1;
}

int vtkCommunicator::ReadImageData(vtkImageData *object)
{
  vtkStructuredPointsReader *reader = vtkStructuredPointsReader::New();

  if (this->MarshalString == NULL || this->MarshalStringLength <= 0)
    {
    return 0;
    }

  reader->ReadFromInputStringOn();

  vtkCharArray* mystring = vtkCharArray::New();
  // mystring should not delete the string when it's done,
  // that's our job.
  mystring->SetArray(this->MarshalString, this->MarshalDataLength, 1);
  reader->SetInputArray(mystring);
  mystring->Delete();

  reader->GetOutput()->Update();

  object->ShallowCopy(reader->GetOutput());
  object->SetUpdateExtent(reader->GetOutput()->GetUpdateExtent());

  reader->Delete();

  return 1;
}

int vtkCommunicator::WriteDataSet(vtkDataSet *data)
{
  vtkDataSet *copy;
  unsigned long size;
  vtkDataSetWriter *writer = vtkDataSetWriter::New();

  copy = data->NewInstance();
  copy->ShallowCopy(data);

  // There is a problem with binary files with no data.
  if (copy->GetNumberOfCells() + copy->GetNumberOfPoints() > 0)
    {
    writer->SetFileTypeToBinary();
    }
  writer->WriteToOutputStringOn();
  writer->SetInput(copy);

  writer->Write();
  size = writer->GetOutputStringLength();
  this->DeleteAndSetMarshalString(writer->RegisterAndGetOutputString(), size);
  this->MarshalDataLength = size;
  writer->Delete();
  copy->Delete();

  return 1;
}

int vtkCommunicator::ReadDataSet(vtkDataSet *object)
{
  vtkDataSetReader *reader = vtkDataSetReader::New();

  if (this->MarshalString == NULL || this->MarshalStringLength <= 0)
    {
    return 0;
    }

  reader->ReadFromInputStringOn();

  vtkCharArray* mystring = vtkCharArray::New();
  // mystring should not delete the string when it's done,
  // that's our job.
  mystring->SetArray(this->MarshalString, this->MarshalDataLength, 1);
  reader->SetInputArray(mystring);
  mystring->Delete();

  reader->Update();
  object->ShallowCopy(reader->GetOutput());

  reader->Delete();

  return 1;
}
<commit_msg>BUG: Should not set update extent. This can cause numerous problems<commit_after>/*=========================================================================

  Program:   Visualization Toolkit
  Module:    vtkCommunicator.cxx

  Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen
  All rights reserved.
  See Copyright.txt or http://www.kitware.com/Copyright.htm for details.

     This software is distributed WITHOUT ANY WARRANTY; without even
     the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
     PURPOSE.  See the above copyright notice for more information.

=========================================================================*/
#include "vtkCommunicator.h"

#include "vtkCharArray.h"
#include "vtkDataSetReader.h"
#include "vtkDataSetWriter.h"
#include "vtkDoubleArray.h"
#include "vtkFloatArray.h"
#include "vtkIdTypeArray.h"
#include "vtkImageClip.h"
#include "vtkIntArray.h"
#include "vtkStructuredPoints.h"
#include "vtkStructuredPointsReader.h"
#include "vtkStructuredPointsWriter.h"
#include "vtkUnsignedCharArray.h"
#include "vtkUnsignedLongArray.h"

vtkCxxRevisionMacro(vtkCommunicator, "1.27");

template <class T>
int SendDataArray(T* data, int length, int handle, int tag, vtkCommunicator *self)
{

  self->Send(data, length, handle, tag);

  return 1;
}

vtkCommunicator::vtkCommunicator()
{
  this->MarshalString = 0;
  this->MarshalStringLength = 0;
  this->MarshalDataLength = 0;
}

vtkCommunicator::~vtkCommunicator()
{
  this->DeleteAndSetMarshalString(0, 0);
}

int vtkCommunicator::UseCopy = 0;
void vtkCommunicator::SetUseCopy(int useCopy)
{
  vtkCommunicator::UseCopy = useCopy;
}

void vtkCommunicator::PrintSelf(ostream& os, vtkIndent indent)
{
  this->Superclass::PrintSelf(os, indent);
  os << indent << "Marshal string: ";
  if ( this->MarshalString )
    {
    os << this->MarshalString << endl;
    }
  else
    {
    os << "(None)" << endl;
    }
  os << indent << "Marshal string length: " << this->MarshalStringLength
     << endl;
  os << indent << "Marshal data length: " << this->MarshalDataLength
     << endl;
}

//----------------------------------------------------------------------------
// Internal method.  Assumes responsibility for deleting the string
void vtkCommunicator::DeleteAndSetMarshalString(char *str, int strLength)
{
  // delete any previous string
  if (this->MarshalString)
    {
    delete [] this->MarshalString;
    this->MarshalString = 0;
    this->MarshalStringLength = 0;
    this->MarshalDataLength = 0;
    }

  this->MarshalString = str;
  this->MarshalStringLength = strLength;
}

// Need to add better error checking
int vtkCommunicator::Send(vtkDataObject* data, int remoteHandle,
                          int tag)
{

  if (data == NULL)
    {
    this->MarshalDataLength = 0;
    this->Send( &this->MarshalDataLength, 1,
                remoteHandle, tag);
    return 1;
    }
  if (this->WriteObject(data))
    {
    this->Send( &this->MarshalDataLength, 1,
                remoteHandle, tag);
    // then send the string.

    this->Send( this->MarshalString, this->MarshalDataLength,
                remoteHandle, tag);

    return 1;
    }

  // could not marshal data
  return 0;
}

int vtkCommunicator::Send(vtkDataArray* data, int remoteHandle, int tag)
{

  int type = -1;
  if (data == NULL)
    {
      this->MarshalDataLength = 0;
      this->Send( &type, 1, remoteHandle, tag);
      return 1;
    }

  // send array type
  type = data->GetDataType();
  this->Send( &type, 1, remoteHandle, tag);

  // send array size
  vtkIdType size = data->GetSize();
  this->Send( &size, 1, remoteHandle, tag);

  // send number of components in array
  int numComponents = data->GetNumberOfComponents();
  this->Send( &numComponents, 1, remoteHandle, tag);

  const char* name = data->GetName();
  int len = 0;
  if (name)
    {
    len = static_cast<int>(strlen(name)) + 1;
    }

  // send length of name
  this->Send( &len, 1, remoteHandle, tag);

  if (len > 0)
    {
    // send name
    this->Send( const_cast<char*>(name), len, remoteHandle, tag);
    }

  // now send the raw array
  switch (type)
    {

    case VTK_CHAR:
      return SendDataArray(static_cast<char*>(data->GetVoidPointer(0)),
                          size, remoteHandle, tag, this);

    case VTK_UNSIGNED_CHAR:
      return SendDataArray(static_cast<unsigned char*>(data->GetVoidPointer(0)),
                          size, remoteHandle, tag, this);

    case VTK_INT:
      return SendDataArray(static_cast<int*>(data->GetVoidPointer(0)),
                          size, remoteHandle, tag, this);

    case VTK_UNSIGNED_LONG:
      return SendDataArray(static_cast<unsigned long*>(data->GetVoidPointer(0)),
                          size, remoteHandle, tag, this);

    case VTK_FLOAT:
      return SendDataArray(static_cast<float*>(data->GetVoidPointer(0)),
                          size, remoteHandle, tag, this);

    case VTK_DOUBLE:
      return SendDataArray(static_cast<double*>(data->GetVoidPointer(0)),
                          size, remoteHandle, tag, this);

    case VTK_ID_TYPE:
      return SendDataArray(static_cast<vtkIdType*>(data->GetVoidPointer(0)),
                          size, remoteHandle, tag, this);

    default:
      vtkErrorMacro(<<"Unsupported data type!");
      return 0; // could not marshal data

    }

}

int vtkCommunicator::Receive(vtkDataObject* data, int remoteHandle,
                             int tag)
{
  int dataLength;

  // First receive the data length.
  if (!this->Receive( &dataLength, 1, remoteHandle, tag))
    {
    vtkErrorMacro("Could not receive data!");
    return 0;
    }

  if (dataLength < 0)
    {
    vtkErrorMacro("Bad data length");
    return 0;
    }

  if (dataLength == 0)
    { // This indicates a NULL object was sent. Do nothing.
    return 1;
    }

  // if we cannot reuse the string, allocate a new one.
  if (dataLength > this->MarshalStringLength)
    {
    char *str = new char[dataLength + 10]; // maybe a little extra?
    this->DeleteAndSetMarshalString(str, dataLength + 10);
    }

  // Receive the string
  this->Receive(this->MarshalString, dataLength,
                remoteHandle, tag);
  this->MarshalDataLength = dataLength;

  this->ReadObject(data);

  // we should really look at status to determine success
  return 1;
}

int vtkCommunicator::Receive(vtkDataArray* data, int remoteHandle,
                             int tag)
{
  vtkIdType size;
  int type;
  int numComponents;
  int nameLength;

  char *c = 0;
  unsigned char *uc = 0;
  int *i = 0;
  unsigned long *ul = 0;
  float *f = 0;
  double *d = 0;
  vtkIdType *idt = 0;

  // First receive the data type.
  if (!this->Receive( &type, 1, remoteHandle, tag))
    {
    vtkErrorMacro("Could not receive data!");
    return 0;
    }

  if (type == -1)
    { // This indicates a NULL object was sent. Do nothing.
    return 1;
    }

  // Next receive the data length.
  if (!this->Receive( &size, 1, remoteHandle, tag))
    {
    vtkErrorMacro("Could not receive data!");
    return 0;
    }

  // Next receive the number of components.
  this->Receive( &numComponents, 1, remoteHandle, tag);

  // Next receive the length of the name.
  this->Receive( &nameLength, 1, remoteHandle, tag);

  if ( nameLength > 0 )
    {
    char *str = new char[nameLength];
    this->DeleteAndSetMarshalString(str, nameLength);

    // Receive the name
    this->Receive(this->MarshalString, nameLength, remoteHandle, tag);
    this->MarshalDataLength = nameLength;
    }

  if (size < 0)
    {
    vtkErrorMacro("Bad data length");
    return 0;
    }

  if (size == 0)
    { // This indicates a NULL object was sent. Do nothing.
    return 1;
    }

  // Receive the raw data array
  switch (type)
    {

    case VTK_CHAR:
      c = new char[size];
      this->Receive(c, size, remoteHandle, tag);
      static_cast<vtkCharArray*>(data)->SetArray(c, size, 0);
      break;

    case VTK_UNSIGNED_CHAR:
      uc = new unsigned char[size];
      this->Receive(uc, size, remoteHandle, tag);
      static_cast<vtkUnsignedCharArray*>(data)->SetArray(uc, size, 0);
      break;

    case VTK_INT:
      i = new int[size];
      this->Receive(i, size, remoteHandle, tag);
      static_cast<vtkIntArray*>(data)->SetArray(i, size, 0);
      break;

    case VTK_UNSIGNED_LONG:
      ul = new unsigned long[size];
      this->Receive(ul, size, remoteHandle, tag);
      static_cast<vtkUnsignedLongArray*>(data)->SetArray(ul, size, 0);
      break;

    case VTK_FLOAT:
      f = new float[size];
      this->Receive(f, size, remoteHandle, tag);
      static_cast<vtkFloatArray*>(data)->SetArray(f, size, 0);
      break;

    case VTK_DOUBLE:

      d = new double[size];
      this->Receive(d, size, remoteHandle, tag);
      static_cast<vtkDoubleArray*>(data)->SetArray(d, size, 0);
      break;

    case VTK_ID_TYPE:
      idt = new vtkIdType[size];
      this->Receive(idt, size, remoteHandle, tag);
      static_cast<vtkIdTypeArray*>(data)->SetArray(idt, size, 0);
      break;

    default:
      vtkErrorMacro(<<"Unsupported data type!");
      return 0; // could not marshal data

    }

  if (nameLength > 0)
    {
    data->SetName(this->MarshalString);
    }
  else
    {
    data->SetName(0);
    }
  data->SetNumberOfComponents(numComponents);

  return 1;

}

int vtkCommunicator::WriteObject(vtkDataObject *data)
{
  if (strcmp(data->GetClassName(), "vtkPolyData") == 0          ||
      strcmp(data->GetClassName(), "vtkUnstructuredGrid") == 0  ||
      strcmp(data->GetClassName(), "vtkStructuredGrid") == 0    ||
      strcmp(data->GetClassName(), "vtkRectilinearGrid") == 0   ||
      strcmp(data->GetClassName(), "vtkStructuredPoints") == 0)
    {
    return this->WriteDataSet((vtkDataSet*)data);
    }
  if (strcmp(data->GetClassName(), "vtkImageData") == 0)
    {
    return this->WriteImageData((vtkImageData*)data);
    }

  vtkErrorMacro("Cannot marshal object of type "
                << data->GetClassName());
  return 0;
}

int vtkCommunicator::ReadObject(vtkDataObject *data)
{
  if (strcmp(data->GetClassName(), "vtkPolyData") == 0          ||
      strcmp(data->GetClassName(), "vtkUnstructuredGrid") == 0  ||
      strcmp(data->GetClassName(), "vtkStructuredGrid") == 0    ||
      strcmp(data->GetClassName(), "vtkRectilinearGrid") == 0   ||
      strcmp(data->GetClassName(), "vtkStructuredPoints") == 0)
    {
    return this->ReadDataSet((vtkDataSet*)data);
    }
  if (strcmp(data->GetClassName(), "vtkImageData") == 0)
    {
    return this->ReadImageData((vtkImageData*)data);
    }

  vtkErrorMacro("Cannot marshal object of type "
                << data->GetClassName());

  return 1;
}

int vtkCommunicator::WriteImageData(vtkImageData *data)
{
  vtkImageClip *clip;
  vtkStructuredPointsWriter *writer;
  int size;

  // keep Update from propagating
  vtkImageData *tmp = vtkImageData::New();
  tmp->ShallowCopy(data);
  tmp->SetUpdateExtent(data->GetUpdateExtent());

  clip = vtkImageClip::New();
  clip->SetInput(tmp);
  clip->SetOutputWholeExtent(data->GetExtent());
  writer = vtkStructuredPointsWriter::New();
  writer->SetFileTypeToBinary();
  writer->WriteToOutputStringOn();
  writer->SetInput(clip->GetOutput());
  writer->Write();
  size = writer->GetOutputStringLength();

  this->DeleteAndSetMarshalString(writer->RegisterAndGetOutputString(), size);
  this->MarshalDataLength = size;
  clip->Delete();
  writer->Delete();
  tmp->Delete();

  return 1;
}

int vtkCommunicator::ReadImageData(vtkImageData *object)
{
  vtkStructuredPointsReader *reader = vtkStructuredPointsReader::New();

  if (this->MarshalString == NULL || this->MarshalStringLength <= 0)
    {
    return 0;
    }

  reader->ReadFromInputStringOn();

  vtkCharArray* mystring = vtkCharArray::New();
  // mystring should not delete the string when it's done,
  // that's our job.
  mystring->SetArray(this->MarshalString, this->MarshalDataLength, 1);
  reader->SetInputArray(mystring);
  mystring->Delete();

  reader->GetOutput()->Update();

  object->ShallowCopy(reader->GetOutput());

  reader->Delete();

  return 1;
}

int vtkCommunicator::WriteDataSet(vtkDataSet *data)
{
  vtkDataSet *copy;
  unsigned long size;
  vtkDataSetWriter *writer = vtkDataSetWriter::New();

  copy = data->NewInstance();
  copy->ShallowCopy(data);

  // There is a problem with binary files with no data.
  if (copy->GetNumberOfCells() + copy->GetNumberOfPoints() > 0)
    {
    writer->SetFileTypeToBinary();
    }
  writer->WriteToOutputStringOn();
  writer->SetInput(copy);

  writer->Write();
  size = writer->GetOutputStringLength();
  this->DeleteAndSetMarshalString(writer->RegisterAndGetOutputString(), size);
  this->MarshalDataLength = size;
  writer->Delete();
  copy->Delete();

  return 1;
}

int vtkCommunicator::ReadDataSet(vtkDataSet *object)
{
  vtkDataSetReader *reader = vtkDataSetReader::New();

  if (this->MarshalString == NULL || this->MarshalStringLength <= 0)
    {
    return 0;
    }

  reader->ReadFromInputStringOn();

  vtkCharArray* mystring = vtkCharArray::New();
  // mystring should not delete the string when it's done,
  // that's our job.
  mystring->SetArray(this->MarshalString, this->MarshalDataLength, 1);
  reader->SetInputArray(mystring);
  mystring->Delete();

  reader->Update();
  object->ShallowCopy(reader->GetOutput());

  reader->Delete();

  return 1;
}
<|endoftext|>


<commit_before>#include <iostream>
#include <stdexcept>

const bool BLACK = 1;
const bool RED = 0;

template<typename T>
struct Node
{
	T value;
	bool color;
	Node* leftNode;
	Node* rightNode;
	Node* parNode;
};

template<typename T>
class RedBlackTree
{
private:
	Node<T>* root;
	Node<T>* NIL;
public:
	RedBlackTree();
	~RedBlackTree();
	bool _color(const T& value) const;
	Node<T>* _root() const;
	Node<T>* _NIL() const;
	void left_rotate(Node<T>* currNode);
	void right_rotate(Node<T>* currNode);
	void insertFix(Node<T>* currNode);
	void insert(const T& value);
	void destroyTree(Node<T>* node);
	void print(const Node<T>* tempNode, int level) const;
	Node<T>* findElement(const T& value) const;
};

template <typename T>
RedBlackTree<T>::RedBlackTree()
{
	NIL = new Node<T>;
	NIL->leftNode = NIL->parNode = NIL->rightNode = nullptr;
	NIL->color = BLACK;
	root = NIL;
}

template <typename T>
bool RedBlackTree<T>::_color(const T& value) const
{
	return findElement(value)->color;
}

template <typename T>
Node<T>* RedBlackTree<T>::_root() const
{
	return root;
}

template <typename T>
Node<T>* RedBlackTree<T>::_NIL()const
{
	return NIL;
}

template <typename T>
void RedBlackTree<T>::left_rotate(Node<T>* currNode)
{
	Node<T>* tempNode= currNode->rightNode;
	currNode->rightNode = tempNode->leftNode;
	if (tempNode->leftNode != NIL)
		tempNode->leftNode->parNode = currNode;
	if (tempNode!= NIL)
		tempNode->parNode = currNode->parNode;
	if (currNode->parNode != NIL)
	{
		if (currNode == currNode->parNode->leftNode)
			currNode->parNode->leftNode = tempNode;
		else
			currNode->parNode->rightNode = tempNode;
	}
	else
	{
		root = tempNode;
	}
	tempNode->leftNode = currNode;
	if (currNode != NIL)
		currNode->parNode = tempNode;
}

template <typename T>
void RedBlackTree<T>::right_rotate(Node<T> *currNode)
{
	Node<T> *tempNode= currNode->leftNode;
	currNode->leftNode = tempNode->rightNode;
	if (tempNode->rightNode != NIL)
		tempNode->rightNode->parNode = currNode;
	if (tempNode!= NIL)
		tempNode->parNode = currNode->parNode;
	if (currNode->parNode != NIL)
	{
		if (currNode == currNode->parNode->rightNode)
			currNode->parNode->rightNode = tempNode;
		else
			currNode->parNode->leftNode = tempNode;
	}
	else
	{
		root = tempNode;
	}

	tempNode->rightNode = currNode;
	if (currNode != NIL)
		currNode->parNode = tempNode;
}

template <typename T>
void RedBlackTree<T>::insertFix(Node<T>* currNode)
{
	while (currNode != root && currNode->parNode->color == RED)
	{
		if (currNode->parNode == currNode->parNode->parNode->leftNode)
		{
			Node<T>* tempNode= currNode->parNode->parNode->rightNode;
			if (tempNode->color == RED)
			{
				currNode->parNode->color = BLACK;
				tempNode->color = BLACK;
				currNode->parNode->parNode->color = RED;
				currNode = currNode->parNode->parNode;
			}

			else
			{
				if (currNode == currNode->parNode->rightNode)
				{
					currNode = currNode->parNode;
					left_rotate(currNode);
				}
				currNode->parNode->color = BLACK;
				currNode->parNode->parNode->color = RED;
				right_rotate(currNode->parNode->parNode);
			}
		}

		else
		{
			Node<T>* tempNode= currNode->parNode->parNode->leftNode;
			if (tempNode->color == RED)
			{
				currNode->parNode->color = BLACK;
				tempNode->color = BLACK;
				currNode->parNode->parNode->color = RED;
				currNode = currNode->parNode->parNode;
			}
			else
			{
				if (currNode == currNode->parNode->leftNode)
				{
					currNode = currNode->parNode;
					right_rotate(currNode);
				}
				currNode->parNode->color = BLACK;
				currNode->parNode->parNode->color = RED;
				left_rotate(currNode->parNode->parNode);
			}
		}
	}
	root->color = BLACK;
}

template <typename T>
void RedBlackTree<T>::insert(const T& value)
{
	if (findElement(value))
	{
		throw std::logic_error("This value is already added!\n");
	}
	Node<T>* child = new Node<T>;
	child->value = value;
	child->color = RED;
	child->leftNode = child->rightNode = child->parNode = NIL;
	Node<T>* parNode = NIL;
	Node<T>* tempNode= root;
	if (root == NIL)
	{
		root = child;
		root->color = BLACK;
		return;
	}
	while (tempNode!= NIL)
	{

		if (child->value == tempNode->value)
			return;

		parNode = tempNode;
		if (value < tempNode->value)
			tempNode= tempNode->leftNode;
		else
			tempNode= tempNode->rightNode;
	}
	if (value < parNode->value)
	{
		parNode->leftNode = child;
	}
	else
	{
		parNode->rightNode = child;

	}
	child->parNode = parNode;
	insertFix(child);
}

template <typename T>
void RedBlackTree<T>::print(const Node<T>* tempNode, int level)const
{
		if (root == NIL)
		{
			throw std::logic_error("Error! The tree is empty!\n");
		}
		if (tempNode!= NIL)
		{
			print(tempNode->leftNode, level + 1);
			for (int i = 0; i < level; i++)
				std::cout << "\t";
			std::cout << "(" << tempNode->color << ")";
			std::cout << tempNode->value << "\n";
			print(tempNode->rightNode, level + 1);
		}
	}

template <typename T>
Node<T>* RedBlackTree<T>::findElement(const T& value) const
{
	Node<T>* currNode = root;
	while (currNode != NIL)
	{
		if (value == currNode->value)
			return currNode;
		else
		{
			if (value < currNode->value)
				currNode = currNode->leftNode;
			else currNode = currNode->rightNode;
		}
	}
	return 0;
}
<commit_msg>Update red_black_tree.hpp<commit_after>#include <iostream>
#include <stdexcept>

const bool BLACK = 1;
const bool RED = 0;

template<typename T>
struct Node
{
	T value;
	bool color;
	Node* leftNode;
	Node* rightNode;
	Node* parNode;
};

template<typename T>
class RedBlackTree
{
private:
	Node<T>* root;
	Node<T>* NIL;
public:
	RedBlackTree();
	bool _color(const T& value) const;
	Node<T>* _root() const;
	Node<T>* _NIL() const;
	void left_rotate(Node<T>* currNode);
	void right_rotate(Node<T>* currNode);
	void insertFix(Node<T>* currNode);
	void insert(const T& value);
	void print(const Node<T>* tempNode, int level) const;
	Node<T>* findElement(const T& value) const;
};

template <typename T>
RedBlackTree<T>::RedBlackTree()
{
	NIL = new Node<T>;
	NIL->leftNode = NIL->parNode = NIL->rightNode = nullptr;
	NIL->color = BLACK;
	root = NIL;
}

template <typename T>
bool RedBlackTree<T>::_color(const T& value) const
{
	return findElement(value)->color;
}

template <typename T>
Node<T>* RedBlackTree<T>::_root() const
{
	return root;
}

template <typename T>
Node<T>* RedBlackTree<T>::_NIL()const
{
	return NIL;
}

template <typename T>
void RedBlackTree<T>::left_rotate(Node<T>* currNode)
{
	Node<T>* tempNode= currNode->rightNode;
	currNode->rightNode = tempNode->leftNode;
	if (tempNode->leftNode != NIL)
		tempNode->leftNode->parNode = currNode;
	if (tempNode!= NIL)
		tempNode->parNode = currNode->parNode;
	if (currNode->parNode != NIL)
	{
		if (currNode == currNode->parNode->leftNode)
			currNode->parNode->leftNode = tempNode;
		else
			currNode->parNode->rightNode = tempNode;
	}
	else
	{
		root = tempNode;
	}
	tempNode->leftNode = currNode;
	if (currNode != NIL)
		currNode->parNode = tempNode;
}

template <typename T>
void RedBlackTree<T>::right_rotate(Node<T> *currNode)
{
	Node<T> *tempNode= currNode->leftNode;
	currNode->leftNode = tempNode->rightNode;
	if (tempNode->rightNode != NIL)
		tempNode->rightNode->parNode = currNode;
	if (tempNode!= NIL)
		tempNode->parNode = currNode->parNode;
	if (currNode->parNode != NIL)
	{
		if (currNode == currNode->parNode->rightNode)
			currNode->parNode->rightNode = tempNode;
		else
			currNode->parNode->leftNode = tempNode;
	}
	else
	{
		root = tempNode;
	}

	tempNode->rightNode = currNode;
	if (currNode != NIL)
		currNode->parNode = tempNode;
}

template <typename T>
void RedBlackTree<T>::insertFix(Node<T>* currNode)
{
	while (currNode != root && currNode->parNode->color == RED)
	{
		if (currNode->parNode == currNode->parNode->parNode->leftNode)
		{
			Node<T>* tempNode= currNode->parNode->parNode->rightNode;
			if (tempNode->color == RED)
			{
				currNode->parNode->color = BLACK;
				tempNode->color = BLACK;
				currNode->parNode->parNode->color = RED;
				currNode = currNode->parNode->parNode;
			}

			else
			{
				if (currNode == currNode->parNode->rightNode)
				{
					currNode = currNode->parNode;
					left_rotate(currNode);
				}
				currNode->parNode->color = BLACK;
				currNode->parNode->parNode->color = RED;
				right_rotate(currNode->parNode->parNode);
			}
		}

		else
		{
			Node<T>* tempNode= currNode->parNode->parNode->leftNode;
			if (tempNode->color == RED)
			{
				currNode->parNode->color = BLACK;
				tempNode->color = BLACK;
				currNode->parNode->parNode->color = RED;
				currNode = currNode->parNode->parNode;
			}
			else
			{
				if (currNode == currNode->parNode->leftNode)
				{
					currNode = currNode->parNode;
					right_rotate(currNode);
				}
				currNode->parNode->color = BLACK;
				currNode->parNode->parNode->color = RED;
				left_rotate(currNode->parNode->parNode);
			}
		}
	}
	root->color = BLACK;
}

template <typename T>
void RedBlackTree<T>::insert(const T& value)
{
	if (findElement(value))
	{
		throw std::logic_error("This value is already added!\n");
	}
	Node<T>* child = new Node<T>;
	child->value = value;
	child->color = RED;
	child->leftNode = child->rightNode = child->parNode = NIL;
	Node<T>* parNode = NIL;
	Node<T>* tempNode= root;
	if (root == NIL)
	{
		root = child;
		root->color = BLACK;
		return;
	}
	while (tempNode!= NIL)
	{

		if (child->value == tempNode->value)
			return;

		parNode = tempNode;
		if (value < tempNode->value)
			tempNode= tempNode->leftNode;
		else
			tempNode= tempNode->rightNode;
	}
	if (value < parNode->value)
	{
		parNode->leftNode = child;
	}
	else
	{
		parNode->rightNode = child;

	}
	child->parNode = parNode;
	insertFix(child);
}

template <typename T>
void RedBlackTree<T>::print(const Node<T>* tempNode, int level)const
{
		if (root == NIL)
		{
			throw std::logic_error("Error! The tree is empty!\n");
		}
		if (tempNode!= NIL)
		{
			print(tempNode->leftNode, level + 1);
			for (int i = 0; i < level; i++)
				std::cout << "\t";
			std::cout << "(" << tempNode->color << ")";
			std::cout << tempNode->value << "\n";
			print(tempNode->rightNode, level + 1);
		}
	}

template <typename T>
Node<T>* RedBlackTree<T>::findElement(const T& value) const
{
	Node<T>* currNode = root;
	while (currNode != NIL)
	{
		if (value == currNode->value)
			return currNode;
		else
		{
			if (value < currNode->value)
				currNode = currNode->leftNode;
			else currNode = currNode->rightNode;
		}
	}
	return 0;
}
<|endoftext|>


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

  Program:   Visualization Toolkit
  Module:    vtkPProbeFilter.cxx

  Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen
  All rights reserved.
  See Copyright.txt or http://www.kitware.com/Copyright.htm for details.

     This software is distributed WITHOUT ANY WARRANTY; without even
     the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
     PURPOSE.  See the above copyright notice for more information.

=========================================================================*/
#include "vtkPProbeFilter.h"

#include "vtkCompositeDataPipeline.h"
#include "vtkCharArray.h"
#include "vtkInformation.h"
#include "vtkInformationVector.h"
#include "vtkMultiProcessController.h"
#include "vtkObjectFactory.h"
#include "vtkPointData.h"
#include "vtkCellData.h"
#include "vtkPolyData.h"
#include "vtkStreamingDemandDrivenPipeline.h"

vtkCxxRevisionMacro(vtkPProbeFilter, "1.22");
vtkStandardNewMacro(vtkPProbeFilter);

vtkCxxSetObjectMacro(vtkPProbeFilter, Controller, vtkMultiProcessController);

//----------------------------------------------------------------------------
vtkPProbeFilter::vtkPProbeFilter()
{
  this->Controller = 0;
  this->SetController(vtkMultiProcessController::GetGlobalController());
}

//----------------------------------------------------------------------------
vtkPProbeFilter::~vtkPProbeFilter()
{
  this->SetController(0);
}

//----------------------------------------------------------------------------
int vtkPProbeFilter::RequestInformation(vtkInformation *request,
                                        vtkInformationVector **inputVector,
                                        vtkInformationVector *outputVector)
{
  this->Superclass::RequestInformation(request, inputVector, outputVector);
  vtkInformation *outInfo = outputVector->GetInformationObject(0);
  outInfo->Set(vtkStreamingDemandDrivenPipeline::MAXIMUM_NUMBER_OF_PIECES(),
               -1);
  return 1;
}

//----------------------------------------------------------------------------
int vtkPProbeFilter::RequestData(vtkInformation *request,
                                 vtkInformationVector **inputVector,
                                 vtkInformationVector *outputVector)
{
  if (!this->Superclass::RequestData(request, inputVector, outputVector))
    {
    return 0;
    }

  vtkInformation *outInfo = outputVector->GetInformationObject(0);
  vtkDataSet *output = vtkDataSet::SafeDownCast(
    outInfo->Get(vtkDataObject::DATA_OBJECT()));

  int procid = 0;
  int numProcs = 1;
  if ( this->Controller )
    {
    procid = this->Controller->GetLocalProcessId();
    numProcs = this->Controller->GetNumberOfProcesses();
    }

  vtkIdType numPoints = this->NumberOfValidPoints;
  if ( procid )
    {
    // Satellite node
    this->Controller->Send(&numPoints, 1, 0, PROBE_COMMUNICATION_TAG);
    if ( numPoints > 0 )
      {
      this->Controller->Send(output, 0, PROBE_COMMUNICATION_TAG);
      }
    output->ReleaseData();
    }
  else if ( numProcs > 1 )
    {
    vtkIdType numRemoteValidPoints = 0;
    vtkDataSet *remoteProbeOutput = output->NewInstance();
    vtkPointData *remotePointData;
    vtkPointData *pointData = output->GetPointData();
    vtkIdType i;
    vtkIdType k;
    vtkIdType pointId;
    for (i = 1; i < numProcs; i++)
      {
      this->Controller->Receive(&numRemoteValidPoints, 1, i, PROBE_COMMUNICATION_TAG);
      if (numRemoteValidPoints > 0)
        {
        this->Controller->Receive(remoteProbeOutput, i, PROBE_COMMUNICATION_TAG);

        remotePointData = remoteProbeOutput->GetPointData();

        vtkCharArray* maskArray = vtkCharArray::SafeDownCast(
          remotePointData->GetArray(this->ValidPointMaskArrayName));

        // Iterate over all point data in the output gathered from the remove
        // and copy array values from all the pointIds which have the mask array
        // bit set to 1.
        vtkIdType numRemotePoints = remoteProbeOutput->GetNumberOfPoints();
        for (pointId=0; (pointId < numRemotePoints) && maskArray; pointId++)
          {
          if (maskArray->GetValue(pointId) == 1)
            {
            for (k = 0; k < pointData->GetNumberOfArrays(); k++)
              {
              vtkAbstractArray *oaa = pointData->GetArray(k);
              vtkAbstractArray *raa = remotePointData->GetArray(oaa->GetName());
              if (raa != NULL)
                {
                oaa->SetTuple(pointId, pointId, raa);
                }
              }
            }
          }
        }
      }
    remoteProbeOutput->Delete();
    }

  return 1;
}

//----------------------------------------------------------------------------
int vtkPProbeFilter::RequestUpdateExtent(vtkInformation *,
                                         vtkInformationVector **inputVector,
                                         vtkInformationVector *outputVector)
{
  vtkInformation *inInfo = inputVector[0]->GetInformationObject(0);
  vtkInformation *sourceInfo = inputVector[1]->GetInformationObject(0);
  vtkInformation *outInfo = outputVector->GetInformationObject(0);

  inInfo->Set(vtkStreamingDemandDrivenPipeline::UPDATE_PIECE_NUMBER(), 0);
  inInfo->Set(vtkStreamingDemandDrivenPipeline::UPDATE_NUMBER_OF_PIECES(), 1);
  inInfo->Set(vtkStreamingDemandDrivenPipeline::UPDATE_NUMBER_OF_GHOST_LEVELS(),
              0);
  sourceInfo->Set(
    vtkStreamingDemandDrivenPipeline::UPDATE_PIECE_NUMBER(),
    outInfo->Get(vtkStreamingDemandDrivenPipeline::UPDATE_PIECE_NUMBER()));
  sourceInfo->Set(
    vtkStreamingDemandDrivenPipeline::UPDATE_NUMBER_OF_PIECES(),
    outInfo->Get(vtkStreamingDemandDrivenPipeline::UPDATE_NUMBER_OF_PIECES()));
  sourceInfo->Set(
    vtkStreamingDemandDrivenPipeline::UPDATE_NUMBER_OF_GHOST_LEVELS(),
    outInfo->Get(vtkStreamingDemandDrivenPipeline::UPDATE_NUMBER_OF_GHOST_LEVELS()));

  return 1;
}

//----------------------------------------------------------------------------
int vtkPProbeFilter::FillInputPortInformation(int port, vtkInformation *info)
{
  if (!this->Superclass::FillInputPortInformation(port, info))
    {
    return 0;
    }

  if (port == 1)
    {
    info->Set(vtkAlgorithm::INPUT_REQUIRED_DATA_TYPE(), "vtkDataObject");
    }
  return 1;
}

//----------------------------------------------------------------------------
void vtkPProbeFilter::PrintSelf(ostream& os, vtkIndent indent)
{
  this->Superclass::PrintSelf(os,indent);
  os << indent << "Controller " << this->Controller << endl;
}
<commit_msg>BUG: Fixed bug in the parallel probe filter.<commit_after>/*=========================================================================

  Program:   Visualization Toolkit
  Module:    vtkPProbeFilter.cxx

  Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen
  All rights reserved.
  See Copyright.txt or http://www.kitware.com/Copyright.htm for details.

     This software is distributed WITHOUT ANY WARRANTY; without even
     the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
     PURPOSE.  See the above copyright notice for more information.

=========================================================================*/
#include "vtkPProbeFilter.h"

#include "vtkCompositeDataPipeline.h"
#include "vtkCharArray.h"
#include "vtkInformation.h"
#include "vtkInformationVector.h"
#include "vtkMultiProcessController.h"
#include "vtkObjectFactory.h"
#include "vtkPointData.h"
#include "vtkCellData.h"
#include "vtkOnePieceExtentTranslator.h"
#include "vtkPolyData.h"
#include "vtkStreamingDemandDrivenPipeline.h"

vtkCxxRevisionMacro(vtkPProbeFilter, "1.22.12.1");
vtkStandardNewMacro(vtkPProbeFilter);

vtkCxxSetObjectMacro(vtkPProbeFilter, Controller, vtkMultiProcessController);

//----------------------------------------------------------------------------
vtkPProbeFilter::vtkPProbeFilter()
{
  this->Controller = 0;
  this->SetController(vtkMultiProcessController::GetGlobalController());
}

//----------------------------------------------------------------------------
vtkPProbeFilter::~vtkPProbeFilter()
{
  this->SetController(0);
}

//----------------------------------------------------------------------------
int vtkPProbeFilter::RequestInformation(vtkInformation *request,
                                        vtkInformationVector **inputVector,
                                        vtkInformationVector *outputVector)
{
  this->Superclass::RequestInformation(request, inputVector, outputVector);
  vtkInformation *outInfo = outputVector->GetInformationObject(0);
  outInfo->Set(vtkStreamingDemandDrivenPipeline::MAXIMUM_NUMBER_OF_PIECES(),
               -1);

  // Setup ExtentTranslator so that all downstream piece requests are
  // converted to whole extent update requests, as need by this filter.
  vtkStreamingDemandDrivenPipeline* sddp =
    vtkStreamingDemandDrivenPipeline::SafeDownCast(this->GetExecutive());
  if (strcmp(
      sddp->GetExtentTranslator(outInfo)->GetClassName(),
      "vtkOnePieceExtentTranslator") != 0)
    {
    vtkExtentTranslator* et = vtkOnePieceExtentTranslator::New();
    sddp->SetExtentTranslator(outInfo, et);
    et->Delete();
    }

  return 1;
}

//----------------------------------------------------------------------------
int vtkPProbeFilter::RequestData(vtkInformation *request,
                                 vtkInformationVector **inputVector,
                                 vtkInformationVector *outputVector)
{
  if (!this->Superclass::RequestData(request, inputVector, outputVector))
    {
    return 0;
    }

  vtkInformation *outInfo = outputVector->GetInformationObject(0);
  vtkDataSet *output = vtkDataSet::SafeDownCast(
    outInfo->Get(vtkDataObject::DATA_OBJECT()));

  int procid = 0;
  int numProcs = 1;
  if ( this->Controller )
    {
    procid = this->Controller->GetLocalProcessId();
    numProcs = this->Controller->GetNumberOfProcesses();
    }

  vtkIdType numPoints = this->NumberOfValidPoints;
  if ( procid )
    {
    // Satellite node
    this->Controller->Send(&numPoints, 1, 0, PROBE_COMMUNICATION_TAG);
    if ( numPoints > 0 )
      {
      this->Controller->Send(output, 0, PROBE_COMMUNICATION_TAG);
      }
    output->ReleaseData();
    }
  else if ( numProcs > 1 )
    {
    vtkIdType numRemoteValidPoints = 0;
    vtkDataSet *remoteProbeOutput = output->NewInstance();
    vtkPointData *remotePointData;
    vtkPointData *pointData = output->GetPointData();
    vtkIdType i;
    vtkIdType k;
    vtkIdType pointId;
    for (i = 1; i < numProcs; i++)
      {
      this->Controller->Receive(&numRemoteValidPoints, 1, i, PROBE_COMMUNICATION_TAG);
      if (numRemoteValidPoints > 0)
        {
        this->Controller->Receive(remoteProbeOutput, i, PROBE_COMMUNICATION_TAG);

        remotePointData = remoteProbeOutput->GetPointData();

        vtkCharArray* maskArray = vtkCharArray::SafeDownCast(
          remotePointData->GetArray(this->ValidPointMaskArrayName));

        // Iterate over all point data in the output gathered from the remove
        // and copy array values from all the pointIds which have the mask array
        // bit set to 1.
        vtkIdType numRemotePoints = remoteProbeOutput->GetNumberOfPoints();
        for (pointId=0; (pointId < numRemotePoints) && maskArray; pointId++)
          {
          if (maskArray->GetValue(pointId) == 1)
            {
            for (k = 0; k < pointData->GetNumberOfArrays(); k++)
              {
              vtkAbstractArray *oaa = pointData->GetArray(k);
              vtkAbstractArray *raa = remotePointData->GetArray(oaa->GetName());
              if (raa != NULL)
                {
                oaa->SetTuple(pointId, pointId, raa);
                }
              }
            }
          }
        }
      }
    remoteProbeOutput->Delete();
    }

  return 1;
}

#include "vtkInformationIntegerVectorKey.h"
//----------------------------------------------------------------------------
int vtkPProbeFilter::RequestUpdateExtent(vtkInformation *,
                                         vtkInformationVector **inputVector,
                                         vtkInformationVector *outputVector)
{
  vtkInformation *inInfo = inputVector[0]->GetInformationObject(0);
  vtkInformation *sourceInfo = inputVector[1]->GetInformationObject(0);
  vtkInformation *outInfo = outputVector->GetInformationObject(0);

  vtkStreamingDemandDrivenPipeline* sddp =
    vtkStreamingDemandDrivenPipeline::SafeDownCast(this->GetExecutive());
  if (sddp)
    {
    sddp->SetUpdateExtentToWholeExtent(inInfo);
    }

//inInfo->Set(vtkStreamingDemandDrivenPipeline::UPDATE_PIECE_NUMBER(), 0);
//inInfo->Set(vtkStreamingDemandDrivenPipeline::UPDATE_NUMBER_OF_PIECES(), 1);
//inInfo->Set(vtkStreamingDemandDrivenPipeline::UPDATE_NUMBER_OF_GHOST_LEVELS(),
//            0);
  sourceInfo->Set(
    vtkStreamingDemandDrivenPipeline::UPDATE_PIECE_NUMBER(),
    outInfo->Get(vtkStreamingDemandDrivenPipeline::UPDATE_PIECE_NUMBER()));
  sourceInfo->Set(
    vtkStreamingDemandDrivenPipeline::UPDATE_NUMBER_OF_PIECES(),
    outInfo->Get(vtkStreamingDemandDrivenPipeline::UPDATE_NUMBER_OF_PIECES()));
  sourceInfo->Set(
    vtkStreamingDemandDrivenPipeline::UPDATE_NUMBER_OF_GHOST_LEVELS(),
    outInfo->Get(vtkStreamingDemandDrivenPipeline::UPDATE_NUMBER_OF_GHOST_LEVELS()));

  return 1;
}

//----------------------------------------------------------------------------
int vtkPProbeFilter::FillInputPortInformation(int port, vtkInformation *info)
{
  if (!this->Superclass::FillInputPortInformation(port, info))
    {
    return 0;
    }

  if (port == 1)
    {
    info->Set(vtkAlgorithm::INPUT_REQUIRED_DATA_TYPE(), "vtkDataObject");
    }
  return 1;
}

//----------------------------------------------------------------------------
void vtkPProbeFilter::PrintSelf(ostream& os, vtkIndent indent)
{
  this->Superclass::PrintSelf(os,indent);
  os << indent << "Controller " << this->Controller << endl;
}
<|endoftext|>