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

#include "sdpage.hxx"
#include "drawdoc.hxx"
#include "sdresid.hxx"
#include "glob.hrc"
#include "app.hrc"
#include "new_foil.hrc"
#include "strings.hrc"
#include "strings.hrc"
#include "helpids.h"
#include "sdattr.hxx"
#include "sdabstdlg.hxx"
#include "unmodpg.hxx"
#include "Window.hxx"
#include "optsitem.hxx"
#include "DrawDocShell.hxx"
#include "FactoryIds.hxx"
#include "slideshow.hxx"
#include "TaskPaneViewShell.hxx"
#include "ViewShellBase.hxx"

#include <sfx2/bindings.hxx>
#include <sfx2/dispatch.hxx>
#include <sfx2/request.hxx>
#include <svtools/aeitem.hxx>
#include <vcl/msgbox.hxx>
#include <basic/sbstar.hxx>

namespace {
class ImpUndoDeleteWarning : public ModalDialog
{
private:
    FixedImage      maImage;
    FixedText       maWarningFT;
    CheckBox        maDisableCB;
    OKButton        maYesBtn;
    CancelButton    maNoBtn;

public:
    ImpUndoDeleteWarning(Window* pParent);
    BOOL IsWarningDisabled() const { return maDisableCB.IsChecked(); }
};

ImpUndoDeleteWarning::ImpUndoDeleteWarning(Window* pParent)
:   ModalDialog(pParent, SdResId(RID_UNDO_DELETE_WARNING)),
    maImage(this, SdResId(IMG_UNDO_DELETE_WARNING)),
    maWarningFT(this, SdResId(FT_UNDO_DELETE_WARNING)),
    maDisableCB(this, SdResId(CB_UNDO_DELETE_DISABLE)),
    maYesBtn(this, SdResId(BTN_UNDO_DELETE_YES)),
    maNoBtn(this, SdResId(BTN_UNDO_DELETE_NO))
{
    FreeResource();

    SetHelpId( HID_SD_UNDODELETEWARNING_DLG );
    maDisableCB.SetHelpId( HID_SD_UNDODELETEWARNING_CBX );

    maYesBtn.SetText(Button::GetStandardText(BUTTON_YES));
    maNoBtn.SetText(Button::GetStandardText(BUTTON_NO));
    maImage.SetImage(WarningBox::GetStandardImage());

    // #93721# Set focus to YES-Button
    maYesBtn.GrabFocus();
}

} // end of anonymous namespace

namespace sd {

ViewShell::Implementation::Implementation (ViewShell& rViewShell)
    : mbIsShowingUIControls(false),
      mbIsMainViewShell(false),
      mrViewShell (rViewShell),
      mbIsInitialized(false)
{
}

ViewShell::Implementation::~Implementation (void)
{
}

void ViewShell::Implementation::ProcessModifyPageSlot (
    SfxRequest& rRequest,
    SdPage* pCurrentPage,
    PageKind ePageKind)
{
    SdDrawDocument* pDocument = mrViewShell.GetDoc();
    SdrLayerAdmin& rLayerAdmin = pDocument->GetLayerAdmin();
    BYTE aBckgrnd = rLayerAdmin.GetLayerID(String(SdResId(STR_LAYER_BCKGRND)), FALSE);
    BYTE aBckgrndObj = rLayerAdmin.GetLayerID(String(SdResId(STR_LAYER_BCKGRNDOBJ)), FALSE);
    SetOfByte aVisibleLayers;
    BOOL bHandoutMode = FALSE;
    SdPage* pHandoutMPage = NULL;
    String aNewName;

    // #95981#
    String aOldName;

    AutoLayout aNewAutoLayout;

    // #95981#
    AutoLayout aOldAutoLayout;

    BOOL bBVisible;
    BOOL bBObjsVisible;
    const SfxItemSet* pArgs = rRequest.GetArgs();

    if (pCurrentPage->TRG_HasMasterPage())
        aVisibleLayers = pCurrentPage->TRG_GetMasterPageVisibleLayers();
    else
        aVisibleLayers.SetAll();

    do
    {
        if (!pArgs || pArgs->Count() == 1 || pArgs->Count() == 2 )
        {
            if (pArgs && pArgs->Count() == 2)
            {
                // We have been called with a request that contains two
                // arguments.  One was used as preselected layout in a
                // dialog.  We could select that layout in the
                // layout panel instead.
                /*
                    SFX_REQUEST_ARG (rRequest, pNewAutoLayout, SfxUInt32Item, ID_VAL_WHATLAYOUT, FALSE);
                    eNewAutoLayout = (AutoLayout) pNewAutoLayout->GetValue
                    ();
                */
            }

            // Make the layout menu visible in the tool pane.
            SfxBoolItem aMakeToolPaneVisible (ID_VAL_ISVISIBLE, TRUE);
            SfxUInt32Item aPanelId (ID_VAL_PANEL_INDEX,
                ::sd::toolpanel::TaskPaneViewShell::PID_LAYOUT);
            mrViewShell.GetDispatcher()->Execute (
                SID_TASK_PANE,
                SFX_CALLMODE_ASYNCHRON | SFX_CALLMODE_RECORD,
                &aMakeToolPaneVisible,
                &aPanelId,
                NULL);

            // We have activated a non-modal control in the task pane.
            // Because it does not return anything we can not do anything
            // more right now and have to exit here.
            break;
        }
        else if (pArgs->Count() == 4)
        {
            SFX_REQUEST_ARG (rRequest, pNewName, SfxStringItem, ID_VAL_PAGENAME, FALSE);
            SFX_REQUEST_ARG (rRequest, pNewAutoLayout, SfxUInt32Item, ID_VAL_WHATLAYOUT, FALSE);
            SFX_REQUEST_ARG (rRequest, pBVisible, SfxBoolItem, ID_VAL_ISPAGEBACK, FALSE);
            SFX_REQUEST_ARG (rRequest, pBObjsVisible, SfxBoolItem, ID_VAL_ISPAGEOBJ, FALSE);
            AutoLayout aLayout ((AutoLayout)pNewAutoLayout->GetValue ());
            if (aLayout >= AUTOLAYOUT__START
                && aLayout < AUTOLAYOUT__END)
            {
                aNewName        = pNewName->GetValue ();
                aNewAutoLayout = (AutoLayout) pNewAutoLayout->GetValue ();
                bBVisible       = pBVisible->GetValue ();
                bBObjsVisible   = pBObjsVisible->GetValue ();
            }
            else
            {
                StarBASIC::FatalError (SbERR_BAD_PROP_VALUE);
                rRequest.Ignore ();
                break;
            }
            if (ePageKind == PK_HANDOUT)
            {
                bHandoutMode = TRUE;
                pHandoutMPage = pDocument->GetMasterSdPage(0, PK_HANDOUT);
            }
        }
        else
        {
            StarBASIC::FatalError (SbERR_WRONG_ARGS);
            rRequest.Ignore ();
            break;
        }

        SdPage* pUndoPage =
            bHandoutMode ? pHandoutMPage : pCurrentPage;

        // #67720#
        SfxUndoManager* pUndoManager = mrViewShell.GetDocSh()->GetUndoManager();
        DBG_ASSERT(pUndoManager, "No UNDO MANAGER ?!?");

        // #90356#
        sal_uInt16 nActionCount(pUndoManager->GetUndoActionCount());
        sal_Bool bContinue(sal_True);

        if(nActionCount)
        {
            // #90356# get SdOptions
            SdOptions* pOptions = SD_MOD()->GetSdOptions(pDocument->GetDocumentType());
            //            sal_Bool bShowDialog(pOptions->IsShowUndoDeleteWarning());
            sal_Bool bShowDialog(sal_False);

            // #95981# If only name is changed do not show
            // ImpUndoDeleteWarning dialog
            if(bShowDialog)
            {
                sal_Bool bNameChanged(aNewName != aOldName);
                sal_Bool bLayoutChanged(aNewAutoLayout != aOldAutoLayout);

                if(bNameChanged && !bLayoutChanged)
                    bShowDialog = sal_False;
            }

            if(bShowDialog)
            {
                // ask user if he wants to loose UNDO stack
                ImpUndoDeleteWarning aUndoDeleteDlg(mrViewShell.GetActiveWindow());

                if(BUTTONID_OK == aUndoDeleteDlg.Execute())
                {
                    pUndoManager->Clear();
                }
                else
                {
                    bContinue = sal_False;
                }

                // #90356# write option flag back if change was done
                if(aUndoDeleteDlg.IsWarningDisabled())
                {
                    pOptions->SetShowUndoDeleteWarning(FALSE);
                }
            }
        }

        if(bContinue)
        {
            ModifyPageUndoAction* pAction = new ModifyPageUndoAction(
                pUndoManager, pDocument, pUndoPage, aNewName, aNewAutoLayout, bBVisible, bBObjsVisible);
            pUndoManager->AddUndoAction(pAction);

            // Clear the selection because the selectec object may be removed as
            // a result of the ssignment of the layout.
            mrViewShell.GetDrawView()->UnmarkAll();

            if (!bHandoutMode)
            {
                if (pCurrentPage->GetName() != aNewName)
                {
                    pCurrentPage->SetName(aNewName);

                    if (ePageKind == PK_STANDARD)
                    {
                        USHORT nPage = (pCurrentPage->GetPageNum()-1) / 2;
                        SdPage* pNotesPage = pDocument->GetSdPage(nPage, PK_NOTES);
                        if (pNotesPage != NULL)
                            pNotesPage->SetName(aNewName);
                    }
                }

                pCurrentPage->SetAutoLayout(aNewAutoLayout, TRUE);

                aBckgrnd = rLayerAdmin.GetLayerID(String(SdResId(STR_LAYER_BCKGRND)), FALSE);
                aBckgrndObj = rLayerAdmin.GetLayerID(String(SdResId(STR_LAYER_BCKGRNDOBJ)), FALSE);
                aVisibleLayers.Set(aBckgrnd, bBVisible);
                aVisibleLayers.Set(aBckgrndObj, bBObjsVisible);
                pCurrentPage->TRG_SetMasterPageVisibleLayers(aVisibleLayers);
            }
            else
            {
                pHandoutMPage->SetAutoLayout(aNewAutoLayout, TRUE);
            }
            // The list of presentation objects at the page
            // has been cleared by SetAutolayout().  We still
            // have to clear the list of removed presentation
            // objects held by the model which references the
            // former list.
            pDocument->ClearDeletedPresObjList();

            mrViewShell.GetViewFrame()->GetDispatcher()->Execute(SID_SWITCHPAGE,
                SFX_CALLMODE_ASYNCHRON | SFX_CALLMODE_RECORD);

            BOOL bSetModified = TRUE;

            if (pArgs && pArgs->Count() == 1)
            {
                bSetModified = (BOOL) ((SfxBoolItem&) pArgs->Get(SID_MODIFYPAGE)).GetValue();
            }

            pDocument->SetChanged(bSetModified);
        }
    }
    while (false);

    mrViewShell.Cancel();
    rRequest.Done ();
}

void ViewShell::Implementation::AssignLayout (
    SdPage* pPage,
    AutoLayout aLayout)
{
    // Transform the given request into the four argument form that is
    // understood by ProcessModifyPageSlot().
    SdrLayerAdmin& rLayerAdmin (mrViewShell.GetViewShellBase().GetDocument()->GetLayerAdmin());
    BYTE aBackground (rLayerAdmin.GetLayerID(String(SdResId(STR_LAYER_BCKGRND)), FALSE));
    BYTE aBackgroundObject (rLayerAdmin.GetLayerID(String(SdResId(STR_LAYER_BCKGRNDOBJ)), FALSE));
    SetOfByte aVisibleLayers (pPage->TRG_GetMasterPageVisibleLayers());
    SfxRequest aRequest (mrViewShell.GetViewShellBase().GetViewFrame(), SID_MODIFYPAGE);
    aRequest.AppendItem(SfxStringItem (ID_VAL_PAGENAME, pPage->GetName()));
    aRequest.AppendItem(SfxUInt32Item (ID_VAL_WHATLAYOUT, aLayout));
    aRequest.AppendItem(SfxBoolItem(ID_VAL_ISPAGEBACK, aVisibleLayers.IsSet(aBackground)));
    aRequest.AppendItem(SfxBoolItem(ID_VAL_ISPAGEOBJ, aVisibleLayers.IsSet(aBackgroundObject)));

    // Forward the call with the new arguments.
    ProcessModifyPageSlot (
        aRequest,
        pPage,
        pPage->GetPageKind());
}

sal_uInt16 ViewShell::Implementation::GetViewId (void)
{
    switch (mrViewShell.GetShellType())
    {
        case ViewShell::ST_IMPRESS:
        case ViewShell::ST_NOTES:
        case ViewShell::ST_HANDOUT:
            return IMPRESS_FACTORY_ID;

        case ViewShell::ST_DRAW:
            return DRAW_FACTORY_ID;

        case ViewShell::ST_OUTLINE:
            return OUTLINE_FACTORY_ID;

        case ViewShell::ST_SLIDE:
        case ViewShell::ST_SLIDE_SORTER:
            return SLIDE_SORTER_FACTORY_ID;

        case ViewShell::ST_PRESENTATION:
            return PRESENTATION_FACTORY_ID;

        // Since we have to return a view id for every possible shell type
        // and there is not (yet) a proper ViewShellBase sub class for the
        // remaining types we chose the Impress factory as a fall back.
        case ViewShell::ST_TASK_PANE:
        case ViewShell::ST_NONE:
        default:
            return IMPRESS_FACTORY_ID;
    }
}

} // end of namespace sd
<commit_msg>INTEGRATION: CWS ooo19126 (1.14.154); FILE MERGED 2005/09/05 13:25:31 rt 1.14.154.1: #i54170# Change license header: remove SISSL<commit_after>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: ViewShellImplementation.cxx,v $
 *
 *  $Revision: 1.15 $
 *
 *  last change: $Author: rt $ $Date: 2005-09-09 07:04:10 $
 *
 *  The Contents of this file are made available subject to
 *  the terms of GNU Lesser General Public License Version 2.1.
 *
 *
 *    GNU Lesser General Public License Version 2.1
 *    =============================================
 *    Copyright 2005 by Sun Microsystems, Inc.
 *    901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *    This library is free software; you can redistribute it and/or
 *    modify it under the terms of the GNU Lesser General Public
 *    License version 2.1, as published by the Free Software Foundation.
 *
 *    This library is distributed in the hope that it will be useful,
 *    but WITHOUT ANY WARRANTY; without even the implied warranty of
 *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *    Lesser General Public License for more details.
 *
 *    You should have received a copy of the GNU Lesser General Public
 *    License along with this library; if not, write to the Free Software
 *    Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *    MA  02111-1307  USA
 *
 ************************************************************************/
#include "ViewShellImplementation.hxx"

#include "sdpage.hxx"
#include "drawdoc.hxx"
#include "sdresid.hxx"
#include "glob.hrc"
#include "app.hrc"
#include "new_foil.hrc"
#include "strings.hrc"
#include "strings.hrc"
#include "helpids.h"
#include "sdattr.hxx"
#include "sdabstdlg.hxx"
#include "unmodpg.hxx"
#include "Window.hxx"
#include "optsitem.hxx"
#include "DrawDocShell.hxx"
#include "FactoryIds.hxx"
#include "slideshow.hxx"
#include "TaskPaneViewShell.hxx"
#include "ViewShellBase.hxx"

#include <sfx2/bindings.hxx>
#include <sfx2/dispatch.hxx>
#include <sfx2/request.hxx>
#include <svtools/aeitem.hxx>
#include <vcl/msgbox.hxx>
#include <basic/sbstar.hxx>

namespace {
class ImpUndoDeleteWarning : public ModalDialog
{
private:
    FixedImage      maImage;
    FixedText       maWarningFT;
    CheckBox        maDisableCB;
    OKButton        maYesBtn;
    CancelButton    maNoBtn;

public:
    ImpUndoDeleteWarning(Window* pParent);
    BOOL IsWarningDisabled() const { return maDisableCB.IsChecked(); }
};

ImpUndoDeleteWarning::ImpUndoDeleteWarning(Window* pParent)
:   ModalDialog(pParent, SdResId(RID_UNDO_DELETE_WARNING)),
    maImage(this, SdResId(IMG_UNDO_DELETE_WARNING)),
    maWarningFT(this, SdResId(FT_UNDO_DELETE_WARNING)),
    maDisableCB(this, SdResId(CB_UNDO_DELETE_DISABLE)),
    maYesBtn(this, SdResId(BTN_UNDO_DELETE_YES)),
    maNoBtn(this, SdResId(BTN_UNDO_DELETE_NO))
{
    FreeResource();

    SetHelpId( HID_SD_UNDODELETEWARNING_DLG );
    maDisableCB.SetHelpId( HID_SD_UNDODELETEWARNING_CBX );

    maYesBtn.SetText(Button::GetStandardText(BUTTON_YES));
    maNoBtn.SetText(Button::GetStandardText(BUTTON_NO));
    maImage.SetImage(WarningBox::GetStandardImage());

    // #93721# Set focus to YES-Button
    maYesBtn.GrabFocus();
}

} // end of anonymous namespace

namespace sd {

ViewShell::Implementation::Implementation (ViewShell& rViewShell)
    : mbIsShowingUIControls(false),
      mbIsMainViewShell(false),
      mrViewShell (rViewShell),
      mbIsInitialized(false)
{
}

ViewShell::Implementation::~Implementation (void)
{
}

void ViewShell::Implementation::ProcessModifyPageSlot (
    SfxRequest& rRequest,
    SdPage* pCurrentPage,
    PageKind ePageKind)
{
    SdDrawDocument* pDocument = mrViewShell.GetDoc();
    SdrLayerAdmin& rLayerAdmin = pDocument->GetLayerAdmin();
    BYTE aBckgrnd = rLayerAdmin.GetLayerID(String(SdResId(STR_LAYER_BCKGRND)), FALSE);
    BYTE aBckgrndObj = rLayerAdmin.GetLayerID(String(SdResId(STR_LAYER_BCKGRNDOBJ)), FALSE);
    SetOfByte aVisibleLayers;
    BOOL bHandoutMode = FALSE;
    SdPage* pHandoutMPage = NULL;
    String aNewName;

    // #95981#
    String aOldName;

    AutoLayout aNewAutoLayout;

    // #95981#
    AutoLayout aOldAutoLayout;

    BOOL bBVisible;
    BOOL bBObjsVisible;
    const SfxItemSet* pArgs = rRequest.GetArgs();

    if (pCurrentPage->TRG_HasMasterPage())
        aVisibleLayers = pCurrentPage->TRG_GetMasterPageVisibleLayers();
    else
        aVisibleLayers.SetAll();

    do
    {
        if (!pArgs || pArgs->Count() == 1 || pArgs->Count() == 2 )
        {
            if (pArgs && pArgs->Count() == 2)
            {
                // We have been called with a request that contains two
                // arguments.  One was used as preselected layout in a
                // dialog.  We could select that layout in the
                // layout panel instead.
                /*
                    SFX_REQUEST_ARG (rRequest, pNewAutoLayout, SfxUInt32Item, ID_VAL_WHATLAYOUT, FALSE);
                    eNewAutoLayout = (AutoLayout) pNewAutoLayout->GetValue
                    ();
                */
            }

            // Make the layout menu visible in the tool pane.
            SfxBoolItem aMakeToolPaneVisible (ID_VAL_ISVISIBLE, TRUE);
            SfxUInt32Item aPanelId (ID_VAL_PANEL_INDEX,
                ::sd::toolpanel::TaskPaneViewShell::PID_LAYOUT);
            mrViewShell.GetDispatcher()->Execute (
                SID_TASK_PANE,
                SFX_CALLMODE_ASYNCHRON | SFX_CALLMODE_RECORD,
                &aMakeToolPaneVisible,
                &aPanelId,
                NULL);

            // We have activated a non-modal control in the task pane.
            // Because it does not return anything we can not do anything
            // more right now and have to exit here.
            break;
        }
        else if (pArgs->Count() == 4)
        {
            SFX_REQUEST_ARG (rRequest, pNewName, SfxStringItem, ID_VAL_PAGENAME, FALSE);
            SFX_REQUEST_ARG (rRequest, pNewAutoLayout, SfxUInt32Item, ID_VAL_WHATLAYOUT, FALSE);
            SFX_REQUEST_ARG (rRequest, pBVisible, SfxBoolItem, ID_VAL_ISPAGEBACK, FALSE);
            SFX_REQUEST_ARG (rRequest, pBObjsVisible, SfxBoolItem, ID_VAL_ISPAGEOBJ, FALSE);
            AutoLayout aLayout ((AutoLayout)pNewAutoLayout->GetValue ());
            if (aLayout >= AUTOLAYOUT__START
                && aLayout < AUTOLAYOUT__END)
            {
                aNewName        = pNewName->GetValue ();
                aNewAutoLayout = (AutoLayout) pNewAutoLayout->GetValue ();
                bBVisible       = pBVisible->GetValue ();
                bBObjsVisible   = pBObjsVisible->GetValue ();
            }
            else
            {
                StarBASIC::FatalError (SbERR_BAD_PROP_VALUE);
                rRequest.Ignore ();
                break;
            }
            if (ePageKind == PK_HANDOUT)
            {
                bHandoutMode = TRUE;
                pHandoutMPage = pDocument->GetMasterSdPage(0, PK_HANDOUT);
            }
        }
        else
        {
            StarBASIC::FatalError (SbERR_WRONG_ARGS);
            rRequest.Ignore ();
            break;
        }

        SdPage* pUndoPage =
            bHandoutMode ? pHandoutMPage : pCurrentPage;

        // #67720#
        SfxUndoManager* pUndoManager = mrViewShell.GetDocSh()->GetUndoManager();
        DBG_ASSERT(pUndoManager, "No UNDO MANAGER ?!?");

        // #90356#
        sal_uInt16 nActionCount(pUndoManager->GetUndoActionCount());
        sal_Bool bContinue(sal_True);

        if(nActionCount)
        {
            // #90356# get SdOptions
            SdOptions* pOptions = SD_MOD()->GetSdOptions(pDocument->GetDocumentType());
            //            sal_Bool bShowDialog(pOptions->IsShowUndoDeleteWarning());
            sal_Bool bShowDialog(sal_False);

            // #95981# If only name is changed do not show
            // ImpUndoDeleteWarning dialog
            if(bShowDialog)
            {
                sal_Bool bNameChanged(aNewName != aOldName);
                sal_Bool bLayoutChanged(aNewAutoLayout != aOldAutoLayout);

                if(bNameChanged && !bLayoutChanged)
                    bShowDialog = sal_False;
            }

            if(bShowDialog)
            {
                // ask user if he wants to loose UNDO stack
                ImpUndoDeleteWarning aUndoDeleteDlg(mrViewShell.GetActiveWindow());

                if(BUTTONID_OK == aUndoDeleteDlg.Execute())
                {
                    pUndoManager->Clear();
                }
                else
                {
                    bContinue = sal_False;
                }

                // #90356# write option flag back if change was done
                if(aUndoDeleteDlg.IsWarningDisabled())
                {
                    pOptions->SetShowUndoDeleteWarning(FALSE);
                }
            }
        }

        if(bContinue)
        {
            ModifyPageUndoAction* pAction = new ModifyPageUndoAction(
                pUndoManager, pDocument, pUndoPage, aNewName, aNewAutoLayout, bBVisible, bBObjsVisible);
            pUndoManager->AddUndoAction(pAction);

            // Clear the selection because the selectec object may be removed as
            // a result of the ssignment of the layout.
            mrViewShell.GetDrawView()->UnmarkAll();

            if (!bHandoutMode)
            {
                if (pCurrentPage->GetName() != aNewName)
                {
                    pCurrentPage->SetName(aNewName);

                    if (ePageKind == PK_STANDARD)
                    {
                        USHORT nPage = (pCurrentPage->GetPageNum()-1) / 2;
                        SdPage* pNotesPage = pDocument->GetSdPage(nPage, PK_NOTES);
                        if (pNotesPage != NULL)
                            pNotesPage->SetName(aNewName);
                    }
                }

                pCurrentPage->SetAutoLayout(aNewAutoLayout, TRUE);

                aBckgrnd = rLayerAdmin.GetLayerID(String(SdResId(STR_LAYER_BCKGRND)), FALSE);
                aBckgrndObj = rLayerAdmin.GetLayerID(String(SdResId(STR_LAYER_BCKGRNDOBJ)), FALSE);
                aVisibleLayers.Set(aBckgrnd, bBVisible);
                aVisibleLayers.Set(aBckgrndObj, bBObjsVisible);
                pCurrentPage->TRG_SetMasterPageVisibleLayers(aVisibleLayers);
            }
            else
            {
                pHandoutMPage->SetAutoLayout(aNewAutoLayout, TRUE);
            }
            // The list of presentation objects at the page
            // has been cleared by SetAutolayout().  We still
            // have to clear the list of removed presentation
            // objects held by the model which references the
            // former list.
            pDocument->ClearDeletedPresObjList();

            mrViewShell.GetViewFrame()->GetDispatcher()->Execute(SID_SWITCHPAGE,
                SFX_CALLMODE_ASYNCHRON | SFX_CALLMODE_RECORD);

            BOOL bSetModified = TRUE;

            if (pArgs && pArgs->Count() == 1)
            {
                bSetModified = (BOOL) ((SfxBoolItem&) pArgs->Get(SID_MODIFYPAGE)).GetValue();
            }

            pDocument->SetChanged(bSetModified);
        }
    }
    while (false);

    mrViewShell.Cancel();
    rRequest.Done ();
}

void ViewShell::Implementation::AssignLayout (
    SdPage* pPage,
    AutoLayout aLayout)
{
    // Transform the given request into the four argument form that is
    // understood by ProcessModifyPageSlot().
    SdrLayerAdmin& rLayerAdmin (mrViewShell.GetViewShellBase().GetDocument()->GetLayerAdmin());
    BYTE aBackground (rLayerAdmin.GetLayerID(String(SdResId(STR_LAYER_BCKGRND)), FALSE));
    BYTE aBackgroundObject (rLayerAdmin.GetLayerID(String(SdResId(STR_LAYER_BCKGRNDOBJ)), FALSE));
    SetOfByte aVisibleLayers (pPage->TRG_GetMasterPageVisibleLayers());
    SfxRequest aRequest (mrViewShell.GetViewShellBase().GetViewFrame(), SID_MODIFYPAGE);
    aRequest.AppendItem(SfxStringItem (ID_VAL_PAGENAME, pPage->GetName()));
    aRequest.AppendItem(SfxUInt32Item (ID_VAL_WHATLAYOUT, aLayout));
    aRequest.AppendItem(SfxBoolItem(ID_VAL_ISPAGEBACK, aVisibleLayers.IsSet(aBackground)));
    aRequest.AppendItem(SfxBoolItem(ID_VAL_ISPAGEOBJ, aVisibleLayers.IsSet(aBackgroundObject)));

    // Forward the call with the new arguments.
    ProcessModifyPageSlot (
        aRequest,
        pPage,
        pPage->GetPageKind());
}

sal_uInt16 ViewShell::Implementation::GetViewId (void)
{
    switch (mrViewShell.GetShellType())
    {
        case ViewShell::ST_IMPRESS:
        case ViewShell::ST_NOTES:
        case ViewShell::ST_HANDOUT:
            return IMPRESS_FACTORY_ID;

        case ViewShell::ST_DRAW:
            return DRAW_FACTORY_ID;

        case ViewShell::ST_OUTLINE:
            return OUTLINE_FACTORY_ID;

        case ViewShell::ST_SLIDE:
        case ViewShell::ST_SLIDE_SORTER:
            return SLIDE_SORTER_FACTORY_ID;

        case ViewShell::ST_PRESENTATION:
            return PRESENTATION_FACTORY_ID;

        // Since we have to return a view id for every possible shell type
        // and there is not (yet) a proper ViewShellBase sub class for the
        // remaining types we chose the Impress factory as a fall back.
        case ViewShell::ST_TASK_PANE:
        case ViewShell::ST_NONE:
        default:
            return IMPRESS_FACTORY_ID;
    }
}

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


<commit_before>/* BEGIN_COMMON_COPYRIGHT_HEADER
 * (c)LGPL2+
 *
 * LXDE-Qt - a lightweight, Qt based, desktop toolset
 * http://razor-qt.org
 *
 * Copyright: 2011 Razor team
 * Authors:
 *   Petr Vanek <petr@scribus.info>
 *   Alexander Sokoloff <sokoloff.a@gmail.com>
 *
 * This program or library is free software; you can redistribute it
 * and/or modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License, or (at your option) any later version.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.

 * You should have received a copy of the GNU Lesser General
 * Public License along with this library; if not, write to the
 * Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
 * Boston, MA 02110-1301 USA
 *
 * END_COMMON_COPYRIGHT_HEADER */

#include "mountbutton.h"
#include <XdgIcon>

MountButton::MountButton(QWidget * parent) :
    QToolButton(parent)
{
    setIcon(XdgIcon::fromTheme(QStringList() << "device-notifier" << "drive-removable-media-usb" << "drive-removable-media"));

    setToolTip(tr("Removable media/devices manager"));
    setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Expanding);
}

MountButton::~MountButton()
{
}

void MountButton::setDown(bool down)
{
    QToolButton::setDown(down);
}
<commit_msg>plugin-mount: Use only one icon instead a list of possible ones<commit_after>/* BEGIN_COMMON_COPYRIGHT_HEADER
 * (c)LGPL2+
 *
 * LXDE-Qt - a lightweight, Qt based, desktop toolset
 * http://razor-qt.org
 *
 * Copyright: 2011 Razor team
 * Authors:
 *   Petr Vanek <petr@scribus.info>
 *   Alexander Sokoloff <sokoloff.a@gmail.com>
 *
 * This program or library is free software; you can redistribute it
 * and/or modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License, or (at your option) any later version.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.

 * You should have received a copy of the GNU Lesser General
 * Public License along with this library; if not, write to the
 * Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
 * Boston, MA 02110-1301 USA
 *
 * END_COMMON_COPYRIGHT_HEADER */

#include "mountbutton.h"
#include <XdgIcon>

MountButton::MountButton(QWidget * parent) :
    QToolButton(parent)
{
    setIcon(XdgIcon::fromTheme(QStringLiteral("drive-removable-media")));

    setToolTip(tr("Removable media/devices manager"));
    setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Expanding);
}

MountButton::~MountButton()
{
}

void MountButton::setDown(bool down)
{
    QToolButton::setDown(down);
}
<|endoftext|>


<commit_before>#include <iostream>
#include <GL/glut.h>
#include "Ising_simulator.hpp"
#include "spin.hpp"
#include "Ising_simulator_traits.hpp"
#include "drawer/Ising_window_traits.hpp"
#include "../openGLwrapper/make_canvas.hpp"
#include "../openGLwrapper/drawquads.hpp"

//~~~~~~~~~~~~~~~~~~~~~~~~~~~~parameter set~~~~~~~~~~~~~~~~~~~~~~~~~~~

using numerical_type = Default_simulator_traits::numerical_type;

constexpr std::size_t system_row_num(250);
constexpr std::size_t system_column_num(250);
constexpr int random_seed(53);
constexpr numerical_type tempreture(1);
constexpr numerical_type magnetic_flux_density(0.0);
constexpr numerical_type spin_interaction(0.5);

using simulator_type = Ising_simulator<
    Neuman_flip_spin, system_row_num, system_column_num, Default_simulator_traits>;

//~~~~~~~~~~~~~~~~~~~~~~~~global func declaration~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

template<typename window_traits>
void set_canvas(int& argc, char** argv);

template<typename window_traits>
void draw_pixel();

template<typename window_traits>
void display();

void update_canvas(int);
//~~~~~~~~~~~~~~~~~~~~~~~~global variable declaration~~~~~~~~~~~~~~~~~~~~~~~~~~~

const simulator_type::array_matrix* Ising_field_ptr(nullptr);
simulator_type* Ising_simulator_ptr(nullptr);
std::size_t step(0);

//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~main~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
int main(int argc, char *argv[]){
    Ising_simulator_ptr = new simulator_type
    	(random_seed, tempreture, magnetic_flux_density, spin_interaction);

    Ising_field_ptr = &(Ising_simulator_ptr->spins_state());

    set_canvas<Ising_window_traits>(argc ,argv);
    glutTimerFunc(10, update_canvas, 0);
    glutMainLoop();

    delete Ising_simulator_ptr;
    return 0;
}

//~~~~~~~~~~~~~~~~~~~~~~~~global func definition~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

template<typename window_traits>
void set_canvas(int& argc, char** argv)
{
    setWindow<window_traits>(argc, argv);
    setBackground();
    glClear(GL_COLOR_BUFFER_BIT);
    glutDisplayFunc(display<window_traits>);
    return;
}

template<typename window_traits>
void display()
{
    glClear(GL_COLOR_BUFFER_BIT);
    draw_pixel<window_traits>();
    glFlush();
    return;
}

void update_canvas(int value)
{
    std::size_t roop_num = 1000;
    ++step;
    std::cout << step * roop_num << std::endl;
    for(std::size_t roop = 0; roop < roop_num; ++roop)
	Ising_simulator_ptr->step();
    glutPostRedisplay();
    glutTimerFunc(50, update_canvas, 0);
    return;
}

template<typename window_traits>
void draw_pixel()
{
    const std::size_t row_n = Ising_field_ptr->row_num();
    const std::size_t column_n = Ising_field_ptr->column_num();
    constexpr float margin = window_traits::margin;
    constexpr float frame_size = 2 - 2.0 * margin;
    const double x_pixel_size = frame_size / row_n;
    const double y_pixel_size = frame_size / column_n;

    const double initial_x_coord = -1 + margin + x_pixel_size * 0.5;
    const double initial_y_coord = -1 + margin + y_pixel_size * 0.5;

    double x_coord = initial_x_coord;
    double y_coord = initial_y_coord;
    for(std::size_t row = 0; row < row_n; ++row){
	for(std::size_t column = 0; column < column_n; ++column){
	    if(Ising_field_ptr->at(row, column).get() == 1)
		drawquads(x_coord, y_coord, x_pixel_size, y_pixel_size, 0.0, 0.0, 0.0);
	    else
		drawquads(x_coord, y_coord, x_pixel_size, y_pixel_size, 1.0, 1.0, 1.0);
	    x_coord += x_pixel_size;
	}
	x_coord = initial_x_coord;
	y_coord += y_pixel_size;
    }
    return;
}

<commit_msg>fix include file pass<commit_after>#include <iostream>
#include <GL/glut.h>
#include "Ising_simulator.hpp"
#include "spin.hpp"
#include "Ising_simulator_traits.hpp"
#include "Ising_window_traits.hpp"
#include "../openGLwrapper/make_canvas.hpp"
#include "../openGLwrapper/drawquads.hpp"

//~~~~~~~~~~~~~~~~~~~~~~~~~~~~parameter set~~~~~~~~~~~~~~~~~~~~~~~~~~~

using numerical_type = Default_simulator_traits::numerical_type;

constexpr std::size_t system_row_num(250);
constexpr std::size_t system_column_num(250);
constexpr int random_seed(53);
constexpr numerical_type tempreture(1);
constexpr numerical_type magnetic_flux_density(0.0);
constexpr numerical_type spin_interaction(0.5);

using simulator_type = Ising_simulator<
    Neuman_flip_spin, system_row_num, system_column_num, Default_simulator_traits>;

//~~~~~~~~~~~~~~~~~~~~~~~~global func declaration~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

template<typename window_traits>
void set_canvas(int& argc, char** argv);

template<typename window_traits>
void draw_pixel();

template<typename window_traits>
void display();

void update_canvas(int);
//~~~~~~~~~~~~~~~~~~~~~~~~global variable declaration~~~~~~~~~~~~~~~~~~~~~~~~~~~

const simulator_type::array_matrix* Ising_field_ptr(nullptr);
simulator_type* Ising_simulator_ptr(nullptr);
std::size_t step(0);

//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~main~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
int main(int argc, char *argv[]){
    Ising_simulator_ptr = new simulator_type
    	(random_seed, tempreture, magnetic_flux_density, spin_interaction);

    Ising_field_ptr = &(Ising_simulator_ptr->spins_state());

    set_canvas<Ising_window_traits>(argc ,argv);
    glutTimerFunc(10, update_canvas, 0);
    glutMainLoop();

    delete Ising_simulator_ptr;
    return 0;
}

//~~~~~~~~~~~~~~~~~~~~~~~~global func definition~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

template<typename window_traits>
void set_canvas(int& argc, char** argv)
{
    setWindow<window_traits>(argc, argv);
    setBackground();
    glClear(GL_COLOR_BUFFER_BIT);
    glutDisplayFunc(display<window_traits>);
    return;
}

template<typename window_traits>
void display()
{
    glClear(GL_COLOR_BUFFER_BIT);
    draw_pixel<window_traits>();
    glFlush();
    return;
}

void update_canvas(int value)
{
    std::size_t roop_num = 1000;
    ++step;
    std::cout << step * roop_num << std::endl;
    for(std::size_t roop = 0; roop < roop_num; ++roop)
	Ising_simulator_ptr->step();
    glutPostRedisplay();
    glutTimerFunc(50, update_canvas, 0);
    return;
}

template<typename window_traits>
void draw_pixel()
{
    const std::size_t row_n = Ising_field_ptr->row_num();
    const std::size_t column_n = Ising_field_ptr->column_num();
    constexpr float margin = window_traits::margin;
    constexpr float frame_size = 2 - 2.0 * margin;
    const double x_pixel_size = frame_size / row_n;
    const double y_pixel_size = frame_size / column_n;

    const double initial_x_coord = -1 + margin + x_pixel_size * 0.5;
    const double initial_y_coord = -1 + margin + y_pixel_size * 0.5;

    double x_coord = initial_x_coord;
    double y_coord = initial_y_coord;
    for(std::size_t row = 0; row < row_n; ++row){
	for(std::size_t column = 0; column < column_n; ++column){
	    if(Ising_field_ptr->at(row, column).get() == 1)
		drawquads(x_coord, y_coord, x_pixel_size, y_pixel_size, 0.0, 0.0, 0.0);
	    else
		drawquads(x_coord, y_coord, x_pixel_size, y_pixel_size, 1.0, 1.0, 1.0);
	    x_coord += x_pixel_size;
	}
	x_coord = initial_x_coord;
	y_coord += y_pixel_size;
    }
    return;
}

<|endoftext|>


<commit_before>/***************************************************************************
 *   Copyright (C) 2004 by Frank Osterfeld                                 *
 *   frank.osterfeld AT kdemail.net                                      *
 *                                                                         *
 *   Licensed under GPL.                                                   *
 ***************************************************************************/

#include "feedgroup.h"
#include "treenode.h"

#include "kdebug.h"

using namespace Akregator;

TreeNode::TreeNode()
    : QObject(0, 0), m_title(""), m_parent(0), m_doNotify(true), m_changeOccured(false)
{
}

TreeNode::~TreeNode()
{
    // tell the world that this node is destroyed
    emit signalDestroyed(this);
}

const QString& TreeNode::title() const
{
    return m_title;
}

void TreeNode::setTitle(const QString& title)
{

    if (m_title != title)
    {
        m_title = title;
        modified();
    }
}

TreeNode* TreeNode::nextSibling() const
{
    if (!m_parent)
        return 0;
    QPtrList<TreeNode> children = m_parent->children();
    children.find(this);
    return children.next();
}

TreeNode* TreeNode::prevSibling() const
{
    if (!m_parent)
        return 0;
    QPtrList<TreeNode> children = m_parent->children();
    children.find(this);
    return children.prev();
}

FeedGroup* TreeNode::parent() const
{
    return m_parent;
}

void TreeNode::setParent(FeedGroup* parent)
{
    m_parent = parent;
}

void TreeNode::setNotificationMode(bool doNotify, bool notifyOccuredChanges)
{
    if (doNotify && !m_doNotify) // turned on
    {
        m_doNotify = true;
        if (m_changeOccured && notifyOccuredChanges)
            emit signalChanged(this);
        m_changeOccured = false;
    }
    if (!doNotify && m_doNotify) //turned off
    {
        m_changeOccured = false;
        m_doNotify = false;
    }
}

void TreeNode::modified()
{
//    kdDebug() << "enter TreeNode::modified" << title() << endl;
    if (m_doNotify)
        emit signalChanged(this);
    else
        m_changeOccured = true;
//    kdDebug() << "leave TreeNode::modified" << title()<< endl;
}

#include "treenode.moc"
<commit_msg>Warning--<commit_after>/***************************************************************************
 *   Copyright (C) 2004 by Frank Osterfeld                                 *
 *   frank.osterfeld AT kdemail.net                                      *
 *                                                                         *
 *   Licensed under GPL.                                                   *
 ***************************************************************************/

#include "feedgroup.h"
#include "treenode.h"

#include "kdebug.h"

using namespace Akregator;

TreeNode::TreeNode()
    : QObject(0, 0), m_doNotify(true), m_changeOccured(false), m_title(""), m_parent(0)
{
}

TreeNode::~TreeNode()
{
    // tell the world that this node is destroyed
    emit signalDestroyed(this);
}

const QString& TreeNode::title() const
{
    return m_title;
}

void TreeNode::setTitle(const QString& title)
{

    if (m_title != title)
    {
        m_title = title;
        modified();
    }
}

TreeNode* TreeNode::nextSibling() const
{
    if (!m_parent)
        return 0;
    QPtrList<TreeNode> children = m_parent->children();
    children.find(this);
    return children.next();
}

TreeNode* TreeNode::prevSibling() const
{
    if (!m_parent)
        return 0;
    QPtrList<TreeNode> children = m_parent->children();
    children.find(this);
    return children.prev();
}

FeedGroup* TreeNode::parent() const
{
    return m_parent;
}

void TreeNode::setParent(FeedGroup* parent)
{
    m_parent = parent;
}

void TreeNode::setNotificationMode(bool doNotify, bool notifyOccuredChanges)
{
    if (doNotify && !m_doNotify) // turned on
    {
        m_doNotify = true;
        if (m_changeOccured && notifyOccuredChanges)
            emit signalChanged(this);
        m_changeOccured = false;
    }
    if (!doNotify && m_doNotify) //turned off
    {
        m_changeOccured = false;
        m_doNotify = false;
    }
}

void TreeNode::modified()
{
//    kdDebug() << "enter TreeNode::modified" << title() << endl;
    if (m_doNotify)
        emit signalChanged(this);
    else
        m_changeOccured = true;
//    kdDebug() << "leave TreeNode::modified" << title()<< endl;
}

#include "treenode.moc"
<|endoftext|>


<commit_before>// Copyright 2015 Google Inc. All rights reserved
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//      http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

// +build ignore

#include "command.h"

#include <unordered_map>
#include <unordered_set>

#include "dep.h"
#include "eval.h"
#include "flags.h"
#include "log.h"
#include "strutil.h"
#include "var.h"

namespace {

class AutoVar : public Var {
 public:
  virtual const char* Flavor() const override {
    return "undefined";
  }
  virtual VarOrigin Origin() const override {
    return VarOrigin::AUTOMATIC;
  }

  virtual void AppendVar(Evaluator*, Value*) override { CHECK(false); }

  virtual StringPiece String() const override {
    ERROR("$(value %s) is not implemented yet", sym_);
    return "";
  }

  virtual string DebugString() const override {
    return string("AutoVar(") + sym_ + ")";
  }

 protected:
  AutoVar(CommandEvaluator* ce, const char* sym) : ce_(ce), sym_(sym) {}
  virtual ~AutoVar() = default;

  CommandEvaluator* ce_;
  const char* sym_;
};

#define DECLARE_AUTO_VAR_CLASS(name)                                    \
  class name : public AutoVar {                                         \
   public:                                                              \
   name(CommandEvaluator* ce, const char* sym)                          \
       : AutoVar(ce, sym) {}                                            \
   virtual ~name() = default;                                           \
   virtual void Eval(Evaluator* ev, string* s) const override;          \
  }

DECLARE_AUTO_VAR_CLASS(AutoAtVar);
DECLARE_AUTO_VAR_CLASS(AutoLessVar);
DECLARE_AUTO_VAR_CLASS(AutoHatVar);
DECLARE_AUTO_VAR_CLASS(AutoPlusVar);
DECLARE_AUTO_VAR_CLASS(AutoStarVar);

class AutoSuffixDVar : public AutoVar {
 public:
  AutoSuffixDVar(CommandEvaluator* ce, const char* sym, Var* wrapped)
      : AutoVar(ce, sym), wrapped_(wrapped) {
  }
  virtual ~AutoSuffixDVar() = default;
  virtual void Eval(Evaluator* ev, string* s) const override;

 private:
  Var* wrapped_;
};

class AutoSuffixFVar : public AutoVar {
 public:
  AutoSuffixFVar(CommandEvaluator* ce, const char* sym, Var* wrapped)
      : AutoVar(ce, sym), wrapped_(wrapped) {}
  virtual ~AutoSuffixFVar() = default;
  virtual void Eval(Evaluator* ev, string* s) const override;

 private:
  Var* wrapped_;
};

void AutoAtVar::Eval(Evaluator*, string* s) const {
  *s += ce_->current_dep_node()->output.str();
}

void AutoLessVar::Eval(Evaluator*, string* s) const {
  auto& ai = ce_->current_dep_node()->actual_inputs;
  if (!ai.empty())
    *s += ai[0].str();
}

void AutoHatVar::Eval(Evaluator*, string* s) const {
  unordered_set<StringPiece> seen;
  WordWriter ww(s);
  for (Symbol ai : ce_->current_dep_node()->actual_inputs) {
    if (seen.insert(ai.str()).second)
      ww.Write(ai.str());
  }
}

void AutoPlusVar::Eval(Evaluator*, string* s) const {
  WordWriter ww(s);
  for (Symbol ai : ce_->current_dep_node()->actual_inputs) {
    ww.Write(ai.str());
  }
}

void AutoStarVar::Eval(Evaluator*, string* s) const {
  const DepNode* n = ce_->current_dep_node();
  if (!n->output_pattern.IsValid())
    return;
  Pattern pat(n->output_pattern.str());
  pat.Stem(n->output.str()).AppendToString(s);
}

void AutoSuffixDVar::Eval(Evaluator* ev, string* s) const {
  string buf;
  wrapped_->Eval(ev, &buf);
  WordWriter ww(s);
  for (StringPiece tok : WordScanner(buf)) {
    ww.Write(Dirname(tok));
  }
}

void AutoSuffixFVar::Eval(Evaluator* ev, string* s) const {
  string buf;
  wrapped_->Eval(ev, &buf);
  WordWriter ww(s);
  for (StringPiece tok : WordScanner(buf)) {
    ww.Write(Basename(tok));
  }
}

void ParseCommandPrefixes(StringPiece* s, bool* echo, bool* ignore_error) {
  *s = TrimLeftSpace(*s);
  while (true) {
    char c = s->get(0);
    if (c == '@') {
      *echo = false;
    } else if (c == '-') {
      *ignore_error = true;
    } else {
      break;
    }
    *s = TrimLeftSpace(s->substr(1));
  }
}

}  // namespace

CommandEvaluator::CommandEvaluator(Evaluator* ev)
    : ev_(ev) {
  Vars* vars = ev_->mutable_vars();
#define INSERT_AUTO_VAR(name, sym) do {                                 \
    Var* v = new name(this, sym);                                       \
    (*vars)[Intern(sym)] = v;                                           \
    (*vars)[Intern(sym"D")] = new AutoSuffixDVar(this, sym"D", v);      \
    (*vars)[Intern(sym"F")] = new AutoSuffixFVar(this, sym"F", v);      \
  } while (0)
  INSERT_AUTO_VAR(AutoAtVar, "@");
  INSERT_AUTO_VAR(AutoLessVar, "<");
  INSERT_AUTO_VAR(AutoHatVar, "^");
  INSERT_AUTO_VAR(AutoPlusVar, "+");
  INSERT_AUTO_VAR(AutoStarVar, "*");
}

void CommandEvaluator::Eval(DepNode* n, vector<Command*>* commands) {
  ev_->set_loc(n->loc);
  ev_->set_current_scope(n->rule_vars);
  current_dep_node_ = n;
  for (Value* v : n->cmds) {
    const string&& cmds_buf = v->Eval(ev_);
    StringPiece cmds = cmds_buf;
    bool global_echo = !g_flags.is_silent_mode;
    bool global_ignore_error = false;
    ParseCommandPrefixes(&cmds, &global_echo, &global_ignore_error);
    if (cmds == "")
      continue;
    while (true) {
      size_t lf_cnt;
      size_t index = FindEndOfLine(cmds, 0, &lf_cnt);
      if (index == cmds.size())
        index = string::npos;
      StringPiece cmd = TrimLeftSpace(cmds.substr(0, index));
      cmds = cmds.substr(index + 1);

      bool echo = global_echo;
      bool ignore_error = global_ignore_error;
      ParseCommandPrefixes(&cmd, &echo, &ignore_error);

      if (!cmd.empty()) {
        Command* command = new Command(n->output);
        command->cmd = cmd.as_string();
        command->echo = echo;
        command->ignore_error = ignore_error;
        commands->push_back(command);
      }
      if (index == string::npos)
        break;
    }
    continue;
  }

  if (!ev_->delayed_output_commands().empty()) {
    vector<Command*> output_commands;
    for (const string& cmd : ev_->delayed_output_commands()) {
      Command* c = new Command(n->output);
      c->cmd = cmd;
      c->echo = false;
      c->ignore_error = false;
      output_commands.push_back(c);
    }
    // Prepend |output_commands|.
    commands->swap(output_commands);
    copy(output_commands.begin(), output_commands.end(),
         back_inserter(*commands));
    ev_->clear_delayed_output_commands();
  }

  ev_->set_current_scope(NULL);
}
<commit_msg>[C++] Fail early for unsupported automatic variables<commit_after>// Copyright 2015 Google Inc. All rights reserved
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//      http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

// +build ignore

#include "command.h"

#include <unordered_map>
#include <unordered_set>

#include "dep.h"
#include "eval.h"
#include "flags.h"
#include "log.h"
#include "strutil.h"
#include "var.h"

namespace {

class AutoVar : public Var {
 public:
  virtual const char* Flavor() const override {
    return "undefined";
  }
  virtual VarOrigin Origin() const override {
    return VarOrigin::AUTOMATIC;
  }

  virtual void AppendVar(Evaluator*, Value*) override { CHECK(false); }

  virtual StringPiece String() const override {
    ERROR("$(value %s) is not implemented yet", sym_);
    return "";
  }

  virtual string DebugString() const override {
    return string("AutoVar(") + sym_ + ")";
  }

 protected:
  AutoVar(CommandEvaluator* ce, const char* sym) : ce_(ce), sym_(sym) {}
  virtual ~AutoVar() = default;

  CommandEvaluator* ce_;
  const char* sym_;
};

#define DECLARE_AUTO_VAR_CLASS(name)                                    \
  class name : public AutoVar {                                         \
   public:                                                              \
   name(CommandEvaluator* ce, const char* sym)                          \
       : AutoVar(ce, sym) {}                                            \
   virtual ~name() = default;                                           \
   virtual void Eval(Evaluator* ev, string* s) const override;          \
  }

DECLARE_AUTO_VAR_CLASS(AutoAtVar);
DECLARE_AUTO_VAR_CLASS(AutoLessVar);
DECLARE_AUTO_VAR_CLASS(AutoHatVar);
DECLARE_AUTO_VAR_CLASS(AutoPlusVar);
DECLARE_AUTO_VAR_CLASS(AutoStarVar);
DECLARE_AUTO_VAR_CLASS(AutoNotImplementedVar);

class AutoSuffixDVar : public AutoVar {
 public:
  AutoSuffixDVar(CommandEvaluator* ce, const char* sym, Var* wrapped)
      : AutoVar(ce, sym), wrapped_(wrapped) {
  }
  virtual ~AutoSuffixDVar() = default;
  virtual void Eval(Evaluator* ev, string* s) const override;

 private:
  Var* wrapped_;
};

class AutoSuffixFVar : public AutoVar {
 public:
  AutoSuffixFVar(CommandEvaluator* ce, const char* sym, Var* wrapped)
      : AutoVar(ce, sym), wrapped_(wrapped) {}
  virtual ~AutoSuffixFVar() = default;
  virtual void Eval(Evaluator* ev, string* s) const override;

 private:
  Var* wrapped_;
};

void AutoAtVar::Eval(Evaluator*, string* s) const {
  *s += ce_->current_dep_node()->output.str();
}

void AutoLessVar::Eval(Evaluator*, string* s) const {
  auto& ai = ce_->current_dep_node()->actual_inputs;
  if (!ai.empty())
    *s += ai[0].str();
}

void AutoHatVar::Eval(Evaluator*, string* s) const {
  unordered_set<StringPiece> seen;
  WordWriter ww(s);
  for (Symbol ai : ce_->current_dep_node()->actual_inputs) {
    if (seen.insert(ai.str()).second)
      ww.Write(ai.str());
  }
}

void AutoPlusVar::Eval(Evaluator*, string* s) const {
  WordWriter ww(s);
  for (Symbol ai : ce_->current_dep_node()->actual_inputs) {
    ww.Write(ai.str());
  }
}

void AutoStarVar::Eval(Evaluator*, string* s) const {
  const DepNode* n = ce_->current_dep_node();
  if (!n->output_pattern.IsValid())
    return;
  Pattern pat(n->output_pattern.str());
  pat.Stem(n->output.str()).AppendToString(s);
}

void AutoNotImplementedVar::Eval(Evaluator*, string*) const {
  ERROR("Automatic variable `$%s' isn't supported yet", sym_);
}

void AutoSuffixDVar::Eval(Evaluator* ev, string* s) const {
  string buf;
  wrapped_->Eval(ev, &buf);
  WordWriter ww(s);
  for (StringPiece tok : WordScanner(buf)) {
    ww.Write(Dirname(tok));
  }
}

void AutoSuffixFVar::Eval(Evaluator* ev, string* s) const {
  string buf;
  wrapped_->Eval(ev, &buf);
  WordWriter ww(s);
  for (StringPiece tok : WordScanner(buf)) {
    ww.Write(Basename(tok));
  }
}

void ParseCommandPrefixes(StringPiece* s, bool* echo, bool* ignore_error) {
  *s = TrimLeftSpace(*s);
  while (true) {
    char c = s->get(0);
    if (c == '@') {
      *echo = false;
    } else if (c == '-') {
      *ignore_error = true;
    } else {
      break;
    }
    *s = TrimLeftSpace(s->substr(1));
  }
}

}  // namespace

CommandEvaluator::CommandEvaluator(Evaluator* ev)
    : ev_(ev) {
  Vars* vars = ev_->mutable_vars();
#define INSERT_AUTO_VAR(name, sym) do {                                 \
    Var* v = new name(this, sym);                                       \
    (*vars)[Intern(sym)] = v;                                           \
    (*vars)[Intern(sym"D")] = new AutoSuffixDVar(this, sym"D", v);      \
    (*vars)[Intern(sym"F")] = new AutoSuffixFVar(this, sym"F", v);      \
  } while (0)
  INSERT_AUTO_VAR(AutoAtVar, "@");
  INSERT_AUTO_VAR(AutoLessVar, "<");
  INSERT_AUTO_VAR(AutoHatVar, "^");
  INSERT_AUTO_VAR(AutoPlusVar, "+");
  INSERT_AUTO_VAR(AutoStarVar, "*");
  // TODO: Implement them.
  INSERT_AUTO_VAR(AutoNotImplementedVar, "%");
  INSERT_AUTO_VAR(AutoNotImplementedVar, "?");
  INSERT_AUTO_VAR(AutoNotImplementedVar, "|");
}

void CommandEvaluator::Eval(DepNode* n, vector<Command*>* commands) {
  ev_->set_loc(n->loc);
  ev_->set_current_scope(n->rule_vars);
  current_dep_node_ = n;
  for (Value* v : n->cmds) {
    const string&& cmds_buf = v->Eval(ev_);
    StringPiece cmds = cmds_buf;
    bool global_echo = !g_flags.is_silent_mode;
    bool global_ignore_error = false;
    ParseCommandPrefixes(&cmds, &global_echo, &global_ignore_error);
    if (cmds == "")
      continue;
    while (true) {
      size_t lf_cnt;
      size_t index = FindEndOfLine(cmds, 0, &lf_cnt);
      if (index == cmds.size())
        index = string::npos;
      StringPiece cmd = TrimLeftSpace(cmds.substr(0, index));
      cmds = cmds.substr(index + 1);

      bool echo = global_echo;
      bool ignore_error = global_ignore_error;
      ParseCommandPrefixes(&cmd, &echo, &ignore_error);

      if (!cmd.empty()) {
        Command* command = new Command(n->output);
        command->cmd = cmd.as_string();
        command->echo = echo;
        command->ignore_error = ignore_error;
        commands->push_back(command);
      }
      if (index == string::npos)
        break;
    }
    continue;
  }

  if (!ev_->delayed_output_commands().empty()) {
    vector<Command*> output_commands;
    for (const string& cmd : ev_->delayed_output_commands()) {
      Command* c = new Command(n->output);
      c->cmd = cmd;
      c->echo = false;
      c->ignore_error = false;
      output_commands.push_back(c);
    }
    // Prepend |output_commands|.
    commands->swap(output_commands);
    copy(output_commands.begin(), output_commands.end(),
         back_inserter(*commands));
    ev_->clear_delayed_output_commands();
  }

  ev_->set_current_scope(NULL);
}
<|endoftext|>


<commit_before>/**************************************************************
* Copyright (c) 2010, Dynamic Network Services, Inc.
* Jake Montgomery (jmontgomery@dyn.com) & Tom Daly (tom@dyn.com)
* Distributed under the FreeBSD License - see LICENSE
***************************************************************/
// Common code for beacon and control
#include "common.h"

namespace openbfdd
{
  static uint8_t tempMagicMessageNumber[4] = {0xfe, 0xed, 0x19, 0x66};
  const uint32_t MagicMessageNumber = *(uint32_t *)tempMagicMessageNumber;
  const char *SofwareVesrion = PACKAGE_VERSION;
  const char *ControlAppName = "bfdd-control";
  const char *BeaconAppName = "bfdd-beacon";
}

<commit_msg>MagicMessageNumber code caused compile error on Ubuntu. MagicMessageNumber was implemented in such a way that the beacon could not be controlled from a system with opposite endianess.<commit_after>/**************************************************************
* Copyright (c) 2010, Dynamic Network Services, Inc.
* Jake Montgomery (jmontgomery@dyn.com) & Tom Daly (tom@dyn.com)
* Distributed under the FreeBSD License - see LICENSE
***************************************************************/
// Common code for beacon and control
#include "common.h"

namespace openbfdd
{
  const uint32_t MagicMessageNumber = 0xfeed1966;
  const char *SofwareVesrion = PACKAGE_VERSION;
  const char *ControlAppName = "bfdd-control";
  const char *BeaconAppName = "bfdd-beacon";
}

<|endoftext|>


<commit_before>#include <stdlib.h>

#include "base/logging.h"
#include "base/NativeApp.h"
#include "gl_state.h"

#ifdef _WIN32
#include "GL/wglew.h"
#endif

#if defined(USING_GLES2)
#if defined(ANDROID) || defined(BLACKBERRY)
PFNEGLGETSYSTEMTIMEFREQUENCYNVPROC eglGetSystemTimeFrequencyNV;
PFNEGLGETSYSTEMTIMENVPROC eglGetSystemTimeNV;
PFNGLDRAWTEXTURENVPROC glDrawTextureNV;
PFNGLCOPYIMAGESUBDATANVPROC glCopyImageSubDataNV ;
PFNGLMAPBUFFERPROC glMapBuffer;

PFNGLDISCARDFRAMEBUFFEREXTPROC glDiscardFramebufferEXT;
PFNGLGENVERTEXARRAYSOESPROC glGenVertexArraysOES;
PFNGLBINDVERTEXARRAYOESPROC glBindVertexArrayOES;
PFNGLDELETEVERTEXARRAYSOESPROC glDeleteVertexArraysOES;
PFNGLISVERTEXARRAYOESPROC glIsVertexArrayOES;
#endif
#endif

OpenGLState glstate;
GLExtensions gl_extensions;
std::string g_all_gl_extensions;
std::string g_all_egl_extensions;

int OpenGLState::state_count = 0;

void OpenGLState::Initialize() {
	if (initialized)
		return;
	initialized = true;

	Restore();
}

void OpenGLState::Restore() {
	int count = 0;

	blend.restore(); count++;
	blendEquation.restore(); count++;
	blendFuncSeparate.restore(); count++;
	blendColor.restore(); count++;

	scissorTest.restore(); count++;
	scissorRect.restore(); count++;

	cullFace.restore(); count++;
	cullFaceMode.restore(); count++;
	frontFace.restore(); count++;

	depthTest.restore(); count++;
	depthRange.restore(); count++;
	depthFunc.restore(); count++;
	depthWrite.restore(); count++;

	colorMask.restore(); count++;
	viewport.restore(); count++;

	stencilTest.restore(); count++;
	stencilOp.restore(); count++;
	stencilFunc.restore(); count++;

	dither.restore(); count++;

#if !defined(USING_GLES2)
	colorLogicOp.restore(); count++;
	logicOp.restore(); count++;
#endif

	if (count != state_count) {
		FLOG("OpenGLState::Restore is missing some states");
	}
}

// http://stackoverflow.com/questions/16147700/opengl-es-using-tegra-specific-extensions-gl-ext-texture-array

void CheckGLExtensions() {
	// Make sure to only do this once. It's okay to call CheckGLExtensions from wherever.
	static bool done = false;
	if (done)
		return;
	done = true;
	memset(&gl_extensions, 0, sizeof(gl_extensions));

	const char *renderer = (const char *)glGetString(GL_RENDERER);
	const char *versionStr = (const char *)glGetString(GL_VERSION);

	// Check vendor string to try and guess GPU
	const char *cvendor = (char *)glGetString(GL_VENDOR);
	// TODO: move this stuff to gpu_features.cpp
	if (cvendor) {
		const std::string vendor(cvendor);
		if (vendor == "NVIDIA Corporation"
			|| vendor == "Nouveau"
			|| vendor == "nouveau") {
				gl_extensions.gpuVendor = GPU_VENDOR_NVIDIA;
		} else if (vendor == "Advanced Micro Devices, Inc."
			|| vendor == "ATI Technologies Inc.") {
				gl_extensions.gpuVendor = GPU_VENDOR_AMD;
		} else if (vendor == "Intel"
			|| vendor == "Intel Inc."
			|| vendor == "Intel Corporation"
			|| vendor == "Tungsten Graphics, Inc") { // We'll assume this last one means Intel
				gl_extensions.gpuVendor = GPU_VENDOR_INTEL;
		} else if (vendor == "ARM") {
			gl_extensions.gpuVendor = GPU_VENDOR_ARM;
		} else if (vendor == "Imagination Technologies") {
			gl_extensions.gpuVendor = GPU_VENDOR_POWERVR;
		} else if (vendor == "Qualcomm") {
			gl_extensions.gpuVendor = GPU_VENDOR_ADRENO;
		} else if (vendor == "Broadcom") {
			gl_extensions.gpuVendor = GPU_VENDOR_BROADCOM;
			// Just for reference: Galaxy Y has renderer == "VideoCore IV HW"
		} else {
			gl_extensions.gpuVendor = GPU_VENDOR_UNKNOWN;
		}
	} else {
		gl_extensions.gpuVendor = GPU_VENDOR_UNKNOWN;
	}

	ILOG("GPU Vendor : %s ; GL version str: %s", cvendor, versionStr ? versionStr : "N/A");

#ifndef USING_GLES2
	char buffer[64] = {0};
	if (versionStr) {
		strncpy(buffer, versionStr, 63);
	}
	const char *lastNumStart = buffer;
	int numVer = 0;
	int len = (int)strlen(buffer);
	for (int i = 0; i < len && numVer < 3; i++) {
		if (buffer[i] == '.') {
			buffer[i] = 0;
			gl_extensions.ver[numVer++] = strtol(lastNumStart, NULL, 10);
			i++;
			lastNumStart = buffer + i;
		}
	}
	if (numVer < 3)
		gl_extensions.ver[numVer++] = strtol(lastNumStart, NULL, 10);
#else
	gl_extensions.ver[0] = 2;
#endif

#if defined(USING_GLES2)
	// MAY_HAVE_GLES3 defined on all platforms that support it
#if defined(MAY_HAVE_GLES3)
	// Try to load GLES 3.0 only if "3.0" found in version
	// This simple heuristic avoids issues on older devices where you can only call eglGetProcAddress a limited
	// number of times.
	if (strstr(versionStr, "3.0") && GL_TRUE == gl3stubInit()) {
		gl_extensions.ver[0] = 3;
		gl_extensions.GLES3 = true;
		ILOG("Full OpenGL ES 3.0 support detected!\n");
		// Though, let's ban Mali from the GLES 3 path for now, see #4078
		if (strstr(renderer, "Mali") != 0) {
			gl_extensions.GLES3 = false;
		}
	}
#endif
#else
	// If the GL version >= 4.3, we know it's a true superset of OpenGL ES 3.0 and can thus enable
	// modern paths.
	// Most of it could be enabled on lower GPUs as well, but let's start this way.
	if ((gl_extensions.ver[0] == 4 && gl_extensions.ver[1] >= 3) || gl_extensions.ver[0] > 4) {
		gl_extensions.GLES3 = true;
	}
#endif

	const char *extString = (const char *)glGetString(GL_EXTENSIONS);
	if (extString) {
		g_all_gl_extensions = extString;
	} else {
		g_all_gl_extensions = "";
	}

#ifdef WIN32
	const char *wglString = 0;
	if (wglGetExtensionsStringEXT)
		wglString = wglGetExtensionsStringEXT();
	if (wglString) {
		gl_extensions.EXT_swap_control_tear = strstr(wglString, "WGL_EXT_swap_control_tear") != 0;
		g_all_egl_extensions = wglString;
	} else {
		g_all_egl_extensions = "";
	}
#elif !defined(USING_GLES2)
	// const char *glXString = glXQueryExtensionString();
	// gl_extensions.EXT_swap_control_tear = strstr(glXString, "GLX_EXT_swap_control_tear") != 0;
#endif

	gl_extensions.NV_draw_texture = strstr(extString, "GL_NV_draw_texture") != 0;
	gl_extensions.ARB_blend_func_extended = strstr(extString, "GL_ARB_blend_func_extended") != 0;

#ifdef USING_GLES2
	gl_extensions.OES_packed_depth_stencil = strstr(extString, "GL_OES_packed_depth_stencil") != 0;
	gl_extensions.OES_depth24 = strstr(extString, "GL_OES_depth24") != 0;
	gl_extensions.OES_depth_texture = strstr(extString, "GL_OES_depth_texture") != 0;
	gl_extensions.OES_mapbuffer = strstr(extString, "GL_OES_mapbuffer") != 0;
	gl_extensions.EXT_blend_minmax = strstr(extString, "GL_EXT_blend_minmax") != 0;
	gl_extensions.EXT_shader_framebuffer_fetch = (strstr(extString, "GL_EXT_shader_framebuffer_fetch") != 0) || (strstr(extString, "GL_NV_shader_framebuffer_fetch") != 0);
	gl_extensions.NV_copy_image = strstr(extString, "GL_NV_copy_image") != 0;
	gl_extensions.EXT_unpack_subimage = strstr(extString, "GL_EXT_unpack_subimage") != 0;
#if defined(ANDROID) || defined(BLACKBERRY)
	// On Android, incredibly, this is not consistently non-zero! It does seem to have the same value though.
	// https://twitter.com/ID_AA_Carmack/status/387383037794603008
#ifdef _DEBUG
	void *invalidAddress = (void *)eglGetProcAddress("InvalidGlCall1");
	void *invalidAddress2 = (void *)eglGetProcAddress("AnotherInvalidGlCall2");
	DLOG("Addresses returned for invalid extensions: %p %p", invalidAddress, invalidAddress2);
#endif

	if (gl_extensions.NV_draw_texture) {
		glDrawTextureNV = (PFNGLDRAWTEXTURENVPROC)eglGetProcAddress("glDrawTextureNV");
	}

	if (gl_extensions.NV_copy_image) {
		glCopyImageSubDataNV = (PFNGLCOPYIMAGESUBDATANVPROC)eglGetProcAddress("glCopyImageSubDataNV");
	}

	gl_extensions.OES_vertex_array_object = strstr(extString, "GL_OES_vertex_array_object") != 0;
	if (gl_extensions.OES_vertex_array_object) {
		glGenVertexArraysOES = (PFNGLGENVERTEXARRAYSOESPROC)eglGetProcAddress ( "glGenVertexArraysOES" );
		glBindVertexArrayOES = (PFNGLBINDVERTEXARRAYOESPROC)eglGetProcAddress ( "glBindVertexArrayOES" );
		glDeleteVertexArraysOES = (PFNGLDELETEVERTEXARRAYSOESPROC)eglGetProcAddress ( "glDeleteVertexArraysOES" );
		glIsVertexArrayOES = (PFNGLISVERTEXARRAYOESPROC)eglGetProcAddress ( "glIsVertexArrayOES" );
	}

	gl_extensions.EXT_discard_framebuffer = strstr(extString, "GL_EXT_discard_framebuffer") != 0;
	if (gl_extensions.EXT_discard_framebuffer) {
		glDiscardFramebufferEXT = (PFNGLDISCARDFRAMEBUFFEREXTPROC)eglGetProcAddress("glDiscardFramebufferEXT");
	}
#else
	gl_extensions.OES_vertex_array_object = false;
	gl_extensions.EXT_discard_framebuffer = false;
#endif
#else
	// Desktops support minmax and subimage unpack (GL_UNPACK_ROW_LENGTH etc)
	gl_extensions.EXT_blend_minmax = true;
	gl_extensions.EXT_unpack_subimage = true;
#endif
	// GLES 3 subsumes many ES2 extensions.
	if (gl_extensions.GLES3) {
		gl_extensions.EXT_unpack_subimage = true;
	}

#if defined(ANDROID) || defined(BLACKBERRY)
	if (gl_extensions.OES_mapbuffer) {
		glMapBuffer = (PFNGLMAPBUFFERPROC)eglGetProcAddress( "glMapBufferOES" );
	}

	// Look for EGL extensions
	EGLDisplay display = eglGetDisplay(EGL_DEFAULT_DISPLAY);

	const char *eglString = eglQueryString(display, EGL_EXTENSIONS);
	if (eglString) {
		g_all_egl_extensions = eglString;

		gl_extensions.EGL_NV_system_time = strstr(eglString, "EGL_NV_system_time") != 0;
		gl_extensions.EGL_NV_coverage_sample = strstr(eglString, "EGL_NV_coverage_sample") != 0;

		if (gl_extensions.EGL_NV_system_time) {
			eglGetSystemTimeNV = (PFNEGLGETSYSTEMTIMENVPROC) eglGetProcAddress("eglGetSystemTimeNV");
			eglGetSystemTimeFrequencyNV = (PFNEGLGETSYSTEMTIMEFREQUENCYNVPROC) eglGetProcAddress("eglGetSystemTimeFrequencyNV");
		}
	} else {
		g_all_egl_extensions = "";
	}
#endif

#ifdef USING_GLES2
	gl_extensions.FBO_ARB = true;
	gl_extensions.FBO_EXT = false;
#else
	gl_extensions.FBO_ARB = false;
	gl_extensions.FBO_EXT = false;
	gl_extensions.PBO_ARB = true;
	if (extString) {
		gl_extensions.FBO_ARB = strstr(extString, "GL_ARB_framebuffer_object") != 0;
		gl_extensions.FBO_EXT = strstr(extString, "GL_EXT_framebuffer_object") != 0;
		gl_extensions.PBO_ARB = strstr(extString, "GL_ARB_pixel_buffer_object") != 0;
		gl_extensions.ATIClampBug = ((strncmp(renderer, "ATI RADEON X", 12) == 0) || (strncmp(renderer, "ATI MOBILITY RADEON X", 21) == 0));
	}
#endif

	ProcessGPUFeatures();
}

void OpenGLState::SetVSyncInterval(int interval) {
#ifdef _WIN32
	if (wglSwapIntervalEXT)
		wglSwapIntervalEXT(interval);
#endif
}
<commit_msg>Force ARB_blend_func_extended off on OpenGL < 3.0.<commit_after>#include <stdlib.h>

#include "base/logging.h"
#include "base/NativeApp.h"
#include "gl_state.h"

#ifdef _WIN32
#include "GL/wglew.h"
#endif

#if defined(USING_GLES2)
#if defined(ANDROID) || defined(BLACKBERRY)
PFNEGLGETSYSTEMTIMEFREQUENCYNVPROC eglGetSystemTimeFrequencyNV;
PFNEGLGETSYSTEMTIMENVPROC eglGetSystemTimeNV;
PFNGLDRAWTEXTURENVPROC glDrawTextureNV;
PFNGLCOPYIMAGESUBDATANVPROC glCopyImageSubDataNV ;
PFNGLMAPBUFFERPROC glMapBuffer;

PFNGLDISCARDFRAMEBUFFEREXTPROC glDiscardFramebufferEXT;
PFNGLGENVERTEXARRAYSOESPROC glGenVertexArraysOES;
PFNGLBINDVERTEXARRAYOESPROC glBindVertexArrayOES;
PFNGLDELETEVERTEXARRAYSOESPROC glDeleteVertexArraysOES;
PFNGLISVERTEXARRAYOESPROC glIsVertexArrayOES;
#endif
#endif

OpenGLState glstate;
GLExtensions gl_extensions;
std::string g_all_gl_extensions;
std::string g_all_egl_extensions;

int OpenGLState::state_count = 0;

void OpenGLState::Initialize() {
	if (initialized)
		return;
	initialized = true;

	Restore();
}

void OpenGLState::Restore() {
	int count = 0;

	blend.restore(); count++;
	blendEquation.restore(); count++;
	blendFuncSeparate.restore(); count++;
	blendColor.restore(); count++;

	scissorTest.restore(); count++;
	scissorRect.restore(); count++;

	cullFace.restore(); count++;
	cullFaceMode.restore(); count++;
	frontFace.restore(); count++;

	depthTest.restore(); count++;
	depthRange.restore(); count++;
	depthFunc.restore(); count++;
	depthWrite.restore(); count++;

	colorMask.restore(); count++;
	viewport.restore(); count++;

	stencilTest.restore(); count++;
	stencilOp.restore(); count++;
	stencilFunc.restore(); count++;

	dither.restore(); count++;

#if !defined(USING_GLES2)
	colorLogicOp.restore(); count++;
	logicOp.restore(); count++;
#endif

	if (count != state_count) {
		FLOG("OpenGLState::Restore is missing some states");
	}
}

// http://stackoverflow.com/questions/16147700/opengl-es-using-tegra-specific-extensions-gl-ext-texture-array

void CheckGLExtensions() {
	// Make sure to only do this once. It's okay to call CheckGLExtensions from wherever.
	static bool done = false;
	if (done)
		return;
	done = true;
	memset(&gl_extensions, 0, sizeof(gl_extensions));

	const char *renderer = (const char *)glGetString(GL_RENDERER);
	const char *versionStr = (const char *)glGetString(GL_VERSION);

	// Check vendor string to try and guess GPU
	const char *cvendor = (char *)glGetString(GL_VENDOR);
	// TODO: move this stuff to gpu_features.cpp
	if (cvendor) {
		const std::string vendor(cvendor);
		if (vendor == "NVIDIA Corporation"
			|| vendor == "Nouveau"
			|| vendor == "nouveau") {
				gl_extensions.gpuVendor = GPU_VENDOR_NVIDIA;
		} else if (vendor == "Advanced Micro Devices, Inc."
			|| vendor == "ATI Technologies Inc.") {
				gl_extensions.gpuVendor = GPU_VENDOR_AMD;
		} else if (vendor == "Intel"
			|| vendor == "Intel Inc."
			|| vendor == "Intel Corporation"
			|| vendor == "Tungsten Graphics, Inc") { // We'll assume this last one means Intel
				gl_extensions.gpuVendor = GPU_VENDOR_INTEL;
		} else if (vendor == "ARM") {
			gl_extensions.gpuVendor = GPU_VENDOR_ARM;
		} else if (vendor == "Imagination Technologies") {
			gl_extensions.gpuVendor = GPU_VENDOR_POWERVR;
		} else if (vendor == "Qualcomm") {
			gl_extensions.gpuVendor = GPU_VENDOR_ADRENO;
		} else if (vendor == "Broadcom") {
			gl_extensions.gpuVendor = GPU_VENDOR_BROADCOM;
			// Just for reference: Galaxy Y has renderer == "VideoCore IV HW"
		} else {
			gl_extensions.gpuVendor = GPU_VENDOR_UNKNOWN;
		}
	} else {
		gl_extensions.gpuVendor = GPU_VENDOR_UNKNOWN;
	}

	ILOG("GPU Vendor : %s ; GL version str: %s", cvendor, versionStr ? versionStr : "N/A");

#ifndef USING_GLES2
	char buffer[64] = {0};
	if (versionStr) {
		strncpy(buffer, versionStr, 63);
	}
	const char *lastNumStart = buffer;
	int numVer = 0;
	int len = (int)strlen(buffer);
	for (int i = 0; i < len && numVer < 3; i++) {
		if (buffer[i] == '.') {
			buffer[i] = 0;
			gl_extensions.ver[numVer++] = strtol(lastNumStart, NULL, 10);
			i++;
			lastNumStart = buffer + i;
		}
	}
	if (numVer < 3)
		gl_extensions.ver[numVer++] = strtol(lastNumStart, NULL, 10);
#else
	gl_extensions.ver[0] = 2;
#endif

#if defined(USING_GLES2)
	// MAY_HAVE_GLES3 defined on all platforms that support it
#if defined(MAY_HAVE_GLES3)
	// Try to load GLES 3.0 only if "3.0" found in version
	// This simple heuristic avoids issues on older devices where you can only call eglGetProcAddress a limited
	// number of times.
	if (strstr(versionStr, "3.0") && GL_TRUE == gl3stubInit()) {
		gl_extensions.ver[0] = 3;
		gl_extensions.GLES3 = true;
		ILOG("Full OpenGL ES 3.0 support detected!\n");
		// Though, let's ban Mali from the GLES 3 path for now, see #4078
		if (strstr(renderer, "Mali") != 0) {
			gl_extensions.GLES3 = false;
		}
	}
#endif
#else
	// If the GL version >= 4.3, we know it's a true superset of OpenGL ES 3.0 and can thus enable
	// all the same modern paths.
	// Most of it could be enabled on lower GPUs as well, but let's start this way.
	if (gl_extensions.VersionGEThan(4, 3, 0)) {
		gl_extensions.GLES3 = true;
	}
#endif

	const char *extString = (const char *)glGetString(GL_EXTENSIONS);
	if (extString) {
		g_all_gl_extensions = extString;
	} else {
		g_all_gl_extensions = "";
	}

#ifdef WIN32
	const char *wglString = 0;
	if (wglGetExtensionsStringEXT)
		wglString = wglGetExtensionsStringEXT();
	if (wglString) {
		gl_extensions.EXT_swap_control_tear = strstr(wglString, "WGL_EXT_swap_control_tear") != 0;
		g_all_egl_extensions = wglString;
	} else {
		g_all_egl_extensions = "";
	}
#elif !defined(USING_GLES2)
	// const char *glXString = glXQueryExtensionString();
	// gl_extensions.EXT_swap_control_tear = strstr(glXString, "GLX_EXT_swap_control_tear") != 0;
#endif

	gl_extensions.NV_draw_texture = strstr(extString, "GL_NV_draw_texture") != 0;
	gl_extensions.ARB_blend_func_extended = strstr(extString, "GL_ARB_blend_func_extended") != 0;
	if (!gl_extensions.VersionGEThan(3, 0, 0)) {
		// Force this extension to off on sub 3.0 OpenGL versions as it does not seem reliable
		gl_extensions.ARB_blend_func_extended = false;
	}

#ifdef USING_GLES2
	gl_extensions.OES_packed_depth_stencil = strstr(extString, "GL_OES_packed_depth_stencil") != 0;
	gl_extensions.OES_depth24 = strstr(extString, "GL_OES_depth24") != 0;
	gl_extensions.OES_depth_texture = strstr(extString, "GL_OES_depth_texture") != 0;
	gl_extensions.OES_mapbuffer = strstr(extString, "GL_OES_mapbuffer") != 0;
	gl_extensions.EXT_blend_minmax = strstr(extString, "GL_EXT_blend_minmax") != 0;
	gl_extensions.EXT_shader_framebuffer_fetch = (strstr(extString, "GL_EXT_shader_framebuffer_fetch") != 0) || (strstr(extString, "GL_NV_shader_framebuffer_fetch") != 0);
	gl_extensions.NV_copy_image = strstr(extString, "GL_NV_copy_image") != 0;
	gl_extensions.EXT_unpack_subimage = strstr(extString, "GL_EXT_unpack_subimage") != 0;
#if defined(ANDROID) || defined(BLACKBERRY)
	// On Android, incredibly, this is not consistently non-zero! It does seem to have the same value though.
	// https://twitter.com/ID_AA_Carmack/status/387383037794603008
#ifdef _DEBUG
	void *invalidAddress = (void *)eglGetProcAddress("InvalidGlCall1");
	void *invalidAddress2 = (void *)eglGetProcAddress("AnotherInvalidGlCall2");
	DLOG("Addresses returned for invalid extensions: %p %p", invalidAddress, invalidAddress2);
#endif

	if (gl_extensions.NV_draw_texture) {
		glDrawTextureNV = (PFNGLDRAWTEXTURENVPROC)eglGetProcAddress("glDrawTextureNV");
	}

	if (gl_extensions.NV_copy_image) {
		glCopyImageSubDataNV = (PFNGLCOPYIMAGESUBDATANVPROC)eglGetProcAddress("glCopyImageSubDataNV");
	}

	gl_extensions.OES_vertex_array_object = strstr(extString, "GL_OES_vertex_array_object") != 0;
	if (gl_extensions.OES_vertex_array_object) {
		glGenVertexArraysOES = (PFNGLGENVERTEXARRAYSOESPROC)eglGetProcAddress ( "glGenVertexArraysOES" );
		glBindVertexArrayOES = (PFNGLBINDVERTEXARRAYOESPROC)eglGetProcAddress ( "glBindVertexArrayOES" );
		glDeleteVertexArraysOES = (PFNGLDELETEVERTEXARRAYSOESPROC)eglGetProcAddress ( "glDeleteVertexArraysOES" );
		glIsVertexArrayOES = (PFNGLISVERTEXARRAYOESPROC)eglGetProcAddress ( "glIsVertexArrayOES" );
	}

	gl_extensions.EXT_discard_framebuffer = strstr(extString, "GL_EXT_discard_framebuffer") != 0;
	if (gl_extensions.EXT_discard_framebuffer) {
		glDiscardFramebufferEXT = (PFNGLDISCARDFRAMEBUFFEREXTPROC)eglGetProcAddress("glDiscardFramebufferEXT");
	}
#else
	gl_extensions.OES_vertex_array_object = false;
	gl_extensions.EXT_discard_framebuffer = false;
#endif
#else
	// Desktops support minmax and subimage unpack (GL_UNPACK_ROW_LENGTH etc)
	gl_extensions.EXT_blend_minmax = true;
	gl_extensions.EXT_unpack_subimage = true;
#endif
	// GLES 3 subsumes many ES2 extensions.
	if (gl_extensions.GLES3) {
		gl_extensions.EXT_unpack_subimage = true;
	}

#if defined(ANDROID) || defined(BLACKBERRY)
	if (gl_extensions.OES_mapbuffer) {
		glMapBuffer = (PFNGLMAPBUFFERPROC)eglGetProcAddress( "glMapBufferOES" );
	}

	// Look for EGL extensions
	EGLDisplay display = eglGetDisplay(EGL_DEFAULT_DISPLAY);

	const char *eglString = eglQueryString(display, EGL_EXTENSIONS);
	if (eglString) {
		g_all_egl_extensions = eglString;

		gl_extensions.EGL_NV_system_time = strstr(eglString, "EGL_NV_system_time") != 0;
		gl_extensions.EGL_NV_coverage_sample = strstr(eglString, "EGL_NV_coverage_sample") != 0;

		if (gl_extensions.EGL_NV_system_time) {
			eglGetSystemTimeNV = (PFNEGLGETSYSTEMTIMENVPROC) eglGetProcAddress("eglGetSystemTimeNV");
			eglGetSystemTimeFrequencyNV = (PFNEGLGETSYSTEMTIMEFREQUENCYNVPROC) eglGetProcAddress("eglGetSystemTimeFrequencyNV");
		}
	} else {
		g_all_egl_extensions = "";
	}
#endif

#ifdef USING_GLES2
	gl_extensions.FBO_ARB = true;
	gl_extensions.FBO_EXT = false;
#else
	gl_extensions.FBO_ARB = false;
	gl_extensions.FBO_EXT = false;
	gl_extensions.PBO_ARB = true;
	if (extString) {
		gl_extensions.FBO_ARB = strstr(extString, "GL_ARB_framebuffer_object") != 0;
		gl_extensions.FBO_EXT = strstr(extString, "GL_EXT_framebuffer_object") != 0;
		gl_extensions.PBO_ARB = strstr(extString, "GL_ARB_pixel_buffer_object") != 0;
		gl_extensions.ATIClampBug = ((strncmp(renderer, "ATI RADEON X", 12) == 0) || (strncmp(renderer, "ATI MOBILITY RADEON X", 21) == 0));
	}
#endif

	ProcessGPUFeatures();
}

void OpenGLState::SetVSyncInterval(int interval) {
#ifdef _WIN32
	if (wglSwapIntervalEXT)
		wglSwapIntervalEXT(interval);
#endif
}
<|endoftext|>


<commit_before>//
//  yas_processing_channel.cpp
//

#include "yas_processing_channel.h"
#include "yas_processing_event.h"
#include "yas_processing_signal_event.h"

using namespace yas;

#pragma mark - processing::channel::impl

struct processing::channel::impl : base::impl {
    events_map_t _events;

    impl() {
    }

    impl(events_map_t &&events) : _events(std::move(events)) {
    }
};

#pragma mark - processing::channel

processing::channel::channel() : base(std::make_shared<impl>()) {
}

processing::channel::channel(events_map_t events) : base(std::make_shared<impl>(std::move(events))) {
}

processing::channel::channel(std::nullptr_t) : base(nullptr) {
}

processing::channel::events_map_t const &processing::channel::events() const {
    return this->impl_ptr<impl>()->_events;
}

processing::channel::events_map_t &processing::channel::events() {
    return this->impl_ptr<impl>()->_events;
}

void processing::channel::insert_event(time time, event event) {
    if (!event.validate_time(time)) {
        throw "invalid time for event.";
    }

    this->impl_ptr<impl>()->_events.emplace(std::move(time), std::move(event));
}

void processing::channel::insert_events(events_map_t events) {
    for (auto &event_pair : events) {
        this->insert_event(event_pair.first, std::move(event_pair.second));
    }
}

processing::channel::events_map_t processing::channel::copied_events(time::range const &copy_range) const {
    events_map_t result;

    for (auto const &event_pair : this->events()) {
        auto const &event_time = event_pair.first;
        auto const &event = event_pair.second;
        if (event_time.is_any_type()) {
            result.emplace(std::make_pair(event_time, event.copy()));
        } else if (event_time.is_frame_type()) {
            if (copy_range.is_contain(event_time.get<time::frame>())) {
                result.emplace(std::make_pair(event_time, event.copy()));
            }
        } else if (event_time.is_range_type()) {
            auto const &event_range = event_time.get<time::range>();
            if (auto const overlap_range_opt = copy_range.intersect(event_range)) {
                auto const &overlap_range = *overlap_range_opt;
                auto const signal = cast<signal_event>(event);
                auto copied_signal =
                    signal.copy_in_range(time::range{overlap_range.frame - event_range.frame, overlap_range.length});
                result.emplace(std::make_pair(time{overlap_range}, std::move(copied_signal)));
            }
        } else {
            throw "unreachable code.";
        }
    }

    return result;
}

void processing::channel::erase_events(time::range const &erase_range) {
    signal_event::pair_vector_t remained_signal;

    erase_if(this->events(), [erase_range, &remained_signal](auto const &event_pair) {
        time const &event_time = event_pair.first;
        if (event_time.is_any_type()) {
            return true;
        } else if (event_time.is_frame_type()) {
            if (erase_range.is_contain(event_time.get<time::frame>())) {
                return true;
            }
        } else if (event_time.is_range_type()) {
            auto const &event_range = event_time.get<time::range>();
            if (auto overlapped_range = erase_range.intersect(event_range)) {
                auto const signal = cast<signal_event>(event_pair.second);
                auto const range = time::range{overlapped_range->frame - event_range.frame, overlapped_range->length};
                signal_event::pair_vector_t erased_signals = signal.erased_in_range(range);
                for (auto const &erased_signal : erased_signals) {
                    auto const &erased_range = erased_signal.first;
                    remained_signal.emplace_back(
                        std::make_pair(time::range{erased_range.frame + event_range.frame, erased_range.length},
                                       erased_signal.second));
                }

                return true;
            }
        } else {
            throw "unreachable code.";
        }

        return false;
    });

    if (remained_signal.size() > 0) {
        for (auto const &signal_pair : remained_signal) {
            this->insert_event(time{signal_pair.first}, signal_pair.second);
        }
    }
}
<commit_msg>use offset<commit_after>//
//  yas_processing_channel.cpp
//

#include "yas_processing_channel.h"
#include "yas_processing_event.h"
#include "yas_processing_signal_event.h"

using namespace yas;

#pragma mark - processing::channel::impl

struct processing::channel::impl : base::impl {
    events_map_t _events;

    impl() {
    }

    impl(events_map_t &&events) : _events(std::move(events)) {
    }
};

#pragma mark - processing::channel

processing::channel::channel() : base(std::make_shared<impl>()) {
}

processing::channel::channel(events_map_t events) : base(std::make_shared<impl>(std::move(events))) {
}

processing::channel::channel(std::nullptr_t) : base(nullptr) {
}

processing::channel::events_map_t const &processing::channel::events() const {
    return this->impl_ptr<impl>()->_events;
}

processing::channel::events_map_t &processing::channel::events() {
    return this->impl_ptr<impl>()->_events;
}

void processing::channel::insert_event(time time, event event) {
    if (!event.validate_time(time)) {
        throw "invalid time for event.";
    }

    this->impl_ptr<impl>()->_events.emplace(std::move(time), std::move(event));
}

void processing::channel::insert_events(events_map_t events) {
    for (auto &event_pair : events) {
        this->insert_event(event_pair.first, std::move(event_pair.second));
    }
}

processing::channel::events_map_t processing::channel::copied_events(time::range const &copy_range) const {
    events_map_t result;

    for (auto const &event_pair : this->events()) {
        auto const &event_time = event_pair.first;
        auto const &event = event_pair.second;
        if (event_time.is_any_type()) {
            result.emplace(std::make_pair(event_time, event.copy()));
        } else if (event_time.is_frame_type()) {
            if (copy_range.is_contain(event_time.get<time::frame>())) {
                result.emplace(std::make_pair(event_time, event.copy()));
            }
        } else if (event_time.is_range_type()) {
            auto const &event_range = event_time.get<time::range>();
            if (auto const overlap_range_opt = copy_range.intersect(event_range)) {
                auto const &overlap_range = *overlap_range_opt;
                auto const signal = cast<signal_event>(event);
                auto copied_signal =
                    signal.copy_in_range(time::range{overlap_range.frame - event_range.frame, overlap_range.length});
                result.emplace(std::make_pair(time{overlap_range}, std::move(copied_signal)));
            }
        } else {
            throw "unreachable code.";
        }
    }

    return result;
}

void processing::channel::erase_events(time::range const &erase_range) {
    signal_event::pair_vector_t remained_signal;

    erase_if(this->events(), [erase_range, &remained_signal](auto const &event_pair) {
        time const &event_time = event_pair.first;
        if (event_time.is_any_type()) {
            return true;
        } else if (event_time.is_frame_type()) {
            if (erase_range.is_contain(event_time.get<time::frame>())) {
                return true;
            }
        } else if (event_time.is_range_type()) {
            auto const &event_range = event_time.get<time::range>();
            if (auto overlapped_range = erase_range.intersect(event_range)) {
                auto const signal = cast<signal_event>(event_pair.second);
                auto const range = time::range{overlapped_range->frame - event_range.frame, overlapped_range->length};
                signal_event::pair_vector_t erased_signals = signal.erased_in_range(range);
                for (auto const &erased_signal : erased_signals) {
                    auto const &erased_range = erased_signal.first;
                    remained_signal.emplace_back(
                        std::make_pair(erased_range.offset(event_range.frame), erased_signal.second));
                }

                return true;
            }
        } else {
            throw "unreachable code.";
        }

        return false;
    });

    if (remained_signal.size() > 0) {
        for (auto const &signal_pair : remained_signal) {
            this->insert_event(time{signal_pair.first}, signal_pair.second);
        }
    }
}
<|endoftext|>