<commit_before>/*************************************************************************
 *
 *  $RCSfile: undopage.cxx,v $
 *
 *  $Revision: 1.3 $
 *
 *  last change: $Author: dl $ $Date: 2001-09-27 15:03: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

#include <svx/svxids.hrc>
#ifndef _SFX_BINDINGS_HXX //autogen
#include <sfx2/bindings.hxx>
#endif
#ifndef _SFXDISPATCH_HXX //autogen
#include <sfx2/dispatch.hxx>
#endif
#ifndef _SFXVIEWFRM_HXX
#include <sfx2/viewfrm.hxx>
#endif

#include "sdpage.hxx"
#include "drviewsh.hxx"
#include "drawview.hxx"
#include "undopage.hxx"

#ifndef _SVDPAGV_HXX //autogen
#include <svx/svdpagv.hxx>
#endif

TYPEINIT1(SdPageFormatUndoAction, SdUndoAction);
TYPEINIT1(SdPageLRUndoAction, SdUndoAction);
TYPEINIT1(SdPageULUndoAction, SdUndoAction);

/*************************************************************************
|*
|* Destruktor
|*
\************************************************************************/

SdPageFormatUndoAction::~SdPageFormatUndoAction()
{
}

/*************************************************************************
|*
|* Undo()
|*
\************************************************************************/

void SdPageFormatUndoAction::Undo()
{
    Rectangle aOldBorderRect(nOldLeft, nOldUpper, nOldRight, nOldLower);
    pPage->ScaleObjects(aOldSize, aOldBorderRect, bNewScale);
    pPage->SetSize(aOldSize);
    pPage->SetLftBorder(nOldLeft);
    pPage->SetRgtBorder(nOldRight);
    pPage->SetUppBorder(nOldUpper);
    pPage->SetLwrBorder(nOldLower);
    pPage->SetOrientation(eOldOrientation);
    pPage->SetPaperBin( nOldPaperBin );

    pPage->SetBackgroundFullSize( bOldFullSize );
    if( !pPage->IsMasterPage() )
        ( (SdPage*) pPage->GetMasterPage(0) )->SetBackgroundFullSize( bOldFullSize );

    SfxViewShell* pViewShell = SfxViewShell::Current();

    if ( pViewShell->ISA(SdDrawViewShell) )
    {
        SdDrawViewShell* pDrViewShell = (SdDrawViewShell*) pViewShell;
        long nWidth = pPage->GetSize().Width();
        long nHeight = pPage->GetSize().Height();

        Point aPageOrg = Point(nWidth, nHeight / 2);
        Size aViewSize = Size(nWidth * 3, nHeight * 2);

        pDrViewShell->InitWindows(aPageOrg, aViewSize, Point(-1, -1), TRUE);
        pDrViewShell->GetView()->SetWorkArea(Rectangle(Point(0,0) - aPageOrg, aViewSize));

        pDrViewShell->UpdateScrollBars();
        pDrViewShell->GetView()->GetPageViewPvNum(0)->SetPageOrigin(Point(0,0));
        pViewShell->GetViewFrame()->GetBindings().Invalidate(SID_RULER_NULL_OFFSET);
        pViewShell->GetViewFrame()->GetDispatcher()->Execute(SID_SIZE_PAGE, SFX_CALLMODE_ASYNCHRON | SFX_CALLMODE_RECORD);
    }
}

/*************************************************************************
|*
|* Redo()
|*
\************************************************************************/

void SdPageFormatUndoAction::Redo()
{
    Rectangle aNewBorderRect(nNewLeft, nNewUpper, nNewRight, nNewLower);
    pPage->ScaleObjects(aNewSize, aNewBorderRect, bNewScale);
    pPage->SetSize(aNewSize);
    pPage->SetLftBorder(nNewLeft);
    pPage->SetRgtBorder(nNewRight);
    pPage->SetUppBorder(nNewUpper);
    pPage->SetLwrBorder(nNewLower);
    pPage->SetOrientation(eNewOrientation);
    pPage->SetPaperBin( nNewPaperBin );

    pPage->SetBackgroundFullSize( bNewFullSize );
    if( !pPage->IsMasterPage() )
        ( (SdPage*) pPage->GetMasterPage(0) )->SetBackgroundFullSize( bNewFullSize );

    SfxViewShell* pViewShell = SfxViewShell::Current();

    if ( pViewShell->ISA(SdDrawViewShell) )
    {
        SdDrawViewShell* pDrViewShell = (SdDrawViewShell*) pViewShell;
        long nWidth = pPage->GetSize().Width();
        long nHeight = pPage->GetSize().Height();

        Point aPageOrg = Point(nWidth, nHeight / 2);
        Size aViewSize = Size(nWidth * 3, nHeight * 2);

        pDrViewShell->InitWindows(aPageOrg, aViewSize, Point(-1, -1), TRUE);
        pDrViewShell->GetView()->SetWorkArea(Rectangle(Point(0,0) - aPageOrg, aViewSize));

        pDrViewShell->UpdateScrollBars();
        pDrViewShell->GetView()->GetPageViewPvNum(0)->SetPageOrigin(Point(0,0));
        pViewShell->GetViewFrame()->GetBindings().Invalidate(SID_RULER_NULL_OFFSET);
        pViewShell->GetViewFrame()->GetDispatcher()->Execute(SID_SIZE_PAGE, SFX_CALLMODE_ASYNCHRON | SFX_CALLMODE_RECORD);
    }
}

/*************************************************************************
|*
|* Repeat()
|*
\************************************************************************/

void SdPageFormatUndoAction::Repeat()
{
    Redo();
}

/*************************************************************************
|*
|* LR-Destruktor
|*
\************************************************************************/

SdPageLRUndoAction::~SdPageLRUndoAction()
{
}

/*************************************************************************
|*
|* LR-Undo()
|*
\************************************************************************/

void SdPageLRUndoAction::Undo()
{
    pPage->SetLftBorder(nOldLeft);
    pPage->SetRgtBorder(nOldRight);
}

/*************************************************************************
|*
|* LR-Redo()
|*
\************************************************************************/

void SdPageLRUndoAction::Redo()
{
    pPage->SetLftBorder(nNewLeft);
    pPage->SetRgtBorder(nNewRight);
}

/*************************************************************************
|*
|* LR-Repeat()
|*
\************************************************************************/

void SdPageLRUndoAction::Repeat()
{
    Redo();
}

/*************************************************************************
|*
|* UL-Destruktor
|*
\************************************************************************/

SdPageULUndoAction::~SdPageULUndoAction()
{
}

/*************************************************************************
|*
|* UL-Undo()
|*
\************************************************************************/

void SdPageULUndoAction::Undo()
{
    pPage->SetUppBorder(nOldUpper);
    pPage->SetLwrBorder(nOldLower);
}

/*************************************************************************
|*
|* UL-Redo()
|*
\************************************************************************/

void SdPageULUndoAction::Redo()
{
    pPage->SetUppBorder(nNewUpper);
    pPage->SetLwrBorder(nNewLower);
}

/*************************************************************************
|*
|* UL-Repeat()
|*
\************************************************************************/

void SdPageULUndoAction::Repeat()
{
    Redo();
}

<commit_msg>INTEGRATION: CWS impress1 (1.3.240); FILE MERGED 2004/01/09 16:32:28 af 1.3.240.2: #111996# Renamed header files DrawView.hxx, Fader.hxx, and ShowView.hxx back to lowercase version. 2003/09/17 09:06:12 af 1.3.240.1: #111996# Transition to stacked sub-shells. Introduction of namespace sd.<commit_after>/*************************************************************************
 *
 *  $RCSfile: undopage.cxx,v $
 *
 *  $Revision: 1.4 $
 *
 *  last change: $Author: obo $ $Date: 2004-01-20 11:25:06 $
 *
 *  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

#include "undopage.hxx"

#include <svx/svxids.hrc>
#ifndef _SFX_BINDINGS_HXX //autogen
#include <sfx2/bindings.hxx>
#endif
#ifndef _SFXDISPATCH_HXX //autogen
#include <sfx2/dispatch.hxx>
#endif
#ifndef _SFXVIEWFRM_HXX
#include <sfx2/viewfrm.hxx>
#endif

#include "sdpage.hxx"
#ifndef SD_DRAW_VIEW_SHELL_HXX
#include "DrawViewShell.hxx"
#endif
#ifndef SD_DRAW_VIEW_HXX
#include "drawview.hxx"
#endif

#ifndef _SVDPAGV_HXX //autogen
#include <svx/svdpagv.hxx>
#endif

TYPEINIT1(SdPageFormatUndoAction, SdUndoAction);
TYPEINIT1(SdPageLRUndoAction, SdUndoAction);
TYPEINIT1(SdPageULUndoAction, SdUndoAction);

/*************************************************************************
|*
|* Destruktor
|*
\************************************************************************/

SdPageFormatUndoAction::~SdPageFormatUndoAction()
{
}

/*************************************************************************
|*
|* Undo()
|*
\************************************************************************/

void SdPageFormatUndoAction::Undo()
{
    Rectangle aOldBorderRect(nOldLeft, nOldUpper, nOldRight, nOldLower);
    pPage->ScaleObjects(aOldSize, aOldBorderRect, bNewScale);
    pPage->SetSize(aOldSize);
    pPage->SetLftBorder(nOldLeft);
    pPage->SetRgtBorder(nOldRight);
    pPage->SetUppBorder(nOldUpper);
    pPage->SetLwrBorder(nOldLower);
    pPage->SetOrientation(eOldOrientation);
    pPage->SetPaperBin( nOldPaperBin );

    pPage->SetBackgroundFullSize( bOldFullSize );
    if( !pPage->IsMasterPage() )
        ( (SdPage*) pPage->GetMasterPage(0) )->SetBackgroundFullSize( bOldFullSize );

    SfxViewShell* pViewShell = SfxViewShell::Current();

    /*  if ( pViewShell->ISA(::sd::DrawViewShell))
    {
        ::sd::DrawViewShell* pDrViewShell =
              static_cast< ::sd::DrawViewShell*>(pViewShell);
        long nWidth = pPage->GetSize().Width();
        long nHeight = pPage->GetSize().Height();

        Point aPageOrg = Point(nWidth, nHeight / 2);
        Size aViewSize = Size(nWidth * 3, nHeight * 2);

        pDrViewShell->InitWindows(aPageOrg, aViewSize, Point(-1, -1), TRUE);
        pDrViewShell->GetView()->SetWorkArea(Rectangle(Point(0,0) - aPageOrg, aViewSize));

        pDrViewShell->UpdateScrollBars();
        pDrViewShell->GetView()->GetPageViewPvNum(0)->SetPageOrigin(Point(0,0));
        pViewShell->GetViewFrame()->GetBindings().Invalidate(SID_RULER_NULL_OFFSET);
        pViewShell->GetViewFrame()->GetDispatcher()->Execute(SID_SIZE_PAGE, SFX_CALLMODE_ASYNCHRON | SFX_CALLMODE_RECORD);
    }
    */
}

/*************************************************************************
|*
|* Redo()
|*
\************************************************************************/

void SdPageFormatUndoAction::Redo()
{
    Rectangle aNewBorderRect(nNewLeft, nNewUpper, nNewRight, nNewLower);
    pPage->ScaleObjects(aNewSize, aNewBorderRect, bNewScale);
    pPage->SetSize(aNewSize);
    pPage->SetLftBorder(nNewLeft);
    pPage->SetRgtBorder(nNewRight);
    pPage->SetUppBorder(nNewUpper);
    pPage->SetLwrBorder(nNewLower);
    pPage->SetOrientation(eNewOrientation);
    pPage->SetPaperBin( nNewPaperBin );

    pPage->SetBackgroundFullSize( bNewFullSize );
    if( !pPage->IsMasterPage() )
        ( (SdPage*) pPage->GetMasterPage(0) )->SetBackgroundFullSize( bNewFullSize );

    SfxViewShell* pViewShell = SfxViewShell::Current();

    /*  if ( pViewShell->ISA(::sd::DrawViewShell))
    {
        ::sd::DrawViewShell* pDrViewShell =
              static_cast< ::sd::DrawViewShell*>(pViewShell);
        long nWidth = pPage->GetSize().Width();
        long nHeight = pPage->GetSize().Height();

        Point aPageOrg = Point(nWidth, nHeight / 2);
        Size aViewSize = Size(nWidth * 3, nHeight * 2);

        pDrViewShell->InitWindows(aPageOrg, aViewSize, Point(-1, -1), TRUE);
        pDrViewShell->GetView()->SetWorkArea(Rectangle(Point(0,0) - aPageOrg, aViewSize));

        pDrViewShell->UpdateScrollBars();
        pDrViewShell->GetView()->GetPageViewPvNum(0)->SetPageOrigin(Point(0,0));
        pViewShell->GetViewFrame()->GetBindings().Invalidate(SID_RULER_NULL_OFFSET);
        pViewShell->GetViewFrame()->GetDispatcher()->Execute(SID_SIZE_PAGE, SFX_CALLMODE_ASYNCHRON | SFX_CALLMODE_RECORD);
    }
    */
}

/*************************************************************************
|*
|* Repeat()
|*
\************************************************************************/

void SdPageFormatUndoAction::Repeat()
{
    Redo();
}

/*************************************************************************
|*
|* LR-Destruktor
|*
\************************************************************************/

SdPageLRUndoAction::~SdPageLRUndoAction()
{
}

/*************************************************************************
|*
|* LR-Undo()
|*
\************************************************************************/

void SdPageLRUndoAction::Undo()
{
    pPage->SetLftBorder(nOldLeft);
    pPage->SetRgtBorder(nOldRight);
}

/*************************************************************************
|*
|* LR-Redo()
|*
\************************************************************************/

void SdPageLRUndoAction::Redo()
{
    pPage->SetLftBorder(nNewLeft);
    pPage->SetRgtBorder(nNewRight);
}

/*************************************************************************
|*
|* LR-Repeat()
|*
\************************************************************************/

void SdPageLRUndoAction::Repeat()
{
    Redo();
}

/*************************************************************************
|*
|* UL-Destruktor
|*
\************************************************************************/

SdPageULUndoAction::~SdPageULUndoAction()
{
}

/*************************************************************************
|*
|* UL-Undo()
|*
\************************************************************************/

void SdPageULUndoAction::Undo()
{
    pPage->SetUppBorder(nOldUpper);
    pPage->SetLwrBorder(nOldLower);
}

/*************************************************************************
|*
|* UL-Redo()
|*
\************************************************************************/

void SdPageULUndoAction::Redo()
{
    pPage->SetUppBorder(nNewUpper);
    pPage->SetLwrBorder(nNewLower);
}

/*************************************************************************
|*
|* UL-Repeat()
|*
\************************************************************************/

void SdPageULUndoAction::Repeat()
{
    Redo();
}

<|endoftext|>


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

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

#include "undopage.hxx"

#include <svx/svxids.hrc>
#ifndef _SFX_BINDINGS_HXX //autogen
#include <sfx2/bindings.hxx>
#endif
#ifndef _SFXDISPATCH_HXX //autogen
#include <sfx2/dispatch.hxx>
#endif
#ifndef _SFXVIEWFRM_HXX
#include <sfx2/viewfrm.hxx>
#endif

#include "sdpage.hxx"
#ifndef SD_DRAW_VIEW_SHELL_HXX
#include "DrawViewShell.hxx"
#endif
#ifndef SD_DRAW_VIEW_HXX
#include "drawview.hxx"
#endif

#ifndef _SVDPAGV_HXX //autogen
#include <svx/svdpagv.hxx>
#endif

TYPEINIT1(SdPageFormatUndoAction, SdUndoAction);
TYPEINIT1(SdPageLRUndoAction, SdUndoAction);
TYPEINIT1(SdPageULUndoAction, SdUndoAction);

/*************************************************************************
|*
|* Destruktor
|*
\************************************************************************/

SdPageFormatUndoAction::~SdPageFormatUndoAction()
{
}

/*************************************************************************
|*
|* Undo()
|*
\************************************************************************/

void SdPageFormatUndoAction::Undo()
{
    Rectangle aOldBorderRect(nOldLeft, nOldUpper, nOldRight, nOldLower);
    pPage->ScaleObjects(aOldSize, aOldBorderRect, bNewScale);
    pPage->SetSize(aOldSize);
    pPage->SetLftBorder(nOldLeft);
    pPage->SetRgtBorder(nOldRight);
    pPage->SetUppBorder(nOldUpper);
    pPage->SetLwrBorder(nOldLower);
    pPage->SetOrientation(eOldOrientation);
    pPage->SetPaperBin( nOldPaperBin );

    pPage->SetBackgroundFullSize( bOldFullSize );
    if( !pPage->IsMasterPage() )
        ( (SdPage&) pPage->TRG_GetMasterPage() ).SetBackgroundFullSize( bOldFullSize );

    SfxViewShell* pViewShell = SfxViewShell::Current();

    /*  if ( pViewShell->ISA(::sd::DrawViewShell))
    {
        ::sd::DrawViewShell* pDrViewShell =
              static_cast< ::sd::DrawViewShell*>(pViewShell);
        long nWidth = pPage->GetSize().Width();
        long nHeight = pPage->GetSize().Height();

        Point aPageOrg = Point(nWidth, nHeight / 2);
        Size aViewSize = Size(nWidth * 3, nHeight * 2);

        pDrViewShell->InitWindows(aPageOrg, aViewSize, Point(-1, -1), TRUE);
        pDrViewShell->GetView()->SetWorkArea(Rectangle(Point(0,0) - aPageOrg, aViewSize));

        pDrViewShell->UpdateScrollBars();
        pDrViewShell->GetView()->GetPageViewPvNum(0)->SetPageOrigin(Point(0,0));
        pViewShell->GetViewFrame()->GetBindings().Invalidate(SID_RULER_NULL_OFFSET);
        pViewShell->GetViewFrame()->GetDispatcher()->Execute(SID_SIZE_PAGE, SFX_CALLMODE_ASYNCHRON | SFX_CALLMODE_RECORD);
    }
    */
}

/*************************************************************************
|*
|* Redo()
|*
\************************************************************************/

void SdPageFormatUndoAction::Redo()
{
    Rectangle aNewBorderRect(nNewLeft, nNewUpper, nNewRight, nNewLower);
    pPage->ScaleObjects(aNewSize, aNewBorderRect, bNewScale);
    pPage->SetSize(aNewSize);
    pPage->SetLftBorder(nNewLeft);
    pPage->SetRgtBorder(nNewRight);
    pPage->SetUppBorder(nNewUpper);
    pPage->SetLwrBorder(nNewLower);
    pPage->SetOrientation(eNewOrientation);
    pPage->SetPaperBin( nNewPaperBin );

    pPage->SetBackgroundFullSize( bNewFullSize );
    if( !pPage->IsMasterPage() )
        ( (SdPage&) pPage->TRG_GetMasterPage() ).SetBackgroundFullSize( bNewFullSize );

    SfxViewShell* pViewShell = SfxViewShell::Current();

    /*  if ( pViewShell->ISA(::sd::DrawViewShell))
    {
        ::sd::DrawViewShell* pDrViewShell =
              static_cast< ::sd::DrawViewShell*>(pViewShell);
        long nWidth = pPage->GetSize().Width();
        long nHeight = pPage->GetSize().Height();

        Point aPageOrg = Point(nWidth, nHeight / 2);
        Size aViewSize = Size(nWidth * 3, nHeight * 2);

        pDrViewShell->InitWindows(aPageOrg, aViewSize, Point(-1, -1), TRUE);
        pDrViewShell->GetView()->SetWorkArea(Rectangle(Point(0,0) - aPageOrg, aViewSize));

        pDrViewShell->UpdateScrollBars();
        pDrViewShell->GetView()->GetPageViewPvNum(0)->SetPageOrigin(Point(0,0));
        pViewShell->GetViewFrame()->GetBindings().Invalidate(SID_RULER_NULL_OFFSET);
        pViewShell->GetViewFrame()->GetDispatcher()->Execute(SID_SIZE_PAGE, SFX_CALLMODE_ASYNCHRON | SFX_CALLMODE_RECORD);
    }
    */
}

/*************************************************************************
|*
|* Repeat()
|*
\************************************************************************/

void SdPageFormatUndoAction::Repeat()
{
    Redo();
}

/*************************************************************************
|*
|* LR-Destruktor
|*
\************************************************************************/

SdPageLRUndoAction::~SdPageLRUndoAction()
{
}

/*************************************************************************
|*
|* LR-Undo()
|*
\************************************************************************/

void SdPageLRUndoAction::Undo()
{
    pPage->SetLftBorder(nOldLeft);
    pPage->SetRgtBorder(nOldRight);
}

/*************************************************************************
|*
|* LR-Redo()
|*
\************************************************************************/

void SdPageLRUndoAction::Redo()
{
    pPage->SetLftBorder(nNewLeft);
    pPage->SetRgtBorder(nNewRight);
}

/*************************************************************************
|*
|* LR-Repeat()
|*
\************************************************************************/

void SdPageLRUndoAction::Repeat()
{
    Redo();
}

/*************************************************************************
|*
|* UL-Destruktor
|*
\************************************************************************/

SdPageULUndoAction::~SdPageULUndoAction()
{
}

/*************************************************************************
|*
|* UL-Undo()
|*
\************************************************************************/

void SdPageULUndoAction::Undo()
{
    pPage->SetUppBorder(nOldUpper);
    pPage->SetLwrBorder(nOldLower);
}

/*************************************************************************
|*
|* UL-Redo()
|*
\************************************************************************/

void SdPageULUndoAction::Redo()
{
    pPage->SetUppBorder(nNewUpper);
    pPage->SetLwrBorder(nNewLower);
}

/*************************************************************************
|*
|* UL-Repeat()
|*
\************************************************************************/

void SdPageULUndoAction::Repeat()
{
    Redo();
}

<commit_msg>INTEGRATION: CWS aw024 (1.5.174); FILE MERGED 2006/09/21 23:20:02 aw 1.5.174.3: RESYNC: (1.6-1.7); FILE MERGED 2005/09/17 11:45:44 aw 1.5.174.2: RESYNC: (1.5-1.6); FILE MERGED 2005/05/19 12:11:29 aw 1.5.174.1: #i39529#<commit_after>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: undopage.cxx,v $
 *
 *  $Revision: 1.8 $
 *
 *  last change: $Author: ihi $ $Date: 2006-11-14 14:32:12 $
 *
 *  The Contents of this file are made available subject to
 *  the terms of GNU Lesser General Public License Version 2.1.
 *
 *
 *    GNU Lesser General Public License Version 2.1
 *    =============================================
 *    Copyright 2005 by Sun Microsystems, Inc.
 *    901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *    This library is free software; you can redistribute it and/or
 *    modify it under the terms of the GNU Lesser General Public
 *    License version 2.1, as published by the Free Software Foundation.
 *
 *    This library is distributed in the hope that it will be useful,
 *    but WITHOUT ANY WARRANTY; without even the implied warranty of
 *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *    Lesser General Public License for more details.
 *
 *    You should have received a copy of the GNU Lesser General Public
 *    License along with this library; if not, write to the Free Software
 *    Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *    MA  02111-1307  USA
 *
 ************************************************************************/

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

#include "undopage.hxx"

#include <svx/svxids.hrc>
#ifndef _SFX_BINDINGS_HXX //autogen
#include <sfx2/bindings.hxx>
#endif
#ifndef _SFXDISPATCH_HXX //autogen
#include <sfx2/dispatch.hxx>
#endif
#ifndef _SFXVIEWFRM_HXX
#include <sfx2/viewfrm.hxx>
#endif

#include "sdpage.hxx"
#ifndef SD_DRAW_VIEW_SHELL_HXX
#include "DrawViewShell.hxx"
#endif
#ifndef SD_DRAW_VIEW_HXX
#include "drawview.hxx"
#endif

#ifndef _SVDPAGV_HXX //autogen
#include <svx/svdpagv.hxx>
#endif

TYPEINIT1(SdPageFormatUndoAction, SdUndoAction);
TYPEINIT1(SdPageLRUndoAction, SdUndoAction);
TYPEINIT1(SdPageULUndoAction, SdUndoAction);

/*************************************************************************
|*
|* Destruktor
|*
\************************************************************************/

SdPageFormatUndoAction::~SdPageFormatUndoAction()
{
}

/*************************************************************************
|*
|* Undo()
|*
\************************************************************************/

void SdPageFormatUndoAction::Undo()
{
    Rectangle aOldBorderRect(nOldLeft, nOldUpper, nOldRight, nOldLower);
    pPage->ScaleObjects(aOldSize, aOldBorderRect, bNewScale);
    pPage->SetSize(aOldSize);
    pPage->SetLftBorder(nOldLeft);
    pPage->SetRgtBorder(nOldRight);
    pPage->SetUppBorder(nOldUpper);
    pPage->SetLwrBorder(nOldLower);
    pPage->SetOrientation(eOldOrientation);
    pPage->SetPaperBin( nOldPaperBin );

    pPage->SetBackgroundFullSize( bOldFullSize );
    if( !pPage->IsMasterPage() )
        ( (SdPage&) pPage->TRG_GetMasterPage() ).SetBackgroundFullSize( bOldFullSize );

    SfxViewShell* pViewShell = SfxViewShell::Current();

    /*  if ( pViewShell->ISA(::sd::DrawViewShell))
    {
        ::sd::DrawViewShell* pDrViewShell =
              static_cast< ::sd::DrawViewShell*>(pViewShell);
        long nWidth = pPage->GetSize().Width();
        long nHeight = pPage->GetSize().Height();

        Point aPageOrg = Point(nWidth, nHeight / 2);
        Size aViewSize = Size(nWidth * 3, nHeight * 2);

        pDrViewShell->InitWindows(aPageOrg, aViewSize, Point(-1, -1), TRUE);
        pDrViewShell->GetView()->SetWorkArea(Rectangle(Point(0,0) - aPageOrg, aViewSize));

        pDrViewShell->UpdateScrollBars();
        pDrViewShell->GetView()->GetPageViewByIndex(0)->SetPageOrigin(Point(0,0));
        pViewShell->GetViewFrame()->GetBindings().Invalidate(SID_RULER_NULL_OFFSET);
        pViewShell->GetViewFrame()->GetDispatcher()->Execute(SID_SIZE_PAGE, SFX_CALLMODE_ASYNCHRON | SFX_CALLMODE_RECORD);
    }
    */
}

/*************************************************************************
|*
|* Redo()
|*
\************************************************************************/

void SdPageFormatUndoAction::Redo()
{
    Rectangle aNewBorderRect(nNewLeft, nNewUpper, nNewRight, nNewLower);
    pPage->ScaleObjects(aNewSize, aNewBorderRect, bNewScale);
    pPage->SetSize(aNewSize);
    pPage->SetLftBorder(nNewLeft);
    pPage->SetRgtBorder(nNewRight);
    pPage->SetUppBorder(nNewUpper);
    pPage->SetLwrBorder(nNewLower);
    pPage->SetOrientation(eNewOrientation);
    pPage->SetPaperBin( nNewPaperBin );

    pPage->SetBackgroundFullSize( bNewFullSize );
    if( !pPage->IsMasterPage() )
        ( (SdPage&) pPage->TRG_GetMasterPage() ).SetBackgroundFullSize( bNewFullSize );

    SfxViewShell* pViewShell = SfxViewShell::Current();

    /*  if ( pViewShell->ISA(::sd::DrawViewShell))
    {
        ::sd::DrawViewShell* pDrViewShell =
              static_cast< ::sd::DrawViewShell*>(pViewShell);
        long nWidth = pPage->GetSize().Width();
        long nHeight = pPage->GetSize().Height();

        Point aPageOrg = Point(nWidth, nHeight / 2);
        Size aViewSize = Size(nWidth * 3, nHeight * 2);

        pDrViewShell->InitWindows(aPageOrg, aViewSize, Point(-1, -1), TRUE);
        pDrViewShell->GetView()->SetWorkArea(Rectangle(Point(0,0) - aPageOrg, aViewSize));

        pDrViewShell->UpdateScrollBars();
        pDrViewShell->GetView()->GetPageViewByIndex(0)->SetPageOrigin(Point(0,0));
        pViewShell->GetViewFrame()->GetBindings().Invalidate(SID_RULER_NULL_OFFSET);
        pViewShell->GetViewFrame()->GetDispatcher()->Execute(SID_SIZE_PAGE, SFX_CALLMODE_ASYNCHRON | SFX_CALLMODE_RECORD);
    }
    */
}

/*************************************************************************
|*
|* Repeat()
|*
\************************************************************************/

void SdPageFormatUndoAction::Repeat()
{
    Redo();
}

/*************************************************************************
|*
|* LR-Destruktor
|*
\************************************************************************/

SdPageLRUndoAction::~SdPageLRUndoAction()
{
}

/*************************************************************************
|*
|* LR-Undo()
|*
\************************************************************************/

void SdPageLRUndoAction::Undo()
{
    pPage->SetLftBorder(nOldLeft);
    pPage->SetRgtBorder(nOldRight);
}

/*************************************************************************
|*
|* LR-Redo()
|*
\************************************************************************/

void SdPageLRUndoAction::Redo()
{
    pPage->SetLftBorder(nNewLeft);
    pPage->SetRgtBorder(nNewRight);
}

/*************************************************************************
|*
|* LR-Repeat()
|*
\************************************************************************/

void SdPageLRUndoAction::Repeat()
{
    Redo();
}

/*************************************************************************
|*
|* UL-Destruktor
|*
\************************************************************************/

SdPageULUndoAction::~SdPageULUndoAction()
{
}

/*************************************************************************
|*
|* UL-Undo()
|*
\************************************************************************/

void SdPageULUndoAction::Undo()
{
    pPage->SetUppBorder(nOldUpper);
    pPage->SetLwrBorder(nOldLower);
}

/*************************************************************************
|*
|* UL-Redo()
|*
\************************************************************************/

void SdPageULUndoAction::Redo()
{
    pPage->SetUppBorder(nNewUpper);
    pPage->SetLwrBorder(nNewLower);
}

/*************************************************************************
|*
|* UL-Repeat()
|*
\************************************************************************/

void SdPageULUndoAction::Repeat()
{
    Redo();
}

<|endoftext|>


<commit_before><commit_msg>don't crash on formatting outline level 10 in master view<commit_after><|endoftext|>


<commit_before>#ifndef ASYNCCURL_HPP_
#define ASYNCCURL_HPP_

/*
 * Author: jrahm
 * created: 2015/02/13
 * AsyncCurl.hpp: <description>
 */

#include <curl/curl.h>

#include <os/Runnable.hpp>
#include <containers/BlockingQueue.hpp>
#include <lang/Deallocator.hpp>

namespace curl {

class CurlException: public CException {
public:
    CurlException(const char* err, int code):
        CException(err, code){}
};

typedef s32_t http_response_code_t;
class CurlObserver {
public:
    virtual void onOK(http_response_code_t status_code) = 0 ;
    virtual void onException(CurlException& exc) = 0 ;
    virtual void read(const byte* bytes, size_t size) = 0 ;
    virtual inline ~CurlObserver(){}
};

class AsyncCurl;

class Curl {
public:
    friend class AsyncCurl;
    inline Curl() {
        raw = curl_easy_init();
    }

    inline void setSSLPeerVerifyEnabled( bool enabled ) {
        curl_easy_setopt(raw, CURLOPT_SSL_VERIFYPEER, enabled);
    }

    inline void setSSLHostVerifyEnabled( bool enabled ) {
        curl_easy_setopt(raw, CURLOPT_SSL_VERIFYHOST, enabled);
    }

    inline void setURL( const char* url ) {
        curl_easy_setopt(raw, CURLOPT_URL, url);
    }

    inline void setFollowLocation( bool follow ) {
        curl_easy_setopt(raw, CURLOPT_FOLLOWLOCATION, follow);
    }

    inline void setPostFields( const char* data ) {
        curl_easy_setopt(raw, CURLOPT_POSTFIELDS, data);
    }

private:
    CURL* raw;
};

class AsyncCurl: public os::Runnable {
public:
    AsyncCurl();

    /* Send a curl request */
    void sendRequest( Curl& c, CurlObserver* observer,
        lang::Deallocator<CurlObserver>* dalloc=NULL );

    void run();

private:
    static size_t __curl_consume_subroutine( void*, size_t, size_t, void* );
    static bool curl_init ;

    class Triad {
    public:
        CURL* request;
        CurlObserver* observer;
        lang::Deallocator<CurlObserver>* dalloc;
    };

    void enqueue_raw( CURL* c,
        CurlObserver* obs,
        lang::Deallocator<CurlObserver>* dealloc );

    containers::BlockingQueue<Triad*> requests;
};

}

#endif /* ASYNCCURL_HPP_ */
<commit_msg>patched async curl<commit_after>#ifndef ASYNCCURL_HPP_
#define ASYNCCURL_HPP_

/*
 * Author: jrahm
 * created: 2015/02/13
 * AsyncCurl.hpp: <description>
 */

#include <curl/curl.h>

#include <os/Runnable.hpp>
#include <containers/BlockingQueue.hpp>
#include <lang/Deallocator.hpp>

namespace curl {

class CurlException: public CException {
public:
    CurlException(const char* err, int code):
        CException(err, code){}
};

typedef s32_t http_response_code_t;
class CurlObserver {
public:
    virtual void onOK(http_response_code_t status_code) = 0 ;
    virtual void onException(CurlException& exc) = 0 ;
    virtual void read(const byte* bytes, size_t size) = 0 ;
    virtual inline ~CurlObserver(){}
};

class AsyncCurl;

class Curl {
public:
    friend class AsyncCurl;
    inline Curl() {
        raw = curl_easy_init();
    }

    inline void setSSLPeerVerifyEnabled( bool enabled ) {
        curl_easy_setopt(raw, CURLOPT_SSL_VERIFYPEER, enabled);
    }

    inline void setSSLHostVerifyEnabled( bool enabled ) {
        curl_easy_setopt(raw, CURLOPT_SSL_VERIFYHOST, enabled);
    }

    inline void setURL( const char* url ) {
        curl_easy_setopt(raw, CURLOPT_URL, url);
    }

    inline void setFollowLocation( bool follow ) {
        curl_easy_setopt(raw, CURLOPT_FOLLOWLOCATION, follow);
    }

    inline void setPostFields( const char* data ) {
        curl_easy_setopt(raw, CURLOPT_POSTFIELDS, strdup(data));
    }

private:
    CURL* raw;
};

class AsyncCurl: public os::Runnable {
public:
    AsyncCurl();

    /* Send a curl request */
    void sendRequest( Curl& c, CurlObserver* observer,
        lang::Deallocator<CurlObserver>* dalloc=NULL );

    void run();

private:
    static size_t __curl_consume_subroutine( void*, size_t, size_t, void* );
    static bool curl_init ;

    class Triad {
    public:
        CURL* request;
        CurlObserver* observer;
        lang::Deallocator<CurlObserver>* dalloc;
    };

    void enqueue_raw( CURL* c,
        CurlObserver* obs,
        lang::Deallocator<CurlObserver>* dealloc );

    containers::BlockingQueue<Triad*> requests;
};

}

#endif /* ASYNCCURL_HPP_ */
<|endoftext|>


<commit_before>/*
 * Licensed to the Apache Software Foundation (ASF) under one or more
 * contributor license agreements.  See the NOTICE file distributed with
 * this work for additional information regarding copyright ownership.
 * The ASF licenses this file to You 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 "CloseTransportsTask.h"

#include <activemq/exceptions/ActiveMQException.h>

using namespace activemq;
using namespace activemq::threads;
using namespace activemq::exceptions;
using namespace activemq::transport;
using namespace activemq::transport::failover;
using namespace decaf;
using namespace decaf::lang;
using namespace decaf::util;
using namespace decaf::util::concurrent;

////////////////////////////////////////////////////////////////////////////////
void CloseTransportsTask::add( const Pointer<Transport>& transport ) {
    synchronized( &transports ) {
        transports.push( transport );
    }
}

////////////////////////////////////////////////////////////////////////////////
bool CloseTransportsTask::isPending() const {
    synchronized( &transports ) {
        return !transports.empty();
    }
}

////////////////////////////////////////////////////////////////////////////////
bool CloseTransportsTask::iterate() {

    synchronized( &transports ) {

        if( !transports.empty() ) {
            Pointer<Transport> transport = transports.pop();

            try{
                transport->close();
            }
            AMQ_CATCHALL_NOTHROW()

            transport.reset( NULL );

            return !transports.empty();
        }

    }

    return false;
}
<commit_msg>Fix a warning on Windows<commit_after>/*
 * Licensed to the Apache Software Foundation (ASF) under one or more
 * contributor license agreements.  See the NOTICE file distributed with
 * this work for additional information regarding copyright ownership.
 * The ASF licenses this file to You 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 "CloseTransportsTask.h"

#include <activemq/exceptions/ActiveMQException.h>

using namespace activemq;
using namespace activemq::threads;
using namespace activemq::exceptions;
using namespace activemq::transport;
using namespace activemq::transport::failover;
using namespace decaf;
using namespace decaf::lang;
using namespace decaf::util;
using namespace decaf::util::concurrent;

////////////////////////////////////////////////////////////////////////////////
void CloseTransportsTask::add( const Pointer<Transport>& transport ) {
    synchronized( &transports ) {
        transports.push( transport );
    }
}

////////////////////////////////////////////////////////////////////////////////
bool CloseTransportsTask::isPending() const {

	bool result = false;

	synchronized( &transports ) {
        result = !transports.empty();
    }

	return result;
}

////////////////////////////////////////////////////////////////////////////////
bool CloseTransportsTask::iterate() {

    synchronized( &transports ) {

        if( !transports.empty() ) {
            Pointer<Transport> transport = transports.pop();

            try{
                transport->close();
            }
            AMQ_CATCHALL_NOTHROW()

            transport.reset( NULL );

            return !transports.empty();
        }

    }

    return false;
}
<|endoftext|>


<commit_before>#ifdef HAVE_CONFIG_H
#  include <simgear_config.h>
#endif

#include "event_mgr.hxx"

#include <simgear/debug/logstream.hxx>

void SGEventMgr::add(const std::string& name, SGCallback* cb,
                     double interval, double delay,
                     bool repeat, bool simtime)
{
    // Clamp the delay value to 1 usec, so that user code can use
    // "zero" as a synonym for "next frame".
    if(delay <= 0) delay = 1e-6;
    if(interval <= 0) interval = 1e-6; // No timer endless loops please...

    SGTimer* t = new SGTimer;
    t->interval = interval;
    t->callback = cb;
    t->repeat = repeat;
    t->name = name;
    t->running = false;

    SGTimerQueue* q = simtime ? &_simQueue : &_rtQueue;

    q->insert(t, delay);
}

SGTimer::~SGTimer()
{
    delete callback;
    callback = NULL;
}

void SGTimer::run()
{
    (*callback)();
}

SGEventMgr::SGEventMgr() :
    _inited(false)
{

}

SGEventMgr::~SGEventMgr()
{

}

void SGEventMgr::unbind()
{
    _freezeProp.clear();
    _rtProp.clear();
}

void SGEventMgr::init()
{
    if (_inited) {
        SG_LOG(SG_GENERAL, SG_WARN, "duplicate init of SGEventMgr");
    }
    _inited = true;
}

void SGEventMgr::shutdown()
{
    _inited = false;

    _simQueue.clear();
    _rtQueue.clear();
}

void SGEventMgr::update(double delta_time_sec)
{
    _simQueue.update(delta_time_sec);

    double rt = _rtProp ? _rtProp->getDoubleValue() : 0;
    _rtQueue.update(rt);
}

void SGEventMgr::removeTask(const std::string& name)
{
    // due to the ordering of the event-mgr in FG, tasks can be removed
    // after we are shutdown (and hence, have all been cleared). Guard
    // against this so we don't generate warnings below.
    if (!_inited) {
        return;
    }

  SGTimer* t = _simQueue.findByName(name);
  if (t) {
    _simQueue.remove(t);
  } else if ((t = _rtQueue.findByName(name))) {
    _rtQueue.remove(t);
  } else {
    SG_LOG(SG_GENERAL, SG_WARN, "removeTask: no task found with name:" << name);
    return;
  }
  if (t->running) {
    // mark as not repeating so that the SGTimerQueue::update()
    // will clean it up
    t->repeat = false;
  } else {
    delete t;
  }
}

////////////////////////////////////////////////////////////////////////
// SGTimerQueue
// This is the priority queue implementation:
////////////////////////////////////////////////////////////////////////

SGTimerQueue::SGTimerQueue(int size)
{
    _now = 0;
    _numEntries = 0;
    _tableSize = 1;
    while(size > _tableSize)
        _tableSize = ((_tableSize + 1)<<1) - 1;

    _table = new HeapEntry[_tableSize];
    for(int i=0; i<_tableSize; i++) {
	    _table[i].pri = 0;
        _table[i].timer = 0;
    }
}

SGTimerQueue::~SGTimerQueue()
{
    clear();
    delete[] _table;
}

void SGTimerQueue::clear()
{
    // delete entries
    for(int i=0; i<_numEntries; i++) {
        delete _table[i].timer;
    }

    _numEntries = 0;

    // clear entire table to empty
    for(int i=0; i<_tableSize; i++) {
	    _table[i].pri = 0;
        _table[i].timer = 0;
    }
}

void SGTimerQueue::update(double deltaSecs)
{
    _now += deltaSecs;
    while(_numEntries && nextTime() <= _now) {
        SGTimer* t = remove();
        if(t->repeat)
            insert(t, t->interval);
        // warning: this is not thread safe
        // but the entire timer queue isn't either
        t->running = true;
        t->run();
        t->running = false;
        if (!t->repeat)
            delete t;
    }
}

void SGTimerQueue::insert(SGTimer* timer, double time)
{
    if(_numEntries >= _tableSize)
	growArray();

    _numEntries++;
    _table[_numEntries-1].pri = -(_now + time);
    _table[_numEntries-1].timer = timer;

    siftUp(_numEntries-1);
}

SGTimer* SGTimerQueue::remove(SGTimer* t)
{
    int entry;
    for(entry=0; entry<_numEntries; entry++)
        if(_table[entry].timer == t)
            break;
    if(entry == _numEntries)
        return 0;

    // Swap in the last item in the table, and sift down
    swap(entry, _numEntries-1);
    _numEntries--;
    siftDown(entry);

    return t;
}

SGTimer* SGTimerQueue::remove()
{
    if(_numEntries == 0) {
	return 0;
    } else if(_numEntries == 1) {
	_numEntries = 0;
	return _table[0].timer;
    }

    SGTimer *result = _table[0].timer;
    _table[0] = _table[_numEntries - 1];
    _numEntries--;
    siftDown(0);
    return result;
}

void SGTimerQueue::siftDown(int n)
{
    // While we have children bigger than us, swap us with the biggest
    // child.
    while(lchild(n) < _numEntries) {
        int bigc = lchild(n);
        if(rchild(n) < _numEntries && pri(rchild(n)) > pri(bigc))
            bigc = rchild(n);
        if(pri(bigc) <= pri(n))
            break;
        swap(n, bigc);
        n = bigc;
    }
}

void SGTimerQueue::siftUp(int n)
{
    while((n != 0) && (_table[n].pri > _table[parent(n)].pri)) {
	swap(n, parent(n));
	n = parent(n);
    }
    siftDown(n);
}

void SGTimerQueue::growArray()
{
    _tableSize = ((_tableSize+1)<<1) - 1;
    HeapEntry *newTable = new HeapEntry[_tableSize];
    for(int i=0; i<_numEntries; i++) {
	newTable[i].pri  = _table[i].pri;
	newTable[i].timer = _table[i].timer;
    }
    delete[] _table;
    _table = newTable;
}

SGTimer* SGTimerQueue::findByName(const std::string& name) const
{
  for (int i=0; i < _numEntries; ++i) {
    if (_table[i].timer->name == name) {
      return _table[i].timer;
    }
  }

  return NULL;
}
<commit_msg>Avoid a warning on startup<commit_after>#ifdef HAVE_CONFIG_H
#  include <simgear_config.h>
#endif

#include "event_mgr.hxx"

#include <simgear/debug/logstream.hxx>

void SGEventMgr::add(const std::string& name, SGCallback* cb,
                     double interval, double delay,
                     bool repeat, bool simtime)
{
    // Clamp the delay value to 1 usec, so that user code can use
    // "zero" as a synonym for "next frame".
    if(delay <= 0) delay = 1e-6;
    if(interval <= 0) interval = 1e-6; // No timer endless loops please...

    SGTimer* t = new SGTimer;
    t->interval = interval;
    t->callback = cb;
    t->repeat = repeat;
    t->name = name;
    t->running = false;

    SGTimerQueue* q = simtime ? &_simQueue : &_rtQueue;

    q->insert(t, delay);
}

SGTimer::~SGTimer()
{
    delete callback;
    callback = NULL;
}

void SGTimer::run()
{
    (*callback)();
}

SGEventMgr::SGEventMgr() :
    _inited(false)
{

}

SGEventMgr::~SGEventMgr()
{

}

void SGEventMgr::unbind()
{
    _freezeProp.clear();
    _rtProp.clear();
}

void SGEventMgr::init()
{
    if (_inited) {
        // protected against duplicate calls here, in case
		// init ever does something more complex in the future.
		return;
    }

    _inited = true;
}

void SGEventMgr::shutdown()
{
    _inited = false;

    _simQueue.clear();
    _rtQueue.clear();
}

void SGEventMgr::update(double delta_time_sec)
{
    _simQueue.update(delta_time_sec);

    double rt = _rtProp ? _rtProp->getDoubleValue() : 0;
    _rtQueue.update(rt);
}

void SGEventMgr::removeTask(const std::string& name)
{
    // due to the ordering of the event-mgr in FG, tasks can be removed
    // after we are shutdown (and hence, have all been cleared). Guard
    // against this so we don't generate warnings below.
    if (!_inited) {
        return;
    }

  SGTimer* t = _simQueue.findByName(name);
  if (t) {
    _simQueue.remove(t);
  } else if ((t = _rtQueue.findByName(name))) {
    _rtQueue.remove(t);
  } else {
    SG_LOG(SG_GENERAL, SG_WARN, "removeTask: no task found with name:" << name);
    return;
  }
  if (t->running) {
    // mark as not repeating so that the SGTimerQueue::update()
    // will clean it up
    t->repeat = false;
  } else {
    delete t;
  }
}

////////////////////////////////////////////////////////////////////////
// SGTimerQueue
// This is the priority queue implementation:
////////////////////////////////////////////////////////////////////////

SGTimerQueue::SGTimerQueue(int size)
{
    _now = 0;
    _numEntries = 0;
    _tableSize = 1;
    while(size > _tableSize)
        _tableSize = ((_tableSize + 1)<<1) - 1;

    _table = new HeapEntry[_tableSize];
    for(int i=0; i<_tableSize; i++) {
	    _table[i].pri = 0;
        _table[i].timer = 0;
    }
}

SGTimerQueue::~SGTimerQueue()
{
    clear();
    delete[] _table;
}

void SGTimerQueue::clear()
{
    // delete entries
    for(int i=0; i<_numEntries; i++) {
        delete _table[i].timer;
    }

    _numEntries = 0;

    // clear entire table to empty
    for(int i=0; i<_tableSize; i++) {
	    _table[i].pri = 0;
        _table[i].timer = 0;
    }
}

void SGTimerQueue::update(double deltaSecs)
{
    _now += deltaSecs;
    while(_numEntries && nextTime() <= _now) {
        SGTimer* t = remove();
        if(t->repeat)
            insert(t, t->interval);
        // warning: this is not thread safe
        // but the entire timer queue isn't either
        t->running = true;
        t->run();
        t->running = false;
        if (!t->repeat)
            delete t;
    }
}

void SGTimerQueue::insert(SGTimer* timer, double time)
{
    if(_numEntries >= _tableSize)
	growArray();

    _numEntries++;
    _table[_numEntries-1].pri = -(_now + time);
    _table[_numEntries-1].timer = timer;

    siftUp(_numEntries-1);
}

SGTimer* SGTimerQueue::remove(SGTimer* t)
{
    int entry;
    for(entry=0; entry<_numEntries; entry++)
        if(_table[entry].timer == t)
            break;
    if(entry == _numEntries)
        return 0;

    // Swap in the last item in the table, and sift down
    swap(entry, _numEntries-1);
    _numEntries--;
    siftDown(entry);

    return t;
}

SGTimer* SGTimerQueue::remove()
{
    if(_numEntries == 0) {
	return 0;
    } else if(_numEntries == 1) {
	_numEntries = 0;
	return _table[0].timer;
    }

    SGTimer *result = _table[0].timer;
    _table[0] = _table[_numEntries - 1];
    _numEntries--;
    siftDown(0);
    return result;
}

void SGTimerQueue::siftDown(int n)
{
    // While we have children bigger than us, swap us with the biggest
    // child.
    while(lchild(n) < _numEntries) {
        int bigc = lchild(n);
        if(rchild(n) < _numEntries && pri(rchild(n)) > pri(bigc))
            bigc = rchild(n);
        if(pri(bigc) <= pri(n))
            break;
        swap(n, bigc);
        n = bigc;
    }
}

void SGTimerQueue::siftUp(int n)
{
    while((n != 0) && (_table[n].pri > _table[parent(n)].pri)) {
	swap(n, parent(n));
	n = parent(n);
    }
    siftDown(n);
}

void SGTimerQueue::growArray()
{
    _tableSize = ((_tableSize+1)<<1) - 1;
    HeapEntry *newTable = new HeapEntry[_tableSize];
    for(int i=0; i<_numEntries; i++) {
	newTable[i].pri  = _table[i].pri;
	newTable[i].timer = _table[i].timer;
    }
    delete[] _table;
    _table = newTable;
}

SGTimer* SGTimerQueue::findByName(const std::string& name) const
{
  for (int i=0; i < _numEntries; ++i) {
    if (_table[i].timer->name == name) {
      return _table[i].timer;
    }
  }

  return NULL;
}
<|endoftext|>


<commit_before>#include <iostream>

#include "readatomslinks.h"
#include "limits.h"
#include "spin.h"

std::vector<Atom> atoms;

/**
 * Computes the energy of the system.
 *

 * Using the atom, the spin and the neighbors, it is computed the energy of the system.
 * @param atoms  vector with the spin values of the atom
 * @param spin  random spin orientation of the atom
 * @param csr  compressed sparse row that contains the information of the atoms' neighbors
 * @return double Ener the energy of the system.
 */
double compute_energy (const std::vector<Atom>& atoms, const std::vector<Spin>& spins, const CSRMatrix& csr)
{
    /** Energy of the system. */
    double Ener{0};
    /** Spin value of the atom and the neighbors. */
    double SpinValue;

    for (int i = 0; i < atoms.size(); ++i)
    {
        for (int j = csr.limits[i] ; j < csr.limits[i+1]; ++j)
        {
            SpinValue = spins[i] * spins[csr.neighboors[j]];
            Ener -= csr.exchanges[j] * atoms[i].s * atoms[csr.neighboors[j]].s * SpinValue;
        }
    }

    return Ener;
}<commit_msg>Testing something with the branches<commit_after>#include <iostream>

#include "readatomslinks.h"
#include "limits.h"
#include "spin.h"

std::vector<Atom> atoms;

/**
 * Computes the energy of the system.
 *

 * Using the atom, the spin and the neighbors, it is computed the energy of the system.
 * @param atoms  vector with the spin values of the atom
 * @param spin  random spin orientation of the atom
 * @param csr  compressed sparse row that contains the information of the atoms' neighbors
 * @return double ener the energy of the system.
 */
double compute_energy (const std::vector<Atom>& atoms, const std::vector<Spin>& spins, const CSRMatrix& csr)
{
    /** Energy of the system. */
    double ener{0};
    /** Spin value of the atom and the neighbors. */
    double SpinValue;

    for (int i = 0; i < atoms.size(); ++i)
    {
        for (int j = csr.limits[i] ; j < csr.limits[i+1]; ++j)
        {
            SpinValue = spins[i] * spins[csr.neighboors[j]];
            ener -= csr.exchanges[j] * atoms[i].s * atoms[csr.neighboors[j]].s * SpinValue;
        }
    }

    return ener;
}<|endoftext|>


<commit_before>#include <cstring>
#include <iostream>
#include <net/ethernet.h>
#include <netinet/ether.h>
#include <netinet/ip.h>
#include <netinet/udp.h>
#include <arpa/inet.h>

#include "colors.h"
#include "interface.h"

using namespace std;
using namespace Colors;

void sigint_handler(int);

int main(int argc, char* argv[])
{
  if (argc != 2)
  {
    std::cerr << "Usage: phantom <interface>" << endl;
    exit(-1);
  }

  if (initSignal(sigint_handler) < 0)
    exit(-1);

  int socket;
  if (initSocket(socket) < 0)
    exit(-1);

  struct ifreq ifr;
  strcpy(ifr.ifr_name, argv[1]);

  if (initInterface(socket, ifr) < 0)
    exit(-1);

  // Ready to capture. :-)
  cout << blue << "Ready to capture from: " << reset << ifr.ifr_name << endl;
  cout << blue << "      Interface Index: " << reset << ifr.ifr_ifindex << endl;
  cout << blue << "        Hardware Addr: " << reset << ether_ntoa((struct ether_addr*)ifr.ifr_hwaddr.sa_data) << endl;
  cout << blue << "        Protocol Addr: " << reset << inet_ntoa(((struct sockaddr_in *)&ifr.ifr_addr)->sin_addr) << endl;

  if (resetInterface(socket, ifr) < 0)
    exit(-1);

  if (closeSocket(socket) < 0)
    exit(-1);

  return 0;
}

void sigint_handler(int)
{
}
<commit_msg>Add sniffing for ethernet & ip packets.<commit_after>#include <cstring>

#include <iostream>
#include <thread>

#include <net/ethernet.h>
#include <netinet/ether.h>
#include <linux/ip.h>
#include <netinet/udp.h>
#include <arpa/inet.h>

#include "colors.h"
#include "interface.h"

using namespace std;
using namespace Colors;

void sigint_handler(int);
void sniff(const int, const ifreq&);

bool stop = false;

int main(int argc, char* argv[])
{
  if (argc != 2)
  {
    std::cerr << "Usage: phantom <interface>" << endl;
    exit(-1);
  }

  if (initSignal(sigint_handler) < 0)
    exit(-1);

  int socket;
  if (initSocket(socket) < 0)
    exit(-1);

  struct ifreq ifr;
  strcpy(ifr.ifr_name, argv[1]);

  if (initInterface(socket, ifr) < 0)
    exit(-1);

  std::thread sniffer(sniff, socket, ifr);
  sniffer.join();

  if (resetInterface(socket, ifr) < 0)
    exit(-1);

  if (closeSocket(socket) < 0)
    exit(-1);

  return 0;
}

void sigint_handler(int)
{
  cout << yellow << "Received SIGINT to interrupt execution." << reset << endl;
  stop = true;
}

void sniff(const int socket, const ifreq& ifr)
{
  cout << blue << "Ready to capture from: " << reset << ifr.ifr_name << endl;
  cout << blue << "      Interface Index: " << reset << ifr.ifr_ifindex << endl;
  cout << blue << "        Hardware Addr: " << reset << ether_ntoa((struct ether_addr*)ifr.ifr_hwaddr.sa_data) << endl;
  cout << blue << "        Protocol Addr: " << reset << inet_ntoa(((struct sockaddr_in *)&ifr.ifr_addr)->sin_addr) << endl;

  u_char buff[ETHER_MAX_LEN];

  for (;;)
  {
    if (stop)
      break;

    if (recv(socket, (char*)&buff, sizeof(buff), 0x00) < ETHER_MIN_LEN)
      continue;

    struct ether_header ether;
    memcpy(&ether, &buff, sizeof(ether));

    cout << endl;
    cout << blue << "Ethernet Packet" << reset << endl;
    cout << blue << "Destination: " << reset << ether_ntoa((struct ether_addr*)ether.ether_dhost) << endl;
    cout << blue << "        Src: " << reset << ether_ntoa((struct ether_addr*)ether.ether_shost) << endl;
    cout << blue << "       Type: " << reset << ntohs(ether.ether_type) << endl;

    if (ntohs(ether.ether_type) == ETHERTYPE_IP)
    {
      struct iphdr ip;
      memcpy(&ip, &buff[ETHER_HDR_LEN], sizeof(iphdr));

      cout << endl;
      cout << blue << "IP Packet" << reset << endl;
      cout << blue << "        IHL: " << reset << ip.ihl << endl;
      cout << blue << "    Version: " << reset << ip.version << endl;
      cout << blue << "        TOS: " << reset << ip.tos << endl;
      cout << blue << "        LEN: " << reset << ip.tot_len << endl;
      cout << blue << "         ID: " << reset << ip.id << endl;
      cout << blue << "   Frag Off: " << reset << ip.frag_off << endl;
      cout << blue << "        TTL: " << reset << ip.ttl << endl;
      cout << blue << "   Protocol: " << reset << ntohs(ip.protocol) << endl;
      cout << blue << "      Check: " << reset << ip.check << endl;
      cout << blue << "     Source: " << reset << inet_ntoa(((struct sockaddr_in *)&ip.saddr)->sin_addr) << endl;
      cout << blue << "Destination: " << reset << inet_ntoa(((struct sockaddr_in *)&ip.daddr)->sin_addr) << endl;

      if (ntohs(ip.protocol) == IPPROTO_UDP)
      {
        cout << endl << red << "Received UDP packet!" << reset << endl;
      }
    }
  }
}
<|endoftext|>


<commit_before>#include <cstdint>
#include <cstring>
#include <memory>
#include <cmath>

namespace Sieves {
	constexpr size_t compileTimeLogBase2(size_t n) {
		return (n <= 1) ? 0 : 1 + compileTimeLogBase2(n / 2);
	}

	constexpr size_t sizeOfElementInBytes = sizeof(uint32_t);
	constexpr size_t sizeOfElementInBits = 8 * sizeOfElementInBytes;
	constexpr size_t logSizeOfElementInBits = compileTimeLogBase2(sizeOfElementInBits);

	class PrimeSieve {
		std::unique_ptr<uint32_t[]> m_sieve;
	public:
		PrimeSieve(const PrimeSieve&) = default;
		PrimeSieve(PrimeSieve&&) = default;
		PrimeSieve& operator=(const PrimeSieve&) = default;
		PrimeSieve& operator=(PrimeSieve&&) = default;

		explicit PrimeSieve(const size_t minSieveSize) {
			const size_t numOfElementsInArray = 1 + minSieveSize / sizeOfElementInBits;
			m_sieve = std::make_unique<uint32_t[]>(numOfElementsInArray);
			const size_t totalSizeInBytes = numOfElementsInArray*sizeOfElementInBytes;

			uint32_t* const sieve = m_sieve.get();
			std::memset(sieve, 0xAA, totalSizeInBytes);
			sieve[0] ^= 6;

			const size_t limit = numOfElementsInArray*sizeOfElementInBits;
			const size_t sqrtLimit = std::sqrt(limit - 1);
			for (size_t i = 3; i <= sqrtLimit; i += 2)
				if (sieve[i >> logSizeOfElementInBits] & (1 << (i&(sizeOfElementInBits - 1))))
					for (size_t j = i + i; j < limit; j += i)
						sieve[j >> logSizeOfElementInBits] &= ~(1 << (j&(sizeOfElementInBits - 1)));
		}

		inline bool isPrime(size_t number) const {
			return m_sieve[number >> logSizeOfElementInBits] & (1 << (number&(sizeOfElementInBits - 1)));
		}

		auto countPrimes(const size_t minSieveSize) {
			const size_t numOfElementsInArray = 1 + minSieveSize / sizeOfElementInBits;
			uint32_t sum = 0;
			for (size_t i = 0; i < numOfElementsInArray; ++i)
#ifdef _MSC_VER
				sum += _mm_popcnt_u32(m_sieve[i]);
#else
				sum += __builtin_popcount(m_sieve[i]);
#endif
			return sum;
		}
	};

	class FactorCountSieve {
		std::unique_ptr<uint8_t[]> m_sieve;
	public:
		explicit FactorCountSieve(const size_t limit) : m_sieve(new uint8_t[limit + 1]) {
			uint8_t* const sieve = m_sieve.get();
			std::memset(sieve, 0, limit + 1);
			for (size_t i = 2; i <= limit; ++i)
				if (!sieve[i])
					for (size_t j = i + i; j <= limit; j += i)
						sieve[j]++;
		}

		inline uint8_t numOfFactors(size_t number) const {
			return m_sieve[number];
		}

		inline uint8_t* get() const {
			return m_sieve.get();
		}
	};
}<commit_msg>fixed count for non intsize multiples<commit_after>#include <cstdint>
#include <cstring>
#include <memory>
#include <cmath>

namespace Sieves {
	constexpr size_t compileTimeLogBase2(size_t n) {
		return (n <= 1) ? 0 : 1 + compileTimeLogBase2(n / 2);
	}

	constexpr size_t sizeOfElementInBytes = sizeof(uint32_t);
	constexpr size_t sizeOfElementInBits = 8 * sizeOfElementInBytes;
	constexpr size_t logSizeOfElementInBits = compileTimeLogBase2(sizeOfElementInBits);

	class PrimeSieve {
		std::unique_ptr<uint32_t[]> m_sieve;
	public:
		PrimeSieve(const PrimeSieve&) = default;
		PrimeSieve(PrimeSieve&&) = default;
		PrimeSieve& operator=(const PrimeSieve&) = default;
		PrimeSieve& operator=(PrimeSieve&&) = default;

		explicit PrimeSieve(const size_t minSieveSize) {
			const size_t numOfElementsInArray = 1 + minSieveSize / sizeOfElementInBits;
			m_sieve = std::make_unique<uint32_t[]>(numOfElementsInArray);
			const size_t totalSizeInBytes = numOfElementsInArray*sizeOfElementInBytes;

			uint32_t* const sieve = m_sieve.get();
			std::memset(sieve, 0xAA, totalSizeInBytes);
			sieve[0] ^= 6;

			const size_t limit = numOfElementsInArray*sizeOfElementInBits;
			const size_t sqrtLimit = std::sqrt(limit - 1);
			for (size_t i = 3; i <= sqrtLimit; i += 2)
				if (sieve[i >> logSizeOfElementInBits] & (1 << (i&(sizeOfElementInBits - 1))))
					for (size_t j = i + i; j < limit; j += i)
						sieve[j >> logSizeOfElementInBits] &= ~(1 << (j&(sizeOfElementInBits - 1)));
		}

		inline bool isPrime(size_t number) const {
			return m_sieve[number >> logSizeOfElementInBits] & (1 << (number&(sizeOfElementInBits - 1)));
		}

		auto countPrimes(const size_t minSieveSize) {
			const size_t lastIdx = minSieveSize / sizeOfElementInBits;
			uint32_t sum = 0;
			for (size_t i = 0; i < lastIdx; ++i)
		#ifdef _MSC_VER
			    sum += _mm_popcnt_u32(m_sieve[i]);
		#else
			    sum += __builtin_popcount(m_sieve[i]);
		#endif
			const size_t remaining = minSieveSize & (sizeOfElementInBits - 1);
			for (size_t i = 0; i < remaining; ++i)
			    if((m_sieve[lastIdx] >> i) & 1)
				sum++;
			return sum;
		}
	};

	class FactorCountSieve {
		std::unique_ptr<uint8_t[]> m_sieve;
	public:
		explicit FactorCountSieve(const size_t limit) : m_sieve(new uint8_t[limit + 1]) {
			uint8_t* const sieve = m_sieve.get();
			std::memset(sieve, 0, limit + 1);
			for (size_t i = 2; i <= limit; ++i)
				if (!sieve[i])
					for (size_t j = i + i; j <= limit; j += i)
						sieve[j]++;
		}

		inline uint8_t numOfFactors(size_t number) const {
			return m_sieve[number];
		}

		inline uint8_t* get() const {
			return m_sieve.get();
		}
	};
}
<|endoftext|>


<commit_before>#include "LiquidCrystal.h"
#include "LiquidCrystalRus.h"

#include <stdio.h>
#include <string.h>
#include <inttypes.h>
#include <avr/pgmspace.h>
#include "WProgram.h"

// except 0401 --> 0xa2 = , 0451 --> 0xb5
PROGMEM prog_uchar utf_recode[] =
{
    0x41,0xa0,0x42,0xa1,0xe0,0x45,0xa3,0xa4,0xa5,0xa6,0x4b,0xa7,0x4d,0x48,0x4f,
    0xa8,0x50,0x43,0x54,0xa9,0xaa,0x58,0xe1,0xab,0xac,0xe2,0xad,0xae,0x62,0xaf,0xb0,0xb1,
    0x61,0xb2,0xb3,0xb4,0xe3,0x65,0xb6,0xb7,0xb8,0xb9,0xba,0xbb,0xbc,0xbd,0x6f,
    0xbe,0x70,0x63,0xbf,0x79,0xe4,0x78,0xe5,0xc0,0xc1,0xe6,0xc2,0xc3,0xc4,0xc5,0xc6,0xc7
};

void LiquidCrystalRus::write(uint8_t value)
{
    uint8_t out_char = value;

    if (value >= 0x80) // UTF-8 handling
    {
        if (value >= 0xc0)
            utf_hi_char = value - 0xd0;
        else
        {
            value &= 0x3f;

            if (!utf_hi_char && value == 1)
                out_char = 0xa2; //
            else if (utf_hi_char == 1 && value == 0x11)
                out_char = 0xb5; //
            else
                out_char = pgm_read_byte_near(utf_recode + value + (utf_hi_char << 6) - 0x10);

            LiquidCrystal::write(out_char);
        }
    }
    else
        LiquidCrystal::write(out_char);
}
<commit_msg>Converted LiquidCrystalRus.cpp source to UTF-8 encoding<commit_after>#include "LiquidCrystal.h"
#include "LiquidCrystalRus.h"

#include <stdio.h>
#include <string.h>
#include <inttypes.h>
#include <avr/pgmspace.h>
#include "WProgram.h"

// except 0401 --> 0xa2 = Ё, 0451 --> 0xb5 = ё
PROGMEM prog_uchar utf_recode[] =
{
    0x41,0xa0,0x42,0xa1,0xe0,0x45,0xa3,0xa4,0xa5,0xa6,0x4b,0xa7,0x4d,0x48,0x4f,
    0xa8,0x50,0x43,0x54,0xa9,0xaa,0x58,0xe1,0xab,0xac,0xe2,0xad,0xae,0x62,0xaf,0xb0,0xb1,
    0x61,0xb2,0xb3,0xb4,0xe3,0x65,0xb6,0xb7,0xb8,0xb9,0xba,0xbb,0xbc,0xbd,0x6f,
    0xbe,0x70,0x63,0xbf,0x79,0xe4,0x78,0xe5,0xc0,0xc1,0xe6,0xc2,0xc3,0xc4,0xc5,0xc6,0xc7
};

void LiquidCrystalRus::write(uint8_t value)
{
    uint8_t out_char = value;

    if (value >= 0x80) // UTF-8 handling
    {
        if (value >= 0xc0)
            utf_hi_char = value - 0xd0;
        else
        {
            value &= 0x3f;

            if (!utf_hi_char && value == 1)
                out_char = 0xa2; // Ё
            else if (utf_hi_char == 1 && value == 0x11)
                out_char = 0xb5; // ё
            else
                out_char = pgm_read_byte_near(utf_recode + value + (utf_hi_char << 6) - 0x10);

            LiquidCrystal::write(out_char);
        }
    }
    else
        LiquidCrystal::write(out_char);
}
<|endoftext|>


<commit_before>// Copyright 2015 Esri.

// 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 "ChangeViewpoint.h"
#include "Map.h"
#include "MapView.h"
#include <QVBoxLayout>
#include <QGraphicsProxyWidget>

using namespace Esri::ArcGISRuntime;

ChangeViewpoint::ChangeViewpoint(QWidget* parent) :
    QWidget(parent),
    m_map(nullptr),
    m_mapView(nullptr)
{
    // Create a map using an imagery basemap
    m_map = new Map(Basemap::imageryWithLabels(this), this);

    // Create a map view, and pass in the map
    m_mapView = new MapView(m_map, this);

    m_rotationValue = 0;

    // Create and populate a combo box with several viewpoint types
    m_viewpointCombo = new QComboBox(this);
    m_viewpointCombo->adjustSize();
    m_viewpointCombo->setStyleSheet("QComboBox#combo {color: black; background-color:#000000;}");
    m_viewpointCombo->addItems(QStringList() << "Center"
                               << "Center and scale"
                               << "Geometry"
                               << "Geometry and padding"
                               << "Rotation"
                               << "Scale: 1:5,000,000"
                               << "Scale: 1:10,000,000"
                               << "Animation");

    // Connect the combo box signal to slot for setting new viewpoint
    connect(m_viewpointCombo, SIGNAL(currentIndexChanged(int)),
            this, SLOT(changeToNewViewpoint(int)));

    // Set up the UI
    QWidget* widget = new QWidget();
    QVBoxLayout* layout = new QVBoxLayout();
    layout->setMargin(0);
    layout->addWidget(m_viewpointCombo);
    widget->setLayout(layout);

    QGraphicsProxyWidget *proxy = m_mapView->scene()->addWidget(widget);
    proxy->setPos(10, 10);
    proxy->setOpacity(0.95);

    QVBoxLayout *vBoxLayout = new QVBoxLayout();
    vBoxLayout->addWidget(m_mapView);
    setLayout(vBoxLayout);
}

void ChangeViewpoint::changeToNewViewpoint(int index)
{
    // Create the objects used to change viewpoint in various cases

    Point ptEsriHeadquarters(-117.195681, 34.056218, 0.0, 0.0, SpatialReference(4236));
    Point ptHawaii(-157.564, 20.677, SpatialReference(4236));
    Envelope envBeijing(116.380, 39.920, 116.400, 39.940, SpatialReference(4236));
    Viewpoint vpSpring(Envelope(-12338668.348591767, 5546908.424239618, -12338247.594362013, 5547223.989911933, SpatialReference(102100)));

    switch (index)
    {
    // Call setViewpoint and pass in the appropriate viewpoint
    case 0: // "Center"
        m_mapView->setViewpointCenter(ptEsriHeadquarters);
        break;
    case 1: // "Center and scale"
        m_mapView->setViewpointCenter(ptHawaii, 4000000.0);
        break;
    case 2: // "Geometry"
        m_mapView->setViewpointGeometry(envBeijing);
        break;
    case 3: // "Geometry and padding"
        m_mapView->setViewpointGeometry(envBeijing, 200);
        break;
    case 4: // "Rotation"
        m_rotationValue = (m_rotationValue + 45) % 360;
        m_mapView->setViewpointRotation(m_rotationValue);
        break;
    case 5: // "Scale: 1:5,000,000"
        m_mapView->setViewpointScale(5000000.0);
        break;
    case 6: // "Scale: 1:10,000,000"
        m_mapView->setViewpointScale(10000000.0);
        break;
    case 7: // "Scale: 1:5,000,000"
        m_mapView->setViewpointAnimated(vpSpring, 4.0, AnimationCurve::EaseInOutCubic);
        break;
    }
}

ChangeViewpoint::~ChangeViewpoint()
{
}
<commit_msg>Fix geometry usage. Just pass x and y.<commit_after>// Copyright 2015 Esri.

// 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 "ChangeViewpoint.h"
#include "Map.h"
#include "MapView.h"
#include <QVBoxLayout>
#include <QGraphicsProxyWidget>

using namespace Esri::ArcGISRuntime;

ChangeViewpoint::ChangeViewpoint(QWidget* parent) :
    QWidget(parent),
    m_map(nullptr),
    m_mapView(nullptr)
{
    // Create a map using an imagery basemap
    m_map = new Map(Basemap::imageryWithLabels(this), this);

    // Create a map view, and pass in the map
    m_mapView = new MapView(m_map, this);

    m_rotationValue = 0;

    // Create and populate a combo box with several viewpoint types
    m_viewpointCombo = new QComboBox(this);
    m_viewpointCombo->adjustSize();
    m_viewpointCombo->setStyleSheet("QComboBox#combo {color: black; background-color:#000000;}");
    m_viewpointCombo->addItems(QStringList() << "Center"
                               << "Center and scale"
                               << "Geometry"
                               << "Geometry and padding"
                               << "Rotation"
                               << "Scale: 1:5,000,000"
                               << "Scale: 1:10,000,000"
                               << "Animation");

    // Connect the combo box signal to slot for setting new viewpoint
    connect(m_viewpointCombo, SIGNAL(currentIndexChanged(int)),
            this, SLOT(changeToNewViewpoint(int)));

    // Set up the UI
    QWidget* widget = new QWidget();
    QVBoxLayout* layout = new QVBoxLayout();
    layout->setMargin(0);
    layout->addWidget(m_viewpointCombo);
    widget->setLayout(layout);

    QGraphicsProxyWidget *proxy = m_mapView->scene()->addWidget(widget);
    proxy->setPos(10, 10);
    proxy->setOpacity(0.95);

    QVBoxLayout *vBoxLayout = new QVBoxLayout();
    vBoxLayout->addWidget(m_mapView);
    setLayout(vBoxLayout);
}

void ChangeViewpoint::changeToNewViewpoint(int index)
{
    // Create the objects used to change viewpoint in various cases

    Point ptEsriHeadquarters(-117.195681, 34.056218, SpatialReference(4236));
    Point ptHawaii(-157.564, 20.677, SpatialReference(4236));
    Envelope envBeijing(116.380, 39.920, 116.400, 39.940, SpatialReference(4236));
    Viewpoint vpSpring(Envelope(-12338668.348591767, 5546908.424239618, -12338247.594362013, 5547223.989911933, SpatialReference(102100)));

    switch (index)
    {
    // Call setViewpoint and pass in the appropriate viewpoint
    case 0: // "Center"
        m_mapView->setViewpointCenter(ptEsriHeadquarters);
        break;
    case 1: // "Center and scale"
        m_mapView->setViewpointCenter(ptHawaii, 4000000.0);
        break;
    case 2: // "Geometry"
        m_mapView->setViewpointGeometry(envBeijing);
        break;
    case 3: // "Geometry and padding"
        m_mapView->setViewpointGeometry(envBeijing, 200);
        break;
    case 4: // "Rotation"
        m_rotationValue = (m_rotationValue + 45) % 360;
        m_mapView->setViewpointRotation(m_rotationValue);
        break;
    case 5: // "Scale: 1:5,000,000"
        m_mapView->setViewpointScale(5000000.0);
        break;
    case 6: // "Scale: 1:10,000,000"
        m_mapView->setViewpointScale(10000000.0);
        break;
    case 7: // "Scale: 1:5,000,000"
        m_mapView->setViewpointAnimated(vpSpring, 4.0, AnimationCurve::EaseInOutCubic);
        break;
    }
}

ChangeViewpoint::~ChangeViewpoint()
{
}
<|endoftext|>


<commit_before>/*
 * The Apache Software License, Version 1.1
 *
 *
 * Copyright (c) 1999 The Apache Software Foundation.  All rights
 * reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 *
 * 1. Redistributions of source code must retain the above copyright
 *    notice, this list of conditions and the following disclaimer.
 *
 * 2. Redistributions in binary form must reproduce the above copyright
 *    notice, this list of conditions and the following disclaimer in
 *    the documentation and/or other materials provided with the
 *    distribution.
 *
 * 3. The end-user documentation included with the redistribution,
 *    if any, must include the following acknowledgment:
 *       "This product includes software developed by the
 *        Apache Software Foundation (http://www.apache.org/)."
 *    Alternately, this acknowledgment may appear in the software itself,
 *    if and wherever such third-party acknowledgments normally appear.
 *
 * 4. The names "Xalan" and "Apache Software Foundation" must
 *    not be used to endorse or promote products derived from this
 *    software without prior written permission. For written
 *    permission, please contact apache@apache.org.
 *
 * 5. Products derived from this software may not be called "Apache",
 *    nor may "Apache" appear in their name, without prior written
 *    permission of the Apache Software Foundation.
 *
 * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED
 * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
 * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
 * DISCLAIMED.  IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR
 * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
 * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
 * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
 * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
 * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
 * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
 * SUCH DAMAGE.
 * ====================================================================
 *
 * This software consists of voluntary contributions made by many
 * individuals on behalf of the Apache Software Foundation and was
 * originally based on software copyright (c) 1999, International
 * Business Machines, Inc., http://www.ibm.com.  For more
 * information on the Apache Software Foundation, please see
 * <http://www.apache.org/>.
 */
#include "ElemLiteralResult.hpp"

#include <algorithm>

#include <sax/AttributeList.hpp>
#include <sax/SAXException.hpp>

#include <Include/STLHelper.hpp>

#include <PlatformSupport/DoubleSupport.hpp>
#include <PlatformSupport/StringTokenizer.hpp>

#include <DOMSupport/DOMServices.hpp>

#include "AVT.hpp"
#include "Constants.hpp"
#include "Stylesheet.hpp"
#include "StylesheetConstructionContext.hpp"
#include "StylesheetExecutionContext.hpp"

ElemLiteralResult::ElemLiteralResult(
			StylesheetConstructionContext&	constructionContext,
			Stylesheet&						stylesheetTree,
			const XalanDOMChar*				name,
			const AttributeList&			atts,
			int								lineNumber,
			int								columnNumber,
			int								xslToken) :
	ElemUse(constructionContext,
			stylesheetTree,
			lineNumber,
			columnNumber,
			xslToken),
	m_elementName(name),
	m_avts()
{
	const unsigned int	nAttrs = atts.getLength();

	m_avts.reserve(nAttrs);

	for(unsigned int i = 0; i < nAttrs; i++)
	{
		const XalanDOMChar*	const	aname = atts.getName(i);

		bool						needToProcess = true;
		const unsigned int			indexOfNSSep = indexOf(aname, XalanUnicode::charColon);

		XalanDOMString				prefix;

		if(indexOfNSSep < length(aname))
		{
			prefix = substring(aname, 0, indexOfNSSep);

			if(!equals(prefix, DOMServices::s_XMLNamespace))
			{
				const XalanDOMString* const		ns =
						getNamespaceForPrefixInternal(prefix, true);

				if(ns != 0 && equals(*ns, stylesheetTree.getXSLTNamespaceURI()))
				{
					const XalanDOMString localName = substring(aname, indexOfNSSep + 1);

					if(processPrefixControl(constructionContext, stylesheetTree, localName, atts.getValue(i)) == true)
					{
						needToProcess = false;
					}
					else if (equals(localName, Constants::ATTRNAME_VERSION) == true)
					{
						const XalanDOMChar*	const	value = atts.getValue(i);

						stylesheetTree.setXSLTVerDeclared(DoubleSupport::toDouble(value));
					}
				}
			}
			else
			{
				// don't process namespace decls
				needToProcess = false;
			}
		}

		if(needToProcess == true)
		{
			processSpaceAttr(aname, atts, i);

			// Add xmlns attribute(except xmlns:xsl), xml:space, etc...
			// Ignore anything with xsl:xxx
			if(! processUseAttributeSets(constructionContext, aname, atts, i) &&
					isAttrOK(aname, atts, i, constructionContext))
			{
				m_avts.push_back(new AVT(aname, atts.getType(i), atts.getValue(i),
							*this, constructionContext));
			}
		}
	}

	// Shrink the vector of AVTS, if necessary...
	if (m_avts.capacity() > m_avts.size())
	{
		// Make a copy that's the exact size, and
		// swap the two...
		AVTVectorType(m_avts).swap(m_avts);
	}
}

ElemLiteralResult::~ElemLiteralResult()
{
#if !defined(XALAN_NO_NAMESPACES)
	using std::for_each;
#endif

	// Clean up all entries in the vector.
	for_each(m_avts.begin(),
			 m_avts.end(),
			 DeleteFunctor<AVT>());
}

const XalanDOMString&
ElemLiteralResult::getElementName() const
{
	return m_elementName;
}

void
ElemLiteralResult::postConstruction(
			StylesheetConstructionContext&	constructionContext,
			const NamespacesHandler&		theParentHandler)
{
	// OK, now check all attribute AVTs to make sure
	// our NamespacesHandler knows about any prefixes
	// that will need namespace declarations...
	const AVTVectorType::size_type	nAttrs = m_avts.size();

	for(AVTVectorType::size_type i = 0; i < nAttrs; ++i)
	{
		const AVT* const	avt = m_avts[i];

		const XalanDOMString&	theName = avt->getName();

		const unsigned int	theColonIndex = indexOf(theName, XalanUnicode::charColon);

		if (theColonIndex != length(theName))
		{
			m_namespacesHandler.addActivePrefix(substring(theName, 0, theColonIndex));
		}
	}

	// OK, now we can chain-up...
	ElemUse::postConstruction(constructionContext, theParentHandler);
}

inline void
ElemLiteralResult::doAddResultAttribute(
			StylesheetExecutionContext&		executionContext,
			const XalanDOMString&			thePrefix,
			const XalanDOMString&			theName,
			const XalanDOMString&			theValue) const
{
	if (isEmpty(thePrefix) == true ||
	    shouldExcludeResultNamespaceNode(
			thePrefix,
			theValue) == false)
	{
		executionContext.addResultAttribute(
				theName,
				theValue);
	}
}

void
ElemLiteralResult::execute(StylesheetExecutionContext&		executionContext) const
{
	executionContext.startElement(c_wstr(getElementName()));

	ElemUse::execute(executionContext);

	m_namespacesHandler.outputResultNamespaces(executionContext);

	// OK, now let's check to make sure we don't have to change the default namespace...
	const XalanDOMString* const		theCurrentDefaultNamespace =
				executionContext.getResultNamespaceForPrefix(s_emptyString);

	if (theCurrentDefaultNamespace != 0)
	{
		const XalanDOMString* const		theElementDefaultNamespace =
					m_namespacesHandler.getNamespace(s_emptyString);

		if (theElementDefaultNamespace == 0)
		{
			// There was no default namespace, so we have to turn the
			// current one off.
			executionContext.addResultAttribute(DOMServices::s_XMLNamespace, s_emptyString);
		}
		else if (equals(*theCurrentDefaultNamespace, *theElementDefaultNamespace) == false)
		{
			executionContext.addResultAttribute(DOMServices::s_XMLNamespace, *theElementDefaultNamespace);
		}
	}

	if(0 != m_avts.size())
	{
		const AVTVectorType::size_type	nAttrs = m_avts.size();

		StylesheetExecutionContext::GetAndReleaseCachedString	theGuard(executionContext);

		XalanDOMString&		theStringedValue = theGuard.get();

		for(AVTVectorType::size_type i = 0; i < nAttrs; ++i)
		{
			const AVT* const	avt = m_avts[i];

			const XalanDOMString&	theName = avt->getName();

			const XalanDOMString&	thePrefix = avt->getPrefix();

			const XalanDOMString&	theSimpleValue = avt->getSimpleValue();

			if (isEmpty(theSimpleValue) == false)
			{
				doAddResultAttribute(executionContext, thePrefix, theName, theSimpleValue);
			}
			else
			{
				avt->evaluate(theStringedValue, executionContext.getCurrentNode(), *this, executionContext);

				doAddResultAttribute(executionContext, thePrefix, theName, theStringedValue);
			}
		}
	}

	executeChildren(executionContext);

	executionContext.endElement(c_wstr(getElementName()));
}

bool
ElemLiteralResult::isAttrOK(
			int						tok,
			const XalanDOMChar*		attrName,
			const AttributeList&	atts,
			int						which) const
{
	return ElemUse::isAttrOK(tok, attrName, atts, which);
}

bool
ElemLiteralResult::isAttrOK(
			const XalanDOMChar*				attrName,
			const AttributeList&			/* atts */,
			int								/* which */,
			StylesheetConstructionContext&	constructionContext) const
{
    bool	isAttrOK = equals(attrName, DOMServices::s_XMLNamespace) ||
					   startsWith(attrName, DOMServices::s_XMLNamespaceWithSeparator);

    if(isAttrOK == false)
    {
		const unsigned int	indexOfNSSep = indexOf(attrName, XalanUnicode::charColon);

		if(indexOfNSSep < length(attrName))
		{
			const XalanDOMString	prefix = substring(attrName, 0, indexOfNSSep);

			const XalanDOMString* const		ns = getStylesheet().getNamespaceForPrefixFromStack(prefix);

			if (ns != 0 && equals(*ns, constructionContext.getXSLTNamespaceURI()) == false)
			{
				isAttrOK = true;
			}
		}
		else
		{
			// An empty namespace is OK.
			isAttrOK = true;
		}
    }

    // TODO: Well, process it...
    return isAttrOK;
}

bool
ElemLiteralResult::processPrefixControl(
			StylesheetConstructionContext&	constructionContext,
			const Stylesheet&				stylesheetTree,
			const XalanDOMString&			localName,
			const XalanDOMChar*				attrValue)
{
	if(equals(localName, Constants::ATTRNAME_EXTENSIONELEMENTPREFIXES))
	{
		m_namespacesHandler.processExtensionElementPrefixes(attrValue, stylesheetTree.getNamespaces(), constructionContext);

		return true;
	}
	else if (equals(localName, Constants::ATTRNAME_EXCLUDE_RESULT_PREFIXES))
	{
		m_namespacesHandler.processExcludeResultPrefixes(attrValue, stylesheetTree.getNamespaces(), constructionContext);

		return true;
	}
	else
	{
		return false;
	}
}

bool
ElemLiteralResult::shouldExcludeResultNamespaceNode(
			const XalanDOMString&	thePrefix,
			const XalanDOMString&	theURI) const
{
	return m_namespacesHandler.shouldExcludeResultNamespaceNode(
				getStylesheet().getXSLTNamespaceURI(),
				thePrefix,
				theURI);
}
<commit_msg>Removed unneeded include.<commit_after>/*
 * The Apache Software License, Version 1.1
 *
 *
 * Copyright (c) 1999 The Apache Software Foundation.  All rights
 * reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 *
 * 1. Redistributions of source code must retain the above copyright
 *    notice, this list of conditions and the following disclaimer.
 *
 * 2. Redistributions in binary form must reproduce the above copyright
 *    notice, this list of conditions and the following disclaimer in
 *    the documentation and/or other materials provided with the
 *    distribution.
 *
 * 3. The end-user documentation included with the redistribution,
 *    if any, must include the following acknowledgment:
 *       "This product includes software developed by the
 *        Apache Software Foundation (http://www.apache.org/)."
 *    Alternately, this acknowledgment may appear in the software itself,
 *    if and wherever such third-party acknowledgments normally appear.
 *
 * 4. The names "Xalan" and "Apache Software Foundation" must
 *    not be used to endorse or promote products derived from this
 *    software without prior written permission. For written
 *    permission, please contact apache@apache.org.
 *
 * 5. Products derived from this software may not be called "Apache",
 *    nor may "Apache" appear in their name, without prior written
 *    permission of the Apache Software Foundation.
 *
 * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED
 * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
 * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
 * DISCLAIMED.  IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR
 * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
 * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
 * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
 * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
 * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
 * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
 * SUCH DAMAGE.
 * ====================================================================
 *
 * This software consists of voluntary contributions made by many
 * individuals on behalf of the Apache Software Foundation and was
 * originally based on software copyright (c) 1999, International
 * Business Machines, Inc., http://www.ibm.com.  For more
 * information on the Apache Software Foundation, please see
 * <http://www.apache.org/>.
 */
#include "ElemLiteralResult.hpp"

#include <algorithm>

#include <sax/AttributeList.hpp>
#include <sax/SAXException.hpp>

#include <Include/STLHelper.hpp>

#include <PlatformSupport/DoubleSupport.hpp>

#include <DOMSupport/DOMServices.hpp>

#include "AVT.hpp"
#include "Constants.hpp"
#include "Stylesheet.hpp"
#include "StylesheetConstructionContext.hpp"
#include "StylesheetExecutionContext.hpp"

ElemLiteralResult::ElemLiteralResult(
			StylesheetConstructionContext&	constructionContext,
			Stylesheet&						stylesheetTree,
			const XalanDOMChar*				name,
			const AttributeList&			atts,
			int								lineNumber,
			int								columnNumber,
			int								xslToken) :
	ElemUse(constructionContext,
			stylesheetTree,
			lineNumber,
			columnNumber,
			xslToken),
	m_elementName(name),
	m_avts()
{
	const unsigned int	nAttrs = atts.getLength();

	m_avts.reserve(nAttrs);

	for(unsigned int i = 0; i < nAttrs; i++)
	{
		const XalanDOMChar*	const	aname = atts.getName(i);

		bool						needToProcess = true;
		const unsigned int			indexOfNSSep = indexOf(aname, XalanUnicode::charColon);

		XalanDOMString				prefix;

		if(indexOfNSSep < length(aname))
		{
			prefix = substring(aname, 0, indexOfNSSep);

			if(!equals(prefix, DOMServices::s_XMLNamespace))
			{
				const XalanDOMString* const		ns =
						getNamespaceForPrefixInternal(prefix, true);

				if(ns != 0 && equals(*ns, stylesheetTree.getXSLTNamespaceURI()))
				{
					const XalanDOMString localName = substring(aname, indexOfNSSep + 1);

					if(processPrefixControl(constructionContext, stylesheetTree, localName, atts.getValue(i)) == true)
					{
						needToProcess = false;
					}
					else if (equals(localName, Constants::ATTRNAME_VERSION) == true)
					{
						const XalanDOMChar*	const	value = atts.getValue(i);

						stylesheetTree.setXSLTVerDeclared(DoubleSupport::toDouble(value));
					}
				}
			}
			else
			{
				// don't process namespace decls
				needToProcess = false;
			}
		}

		if(needToProcess == true)
		{
			processSpaceAttr(aname, atts, i);

			// Add xmlns attribute(except xmlns:xsl), xml:space, etc...
			// Ignore anything with xsl:xxx
			if(! processUseAttributeSets(constructionContext, aname, atts, i) &&
					isAttrOK(aname, atts, i, constructionContext))
			{
				m_avts.push_back(new AVT(aname, atts.getType(i), atts.getValue(i),
							*this, constructionContext));
			}
		}
	}

	// Shrink the vector of AVTS, if necessary...
	if (m_avts.capacity() > m_avts.size())
	{
		// Make a copy that's the exact size, and
		// swap the two...
		AVTVectorType(m_avts).swap(m_avts);
	}
}

ElemLiteralResult::~ElemLiteralResult()
{
#if !defined(XALAN_NO_NAMESPACES)
	using std::for_each;
#endif

	// Clean up all entries in the vector.
	for_each(m_avts.begin(),
			 m_avts.end(),
			 DeleteFunctor<AVT>());
}

const XalanDOMString&
ElemLiteralResult::getElementName() const
{
	return m_elementName;
}

void
ElemLiteralResult::postConstruction(
			StylesheetConstructionContext&	constructionContext,
			const NamespacesHandler&		theParentHandler)
{
	// OK, now check all attribute AVTs to make sure
	// our NamespacesHandler knows about any prefixes
	// that will need namespace declarations...
	const AVTVectorType::size_type	nAttrs = m_avts.size();

	for(AVTVectorType::size_type i = 0; i < nAttrs; ++i)
	{
		const AVT* const	avt = m_avts[i];

		const XalanDOMString&	theName = avt->getName();

		const unsigned int	theColonIndex = indexOf(theName, XalanUnicode::charColon);

		if (theColonIndex != length(theName))
		{
			m_namespacesHandler.addActivePrefix(substring(theName, 0, theColonIndex));
		}
	}

	// OK, now we can chain-up...
	ElemUse::postConstruction(constructionContext, theParentHandler);
}

inline void
ElemLiteralResult::doAddResultAttribute(
			StylesheetExecutionContext&		executionContext,
			const XalanDOMString&			thePrefix,
			const XalanDOMString&			theName,
			const XalanDOMString&			theValue) const
{
	if (isEmpty(thePrefix) == true ||
	    shouldExcludeResultNamespaceNode(
			thePrefix,
			theValue) == false)
	{
		executionContext.addResultAttribute(
				theName,
				theValue);
	}
}

void
ElemLiteralResult::execute(StylesheetExecutionContext&		executionContext) const
{
	executionContext.startElement(c_wstr(getElementName()));

	ElemUse::execute(executionContext);

	m_namespacesHandler.outputResultNamespaces(executionContext);

	// OK, now let's check to make sure we don't have to change the default namespace...
	const XalanDOMString* const		theCurrentDefaultNamespace =
				executionContext.getResultNamespaceForPrefix(s_emptyString);

	if (theCurrentDefaultNamespace != 0)
	{
		const XalanDOMString* const		theElementDefaultNamespace =
					m_namespacesHandler.getNamespace(s_emptyString);

		if (theElementDefaultNamespace == 0)
		{
			// There was no default namespace, so we have to turn the
			// current one off.
			executionContext.addResultAttribute(DOMServices::s_XMLNamespace, s_emptyString);
		}
		else if (equals(*theCurrentDefaultNamespace, *theElementDefaultNamespace) == false)
		{
			executionContext.addResultAttribute(DOMServices::s_XMLNamespace, *theElementDefaultNamespace);
		}
	}

	if(0 != m_avts.size())
	{
		const AVTVectorType::size_type	nAttrs = m_avts.size();

		StylesheetExecutionContext::GetAndReleaseCachedString	theGuard(executionContext);

		XalanDOMString&		theStringedValue = theGuard.get();

		for(AVTVectorType::size_type i = 0; i < nAttrs; ++i)
		{
			const AVT* const	avt = m_avts[i];

			const XalanDOMString&	theName = avt->getName();

			const XalanDOMString&	thePrefix = avt->getPrefix();

			const XalanDOMString&	theSimpleValue = avt->getSimpleValue();

			if (isEmpty(theSimpleValue) == false)
			{
				doAddResultAttribute(executionContext, thePrefix, theName, theSimpleValue);
			}
			else
			{
				avt->evaluate(theStringedValue, executionContext.getCurrentNode(), *this, executionContext);

				doAddResultAttribute(executionContext, thePrefix, theName, theStringedValue);
			}
		}
	}

	executeChildren(executionContext);

	executionContext.endElement(c_wstr(getElementName()));
}

bool
ElemLiteralResult::isAttrOK(
			int						tok,
			const XalanDOMChar*		attrName,
			const AttributeList&	atts,
			int						which) const
{
	return ElemUse::isAttrOK(tok, attrName, atts, which);
}

bool
ElemLiteralResult::isAttrOK(
			const XalanDOMChar*				attrName,
			const AttributeList&			/* atts */,
			int								/* which */,
			StylesheetConstructionContext&	constructionContext) const
{
    bool	isAttrOK = equals(attrName, DOMServices::s_XMLNamespace) ||
					   startsWith(attrName, DOMServices::s_XMLNamespaceWithSeparator);

    if(isAttrOK == false)
    {
		const unsigned int	indexOfNSSep = indexOf(attrName, XalanUnicode::charColon);

		if(indexOfNSSep < length(attrName))
		{
			const XalanDOMString	prefix = substring(attrName, 0, indexOfNSSep);

			const XalanDOMString* const		ns = getStylesheet().getNamespaceForPrefixFromStack(prefix);

			if (ns != 0 && equals(*ns, constructionContext.getXSLTNamespaceURI()) == false)
			{
				isAttrOK = true;
			}
		}
		else
		{
			// An empty namespace is OK.
			isAttrOK = true;
		}
    }

    // TODO: Well, process it...
    return isAttrOK;
}

bool
ElemLiteralResult::processPrefixControl(
			StylesheetConstructionContext&	constructionContext,
			const Stylesheet&				stylesheetTree,
			const XalanDOMString&			localName,
			const XalanDOMChar*				attrValue)
{
	if(equals(localName, Constants::ATTRNAME_EXTENSIONELEMENTPREFIXES))
	{
		m_namespacesHandler.processExtensionElementPrefixes(attrValue, stylesheetTree.getNamespaces(), constructionContext);

		return true;
	}
	else if (equals(localName, Constants::ATTRNAME_EXCLUDE_RESULT_PREFIXES))
	{
		m_namespacesHandler.processExcludeResultPrefixes(attrValue, stylesheetTree.getNamespaces(), constructionContext);

		return true;
	}
	else
	{
		return false;
	}
}

bool
ElemLiteralResult::shouldExcludeResultNamespaceNode(
			const XalanDOMString&	thePrefix,
			const XalanDOMString&	theURI) const
{
	return m_namespacesHandler.shouldExcludeResultNamespaceNode(
				getStylesheet().getXSLTNamespaceURI(),
				thePrefix,
				theURI);
}
<|endoftext|>