<commit_before>/*************************************************************************
 *
 *  $RCSfile: conpoly.cxx,v $
 *
 *  $Revision: 1.2 $
 *
 *  last change: $Author: os $ $Date: 2002-12-05 12:47:05 $
 *
 *  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): _______________________________________
 *
 *
 ************************************************************************/

#ifdef PRECOMPILED
#include "ui_pch.hxx"
#endif

#pragma hdrstop

#ifndef _SVDMARK_HXX //autogen
#include <svx/svdmark.hxx>
#endif
#ifndef _SVDVIEW_HXX //autogen
#include <svx/svdview.hxx>
#endif
#ifndef _SVDOPATH_HXX //autogen
#include <svx/svdopath.hxx>
#endif

#include "view.hxx"
#include "edtwin.hxx"
#include "wrtsh.hxx"
#include "drawbase.hxx"
#include "conpoly.hxx"

/************************************************************************/

#define CLOSE_PIXDIST   5   // Pixelabstand, ab dem geschlossen wird

/*************************************************************************
|*
|* Konstruktor
|*
\************************************************************************/

ConstPolygon::ConstPolygon(SwWrtShell* pWrtShell, SwEditWin* pEditWin, SwView* pSwView) :
                SwDrawBase(pWrtShell, pEditWin, pSwView)
{
}

/*************************************************************************
|*
|* MouseButtonDown-event
|*
\************************************************************************/

BOOL ConstPolygon::MouseButtonDown(const MouseEvent& rMEvt)
{
    BOOL bReturn;

    if ((bReturn = SwDrawBase::MouseButtonDown(rMEvt)) == TRUE)
        aLastPos = rMEvt.GetPosPixel();

    return (bReturn);
}

/*************************************************************************
|*
|* MouseMove-event
|*
\************************************************************************/

BOOL ConstPolygon::MouseMove(const MouseEvent& rMEvt)
{
    BOOL bReturn = FALSE;

    bReturn = SwDrawBase::MouseMove(rMEvt);

    return bReturn;
}

/*************************************************************************
|*
|* MouseButtonUp-event
|*
\************************************************************************/

BOOL ConstPolygon::MouseButtonUp(const MouseEvent& rMEvt)
{
    BOOL bReturn = FALSE;

    if (pSh->IsDrawCreate())
    {
        if (rMEvt.IsLeft() && rMEvt.GetClicks() == 1 &&
                                        pWin->GetDrawMode() != OBJ_FREELINE)
        {
            if (!pSh->EndCreate(SDRCREATE_NEXTPOINT))
            {
                pSh->BreakCreate();
                EnterSelectMode(rMEvt);
                return TRUE;
            }
        }
        else
        {
            Point aPnt(pWin->PixelToLogic(rMEvt.GetPosPixel()));
            bReturn = SwDrawBase::MouseButtonUp(rMEvt);

            if (!(bReturn && (aPnt == aStartPos || rMEvt.IsRight())))
            {
                SdrView *pSdrView = pSh->GetDrawView();

                long nCloseDist = pWin->PixelToLogic(Size(CLOSE_PIXDIST, 0)).Width();
                const SdrMarkList& rMarkList = pSdrView->GetMarkList();
                if (rMarkList.GetMark(0))
                {
                    SdrPathObj* pPathObj = (SdrPathObj *)rMarkList.GetMark(0)->GetObj();
                    const XPolyPolygon& rXPP = pPathObj->GetPathPoly();
                    if (rXPP.Count() == 1)
                    {
                        USHORT nPntMax = rXPP[0].GetPointCount() - 1;
                        Point aDiff = rXPP[0][nPntMax] - rXPP[0][0];
                        long nSqDist = aDiff.X() * aDiff.X() + aDiff.Y() * aDiff.Y();
                        nCloseDist *= nCloseDist;

                        if (nSqDist <= nCloseDist && !pPathObj->IsClosed())
                            pPathObj->ToggleClosed(0);
                    }
                }
            }
        }
    }
    else
        bReturn = SwDrawBase::MouseButtonUp(rMEvt);

    return (bReturn);
}

/*************************************************************************
|*
|* Function aktivieren
|*
\************************************************************************/

void ConstPolygon::Activate(const USHORT nSlotId)
{
    switch (nSlotId)
    {
        case SID_DRAW_POLYGON_NOFILL:
            pWin->SetDrawMode(OBJ_PLIN);
            break;

        case SID_DRAW_BEZIER_NOFILL:
            pWin->SetDrawMode(OBJ_PATHLINE);
            break;

        case SID_DRAW_FREELINE_NOFILL:
            pWin->SetDrawMode(OBJ_FREELINE);
            break;

        default:
            break;
    }

    SwDrawBase::Activate(nSlotId);
}

<commit_msg>INTEGRATION: CWS os8 (1.2.138); FILE MERGED 2003/04/03 07:14:53 os 1.2.138.1: #108583# precompiled headers removed<commit_after>/*************************************************************************
 *
 *  $RCSfile: conpoly.cxx,v $
 *
 *  $Revision: 1.3 $
 *
 *  last change: $Author: vg $ $Date: 2003-04-17 15:38:46 $
 *
 *  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): _______________________________________
 *
 *
 ************************************************************************/

#pragma hdrstop

#ifndef _SVDMARK_HXX //autogen
#include <svx/svdmark.hxx>
#endif
#ifndef _SVDVIEW_HXX //autogen
#include <svx/svdview.hxx>
#endif
#ifndef _SVDOPATH_HXX //autogen
#include <svx/svdopath.hxx>
#endif

#include "view.hxx"
#include "edtwin.hxx"
#include "wrtsh.hxx"
#include "drawbase.hxx"
#include "conpoly.hxx"

/************************************************************************/

#define CLOSE_PIXDIST   5   // Pixelabstand, ab dem geschlossen wird

/*************************************************************************
|*
|* Konstruktor
|*
\************************************************************************/

ConstPolygon::ConstPolygon(SwWrtShell* pWrtShell, SwEditWin* pEditWin, SwView* pSwView) :
                SwDrawBase(pWrtShell, pEditWin, pSwView)
{
}

/*************************************************************************
|*
|* MouseButtonDown-event
|*
\************************************************************************/

BOOL ConstPolygon::MouseButtonDown(const MouseEvent& rMEvt)
{
    BOOL bReturn;

    if ((bReturn = SwDrawBase::MouseButtonDown(rMEvt)) == TRUE)
        aLastPos = rMEvt.GetPosPixel();

    return (bReturn);
}

/*************************************************************************
|*
|* MouseMove-event
|*
\************************************************************************/

BOOL ConstPolygon::MouseMove(const MouseEvent& rMEvt)
{
    BOOL bReturn = FALSE;

    bReturn = SwDrawBase::MouseMove(rMEvt);

    return bReturn;
}

/*************************************************************************
|*
|* MouseButtonUp-event
|*
\************************************************************************/

BOOL ConstPolygon::MouseButtonUp(const MouseEvent& rMEvt)
{
    BOOL bReturn = FALSE;

    if (pSh->IsDrawCreate())
    {
        if (rMEvt.IsLeft() && rMEvt.GetClicks() == 1 &&
                                        pWin->GetDrawMode() != OBJ_FREELINE)
        {
            if (!pSh->EndCreate(SDRCREATE_NEXTPOINT))
            {
                pSh->BreakCreate();
                EnterSelectMode(rMEvt);
                return TRUE;
            }
        }
        else
        {
            Point aPnt(pWin->PixelToLogic(rMEvt.GetPosPixel()));
            bReturn = SwDrawBase::MouseButtonUp(rMEvt);

            if (!(bReturn && (aPnt == aStartPos || rMEvt.IsRight())))
            {
                SdrView *pSdrView = pSh->GetDrawView();

                long nCloseDist = pWin->PixelToLogic(Size(CLOSE_PIXDIST, 0)).Width();
                const SdrMarkList& rMarkList = pSdrView->GetMarkList();
                if (rMarkList.GetMark(0))
                {
                    SdrPathObj* pPathObj = (SdrPathObj *)rMarkList.GetMark(0)->GetObj();
                    const XPolyPolygon& rXPP = pPathObj->GetPathPoly();
                    if (rXPP.Count() == 1)
                    {
                        USHORT nPntMax = rXPP[0].GetPointCount() - 1;
                        Point aDiff = rXPP[0][nPntMax] - rXPP[0][0];
                        long nSqDist = aDiff.X() * aDiff.X() + aDiff.Y() * aDiff.Y();
                        nCloseDist *= nCloseDist;

                        if (nSqDist <= nCloseDist && !pPathObj->IsClosed())
                            pPathObj->ToggleClosed(0);
                    }
                }
            }
        }
    }
    else
        bReturn = SwDrawBase::MouseButtonUp(rMEvt);

    return (bReturn);
}

/*************************************************************************
|*
|* Function aktivieren
|*
\************************************************************************/

void ConstPolygon::Activate(const USHORT nSlotId)
{
    switch (nSlotId)
    {
        case SID_DRAW_POLYGON_NOFILL:
            pWin->SetDrawMode(OBJ_PLIN);
            break;

        case SID_DRAW_BEZIER_NOFILL:
            pWin->SetDrawMode(OBJ_PATHLINE);
            break;

        case SID_DRAW_FREELINE_NOFILL:
            pWin->SetDrawMode(OBJ_FREELINE);
            break;

        default:
            break;
    }

    SwDrawBase::Activate(nSlotId);
}

<|endoftext|>


<commit_before>
#include "Globals.h"  // NOTE: MSVC stupidness requires this to be the same across all modules

#include "BeaconEntity.h"
#include "../BlockArea.h"

cBeaconEntity::cBeaconEntity(int a_BlockX, int a_BlockY, int a_BlockZ, cWorld * a_World) :
	super(E_BLOCK_BEACON, a_BlockX, a_BlockY, a_BlockZ, a_World)
{
}

int cBeaconEntity::GetPyramidLevel()
{
	cBlockArea Area;
	Area.Read(
		m_World,
		GetPosX() - 4,
		GetPosX() + 4,
		GetPosY() - 5,
		GetPosY() - 1,
		GetPosZ() - 4,
		GetPosZ() + 4
	);

	int Layer = 1;
	int MiddleXZ = 4;

	for (int Y = Area.GetSizeY() - 1; Y > 0; Y--)
	{
		bool FullLayer = true;
		for (int X = MiddleXZ - Layer; X <= (MiddleXZ + Layer); X++)
		{
			for (int Z = MiddleXZ - Layer; Z <= (MiddleXZ + Layer); Z++)
			{
				if (!IsMineralBlock(Area.GetRelBlockType(X, Y, Z)))
				{
					FullLayer = false;
				}
			}
		}
		if (!FullLayer)
		{
			break;
		}
		else
		{
			Layer++;
		}
	}

	return Layer;
}

bool cBeaconEntity::IsMineralBlock(BLOCKTYPE a_BlockType)
{
	switch(a_BlockType)
	{
		case E_BLOCK_DIAMOND_BLOCK:
		case E_BLOCK_GOLD_BLOCK:
		case E_BLOCK_IRON_BLOCK:
		case E_BLOCK_EMERALD_BLOCK:
		{
			return true;
		}
	}
	return false;
}

bool cBeaconEntity::Tick(float a_Dt, cChunk & a_Chunk)
{
	return false;
}

void cBeaconEntity::SaveToJson(Json::Value& a_Value)
{
}

void cBeaconEntity::SendTo(cClientHandle & a_Client)
{
}

void cBeaconEntity::UsedBy(cPlayer * a_Player)
{
}<commit_msg>Simplefied GetPyramidLevel<commit_after>
#include "Globals.h"  // NOTE: MSVC stupidness requires this to be the same across all modules

#include "BeaconEntity.h"
#include "../BlockArea.h"

cBeaconEntity::cBeaconEntity(int a_BlockX, int a_BlockY, int a_BlockZ, cWorld * a_World) :
	super(E_BLOCK_BEACON, a_BlockX, a_BlockY, a_BlockZ, a_World)
{
}

int cBeaconEntity::GetPyramidLevel()
{
	cBlockArea Area;
	Area.Read(
		m_World,
		GetPosX() - 4,
		GetPosX() + 4,
		GetPosY() - 5,
		GetPosY() - 1,
		GetPosZ() - 4,
		GetPosZ() + 4
	);

	int Layer = 1;
	int MiddleXZ = 4;

	for (int Y = Area.GetSizeY() - 1; Y > 0; Y--)
	{
		for (int X = MiddleXZ - Layer; X <= (MiddleXZ + Layer); X++)
		{
			for (int Z = MiddleXZ - Layer; Z <= (MiddleXZ + Layer); Z++)
			{
				if (!IsMineralBlock(Area.GetRelBlockType(X, Y, Z)))
				{
					return Layer;
				}
			}
		}
		Layer++;
	}

	return Layer;
}

bool cBeaconEntity::IsMineralBlock(BLOCKTYPE a_BlockType)
{
	switch(a_BlockType)
	{
		case E_BLOCK_DIAMOND_BLOCK:
		case E_BLOCK_GOLD_BLOCK:
		case E_BLOCK_IRON_BLOCK:
		case E_BLOCK_EMERALD_BLOCK:
		{
			return true;
		}
	}
	return false;
}

bool cBeaconEntity::Tick(float a_Dt, cChunk & a_Chunk)
{
	std::cout << GetPyramidLevel() << "\n";
	return false;
}

void cBeaconEntity::SaveToJson(Json::Value& a_Value)
{
}

void cBeaconEntity::SendTo(cClientHandle & a_Client)
{
}

void cBeaconEntity::UsedBy(cPlayer * a_Player)
{
}<|endoftext|>


<commit_before>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: grfshex.cxx,v $
 *
 *  $Revision: 1.16 $
 *
 *  last change: $Author: hr $ $Date: 2006-08-14 17:54:10 $
 *
 *  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
 *
 ************************************************************************/

#pragma hdrstop

#ifndef _DOCARY_HXX
#include <docary.hxx>
#endif
#ifndef _GRFSH_HXX
#include <grfsh.hxx>
#endif
#ifndef _WRTSH_HXX
#include <wrtsh.hxx>
#endif
#ifndef _VIEW_HXX
#include <view.hxx>
#endif
#ifndef _DOCARY_HXX
#include <docary.hxx>
#endif
#ifndef _TEXTSH_HXX
#include <textsh.hxx>
#endif
#ifndef _VIEWOPT_HXX
#include <viewopt.hxx>
#endif
#ifndef _SWUNDO_HXX
#include <swundo.hxx>
#endif
#ifndef _SHELLS_HRC
#include <shells.hrc>
#endif
#ifndef _CAPTION_HXX
#include <caption.hxx>
#endif
#define _SVSTDARR_STRINGSSORTDTOR
#include <svtools/svstdarr.hxx>
#ifndef _FILTER_HXX
#include <svtools/filter.hxx>
#endif
#ifndef _SVX_IMPGRF_HXX
#include <svx/impgrf.hxx>
#endif
#ifndef _SVX_HTMLMODE_HXX //autogen
#include <svx/htmlmode.hxx>
#endif
#ifndef _DOCSH_HXX
#include <docsh.hxx>
#endif
#ifndef _FRMFMT_HXX
#include <frmfmt.hxx>
#endif
#ifndef _FRMMGR_HXX
#include <frmmgr.hxx>
#endif
#ifndef _SV_MSGBOX_HXX
#include <vcl/msgbox.hxx>
#endif
#ifndef _SVX_SVDOMEDIA_HXX
#include <svx/svdomedia.hxx>
#endif
#ifndef _SVX_SVDVIEW_HXX
#include <svx/svdview.hxx>
#endif
#ifndef _SVX_SVDPAGV_HXX
#include <svx/svdpagv.hxx>
#endif
#ifndef _SWSTYLENAMEMAPPER_HXX
#include <SwStyleNameMapper.hxx>
#endif

#ifndef _FILEDLGHELPER_HXX
#include <sfx2/filedlghelper.hxx>
#endif
#ifndef _COM_SUN_STAR_UI_DIALOGS_XFILEPICKERCONTROLACCESS_HPP_
#include <com/sun/star/ui/dialogs/XFilePickerControlAccess.hpp>
#endif
#ifndef _COM_SUN_STAR_UI_DIALOGS_EXTENDEDFILEPICKERELEMENTIDS_HPP_
#include <com/sun/star/ui/dialogs/ExtendedFilePickerElementIds.hpp>
#endif
#ifndef _COM_SUN_STAR_UI_DIALOGS_LISTBOXCONTROLACTIONS_HPP_
#include <com/sun/star/ui/dialogs/ListboxControlActions.hpp>
#endif
#ifndef _POOLFMT_HRC
#include <poolfmt.hrc>
#endif

#include <sfx2/request.hxx>
#include <sfx2/viewfrm.hxx>
#include <svtools/stritem.hxx>
#include <avmedia/mediawindow.hxx>

// -> #111827#
#include <SwRewriter.hxx>
#include <undobj.hxx>
#include <comcore.hrc>
// <- #111827#

using namespace ::com::sun::star::uno;
using namespace ::com::sun::star::ui::dialogs;
using namespace ::sfx2;
using namespace ::rtl;

bool SwTextShell::InsertMediaDlg( SfxRequest& rReq )
{
    ::rtl::OUString     aURL;
    const SfxItemSet*   pReqArgs = rReq.GetArgs();
    Window*             pWindow = &GetView().GetViewFrame()->GetWindow();
    bool                bAPI = false, bRet = false;

    if( pReqArgs )
    {
        const SfxStringItem* pStringItem = PTR_CAST( SfxStringItem, &pReqArgs->Get( rReq.GetSlot() ) );

        if( pStringItem )
        {
            aURL = pStringItem->GetValue();
            bAPI = aURL.getLength();
        }
    }

    if( bAPI || ::avmedia::MediaWindow::executeMediaURLDialog( pWindow, aURL ) )
    {
        Size aPrefSize;

        if( pWindow )
            pWindow->EnterWait();

        if( !::avmedia::MediaWindow::isMediaURL( aURL, true, &aPrefSize ) )
        {
            if( pWindow )
                pWindow->LeaveWait();

            if( !bAPI )
                ::avmedia::MediaWindow::executeFormatErrorBox( pWindow );
        }
        else
        {
            SwWrtShell& rSh = GetShell();

            if( !rSh.HasDrawView() )
                rSh.MakeDrawView();

            Size            aDocSz( rSh.GetDocSize() );
               const SwRect&    rVisArea = rSh.VisArea();
            Point           aPos( rVisArea.Center() );
            Size            aSize;

            if( rVisArea.Width() > aDocSz.Width())
                aPos.X() = aDocSz.Width() / 2 + rVisArea.Left();

            if(rVisArea.Height() > aDocSz.Height())
                aPos.Y() = aDocSz.Height() / 2 + rVisArea.Top();

            if( aPrefSize.Width() && aPrefSize.Height() )
            {
                if( pWindow )
                    aSize = pWindow->PixelToLogic( aPrefSize, MAP_TWIP );
                else
                    aSize = Application::GetDefaultDevice()->PixelToLogic( aPrefSize, MAP_TWIP );
            }
            else
                aSize = Size( 2835, 2835 );

            SdrMediaObj* pObj = new SdrMediaObj( Rectangle( aPos, aSize ) );

            pObj->setURL( aURL );
            rSh.EnterStdMode();
            rSh.SwFEShell::Insert( *pObj, 0, 0, &aPos );
            bRet = true;

            if( pWindow )
                pWindow->LeaveWait();
        }
    }

    return bRet;
}
<commit_msg>INTEGRATION: CWS pchfix02 (1.16.2); FILE MERGED 2006/09/01 17:53:19 kaib 1.16.2.1: #i68856# Added header markers and pch files<commit_after>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: grfshex.cxx,v $
 *
 *  $Revision: 1.17 $
 *
 *  last change: $Author: obo $ $Date: 2006-09-16 23:15:24 $
 *
 *  The Contents of this file are made available subject to
 *  the terms of GNU Lesser General Public License Version 2.1.
 *
 *
 *    GNU Lesser General Public License Version 2.1
 *    =============================================
 *    Copyright 2005 by Sun Microsystems, Inc.
 *    901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *    This library is free software; you can redistribute it and/or
 *    modify it under the terms of the GNU Lesser General Public
 *    License version 2.1, as published by the Free Software Foundation.
 *
 *    This library is distributed in the hope that it will be useful,
 *    but WITHOUT ANY WARRANTY; without even the implied warranty of
 *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *    Lesser General Public License for more details.
 *
 *    You should have received a copy of the GNU Lesser General Public
 *    License along with this library; if not, write to the Free Software
 *    Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *    MA  02111-1307  USA
 *
 ************************************************************************/

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

#ifndef _DOCARY_HXX
#include <docary.hxx>
#endif
#ifndef _GRFSH_HXX
#include <grfsh.hxx>
#endif
#ifndef _WRTSH_HXX
#include <wrtsh.hxx>
#endif
#ifndef _VIEW_HXX
#include <view.hxx>
#endif
#ifndef _DOCARY_HXX
#include <docary.hxx>
#endif
#ifndef _TEXTSH_HXX
#include <textsh.hxx>
#endif
#ifndef _VIEWOPT_HXX
#include <viewopt.hxx>
#endif
#ifndef _SWUNDO_HXX
#include <swundo.hxx>
#endif
#ifndef _SHELLS_HRC
#include <shells.hrc>
#endif
#ifndef _CAPTION_HXX
#include <caption.hxx>
#endif
#define _SVSTDARR_STRINGSSORTDTOR
#include <svtools/svstdarr.hxx>
#ifndef _FILTER_HXX
#include <svtools/filter.hxx>
#endif
#ifndef _SVX_IMPGRF_HXX
#include <svx/impgrf.hxx>
#endif
#ifndef _SVX_HTMLMODE_HXX //autogen
#include <svx/htmlmode.hxx>
#endif
#ifndef _DOCSH_HXX
#include <docsh.hxx>
#endif
#ifndef _FRMFMT_HXX
#include <frmfmt.hxx>
#endif
#ifndef _FRMMGR_HXX
#include <frmmgr.hxx>
#endif
#ifndef _SV_MSGBOX_HXX
#include <vcl/msgbox.hxx>
#endif
#ifndef _SVX_SVDOMEDIA_HXX
#include <svx/svdomedia.hxx>
#endif
#ifndef _SVX_SVDVIEW_HXX
#include <svx/svdview.hxx>
#endif
#ifndef _SVX_SVDPAGV_HXX
#include <svx/svdpagv.hxx>
#endif
#ifndef _SWSTYLENAMEMAPPER_HXX
#include <SwStyleNameMapper.hxx>
#endif

#ifndef _FILEDLGHELPER_HXX
#include <sfx2/filedlghelper.hxx>
#endif
#ifndef _COM_SUN_STAR_UI_DIALOGS_XFILEPICKERCONTROLACCESS_HPP_
#include <com/sun/star/ui/dialogs/XFilePickerControlAccess.hpp>
#endif
#ifndef _COM_SUN_STAR_UI_DIALOGS_EXTENDEDFILEPICKERELEMENTIDS_HPP_
#include <com/sun/star/ui/dialogs/ExtendedFilePickerElementIds.hpp>
#endif
#ifndef _COM_SUN_STAR_UI_DIALOGS_LISTBOXCONTROLACTIONS_HPP_
#include <com/sun/star/ui/dialogs/ListboxControlActions.hpp>
#endif
#ifndef _POOLFMT_HRC
#include <poolfmt.hrc>
#endif

#include <sfx2/request.hxx>
#include <sfx2/viewfrm.hxx>
#include <svtools/stritem.hxx>
#include <avmedia/mediawindow.hxx>

// -> #111827#
#include <SwRewriter.hxx>
#include <undobj.hxx>
#include <comcore.hrc>
// <- #111827#

using namespace ::com::sun::star::uno;
using namespace ::com::sun::star::ui::dialogs;
using namespace ::sfx2;
using namespace ::rtl;

bool SwTextShell::InsertMediaDlg( SfxRequest& rReq )
{
    ::rtl::OUString     aURL;
    const SfxItemSet*   pReqArgs = rReq.GetArgs();
    Window*             pWindow = &GetView().GetViewFrame()->GetWindow();
    bool                bAPI = false, bRet = false;

    if( pReqArgs )
    {
        const SfxStringItem* pStringItem = PTR_CAST( SfxStringItem, &pReqArgs->Get( rReq.GetSlot() ) );

        if( pStringItem )
        {
            aURL = pStringItem->GetValue();
            bAPI = aURL.getLength();
        }
    }

    if( bAPI || ::avmedia::MediaWindow::executeMediaURLDialog( pWindow, aURL ) )
    {
        Size aPrefSize;

        if( pWindow )
            pWindow->EnterWait();

        if( !::avmedia::MediaWindow::isMediaURL( aURL, true, &aPrefSize ) )
        {
            if( pWindow )
                pWindow->LeaveWait();

            if( !bAPI )
                ::avmedia::MediaWindow::executeFormatErrorBox( pWindow );
        }
        else
        {
            SwWrtShell& rSh = GetShell();

            if( !rSh.HasDrawView() )
                rSh.MakeDrawView();

            Size            aDocSz( rSh.GetDocSize() );
               const SwRect&    rVisArea = rSh.VisArea();
            Point           aPos( rVisArea.Center() );
            Size            aSize;

            if( rVisArea.Width() > aDocSz.Width())
                aPos.X() = aDocSz.Width() / 2 + rVisArea.Left();

            if(rVisArea.Height() > aDocSz.Height())
                aPos.Y() = aDocSz.Height() / 2 + rVisArea.Top();

            if( aPrefSize.Width() && aPrefSize.Height() )
            {
                if( pWindow )
                    aSize = pWindow->PixelToLogic( aPrefSize, MAP_TWIP );
                else
                    aSize = Application::GetDefaultDevice()->PixelToLogic( aPrefSize, MAP_TWIP );
            }
            else
                aSize = Size( 2835, 2835 );

            SdrMediaObj* pObj = new SdrMediaObj( Rectangle( aPos, aSize ) );

            pObj->setURL( aURL );
            rSh.EnterStdMode();
            rSh.SwFEShell::Insert( *pObj, 0, 0, &aPos );
            bRet = true;

            if( pWindow )
                pWindow->LeaveWait();
        }
    }

    return bRet;
}
<|endoftext|>


<commit_before>//-----------------------------------------------------------------------------
// Copyright (c) 2014 Michael G. Brehm
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
//-----------------------------------------------------------------------------

#include "stdafx.h"
#include "resource.h"
#include "VmService.h"

#pragma warning(push, 4)

//---------------------------------------------------------------------------
// _tWinMain
//
// Main application entry point
//
// Arguments :
//
//	instance		- Application instance handle
//	previnstance	- Unused in Win32, always set to NULL
//	cmdline			- Pointer to application command line string
//	show			- Application initial display flags

int APIENTRY _tWinMain(HINSTANCE, HINSTANCE, LPTSTR, int)
{

#ifdef _DEBUG

	int nDbgFlags = _CrtSetDbgFlag(_CRTDBG_REPORT_FLAG);	// Get current flags
	nDbgFlags |= _CRTDBG_LEAK_CHECK_DF;						// Enable leak-check
	_CrtSetDbgFlag(nDbgFlags);								// Set the new flags

#endif	// _DEBUG

	////////
	RPC_STATUS rpcresult = RpcServerUseAllProtseqsIf(RPC_C_PROTSEQ_MAX_REQS_DEFAULT, SystemCalls_v1_0_s_ifspec, nullptr);
	if(rpcresult != RPC_S_OK) {
	}
	///////

	// Use manual dispatching for now; haven't implemented a new ServiceModule<> class yet
	ServiceTable services = { ServiceTableEntry<VmService>(L"Instance Service") };
	services.Dispatch();

	return 0;
}

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

#pragma warning(pop)
<commit_msg>Updated service template library to allow resource IDs as service name strings<commit_after>//-----------------------------------------------------------------------------
// Copyright (c) 2014 Michael G. Brehm
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
//-----------------------------------------------------------------------------

#include "stdafx.h"
#include "resource.h"
#include "VmService.h"

#pragma warning(push, 4)

//---------------------------------------------------------------------------
// _tWinMain
//
// Main application entry point
//
// Arguments :
//
//	instance		- Application instance handle
//	previnstance	- Unused in Win32, always set to NULL
//	cmdline			- Pointer to application command line string
//	show			- Application initial display flags

int APIENTRY _tWinMain(HINSTANCE, HINSTANCE, LPTSTR, int)
{

#ifdef _DEBUG

	int nDbgFlags = _CrtSetDbgFlag(_CRTDBG_REPORT_FLAG);	// Get current flags
	nDbgFlags |= _CRTDBG_LEAK_CHECK_DF;						// Enable leak-check
	_CrtSetDbgFlag(nDbgFlags);								// Set the new flags

#endif	// _DEBUG

	////////
	RPC_STATUS rpcresult = RpcServerUseAllProtseqsIf(RPC_C_PROTSEQ_MAX_REQS_DEFAULT, SystemCalls_v1_0_s_ifspec, nullptr);
	if(rpcresult != RPC_S_OK) {
	}
	///////

	// Use manual dispatching for now; haven't implemented a new ServiceModule<> class yet
	ServiceTable services = { ServiceTableEntry<VmService>(IDS_VMSERVICE_NAME) };
	services.Dispatch();

	return 0;
}

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

#pragma warning(pop)
<|endoftext|>


<commit_before>#pragma once

#include <map>
#include <type_traits> // conditionals
#include <unordered_map>

/// \file This file contains utilities and wrapper to iterate over Map and OrderedMap values/keys
/// Source: https://gist.github.com/eruffaldi/93d09ed6644ae3fa279f
namespace Ra {
namespace Core {
namespace Utils {

/// \brief Generate a range to iterate over the keys of a map
///
/// \tparam Mapclass Specialized Map or OrderedMap
///
/// Usage:
/// \snippet tests/unittest/Core/mapiterators.cpp Iterating over keys
template <class Mapclass>
struct map_keys {
    using map_t = Mapclass;

    struct iterator {
        using realiterator_t = typename std::conditional<std::is_const<map_t>::value,
                                                         typename map_t::const_iterator,
                                                         typename map_t::iterator>::type;
        using value_t        = typename std::add_const<typename map_t::key_type>::type;
        realiterator_t under;

        iterator( realiterator_t x ) : under( x ) {}

        auto operator*() -> typename std::add_lvalue_reference<value_t>::type {
            return under->first;
        }
        auto operator-> () -> typename std::add_pointer<value_t>::type { return &under->first; }

        bool operator!=( const iterator& o ) const { return under != o.under; }

        iterator& operator++() {
            ++under;
            return *this;
        }
        iterator operator++( int ) {
            iterator x( *this );
            ++under;
            return x;
        }
    };

    map_keys( map_t& x ) : x_( x ) {}

    iterator begin() { return iterator( x_.begin() ); }
    iterator end() { return iterator( x_.end() ); }
    unsigned int size() const { return x_.size(); }

    map_t& x_;
};

/// \brief Generate a range to iterate over the values of a map
///
/// \tparam Mapclass Specialized Map or OrderedMap
///
/// Usage:
/// \snippet tests/unittest/Core/mapiterators.cpp Iterating over values
template <class Mapclass>
struct map_values {
    using map_t = Mapclass;

    struct iterator {
        using realiterator_t = typename std::conditional<std::is_const<map_t>::value,
                                                         typename map_t::const_iterator,
                                                         typename map_t::iterator>::type;
        using value_t =
            typename std::conditional<std::is_const<map_t>::value,
                                      typename std::add_const<typename map_t::mapped_type>::type,
                                      typename map_t::mapped_type>::type;
        realiterator_t under;

        iterator( realiterator_t x ) : under( x ) {}

        auto operator*() -> typename std::add_lvalue_reference<value_t>::type {
            return under->second;
        }
        auto operator-> () -> typename std::add_pointer<value_t>::type { return &under->second; }

        bool operator!=( const iterator& o ) const { return under != o.under; }

        iterator& operator++() {
            ++under;
            return *this;
        }
        iterator operator++( int ) {
            iterator x( *this );
            ++under;
            return x;
        }
    };

    map_values( map_t& x ) : x_( x ) {}

    iterator begin() { return iterator( x_.begin() ); }
    iterator end() { return iterator( x_.end() ); }
    unsigned int size() const { return x_.size(); }

    map_t& x_;
};
} // namespace Utils
} // namespace Core
} // namespace Ra
<commit_msg>[Core] StdMapIterator: add virtual destructor<commit_after>#pragma once

#include <map>
#include <type_traits> // conditionals
#include <unordered_map>

/// \file This file contains utilities and wrapper to iterate over Map and OrderedMap values/keys
/// Source: https://gist.github.com/eruffaldi/93d09ed6644ae3fa279f
namespace Ra {
namespace Core {
namespace Utils {

/// \brief Generate a range to iterate over the keys of a map
///
/// \tparam Mapclass Specialized Map or OrderedMap
///
/// Usage:
/// \snippet tests/unittest/Core/mapiterators.cpp Iterating over keys
template <class Mapclass>
struct map_keys {
    using map_t = Mapclass;

    struct iterator {
        using realiterator_t = typename std::conditional<std::is_const<map_t>::value,
                                                         typename map_t::const_iterator,
                                                         typename map_t::iterator>::type;
        using value_t        = typename std::add_const<typename map_t::key_type>::type;
        realiterator_t under;

        iterator( realiterator_t x ) : under( x ) {}

        auto operator*() -> typename std::add_lvalue_reference<value_t>::type {
            return under->first;
        }
        auto operator-> () -> typename std::add_pointer<value_t>::type { return &under->first; }

        bool operator!=( const iterator& o ) const { return under != o.under; }

        iterator& operator++() {
            ++under;
            return *this;
        }
        iterator operator++( int ) {
            iterator x( *this );
            ++under;
            return x;
        }
    };

    map_keys( map_t& x ) : x_( x ) {}
    virtual inline ~map_keys() = default;

    iterator begin() { return iterator( x_.begin() ); }
    iterator end() { return iterator( x_.end() ); }
    unsigned int size() const { return x_.size(); }

    map_t& x_;
};

/// \brief Generate a range to iterate over the values of a map
///
/// \tparam Mapclass Specialized Map or OrderedMap
///
/// Usage:
/// \snippet tests/unittest/Core/mapiterators.cpp Iterating over values
template <class Mapclass>
struct map_values {
    using map_t = Mapclass;

    struct iterator {
        using realiterator_t = typename std::conditional<std::is_const<map_t>::value,
                                                         typename map_t::const_iterator,
                                                         typename map_t::iterator>::type;
        using value_t =
            typename std::conditional<std::is_const<map_t>::value,
                                      typename std::add_const<typename map_t::mapped_type>::type,
                                      typename map_t::mapped_type>::type;
        realiterator_t under;

        iterator( realiterator_t x ) : under( x ) {}

        auto operator*() -> typename std::add_lvalue_reference<value_t>::type {
            return under->second;
        }
        auto operator-> () -> typename std::add_pointer<value_t>::type { return &under->second; }

        bool operator!=( const iterator& o ) const { return under != o.under; }

        iterator& operator++() {
            ++under;
            return *this;
        }
        iterator operator++( int ) {
            iterator x( *this );
            ++under;
            return x;
        }
    };

    map_values( map_t& x ) : x_( x ) {}

    iterator begin() { return iterator( x_.begin() ); }
    iterator end() { return iterator( x_.end() ); }
    unsigned int size() const { return x_.size(); }

    map_t& x_;
};
} // namespace Utils
} // namespace Core
} // namespace Ra
<|endoftext|>


<commit_before>
#include "otbWrapperOutputProcessXMLParameter.h"

#include "otbWrapperChoiceParameter.h"
#include "otbWrapperListViewParameter.h"
#include "otbWrapperDirectoryParameter.h"
#include "otbWrapperEmptyParameter.h"
#include "otbWrapperInputFilenameParameter.h"
#include "otbWrapperInputFilenameListParameter.h"
#include "otbWrapperOutputFilenameParameter.h"
#include "otbWrapperInputVectorDataParameter.h"
#include "otbWrapperInputVectorDataListParameter.h"
#include "otbWrapperNumericalParameter.h"
#include "otbWrapperOutputVectorDataParameter.h"
#include "otbWrapperRadiusParameter.h"
#include "otbWrapperStringParameter.h"
#include "otbWrapperStringListParameter.h"
#include "otbWrapperInputImageParameter.h"
#include "otbWrapperInputImageListParameter.h"
#include "otbWrapperComplexInputImageParameter.h"
#include "otbWrapperOutputImageParameter.h"
#include "otbWrapperComplexOutputImageParameter.h"
#include "otbWrapperRAMParameter.h"
#include "itksys/SystemTools.hxx"

namespace otb
{
namespace Wrapper
{
OutputProcessXMLParameter::OutputProcessXMLParameter()
{
  this->SetKey("outxml");
  this->SetName("Save otb application to xml file");
  this->SetDescription("Save otb application to xml file");
  this->SetMandatory(false);
  this->SetActive(false);
  this->SetRole(Role_Output);
}

OutputProcessXMLParameter::~OutputProcessXMLParameter()
{

}

std::string
OutputProcessXMLParameter::pixelTypeToString(ImagePixelType pixType)
{
  std::string type;

  switch( pixType )
    {
    case ImagePixelType_uint8:
    {
    type = "uint8";
    break;
    }
    case ImagePixelType_int16:
    {
    type = "int16";
    break;
    }
    case ImagePixelType_uint16:
    {
    type = "uint16";
    break;
    }
    case ImagePixelType_int32:
    {
    type = "int32";
    break;
    }
    case ImagePixelType_uint32:
    {
    type = "uint32";
    break;
    }
    case ImagePixelType_float:
    {
      type = "float";
    break;
    }
    case ImagePixelType_double:
    {
    type = "double";
    break;
    }
    }
  return type;
}

TiXmlElement* OutputProcessXMLParameter::AddChildNodeTo(TiXmlElement *parent, std::string name, std::string value)
{
  TiXmlElement * n_Node = new TiXmlElement( name.c_str() );
  parent->LinkEndChild( n_Node );
  if(!value.empty())
    {
      TiXmlText * nv_NodeValue = new TiXmlText( value.c_str() );
      n_Node->LinkEndChild( nv_NodeValue );
    }
  return n_Node;
}

void
OutputProcessXMLParameter::Write(Application::Pointer app)
{
  // Check if the filename is not empty
  if(m_FileName.empty())
    itkExceptionMacro("The XML output FileName is empty, please set the filename via the method SetFileName");

  // Check that the right extension is given : expected .xml */
  if (itksys::SystemTools::GetFilenameLastExtension(m_FileName) != ".xml")
    {
    itkExceptionMacro(<<itksys::SystemTools::GetFilenameLastExtension(m_FileName)
                      <<" is a wrong Extension FileName : Expected .xml");
    }

  // start creating XML file
  TiXmlDocument doc;

  TiXmlDeclaration* decl = new TiXmlDeclaration( "1.0", "", "" );
  doc.LinkEndChild( decl );

  TiXmlElement * n_OTB = new TiXmlElement( "OTB");
  doc.LinkEndChild( n_OTB );

  std::string version = "3.18";
  std::string platform = "Linux";
  std::string build = "18-05-2013";

  AddChildNodeTo(n_OTB, "version", version);
  AddChildNodeTo(n_OTB, "build", build);
  AddChildNodeTo(n_OTB, "platform", platform);

  TiXmlElement *n_App;
  n_App = AddChildNodeTo(n_OTB, "application");
  AddChildNodeTo(n_App, "name", app->GetName());
  AddChildNodeTo(n_App, "descr", app->GetDescription());

  TiXmlElement *n_AppDoc;
  n_AppDoc = AddChildNodeTo(n_App, "doc");
  AddChildNodeTo(n_AppDoc, "name", app->GetDocName());
  AddChildNodeTo(n_AppDoc, "longdescr", app->GetDocLongDescription());
  AddChildNodeTo(n_AppDoc, "authors", app->GetDocAuthors());
  AddChildNodeTo(n_AppDoc, "limitations", app->GetDocLimitations());
  AddChildNodeTo(n_AppDoc, "seealso", app->GetDocSeeAlso());

  TiXmlElement *n_DocTags;
  n_DocTags = AddChildNodeTo(n_AppDoc, "tags");
  std::vector<std::string> docTagList = app->GetDocTags();
  std::vector<std::string>::iterator tagIt;
  for(tagIt = docTagList.begin(); tagIt!= docTagList.end(); ++tagIt)
    {
      std::string tag = *tagIt;
      AddChildNodeTo(n_DocTags, "tag", tag);
    }
  ParameterGroup::Pointer paramGroup = app->GetParameterList();

  std::vector<std::string> paramList = paramGroup->GetParametersKeys(true);

  // Iterate through parameters
  for (std::vector<std::string>::const_iterator it = paramList.begin(); it!= paramList.end(); ++it)
    {
      std::string key = *it;
      Parameter *param = paramGroup->GetParameterByKey(key);
      std::string paramName = param->GetName();
      ParameterType type = app->GetParameterType(key);
      std::string typeAsString = paramGroup->GetParameterTypeAsString(type);

      // if param is a Group, dont do anything, ParamGroup dont have values
      if (type != ParameterType_Group)
      {
       bool paramExists = app->HasValue(key) && app->IsParameterEnabled(key);
       if ( key == "outxml" )
         {
           paramExists = false;
         }
       if (type == ParameterType_Empty)
         {
           paramExists = true;
         }
       // if parameter doesn't have any value then skip it
       if (paramExists)
        {
         std::vector<std::string> values;
         std::string value;
         bool hasValueList = false;
         if (type == ParameterType_OutputImage)
          {
           OutputImageParameter *imgParam = dynamic_cast<OutputImageParameter *>(param);
           value = imgParam->GetFileName();
           ImagePixelType pixType = imgParam->GetPixelType();
           std::string ptype = pixelTypeToString(pixType); //FIXME save this

         }
         else
           if( type == ParameterType_InputImageList || type == ParameterType_InputFilenameList ||
              type == ParameterType_InputVectorDataList || type == ParameterType_StringList )
             {
              values = app->GetParameterStringList(key);
              hasValueList = true;
             }
         else
           if (type == ParameterType_Float || type == ParameterType_Int ||
              type == ParameterType_Radius || type == ParameterType_RAM )
             {
              value = app->GetParameterAsString(key);
             }
           else
             if ( type == ParameterType_String || type == ParameterType_InputFilename ||
                 type == ParameterType_Directory || type == ParameterType_InputImage ||
                 type == ParameterType_ComplexInputImage || type == ParameterType_InputVectorData ||
                 type == ParameterType_Choice || type == ParameterType_ListView ||
                 type == ParameterType_OutputVectorData || type == ParameterType_OutputFilename)
              {
                value = app->GetParameterString(key);
              }
             else
       if(key == "rand")
        {
          std::ostringstream strm;
        strm << app->GetParameterInt("rand");
        value = strm.str();
        }
       else
      if (typeAsString == "Empty")
       {
         EmptyParameter* eParam = dynamic_cast<EmptyParameter *> (param);
         value = "false";
         if( eParam->GetActive() )
           {
             value = "true";
           }
       }

         //get only file name
    /*
      if(type == ParameterType_InputFilename || type == ParameterType_InputImage ||
      type == ParameterType_ComplexInputImage || type == ParameterType_InputVectorData ||
      type == ParameterType_OutputVectorData || type == ParameterType_OutputFilename)
           {
           unsigned found = value.find_last_of("/\\");
           //std::cerr << " path: " << value.substr(0,found) << '\n';
           value = value.substr(found+1);
           }
           else
           if(type == ParameterType_InputImageList || type == ParameterType_InputFilenameList ||
           type == ParameterType_InputVectorDataList)
           {
           std::vector<std::string>::iterator strIt;
           for(strIt = values.begin(); strIt != values.end(); ++strIt)
                    {
                    std::string val = *strIt;
                    unsigned found = val.find_last_of("/\\");
                    *strIt = val.substr(found+1);
                    }
                    }
  */
         //parameter node in xml
         TiXmlElement * n_Parameter = new TiXmlElement("parameter");

         const char * mandatory = "false";

         if( param->GetMandatory() )
           mandatory = "true";

         n_Parameter->SetAttribute("mandatory", mandatory);

         //setting parameter key as child node in parameter
         AddChildNodeTo(n_Parameter, "key", key);
         AddChildNodeTo(n_Parameter, "type", typeAsString);
         AddChildNodeTo(n_Parameter, "name", paramName);

         if(!hasValueList)
           {
             AddChildNodeTo(n_Parameter, "value", value);
           }
         else
           {
             TiXmlElement *n_Values = AddChildNodeTo(n_Parameter, "values");
             std::vector<std::string>::iterator strIt;
             for(strIt = values.begin(); strIt != values.end(); ++strIt)
              {
                AddChildNodeTo(n_Values, "value",*strIt);
              }
           }
         n_App->LinkEndChild(n_Parameter);
       }
      }
    }

  // Finally, write xml contents to file
  doc.SaveFile( m_FileName.c_str() );

}

} //end namespace wrapper

} //end namespace otb
<commit_msg>BUG: setting precision for float parameter for writing as string to xml<commit_after>
#include "otbWrapperOutputProcessXMLParameter.h"

#include "otbWrapperChoiceParameter.h"
#include "otbWrapperListViewParameter.h"
#include "otbWrapperDirectoryParameter.h"
#include "otbWrapperEmptyParameter.h"
#include "otbWrapperInputFilenameParameter.h"
#include "otbWrapperInputFilenameListParameter.h"
#include "otbWrapperOutputFilenameParameter.h"
#include "otbWrapperInputVectorDataParameter.h"
#include "otbWrapperInputVectorDataListParameter.h"
#include "otbWrapperNumericalParameter.h"
#include "otbWrapperOutputVectorDataParameter.h"
#include "otbWrapperRadiusParameter.h"
#include "otbWrapperStringParameter.h"
#include "otbWrapperStringListParameter.h"
#include "otbWrapperInputImageParameter.h"
#include "otbWrapperInputImageListParameter.h"
#include "otbWrapperComplexInputImageParameter.h"
#include "otbWrapperOutputImageParameter.h"
#include "otbWrapperComplexOutputImageParameter.h"
#include "otbWrapperRAMParameter.h"
#include "itksys/SystemTools.hxx"

namespace otb
{
namespace Wrapper
{
OutputProcessXMLParameter::OutputProcessXMLParameter()
{
  this->SetKey("outxml");
  this->SetName("Save otb application to xml file");
  this->SetDescription("Save otb application to xml file");
  this->SetMandatory(false);
  this->SetActive(false);
  this->SetRole(Role_Output);
}

OutputProcessXMLParameter::~OutputProcessXMLParameter()
{

}

std::string
OutputProcessXMLParameter::pixelTypeToString(ImagePixelType pixType)
{
  std::string type;

  switch( pixType )
    {
    case ImagePixelType_uint8:
    {
    type = "uint8";
    break;
    }
    case ImagePixelType_int16:
    {
    type = "int16";
    break;
    }
    case ImagePixelType_uint16:
    {
    type = "uint16";
    break;
    }
    case ImagePixelType_int32:
    {
    type = "int32";
    break;
    }
    case ImagePixelType_uint32:
    {
    type = "uint32";
    break;
    }
    case ImagePixelType_float:
    {
      type = "float";
    break;
    }
    case ImagePixelType_double:
    {
    type = "double";
    break;
    }
    }
  return type;
}

TiXmlElement* OutputProcessXMLParameter::AddChildNodeTo(TiXmlElement *parent, std::string name, std::string value)
{
  TiXmlElement * n_Node = new TiXmlElement( name.c_str() );
  parent->LinkEndChild( n_Node );
  if(!value.empty())
    {
      TiXmlText * nv_NodeValue = new TiXmlText( value.c_str() );
      n_Node->LinkEndChild( nv_NodeValue );
    }
  return n_Node;
}

void
OutputProcessXMLParameter::Write(Application::Pointer app)
{
  // Check if the filename is not empty
  if(m_FileName.empty())
    itkExceptionMacro("The XML output FileName is empty, please set the filename via the method SetFileName");

  // Check that the right extension is given : expected .xml */
  if (itksys::SystemTools::GetFilenameLastExtension(m_FileName) != ".xml")
    {
    itkExceptionMacro(<<itksys::SystemTools::GetFilenameLastExtension(m_FileName)
                      <<" is a wrong Extension FileName : Expected .xml");
    }

  // start creating XML file
  TiXmlDocument doc;

  TiXmlDeclaration* decl = new TiXmlDeclaration( "1.0", "", "" );
  doc.LinkEndChild( decl );

  TiXmlElement * n_OTB = new TiXmlElement( "OTB");
  doc.LinkEndChild( n_OTB );

  std::string version = "3.18";
  std::string platform = "Linux";
  std::string build = "18-05-2013";

  AddChildNodeTo(n_OTB, "version", version);
  AddChildNodeTo(n_OTB, "build", build);
  AddChildNodeTo(n_OTB, "platform", platform);

  TiXmlElement *n_App;
  n_App = AddChildNodeTo(n_OTB, "application");
  AddChildNodeTo(n_App, "name", app->GetName());
  AddChildNodeTo(n_App, "descr", app->GetDescription());

  TiXmlElement *n_AppDoc;
  n_AppDoc = AddChildNodeTo(n_App, "doc");
  AddChildNodeTo(n_AppDoc, "name", app->GetDocName());
  AddChildNodeTo(n_AppDoc, "longdescr", app->GetDocLongDescription());
  AddChildNodeTo(n_AppDoc, "authors", app->GetDocAuthors());
  AddChildNodeTo(n_AppDoc, "limitations", app->GetDocLimitations());
  AddChildNodeTo(n_AppDoc, "seealso", app->GetDocSeeAlso());

  TiXmlElement *n_DocTags;
  n_DocTags = AddChildNodeTo(n_AppDoc, "tags");
  std::vector<std::string> docTagList = app->GetDocTags();
  std::vector<std::string>::iterator tagIt;
  for(tagIt = docTagList.begin(); tagIt!= docTagList.end(); ++tagIt)
    {
      std::string tag = *tagIt;
      AddChildNodeTo(n_DocTags, "tag", tag);
    }
  ParameterGroup::Pointer paramGroup = app->GetParameterList();

  std::vector<std::string> paramList = paramGroup->GetParametersKeys(true);

  // Iterate through parameters
  for (std::vector<std::string>::const_iterator it = paramList.begin(); it!= paramList.end(); ++it)
    {
      std::string key = *it;
      Parameter *param = paramGroup->GetParameterByKey(key);
      std::string paramName = param->GetName();
      ParameterType type = app->GetParameterType(key);
      std::string typeAsString = paramGroup->GetParameterTypeAsString(type);

      // if param is a Group, dont do anything, ParamGroup dont have values
      if (type != ParameterType_Group)
      {
       bool paramExists = app->HasValue(key) && app->IsParameterEnabled(key);
       if ( key == "outxml" )
         {
           paramExists = false;
         }
       if (type == ParameterType_Empty)
         {
           paramExists = true;
         }
       // if parameter doesn't have any value then skip it
       if (paramExists)
        {
         std::vector<std::string> values;
         std::string value;
         bool hasValueList = false;
         if (type == ParameterType_OutputImage)
          {
           OutputImageParameter *imgParam = dynamic_cast<OutputImageParameter *>(param);
           value = imgParam->GetFileName();
           ImagePixelType pixType = imgParam->GetPixelType();
           std::string ptype = pixelTypeToString(pixType); //FIXME save this

         }
         else if( type == ParameterType_InputImageList || type == ParameterType_InputFilenameList ||
                  type == ParameterType_InputVectorDataList || type == ParameterType_StringList )
           {
           values = app->GetParameterStringList(key);
           hasValueList = true;
           }
         else if (type == ParameterType_Int || type == ParameterType_Radius || type == ParameterType_RAM )
           {
           value = app->GetParameterAsString(key);
           }
         else if(type == ParameterType_Float)
           {
           std::ostringstream oss;
           oss << std::setprecision(10);
           oss << app->GetParameterFloat( key );
           value = oss.str();
           }
         else if ( type == ParameterType_String || type == ParameterType_InputFilename ||
                   type == ParameterType_Directory || type == ParameterType_InputImage ||
                   type == ParameterType_ComplexInputImage || type == ParameterType_InputVectorData ||
                   type == ParameterType_Choice || type == ParameterType_ListView ||
                   type == ParameterType_OutputVectorData || type == ParameterType_OutputFilename)
           {
           value = app->GetParameterString(key);
           }
         else if(key == "rand")
           {
           std::ostringstream strm;
           strm << app->GetParameterInt("rand");
           value = strm.str();
           }
         else if (typeAsString == "Empty")
           {
           EmptyParameter* eParam = dynamic_cast<EmptyParameter *> (param);
           value = "false";
           if( eParam->GetActive() )
             {
             value = "true";
             }
           }

         //get only file name
    /*
      if(type == ParameterType_InputFilename || type == ParameterType_InputImage ||
      type == ParameterType_ComplexInputImage || type == ParameterType_InputVectorData ||
      type == ParameterType_OutputVectorData || type == ParameterType_OutputFilename)
           {
           unsigned found = value.find_last_of("/\\");
           //std::cerr << " path: " << value.substr(0,found) << '\n';
           value = value.substr(found+1);
           }
           else
           if(type == ParameterType_InputImageList || type == ParameterType_InputFilenameList ||
           type == ParameterType_InputVectorDataList)
           {
           std::vector<std::string>::iterator strIt;
           for(strIt = values.begin(); strIt != values.end(); ++strIt)
                    {
                    std::string val = *strIt;
                    unsigned found = val.find_last_of("/\\");
                    *strIt = val.substr(found+1);
                    }
                    }
  */
         //parameter node in xml
         TiXmlElement * n_Parameter = new TiXmlElement("parameter");

         const char * mandatory = "false";

         if( param->GetMandatory() )
           mandatory = "true";

         n_Parameter->SetAttribute("mandatory", mandatory);

         //setting parameter key as child node in parameter
         AddChildNodeTo(n_Parameter, "key", key);
         AddChildNodeTo(n_Parameter, "type", typeAsString);
         AddChildNodeTo(n_Parameter, "name", paramName);

         if(!hasValueList)
           {
             AddChildNodeTo(n_Parameter, "value", value);
           }
         else
           {
             TiXmlElement *n_Values = AddChildNodeTo(n_Parameter, "values");
             std::vector<std::string>::iterator strIt;
             for(strIt = values.begin(); strIt != values.end(); ++strIt)
              {
                AddChildNodeTo(n_Values, "value",*strIt);
              }
           }
         n_App->LinkEndChild(n_Parameter);
       }
      }
    }

  // Finally, write xml contents to file
  doc.SaveFile( m_FileName.c_str() );

}

} //end namespace wrapper

} //end namespace otb
<|endoftext|>


<commit_before>// $Id: mesh_data_unv_support.C,v 1.3 2003-05-22 09:39:58 spetersen Exp $

// The Next Great Finite Element Library.
// Copyright (C) 2002  Benjamin S. Kirk, John W. Peterson

// This library is free software; you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public
// License as published by the Free Software Foundation; either
// version 2.1 of the License, or (at your option) any later version.

// 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

// C++ includes
#include <fstream>
#include <stdio.h>

// Local includes
#include "mesh_data.h"
#include "mesh_base.h"

//------------------------------------------------------
// MeshData UNV support functions
void MeshData::read_unv(const std::string& name)
{
  /*
   * When reading data, make sure the id maps are ok
   */
  assert (_node_id_map_closed);
  assert (_elem_id_map_closed);

  /**
   * clear the data, but keep the id maps
   */
  this->clear();

  std::ifstream in_file (name.c_str());

  if ( !in_file.good() )
    {
      std::cerr << "ERROR: Input file not good."
		<< std::endl;
      error();
    }

  const std::string  _label_dataset_mesh_data    = "2414";

  /**
   * locate the beginning of data set
   * and read it.
   */
  {
    std::string olds, news;

    while (true)
    {
      in_file >> olds >> news;

      /*
       * a "-1" followed by a number means the beginning of a dataset
       * stop combing at the end of the file
       */
      while( ((olds != "-1") || (news == "-1") ) && !in_file.eof() )
	{
	  olds = news;
	  in_file >> news;
	}

      if(in_file.eof())
	break;

      /*
       * if beginning of dataset, buffer it in
       * temp_buffer, if desired
       */
      if (news == _label_dataset_mesh_data)
        {

	  /**
	   * Now read the data of interest.
	   */

	  /**
	   * Ignore the first lines that stand for
	   * analysis dataset label and name.
	   */
	  for(unsigned int i=0; i<3; i++)
	    in_file.ignore(256,'\n');

	  unsigned int Dataset_location;

	  unsigned int Model_type,
	               Analysis_type,
	               Data_characteristic,
	               Result_type,
	               Data_type,
	               NVALDC;

	  Real dummy_Real;

	  /**
	   * Read the dataset location, where
	   * 1: Data at nodes
	   * 2: Data on elements
	   * other sets are currently not supported.
	   */
	  in_file >> Dataset_location;

	  if (Dataset_location != 1)
	    {
	      std::cerr << "ERROR: Currently only Data at nodes is supported."
			<< std::endl;
	      error();
	    }

	  /**
	   * Ignore five ID lines.
	   */
	  for(unsigned int i=0; i<6; i++)
	    in_file.ignore(256,'\n');

	  /**
	   * Read record 9.
	   */
	  in_file >> Model_type           // not supported yet
		  >> Analysis_type        // not supported yet
		  >> Data_characteristic  // not supported yet
		  >> Result_type          // not supported yet
		  >> Data_type
		  >> NVALDC;

	  /**
	   * Ignore record 10 and 11
	   * (Integer analysis type specific data).
	   */
	  for (unsigned int i=0; i<3; i++)
	    in_file.ignore(256,'\n');

	  /**
	   * Ignore record 12 and record 13.
	   */
	  for (unsigned int i=0; i<12; i++)
	      in_file >> dummy_Real;

	  /**
	   * Now get the foreign node id number and the respective nodal data.
	   */
	  int f_n_id;
	  std::vector<Number> values;

	  while(true)
	    {
	      in_file >> f_n_id;

	      /**
	       * if node_nr = -1 then we have reached the end of the dataset.
	       */
	      if (f_n_id==-1)
		  break;

	      /**
	       * Resize the values vector (usually data in three
	       * principal directions, i.e. NVALDC = 3).
	       */
	      values.resize(NVALDC);

	      /**
	       * Read the meshdata for the respective node.
	       */
	      for (unsigned int data_cnt=0; data_cnt<NVALDC; data_cnt++)
		{
		  /**
		   * Check what data type we are reading.
		   * 2,4: Real
		   * 5,6: Complex
		   * other data types are not supported yet.
		   */
		  if (Data_type == 2 || Data_type == 4)
		    in_file >> values[data_cnt];

		  else if(Data_type == 5 || Data_type == 6)
		    {
		      Real re_val, im_val;

		      in_file >> re_val
			      >> im_val;

		      values[data_cnt] = Complex(re_val,im_val);

		    }

		  else
		    {
		      std::cerr << "ERROR: Data type not supported."
				<< std::endl;
		      error();
		    }

		} // end loop data_cnt

	      /**
	       * Add the values vector to the MechData data structure.
	       */
	      const Node* node = foreign_id_to_node(f_n_id);
	      _node_data.insert (std::make_pair(node, values));

	    } // while(true)
	}

      else
        {
	  /**
	   * all other datasets are ignored
	   */
        }

    }
  }

  /*
   * finished reading.  Ready for use
   */
  this->_node_data_closed = true;
  this->_elem_data_closed = true;
}

void MeshData::write_unv (const std::string& name)
{
  /*
   * make sure the id maps are ready
   * and that we have data to write
   */
  assert (_node_id_map_closed);
  assert (_elem_id_map_closed);

  assert (_node_data_closed);
  assert (_elem_data_closed);

  std::ofstream out_file (name.c_str());

  const std::string  _label_dataset_mesh_data    = "2414";

  /**
   * Currently this function handles only nodal data.
   */
  assert (!_node_data.empty());

  /**
   * Write the beginning of the dataset.
   */
  out_file << "    -1\n"
	   << "  "
	   << _label_dataset_mesh_data
	   << "\n";

  /**
   * Record 1 (analysis dataset label, currently just a dummy).
   */
  char buf[78];
  sprintf(buf, "%10i\n",1);
  out_file << buf;

  /**
   * Record 2 (analysis dataset name, currently just a dummy).
   */
  std::string _dummy_string = "libMesh\n";
  out_file << _dummy_string;

  /**
   * Record 3 (dataset location).
   */
  sprintf(buf, "%10i\n",1);
  out_file << buf;

  /**
   * Record 4 trough 8 (ID lines).
   */
  for (unsigned int i=0; i<5;i++)
    out_file << _dummy_string;

  /**
   * Record 9 trough 11.
   */
  sprintf(buf, "%10i%10i%10i%10i%10i%10i\n", 0, 0, 0, 0, 0, 0);
  out_file << buf;

  sprintf(buf, "%10i%10i%10i%10i%10i%10i%10i%10i\n", 0, 0, 0, 0, 0, 0, 0, 0);
  out_file << buf;

  sprintf(buf, "%10i%10i\n", 0, 0);
  out_file << buf;

  /**
   * Record 12 and 13.
   */
  sprintf(buf, "%13.5E%13.5E%13.5E%13.5E%13.5E%13.5E\n", 0., 0., 0., 0., 0., 0.);
  out_file << buf;

  sprintf(buf, "%13.5E%13.5E%13.5E%13.5E%13.5E%13.5E\n", 0., 0., 0., 0., 0., 0.);
  out_file << buf;

  /**
   * Write the foreign node number and the respective data.
   */
  std::map<const Node*,
    std::vector<Number> >::const_iterator nit = _node_data.begin();

  for (; nit != _node_data.end(); ++nit)
    {
      const Node* node = (*nit).first;

      unsigned int f_n_id = node_to_foreign_id (node);
      sprintf(buf, "%10i\n", f_n_id);
      out_file << buf;

      std::vector<Number> values;
      this->operator()(node, values);

      for (unsigned int v_cnt=0; v_cnt<values.size(); v_cnt++)
	{
#ifdef USE_COMPLEX_NUMBERS
	  sprintf(buf, "%13.5E%13.5E", values[v_cnt].real(),
		                       values[v_cnt].imag());
	  out_file << buf;
#else
	  sprintf(buf, "%13.5E%13.5E", values[v_cnt]);
	  out_file << buf;
#endif
	}

      out_file << "\n";

    }

  /**
   * Write end of the dataset.
   */
  out_file << "    -1\n";

}

<commit_msg>fixed for Real data<commit_after>// $Id: mesh_data_unv_support.C,v 1.4 2003-05-22 16:20:52 benkirk Exp $

// The Next Great Finite Element Library.
// Copyright (C) 2002  Benjamin S. Kirk, John W. Peterson

// This library is free software; you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public
// License as published by the Free Software Foundation; either
// version 2.1 of the License, or (at your option) any later version.

// 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

// C++ includes
#include <fstream>
#include <stdio.h>

// Local includes
#include "mesh_data.h"
#include "mesh_base.h"

//------------------------------------------------------
// MeshData UNV support functions
void MeshData::read_unv(const std::string& name)
{
  /*
   * When reading data, make sure the id maps are ok
   */
  assert (_node_id_map_closed);
  assert (_elem_id_map_closed);

  /**
   * clear the data, but keep the id maps
   */
  this->clear();

  std::ifstream in_file (name.c_str());

  if ( !in_file.good() )
    {
      std::cerr << "ERROR: Input file not good."
		<< std::endl;
      error();
    }

  const std::string  _label_dataset_mesh_data    = "2414";

  /**
   * locate the beginning of data set
   * and read it.
   */
  {
    std::string olds, news;

    while (true)
    {
      in_file >> olds >> news;

      /*
       * a "-1" followed by a number means the beginning of a dataset
       * stop combing at the end of the file
       */
      while( ((olds != "-1") || (news == "-1") ) && !in_file.eof() )
	{
	  olds = news;
	  in_file >> news;
	}

      if(in_file.eof())
	break;

      /*
       * if beginning of dataset, buffer it in
       * temp_buffer, if desired
       */
      if (news == _label_dataset_mesh_data)
        {

	  /**
	   * Now read the data of interest.
	   */

	  /**
	   * Ignore the first lines that stand for
	   * analysis dataset label and name.
	   */
	  for(unsigned int i=0; i<3; i++)
	    in_file.ignore(256,'\n');

	  unsigned int Dataset_location;

	  unsigned int Model_type,
	               Analysis_type,
	               Data_characteristic,
	               Result_type,
	               Data_type,
	               NVALDC;

	  Real dummy_Real;

	  /**
	   * Read the dataset location, where
	   * 1: Data at nodes
	   * 2: Data on elements
	   * other sets are currently not supported.
	   */
	  in_file >> Dataset_location;

	  if (Dataset_location != 1)
	    {
	      std::cerr << "ERROR: Currently only Data at nodes is supported."
			<< std::endl;
	      error();
	    }

	  /**
	   * Ignore five ID lines.
	   */
	  for(unsigned int i=0; i<6; i++)
	    in_file.ignore(256,'\n');

	  /**
	   * Read record 9.
	   */
	  in_file >> Model_type           // not supported yet
		  >> Analysis_type        // not supported yet
		  >> Data_characteristic  // not supported yet
		  >> Result_type          // not supported yet
		  >> Data_type
		  >> NVALDC;

	  /**
	   * Ignore record 10 and 11
	   * (Integer analysis type specific data).
	   */
	  for (unsigned int i=0; i<3; i++)
	    in_file.ignore(256,'\n');

	  /**
	   * Ignore record 12 and record 13.
	   */
	  for (unsigned int i=0; i<12; i++)
	      in_file >> dummy_Real;

	  /**
	   * Now get the foreign node id number and the respective nodal data.
	   */
	  int f_n_id;
	  std::vector<Number> values;

	  while(true)
	    {
	      in_file >> f_n_id;

	      /**
	       * if node_nr = -1 then we have reached the end of the dataset.
	       */
	      if (f_n_id==-1)
		  break;

	      /**
	       * Resize the values vector (usually data in three
	       * principal directions, i.e. NVALDC = 3).
	       */
	      values.resize(NVALDC);

	      /**
	       * Read the meshdata for the respective node.
	       */
	      for (unsigned int data_cnt=0; data_cnt<NVALDC; data_cnt++)
		{
		  /**
		   * Check what data type we are reading.
		   * 2,4: Real
		   * 5,6: Complex
		   * other data types are not supported yet.
		   */
		  if (Data_type == 2 || Data_type == 4)
		    in_file >> values[data_cnt];

		  else if(Data_type == 5 || Data_type == 6)
		    {
#ifdef USE_COMPLEX_NUMBERS

		      Real re_val, im_val;

		      in_file >> re_val
			      >> im_val;

		      values[data_cnt] = Complex(re_val,im_val);
#else

		      std::cerr << "ERROR: Complex data only supported" << std::endl
				<< "when libMesh is configured with --enable-complex!"
				<< std::endl;
		      error();
#endif
		    }

		  else
		    {
		      std::cerr << "ERROR: Data type not supported."
				<< std::endl;
		      error();
		    }

		} // end loop data_cnt

	      /**
	       * Add the values vector to the MechData data structure.
	       */
	      const Node* node = foreign_id_to_node(f_n_id);
	      _node_data.insert (std::make_pair(node, values));

	    } // while(true)
	}

      else
        {
	  /**
	   * all other datasets are ignored
	   */
        }

    }
  }

  /*
   * finished reading.  Ready for use
   */
  this->_node_data_closed = true;
  this->_elem_data_closed = true;
}

void MeshData::write_unv (const std::string& name)
{
  /*
   * make sure the id maps are ready
   * and that we have data to write
   */
  assert (_node_id_map_closed);
  assert (_elem_id_map_closed);

  assert (_node_data_closed);
  assert (_elem_data_closed);

  std::ofstream out_file (name.c_str());

  const std::string  _label_dataset_mesh_data    = "2414";

  /**
   * Currently this function handles only nodal data.
   */
  assert (!_node_data.empty());

  /**
   * Write the beginning of the dataset.
   */
  out_file << "    -1\n"
	   << "  "
	   << _label_dataset_mesh_data
	   << "\n";

  /**
   * Record 1 (analysis dataset label, currently just a dummy).
   */
  char buf[78];
  sprintf(buf, "%10i\n",1);
  out_file << buf;

  /**
   * Record 2 (analysis dataset name, currently just a dummy).
   */
  std::string _dummy_string = "libMesh\n";
  out_file << _dummy_string;

  /**
   * Record 3 (dataset location).
   */
  sprintf(buf, "%10i\n",1);
  out_file << buf;

  /**
   * Record 4 trough 8 (ID lines).
   */
  for (unsigned int i=0; i<5;i++)
    out_file << _dummy_string;

  /**
   * Record 9 trough 11.
   */
  sprintf(buf, "%10i%10i%10i%10i%10i%10i\n", 0, 0, 0, 0, 0, 0);
  out_file << buf;

  sprintf(buf, "%10i%10i%10i%10i%10i%10i%10i%10i\n", 0, 0, 0, 0, 0, 0, 0, 0);
  out_file << buf;

  sprintf(buf, "%10i%10i\n", 0, 0);
  out_file << buf;

  /**
   * Record 12 and 13.
   */
  sprintf(buf, "%13.5E%13.5E%13.5E%13.5E%13.5E%13.5E\n", 0., 0., 0., 0., 0., 0.);
  out_file << buf;

  sprintf(buf, "%13.5E%13.5E%13.5E%13.5E%13.5E%13.5E\n", 0., 0., 0., 0., 0., 0.);
  out_file << buf;

  /**
   * Write the foreign node number and the respective data.
   */
  std::map<const Node*,
    std::vector<Number> >::const_iterator nit = _node_data.begin();

  for (; nit != _node_data.end(); ++nit)
    {
      const Node* node = (*nit).first;

      unsigned int f_n_id = node_to_foreign_id (node);
      sprintf(buf, "%10i\n", f_n_id);
      out_file << buf;

      std::vector<Number> values;
      this->operator()(node, values);

      for (unsigned int v_cnt=0; v_cnt<values.size(); v_cnt++)
	{
#ifdef USE_COMPLEX_NUMBERS
	  sprintf(buf, "%13.5E%13.5E", values[v_cnt].real(),
		                       values[v_cnt].imag());
	  out_file << buf;
#else
	  sprintf(buf, "%13.5E", values[v_cnt]);
	  out_file << buf;
#endif
	}

      out_file << "\n";

    }

  /**
   * Write end of the dataset.
   */
  out_file << "    -1\n";

}

<|endoftext|>


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

  Library: CppMicroServices

  Copyright (c) German Cancer Research Center,
    Division of Medical and Biological Informatics

  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 <usModuleContext.h>
#include <usGetModuleContext.h>
#include <usModuleRegistry.h>
#include <usModule.h>
#include <usModuleResource.h>
#include <usModuleResourceStream.h>

#include <usTestingConfig.h>

#include "usTestUtilSharedLibrary.h"
#include "usTestingMacros.h"

#include <assert.h>

#include <set>

US_USE_NAMESPACE

namespace {

std::string GetResourceContent(const ModuleResource& resource)
{
  std::string line;
  ModuleResourceStream rs(resource);
  std::getline(rs, line);
  return line;
}

struct ResourceComparator {
  bool operator()(const ModuleResource& mr1, const ModuleResource& mr2) const
  {
    return mr1 < mr2;
  }
};

void testResourceOperators(Module* module)
{
  std::vector<ModuleResource> resources = module->FindResources("", "res.txt", false);
  US_TEST_CONDITION_REQUIRED(resources.size() == 2, "Check resource count")
  US_TEST_CONDITION(resources[0] != resources[1], "Check non-equality for equally named resources")
}

void testResourcesWithStaticImport(Module* module)
{
  ModuleResource resource = module->GetResource("res.txt");
  US_TEST_CONDITION_REQUIRED(resource.IsValid(), "Check valid res.txt resource")
  std::string line = GetResourceContent(resource);
  US_TEST_CONDITION(line == "dynamic resource", "Check dynamic resource content")

  resource = module->GetResource("dynamic.txt");
  US_TEST_CONDITION_REQUIRED(resource.IsValid(), "Check valid dynamic.txt resource")
  line = GetResourceContent(resource);
  US_TEST_CONDITION(line == "dynamic", "Check dynamic resource content")

  resource = module->GetResource("static.txt");
  US_TEST_CONDITION_REQUIRED(resource.IsValid(), "Check valid static.txt resource")
  line = GetResourceContent(resource);
  US_TEST_CONDITION(line == "static", "Check dynamic resource content")

  std::vector<ModuleResource> resources = module->FindResources("", "*.txt", false);
  std::stable_sort(resources.begin(), resources.end(), ResourceComparator());
#ifdef US_BUILD_SHARED_LIBS
  US_TEST_CONDITION(resources.size() == 4, "Check imported resource count")
  line = GetResourceContent(resources[0]);
  US_TEST_CONDITION(line == "dynamic", "Check dynamic.txt resource content")
  line = GetResourceContent(resources[1]);
  US_TEST_CONDITION(line == "dynamic resource", "Check res.txt (from importing module) resource content")
  line = GetResourceContent(resources[2]);
  US_TEST_CONDITION(line == "static resource", "Check res.txt (from imported module) resource content")
  line = GetResourceContent(resources[3]);
  US_TEST_CONDITION(line == "static", "Check static.txt (from importing module) resource content")
#else
  US_TEST_CONDITION(resources.size() == 6, "Check imported resource count")
  line = GetResourceContent(resources[0]);
  US_TEST_CONDITION(line == "dynamic", "Check dynamic.txt resource content")
  // skip foo.txt
  line = GetResourceContent(resources[2]);
  US_TEST_CONDITION(line == "dynamic resource", "Check res.txt (from importing module) resource content")
  line = GetResourceContent(resources[3]);
  US_TEST_CONDITION(line == "static resource", "Check res.txt (from imported module) resource content")
  // skip special_chars.dummy.txt
  line = GetResourceContent(resources[5]);
  US_TEST_CONDITION(line == "static", "Check static.txt (from importing module) resource content")
#endif
}

} // end unnamed namespace

int usStaticModuleResourceTest(int /*argc*/, char* /*argv*/[])
{
  US_TEST_BEGIN("StaticModuleResourceTest");

  ModuleContext* mc = GetModuleContext();
  assert(mc);

#ifdef US_BUILD_SHARED_LIBS
  SharedLibraryHandle libB("TestModuleB");

  try
  {
    libB.Load();
  }
  catch (const std::exception& e)
  {
    US_TEST_FAILED_MSG(<< "Load module exception: " << e.what())
  }

  Module* module = ModuleRegistry::GetModule("TestModuleB Module");
  US_TEST_CONDITION_REQUIRED(module != NULL, "Test for existing module TestModuleB")

  US_TEST_CONDITION(module->GetName() == "TestModuleB Module", "Test module name")
#else
  Module* module = mc->GetModule();
#endif

  testResourceOperators(module);
  testResourcesWithStaticImport(module);

#ifdef US_BUILD_SHARED_LIBS
  ModuleResource resource = module->GetResource("static.txt");
  US_TEST_CONDITION_REQUIRED(resource.IsValid(), "Check valid static.txt resource")

  libB.Unload();

  US_TEST_CONDITION_REQUIRED(resource.IsValid() == false, "Check invalid static.txt resource")
#endif

  US_TEST_END()
}
<commit_msg>Fix unused variable error in release builds.<commit_after>/*=============================================================================

  Library: CppMicroServices

  Copyright (c) German Cancer Research Center,
    Division of Medical and Biological Informatics

  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 <usModuleContext.h>
#include <usGetModuleContext.h>
#include <usModuleRegistry.h>
#include <usModule.h>
#include <usModuleResource.h>
#include <usModuleResourceStream.h>

#include <usTestingConfig.h>

#include "usTestUtilSharedLibrary.h"
#include "usTestingMacros.h"

#include <assert.h>

#include <set>

US_USE_NAMESPACE

namespace {

std::string GetResourceContent(const ModuleResource& resource)
{
  std::string line;
  ModuleResourceStream rs(resource);
  std::getline(rs, line);
  return line;
}

struct ResourceComparator {
  bool operator()(const ModuleResource& mr1, const ModuleResource& mr2) const
  {
    return mr1 < mr2;
  }
};

void testResourceOperators(Module* module)
{
  std::vector<ModuleResource> resources = module->FindResources("", "res.txt", false);
  US_TEST_CONDITION_REQUIRED(resources.size() == 2, "Check resource count")
  US_TEST_CONDITION(resources[0] != resources[1], "Check non-equality for equally named resources")
}

void testResourcesWithStaticImport(Module* module)
{
  ModuleResource resource = module->GetResource("res.txt");
  US_TEST_CONDITION_REQUIRED(resource.IsValid(), "Check valid res.txt resource")
  std::string line = GetResourceContent(resource);
  US_TEST_CONDITION(line == "dynamic resource", "Check dynamic resource content")

  resource = module->GetResource("dynamic.txt");
  US_TEST_CONDITION_REQUIRED(resource.IsValid(), "Check valid dynamic.txt resource")
  line = GetResourceContent(resource);
  US_TEST_CONDITION(line == "dynamic", "Check dynamic resource content")

  resource = module->GetResource("static.txt");
  US_TEST_CONDITION_REQUIRED(resource.IsValid(), "Check valid static.txt resource")
  line = GetResourceContent(resource);
  US_TEST_CONDITION(line == "static", "Check dynamic resource content")

  std::vector<ModuleResource> resources = module->FindResources("", "*.txt", false);
  std::stable_sort(resources.begin(), resources.end(), ResourceComparator());
#ifdef US_BUILD_SHARED_LIBS
  US_TEST_CONDITION(resources.size() == 4, "Check imported resource count")
  line = GetResourceContent(resources[0]);
  US_TEST_CONDITION(line == "dynamic", "Check dynamic.txt resource content")
  line = GetResourceContent(resources[1]);
  US_TEST_CONDITION(line == "dynamic resource", "Check res.txt (from importing module) resource content")
  line = GetResourceContent(resources[2]);
  US_TEST_CONDITION(line == "static resource", "Check res.txt (from imported module) resource content")
  line = GetResourceContent(resources[3]);
  US_TEST_CONDITION(line == "static", "Check static.txt (from importing module) resource content")
#else
  US_TEST_CONDITION(resources.size() == 6, "Check imported resource count")
  line = GetResourceContent(resources[0]);
  US_TEST_CONDITION(line == "dynamic", "Check dynamic.txt resource content")
  // skip foo.txt
  line = GetResourceContent(resources[2]);
  US_TEST_CONDITION(line == "dynamic resource", "Check res.txt (from importing module) resource content")
  line = GetResourceContent(resources[3]);
  US_TEST_CONDITION(line == "static resource", "Check res.txt (from imported module) resource content")
  // skip special_chars.dummy.txt
  line = GetResourceContent(resources[5]);
  US_TEST_CONDITION(line == "static", "Check static.txt (from importing module) resource content")
#endif
}

} // end unnamed namespace

int usStaticModuleResourceTest(int /*argc*/, char* /*argv*/[])
{
  US_TEST_BEGIN("StaticModuleResourceTest");

  assert(GetModuleContext());

#ifdef US_BUILD_SHARED_LIBS
  SharedLibraryHandle libB("TestModuleB");

  try
  {
    libB.Load();
  }
  catch (const std::exception& e)
  {
    US_TEST_FAILED_MSG(<< "Load module exception: " << e.what())
  }

  Module* module = ModuleRegistry::GetModule("TestModuleB Module");
  US_TEST_CONDITION_REQUIRED(module != NULL, "Test for existing module TestModuleB")

  US_TEST_CONDITION(module->GetName() == "TestModuleB Module", "Test module name")
#else
  Module* module = mc->GetModule();
#endif

  testResourceOperators(module);
  testResourcesWithStaticImport(module);

#ifdef US_BUILD_SHARED_LIBS
  ModuleResource resource = module->GetResource("static.txt");
  US_TEST_CONDITION_REQUIRED(resource.IsValid(), "Check valid static.txt resource")

  libB.Unload();

  US_TEST_CONDITION_REQUIRED(resource.IsValid() == false, "Check invalid static.txt resource")
#endif

  US_TEST_END()
}
<|endoftext|>